# Pekka Kana 2 by Janne Kivilahti from Piste Gamez (2003-2007)
# https://pistegamez.net/game_pk2.html
#
# This public release and rewritten is governed by a BSD-2-clause license.
#
# Makefile command:
# "make" - Creates Pekka Kana 2 binary
# "make clean" - Removes all objects, executables and dependencies
#
# To put more focus on warnings, be less verbose as default
# Use 'make V=1' to see the full commands

CXX = g++
CXXFLAGS += $(shell pkg-config --cflags sdl2) -g -O2 -std=gnu++17 -fPIE \
-D_FORTIFY_SOURCE=2 -Wno-unused-result -Wno-write-strings
LDFLAGS += $(shell pkg-config --libs sdl2) -lSDL2_image -lSDL2_mixer \
-pie -Wl,-z,relro

# Defines directories
SRC_DIR = src/
BIN_DIR = bin/
BUILD_DIR = build/

# Defines the engine and src used in main codes
ENGINE_SRC  = $(wildcard $(SRC_DIR)*.cpp)
ENGINE_OBJ := $(basename $(ENGINE_SRC))
ENGINE_OBJ := $(notdir $(ENGINE_OBJ))
ENGINE_OBJ := $(addsuffix .o, $(ENGINE_OBJ))
ENGINE_OBJ := $(addprefix $(BUILD_DIR), $(ENGINE_OBJ))

PK2_SPRITE_SRC = $(SRC_DIR)sprite.cpp
PK2_SPRITE_OBJ = $(BUILD_DIR)sprite.o

PK2_MAP_SRC = $(SRC_DIR)map.cpp
PK2_MAP_OBJ = $(BUILD_DIR)map.o

PK2_SRC = $(SRC_DIR)pk2.cpp
PK2_OBJ = $(BUILD_DIR)pk2.o

# Defines the destination of each binary file
PK2_BIN = $(BIN_DIR)/pekka-kana-2

DEPENDENCIES := $(PK2_OBJ) $(PK2_SPRITE_OBJ) $(PK2_MAP_OBJ) $(ENGINE_OBJ)
DEPENDENCIES := $(basename $(DEPENDENCIES))
DEPENDENCIES := $(addsuffix .d, $(DEPENDENCIES))

# If KBUILD_VERBOSE equals 0 then the above command will be hidden.
# If KBUILD_VERBOSE equals 1 then the above command is displayed.
ifeq ("$(origin V)", "command line")
    KBUILD_VERBOSE = $(V)
endif

ifndef KBUILD_VERBOSE
    KBUILD_VERBOSE = 0
endif

ifeq ($(KBUILD_VERBOSE),1)
    Q =
    else
    Q = @
endif

pk2: makedirs $(PK2_BIN)

# Rules for generate the binaries using the object files
$(PK2_BIN): $(PK2_OBJ) $(PK2_SPRITE_OBJ) $(PK2_MAP_OBJ) $(ENGINE_OBJ)
	@echo -Linking Pekka Kana 2
	$(Q)$(CXX) $(CXXFLAGS) $^ $(LDFLAGS) -o $@

# Rules for generate any *.o file
-include $(DEPENDENCIES)

build/%.o : src/%.cpp
	@echo -Some dependence of $@ was changed, updating
	$(Q)$(CXX) $(CXXFLAGS) -I$(SRC_DIR) -o $@ -c $<
	$(Q)$(CXX) $(CXXFLAGS) -MM -MT $@ -I$(SRC_DIR) $< > build/$*.d

makedirs:
	$(Q)mkdir -p $(BIN_DIR) >/dev/null
	$(Q)mkdir -p $(BUILD_DIR) >/dev/null

clean:
	$(Q)rm -rf $(BIN_DIR)
	$(Q)rm -rf $(BUILD_DIR)

.PHONY: pk2 clean makedirs
