# Specify our compiler
CXX := em++
# Specify where our source files are
SOURCE_DIR := src
# Specify where our object and program files should go
BUILD_DIR := build/web
# Specify our program's name
BINARY := game.html

# Specify what flags to give to the compiler
CXX_FLAGS := -g -std=c++20 -Wall -Werror -Wextra -c -s USE_SDL=2

# Specify what flags to give to the linker
LINK_FLAGS := -lSDL2 -lGL -lGLEW -lGLU -s MIN_WEBGL_VERSION=2

# Find all the source files
CXX_FILES := $(shell find $(SOURCE_DIR) -name *.cpp)

# Find all the source shaders
SHADER_FILES := $(shell find $(SOURCE_DIR) -name *.vert) $(shell find $(SOURCE_DIR) -name *.frag)
LINK_FLAGS += $(foreach SHADER,$(SHADER_FILES),$(shell echo "$(SHADER)" | sed -e 's/src\/\(.*\)/--preload-file "src\/\1@\1"/'))

# Determine a list of object and dependency files from all the source files
OBJ_FILES := $(patsubst $(SOURCE_DIR)/%.cpp,$(BUILD_DIR)/%.o,$(CXX_FILES))
DEP_FILES := $(patsubst %.o,%.d,$(OBJ_FILES))

.PHONY: program
program: $(BUILD_DIR)/$(BINARY)

.PHONY: clean
clean:
	rm -rf $(BUILD_DIR)

$(BUILD_DIR)/$(BINARY): $(OBJ_FILES) $(BUILD_DIR) $(SHADER_FILES)
	$(CXX) $(OBJ_FILES) $(LINK_FLAGS) -o "$@"

$(BUILD_DIR):
	mkdir -p $@

-include $(DEP_FILES)

$(BUILD_DIR)/%.o: $(SOURCE_DIR)/%.cpp
	@mkdir -p "$(@D)"
	$(CXX) $(CXX_FLAGS) -MMD -c "$<" -o "$@"
