# Directories
INCLUDE_DIR = inc
SRC_DIR = src
BUILD_DIR = build

# imgui
IMGUI_DIR = lib/imgui
INCLUDE_DIR += $(IMGUI_DIR) $(IMGUI_DIR)/backends

# Compiler, flags and libraries
CXX = g++
CXXFLAGS = -std=c++17
LIBS = -lGL -lglm `pkg-config --libs sdl3 sdl3-image`

# Include dirs in compiler flags
CXXFLAGS += $(addprefix -I, $(INCLUDE_DIR))

# Source files (app + subdirs)
SRC := $(wildcard $(SRC_DIR)/*.cpp) $(wildcard $(SRC_DIR)/*/*.cpp)

# ImGui specific sources (explicit list)
IMGUI_SRC := \
	$(IMGUI_DIR)/imgui.cpp \
	$(IMGUI_DIR)/imgui_demo.cpp \
	$(IMGUI_DIR)/imgui_draw.cpp \
	$(IMGUI_DIR)/imgui_tables.cpp \
	$(IMGUI_DIR)/imgui_widgets.cpp \
	$(IMGUI_DIR)/backends/imgui_impl_sdl3.cpp \
	$(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp

SRC += $(IMGUI_SRC)

# Target executable
UNAME := $(shell uname -s)
BUILD_DIR := $(BUILD_DIR)/$(UNAME)
OBJ_DIR := $(BUILD_DIR)/objs
BIN = $(BUILD_DIR)/main


# Note: I have no clue how this works, copilot made it for me cus my usual makefile didn't like the directory structure :P
# Object files corresponding to the source files
# Map source paths to object paths so subdirectories are preserved.
# - Files under `$(SRC_DIR)` become `$(OBJ_DIR)/<subdirs>/name.o`
# - ImGui files (in `$(IMGUI_DIR)` and its `backends`) become `$(OBJ_DIR)/name.o`
OBJS := $(foreach f,$(SRC),$(if $(filter $(SRC_DIR)/%,$(f)),$(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(f)),$(if $(filter $(IMGUI_DIR)/backends/%,$(f)),$(patsubst $(IMGUI_DIR)/backends/%.cpp,$(OBJ_DIR)/%.o,$(f)),$(patsubst $(IMGUI_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(f)))) )

# black magic wizardry below this line (pwease don't touch i beg you)
dev: CXXFLAGS += -g -Wall -Wformat
dev: all

release: CXXFLAGS += -O3
release: all

dirs:
	@mkdir -p $(BUILD_DIR)
	@mkdir -p $(OBJ_DIR)
	# create any required subdirectories for object files
	@mkdir -p $(sort $(dir $(OBJS)))

# Even more imgui specific stuff >:(
$(OBJ_DIR)/%.o: $(IMGUI_DIR)/%.cpp
	$(CXX) $(CXXFLAGS) -c -o $@ $<

$(OBJ_DIR)/%.o: $(IMGUI_DIR)/backends/%.cpp
	$(CXX) $(CXXFLAGS) -c -o $@ $<

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
	$(CXX) $(CXXFLAGS) -c -o $@ $<

all: dirs $(BIN)
	@echo Build complete

$(BIN): $(OBJS)
	$(CXX) $(CXXFLAGS) -o $@ $^ $(LIBS)

.PHONY: all dev release clean dirs

clean:
	rm -rf $(BUILD_DIR)