# SPDX-License-Identifier: GPL-3.0-or-later
cmake_minimum_required(VERSION 3.20)
project(isleforge VERSION 0.0.1 LANGUAGES C)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
# macOS: _POSIX_C_SOURCE hides mkdtemp etc.; re-expose Darwin APIs for the verify/install dev builds
if(APPLE)
  add_compile_definitions(_DARWIN_C_SOURCE)
endif()
option(ISLE_SANITIZE "ASan+UBSan" OFF)
option(ISLE_WITH_SDL "Build the SDL2 frontend" ON)
if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
  if(ISLE_SANITIZE)
    add_compile_options(-fsanitize=address,undefined -fno-omit-frame-pointer)
    add_link_options(-fsanitize=address,undefined)
  endif()
endif()
include(GNUInstallDirs)
add_library(islecore STATIC
  src/core/version.c src/core/present.c src/core/block.c src/core/clock.c
  src/core/settings.c src/core/action.c src/core/gesture.c
  src/core/keymap.c src/core/seats.c src/core/pad.c src/core/ctrlprofile.c
  src/core/camera.c src/core/layout.c src/core/timing.c src/core/coopsave.c)
target_include_directories(islecore PUBLIC src)
if(UNIX)
  target_link_libraries(islecore PUBLIC m)  # action.c stick math (sqrt/pow)
endif()
add_executable(isleforge src/main.c)
target_link_libraries(isleforge PRIVATE islecore)

# Engine VFS (FMT-1): read-only mmap/stdio file views over the installed game-data tree plus
# the bounds-checked 16-byte chunk-container walker. Depends only on islecore (reuses
# isle_block_parse for the strict ANNO magic); never on the installer core.
add_library(islevfs STATIC src/vfs/chunk.c src/vfs/vfs.c)
target_include_directories(islevfs PUBLIC src)
target_link_libraries(islevfs PUBLIC islecore)

# Dev-only chunk-tree inspector. NOT installed (no install() rule): it is a debugging aid to
# eyeball the container reader against a developer's own game files (repo ships none).
add_executable(isleforge-vfs-ls src/vfs/vfs_ls.c)
target_link_libraries(isleforge-vfs-ls PRIVATE islevfs)

# Dev-only timing-parity harness (TIM-3). NOT installed: drives the sim clock with a fake
# monotonic source (selfcheck) or folds a (wall_ms, game_tick, speed) trace against
# config/timing.ini. No game data, no OS clock in the measurement path (D-010/D-011).
add_executable(isle-timing src/core/timing_cli.c)
target_link_libraries(isle-timing PRIVATE islecore)

# Format readers (FMT-2/FMT-5): streaming, zero-copy parsers over a const buffer (mmap from the
# VFS later). No heap, bounded stack, no external deps. .ddf slideshow scripts and text .dat
# tables (FMT-2); RIFF/WAVE audio reader and Bink video detect+metadata (FMT-5: docs/formats/
# ddf.md, dat.md, wav.md, bik.md).
add_library(islefmt STATIC src/fmt/ddf.c src/fmt/ddf_play.c src/fmt/textdat.c src/fmt/wav.c src/fmt/bik.c
  src/fmt/bgruppen.c src/fmt/chains.c src/fmt/housing.c src/fmt/simmap.c
  src/fmt/origsave_walk.c)
target_include_directories(islefmt PUBLIC src)

# Audio mixer core (FMT-5): pure integer software mixer (no SDL, no float) — unit-testable on its
# own and the whole implementation of the null backend. The SDL device wrapper that drives it
# (src/platform/audio.c) is added to the SDL frontend (isleplat) below.
add_library(isleaudio STATIC src/platform/mixer.c src/platform/music.c)
target_include_directories(isleaudio PUBLIC src)
target_link_libraries(isleaudio PUBLIC islecore)

# Sound bank (FMT-5 "VFS wav -> voices", D-039): loads a named .wav through the read-only VFS
# (islevfs), validates it with the RIFF reader (islefmt wav), converts once to the mixer s16 and
# caches it under a byte budget with LRU eviction (§17), then plays it on a voice with volume/pan/
# loop; music is streamed from the VFS in bounded chunks. Pure, SDL-free, directly unit-testable.
add_library(islebank STATIC src/platform/bank.c)
target_include_directories(islebank PUBLIC src)
target_link_libraries(islebank PUBLIC isleaudio islevfs islefmt)
# Sprite/texture format readers (FMT-3): .tex palette + body locator, .inc name->index map, and
# the Figuren* header offset index + bounded on-demand surface cache (LRU, byte cap). Builds on
# the chunk walker (islevfs); decodes no undocumented pixel data — the .tex body encoding and the
# Figuren###.dat RLE grammar stay FMT-6 open questions (D-031). Separate target from the FMT-2
# text parsers to keep the two format PRs independent. Also carries the FMT-4 `.zei` font
# container reader (tex.{c,h}-style: CHARSET + HEAD metrics located, per-glyph table left as an
# undecoded opaque span -> FMT-6), which shares the same chunk walker.
add_library(islesprite STATIC src/fmt/rle.c src/fmt/tex.c src/fmt/incmap.c src/fmt/figuren.c src/fmt/zei.c src/fmt/scp.c src/fmt/anlagen.c src/fmt/bshframe.c src/fmt/groundtex.c src/fmt/objmap.c src/fmt/sze.c)
target_include_directories(islesprite PUBLIC src)
target_link_libraries(islesprite PUBLIC islevfs)

# Dev-only FMT-6 measurement viewer (D1-VIEW, D-038). NOT installed: structure-only stats,
# capped hex excerpts and a local palette swatch over a developer's own game files.
add_library(isledev STATIC src/devtools/measure.c)
target_include_directories(isledev PUBLIC src)
add_executable(isleforge-view src/devtools/view.c)
target_link_libraries(isleforge-view PRIVATE isledev islesprite islefmt)

