Crusader_Decomp/docs/rebuild-sharp/remorse-csharp-sdl3-implementation-plan.md

400 lines
45 KiB
Markdown
Raw Normal View History

# No Remorse C# and SDL3 Implementation Plan
- **Status:** Working implementation plan
- **Updated:** 2026-10-12
- **Target:** No Remorse first; No Regret after shared systems are verified
- **Runtime:** C# on .NET 10 with SDL3; desktop Windows, Linux, and macOS
- **Parent study:** [C# and SDL3 rebuild feasibility](remorse-csharp-sdl3-rebuild-feasibility.md)
## Purpose and Scope
This plan turns the feasibility study's broad delivery phases into implementation milestones with concrete outputs, dependencies, and acceptance checks. It is the work order for the C# rebuild; it does not claim that feasibility research or the existing C++/MSVC diagnostic scaffold is already implemented in C#.
The first product target is a playable No Remorse vertical slice driven by the rebuild's own simulation and USECODE runtime. The long-term target is broad retail No Remorse support and an initial documented mod workflow. No Regret remains a later, separately verified profile. This plan does not require pixel-perfect DOS timing or immediate creator-grade editors.
Retail executables and data remain user-provided, read-only inputs. Builds and synthetic tests must work without retail files. Saves, extracted content, generated assets, logs, and mods are written to a separate user data/output location.
## Current C# Baseline
The solution currently contains:
- `CrusaderRebuild.Core`, an otherwise empty class library with `GameVariant` and `GameProfile` identities for No Remorse and No Regret.
- `CrusaderRebuild.App`, which opens and clears an SDL window and selects No Remorse at startup.
- `CrusaderRebuild.Core.Tests`, with one test for stable profile identities.
- A .NET 10 target and an SDL3 C# package reference.
There are not yet C# archive or map readers, rendering or simulation systems, a USECODE interpreter, a debugger, mod support, or a retail-data test harness. Treat all of these as planned work until their milestone gates pass. The existing Windows/C++ roadmap and its subsystem notes are useful evidence and regression references, but their host implementation and modeled behavior are not completion credit for the C# runtime.
## Progress
### M0. Reproducible Build and Evidence Baseline - Complete
- `dotnet build` from `Crusader-Rebuild-Sharp`: passed.
- `dotnet test` from `Crusader-Rebuild-Sharp`: passed, 2 tests.
- `SdlApplication` now exits its event loop on either `SDL_EVENT_QUIT` or `SDL_EVENT_WINDOW_CLOSE_REQUESTED`; the binding and change compile successfully.
- A direct visible Windows launch/close check passed: the SDL window appeared, and closing it returned the terminal to the prompt.
### M1. SDL Host and Cross-Platform Deployment Spike - In Progress
- Windows x64 and Linux x64 publishes both succeed and include their native SDL library. A self-contained Linux x64 publish also succeeds.
- Visible startup and normal close passed on Windows and Linux under WSLg; both terminal commands returned after the window was closed.
- The Windows SDL window resize/redraw and close smoke test passed; the Linux x86_64 .NET 10 container builds the SDL app and runs automated core tests. Linux interactive resize and macOS deployment remain unverified. Do not claim those checks or platform support yet.
### M2. Retail Root, Build Profile, and Binary Reader Primitives - In Progress
- `GameProfile` now identifies the expected executable filename for each game. `RetailDataRoot.OpenCandidate` canonicalizes a selected directory, checks the expected executable plus `STATIC` and its initial required files, resolves names without case sensitivity, and opens executable/static files read-only.
- `BinaryDataReader` now reads bytes and little-endian 16-/32-bit values, returns bounded slices, and includes source names and absolute offsets in bounds errors.
- Synthetic tests cover both game profiles, missing/wrong files, path-component rejection, read-only streams, endianness, slice boundaries, and error offsets.
- The app's `--check-data-root` mode accepted the local No Remorse install as a candidate layout and rejected the No Regret install under the No Remorse profile; it explicitly reports that build identity is not fingerprint-verified.
- Normal startup now accepts `--data-root`, loads the No Remorse palette/maps/globs/typeflags, and displays a candidate-resource status line inside the SDL window. A No Regret root is rejected under No Remorse; the Windows visible startup/close check passed.
- `dotnet build` passed; `dotnet test` passed, 11 tests.
- This is candidate-layout validation, not exact build identification. Executable/data fingerprints and broader opt-in retail regression checks remain open.
### M3. Archive, Metadata, and Map Data Pipeline - Complete
- `FlexArchive` parses the padded header, little-endian entry count at `0x54`, and 8-byte directory rows at `0x80`; it preserves header bytes and empty entries and rejects truncated directories or non-empty entry ranges outside the archive.
- Synthetic FLEX tests cover valid data, empty entries, bad padding, truncated directories, invalid extents, and bad indices. The opt-in local No Remorse regression parses `STATIC/GLOB.FLX` and validates all 3,072 directory rows and non-empty data extents.
- `FixedMapArchive` now parses `FIXED.DAT` as a FLEX directory and decodes each map payload as unsigned 16-byte records, retaining each raw payload/record and the on-disk X/Y values. Partial records are rejected.
- `GlobArchive` decodes each object's 16-bit child count and six-byte child records, validates the required payload length, and preserves trailing bytes without assigning them meaning.
- `TypeFlagArchive` decodes Crusader's 9-byte rows into shape family, packed flags, equipment type, footpad dimensions, animation fields, weight, and volume while retaining every raw row.
- `GamePalette` parses all 256 RGB6 colors, validates component ranges, retains source bytes, and expands components using `(component * 255) / 63`.
- `NoRemorseResourceSet` loads the palette, fixed maps, globs, and typeflags from a candidate retail root. Its map validator returns structured diagnostics for invalid shape, glob, and glob-child references while preserving original map and record bytes.
- Opt-in regressions parsed every local FIXED map, all 3,072 GLOB objects, all 2,048 TYPEFLAG rows, and the 256-color palette. Map 244 contains out-of-range shape references (including record 0 shape `0x6000`); those raw records are preserved and reported, and their intended meaning remains unresolved.
- `dotnet build` passed. With `CRUSADER_REMORSE_DATA_ROOT` set, `dotnet test` passed all 43 tests; without retail data, 37 passed and 6 retail-only tests skipped.
- The readers use in-memory archives. SHAPES frame decoding and application-level loading remain open; observed archive counts are not retail build fingerprints.
### M4. Palette and Shape Decode with Deterministic Image Tests - In Progress
- `GamePalette` retains all source RGB6 components and converts entries to RGB24 with the documented integer scale.
- `ShapeArchive` reads FLEX-backed shape headers, 24-bit frame offsets, frame extents, dimensions, signed draw offsets, and per-row RLE offsets. It preserves raw shape/frame data and decodes transparent pixels as `-1` and palette pixels as `0..255`.
- The decoder validates table/extents, dimensions, pixel count, line offsets, and literal/repeated RLE runs; transparent skips that reach or pass row width terminate the row, matching the live runtime. Synthetic tests cover compressed and uncompressed runs, zero-length runs, transparency, signed offsets, empty entries, malformed extents, and invalid runs.
- Windows Debug `dotnet build` and retail-enabled `dotnet test` passed all 51 tests. Release build and synthetic-only tests also passed; without retail data, 44 passed and 7 retail-only tests skipped.
- The Linux x86_64 .NET 10 container builds the SDL app with zero warnings/errors and passes 51 retail-enabled tests; without retail data, 44 pass and 7 are skipped. Both pinned pixel samples are stable on Windows and Linux.
- The opt-in shape 1 regression now pins every decoded frame using a SHA-256 over ordered dimensions, offsets, and little-endian indexed pixels: `E8C2C409854E0F0DDE4C8AE16F20CEA4F88443482271DDCDD58F493A4AD5CDD1`. This golden is tied to the configured local corpus; exact retail build identification remains unverified.
- A second selected-art golden pins Observer shape `0x033c` frames 7 (`121x98`) and 15 (`48x35`), matching the documented usable preview frames: `582F1C15133F0BD1B0F7CA4A2723E4687D04DA3257A5E233529FAAAA0442A0C6`. It is also tied to the configured local corpus.
- The opt-in retail regression now decodes every frame in every non-empty configured No Remorse shape entry. It exposed and now covers zero-length compressed runs (shape 804/frame 14) and transparent skips beyond frame width (shape 1431/frame 131), with synthetic regressions for both. Live `CRUSADER.EXE` evidence from `ShapeFrame_HasPixelInRegion_1140_01c8` confirms zero-length runs advance the source cursor and skips that reach or pass frame width end the row. The configured archive passes the full-frame decode regression; its exact retail build identity remains unverified.
- The SDL app now loads `SHAPES.FLX` through `NoRemorseResourceSet` and presents a palette-expanded CPU texture for Observer shape `0x033c`, frame 15, with transparency and nearest-neighbor scaling. A visible Windows smoke test confirmed the sprite, status strip, resize, and clean close. This is a diagnostic sprite preview, not map rendering or gameplay.
- Additional per-frame pixel goldens beyond shape 1 and Observer frames 7/15 remain open.
### M5. Fixed-Map Renderer and SDL Presentation - Complete
- `FixedMapRenderer` now produces an SDL-free indexed CPU image from fixed-map records, including the documented X/Y scale, glob expansion offsets, world-bounds filtering, frame offsets, transparent pixels, horizontal flips, and palette-index blitting. Its footpad geometry, overlap/occlusion checks, and dependency-graph paint resolution follow the existing renderer reference in `docs/map-rendering.md` and `tools/crusader_map/sorting.py`; this comparison implementation is not claimed as proof of original-runtime ordering.
- The map-1 diagnostic defaults to the 0..4096 world crop. Against the configured local No Remorse data it renders 129 candidates (129 painted, 9 glob expansions, 0 invalid frames) into a 1537x769 indexed image. The pixel buffer is pinned to SHA-256 `BF2E6F4CED8796C5D922D34E8474989ECCC178D0B68B2F4EA702DB0D49F6644D`; this golden is corpus-specific because the data build is not fingerprint-verified.
- The SDL host expands the indexed surface through the game palette and keeps the source image dimensions fixed across resize and zoom. The diagnostic supports `+`/keypad `+` and `-`/keypad `-` in 25% steps, bounded to 0.25x..8x; startup accepts `--zoom` and `--world-bounds` options.
- Synthetic tests cover projection/frame anchors, transparent/background distinction, flipping, overlap ordering, glob coordinates/Z, viewport fitting at two sizes, and zoom limits. The opt-in retail test pins the selected map-1 crop and deterministic indexed pixels.
- A visible Windows run was checked: map and status were visible, resize worked, zoom keys changed scale and status, and close returned cleanly. `dotnet build` passed; the full retail-enabled `dotnet test` run passed all 57 tests.
- This view is diagnostic only: it has no screen-to-world targeting, target selection, or simulation input. Resizing and zooming only alter presentation. Exact retail build identity and original-runtime draw-order parity remain unverified.
### M6. Deterministic Simulation and World Ownership - Complete
- `SimulationWorld.Load` creates mutable world-owned entity state from a `FixedMap`, with stable map-scoped IDs, immutable snapshots, spawn/removal and owner-link operations, and detached source-record byte copies for comparison. Initial positions retain the raw FIXED.DAT X/Y/Z values; the renderer's X/Y scale is not applied to simulation state.
- `SimulationWorld.Advance` accumulates host-supplied elapsed time against a fixed 60 Hz delta. Each process callback receives that same fixed delta, independent of render cadence. The SDL host measures elapsed time with monotonic `Stopwatch`; a world is advanced only through this accumulator.
- Catch-up is capped at five simulation ticks per host update. Excess elapsed time is dropped and reported in the advance result and cumulative world total, preventing an unbounded catch-up loop after stalls. This can slow simulation under sustained overload; it does not let a fast CPU run the simulation faster. The 60 Hz rate is a C# host default, not a verified original-game target.
- The world runs bounded process callbacks in stable ID order; callbacks can continue, sleep for a positive number of ticks, or complete. Cancellation, faulted callbacks, and `NotSupportedException` results have distinct terminal states, with unsupported-operation diagnostics. Default limits are 65,536 entities and 4,096 process IDs per world.
- Live No Remorse `CRUSADER.EXE` Ghidra evidence: `1040:0079` calls `Kernel_RunTimedSchedulerLoop_11d0_31cf` with interval `(0,0)`, confirming that the native main loop has no global timer bound; `11d0:0255` scans the process table and dispatches eligible virtual callbacks after flag/timer checks; `11e0:0379` compares the process's 32-bit timer against the system timer and unlinks an expired process. The native timer is useful for local process eligibility, not global loop pacing or the host model's exact timing units.
- Synthetic tests cover elapsed-time partition equivalence, sub-step accumulation, long-stall catch-up bounds and dropped-time reporting, constant callback delta, sleep/wake boundaries, deterministic replay, world ownership transfer/removal, invalid IDs, capacity limits, unsupported-process reporting, and source-record isolation. The opt-in retail map-1 regression loads all 7,547 fixed records and verifies each raw record and initial coordinate is retained.
- `dotnet build` passed. Retail-enabled `dotnet test` passed all 69 tests; without retail data, 60 passed and 9 retail-only tests skipped.
- This is not a port of the DOS process table, BIOS timer cadence, or native process flags. At the M6 boundary there was no player movement and the window did not display mutable entities; the partial M7 connection is recorded below.
### M7. No Remorse Startup and Input-Driven Movement Slice - In Progress
- Live No Remorse `CRUSADER.EXE` Ghidra evidence: `1020:0000` (`Game_Start`) initializes gameplay and calls `Teleporter_CreateProcessDirect(1, 0x1e, 1)`; `10e8:000c` (`NPC_Init`) initializes avatar item 1 with shape 1/frame 0. Teleporter creation and hatch paths at `1090:04ce`, `1090:0072`, `1090:05fd`, `1090:0718`, and `1090:022d` support the modeled two-hop route. Movement behavior is derived from live decompilation and local static retail assets; runtime comparison is out of scope.
- The configured local map-1 data resolves record 1341 as the `0x1e` staging egg at `(6399,6399,0)`, record 1342 as the active `0x63` trigger (packed range `0x44`, map 1), and record 6556 as the destination egg at `(30328,29656,16)`. The retail corpus is not fingerprint-verified.
- `NoRemorseFreshStart` creates a simulation-owned avatar (shape 1/frame 0), models both teleports, and schedules movement for that same entity. The normal `--data-root <install directory>` path loads map 1 and its local scene; `--map` remains a separate fixed-map diagnostic.
- SDL key handling preserves absolute eight-direction controls with NumLock off. With NumLock on, Up/Down hold advance/reverse and Left/Right request relative turns; turn key repeats produce additional discrete turns. Losing window focus releases held movement. Caps Lock and Shift continue to choose walk versus run. This is the verified cardinal movement subset, not the full DOS keypad, modifier, or action-key controller.
- Core movement loads shape 1 stand, walk, reverse, unarmed-run, combat-stand, and armed-run clips from `ANIM.DAT`, advances direction-specific frame metadata, and applies the signed 9-bit stride multiplied by two through the native direction projection table, the clip rotation flag, signed Z displacement, 12-bit shape-frame ID, and horizontal-flip bit. The local retail walk/run headers are `[17, 5, 2, 0]` and `[12, 5, 2, 0]`; these are static-data findings, not runtime observations. The host honors two-step starts, the looping frame path, and frame-repeat delays.
- Live Ghidra evidence: `1130:12d6` (`Controller_PickNextAnimByKeyevent`) uses current facing for NumLock-on advance/reverse; relative left/right turns select stand animation `0` when unarmed and combat stand `4` when armed. The follow-up direction step is two slots for the 8-direction stand clip and one slot for the 16-direction combat stand clip. An active weapon selects run animation `0x30` instead of unarmed run `3`; `Controller_UpdateAvatarAngle` at `1130:10cf` confirms the weapon-out combat-stance turn path. The host implements these modes and exposes weapon-drawn state through `AvatarInputQueue.EnqueueWeaponDrawn`; inventory and weapon-ready actions do not yet drive that state. `1150:016f` (`AnimPrimitive_CheckToStartNewAnimation`) starts animation processes, and `1150:1906` (`AnimPrimitiveProcess_Run`) advances metadata and displacement.
- The animation caller sends grounded frames through `AreaSearch_SweepShapeBetweenPointsWithStepUp` at `10e0:162f` with flags `0x11`; airborne frames call `AreaSearch_SweepTestPt` at `10e0:0b39` directly with flags `4`. The grounded wrapper first tries the requested sweep, then on failure tests vertical clearance and the raised destination at +8, followed by +9. The host models that retry as separate vertical and horizontal TYPEFLAG-bound sweeps, and keeps the direct-only path for airborne frames. For a rejected grounded solid sweep, it retains the last legal position and enters a blocked state. SDL key-repeat events can retry a held direction, while other repeated key-downs do not advance the movement animation. `AnimPrimitiveProcess_Run` at `1150:1906` applies frame flip metadata to persistent `FLG_Flipped` status before collision, but the `gotBlocked` jump bypasses `Item_SetFrame`; the host now preserves that status update without advancing the blocked sprite frame. The native candidate-area scan, point-sweep details, AreaSearch flags, and collision notifications/hurl response remain unimplemented.
- Map-loaded entity snapshots now derive horizontal flip from FIXED.DAT status bit `0x20`, matching the flag already consumed by the renderer.
- The SDL scene sends all spawned or source-pose-changed world entities to a persistent map-render session. The session caches static indexed pixels and prepared shape frames, indexes static nodes in 128-pixel spatial cells, and recomposes only merged old/new sprite bounds intersecting the current viewport. Camera shifts refresh only visible dynamic sprites; deferred offscreen bounds are skipped until visible. The App reuses one streaming SDL texture and converts/uploads only returned patches. The live map's static-item crop recenters around the avatar before its `0x1000` world-coordinate radius is exhausted, then rebuilds the scene and texture so records outside the startup crop enter view; this is rolling map rendering, not a verified native tile-streaming implementation. The live avatar is not drawn as a topmost overlay. Snap camera follow is the default; `--smooth-camera` enables host-side exponential follow and edge clamping. Large position jumps and Z changes snap the camera so the modeled startup teleports do not leave interpolation trails.
- The top-left HUD displays FPS. Frame pacing targets 60 FPS and waits only for the remaining frame budget instead of adding a fixed 16 ms sleep after rendering; sustained runtime performance remains unmeasured. Press `H` to toggle the temporary hack mover; while active, `HACK MODE (H)` appears at the top of the screen and a left click inside the map teleports the avatar to that projected world position at its current Z. This is a rebuild debugging control, not a port of the original mover. Follow zoom is limited to 0.5x-1x, using the original 640x480 screen as the native-scale reference. The map fills the available host area without side bars; wider aspect ratios show additional horizontal world. At 0.5x, the visible source dimensions are approximately doubled. The fixed-map diagnostic remains fit-to-window.
- Renderer comparison with the earlier C++ implementation found two omission cases: fresh-start rendering inherited the diagnostic default that filters roof-flagged shapes, and C# allowed invisible map records to act as occluders although C++ excludes them. Gameplay now includes roofs, and invisible records no longer cull overlapping sprites. The separate map diagnostic retains its roof toggle/default.
- Synthetic tests cover absolute controls, tank advance/reverse, unarmed 8-way and armed 16-way turns, armed run-clip selection, held/released input, walk/run selection, stand transitions, animation displacement and cadence, shape-frame/flip metadata, imported FIXED.DAT flip status, flip-state update before blocked frame rejection, focus-loss release, facing, rollback and held-input retry on map and spawned solid collisions, grounded low-solid step-up, spawn-overlap exit, renderer patch parity, sprite removal, moving bounds, zoom/camera behavior, and projection. Opt-in retail tests cover the roof-flagged shape `0x003c`, the avatar in the shared sort pass, start-scene crop, and the full route followed by movement of the same avatar ID.
- `dotnet build CrusaderRebuild.slnx` passed. With `CRUSADER_REMORSE_DATA_ROOT` set to the configured No Remorse install, `dotnet test CrusaderRebuild.slnx` passed all 114 tests. An earlier SDL launch smoke test loaded retail resources, rendered a crop with 1,155 static scene items, and entered the event loop; it was stopped with Ctrl+C. The rolling map window has not yet had a manual boundary-crossing check because the existing debugger session was left undisturbed.
- M7 remains incomplete: inventory/weapon-ready transitions into the weapon-drawn movement state, other DOS keypad and modifier combinations, target/crosshair angle updates, exact AreaSearch candidate selection and point-sweep behavior, native collision response/hurl behavior, frame-skip handling, visual input verification, rolling-map boundary verification, measured continuous-motion performance, and parity with native occlusion. The current TYPEFLAG AABB sweep is not full collision parity. Runtime comparison is intentionally out of scope for this movement work. The 320x200 rectangle in `Camera_RedrawViewportAndGameplayOverlays` is a centered redraw region, not the full screen; `Init_Everything` initializes viewport bounds through 639x479. Do not claim native movement or scheduler parity.
## Implementation Rules
1. Keep game rules, parsers, and simulation in `CrusaderRebuild.Core`; keep SDL, filesystem dialogs, audio devices, and other operating-system services at the application boundary.
2. Use explicit game profiles for build identity, startup, mission metadata, globals, and USECODE intrinsics. Do not infer shared behavior from similar names or layouts.
3. For each substantial behavior, record the target program/build, Ghidra address, variant, evidence type, confidence, implementation state, and runtime/test status. A function name or decompilation alone is not proof of behavior.
4. Preserve unknown binary fields and original widths where compatibility depends on them. Validate all lengths, counts, offsets, IDs, and references before use; fail with actionable diagnostics rather than guessed values.
5. Keep fixed simulation ticks deterministic and independent from render cadence. Tests should control time and input without launching SDL.
6. Keep diagnostics and temporary stand-ins visibly separate from gameplay paths. A map preview, test actor, or host-only state mutation does not pass a playable-game gate.
7. Build synthetic fixtures first. Retail-data checks are opt-in and must not write to the retail tree.
8. Keep expanded viewport, zoom, and camera interpolation in presentation. Optional No Regret-derived behavior must be disabled by default for No Remorse and must not replace its profile-specific rules.
## Milestone Sequence
Milestones are ordered by dependency, not calendar duration. Each gate is a stop-and-check point: record the result and unresolved issues before starting dependent work. A milestone can be split into smaller pull requests, but its acceptance criteria should remain intact.
### M0. Reproducible Build and Evidence Baseline
**Outcome:** A clean checkout can build and test without game data, and the project has a consistent way to track reverse-engineering evidence.
**Work items:**
- Run and record the baseline `dotnet build` and `dotnet test` results for the solution.
- Confirm SDK selection from `global.json`, nullable/compiler settings, and that the SDL app starts and exits cleanly on the development host.
- Establish a compact evidence-record format for ported behaviors, including Ghidra program/build identity, address, variant, source evidence, confidence, tests, and remaining gaps.
- Identify the exact No Remorse executable/data build used for local validation without checking retail files into source control.
- Keep the first test fixtures synthetic and deterministic; document any opt-in retail regression prerequisites.
**Acceptance:** Build and tests pass from a clean checkout without retail data. SDL initialization/window failures return a useful error and still release initialized resources. Evidence records can distinguish a hypothesis, a translated implementation, and runtime-verified behavior.
### M1. SDL Host and Cross-Platform Deployment Spike
**Depends on:** M0.
**Outcome:** The selected SDL3 binding and native packaging are proven independently of game logic.
**Work items:**
- Put SDL initialization, window/renderer ownership, event polling, and presentation behind a small application-host boundary.
- Define host-neutral input, elapsed-time, and presentation interfaces without introducing SDL types into `CrusaderRebuild.Core`.
- Exercise startup, resize, quit, and orderly cleanup on Windows and at least one non-Windows desktop target; record native-library packaging requirements for all claimed platforms.
- Keep a CPU-side image buffer as the initial correctness surface; do not add GPU palette logic before image tests justify it.
**Acceptance:** The same core and host smoke tests run on Windows and one non-Windows desktop target, the application starts and exits without leaked SDL resources, and no SDL or operating-system type crosses into the core project. Do not claim untested operating systems as supported.
### M2. Retail Root, Build Profile, and Binary Reader Primitives
**Depends on:** M0.
**Outcome:** The application can safely identify a supported local data set and parse bounded binary structures.
**Work items:**
- Define a user-selected or command-line retail data root; canonicalize it and open source files read-only.
- Add build/profile detection based on explicit fingerprints and required-file checks, with clear unsupported/ambiguous-build errors.
- Implement reusable little-endian readers with checked offsets, bounded slices, and useful file/offset diagnostics.
- Add synthetic malformed-input tests for truncated headers, out-of-range offsets/counts, overflow, duplicate IDs where relevant, and unsupported variants.
- Add an opt-in local retail smoke test that reports detected files/build without modifying them.
**Acceptance:** Synthetic parser tests run without installed assets. Invalid files fail safely with the failing file and offset identified. A local supported install is recognized read-only, and an unsupported or incomplete install is rejected with actionable diagnostics.
### M3. Archive, Metadata, and Map Data Pipeline
**Depends on:** M2.
**Outcome:** Required No Remorse resources can be resolved and a retail map is represented as validated data, not yet as gameplay.
**Work items:**
- Implement FLEX directory/entry reading with bounds checks and preserve entry bytes exactly.
- Parse the required palette, fixed-map records, glob/map metadata, shape metadata, and resource indexes in dependency order.
- Represent parsed data with typed IDs and coordinates while retaining opaque/unknown bytes needed for round trips.
- Add small synthetic fixtures for valid, empty, truncated, overlapping, and invalid-reference cases.
- Add retail regression assertions for known archive entries and map records; keep these tests explicitly opt-in.
**Acceptance:** Readers produce stable results for the synthetic corpus and a selected No Remorse retail build. Malformed references are reported rather than silently clamped or skipped. Reading data leaves the retail root unchanged.
### M4. Palette and Shape Decode with Deterministic Image Tests
**Depends on:** M3.
**Outcome:** The core can decode a bounded set of retail graphics into repeatable CPU images.
**Work items:**
- Decode palette entries and the first required shape/frame formats, including transparency, frame offsets, and horizontal flip behavior where confirmed.
- Keep decoded frame data independent of SDL and use explicit palette/index representation until presentation.
- Add pixel-level golden tests from synthetic data, plus opt-in retail checks for selected known shapes and palette values.
- Build a diagnostic image export or test artifact path outside the retail tree.
**Acceptance:** Synthetic frame tests cover dimensions, transparency, offsets, palette selection, and malformed frame data. Selected retail frames decode to stable pixel output on all test hosts. This gate proves asset decoding only, not playable rendering.
### M5. Fixed-Map Renderer and SDL Presentation
**Depends on:** M1, M3, and M4.
**Outcome:** A diagnostic renderer displays a stable, recognizable No Remorse map scene through an expanded, zoomable viewport.
**Work items:**
- Implement world-to-screen projection, clipping, background/map layers, and a first source-evidence-backed draw ordering for fixed items.
- Separate render-surface dimensions from the logical viewport and support expanded world coverage plus bounded user-controlled zoom; keep source-art resolution and simulation coordinates unchanged.
- Keep screen-to-world input conversion and target-selection rules explicit so changing viewport size or zoom does not silently change gameplay reach.
- Convert the CPU image buffer to an SDL presentation texture at the host boundary.
- Add image comparison tests for multiple viewport sizes/zoom levels and a retail scene regression for known map regions, frame anchors, palette, and ordering.
- Label the fixed-map view as a diagnostic; do not use it as evidence of live simulation or player control.
**Acceptance:** A selected retail map renders repeatably through the SDL host. The viewport can show expanded world coverage and zoom within defined limits. Image tests detect ordering, clipping, and palette regressions; input and target rules stay stable across view settings. Resizing or presenting frames does not mutate world coordinates or simulation state.
### M6. Deterministic Simulation and World Ownership
**Depends on:** M3; can proceed alongside M4/M5 after data models stabilize.
**Outcome:** The core owns mutable world entities and advances them using controlled fixed ticks.
**Work items:**
- Define simulation state, stable item/entity identities, mission state, and explicit ownership/lifetime rules.
- Add a fixed-step clock interface that can be driven directly by tests; keep render interpolation and wall-clock pacing outside the simulation.
- Implement only the scheduler/process primitives supported by evidence, with bounded collections and explicit unsupported-process diagnostics.
- Load the map's fixed records into mutable runtime state while retaining source records for comparison.
- Add deterministic state-transition tests for idle ticks, process wake/sleep boundaries, ownership changes, and invalid IDs.
**Acceptance:** Replaying the same initial state and input/tick sequence yields identical state snapshots. Every displayed mutable actor is backed by the same simulation-owned entity that receives updates. No app or SDL call is needed to test the simulation.
### M7. No Remorse Startup and Input-Driven Movement Slice
**Depends on:** M5 and M6.
**Outcome:** A retail map-1 fresh start reaches the level-start location, and input drives the simulation-owned avatar through the core update path.
**Work items:**
- Trace the fresh-game startup and map-1 egg `0x1e` placement chain against the exact No Remorse target in Ghidra and controlled runtime observations.
- Implement the minimum startup, item ownership, scheduler, keyboard queue/control, and movement behavior needed for that path; record host substitutions explicitly.
- Route host input into core commands and render live item/frame state in source-evidence-backed order.
- Preserve snap/parity camera behavior as the default and add a separate opt-in smooth-follow setting. Interpolate camera presentation from simulation snapshots using elapsed render time; reset/snap on map changes, teleports, and other discontinuities.
- Test idle input, movement, blocked movement, facing, spawn coordinates, and the verified two-hop teleporter/start-pad path.
- Test camera convergence at different render rates, pause/resume, edge clamping, and scripted moves, asserting camera interpolation does not alter actor coordinates, collision, or fixed-tick results.
- Keep a diagnostic traversal or preview mode separate from the normal startup and play path.
**Acceptance:** A deterministic integration test starts from the retail scenario data, follows the normal modeled startup path to the level-start pad, then moves the same live avatar item through core ticks. The window shows those state changes without drawing a separate stand-in. The camera option can be toggled without changing simulation results, and discontinuities do not produce long interpolation trails. Any unported startup or scheduler portion is called out; no claim of original-loop parity is made unless verified.
### M8. USECODE Decoder, Interpreter, and First Real Interaction
**Depends on:** M6; the first interactive scenario can proceed alongside M7 once item/event contracts are stable.
**Outcome:** One reachable retail interaction executes from original USECODE through the rebuild VM and changes world state.
**Work items:**
- Build a corpus of archive chunks, dispatch rows, and relevant event bodies from the selected No Remorse build; preserve unresolved bytes.
- Resolve the archive/event-format disagreements using target evidence and round-trip fixtures before enabling writes or authored scripts.
- Implement the VM value model, instruction decoder, frames, stack, calls, event dispatch, and only the verified opcodes/intrinsics needed for the scenario.
- Keep intrinsic registration variant-specific. Report unsupported opcodes, bad frames, and unavailable metadata explicitly.
- Connect one reachable item event to normal item search/dispatch and assert the resulting world mutation and rendered effect.
- Capture deterministic traces that include profile, class/unit, event, bytecode offset, intrinsic calls, and state changes.
**Acceptance:** The integration test exercises the normal item/event path and a real script body, not a host-only mutation or release counter. It asserts before/input/after world state and visible output. Unsupported instructions halt with a traceable diagnostic rather than fabricated results.
### M9. VM Debugger and Execution Inspection
**Depends on:** M8; instruction-boundary hooks should be designed with M8 rather than retrofitted later.
**Outcome:** VM execution can be paused and inspected through a debugger model, with an initial usable UI.
**Work items:**
- Implement break, continue, instruction-step, step-over, and step-out at interpreter boundaries.
- Key breakpoints by game profile, class/unit, event slot, and bytecode offset; add source-line breakpoints only where metadata is verified.
- Expose current unit/event/PC, nested frames, evaluation stack, supported locals/globals, intrinsic arguments/results, and state-mutation trace.
- Build a minimal debugger view in the SDL application after the model is testable headlessly.
- Mark synthetic source mappings as synthetic; defer watches and expression evaluation until descriptors and value lifetimes are established.
**Acceptance:** Tests exercise nested calls and balanced stepping state deterministically. In a retail scenario, a user can pause at a known instruction, step through a nested call, inspect supported values, and resume. Unknown source/value information is labeled unavailable rather than guessed.
### M10. Versioned Mod Resource Layer and Validation
**Depends on:** M2 and M3; runtime resource resolution is required before custom-mission work.
**Outcome:** Mods can safely override complete resources with deterministic precedence and useful compatibility diagnostics.
**Work items:**
- Define a manifest with mod identity/version, game/build/language compatibility, required files, dependencies/conflicts, entry mission, and content hash.
- Implement deterministic base-game/mod mount order and report the supplying package for each resolved resource.
- Start with complete-file replacement; do not imply per-entry archive merging.
- Add a no-write package validation command for malformed manifests, missing resources, incompatible builds, and dependency conflicts.
- Include ordered mod identities/hashes in save compatibility metadata before allowing modded saves.
**Acceptance:** Synthetic package tests prove deterministic resolution and reject incompatible or unsafe packages. Retail sources remain unchanged. A running scenario reports which package supplied each overridden resource.
### M11. Custom Map, Graphic, and Mission Workflow
**Depends on:** M8 and M10; authoring/rebuild work requires validated parsers and stable runtime entry contracts.
**Outcome:** A small custom mission can be built, validated, launched, and transitioned without editing retail files.
**Work items:**
- Add map/glob export and rebuild while preserving unknown fields and rejecting invalid references.
- Add shape/frame extraction and re-import with palette, offsets, and transparency preserved.
- Require byte-identical unchanged archive round trips before enabling edited archive output.
- Define mission entry and transition metadata, including start map/egg or coordinates, required resources/scripts, and save compatibility identity.
- Add a small authored scenario exercising one spawn, one transition, one custom graphic, and one USECODE-backed interaction.
- Add validation diagnostics for missing resources, invalid IDs, unsupported script operations, and incompatible save/mod identities.
**Acceptance:** The packaged custom scenario starts, transitions, saves, and reloads under the same ordered mod set. Map/graphic round-trip tests preserve supported and opaque data. Generated files are written only to the selected output area.
### M12. No Remorse Retail Coverage and Release Candidate
**Depends on:** M7-M11, with the debugger/tools allowed to remain separately gated if their limitations are explicit.
**Outcome:** The implementation grows from one slice into declared No Remorse retail coverage and can be tested as a user-facing desktop application.
**Work items:**
- Expand the evidence and regression inventory across startup/menu flow, mission transitions, NPC/process behavior, combat, projectiles, inventory, doors/panels/triggers, saves, audio, fonts/gumps, and movies.
- Capture and test No Remorse's weapon-capacity behavior as the profile default; do not apply Regret's unlimited carrying rule before M14.
- Prioritize behavior by campaign reachability and dependency; do not substitute empty stubs for unsupported paths without labeling them.
- Implement save/load compatibility checks and per-user config/save/cache/log locations.
- Add crash reporting, missing-data diagnostics, packaging, clean-install tests, and Windows/Linux/macOS smoke tests for each claimed target.
- Publish a feature/support matrix distinguishing verified, partial, unsupported, and untested behavior/builds.
**Acceptance:** The stated No Remorse support level is demonstrated by repeatable campaign-path tests and clean-install smoke tests using user-provided data. Saves reject or explicitly migrate build/mod mismatches. The release does not claim platforms or gameplay paths that have not passed their gates.
### M13. No Regret Profile and Compatibility Pass
**Depends on:** M12's shared contracts and deterministic regression infrastructure.
**Outcome:** No Regret runs through explicit variant behavior without weakening No Remorse guarantees.
**Work items:**
- Fingerprint supported Regret executable/data builds independently.
- Add profile-specific startup/global initialization, mission metadata, resource differences, and USECODE intrinsic tables.
- Re-verify shared format and runtime behavior instead of copying Remorse assumptions based on matching names.
- Build Regret synthetic and opt-in retail fixtures, including debugger/source-mapping coverage based on actual metadata.
- Extend mod/save compatibility identity to the Regret build and profile.
**Acceptance:** No Regret-specific integration tests pass without regressing No Remorse tests. Unsupported build variants are rejected explicitly, and each shared behavior has evidence that it is actually shared. This milestone must pass before adding Regret-derived movement, inventory, or USECODE behavior to No Remorse.
### M14. Optional No Regret Movement and Weapon-Capacity Backports
**Depends on:** M7, M12, and M13.
**Outcome:** No Remorse can opt into two specific Regret-derived behaviors while keeping retail Remorse behavior as the default.
**Work items:**
- Add an independent No Remorse option for the Regret-style forward roll, triggered by Ctrl+Forward. Verify supported controller states, animation availability, input precedence, and interruption behavior before enabling it.
- Add an independent option for Regret-style unlimited weapon carrying. When disabled, preserve and test the No Remorse weapon limit; when enabled, validate pickup, equip, drop, mission transition, and save/load behavior.
- Expose both options as separate settings and test each option alone, both together, and the default configuration. Keep native No Regret behavior owned by its own profile.
**Acceptance:** Default No Remorse movement and inventory regressions remain unchanged. Each option is independently configurable and covered by deterministic controller/inventory tests plus an opt-in retail regression where available. Unsupported roll states fail safely rather than entering an invalid animation.
### M15. Additive No Regret USECODE Extensions for No Remorse
**Depends on:** M8 and M13; start only after No Regret profile integration is accepted.
**Outcome:** Selected Regret-derived script capabilities are available to No Remorse as optional extensions, without replacing No Remorse USECODE behavior.
**Work items:**
- Keep the No Remorse intrinsic table and ordinal meanings intact; register only reviewed, testable Regret-derived capabilities through an explicit extension set.
- Do not silently bind a Regret call to a colliding Remorse ordinal. Use explicit extension identities/aliases or reject ambiguous scripts with a diagnostic.
- Version extension metadata and make scenario/resource compatibility explicit. Backport only features supported by the shared runtime; this is not wholesale replacement with Regret scripts or tables.
- Add fixtures that exercise each extension and run existing No Remorse script regressions with extensions both disabled and enabled.
**Acceptance:** Extension-disabled No Remorse scripts retain existing semantics. Enabled fixtures exercise documented Regret-derived capabilities, existing intrinsic ordinals remain unchanged, and unsupported or ambiguous calls fail with actionable diagnostics.
## Cross-Milestone Completion Record
For each completed milestone, add a concise progress entry under `docs/rebuild-sharp/` that records:
- milestone and acceptance criteria passed;
- changed C# projects/subsystems;
- Ghidra addresses/build identity and confidence for behavior ports;
- focused build/test commands and results;
- retail fixture requirements, if any;
- unresolved behavior and the next dependency-blocking question.
Keep implementation code in `Crusader-Rebuild-Sharp`; keep rebuild progress documentation in this repository. Do not update legacy decompilation notes by default.
## Immediate Start Order
1. Complete M0 by running `dotnet build` and `dotnet test` from `Crusader-Rebuild-Sharp` and recording the baseline.
2. Start M1 and M2 as independent tracks: prove SDL deployment and establish safe retail-data/profile handling.
3. Begin M3 with FLEX and map fixtures, using the selected No Remorse build as an opt-in regression corpus.
4. Reassess the remaining milestone estimates and implementation order after the data/render spike; do not commit to full campaign scope based on the empty SDL shell.
5. After M13 passes, schedule M14 and M15 as separate opt-in follow-ons; neither is part of the No Remorse or No Regret baseline acceptance gate.
## Explicit Non-Goals Until Their Gates
- No Regret gameplay before M13.
- No Regret-derived movement/inventory behavior before M13, or as a default change to No Remorse behavior.
- No additive Regret-derived USECODE extensions before No Regret integration passes M13; the Remorse intrinsic table is never replaced by the Regret table.
- No arbitrary native plug-ins or executable code supplied by mods.
- No retail-data writes, byte patching, or in-place archive editing.
- No claim of a playable game from a static map preview or host-only actor/script shortcut.
- No pixel-perfect DOS reproduction requirement unless a later acceptance target specifically calls for it.
- No assumption that the existing C++ scaffold, exported C, or symbol coverage constitutes implemented C# behavior.