# GONG RIDER for the PiTrex.
#
#   make            the game in the desktop PiTrex simulator: build_sim/gongrider
#   make run        build and start it (arrow keys, buttons 1-4, Esc quits)
#   make test       the autopilot plays 5 minutes headless, prints the numbers
#   make shots      the pictures for the article, images/*.png
#   make img        a kernel image for the PiTrex (Pi Zero), with the
#                   pitrex-baremetal SDK: make img PITREX_SDK=/path/to/pitrex-baremetal
#
# The simulator is in simulator/ (sim/: beam model,
# keyboard as controller, screenshot mode). Needs SDL2.

PITREX_SIM ?= simulator
MENU_DIR   ?= simulator
PITREX_SDK ?= $(HOME)/pitrex-baremetal

BUILD = build_sim

SDL_CFLAGS := $(shell sdl2-config --cflags)
SDL_LIBS   := $(shell sdl2-config --libs)

CFLAGS   ?= -O2 -Wall -Wextra
CXXFLAGS ?= -O2 -std=c++17

INCS      = -I$(PITREX_SIM)/include -I$(PITREX_SIM) -I$(MENU_DIR) -Isim
SIM_FLAGS = -include sim/sim_extra.h

SIM_OBJS  = $(BUILD)/sim/host.o $(BUILD)/sim/vectrex_sim.o $(BUILD)/sim/beam_model.o \
            $(BUILD)/sim/draw.o $(BUILD)/sim/sim_extra.o

# The test build: three library calls go through the autopilot.
AP_RENAME = -Dv_WaitRecal=ap_WaitRecal -Dv_readButtons=ap_readButtons \
            -Dv_readJoystick1Analog=ap_readJoystick1Analog

all: $(BUILD)/gongrider

$(BUILD)/gongrider: $(BUILD)/gongrider.o $(SIM_OBJS)
	$(CXX) $^ $(SDL_LIBS) -lm -o $@

$(BUILD)/gongrider_test: $(BUILD)/gongrider_ap.o $(BUILD)/autopilot.o $(BUILD)/sim/beam_stats.o $(SIM_OBJS)
	$(CXX) $^ $(SDL_LIBS) -lm -o $@

$(BUILD)/gongrider.o: src/gongrider.c sim/sim_extra.h
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) $(SIM_FLAGS) $(INCS) -c $< -o $@

$(BUILD)/gongrider_ap.o: src/gongrider.c sim/sim_extra.h
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) $(SIM_FLAGS) $(AP_RENAME) $(INCS) -c $< -o $@

$(BUILD)/autopilot.o: test/autopilot.c
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) $(INCS) -c $< -o $@

$(BUILD)/sim/sim_extra.o: sim/sim_extra.c sim/sim_extra.h
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) $(INCS) -c $< -o $@

$(BUILD)/sim/draw.o: $(MENU_DIR)/draw.c
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) $(INCS) -c $< -o $@

$(BUILD)/sim/beam_stats.o: sim/beam_stats.cpp
	@mkdir -p $(@D)
	$(CXX) $(CXXFLAGS) $(INCS) $(SDL_CFLAGS) -c $< -o $@

$(BUILD)/sim/%.o: $(PITREX_SIM)/%.cpp
	@mkdir -p $(@D)
	$(CXX) $(CXXFLAGS) $(INCS) $(SDL_CFLAGS) -c $< -o $@

run: $(BUILD)/gongrider
	$(BUILD)/gongrider

# 15000 frames = 5 minutes at 50 Hz. The autopilot lets go at 4:30, so the
# run ends with GAME OVER and the title.
test: $(BUILD)/gongrider_test
	AP_LOG=$(BUILD)/play.csv AP_STOP=13500 PITREX_SHOT=$(BUILD)/test-end.bmp PITREX_FRAMES=15000 \
	    $(BUILD)/gongrider_test

shots: $(BUILD)/gongrider_test
	sh test/shots.sh $(BUILD)/gongrider_test images

img:
	$(MAKE) -f Makefile.pitrex BASE_DIR=$(PITREX_SDK) BAREMETALLIB=yes

clean:
	rm -rf $(BUILD) build build7 gongrider.img

.PHONY: all run test shots img clean