# Dev-only production-chains inspector (S-SIM). NOT installed: reads Anlagen.dat,
# indexes economy production chains, and prints counts / tables to stdout.
add_executable(isle-anlagen-chains src/fmt/chains_cli.c)
target_link_libraries(isle-anlagen-chains PRIVATE islesprite islevfs islefmt)

# Dev-only housing index inspector (S-SIM). NOT installed: reads Anlagen.dat
# and BGruppen.dat, derives housing assignments, and prints counts / tables to stdout.
add_executable(isle-anlagen-housing src/fmt/housing_cli.c)
target_link_libraries(isle-anlagen-housing PRIVATE islesprite islevfs islefmt)

# Dev-only sim building mapping inspector (S-SIM-MAP). NOT installed: reads Anlagen.dat
# and BGruppen.dat, computes candidates, overlap, and unified goods union.
add_executable(isle-anlagen-simmap src/fmt/simmap_cli.c)
target_link_libraries(isle-anlagen-simmap PRIVATE islesprite islevfs islefmt)

# Dev-only original save container inspector (S-FMT-SAVE, H-013). NOT installed:
# reads a user-supplied .sav file, validates the ANNOADDON1 container,
# and prints the tag tree with offsets and lengths.
add_executable(isle-origsave-inspector src/fmt/origsave_cli.c)
target_link_libraries(isle-origsave-inspector PRIVATE islefmt)


# Software compositor (REN-1/REN-2, D-023/D-028/D-029): pure C11, SDL-free, integer-only. One
# ARGB8888 framebuffer (no per-frame malloc), clipped sprite blit from FMT-3-shaped indexed
# surfaces, dirty-rect tracking, HUD edge anchoring + 4:3 pillarbox, and widescreen render-size
# resolution (mirrors the installer's isle_widescreen_resolve math without depending on the
# installer core, D-026). The platform layer uploads its dirty rects to a GLES2 texture.
add_library(islerender STATIC
  src/render/framebuffer.c src/render/dirty.c src/render/fbdiff.c src/render/hud.c
  src/render/viewport.c src/render/mapview.c src/render/seatview.c src/render/minimap.c)
target_include_directories(islerender PUBLIC src)
target_link_libraries(islerender PUBLIC islecore islesprite)

# Deterministic simulation core (SIM-1, D-040) + native save format (SAVE-0, D-041):
# pure C11, SDL-free, integer/fixed-point only (no float in any state field), one arena
# sized at load (no per-tick heap). Data-driven type table from a caller-supplied
# description (placeholders in config/sim-placeholder.ini, [unverified -> S-SIM]); a
# timestamped command queue applied at fixed ticks; an FNV-1a state hash; and a
# versioned, 16-byte-chunk little-endian save with a bounded, hostile-input-safe reader.
# Also carries the S-FMT-SAVE original-save import/export INTERFACE STUB (origsave.c, D-069):
# the boundary exists and reports "unspecified layout", inventing no original-format fact.
# Depends only on islecore (for the isle_speed enum in core/clock.h); never on SDL.
add_library(islesim STATIC
  src/sim/hash.c src/sim/types.c src/sim/sim.c src/sim/save.c src/sim/origsave.c
  src/sim/aicomp.c src/sim/tradepost.c)
target_include_directories(islesim PUBLIC src)
target_link_libraries(islesim PUBLIC islecore)

# S-ECON-1 (D-061): BGruppen.dat -> economy ruleset glue. Assembles an isle_sim_types from
# the documented goods/groups/demand (islefmt bgruppen reader) + the config placeholder glue
# (terrain/buildings/housing/period/tax, [unverified -> S-SIM]). Depends on islesim + islefmt;
# the consumption tick itself lives in islesim (no islefmt dependency there).
add_library(islesimecon STATIC src/sim/econ.c)
target_include_directories(islesimecon PUBLIC src)
target_link_libraries(islesimecon PUBLIC islesim islefmt)

# S-SIM-MAP (Stage 3): Anlagen records -> sim building-types table and buildmap ingest.
add_library(islesimanlagentypes STATIC src/sim/anlagen_types.c)
target_include_directories(islesimanlagentypes PUBLIC src)
target_link_libraries(islesimanlagentypes PUBLIC islesim islefmt)

# S-SIM-BUILD (D-057): bridge the decoded `.scp` GELAENDE object layer into sim building
# instances via the command queue, so a SAVE-0 round trip is byte-stable with the placed
# buildings. Depends on both the sim core (islesim) and the `.scp` object reader
# (islesprite, for isle_scp_object); the object->building-type map is a placeholder table
# (config/obj-building-placeholder.ini, [unverified -> S-SIM]) that asserts no original fact.
# S-SIM-MAP (Stage 4): loader bridges isle_anlagen_buildmap_build into objbuild behind opt-in.
add_library(islesimbuild STATIC src/sim/objbuild.c)
target_include_directories(islesimbuild PUBLIC src)
target_link_libraries(islesimbuild PUBLIC islesim islesprite islesimanlagentypes)

# UI widget layer + own placeholder bitmap font (UI-1): pure C11, SDL-free, draws into the
# software framebuffer. Mouse/touch/controller-cursor/keyboard all drive the same widgets through
# the core action stream, so focus/nav/hit-test and font metrics are unit-tested with no window.
# The bitmap font is our own GPL glyph design (ASCII + German umlauts), a placeholder until the
# real .zei fonts land (FMT-4); it is NOT copied from any existing typeface.
add_library(isleui STATIC src/ui/font.c src/ui/textfont.c src/ui/ui.c)
target_include_directories(isleui PUBLIC src)
target_link_libraries(isleui PUBLIC islerender)

# S-BUILD-UI (D-059): in-app building placement on the GAME map view. Pure C11, SDL-free: the
# cursor cell picking (inverse of the ground pass's cell->world->screen map), the build-mode state
# machine, and place/remove through the deterministic sim command queue all unit-test with no
# window. Draws only into the software framebuffer + the own font renderer (no sprites, D-050).
# Depends on islesim (queue + placement queries) and isleui (framebuffer + textfont + camera).
add_library(islebuildui STATIC src/app/buildmode.c)
target_include_directories(islebuildui PUBLIC src)
target_link_libraries(islebuildui PUBLIC islesim isleui)

