#
# tngp/emscripten/Makefile
#
# Copyright (C) 2022 bzt
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# @brief Dirty hacks to compile tngp with emscripten...
#

all: tngp.js

# download an unofficial, but patched for wasm libtheora repo, because the original library does not compile with emscripten
./libtheora/autogen.sh:
	curl https://github.com/brion/theora/archive/2d97ea8166e307ba52dcbbf598a907d8c803c76c.zip | unzip /dev/stdin
	mv theora-* libtheora

./libtheora/lib/.libs/libtheoradec.a:

./libtheora/lib/.libs/libtheora.a: libtheora/autogen.sh
ifeq ($(wildcard libtheora/configure),)
	cd libtheora && ./autogen.sh
	@rm libtheora/Makefile 2>/dev/null || true
endif
ifeq ($(wildcard libtheora/Makefile),)
	cd libtheora && emconfigure ./configure --disable-shared --enable-static --disable-telemetry --disable-doc --disable-spec \
	--disable-valgrind-testing --disable-asm --disable-encode --disable-oggtest --disable-examples --with-ogg=$(abspath ../../src)
endif
	@emmake make --no-print-directory -s -C libtheora all

tngp.js: ./libtheora/lib/.libs/libtheora.a
	CC=emcc USE_EMCC=1 make -C ../src objs
	@cd ../src/mbedtls && emcc -I.. -c sha256.c -o sha256.o
	emcc ./libtheora/lib/.libs/libtheoradec.a ./libtheora/lib/.libs/libtheora.a ../src/mbedtls/sha256.o ../src/*.o -o tngp.js \
	-s USE_SDL=2 -s USE_SDL_MIXER=2 -s USE_OGG=1 -s USE_VORBIS=1 -s ASYNCIFY=1 -s EXIT_RUNTIME=1 -s ALLOW_MEMORY_GROWTH=1 -s WASM_BIGINT
	@rm ../src/mbedtls/sha256.o

package: tngp.js
	tar -czvf ../tngp-wasm-emscripten.tgz tngp.html tngp.js tngp.wasm

clean:
	make -C ../src clean
	rm tngp*.js tngp.wasm || true

distclean:
	rm -rf libtheora 2>/dev/null || true
	make clean
