From 384f1ed1f20568810e05a0221257c1a89c676b00 Mon Sep 17 00:00:00 2001 From: Erik Simon Date: Fri, 25 Sep 2026 00:25:51 +0200 Subject: [PATCH] feat: engine skeleton (Build Order step 1) and siege_tests Engine: - SdlContext and Window: RAII, throwing constructors, non-movable - FrameClock (real time, clamped dt) and SimClock (fixed 1/60 s steps, speed 0 = planning phase, backlog capped per frame) - Application owns them in lifetime order, exposes EngineContext, and runs the fixed-timestep loop; AppConfig::FromArgs parses --frames, --seed and --fullscreen - Temporary window-surface fill so Wayland maps the window until RenderDevice lands in step 2 Build: - Split into the siege_engine static lib and the siege_deck exe - check_engine_deps fails the build if Engine/ includes Game/ - ctest smoke test: siege_deck --frames 30 on the offscreen driver - siege_tests on Catch2 v3.15.3 (nixpkgs + CPM pin), with SimClock, FrameClock and AppConfig tests Docs: - Decision Log: error handling split, Catch2 for unit tests - Build Order step 1 done; Engine Overview, Main Loop and Time and README updated to match - AGENTS.md with build, conventions and gotchas for coding agents - .gitignore: .mcp.json (local CLion MCP port) and Obsidian's workspace.json (tab/pane state), now untracked Co-Authored-By: Claude Opus 5.5 --- .gitignore | 7 +- AGENTS.md | 126 ++++++++++ CMakeLists.txt | 83 ++++++- CMakePresets.json | 4 + Docs/SiegeDeck/.obsidian/workspace.json | 250 -------------------- Docs/SiegeDeck/Decision Log.md | 7 + Docs/SiegeDeck/Engine/Build Order.md | 2 +- Docs/SiegeDeck/Engine/Engine Overview.md | 6 +- Docs/SiegeDeck/Engine/Main Loop and Time.md | 7 +- README.md | 10 +- Source/Engine/Application.cpp | 124 ++++++++++ Source/Engine/Application.h | 77 ++++++ Source/Engine/Platform/SdlContext.cpp | 32 +++ Source/Engine/Platform/SdlContext.h | 31 +++ Source/Engine/Platform/Window.cpp | 61 +++++ Source/Engine/Platform/Window.h | 59 +++++ Source/Engine/Time/FrameClock.cpp | 30 +++ Source/Engine/Time/FrameClock.h | 40 ++++ Source/Engine/Time/SimClock.cpp | 41 ++++ Source/Engine/Time/SimClock.h | 54 +++++ Source/Main.cpp | 27 ++- Tests/Engine/AppConfigTests.cpp | 66 ++++++ Tests/Engine/Time/FrameClockTests.cpp | 41 ++++ Tests/Engine/Time/SimClockTests.cpp | 133 +++++++++++ cmake/CheckEngineDeps.cmake | 22 ++ flake.nix | 3 + 26 files changed, 1072 insertions(+), 271 deletions(-) create mode 100644 AGENTS.md delete mode 100644 Docs/SiegeDeck/.obsidian/workspace.json create mode 100644 Source/Engine/Application.cpp create mode 100644 Source/Engine/Application.h create mode 100644 Source/Engine/Platform/SdlContext.cpp create mode 100644 Source/Engine/Platform/SdlContext.h create mode 100644 Source/Engine/Platform/Window.cpp create mode 100644 Source/Engine/Platform/Window.h create mode 100644 Source/Engine/Time/FrameClock.cpp create mode 100644 Source/Engine/Time/FrameClock.h create mode 100644 Source/Engine/Time/SimClock.cpp create mode 100644 Source/Engine/Time/SimClock.h create mode 100644 Tests/Engine/AppConfigTests.cpp create mode 100644 Tests/Engine/Time/FrameClockTests.cpp create mode 100644 Tests/Engine/Time/SimClockTests.cpp create mode 100644 cmake/CheckEngineDeps.cmake diff --git a/.gitignore b/.gitignore index eea23aa..9c6160a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,8 @@ cmake-build-*/ build/ out/ -# CLion +# CLion (.mcp.json points at the local CLion MCP server; its port is per machine) +.mcp.json .idea/ # direnv @@ -39,6 +40,10 @@ _deps/ # ImGui window layout, written at runtime next to the executable imgui.ini +# Obsidian: open tabs and pane layout, rewritten on every use of the vault. +# The rest of .obsidian/ (settings, plugins) stays tracked. +Docs/SiegeDeck/.obsidian/workspace.json + # Editors / OS .vscode/ *.code-workspace diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..7046245 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,126 @@ +# AGENTS.md + +Guidance for coding agents working in this repository. The README covers human setup +(direnv, CLion, clangd); this file covers what you need to change code safely. + +## What this is + +Siege Deck: a from-scratch tower defense deck-builder in C++26 on SDL3. Rounds are a +paused planning phase (play cards, place towers) followed by a real-time wave. Towers +sit on a tile grid; enemies walk fixed lanes. Rendering is rigid-part 3D on SDL_GPU; +the simulation is 2D on the ground plane. + +## Build and test + +Everything needs the nix devShell. Outside direnv, wrap every command in +`nix develop --command bash -c '...'`. + +```sh +cmake --preset debug # configure (Ninja) into cmake-build-debug/ +cmake --build --preset debug # siege_engine, siege_deck, siege_tests +ctest --preset debug # Catch2 cases + the headless smoke test +./cmake-build-debug/bin/siege_deck --frames 30 +``` + +- `nix develop .#gcc` gives the same shell with gcc 15. Build with both before calling + anything done: gcc is stricter about name lookup (a member can't be named like its + type, e.g. `Window& Window;`). +- The smoke test runs `siege_deck --frames 30` with `SDL_VIDEO_DRIVER=offscreen`, so it + needs no display. +- A bare `ctest` from a build directory that isn't a preset works too; `--preset` only + adds `outputOnFailure`. +- `python3` is not installed. Use sed/awk, a heredoc, or a `cmake -P` script. + +## Layout + +``` +Source/ + Common.h, Pch.h vocabulary types; Pch.h is force-included everywhere + Engine/ static lib siege_engine: game-agnostic + Game/ everything specific to Siege Deck (still empty) + Main.cpp parses AppConfig, runs Application +Tests/ siege_tests (Catch2 v3), mirrors Source/ +Docs/SiegeDeck/ Obsidian vault: design docs, GDD, Decision Log +cmake/ CPM bootstrap, ImGui build, CheckEngineDeps.cmake, CLion env +``` + +The planned engine layout (Core, Platform, Time, Input, Render, Assets, Audio, Script, +Scene, Ecs, Random, Debug) is in `Docs/SiegeDeck/Engine/Engine Overview.md`. Put new +engine code where that page says it goes. + +## Rules that are enforced + +- **Engine never includes Game.** Both targets use `Source/` as the include root, so the + compiler can't stop it. `check_engine_deps` fails the build if any file under + `Source/Engine` includes `Game/...`. +- **New source files go in `CMakeLists.txt` by hand.** No globbing. Engine files are + listed in `add_library(siege_engine ...)`, tests in `add_executable(siege_tests ...)`. +- **Dependencies are pinned twice, to the same version.** Each dependency is a + `CPMAddPackage` whose `VERSION` matches nixpkgs, plus an entry in `flake.nix`'s `deps`. + `NAME` must be the `find_package` name. Bumping one side means bumping the other. + Check the nixpkgs version with `nix eval --raw --inputs-from . nixpkgs#.version`. + +## Conventions + +- **Formatting:** `.clang-format` (Allman braces, 4 spaces, namespace bodies indented, + 110 columns, `Type name { value }` with spaces around braces). +- **Naming:** types, functions and public struct fields in PascalCase (`AppConfig::MaxFrames`); + private members and locals in camelCase with no prefix (`frameClock`); constants `kName`. + Constructor parameters must not shadow members: in an initializer list, later + initializers would read the moved-from parameter. +- **Vocabulary types from `Common.h`:** `int32`, `uint64`, `string`, `Vector`, `Map`, + `Optional`/`None`, `Ref`/`MakeRef`, `UniqueRef`/`MakeUniqueRef`. Headers rely on `Pch.h` + and don't include `Common.h` themselves. +- **Namespaces:** `SiegeDeck::Engine` (nested-name form, not nested blocks). File-local + helpers go in an unnamed namespace; clang-tidy's `misc-*` flags `static` and + external-linkage helpers. +- **File header:** new files start with the `// Created by darman on ` block the + IDE writes. +- **Comments:** explain *why*, not what. Match the existing density. + +## Error handling + +Recoverable errors are values; fatal ones are exceptions (Decision Log: "Error handling +split"). + +- `std::expected` for failures the caller handles on the spot: asset/script/definition + loading, CLI parsing. Callers log and fall back, which hot reload depends on. +- Exceptions (`std::runtime_error`, `std::invalid_argument`) for startup failures and + broken invariants. Constructors throw; `main` catches once, logs, and exits with 1. +- Platform types are plain RAII: throwing constructor, non-movable when there's exactly + one (`SdlContext`, `Window`), no empty or moved-from state. +- Never let an exception cross a C callback (SDL, the script VM). + +## Architecture in brief + +- `Application` owns every subsystem as a member. **Declaration order is lifetime order**: + a subsystem is declared after everything it depends on. Scenes reach the engine through + `EngineContext` (a struct of references). No singletons, no globals. +- Two clocks: `FrameClock` (real time, for UI/cards/camera, never paused) and `SimClock` + (fixed 1/60 s steps, `SetSpeed(0)` is the planning phase, 2x/3x runs more steps rather + than bigger ones). See `Docs/SiegeDeck/Engine/Main Loop and Time.md`. +- Runs are seeded (`--seed`); combat does not need to replay bit-exactly. + +## Docs + +The vault in `Docs/SiegeDeck/` is the design source of truth. It uses Obsidian +`[[wikilinks]]`. + +- `Engine/Build Order.md`: the roadmap. Tick the checkbox when you finish a step. +- `Decision Log.md`: append an entry (date, status, context, decision, consequences) for + any architectural decision. Newest at the bottom. +- `Open Questions.md`: things still undecided (e.g. the scripting language). +- When code diverges from a doc, update the doc in the same change. +- Don't edit `Docs/SiegeDeck/.obsidian/`. + +## Gotchas + +- **Wayland shows no window until a frame is presented.** Until `RenderDevice` exists, + `Application::DrawFrame` fills the window surface each frame. Window surfaces can't be + mixed with SDL_GPU, so that stand-in goes away in Build Order step 2. +- **clang-tidy on the command line fails** with a PCH `__OPTIMIZE__` mismatch against + `cmake-build-debug`. clangd in the editor is fine. +- **The compositor may resize the window** (tiling). Read `Window::Size()` and + `PixelSize()` every frame; don't cache the requested size. +- **`FrameClock` tests sleep for real**, so timing bounds are loose, and the slow one is + tagged `[slow]`. diff --git a/CMakeLists.txt b/CMakeLists.txt index eae7214..ef381b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -115,21 +115,58 @@ list(APPEND LIBS EnTT::EnTT) include(ImGui) list(APPEND LIBS imgui::imgui) +# Unit tests (siege_tests only, not in LIBS). +CPMAddPackage( + NAME Catch2 + VERSION 3.15.3 + GITHUB_REPOSITORY catchorg/Catch2 + GIT_TAG v3.15.3 + FIND_PACKAGE_ARGUMENTS "CONFIG") + # --------------------------------------------------------------------------- -# Target +# Targets +# +# siege_engine is game-agnostic; siege_deck is the game on top of it. Engine code +# must never include anything from Source/Game (see Docs: Engine Overview). +# Both share Source/ as their include root, so the compiler can't stop that on +# its own; check_engine_deps does, on every build. # --------------------------------------------------------------------------- -add_executable(${PROJECT_NAME} - Source/Main.cpp +add_library(siege_engine STATIC Source/Common.h - Source/Pch.h) + Source/Pch.h + Source/Engine/Application.cpp + Source/Engine/Application.h + Source/Engine/Platform/SdlContext.cpp + Source/Engine/Platform/SdlContext.h + Source/Engine/Platform/Window.cpp + Source/Engine/Platform/Window.h + Source/Engine/Time/FrameClock.cpp + Source/Engine/Time/FrameClock.h + Source/Engine/Time/SimClock.cpp + Source/Engine/Time/SimClock.h) -target_include_directories(${PROJECT_NAME} PRIVATE +target_include_directories(siege_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/Source) -target_link_libraries(${PROJECT_NAME} PRIVATE ${LIBS}) +# PUBLIC: engine headers expose SDL, glm and Common.h types, so the game needs them too. +target_link_libraries(siege_engine PUBLIC ${LIBS}) -target_precompile_headers(${PROJECT_NAME} PRIVATE Source/Pch.h) +# PUBLIC so siege_deck builds its own PCH from the same header: engine headers +# rely on Common.h being there without including it. +target_precompile_headers(siege_engine PUBLIC Source/Pch.h) + +add_custom_target(check_engine_deps + COMMAND ${CMAKE_COMMAND} -DENGINE_DIR=${CMAKE_CURRENT_SOURCE_DIR}/Source/Engine + -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/CheckEngineDeps.cmake + COMMENT "Checking that Engine/ doesn't include Game/" + VERBATIM) +add_dependencies(siege_engine check_engine_deps) + +add_executable(${PROJECT_NAME} + Source/Main.cpp) + +target_link_libraries(${PROJECT_NAME} PRIVATE siege_engine) # Assets are looked up relative to the executable, so the same path works from # the build dir, from CLion's runner, and from an installed copy. @@ -137,3 +174,35 @@ add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Assets $/Assets) + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + +enable_testing() + +# Boots the whole engine and runs 30 frames. The offscreen video driver needs no +# display, so this runs unattended in CI: ctest --preset debug +add_test(NAME smoke COMMAND ${PROJECT_NAME} --frames 30) +set_tests_properties(smoke PROPERTIES + ENVIRONMENT "SDL_VIDEO_DRIVER=offscreen" + TIMEOUT 30) + +# Unit tests: engine (and later game) logic, no window. Each TEST_CASE shows up in +# ctest on its own, next to the smoke test. +add_executable(siege_tests + Tests/Engine/AppConfigTests.cpp + Tests/Engine/Time/FrameClockTests.cpp + Tests/Engine/Time/SimClockTests.cpp) + +target_link_libraries(siege_tests PRIVATE siege_engine Catch2::Catch2WithMain) + +# catch_discover_tests lives in Catch.cmake: under extras/ in a source checkout +# (CPM download), next to Catch2Config.cmake in an installed one (nixpkgs). +if (Catch2_SOURCE_DIR) + list(APPEND CMAKE_MODULE_PATH ${Catch2_SOURCE_DIR}/extras) +else () + list(APPEND CMAKE_MODULE_PATH ${Catch2_DIR}) +endif () +include(Catch) +catch_discover_tests(siege_tests) diff --git a/CMakePresets.json b/CMakePresets.json index 8123c70..431c52f 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -30,5 +30,9 @@ "buildPresets": [ { "name": "debug", "configurePreset": "debug" }, { "name": "release", "configurePreset": "release" } + ], + "testPresets": [ + { "name": "debug", "configurePreset": "debug", "output": { "outputOnFailure": true } }, + { "name": "release", "configurePreset": "release", "output": { "outputOnFailure": true } } ] } diff --git a/Docs/SiegeDeck/.obsidian/workspace.json b/Docs/SiegeDeck/.obsidian/workspace.json deleted file mode 100644 index 7b10ba8..0000000 --- a/Docs/SiegeDeck/.obsidian/workspace.json +++ /dev/null @@ -1,250 +0,0 @@ -{ - "main": { - "id": "c6ad48c4d87faead", - "type": "split", - "children": [ - { - "id": "dd3e919d5adca5d6", - "type": "tabs", - "dimension": 75.6, - "children": [ - { - "id": "ca9ae29dd35549a6", - "type": "leaf", - "state": { - "type": "markdown", - "state": { - "file": "Engine/Engine Overview.md", - "mode": "source", - "source": false - }, - "icon": "lucide-file", - "title": "Engine Overview" - }, - "group": "994c0f9c38f6b8e7" - } - ] - }, - { - "id": "81ff5c2ddea79443", - "type": "tabs", - "dimension": 24.4, - "children": [ - { - "id": "3ffd1b71ff5031fb", - "type": "leaf", - "state": { - "type": "graph", - "state": {}, - "icon": "lucide-git-fork", - "title": "Graph view" - }, - "group": "994c0f9c38f6b8e7" - } - ] - } - ], - "direction": "vertical" - }, - "left": { - "id": "c526f838c3013812", - "type": "split", - "children": [ - { - "id": "eb2dfb1df8634a0c", - "type": "tabs", - "children": [ - { - "id": "52a36e40b9c1e252", - "type": "leaf", - "state": { - "type": "file-explorer", - "state": { - "sortOrder": "alphabetical", - "autoReveal": false, - "showSearch": false, - "searchQuery": "" - }, - "icon": "lucide-folder-closed", - "title": "Files" - } - }, - { - "id": "2c43a3b8b250ec4b", - "type": "leaf", - "state": { - "type": "search", - "state": { - "query": "", - "matchingCase": false, - "explainSearch": false, - "collapseAll": false, - "extraContext": false, - "sortOrder": "alphabetical" - }, - "icon": "lucide-search", - "title": "Search" - } - }, - { - "id": "bef1b4e0dcac47ac", - "type": "leaf", - "state": { - "type": "bookmarks", - "state": { - "showSearch": false, - "searchQuery": "" - }, - "icon": "lucide-bookmark", - "title": "Bookmarks" - } - } - ] - } - ], - "direction": "horizontal", - "width": 200 - }, - "right": { - "id": "165c68de881d9c62", - "type": "split", - "children": [ - { - "id": "56bb9a9be0aad677", - "type": "tabs", - "children": [ - { - "id": "2d2d24ac04d84dfa", - "type": "leaf", - "state": { - "type": "backlink", - "state": { - "file": "GDD/GDD.md", - "collapseAll": false, - "extraContext": false, - "sortOrder": "alphabetical", - "showSearch": false, - "searchQuery": "", - "backlinkCollapsed": false, - "unlinkedCollapsed": true - }, - "icon": "links-coming-in", - "title": "Backlinks" - } - }, - { - "id": "9b473e8ba1177409", - "type": "leaf", - "state": { - "type": "outgoing-link", - "state": { - "file": "GDD/GDD.md", - "linksCollapsed": false, - "unlinkedCollapsed": true - }, - "icon": "links-going-out", - "title": "Outgoing links" - } - }, - { - "id": "aa2f1e787db366cd", - "type": "leaf", - "state": { - "type": "tag", - "state": { - "sortOrder": "frequency", - "useHierarchy": true, - "showSearch": false, - "searchQuery": "" - }, - "icon": "lucide-tags", - "title": "Tags" - } - }, - { - "id": "29c62914f1935eb6", - "type": "leaf", - "state": { - "type": "all-properties", - "state": { - "sortOrder": "frequency", - "showSearch": false, - "searchQuery": "" - }, - "icon": "lucide-archive", - "title": "All properties" - } - }, - { - "id": "8dc46f1b185ecc04", - "type": "leaf", - "state": { - "type": "outline", - "state": { - "file": "GDD/GDD.md", - "followCursor": false, - "showSearch": false, - "searchQuery": "" - }, - "icon": "lucide-list", - "title": "Outline" - } - } - ] - } - ], - "direction": "horizontal", - "width": 300, - "collapsed": true - }, - "left-ribbon": { - "hiddenItems": { - "switcher:Open quick switcher": false, - "graph:Open graph view": false, - "canvas:Create new canvas": false, - "daily-notes:Open today's daily note": false, - "templates:Insert template": false, - "command-palette:Open command palette": false, - "bases:Create new base": false - } - }, - "active": "ca9ae29dd35549a6", - "lastOpenFiles": [ - "Engine/sedb6yZpr", - "Engine/Main Loop and Time.md", - "Engine/Randomness.md", - "GDD/GDD.md", - "Home.md", - "Game/Game Constraints.md", - "Open Questions.md.tmp.234529.84c632e447bb", - "Home.md.tmp.234529.043e8195cd1a", - "GDD/Inspiration.md", - "GDD/Inspiration.md.tmp.234529.bae427cc494d", - "GDD/Units.md", - "GDD/Units.md.tmp.234529.78abac70c7e3", - "GDD/Characters.md", - "GDD/Characters.md.tmp.234529.9a90cdbaf210", - "GDD/Ideas/Enemy Archetypes.md", - "GDD/Ideas/Enemy Archetypes.md.tmp.234529.be6735876c7b", - "GDD/Ideas/Unit Archetypes.md", - "GDD/Ideas/Unit Archetypes.md.tmp.234529.e5a9149ef6cc", - "GDD/Ideas/Characters with own Card Pools.md", - "GDD/Ideas/Characters with own Card Pools.md.tmp.234529.42ebd48e29e2", - "GDD/Ideas/Resources.md", - "GDD/Ideas/Resources.md.tmp.234529.a8ac0f0ee74e", - "GDD/Ideas/Card Types.md", - "GDD/Ideas/Card Types.md.tmp.234529.13bf9d1c7f6f", - "GDD/Ideas/Gameplay Loop.md", - "GDD/Discussions/Stages und Mapgröße.md", - "GDD/Discussions/Einheiten Karten oder Spawn Gebäude.md", - "GDD/Discussions/Grundlegende Gamedesign Fragen.md", - "GDD/Discussions/GDD Workflow.md", - "Open Questions.md", - "Decision Log.md", - "Engine/Build Order.md", - "Engine/Debug and Tooling.md", - "Engine/Audio.md", - "Engine/Input.md", - "Engine/Scripting.md" - ] -} \ No newline at end of file diff --git a/Docs/SiegeDeck/Decision Log.md b/Docs/SiegeDeck/Decision Log.md index 9046426..e403131 100644 --- a/Docs/SiegeDeck/Decision Log.md +++ b/Docs/SiegeDeck/Decision Log.md @@ -49,3 +49,10 @@ Newest at the bottom. Status is one of: **accepted**, **proposed**, **rejected** - `std::expected` for failures the caller really handles on the spot: loading assets, compiling scripts, parsing definitions. The caller falls back and keeps running, which hot reload depends on. - Exceptions (`std::runtime_error` for now) for failures with nothing to fall back to: SDL/window/GPU startup, broken invariants. Thrown from constructors and caught once in `main`, which logs and exits with 1. - **Consequences:** platform types are plain RAII classes: a constructor that throws, non-movable when they mean "exactly one" (`SdlContext`, `Window`), and no empty state. The STL throws anyway, so `-fno-exceptions` was never an option. Exceptions must not cross C callbacks (SDL, the script VM): script bindings need a catch boundary. + +## Catch2 v3 for unit tests +- **Date:** 2026-09-25 · **Status:** accepted +- **Context:** we needed a framework for `siege_tests`; the candidates were doctest and Catch2 v3. +- **Decision:** Catch2 v3, pinned to the nixpkgs version like every other dependency. Tests live in `Tests/`, mirroring `Source/`. +- **Reason:** doctest's main advantage (tests inline in production `.cpp` files) doesn't work well with `siege_engine` being a static library: the linker drops test-only object files unless the whole archive is force-linked. Catch2's generators suit the RNG and property tests we'll need, its floating-point matchers suit the clocks and simulation, it has built-in benchmarks, and it's actively maintained. Compile time is a non-issue at this size, with the PCH. +- **Consequences:** `catch_discover_tests` registers each `TEST_CASE` with ctest. Slow tests are tagged `[slow]`. diff --git a/Docs/SiegeDeck/Engine/Build Order.md b/Docs/SiegeDeck/Engine/Build Order.md index 1ad648a..d0537dd 100644 --- a/Docs/SiegeDeck/Engine/Build Order.md +++ b/Docs/SiegeDeck/Engine/Build Order.md @@ -6,7 +6,7 @@ tags: # Build Order -- [ ] **1. Skeleton:** split CMake into `siege_engine` and `siege_deck`; write `Application`, `FrameClock`, `SimClock` and the main loop. `--frames N` keeps working. See [[Main Loop and Time]]. +- [x] **1. Skeleton:** split CMake into `siege_engine` and `siege_deck`; write `Application`, `FrameClock`, `SimClock` and the main loop. `--frames N` keeps working. See [[Main Loop and Time]]. - [ ] **2. RenderDevice:** SDL_GPU device and swapchain, the GLSL → SPIR-V build step, clear the screen, ImGui on `imgui_impl_sdlgpu3`. See [[Rendering]]. - [ ] **3. Renderer2D:** sprite batch, text, debug overlay. - [ ] **4. SceneRenderer3D:** glTF loading, instanced static meshes, camera, a ground-plane picking ray to a tile. diff --git a/Docs/SiegeDeck/Engine/Engine Overview.md b/Docs/SiegeDeck/Engine/Engine Overview.md index 9d9ad4c..c763da8 100644 --- a/Docs/SiegeDeck/Engine/Engine Overview.md +++ b/Docs/SiegeDeck/Engine/Engine Overview.md @@ -30,7 +30,7 @@ flowchart TD ``` > [!important] Dependency rule -> `Engine/` must never include anything from `Game/`. The CMake target split enforces this. +> `Engine/` must never include anything from `Game/`. Both targets share `Source/` as their include root, so the compiler can't prevent it; the `check_engine_deps` build step (`cmake/CheckEngineDeps.cmake`) fails the build instead. ## Source layout @@ -61,7 +61,9 @@ Source/ |---|---|---| | `siege_engine` | static lib | SDL3 family, glm, EnTT, ImGui, spdlog, script runtime | | `siege_deck` | executable | `siege_engine` + `Game/` | -| `siege_tests` (later) | executable | engine + game logic, headless | +| `siege_tests` | executable | engine + game logic, headless; Catch2 v3 (`Tests/`) | + +`ctest --preset debug` runs every `siege_tests` case (each `TEST_CASE` is its own ctest entry) plus the `smoke` test: `siege_deck --frames 30` on SDL's offscreen video driver, so it needs no display. ## Principles diff --git a/Docs/SiegeDeck/Engine/Main Loop and Time.md b/Docs/SiegeDeck/Engine/Main Loop and Time.md index 838f2f9..04dfa39 100644 --- a/Docs/SiegeDeck/Engine/Main Loop and Time.md +++ b/Docs/SiegeDeck/Engine/Main Loop and Time.md @@ -17,9 +17,8 @@ while (running) { scenes.Update(frameClock.Dt()); // UI, tweens, card hand, camera: real time - simClock.Accumulate(frameClock.Dt() * simClock.Speed()); - int steps = 0; - while (simClock.ConsumeStep() && steps++ < kMaxStepsPerFrame) // spiral-of-death guard + simClock.Accumulate(frameClock.Dt()); // scaled by Speed(), backlog capped at kMaxStepsPerFrame steps + while (simClock.ConsumeStep()) scenes.FixedUpdate(kSimDt); // 1/60 s: movement, targeting, projectiles, damage renderer.BeginFrame(); @@ -42,7 +41,7 @@ The planning phase is simply `simClock.SetSpeed(0)`. Cards still animate and hov At 1×, 2× or 3× the loop runs **more fixed steps per frame, never bigger ones**. A 3× frame runs three 1/60 s steps, not one 1/20 s step, so fast projectiles can't skip past enemies at high speed. -`kMaxStepsPerFrame` caps the catch-up work after a stall (window drag, breakpoint). The simulation slows down rather than freezing the frame. +`kMaxStepsPerFrame` caps the catch-up work after a stall (window drag, breakpoint). `SimClock::Accumulate` clamps the backlog to that many steps and drops the rest, so the simulation slows down rather than freezing the frame, and the lost time never piles up across frames. ## Interpolation diff --git a/README.md b/README.md index 3c1d1db..f8a0d76 100644 --- a/README.md +++ b/README.md @@ -15,18 +15,20 @@ cmake --build --preset debug Without direnv, prefix commands with `nix develop --command`. -`siege_deck --frames N` renders N frames and exits, so the smoke test can run -unattended from a script or CI. +`siege_deck --frames N` renders N frames and exits. `ctest --preset debug` runs +the `siege_tests` unit tests, plus `--frames 30` headless (offscreen video +driver) as the `smoke` test, so it can run unattended from a script or CI. ## Layout | Path | What it is | |---------------------|------------------------------------------------------| | `flake.nix` | devShells: `default` (clang), `gcc` | -| `CMakeLists.txt` | dependency pins + the single executable target | +| `CMakeLists.txt` | dependency pins, engine lib, game exe, tests | | `cmake/Cpm.cmake` | CPM bootstrap — nixpkgs copy, else pinned download | | `cmake/ImGui.cmake` | defines `imgui::imgui` from either nixpkgs or source | -| `Source/` | `Common.h` (vocabulary types), `Pch.h`, `Main.cpp` | +| `Source/` | `Engine/` (`siege_engine`), `Game/`, `Main.cpp` | +| `Tests/` | `siege_tests` (Catch2), mirrors `Source/` | | `Assets/` | copied next to the executable after each build | ## How dependencies resolve diff --git a/Source/Engine/Application.cpp b/Source/Engine/Application.cpp new file mode 100644 index 0000000..c9bb0d2 --- /dev/null +++ b/Source/Engine/Application.cpp @@ -0,0 +1,124 @@ +// +// Created by darman on 9/24/26. +// + +#include "Application.h" + +#include +#include + +#include +#include +#include + +namespace SiegeDeck::Engine +{ + namespace + { + std::expected ParseUInt(std::string_view flag, std::string_view value) + { + uint64 result = 0; + auto [end, ec] = std::from_chars(value.data(), value.data() + value.size(), result); + if (ec != std::errc() || end != value.data() + value.size()) + return std::unexpected(std::format("{} expects a non-negative integer, got '{}'", flag, value)); + return result; + } + } + + std::expected AppConfig::FromArgs(int argc, char* argv[]) + { + AppConfig config; + for (int i = 1; i < argc; ++i) + { + std::string_view arg = argv[i]; + + if (arg == "--fullscreen") + { + config.Fullscreen = true; + continue; + } + + if (arg != "--frames" && arg != "--seed") + return std::unexpected(std::format("unknown argument '{}'", arg)); + if (i + 1 >= argc) + return std::unexpected(std::format("{} expects a value", arg)); + + auto value = ParseUInt(arg, argv[++i]); + if (!value) + return std::unexpected(value.error()); + + if (arg == "--frames") + config.MaxFrames = *value; + else + config.Seed = *value; + } + return config; + } + + Application::Application(AppConfig appConfig) + : config(std::move(appConfig)), + sdl(config.Title, config.Version), + window(sdl, + WindowDesc { + .Title = config.Title, + .Width = config.Width, + .Height = config.Height, + .Fullscreen = config.Fullscreen, + }), + context { + .App = *this, + .MainWindow = window, + .Frame = frameClock, + .Sim = simClock, + } + { + } + + Application::~Application() = default; + + int Application::Run() + { + while (running) + { + frameClock.Tick(); + HandleEvents(); + + // scenes.Update(frameClock.Dt()) goes here: UI, card hand, camera. + + simClock.Accumulate(frameClock.Dt()); + while (simClock.ConsumeStep()) + { + // scenes.FixedUpdate(simClock.StepDt()) goes here: movement, targeting, damage. + } + + DrawFrame(simClock.Alpha()); + + if (config.MaxFrames && frameClock.FrameCount() >= *config.MaxFrames) + Quit(); + } + + spdlog::info("Ran {} frames, {} sim steps in {:.2f} s", frameClock.FrameCount(), simClock.StepIndex(), + frameClock.Time()); + return 0; + } + + void Application::HandleEvents() + { + SDL_Event event; + while (SDL_PollEvent(&event)) + { + if (event.type == SDL_EVENT_QUIT) + Quit(); + } + } + + void Application::DrawFrame(double /*alpha*/) + { + // Wayland doesn't map a window until a frame is presented. Stand-in for RenderDevice's + // clear + present; a window surface can't be combined with SDL_GPU, so this goes in step 2. + SDL_Surface* surface = SDL_GetWindowSurface(window.Handle()); + SDL_FillSurfaceRect(surface, nullptr, SDL_MapSurfaceRGB(surface, 24, 26, 32)); + SDL_UpdateWindowSurface(window.Handle()); + SDL_Delay(16); // no vsync yet + } +} diff --git a/Source/Engine/Application.h b/Source/Engine/Application.h new file mode 100644 index 0000000..342f213 --- /dev/null +++ b/Source/Engine/Application.h @@ -0,0 +1,77 @@ +// +// Created by darman on 9/24/26. +// + +#pragma once + +#include "Engine/Platform/SdlContext.h" +#include "Engine/Platform/Window.h" +#include "Engine/Time/FrameClock.h" +#include "Engine/Time/SimClock.h" + +#include + +namespace SiegeDeck::Engine +{ + class Application; + + struct AppConfig + { + string Title = "Siege Deck"; + string Version = "0.1.0"; + int32 Width = 1280; + int32 Height = 720; + bool Fullscreen = false; + bool Vsync = false; + uint64 Seed = 0; + Optional MaxFrames = None; + + // Bad arguments are reported, not thrown: main prints them and exits with a usage error. + static std::expected FromArgs(int argc, char* argv[]); + }; + + struct EngineContext + { + Application& App; + Window& MainWindow; + const FrameClock& Frame; // real time: UI, card hand, camera + SimClock& Sim; // sim time: SetSpeed(0) is the planning phase + }; + + class Application + { + public: + explicit Application(AppConfig appConfig); + ~Application(); + + Application(const Application&) = delete; + Application& operator=(const Application&) = delete; + Application(Application&&) = delete; + Application& operator=(Application&&) = delete; + + int Run(); + void Quit() { running = false; }; + + EngineContext& GetContext() { return context; } + + private: + void HandleEvents(); + void DrawFrame(double alpha); + + static constexpr double kSimDt = 1.0 / 60.0; + static constexpr int32 kMaxStepsPerFrame = 8; + + AppConfig config; + + // Members are constructed in declaration order and destroyed in reverse, + // so anything that depends on another subsystem is declared after it. + SdlContext sdl; + Window window; + FrameClock frameClock; + SimClock simClock { kSimDt, kMaxStepsPerFrame }; + + EngineContext context; + bool running = true; + }; + +} diff --git a/Source/Engine/Platform/SdlContext.cpp b/Source/Engine/Platform/SdlContext.cpp new file mode 100644 index 0000000..b6e1a53 --- /dev/null +++ b/Source/Engine/Platform/SdlContext.cpp @@ -0,0 +1,32 @@ +// +// Created by darman on 9/24/26. +// + +#include "SdlContext.h" + +#include +#include + +namespace SiegeDeck::Engine +{ + + SdlContext::SdlContext(const string& appName, const string& appVersion) + { + // Must precede SDL_Init: some platforms read it during init (audio stream names, Wayland app id). + SDL_SetAppMetadata(appName.c_str(), appVersion.c_str(), nullptr); + + // If this throws, the destructor doesn't run, and SDL_Init has cleaned up after itself. + if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) + throw std::runtime_error(std::format("SDL_Init failed: {}", SDL_GetError())); + + int version = SDL_GetVersion(); + spdlog::info("SDL {}.{}.{} ({} video)", SDL_VERSIONNUM_MAJOR(version), SDL_VERSIONNUM_MINOR(version), + SDL_VERSIONNUM_MICRO(version), SDL_GetCurrentVideoDriver()); + } + + SdlContext::~SdlContext() + { + SDL_Quit(); + } + +} diff --git a/Source/Engine/Platform/SdlContext.h b/Source/Engine/Platform/SdlContext.h new file mode 100644 index 0000000..b02a047 --- /dev/null +++ b/Source/Engine/Platform/SdlContext.h @@ -0,0 +1,31 @@ +// +// Created by darman on 9/24/26. +// + +#pragma once + +namespace SiegeDeck::Engine +{ + + // Owns the process-wide SDL_Init / SDL_Quit pair. Anything that talks to SDL + // must be declared after this in Application, so it is torn down first. + // + // Only core subsystems are initialized here. Audio belongs to AudioSystem, which + // brings it up through SDL_mixer, so a machine without an audio device can still + // run the headless --frames smoke test. + // + // Exactly one per process, and never relocated: not copyable, not movable. + class SdlContext + { + public: + // Throws std::runtime_error if SDL can't initialize (fatal: nothing to fall back to). + SdlContext(const string& appName, const string& appVersion); + ~SdlContext(); + + SdlContext(const SdlContext&) = delete; + SdlContext& operator=(const SdlContext&) = delete; + SdlContext(SdlContext&&) = delete; + SdlContext& operator=(SdlContext&&) = delete; + }; + +} diff --git a/Source/Engine/Platform/Window.cpp b/Source/Engine/Platform/Window.cpp new file mode 100644 index 0000000..22c1306 --- /dev/null +++ b/Source/Engine/Platform/Window.cpp @@ -0,0 +1,61 @@ +// +// Created by darman on 9/24/26. +// + +#include "Window.h" + +#include +#include + +namespace SiegeDeck::Engine +{ + + Window::Window(const SdlContext& /*sdl*/, const WindowDesc& desc) + { + // No SDL_WINDOW_VULKAN etc.: SDL_ClaimWindowForGPUDevice picks the backend later. + SDL_WindowFlags flags = SDL_WINDOW_HIGH_PIXEL_DENSITY; + if (desc.Resizable) + flags |= SDL_WINDOW_RESIZABLE; + if (desc.Fullscreen) + flags |= SDL_WINDOW_FULLSCREEN; + + handle.reset(SDL_CreateWindow(desc.Title.c_str(), desc.Width, desc.Height, flags)); + if (!handle) + throw std::runtime_error(std::format("SDL_CreateWindow failed: {}", SDL_GetError())); + + glm::ivec2 pixels = PixelSize(); + spdlog::info("Window {}x{} ({}x{} px, scale {:.2f})", desc.Width, desc.Height, pixels.x, pixels.y, + DisplayScale()); + } + + SDL_WindowID Window::Id() const + { + return SDL_GetWindowID(handle.get()); + } + + glm::ivec2 Window::Size() const + { + glm::ivec2 size { 0 }; + SDL_GetWindowSize(handle.get(), &size.x, &size.y); + return size; + } + + glm::ivec2 Window::PixelSize() const + { + glm::ivec2 size { 0 }; + SDL_GetWindowSizeInPixels(handle.get(), &size.x, &size.y); + return size; + } + + float Window::DisplayScale() const + { + float scale = SDL_GetWindowDisplayScale(handle.get()); + return scale > 0.0f ? scale : 1.0f; // 0 means SDL couldn't tell + } + + void Window::SetTitle(const string& title) + { + SDL_SetWindowTitle(handle.get(), title.c_str()); + } + +} diff --git a/Source/Engine/Platform/Window.h b/Source/Engine/Platform/Window.h new file mode 100644 index 0000000..477bb25 --- /dev/null +++ b/Source/Engine/Platform/Window.h @@ -0,0 +1,59 @@ +// +// Created by darman on 9/24/26. +// + +#pragma once + +#include +#include + +namespace SiegeDeck::Engine +{ + + class SdlContext; + + struct WindowDesc + { + string Title { "Siege Deck" }; + int32 Width { 1600 }; // logical size; the backbuffer is larger on high-DPI displays + int32 Height { 900 }; + bool Resizable { true }; + bool Fullscreen { false }; // borderless desktop fullscreen, not an exclusive mode change + }; + + // Not movable: a Window that exists always has a live SDL_Window, and the render + // device and ImGui backend will hold on to it by reference. + class Window + { + public: + // Takes the SdlContext only as proof that SDL is initialized. + // Throws std::runtime_error if the window can't be created. + Window(const SdlContext& sdl, const WindowDesc& desc); + + Window(const Window&) = delete; + Window& operator=(const Window&) = delete; + Window(Window&&) = delete; + Window& operator=(Window&&) = delete; + + [[nodiscard]] SDL_Window* Handle() const { return handle.get(); } + [[nodiscard]] SDL_WindowID Id() const; + + // Logical size, for UI layout and mouse coordinates. + [[nodiscard]] glm::ivec2 Size() const; + // Backbuffer size, for the swapchain and viewport. + [[nodiscard]] glm::ivec2 PixelSize() const; + // Content scale of the current display (1.0 = 96 DPI), for sizing UI and fonts. + [[nodiscard]] float DisplayScale() const; + + void SetTitle(const string& title); + + private: + struct Destroy + { + void operator()(SDL_Window* window) const { SDL_DestroyWindow(window); } + }; + + UniqueRef handle; + }; + +} diff --git a/Source/Engine/Time/FrameClock.cpp b/Source/Engine/Time/FrameClock.cpp new file mode 100644 index 0000000..cb16adc --- /dev/null +++ b/Source/Engine/Time/FrameClock.cpp @@ -0,0 +1,30 @@ +// +// Created by darman on 9/24/26. +// + +#include "FrameClock.h" + +#include + +#include + +namespace SiegeDeck::Engine +{ + + FrameClock::FrameClock() : frequency(SDL_GetPerformanceFrequency()), lastCounter(SDL_GetPerformanceCounter()) + { + } + + void FrameClock::Tick() + { + uint64 now = SDL_GetPerformanceCounter(); + // The first frame measures from construction (startup time), which would read as one long hitch. + double elapsed = frameCount == 0 ? 0.0 : static_cast(now - lastCounter) / frequency; + lastCounter = now; + + dt = std::min(elapsed, kMaxDt); + time += dt; + ++frameCount; + } + +} diff --git a/Source/Engine/Time/FrameClock.h b/Source/Engine/Time/FrameClock.h new file mode 100644 index 0000000..b9fa914 --- /dev/null +++ b/Source/Engine/Time/FrameClock.h @@ -0,0 +1,40 @@ +// +// Created by darman on 9/24/26. +// + +#pragma once + +namespace SiegeDeck::Engine +{ + + // Real (wall-clock) time between frames. Drives UI, the card hand, menus, the camera + // and UI tweens: things that keep moving while the simulation is paused. + // Not pausable and not scaled by game speed; see SimClock for that. + class FrameClock + { + public: + // A frame longer than this (window drag, breakpoint, loading hitch) counts as this long, + // so nothing driven by Dt() jumps across the screen afterwards. + static constexpr double kMaxDt = 0.25; + + FrameClock(); + + // Call once at the start of every frame. The first call yields Dt() == 0. + void Tick(); + + // Seconds since the previous Tick(), clamped to kMaxDt. + [[nodiscard]] double Dt() const { return dt; } + // Sum of all clamped Dt()s: time the game has seen, not wall-clock uptime. + [[nodiscard]] double Time() const { return time; } + [[nodiscard]] uint64 FrameCount() const { return frameCount; } + + private: + uint64 frequency; + uint64 lastCounter; + + double dt = 0.0; + double time = 0.0; + uint64 frameCount = 0; + }; + +} diff --git a/Source/Engine/Time/SimClock.cpp b/Source/Engine/Time/SimClock.cpp new file mode 100644 index 0000000..52ab2f3 --- /dev/null +++ b/Source/Engine/Time/SimClock.cpp @@ -0,0 +1,41 @@ +// +// Created by darman on 9/24/26. +// + +#include "SimClock.h" + +#include + +namespace SiegeDeck::Engine +{ + + SimClock::SimClock(double stepDt, int32 maxStepsPerFrame) + : stepDt(stepDt), maxBacklog(stepDt * maxStepsPerFrame) + { + if (stepDt <= 0.0 || maxStepsPerFrame < 1) + throw std::invalid_argument("SimClock needs a positive step and at least one step per frame"); + } + + void SimClock::Accumulate(double realDt) + { + // Capping here, not in the step loop, keeps the caller's loop a plain while. It also + // means a stall loses its excess time for good instead of piling up across frames. + accumulator = std::min(accumulator + realDt * speed, maxBacklog); + } + + bool SimClock::ConsumeStep() + { + if (accumulator < stepDt) + return false; + accumulator -= stepDt; + ++stepIndex; + return true; + } + + void SimClock::SetSpeed(double newSpeed) + { + // The accumulator is kept on pause, so Alpha() holds still and paused entities don't snap. + speed = std::max(newSpeed, 0.0); + } + +} diff --git a/Source/Engine/Time/SimClock.h b/Source/Engine/Time/SimClock.h new file mode 100644 index 0000000..64c2f13 --- /dev/null +++ b/Source/Engine/Time/SimClock.h @@ -0,0 +1,54 @@ +// +// Created by darman on 9/24/26. +// + +#pragma once + +namespace SiegeDeck::Engine +{ + + // Fixed-timestep simulation time. Real time is fed in each frame, scaled by Speed(), + // and handed out again as whole steps of StepDt(): + // + // sim.Accumulate(frame.Dt()); + // while (sim.ConsumeStep()) + // FixedUpdate(sim.StepDt()); + // Render(sim.Alpha()); + // + // Speed 0 is the planning phase. 2x and 3x run more steps per frame, never bigger ones, + // so fast projectiles can't skip past enemies at high speed. + class SimClock + { + public: + // maxStepsPerFrame caps catch-up work after a stall: past it, the backlog is dropped + // and the simulation slows down instead of freezing the frame (the spiral of death). + SimClock(double stepDt, int32 maxStepsPerFrame); + + void Accumulate(double realDt); + // True if a whole step is available; consumes it and advances Time() and StepIndex(). + bool ConsumeStep(); + + // 0 pauses. Negative values are treated as 0. + void SetSpeed(double newSpeed); + [[nodiscard]] double Speed() const { return speed; } + [[nodiscard]] bool Paused() const { return speed == 0.0; } + + [[nodiscard]] double StepDt() const { return stepDt; } + // How far between the previous and the current step the renderer is, in [0, 1). + // Blend PrevTransform -> Transform3D by this. + [[nodiscard]] double Alpha() const { return accumulator / stepDt; } + + // Simulated seconds and steps since construction. Stops advancing while paused. + [[nodiscard]] double Time() const { return static_cast(stepIndex) * stepDt; } + [[nodiscard]] uint64 StepIndex() const { return stepIndex; } + + private: + double stepDt; + double maxBacklog; + + double speed = 1.0; + double accumulator = 0.0; + uint64 stepIndex = 0; + }; + +} diff --git a/Source/Main.cpp b/Source/Main.cpp index 7022895..e42daa3 100644 --- a/Source/Main.cpp +++ b/Source/Main.cpp @@ -1,6 +1,29 @@ -#include +#include "Engine/Application.h" + +#include + +using namespace SiegeDeck; int main(const int argc, char** argv) { - std::cout << "Hello World!" << std::endl; + auto config = Engine::AppConfig::FromArgs(argc, argv); + if (!config) + { + spdlog::error("{}", config.error()); + spdlog::info("usage: {} [--frames N] [--seed N] [--fullscreen]", argv[0]); + return 2; + } + + // Fatal errors (startup, broken invariants) are exceptions and end up here. Recoverable + // ones (assets, scripts) are std::expected and are handled where they happen. + try + { + Engine::Application app { std::move(*config) }; + return app.Run(); + } + catch (const std::exception& e) + { + spdlog::critical("{}", e.what()); + return 1; + } } diff --git a/Tests/Engine/AppConfigTests.cpp b/Tests/Engine/AppConfigTests.cpp new file mode 100644 index 0000000..fc6ea63 --- /dev/null +++ b/Tests/Engine/AppConfigTests.cpp @@ -0,0 +1,66 @@ +#include "Engine/Application.h" + +#include + +using namespace SiegeDeck::Engine; + +namespace +{ + // FromArgs takes a mutable argv, like main's; build one from string literals. + std::expected Parse(std::initializer_list args) + { + Vector storage { "siege_deck" }; + storage.insert(storage.end(), args.begin(), args.end()); + + Vector argv; + for (string& arg : storage) + argv.push_back(arg.data()); + return AppConfig::FromArgs(static_cast(argv.size()), argv.data()); + } +} + +TEST_CASE("AppConfig without arguments keeps the defaults", "[config]") +{ + auto config = Parse({}); + REQUIRE(config); + + CHECK_FALSE(config->MaxFrames); + CHECK(config->Seed == 0); + CHECK_FALSE(config->Fullscreen); +} + +TEST_CASE("AppConfig reads every flag", "[config]") +{ + auto config = Parse({ "--frames", "30", "--seed", "42", "--fullscreen" }); + REQUIRE(config); + + CHECK(config->MaxFrames == 30u); + CHECK(config->Seed == 42); + CHECK(config->Fullscreen); +} + +TEST_CASE("AppConfig reports bad arguments instead of guessing", "[config]") +{ + SECTION("unknown flag") + { + auto config = Parse({ "--bogus" }); + REQUIRE_FALSE(config); + CHECK(config.error().find("--bogus") != string::npos); + } + SECTION("missing value") + { + CHECK_FALSE(Parse({ "--frames" })); + } + SECTION("not a number") + { + CHECK_FALSE(Parse({ "--frames", "abc" })); + } + SECTION("trailing garbage") + { + CHECK_FALSE(Parse({ "--seed", "12x" })); + } + SECTION("negative") + { + CHECK_FALSE(Parse({ "--frames", "-1" })); + } +} diff --git a/Tests/Engine/Time/FrameClockTests.cpp b/Tests/Engine/Time/FrameClockTests.cpp new file mode 100644 index 0000000..e822e42 --- /dev/null +++ b/Tests/Engine/Time/FrameClockTests.cpp @@ -0,0 +1,41 @@ +#include "Engine/Time/FrameClock.h" + +#include +#include + +using namespace SiegeDeck::Engine; + +TEST_CASE("FrameClock's first tick is zero, not the time since construction", "[time]") +{ + FrameClock clock; + SDL_Delay(20); + clock.Tick(); + + CHECK(clock.Dt() == 0.0); + CHECK(clock.Time() == 0.0); + CHECK(clock.FrameCount() == 1); +} + +TEST_CASE("FrameClock measures real time between ticks", "[time]") +{ + FrameClock clock; + clock.Tick(); + SDL_Delay(20); + clock.Tick(); + + // Loose bounds: the scheduler can oversleep, never undersleep. + CHECK(clock.Dt() >= 0.019); + CHECK(clock.Dt() <= FrameClock::kMaxDt); + CHECK(clock.Time() == clock.Dt()); + CHECK(clock.FrameCount() == 2); +} + +TEST_CASE("FrameClock clamps a long frame", "[time][slow]") +{ + FrameClock clock; + clock.Tick(); + SDL_Delay(300); + clock.Tick(); + + CHECK(clock.Dt() == FrameClock::kMaxDt); +} diff --git a/Tests/Engine/Time/SimClockTests.cpp b/Tests/Engine/Time/SimClockTests.cpp new file mode 100644 index 0000000..38c2843 --- /dev/null +++ b/Tests/Engine/Time/SimClockTests.cpp @@ -0,0 +1,133 @@ +#include "Engine/Time/SimClock.h" + +#include +#include +#include +#include +#include + +using namespace SiegeDeck::Engine; +using Catch::Matchers::WithinAbs; + +namespace +{ + constexpr double kStep = 1.0 / 60.0; + + // One frame of the main loop: feed real time in, count the steps that come out. + int32 RunFrame(SimClock& clock, double realDt) + { + clock.Accumulate(realDt); + int32 steps = 0; + while (clock.ConsumeStep()) + ++steps; + return steps; + } + + int32 RunFrames(SimClock& clock, double realDt, int32 frames) + { + int32 steps = 0; + for (int32 i = 0; i < frames; ++i) + steps += RunFrame(clock, realDt); + return steps; + } +} + +TEST_CASE("SimClock runs 60 steps per simulated second at any frame rate", "[time]") +{ + double fps = GENERATE(30.0, 60.0, 75.0, 144.0, 240.0); + CAPTURE(fps); + + SimClock clock { kStep, 8 }; + int32 steps = RunFrames(clock, 1.0 / fps, static_cast(fps)); + + // Rounding can leave the last step a hair short; it runs on the next frame instead. + CHECK(steps >= 59); + CHECK(steps <= 60); +} + +TEST_CASE("SimClock speed runs more steps, never bigger ones", "[time]") +{ + double speed = GENERATE(2.0, 3.0); + CAPTURE(speed); + + SimClock clock { kStep, 8 }; + clock.SetSpeed(speed); + int32 steps = RunFrames(clock, kStep, 60); + + CHECK(steps >= static_cast(60 * speed) - 1); + CHECK(steps <= static_cast(60 * speed)); + CHECK(clock.StepDt() == kStep); +} + +TEST_CASE("SimClock speed 0 pauses without disturbing interpolation", "[time]") +{ + SimClock clock { kStep, 8 }; + RunFrame(clock, kStep * 0.5); + double alpha = clock.Alpha(); + uint64 stepsBefore = clock.StepIndex(); + + clock.SetSpeed(0.0); + REQUIRE(clock.Paused()); + + CHECK(RunFrames(clock, kStep, 120) == 0); + CHECK(clock.StepIndex() == stepsBefore); + CHECK(clock.Alpha() == alpha); // nothing snaps while paused + + SECTION("resuming picks up where it left off") + { + clock.SetSpeed(1.0); + CHECK(RunFrame(clock, kStep * 0.5) == 1); + CHECK_THAT(clock.Alpha(), WithinAbs(0.0, 1e-9)); + } +} + +TEST_CASE("SimClock treats negative speed as paused", "[time]") +{ + SimClock clock { kStep, 8 }; + clock.SetSpeed(-2.0); + + CHECK(clock.Speed() == 0.0); + CHECK(RunFrame(clock, 1.0) == 0); +} + +TEST_CASE("SimClock caps catch-up work after a stall and drops the backlog", "[time]") +{ + SimClock clock { kStep, 8 }; + + int32 stalled = RunFrame(clock, 0.25); // 15 steps' worth of time + CHECK(stalled >= 7); + CHECK(stalled <= 8); + + // The dropped time is gone for good: the next normal frame is a normal frame. + CHECK(RunFrame(clock, kStep) == 1); +} + +TEST_CASE("SimClock alpha stays in [0, 1)", "[time]") +{ + double dt = GENERATE(take(50, random(0.0, 0.3))); + CAPTURE(dt); + + SimClock clock { kStep, 8 }; + for (int32 i = 0; i < 20; ++i) + { + RunFrame(clock, dt); + CHECK(clock.Alpha() >= 0.0); + CHECK(clock.Alpha() < 1.0); + } +} + +TEST_CASE("SimClock time is steps times the step length", "[time]") +{ + SimClock clock { kStep, 8 }; + RunFrames(clock, kStep, 90); + + CHECK(clock.StepIndex() == 90); + CHECK_THAT(clock.Time(), WithinAbs(1.5, 1e-12)); +} + +TEST_CASE("SimClock rejects a broken configuration", "[time]") +{ + CHECK_THROWS_AS((SimClock { 0.0, 8 }), std::invalid_argument); + CHECK_THROWS_AS((SimClock { -kStep, 8 }), std::invalid_argument); + CHECK_THROWS_AS((SimClock { kStep, 0 }), std::invalid_argument); +} diff --git a/cmake/CheckEngineDeps.cmake b/cmake/CheckEngineDeps.cmake new file mode 100644 index 0000000..02803e4 --- /dev/null +++ b/cmake/CheckEngineDeps.cmake @@ -0,0 +1,22 @@ +# Fails the build if any file under Source/Engine includes something from Source/Game. +# +# cmake -DENGINE_DIR= -P CheckEngineDeps.cmake +# +# Engine and game share Source/ as their include root, so the compiler would +# happily resolve "Game/..." from engine code. This keeps the dependency one-way. + +file(GLOB_RECURSE engine_files "${ENGINE_DIR}/*.h" "${ENGINE_DIR}/*.hpp" "${ENGINE_DIR}/*.cpp") + +set(violations "") +foreach (file IN LISTS engine_files) + file(STRINGS "${file}" lines REGEX "^[ \t]*#[ \t]*include[ \t]*[<\"](\\.\\./)*Game/") + foreach (line IN LISTS lines) + file(RELATIVE_PATH rel "${ENGINE_DIR}/.." "${file}") + string(STRIP "${line}" line) + string(APPEND violations "\n ${rel}: ${line}") + endforeach () +endforeach () + +if (violations) + message(FATAL_ERROR "Engine code must not include Game code:${violations}") +endif () diff --git a/flake.nix b/flake.nix index 03244e7..f1daba7 100644 --- a/flake.nix +++ b/flake.nix @@ -43,6 +43,9 @@ glm entt boost + + # siege_tests only. + catch2_3 ]) ++ [ imgui ]; tools = with pkgs; [