# App shell + screen state machine (APP-1): pure, SDL-free. BOOT -> MENU -> OPTIONS/GAME -> QUIT;
# the OPTIONS screen edits the settings schema and the host saves it via core/settings. The SDL
# host (src/main.c) only pumps actions/ticks in and presents the framebuffer out.
add_library(isleapp STATIC src/app/app.c src/app/sfx.c src/app/savemenu.c src/app/hotkeys.c
                         src/app/video.c)
target_include_directories(isleapp PUBLIC src)
# S-SAVE-MENU (D-060): src/app/savemenu.c serializes/loads the sim via the SAVE-0 core (islesim)
# and drives the overlay through the UI widget layer (isleui), so the app links both. Pure/SDL-free.
# S-BIK-SPEC: video.c reads the intro .bik container header through the read-only VFS (islevfs)
# and fmt/bik.c (islefmt) to specify the fake decoder — still no codec, still SDL-free.
target_link_libraries(isleapp PUBLIC isleui islesim islebuildui islevfs islefmt)
target_link_libraries(isleforge PRIVATE isleapp)

# Dev-only CLI wiring for the S-FMT-SAVE import (D-075). NOT installed: translates a
# user-supplied ORIGINAL .sav into a native, in-game loadable ISLEMENU save slot using the
# implemented library path (origsave import -> buildmap PROD2 restore -> savemenu encode).
# Export stays a stub by design (src/sim/origsave.h). SDL-free (isleapp is pure).
add_executable(isle-origsave-import src/sim/origsave_import_cli.c)
target_link_libraries(isle-origsave-import PRIVATE islesim islesimbuild isleapp)

# Game-data asset loader (APP-2): opens the installed gamedata through the read-only VFS
# (islevfs via islesprite) and decodes the UI `.zei` font + a menu-background / sprite-sheet `.tex`
# (islesprite) into an isle_textfont + ARGB images the app shell renders. SDL-free: the SDL host
# (src/main.c) opens it and hands the pointers to the app. Absent/corrupt data -> NULL accessors
# and the placeholder path is unchanged.
# objview.c (S-OBJ-MAP-b) bridges the GELAENDE object list + the Anlagen sprite cache (islesprite)
# to the framebuffer + camera projection (islerender) and composes the object sprites on top of the
# ground pass; it sits here (not in isleapp) so app.h stays sprite-free and draws through a callback.
add_library(isleassets STATIC src/app/assets.c src/app/objview.c)
target_include_directories(isleassets PUBLIC src)
target_link_libraries(isleassets PUBLIC islesprite isleui islefmt)
target_link_libraries(isleforge PRIVATE isleassets)

# REV-C03: the live main loop owns one isle_sim and steps it via isle_sim_drive on the
# timing.ini sim clock, so src/main.c links the deterministic sim core directly.
target_link_libraries(isleforge PRIVATE islesim)
# S-ECON-1: main.c builds the economy ruleset from BGruppen.dat + the sim config glue.
target_link_libraries(isleforge PRIVATE islesimecon)
# S-SIM-MAP Stage 4: bridge to map placement and ruleset opt-in (--sim-ruleset=anlagen).
target_link_libraries(isleforge PRIVATE islesimbuild islesimanlagentypes)

# Installer core (P1a): own SHA-256, manifest parser, source-tree verifier, filesystem
# helpers, source location, external-unpacker driver and the gamedata installer. No external
# build deps; the only optional runtime tool is innoextract, invoked by execv (D-024).
add_library(isleinstall STATIC
  src/installer/sha256.c src/installer/manifest.c src/installer/verify.c
  src/installer/fsutil.c src/installer/locate.c src/installer/extract.c
  src/installer/install.c src/installer/settings.c src/installer/detect.c)
target_include_directories(isleinstall PUBLIC src)

# Default manifest installed alongside the binary (share/isleforge/manifests).
set(ISLE_MANIFEST_INSTALL_DIR ${CMAKE_INSTALL_FULL_DATADIR}/isleforge/manifests)
add_executable(isleforge-install src/installer/main.c)
target_link_libraries(isleforge-install PRIVATE islecore isleinstall)
target_compile_definitions(isleforge-install PRIVATE
  ISLE_DEFAULT_MANIFEST="${ISLE_MANIFEST_INSTALL_DIR}/gog-2.0.0.5-en-installed.sha256"
  ISLE_DEFAULT_INSTALLER_MANIFEST="${ISLE_MANIFEST_INSTALL_DIR}/gog-2.0.0.5-en-installer.sha256")

install(TARGETS isleforge isleforge-install RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES manifests/gog-2.0.0.5-en-installed.sha256
              manifests/gog-2.0.0.5-en-installer.sha256
        DESTINATION ${CMAKE_INSTALL_DATADIR}/isleforge/manifests)
# Timing-parity config (REV-C03/TIM-3): the engine reads the installed copy for the sim clock
# periods + loop knobs; tools/install.sh also seeds a user-editable copy under the config dir.
install(FILES config/timing.ini DESTINATION ${CMAKE_INSTALL_DATADIR}/isleforge)
# The engine falls back to this read-only installed copy when no --timing PATH and no user-config
# copy is present (src/main.c timing resolution); it never writes it.
target_compile_definitions(isleforge PRIVATE
  ISLE_TIMING_INSTALL_PATH="${CMAKE_INSTALL_FULL_DATADIR}/isleforge/timing.ini")
# REV-C14: the default controller profile (antimicroX .amgp). The engine's load_profile searches
# <datadir>/isleforge/controller for "<controller_profile>.amgp"; package it there so an installed
# run finds it (tools/install.sh copies it under $XDG_DATA_HOME/isleforge/controller as well).
install(FILES config/controller/claw-default.amgp
        DESTINATION ${CMAKE_INSTALL_DATADIR}/isleforge/controller)
