--- last_mapped_commit: bdca29d3aa31face0c0023537ff98783716dbc45 last_mapped_at: 2026-11-12 --- # Architecture **Analysis Date:** 2026-11-12 ## System Overview ```text Read-only ../Original assets -> tools/extractors/prepare.py -> artifacts/extracted manifests/buffers/WAV -> src/GamePort/Assets + original GAM/TSK/ASE/PNG readers -> Program.Run scene composition Game simulation/scripts -> Application visuals/HUD -> VulkanRenderer Game events -> SceneAudio -> SdlAudio -> SDL3 Program.Main -> persistent RenderSession -> SDL window + Vulkan instance/device ``` The desktop application is a single shared Linux/Windows C# executable (`GamePort.csproj`). `src/GamePort/Program.cs` composes concrete systems and owns scheduling. There is no runtime server, database, dependency-injection container, or external game engine. ## Component Responsibilities | Component | Responsibility | File | |-----------|----------------|------| | Application entry | CLI, resource composition, input dispatch, fixed ticks, scene continuation | `src/GamePort/Program.cs` | | Presentation session | Application lifetime window and renderer; replace scene resources | `src/GamePort/Application/RenderSession.cs` | | Player simulation | Physics, input/apply order, facing, jump/effects, player camera | `src/GamePort/Game/LabSimulation.cs` | | Script bridge | Raw control owner, authored transforms, gadget cleanup, vehicle/passenger phases | `src/GamePort/Game/PlayerSceneBinding.cs` | | Scene director | GAM actors, CAM/MCA/AI chains, cutscene camera, control and issue reporting | `src/GamePort/Game/SceneDirector.cs` | | Progression | Contacts, inventory, tasks, transitions and save snapshots | `src/GamePort/Game/SceneInteractions.cs`, `src/GamePort/Game/TaskStates.cs` | | Resource readers | Original and prepared data decoding | `src/GamePort/Assets/` | | Presentation adapters | Mutable geometry, morphs, sprites, UI and camera projection | `src/GamePort/Application/` | | GPU backend | Vulkan resources, rendering, resizing, readback and disposal | `src/GamePort/Rendering/Vulkan/VulkanRenderer.cs` | | Audio | Independent music/speech/effects and SDL WAV stream ownership | `src/GamePort/Audio/SceneAudio.cs`, `src/GamePort/Audio/SdlAudio.cs` | ## Pattern Overview **Overall:** Explicit application composition with scene-local state, event-connected gameplay systems and a persistent native presentation owner. **Key Characteristics:** - Keep scheduling visible in `src/GamePort/Program.cs`; source ordering is behavior, not interchangeable service invocation order. - Keep recovered arithmetic in focused `src/GamePort/Game/` modules and presentation in `src/GamePort/Application/`. - Preserve the distinction between isolated recovered components and admitted live scene adapters (`src/GamePort/Game/OriginalPairCollision.cs`, `src/GamePort/Game/OriginalNormalContacts.cs`). - Use local original-derived assets; Python preparation is a development/package stage (`tools/extractors/prepare.py`, `scripts/package.sh`). ## Layers **Application composition and presentation:** - Purpose: Connect input, simulation, scripts, visuals, audio and GPU submission. - Location: `src/GamePort/Program.cs`, `src/GamePort/Application/`. - Contains: `RenderSession`, debug interfaces, `SceneHud`, visual adapters and smoke fixtures. - Depends on: Game, Assets, Audio, Platform and Rendering namespaces. - Used by: Executable entry and managed regression projects. **Game state and recovered algorithms:** - Purpose: Own simulation and script/progression semantics. - Location: `src/GamePort/Game/`. - Contains: `LabSimulation`, `SceneDirector`, inventory/tasks, gadgets, vehicles, collision and numeric kernels. - Depends on: `System.Numerics` and decoded asset types in `src/GamePort/Assets/`. - Used by: Application orchestration and focused `tests/GamePort.*Tests/` executables. **Asset decoding:** - Purpose: Convert bounded original/prepared files into typed CPU resources. - Location: `src/GamePort/Assets/`. - Contains: `GamLevel`, `OriginalSave`, `Mesh`, `MorphAnimation`, `PngImage`, resource identities and path resolution. - Depends on: Filesystem, binary primitives, JSON and numerics; no renderer ownership. - Used by: Game systems and application/renderer initialization. **Native platform, GPU and audio:** - Purpose: Own unmanaged interoperability and device resources. - Location: `src/GamePort/Platform/Sdl.cs`, `src/GamePort/Rendering/Vulkan/VulkanRenderer.cs`, `src/GamePort/Audio/`. - Contains: SDL3 imports, Vulkan offscreen/present paths, WAV streams and scene audio orchestration. - Depends on: SDL3, Silk.NET.Vulkan, shaders and decoded meshes/textures. - Used by: `src/GamePort/Application/RenderSession.cs` and `src/GamePort/Program.cs`. **Offline evidence and preparation:** - Purpose: Inspect source evidence and create reusable resources without modifying originals. - Location: `tools/binary/`, `tools/extractors/`, `tools/levels/`, `tools/recon/`. - Contains: Python parsers, extraction manifests, C component probes and observation tools. - Depends on: Local original files and explicit analysis tooling; not part of the native runtime dependency graph. - Used by: Tests, local preparation, research and `scripts/package.sh`. ## Data Flow ### Primary Request Path 1. `Program.Main` creates persistent presentation, energy, grappler memory and diagnostics, then invokes the scene runner (`src/GamePort/Program.cs:14`). 2. `Run` resolves originals, loads prepared geometry and original GAM/save data, constructs scene systems and binds the player (`src/GamePort/Program.cs:46`). 3. SDL polling updates held input; unpaused gameplay advances through a 60 Hz accumulator, while bounded fixtures use explicit steps (`src/GamePort/Program.cs:1057`, `src/GamePort/Game/FixedStepClock.cs`). 4. Each tick advances gadget/projectile bodies, player/vehicle binding, timers/targets, interactions/mechanisms, patrols, director and animation state (`src/GamePort/Program.cs:1271`). 5. Application visuals mutate mesh vertices/draw properties, update HUD and select gameplay/script/orbit camera; renderer uploads and renders (`src/GamePort/Program.cs:1371`, `src/GamePort/Rendering/Vulkan/VulkanRenderer.cs`). ### Player and cutscene phase ordering 1. `LabSimulation.Step` runs body physics before registry-style callbacks (`src/GamePort/Game/LabSimulation.cs:265`). 2. Fresh direct-scene input runs before ceiling/floor/facing and player apply. Retained input runs after player/effect updates. `Program` sets `InputAfterPlayerUpdate` for story entry or carried saves (`src/GamePort/Program.cs:361`). 3. Lack of Jimmy control gates input/player apply, not body, facing or owned effect clocks. `PlayerSceneBinding` receives director preparation/transform events and preserves vehicle control ordering (`src/GamePort/Game/PlayerSceneBinding.cs`). 4. Script preparation separates stop-motion, orientation flattening, gadget release and authored transforms; do not replace these with a generic player reset (`src/GamePort/Game/PlayerSceneBinding.cs`, `src/GamePort/Game/SceneDirector.cs`). ### Scene loading and retained state 1. Contact or practice logic requests a `LevelTransition`; application stages a departure/RETURN root through `RuntimeCheckpoint` (`src/GamePort/Program.cs:339`, `src/GamePort/Game/RuntimeCheckpoint.cs`). 2. Scene runner returns a continuation with destination arguments, original-format save snapshot and optional bounded `PlayerLevelState` (`src/GamePort/Program.cs`, `src/GamePort/Game/PlayerLevelState.cs`). 3. `Main` invokes a new scene run. GAM actors, bindings, visual resources and scene audio are rebuilt; `RenderSession.LoadScene` calls `ReplaceScene` on the existing renderer (`src/GamePort/Application/RenderSession.cs`). 4. Vulkan scene replacement waits for device idle and replaces scene GPU resources while retaining presentation identity (`src/GamePort/Rendering/Vulkan/VulkanRenderer.cs:101`). ### Source-to-extracted-assets pipeline 1. `tools/recon/inventory.py` provides original manifest verification against `docs/original-manifest.json`. 2. `tools/extractors/prepare.py` reads OMT/GAM/ASE/PNG and dispatches scene, entity, model, UI, effect and gadget resource extraction. `tools/extractors/omt.py` and `tools/levels/gam.py` retain format-specific parsing. 3. Generated `artifacts/extracted/` contains scene JSON, textures, animation buffers/manifests, entity/model resources, WAV and a scene catalog. Missing scene archives are reported rather than substituted (`tools/extractors/prepare.py`). 4. Runtime readers load prepared resources and original GAM/TSK/base assets; `scripts/package.sh` copies those into local package `scenes/` and `assets/` trees. Runtime packages do not need Python. **State Management:** - Application session: presentation, diagnostics preference, `PlayerEnergy` and `GrapplerMemory` are created outside the scene loop (`src/GamePort/Program.cs`). - Scene: simulation, actors, tasks/inventory, mechanisms, animation meshes, audio and bindings are concrete objects recreated by `Run` (`src/GamePort/Program.cs`). - Retained route scalars: `PlayerLevelState` supports LV1B/VR04/LEV1 with selected gadget -1 or 3; this is in-memory state, not an extension of TSK (`src/GamePort/Game/PlayerLevelState.cs`). - Original save persistence: `OriginalSave` encodes TSK tasks/items/checkpoint state; save output uses a temporary file and move outside original assets (`src/GamePort/Assets/OriginalSave.cs`, `src/GamePort/Program.cs`). ## Key Abstractions **Mesh and MeshDraw:** - Purpose: CPU geometry, source collision polygons, textures and per-range material/presentation state. - Examples: `src/GamePort/Assets/Mesh.cs`, `src/GamePort/Application/SceneActorVisuals.cs`. - Pattern: Arrays plus mutable draw state; visual adapters append/update shared scene data rather than owning Vulkan objects. **GamEntity and DirectorActor:** - Purpose: Preserve serialized properties separately from live authored actor state. - Examples: `src/GamePort/Assets/GamLevel.cs`, `src/GamePort/Game/SceneDirector.cs`. - Pattern: Bounded typed decoding followed by scene-specific actor/script execution; unknown behavior produces issues. **Original collision components and live adapters:** - Purpose: Express bounded source contracts without assuming a complete recovered physical registry. - Examples: `src/GamePort/Game/OriginalBodyPhysics.cs`, `src/GamePort/Game/OriginalStaticCollision.cs`, `src/GamePort/Game/OriginalPairCollision.cs`, `src/GamePort/Game/OriginalNormalContacts.cs`. - Pattern: Caller-owned state/accessors and explicit profiles. Pair callbacks and generic normal responses do not establish scene membership or Jimmy's override policy. ## Entry Points **Native executable:** - Location: `src/GamePort/Program.cs`. - Triggers: `dotnet run`, local published executable or package launchers. - Responsibilities: Scene/model preview, playable story, asset verification, audio/GPU/SDL fixtures and explicit CLI validation. **Offline preparation:** - Location: `tools/extractors/prepare.py`. - Triggers: Local developer invocation and `scripts/package.sh`. - Responsibilities: Original-derived resource production outside the source installation. **Regression and build entry points:** - Location: `scripts/test.sh`, `scripts/build-linux.sh`, `scripts/build-windows.sh`, `tests/GamePort.*Tests/Program.cs`, `tests/test_*.py`. - Triggers: Local scripts or direct test projects. - Responsibilities: Bounded source/algorithm/parser checks, GPU fixtures and native packaging inputs. A cross-publish is not native Windows runtime evidence. ## Architectural Constraints - **Threading:** Gameplay and rendering are explicitly scheduled on the application loop; Vulkan submission/presentation waits synchronously (`src/GamePort/Program.cs`, `src/GamePort/Rendering/Vulkan/VulkanRenderer.cs`). SDL manages audio stream transport (`src/GamePort/Audio/SdlAudio.cs`). - **Global state:** Native SDL state is process-level; managed session state is explicitly passed. Keep native resource disposal scoped through `RenderSession` and `SdlAudio` (`src/GamePort/Application/RenderSession.cs`, `src/GamePort/Audio/SdlAudio.cs`). - **Circular imports:** No project-layer circular project-reference chain is detected: production source is compiled into one executable (`GamePort.csproj`). Events intentionally connect director/player/inventory lifetimes (`src/GamePort/Game/PlayerSceneBinding.cs`). - **Live solver boundaries:** Lab/outside retain capsule compatibility. Original static body is admitted by explicit scene gates including VR01/VR02/VR04/VR07/VR08; VR04 is a bounded source-body scene, not a full dynamic registry (`src/GamePort/Program.cs:361`, `src/GamePort/Game/LabSimulation.cs`). - **Recovery gates:** `OriginalPairCollision` and `OriginalNormalContacts` are isolated components, not live admission. Physical activation/helper lifetime, actual derived callbacks and shared reclip remain separate obligations (`src/GamePort/Game/OriginalPairCollision.cs`, `src/GamePort/Game/OriginalNormalContacts.cs`, `docs/checkpoint/next-work-plan.md`). - **Movement priority:** Preserve Jimmy movement and caller-dependent retained cutscene state before gameplay expansion (`AGENTS.md`, `docs/gameplay/jimmy-movement-stabilization.md`). - **References:** `../Original/` is immutable authoritative evidence; sibling JN-Engine research is a source lead, not a runtime service or replacement movement implementation (`AGENTS.md`, `docs/reviews/jn-engine-survey.md`). ## Anti-Patterns ### Treating component recovery as live scene coverage **What happens:** Bounded pair/contact components coexist with separately gated runtime solvers (`src/GamePort/Game/OriginalPairCollision.cs`, `src/GamePort/Program.cs`). **Why it's wrong:** Substituting them solely because component tests pass loses physical registration, activation and real derived callback policies. **Do this instead:** Preserve explicit scene admission in `src/GamePort/Program.cs` and require the dependencies recorded in `docs/checkpoint/next-work-plan.md` before wiring new actors. ### Collapsing input, control and body phases **What happens:** `LabSimulation` exposes both fresh and retained callback orders, while scripts independently gate raw control (`src/GamePort/Game/LabSimulation.cs`, `src/GamePort/Game/PlayerSceneBinding.cs`). **Why it's wrong:** A generic reset or input-first rewrite changes neutral cutscene return, facing and effect behavior. **Do this instead:** Preserve named preparation events, retained scalar state and `InputAfterPlayerUpdate`; extend focused lifecycle regressions (`tests/GamePort.BodyOwnershipTests/Program.cs`, `tests/GamePort.DirectorTests/Program.cs`). ## Error Handling **Strategy:** Reject invalid data and native failures explicitly; report unrecovered script behavior without inventing execution (`src/GamePort/Assets/GamLevel.cs`, `src/GamePort/Game/SceneDirector.cs`). **Patterns:** - Top-level exception handling prints to stderr and returns 1; validation/fixture failures return 2 (`src/GamePort/Program.cs`). - Bounded readers throw `InvalidDataException`; missing resources use explicit missing/ambiguous errors (`src/GamePort/Assets/AssetPath.cs`, `src/GamePort/Assets/PreparedEntityResources.cs`). - SDL/Vulkan failure checks throw with native operation context; cleanup uses `IDisposable`/`finally` (`src/GamePort/Application/RenderSession.cs`, `src/GamePort/Rendering/Vulkan/VulkanRenderer.cs`). - Director bounded dispatch records unsupported behavior and blocks problematic chains (`src/GamePort/Game/SceneDirector.cs`). ## Cross-Cutting Concerns **Logging:** Console diagnostics, unrecovered behavior lists and live debug overlays (`src/GamePort/Program.cs`, `src/GamePort/Application/DebugDiagnostics.cs`). **Validation:** Explicit endian parsing, finite/count/size checks, resource identity validation and Vulkan validation/error counts (`src/GamePort/Assets/GamLevel.cs`, `src/GamePort/Assets/PreparedEntityResources.cs`, `src/GamePort/Rendering/Vulkan/VulkanRenderer.cs`). **Authentication:** Not applicable; local desktop runtime with no online identity service (`GamePort.csproj`, `src/GamePort/Program.cs`). --- *Architecture analysis: 2026-11-12*