# S-ECON-1: the economy glue placeholders [unverified -> S-SIM]. The engine reads the installed
# copy when BGruppen.dat is present and no --sim-config / user-config copy exists; never written.
install(FILES config/sim-placeholder.ini DESTINATION ${CMAKE_INSTALL_DATADIR}/isleforge)
target_compile_definitions(isleforge PRIVATE
  ISLE_SIM_CONFIG_INSTALL_PATH="${CMAKE_INSTALL_FULL_DATADIR}/isleforge/sim-placeholder.ini")
set(_isle_sdl_target "")
if(ISLE_WITH_SDL)
  find_package(SDL2 CONFIG QUIET)
  if(TARGET SDL2::SDL2)
    set(_isle_sdl_target SDL2::SDL2)
  else()
    find_package(PkgConfig QUIET)
    if(PkgConfig_FOUND)
      pkg_check_modules(SDL2PC QUIET IMPORTED_TARGET sdl2)
      if(TARGET PkgConfig::SDL2PC)
        set(_isle_sdl_target PkgConfig::SDL2PC)
      endif()
    endif()
  endif()
endif()
if(_isle_sdl_target)
  # SDL2 frontend: platform layer (D-023 GLES2-first, zlib-licensed SDL2 only, no other deps).
  add_library(isleplat STATIC
    src/platform/video.c src/platform/input.c src/platform/probe.c src/platform/audio.c)
  target_link_libraries(isleplat PUBLIC islecore islerender isleaudio islebank ${_isle_sdl_target})
  target_compile_definitions(isleplat PUBLIC ISLE_HAVE_SDL=1)
  # load_profile (src/platform/input.c, compiled into isleplat) only searches the dev checkout and
  # per-user XDG dirs by default; hand it the absolute install path so a system-prefix
  # `cmake --install` (no user-data copy) can still find the profile.
  target_compile_definitions(isleplat PRIVATE
    ISLE_CONTROLLER_INSTALL_DIR="${CMAKE_INSTALL_FULL_DATADIR}/isleforge/controller")
  target_link_libraries(isleforge PRIVATE isleplat)
elseif(ISLE_WITH_SDL)
  message(STATUS "SDL2 not found: building headless stub (ISLE_HAVE_SDL unset)")
endif()
enable_testing()
foreach(t present block clock core_settings action gesture keymap seats pad camera layout ctrlprofile ctrlmap coopsave)
  add_executable(test_${t} tests/test_${t}.c)
  target_link_libraries(test_${t} PRIVATE islecore)
  add_test(NAME ${t} COMMAND test_${t})
endforeach()
foreach(t sha256 manifest verify fsutil locate extract install settings detect)
  add_executable(test_${t} tests/test_${t}.c)
  target_link_libraries(test_${t} PRIVATE isleinstall)
  add_test(NAME ${t} COMMAND test_${t})
endforeach()
foreach(t chunk vfs vfs_symlink)
  add_executable(test_${t} tests/test_${t}.c)
  target_link_libraries(test_${t} PRIVATE islevfs)
  add_test(NAME ${t} COMMAND test_${t})
endforeach()
foreach(t rle incmap tex figuren zei scp anlagen bshframe groundtex objmap sze)
  add_executable(test_${t} tests/test_${t}.c)
  target_link_libraries(test_${t} PRIVATE islesprite)
  add_test(NAME ${t} COMMAND test_${t})
endforeach()
# Software compositor (REN-1/REN-2): blit clipping/palette/colour-key/alpha + golden hash (fb),
# HUD anchoring + pillarbox + min-size (hud), widescreen render widths + per-viewport
# world<->screen (render), seat-local picking + per-seat software cursors (seatview, REV-C15),
# island-grid minimap with terrain-class colours (minimap, S-MINIMAP).
foreach(t fb hud render mapview fbdiff seatview minimap)
  add_executable(test_${t} tests/test_${t}.c)
  target_link_libraries(test_${t} PRIVATE islerender)
  add_test(NAME ${t} COMMAND test_${t})
endforeach()
# UI-1 (font metrics/glyph coverage, widget focus/nav/hit-test) and APP-1 (state-machine
# transitions + options->settings wiring). All pure C11, no window.
foreach(t font ui)
  add_executable(test_${t} tests/test_${t}.c)
  target_link_libraries(test_${t} PRIVATE isleui)
  add_test(NAME ${t} COMMAND test_${t})
endforeach()
add_executable(test_app tests/test_app.c)
target_link_libraries(test_app PRIVATE isleapp)
add_test(NAME app COMMAND test_app)
# REV-C16 (D-062): documented controller/keyboard hotkey -> engine command lookup (pure, SDL-free).
add_executable(test_hotkeys tests/test_hotkeys.c)
target_link_libraries(test_hotkeys PRIVATE isleapp)
add_test(NAME hotkeys COMMAND test_hotkeys)
# S-SAVE-MENU (D-060): pure headless coverage of the save/load core + slot I/O (temp dirs only) and
# the overlay navigation per input kind. Links isleapp (savemenu + the sim core it wraps).
add_executable(test_savemenu tests/test_savemenu.c)
target_link_libraries(test_savemenu PRIVATE isleapp)
add_test(NAME savemenu COMMAND test_savemenu)
# S-BUILD-UI: cursor cell picking (zoom/offset round-trips), build-mode transitions, place/remove
# via mouse/touch/keyboard/pad actions, invalid placement rejected, and a no-per-frame-heap guard.
add_executable(test_buildmode tests/test_buildmode.c)
target_link_libraries(test_buildmode PRIVATE islebuildui)
add_test(NAME buildmode COMMAND test_buildmode)
# S-AUDIO-EVNT: the pure event -> bank-sample mapping table, the buildmode confirm-outcome
# contract, and the app sfx hook firing (UI focus). Pure C11, no window, no game data (D-007).
add_executable(test_sfx tests/test_sfx.c)
target_link_libraries(test_sfx PRIVATE isleapp islebuildui)
add_test(NAME sfx COMMAND test_sfx)
# S-BIK-PIPE: the playback pipeline behind the frame-source interface — synthetic colour-bar
# fake decoder (bars + frame-marker pixels), budget gate, fixed-step pacing with pause
# semantics, skip, present into the framebuffer, and the app-level play/skip wiring. Pure.
add_executable(test_bikpipe tests/test_bikpipe.c)
target_link_libraries(test_bikpipe PRIVATE isleapp)
add_test(NAME bikpipe COMMAND test_bikpipe)
# APP-2 asset loader: synthetic gamedata tree in a temp dir (no game data, D-007) -> decoded .zei
# font atlas via the VFS, .tex image decode, and the missing/corrupt-data fallback to NULL.
add_executable(test_assets tests/test_assets.c)
target_link_libraries(test_assets PRIVATE isleassets)
add_test(NAME assets COMMAND test_assets)
# S-OBJ-MAP-b object layer: a synthetic Anlagen.dat + a tiny object list composed into a
# framebuffer; asserts pixels/palette, back-to-front order (nearer overwrites farther), culling
# (off-screen objects draw nothing) and the missing-data fallbacks. No game data (D-007), no window.
add_executable(test_objview tests/test_objview.c)
target_link_libraries(test_objview PRIVATE isleassets)
add_test(NAME objview COMMAND test_objview)
add_executable(test_measure tests/test_measure.c)
target_link_libraries(test_measure PRIVATE isledev)
add_test(NAME measure COMMAND test_measure)
add_executable(test_view tests/test_view.c)
add_dependencies(test_view isleforge-view)
add_test(NAME view COMMAND test_view $<TARGET_FILE:isleforge-view>)
add_executable(test_vfs_ls tests/test_vfs_ls.c)
add_dependencies(test_vfs_ls isleforge-vfs-ls)
add_test(NAME vfs_ls COMMAND test_vfs_ls $<TARGET_FILE:isleforge-vfs-ls>)

foreach(t ddf ddfplay textdat wav bik bgruppen chains housing simmap origsave_walk)
  add_executable(test_${t} tests/test_${t}.c)
  target_link_libraries(test_${t} PRIVATE islefmt)
  add_test(NAME ${t} COMMAND test_${t})
endforeach()
# TIM-3: individually selectable pure C11 cases, all using the committed config.
add_executable(test_timing tests/test_timing.c)
target_link_libraries(test_timing PRIVATE islecore)
foreach(case config drift jitter long_run speed_switch pause malformed_csv trace log)
  add_test(NAME timing_${case} COMMAND test_timing ${case} ${CMAKE_SOURCE_DIR}/config/timing.ini)
endforeach()
add_test(NAME timing_selfcheck COMMAND isle-timing selfcheck
  --config ${CMAKE_SOURCE_DIR}/config/timing.ini --seconds 3600 --frame-ms 16)
add_test(NAME timing_trace_cli COMMAND isle-timing trace
  --config ${CMAKE_SOURCE_DIR}/config/timing.ini ${CMAKE_SOURCE_DIR}/tests/timing_trace_sample.csv)
add_test(NAME timing_cli_errors COMMAND ${CMAKE_COMMAND}
  -DTOOL=$<TARGET_FILE:isle-timing> -DCONFIG=${CMAKE_SOURCE_DIR}/config/timing.ini
  -DWORK=${CMAKE_CURRENT_BINARY_DIR}/timing-fixtures -P ${CMAKE_SOURCE_DIR}/tests/timing_cli.cmake)

# SIM-1 / SAVE-0: type-table parse + fingerprint (sim_types), deterministic world/step/
# command-queue/hash incl. 10^5-tick replay determinism + pool exhaustion (sim), and the
# versioned save round-trip + bounded-reader loader fuzz (sim_save). The type-table test
# parses the committed placeholder config; pass its path like the timing cases.
add_executable(test_sim_types tests/test_sim_types.c)
target_link_libraries(test_sim_types PRIVATE islesim)
add_test(NAME sim_types COMMAND test_sim_types ${CMAKE_SOURCE_DIR}/config/sim-placeholder.ini)
foreach(t sim simdrive)
  add_executable(test_${t} tests/test_${t}.c)
  target_link_libraries(test_${t} PRIVATE islesim)
  add_test(NAME ${t} COMMAND test_${t})
endforeach()
add_executable(test_sim_save tests/test_sim_save.c)
target_link_libraries(test_sim_save PRIVATE islesim)
add_test(NAME sim_save COMMAND test_sim_save ${CMAKE_SOURCE_DIR}/config/sim-placeholder.ini)

# S-FMT-SAVE (H-013): original-save import translation + the objbuild PROD2 placement bridge,
# over SYNTHETIC containers built in-test (no game data, D-007): WELT/WARETYPE/role-mapped
# companies/islands/STADT2 stocks/PROD2 records, determinism, hostile-input paths.
add_executable(test_origsave tests/test_origsave.c)
target_link_libraries(test_origsave PRIVATE islesim islesimbuild)
add_test(NAME origsave COMMAND test_origsave)

# S-FMT-SAVE-b (D-075): the isle-origsave-import CLI, run as the REAL binary (test_view
# pattern) over synthetic containers + placeholder inis in a mkdtemp dir (no game data).
add_executable(test_origsave_import_cli tests/test_origsave_import_cli.c)
add_dependencies(test_origsave_import_cli isle-origsave-import)
target_link_libraries(test_origsave_import_cli PRIVATE islesim islesimbuild isleapp)
add_test(NAME origsave_import_cli COMMAND test_origsave_import_cli $<TARGET_FILE:isle-origsave-import>)

# S-FMT-SAVE-c: the engine --origsave boot flag, run as the REAL isleforge binary (test_view
# pattern) over the same synthetic containers as test_origsave_import_cli — GAME entry via the
# script `expect game`, the D-075 summary line, the no-slot-round-trip guarantee (empty XDG data
# dir), and the exit-2 failure paths.
add_executable(test_origsave_boot tests/test_origsave_boot.c)
add_dependencies(test_origsave_boot isleforge)
add_test(NAME origsave_boot COMMAND test_origsave_boot $<TARGET_FILE:isleforge>)

# REV-C18: cross-arch canonical replay and save digests (pure C11, integer only, no SDL).
add_executable(test_xarch tests/test_xarch.c)
target_link_libraries(test_xarch PRIVATE islesim isleinstall)
add_test(NAME xarch COMMAND test_xarch ${CMAKE_SOURCE_DIR}/tests/golden/xarch-digests.txt)

# S-SIM-BUILD (D-057): object layer -> sim buildings via the command queue + the SAVE-0
# round trip with buildings present. Passes the committed placeholder object->building map
# so the config-parse case runs (like the sim_types test). Synthetic only (no game data).
add_executable(test_objbuild tests/test_objbuild.c)
target_link_libraries(test_objbuild PRIVATE islesimbuild)
add_test(NAME objbuild COMMAND test_objbuild ${CMAKE_SOURCE_DIR}/config/obj-building-placeholder.ini)

# S-ECON-1 (D-061): BGruppen glue + the economy consumption tick, over SYNTHETIC fixtures
# (invented symbols/values, no game data D-007). Asserts: goods/groups/demand built from a
# parsed BGruppen fixture, residents consuming demand goods, unmet-demand counting, hash
# determinism and a SAVE-0 round trip carrying the ECON chunk. Passes the committed config so
# the glue's config-parse path runs against the real placeholder file (like sim_types).
add_executable(test_econ tests/test_econ.c)
target_link_libraries(test_econ PRIVATE islesimecon)
add_test(NAME econ COMMAND test_econ ${CMAKE_SOURCE_DIR}/config/sim-placeholder.ini)

# S-AI-COMP (D-081): AI company controller skeleton driving role-12 companies through the
# existing command queue + authorization, over SYNTHETIC fixtures (invented values, no game
# data, D-007). Asserts build-to-demand, treasury guard, authorization, cadence, knob-off
# zero-command identity, two-world determinism (identical command logs) and hostile/empty
# no-ops. Passes the committed config so the [econ] ai_* parse path runs against the real
# placeholder (like test_econ).
add_executable(test_aicomp tests/test_aicomp.c)
target_link_libraries(test_aicomp PRIVATE islesim)
add_test(NAME aicomp COMMAND test_aicomp ${CMAKE_SOURCE_DIR}/config/sim-placeholder.ini)

# S-TRADE-POST (D-082): trade-post pass tests over SYNTHETIC fixtures (invented values,
# no game data, D-007). Asserts NPC + inter-company buy/sell at base prices with exact
# treasury/goods deltas, the ISLE_CMD_TRANSFER_GOODS clamps, owner consent (post-less
# companies never touched; cross-company transfer commands stay DENIED per D-063),
# cadence, knob-off identity, two-world determinism, SAVE-0 re-derivation and hostile
# no-ops. Passes the committed config so the [econ] trade_* parse path runs against the
# real placeholder (like test_econ/test_aicomp).
add_executable(test_tradepost tests/test_tradepost.c)
target_link_libraries(test_tradepost PRIVATE islesim)
add_test(NAME tradepost COMMAND test_tradepost ${CMAKE_SOURCE_DIR}/config/sim-placeholder.ini)

# S-SIM-MAP (Stage 3): synthetic tests for Anlagen economy & housing records ingest
# into simulation building types and objbuild reverse mapping.
add_executable(test_anlagen_types tests/test_anlagen_types.c)
target_link_libraries(test_anlagen_types PRIVATE islesimanlagentypes islesimbuild islesim islefmt islecore)
add_test(NAME anlagen_types COMMAND test_anlagen_types ${CMAKE_SOURCE_DIR}/config/sim-placeholder.ini)

# Pure mixer core (FMT-5): synthetic PCM voices, resampling, volume/mute, music streaming,
# hostile/overflow inputs. No audio device needed; runs everywhere, ASan-clean.
add_executable(test_mixer tests/test_mixer.c)
target_link_libraries(test_mixer PRIVATE isleaudio)
add_test(NAME mixer COMMAND test_mixer)

# Playlist state machine over the mixer music stream (S-MUSIC-STATE): synthetic track
# specs only, boundary-split pulls, loop modes, pause/stop, spin guard, mixer end to end.
add_executable(test_music tests/test_music.c)
target_link_libraries(test_music PRIVATE isleaudio)
add_test(NAME music COMMAND test_music)

# Sound bank (FMT-5, D-039): synthetic WAVs written to a temp VFS tree (no game data, D-007);
# case-insensitive VFS load, cache hit/eviction under budget, unsupported-encoding negative cache,
# volume/pan voices and bounded music streaming. SDL-free, runs everywhere, ASan/UBSan-clean.
add_executable(test_bank tests/test_bank.c)
target_link_libraries(test_bank PRIVATE islebank)
add_test(NAME bank COMMAND test_bank)
add_test(NAME version COMMAND isleforge --version)
add_test(NAME installer_defaults COMMAND isleforge-install --print-defaults)
if(_isle_sdl_target)
  add_executable(test_build_startup tests/test_build_startup.c)
  target_link_libraries(test_build_startup PRIVATE isleplat isleapp isleassets islesimecon islesim islesimbuild islesimanlagentypes)
  add_test(NAME build_startup COMMAND test_build_startup ${CMAKE_SOURCE_DIR}/config/sim-placeholder.ini)

  add_executable(test_present_upload tests/test_present_upload.c)
  target_link_libraries(test_present_upload PRIVATE isleplat isleapp isleassets islesimecon islesim islesimbuild islesimanlagentypes)
  add_test(NAME present_upload COMMAND test_present_upload)

  # Upload dimension validation and texture contents, using an in-memory software renderer.
  add_executable(test_video tests/test_video.c)
  target_link_libraries(test_video PRIVATE isleplat)
  add_test(NAME video COMMAND test_video)

  # Headless SDL smoke: run the app shell for a few frames under the dummy driver.
  add_test(NAME headless_smoke COMMAND isleforge --headless --frames 3)
  set_tests_properties(headless_smoke PROPERTIES
    ENVIRONMENT "SDL_VIDEODRIVER=dummy;SDL_AUDIODRIVER=dummy")
  # APP-1 scripted end-to-end (SDL dummy): walk menu -> options -> change a value -> save -> quit
  # and assert the written settings.ini reflects the change (and still loads with zero rejects).
  add_test(NAME app_selftest COMMAND /bin/sh ${CMAKE_SOURCE_DIR}/tests/app_selftest.sh
    $<TARGET_FILE:isleforge> ${CMAKE_SOURCE_DIR}/tests/app_selftest.script)
  set_tests_properties(app_selftest PROPERTIES
    ENVIRONMENT "SDL_VIDEODRIVER=dummy;SDL_AUDIODRIVER=dummy")
  # S-SHOT-TEST: `shot <path>` coverage — a scripted mini-walk dumps two BMP evidence frames
  # (menu + GAME after a pan); the harness asserts 'BM' magic, the 54-byte header fields and
  # the exact 54 + 800*600*3 size, pinning the format the VIM1S board evidence walks rely on.
  add_test(NAME shot_selftest COMMAND /bin/sh ${CMAKE_SOURCE_DIR}/tests/shot_selftest.sh
    $<TARGET_FILE:isleforge> ${CMAKE_SOURCE_DIR}/tests/shot_selftest.script)
  set_tests_properties(shot_selftest PROPERTIES
    ENVIRONMENT "SDL_VIDEODRIVER=dummy;SDL_AUDIODRIVER=dummy")
  # S-MM-WALK-TEST: `--synthetic-island` + `zoom` script command coverage (S-MINIMAP-CAM-VIM1S).
  # The board evidence walk runs on a synthetic 64x64 island; mmwalk_check (C, white-pixel scan
  # of the minimap panel) asserts the viewport indicator bbox of every dumped frame — tap-jump
  # pin, pan follow, zoom grow to the full panel, and the zoom round-trip back to the exact
  # reset bbox (byte-identical frame) — securing the board evidence path against regressions.
  add_executable(mmwalk_check tests/mmwalk_check.c)
  add_test(NAME mmwalk_selftest COMMAND /bin/sh ${CMAKE_SOURCE_DIR}/tests/mmwalk_selftest.sh
    $<TARGET_FILE:isleforge> ${CMAKE_SOURCE_DIR}/tests/mmwalk_selftest.script
    $<TARGET_FILE:mmwalk_check>)
  set_tests_properties(mmwalk_selftest PROPERTIES
    ENVIRONMENT "SDL_VIDEODRIVER=dummy;SDL_AUDIODRIVER=dummy")
  # S-TIMING-SCRIPT: --script runs must honour ISLE_TIMING_LOG (the PERF-VIM1S board benchmarks
  # are scripted runs) — assert the strict (wall_ms,game_tick,speed) CSV: header, known speeds,
  # strictly increasing wall_ms, and pause with a frozen tick across the menu walk.
  add_test(NAME timing_script COMMAND /bin/sh ${CMAKE_SOURCE_DIR}/tests/timing_script.sh
    $<TARGET_FILE:isleforge> ${CMAKE_SOURCE_DIR}/tests/timing_script.script pause)
  set_tests_properties(timing_script PROPERTIES
    ENVIRONMENT "SDL_VIDEODRIVER=dummy;SDL_AUDIODRIVER=dummy")
  # S-TIMING-SCRIPT-b: same strict CSV across a MIXED walk (menu -> GAME -> menu): every
  # pause<->running flip gets a transition row before ticks run at the new speed, so no
  # pause interval may absorb the GAME ticks (isle-timing trace attribution).
  add_test(NAME timing_script_mixed COMMAND /bin/sh ${CMAKE_SOURCE_DIR}/tests/timing_script.sh
    $<TARGET_FILE:isleforge> ${CMAKE_SOURCE_DIR}/tests/timing_script_mixed.script mixed)
  set_tests_properties(timing_script_mixed PROPERTIES
    ENVIRONMENT "SDL_VIDEODRIVER=dummy;SDL_AUDIODRIVER=dummy")
  # S-TIMING-SCRIPT-c: paced walk — every running interval comes from `wait_real`'s fixed-step
  # sim clock, so its ticks can never complete faster than real time (>= 100 ms/tick); the
  # unpaced `wait` fast-forward (~0.2-0.5 ms/tick on the VIM1S A35, PERF-VIM1S-d) fails it.
  add_test(NAME timing_script_paced COMMAND /bin/sh ${CMAKE_SOURCE_DIR}/tests/timing_script.sh
    $<TARGET_FILE:isleforge> ${CMAKE_SOURCE_DIR}/tests/timing_script_paced.script paced)
  set_tests_properties(timing_script_paced PROPERTIES
    ENVIRONMENT "SDL_VIDEODRIVER=dummy;SDL_AUDIODRIVER=dummy")
  # S-TIMING-SCRIPT-f: every-speed paced walk — `speed` flips route SET_SPEED like the future
  # speed UI; each running interval is judged at ITS speed's timing.ini period (half 200 /
  # normal 100 / double 50 / quad 25 ms/tick) and the walk must pace ticks at all four speeds
  # (P6 parity is judged at every speed; PERF-VIM1S-d/e device evidence was normal-only).
  add_test(NAME timing_script_speeds COMMAND /bin/sh ${CMAKE_SOURCE_DIR}/tests/timing_script.sh
    $<TARGET_FILE:isleforge> ${CMAKE_SOURCE_DIR}/tests/timing_script_speeds.script speeds)
  set_tests_properties(timing_script_speeds PROPERTIES
    ENVIRONMENT "SDL_VIDEODRIVER=dummy;SDL_AUDIODRIVER=dummy")
  # Touch vs synthesized-mouse de-duplication (CodeRabbit PR #6).
  add_executable(test_input tests/test_input.c)
  target_link_libraries(test_input PRIVATE isleplat)
  # Run from the source tree so isle_input_init finds the shipped controller profile
  # (config/controller/claw-default.amgp) and the SDL virtual-pad test exercises the real
  # profile-driven button mapping (REV-C14).
  add_test(NAME input COMMAND test_input WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
  set_tests_properties(input PROPERTIES
    ENVIRONMENT "SDL_VIDEODRIVER=dummy;SDL_AUDIODRIVER=dummy")
  # SDL audio backend: open under the dummy driver, play/stop voices, stream music, destroy.
  add_executable(test_audio tests/test_audio.c)
  target_link_libraries(test_audio PRIVATE isleplat)
  add_test(NAME audio COMMAND test_audio)
  set_tests_properties(audio PROPERTIES
    ENVIRONMENT "SDL_VIDEODRIVER=dummy;SDL_AUDIODRIVER=dummy")

  # PERF-1/PERF-2 (D-032): proxy-measurable VIM1S §17 budget gate. Runs the engine
  # headless, measures peak RSS (getrusage), stripped binary sizes and headless startup
  # against config/budgets.ini; emits a markdown report into the build dir (gitignored).
  # Under sanitizers the numbers are inflated, so the gate is report-only (ISLE_BUDGET_SOFT)
  # and the real enforcement is the Release proxy (tools/perf-proxy.sh, tools/ci-arm64.sh).
  add_executable(budget_smoke tests/budget_smoke.c)
  if(ISLE_SANITIZE)
    target_compile_definitions(budget_smoke PRIVATE ISLE_BUDGET_SOFT=1)
  endif()
  add_test(NAME budget_smoke COMMAND budget_smoke
    --engine $<TARGET_FILE:isleforge>
    --installer $<TARGET_FILE:isleforge-install>
    --budgets ${CMAKE_SOURCE_DIR}/config/budgets.ini
    --report ${CMAKE_BINARY_DIR}/budget-report.md)
  add_test(NAME budget_report_validation COMMAND /bin/sh
    ${CMAKE_SOURCE_DIR}/tests/budget_report_validation.sh $<TARGET_FILE:budget_smoke>)
  set_tests_properties(budget_smoke budget_report_validation PROPERTIES LABELS "budget")
endif()

# REV-C06 (D-032): budget gates BEYOND the headless shell (ctest label "budget"). SDL-free,
# in-process workloads so they run with or without SDL: a synthetic world + economy + audio +
# save/load + two co-op views (budget_workload), and the installer SHA-256 verify + tree-install
# core (budget_installer). Each measures this process's peak RSS (VmHWM) + its temp/install disk
# footprint against the VIM1S caps in config/budgets.ini (docs/VIM1S.md §6). As with budget_smoke,
# RSS gates are report-only under sanitizers (ISLE_BUDGET_SOFT; ASan inflates RSS) and the Release
# proxy (tools/perf-proxy.sh) is the real RSS gate; the disk gates are not sanitizer-affected and
# bite in every build. Run just these with: ctest -L budget.
add_executable(budget_workload tests/budget_workload.c)
target_include_directories(budget_workload PRIVATE ${CMAKE_SOURCE_DIR}/tests)
target_link_libraries(budget_workload PRIVATE islesim islerender islebank isleaudio islevfs islefmt islecore)
add_executable(budget_installer tests/budget_installer.c)
target_include_directories(budget_installer PRIVATE ${CMAKE_SOURCE_DIR}/tests)
target_link_libraries(budget_installer PRIVATE isleinstall islecore)
if(ISLE_SANITIZE)
  target_compile_definitions(budget_workload PRIVATE ISLE_BUDGET_SOFT=1)
  target_compile_definitions(budget_installer PRIVATE ISLE_BUDGET_SOFT=1)
endif()
add_test(NAME budget_workload COMMAND budget_workload --budgets ${CMAKE_SOURCE_DIR}/config/budgets.ini)
add_test(NAME budget_installer COMMAND budget_installer --budgets ${CMAKE_SOURCE_DIR}/config/budgets.ini)
set_tests_properties(budget_workload budget_installer PROPERTIES LABELS "budget")
# P1a-D: end-to-end test of tools/install.sh (install -> update -> repair -> uninstall) against
# the built binaries, using a synthetic game tree + manifest only (no real game data, D-007).
# Skips (77) when no sha256 CLI is present. Uses both the installer core and the engine binary.
add_test(NAME install_e2e
  COMMAND /bin/sh ${CMAKE_SOURCE_DIR}/tests/install_e2e.sh)
set_tests_properties(install_e2e PROPERTIES
  ENVIRONMENT "ISLE_INSTALL_E2E_BUILD=${CMAKE_BINARY_DIR}"
  SKIP_RETURN_CODE 77)

# S-PKG-RC: the RC bundling path — tools/release.sh builds a clean tarball (no game data, D-007)
# and install.sh --prebuilt uses the bundled binaries or falls back to a build. Synthetic fixtures
# only (reuses the built binaries for the --prebuilt smoke). Skips (77) when no sha256 CLI.
add_test(NAME release_e2e
  COMMAND /bin/sh ${CMAKE_SOURCE_DIR}/tests/release_e2e.sh)
set_tests_properties(release_e2e PROPERTIES
  ENVIRONMENT "ISLE_INSTALL_E2E_BUILD=${CMAKE_BINARY_DIR}"
  SKIP_RETURN_CODE 77)

# D-009: C11 only, no C++ in the core. Fails if any .cpp/.cc/.hpp (etc.) lives under src/ or tests/.
add_test(NAME no_cxx COMMAND ${CMAKE_COMMAND} -DISLE_ROOT=${CMAKE_SOURCE_DIR} -P ${CMAKE_SOURCE_DIR}/cmake/no_cxx.cmake)

# REV-C16: negative test suite for tools/check-clean.sh (renamed assets, staged/historical
# forbidden blobs, decompiler text in docs, and positive clean case). Label "clean".
add_test(NAME check_clean_neg
  COMMAND /bin/sh ${CMAKE_SOURCE_DIR}/tests/test_check_clean.sh)
set_tests_properties(check_clean_neg PROPERTIES
  LABELS "clean"
  ENVIRONMENT "ISLE_SOURCE_DIR=${CMAKE_SOURCE_DIR}"
  SKIP_RETURN_CODE 77)

