Crusader_Decomp/docs/remorse-windows-rebuild-roadmap.md

615 lines
84 KiB
Markdown
Raw Normal View History

# Remorse Windows Rebuild Roadmap
## Purpose
This note records the current effort to turn the live Ghidra analysis and the exported C decompilation of `CRUSADER.EXE` into a source tree that can be recompiled and run on modern hosts. Windows is the current development and acceptance target, not the only intended platform: keep recovered game logic and data formats host-independent, isolate Win32 presentation and diagnostics behind replaceable platform boundaries, and plan a portable window/input/timing/audio host when the original runtime call chains require it. Other platforms are a future goal, not a claim of current support.
The first deliverable is a functioning modern Windows game compiled from cleaned, traceable decompiled `CRUSADER.EXE` game code, with a path to multi-platform builds. Replace DOS/Phar Lap and hardware services at their call boundaries; retain and repair the original control flow, data structures, scheduler, rendering, input semantics, and gameplay logic wherever recoverable. This is a source port, not a clean-room engine reconstruction. Modding is a later goal, not an initial acceptance criterion.
The exported files are evidence, not directly compilable game source. Keep them unchanged and move verified, subsystem-sized function bodies into the rebuild tree, recording each original address and any corrections to decompiler artifacts. Do not substitute a newly designed gameplay implementation for an unported function and call that function complete.
## Recompilation Gate
- Every claimed port identifies its original NE address, exported function, unresolved decompiler ambiguities, and host-only substitutions. Distinguish direct translations, behaviorally verified ports, and temporary stand-ins.
- Compile recovered game functions into `remorse_core`; call them from the runtime path that needs them, not only from isolated tests. Tests should compare state transitions, side effects, and error paths with binary/decompiler evidence where possible.
- Keep DOS file, memory, timing, input, video, and audio replacements behind explicit platform boundaries. Resource parsers and the current preview/window remain useful diagnostics, but are not substitutes for porting the original game loop and its callees.
- At each milestone, count original functions translated and exercised in the Windows build, platform calls replaced, and parity checks passed. A rendered scene or a controllable stand-in actor alone does not pass a game-code milestone.
- Do not claim whole-game recompilation until startup, game ticks, interactions, mission flow, save/load, and presentation are driven by ported game code and playable on modern Windows using the original data.
## Source-Backed In-Game Vertical Slice
The immediate target is a fresh game on retail map 1 that follows the original start sequence from the staging teleporter to the level-start pad, with an avatar owned by the ported item/NPC runtime, a tick and input path that actually drive that avatar, a changing world image, and at least one original-script-backed interaction. The current host item/process movement and live-item rendering are useful verified steps, but do **not** count as the original loop or interaction. Keep the diagnostic traversal view separate while replacing its behavior; no DOSBox parity gate is required for this Windows milestone.
1. **Startup and spawn:** port the fresh-game branch of `Game_Start` (`1020:0000`) through `Teleporter_CreateProcessDirect(1, 0x1e, 1)` and its placement callee. Resolve egg `0x1e` from original map data, then follow the nearby active `0x63` teleporter to destination egg item 6812 at `(30328, 29656, 16)`. The host path and retail test now verify item 1 reaches that pad; the original `Game_Start` call chain remains unported. Do not implement intro movies, main menu, save loading, or warp overrides for this slice.
2. **Live world ownership:** initialize the original item cache and NPC/avatar state for that map. The displayed avatar must be the same numbered, mutable item advanced by the process runtime; reject a separately drawn or separately positioned stand-in.
3. **Tick and input:** port the minimal recovered cycle/scheduler and keyboard queue/control chain that moves that avatar. Route Win32 key/timer events through the host boundary into those routines; test deterministic state changes with recorded inputs, including idle and blocked movement.
4. **Gameplay presentation:** render the live item/sprite state in source draw order each tick and follow the recovered camera state. Verify that movement, facing, and at least one changed world item appear on screen, without relying on a single prepainted fixed-map image.
5. **Real interaction:** implement one reachable map-1 usecode event through the original item find/grab, VM dispatch, and resulting world-state mutation. Demonstrate a repeatable before/input/after trace and visible effect; a script lookup or release-request counter is not an interaction.
6. **Acceptance:** launch the normal Windows executable with retail data, follow map 1's fresh-start sequence from egg `0x1e` through the active `0x63` trigger to the level-start pad, then move and interact without a diagnostic shortcut. Verify on-screen state plus a deterministic integration test. Keep absent combat, audio, menus, persistence, and broader missions listed as limitations, not silently simulated features.
### Progress Update (2026-10-06)
The normal map-1 host startup now follows the two-hop placement: start egg item 1597 (`0x1e`) reaches active trigger item 1598 (shape `0x0194`, frame 0, ID `0x63`), which places item 1 at destination egg item 6812 (`30328, 29656, 16`). The retail regression verifies the trigger, destination, avatar coordinates, and preservation of the timer, keyboard, and controller processes. The renderer centers on the destination, and the player sprite now uses the same frame-anchor convention as map objects. The MSVC gate passed all 15 CTests and the retail harness; the user confirms the avatar now appears at the correct location.
This remains a host-modeled startup, not execution through `Game_Start`, `Teleporter_CreateProcessDirect`, or the original scheduler. A destination-area eligible-use scan, reachable original-script mutation, and original loop/render parity remain open.
### Historical Staging-Point Snapshot
The following blocker details were recorded before the second hop was implemented. In particular, the no-eligible-use result and candidate distances refer to the old staging coordinate near `(6399, 6399, 0)`; they do not establish which interactions are reachable from the current destination `(30328, 29656, 16)`.
Current blocker: the normal host window resolves egg `0x1e` from map 1 and places host item 1 at that retail record, then routes queued input through host controller and animation processes that mutate the same live item. Startup now models the constructor's clear-stasis waiter and schedules the same-map teleporter over two kernel scans, but these remain host models, not calls through `Game_Start`, `Teleporter_CreateProcessDirect`, or the original scheduler. The ordinary host tick now also scans ready `Gravity` processes through the live-item collision sweep and requests a redraw when a falling item moves, including while the avatar is idle; this is not original scheduler parity. Idle ticks also consume pending usecode frame mutations and wake the renderer, rather than waiting for another movement input. The production-equivalent item search at the egg spawn still finds one candidate and no eligible `use` event. A retail scan finds 218 map-1 use-eligible items; the nearest is `PANELNS` item 288 at `(2919, 1061, 48)`, frame 0, quality 6, map-array 134, at horizontal Manhattan distance 8,818 staged-coordinate units from spawn `(6399, 6399, 0)`. Its recovered handler exits on frame 0 and nonzero map-array. A nearby `CARD_NS` at staged `(2783, 1055, 40)` has frame 0 and `QLo=6`; its `SWITCH::ordinal21` path needs keycard 6 to authorize the visible frame-4 state, and the fresh-game host keycard set is empty. The nearest chest candidate is `CHEST_EW` map-source record 151 at staged `(1087, 2559, 0)`, frame 0, `QLo=5`, 9,152 horizontal units from spawn. Its handler calls `FREE.slot_2d` to test a same-family legal swap to shape `0x054b`, then animates frames 0 through 4 and dispatches `TRIGGER` if the swap succeeds. The host currently lacks that shape-swap service, and no collision route from spawn to this chest has been verified. The nearest frame-0 `BOX_NS` is 18,048 staged-coordinate units away. The BOX_NS effect test remains fixture-origin coverage; no reachable retail interaction or original item/event dispatch is established.
### Current Blocker
The first reachable map-1 retail interaction now passes a deterministic host regression through item search, owner-row event selection, nested VM dispatch, and a rendered chest-frame mutation. Original `Item_Grab` and `Usecode_ItemCallEvent` are still not integrated into normal gameplay, and the chest's later `0x70` loot search and full script completion remain unsupported. The original startup call chain, game scheduler, and source draw/camera behavior are also incomplete.
## Current Inputs
- `exports/src_remorse/export_manifest.json` reports `CRUSADER.EXE`, 2,984 exported function files, 9 fallback function files, 57 global buckets, and 15,403 global definitions.
- `exports/src_remorse/CRUSADER.EXE.h` contains the bulk Ghidra data types and provisional structure definitions.
- `exports/src_remorse/functions/` contains split function bodies, including class-like folders such as `Remorse/EntityDispatchEntry`, `Remorse/SpriteNode`, `Remorse/EntityVmRuntime`, and related process families.
- Existing rebuild planning is in `docs/remorse-cpp-decompilation-plan.md`, `docs/remorse-rebuild-abi-notes.md`, and `docs/remorse-cpp-compatibility-header-draft.md`.
## Rebuild Scaffold
`rebuild/remorse/` contains the MSVC/CMake build, retail-data readers, diagnostic map/window, partial process/item/USECODE runtime, and focused tests. These are host infrastructure and partial source ports, not a playable game; subsystem documents retain detailed implementation evidence.
## Why The Export Does Not Compile Yet
The current exported C is very valuable, but it is not compiler-ready source for either DOS or Windows.
Known blockers visible in the export:
- C++ namespace-qualified function names appear inside `.c` files, for example `Remorse::EntityDispatchEntry::InitBase`.
- Ghidra calling-convention spellings such as `__cdecl16far`, `__cdecl16near`, `__stdcall16far`, and `__regcall` are not portable host compiler syntax.
- Ghidra undefined-width types and decompiler temporaries (`undefined`, `undefined2`, `undefined4`, `unaff_SS`, `unaff_CS`, synthetic stack variables, and return-storage pointers) need type and calling-convention cleanup.
- Header output includes invalid or provisional C declarations such as structure names containing spaces.
- Switch-table and global-byte exports are emitted as raw `undefined` objects that need relocation-aware or data-layout-aware modeling.
- Some functions still rely on segmented pointer reconstruction through expressions such as `CONCAT22`, not host pointers.
- The original binary is a DOS protected-mode `MZ -> NE` program using Phar Lap 286 extender behavior and far calls, so a modern Windows build needs a platform/runtime replacement rather than a simple relink.
## Rebuild Tracks
### Track A: Historical Executable Reconstruction
This track tries to rebuild something close to the original DOS protected-mode executable model.
It must preserve segmented pointers, far-call provenance, original-style packing, external runtime calls, and NE/Phar Lap assumptions. It is the hardest path and is not the primary route to modern Windows compatibility, but it remains important because it keeps the reverse-engineered ABI honest.
### Track B: Windows Source Port
This track compiles corrected decompiled game source, retaining original behavior and object layouts while replacing only the OS/hardware-facing calls needed to run it on Windows.
It can replace DOS extender, VGA, sound, input, timing, file, and memory services with host implementations, but it should initially preserve exact-width data layouts and far-pointer provenance so behavior can be compared back to the original.
For the stated goal of running on modern Windows, Track B is the practical primary track. Track A should still guide early type cleanup so the port does not accidentally erase evidence.
Goal: put a real Crusader world image on screen on Windows.
Work:
- choose initial graphics layer, likely SDL for window/input/timing/audio portability
- convert paletted frames to host pixels
- implement deterministic fixed-map painter first
- add debug overlay/status console for loaded map and camera position
Exit criteria: running the host executable opens a window and displays a recognizable fixed-map scene from retail data.
### Phase 4: Process, Item, And Entity Runtime
Goal: lift the core object/process model into host source.
Work:
- typed `Process` / `EntityDispatchEntry` layout
- item allocation, fixed-format conversion, map item cache
- scheduler/process list
- sprite-node/draw-list families
- core entity fields and update lanes
Exit criteria: the host runtime can instantiate map items/entities and advance a deterministic tick without requiring the full original VM yet.
### Phase 5: Input, Camera, And Player Loop
Goal: make the rendered world navigable.
Work:
- keyboard/mouse abstraction
- camera scroll/viewport state
- cursor/selection state
- player/avatar process skeleton
- collision/line-of-sight primitives as needed
Exit criteria: the user can launch the host build, view a map, move the camera/avatar test object, and observe stable tick/update behavior.
#### ScummVM-Style Live Viewport, Zoom, And Smooth Camera
After live item state and source draw-order behavior are available, replace the fixed player-centered scene bitmap as the primary world-rendering path with a live viewport renderer based on ScummVM's useful architecture: select nearby world candidates, clip before sorting, build a reusable display list, and paint the current view each frame. Retain the fixed-scene/offline renderer as a diagnostic and regression oracle during migration. Do not copy `CurrentMap` fast-area activation directly for render culling: ScummVM's fast-area enter/leave callbacks also affect gameplay objects.
1. **Bound render candidates:** index fixed, live, and expanded-glob items by world chunk or another measured spatial structure. Query the camera's visible world bounds plus an overscan margin; keep this render set separate from gameplay activation and process scheduling.
2. **Cull before sorting:** compute conservative projected frame bounds, reject candidates outside the viewport clip before decoded-frame misses and dependency comparisons, and retain final per-pixel clipping. Preserve Crusader-specific overlap/order rules and add regressions for tall sprites, roofs, transparency, flipped frames, inventory items, and player overlays.
3. **Reuse per-frame work:** reuse display-list, node, dependency, and frame-cache storage. Invalidate cached geometry/order on position, frame, flag, roof, glob-hatch, or world-mutation changes. Measure candidate counts, clip rejects, sorter comparisons, allocations/cache hits, and collection/sort/raster/presentation time before selecting an indexed-frame or palette-expanded cache policy.
4. **Separate camera projection:** represent camera position and zoom independently of avatar/world state. Centralize world-to-screen projection and its inverse; derive the queried world bounds and sprite clip bounds from viewport dimensions and zoom. Keep HUD and window controls in screen space. Preserve a pixel-art-friendly sampling policy and test zoom limits, viewport resize, and edge clipping.
5. **Add optional smooth follow:** keep the recovered/legacy camera behavior as the parity mode and add a selectable host-only smooth-follow mode. Interpolate camera position using elapsed time toward a configurable target/offset, independent of the fixed simulation tick; apply zoom around a stable screen anchor so zoom changes do not jump the avatar. Camera motion must not alter gameplay coordinates, animation state, or simulation tick counts.
6. **Integrate animation and presentation:** choose animation frames from simulation state and render interpolation without blocking camera updates on a full-scene rebuild. Keep mutable/player animation responsive while scene candidates are gathered and painted; remove the backing-image recenter dependency from the normal viewport path only after the live path meets parity and performance gates.
Exit criteria: deterministic tests cover camera projection/inverse bounds, zoom in/out and resize, smooth-camera convergence at different frame rates, and unchanged world/avatar state under camera-only motion. A retail map regression checks item ordering, clipping, animation, and screen-edge behavior at minimum/default/maximum zoom. Profiling demonstrates bounded candidate/sort work and no camera-induced animation stalls. The smooth-follow mode remains opt-in and is documented as a modernization, not original-binary parity.
### Phase 6: USECODE / VM Runtime
Goal: execute game scripts from original `EUSECODE.FLX`.
Current foundation: `UsecodeProcessTask` already tracks class/event identity, bytecode PC, process frame, value stack, and nested routine/call frames. The context factory also models owner/source pointers in emulated runtime memory. Opcode support remains partial, so this is a VM foundation rather than full execution or debugger parity.
Work:
- import and type `EntityVmRuntime`, owner-resource, context, and slot-entry families
- parse usecode chunks and dispatch tables
- implement VM value stack, globals, calls, and event dispatch
- add an optional debugger state derived from VM tasks: unit/class/event, bytecode PC and available line metadata, source cursor, frame/evaluation context, and a balanced current-entry stack across nested calls and returns
- implement breakpoint and single-step hooks against that structured state; emulate segmented pointers only where binary parity requires them
- add descriptor/watch evaluation only as the corresponding source metadata and VM services become supported
- cross-check against existing usecode extraction tools
Exit criteria: selected map triggers and object interactions execute through the host VM with traceable parity against known extracted usecode behavior. When debugger support is enabled, supported instructions produce deterministic line/call-stack snapshots and balanced entry/return transitions; unsupported opcodes and unavailable source metadata are reported rather than guessed. This does not claim full watch/inspect or original VM parity until descriptor evaluation and required runtime services are implemented.
### Phase 7: Gameplay Systems
Goal: make core No Remorse gameplay work.
Work:
- actor movement and animation
- combat tactic interpreter from `COMBAT.DAT`
- projectiles and hit resolution
- inventory/equipment
- doors, elevators, panels, triggers, movable walls
- save/load state
Exit criteria: a small scenario can be played end to end with movement, combat, interaction, and persistence.
### Phase 8: Media And Presentation
Goal: reach production game flow rather than only a debug map runner.
Work:
- menu/frontend flow
- fonts/gumps/icons/HUD
- music/audio mixer
- flic/movie playback
- cutscene and mission transition behavior
Exit criteria: the host build can boot through a recognizable frontend and enter gameplay using retail resources.
### Phase 9: Whole-Game Integration And Parity
Goal: turn subsystem success into a working game.
Work:
- mission progression
- all retail maps/resource variants
- error recovery and missing-data handling
- deterministic trace comparisons for high-risk systems
- long-run smoke tests
Exit criteria: the game can be started, played across mission transitions, saved, loaded, and exited on modern Windows.
### Phase 10: Packaging And Modernization
Goal: make it usable outside the development repo.
Work:
- data-root picker or command-line root selection
- per-user config/save directory
- release build profile
- crash logs
- user documentation
- optional quality-of-life settings that do not obscure parity bugs
Exit criteria: a clean checkout/build can run against a retail data directory with documented setup steps.
## Historical Implementation Evidence
Partial process and item ports below are retained as technical evidence, not as the active work order. Follow **Near-Term Next Actions** for current priorities.
| Exported function | Compiled status | Evidence and remaining boundary |
|---|---|---|
| `FUN_11d0_0255` (`11d0:0255`) | Normal-process scan and timer wake translated; harness callback invokes compiled Stand `Run`, tests cover sleep/wake and scheduler gates | Live `11d0:02b4-03ac`: skip terminated, process sleep via `11e0:0379`, clear `Proc_Syncing` for one pass, skip nonzero `+0x24/+0x26`, `Proc_Waiting`, and off-group entries unless daemon or group 30/31; set current ID around vtable run call. Host receives an explicit timer tick, uses the original strict `start+duration < tick` wake comparison, and recognizes Stand's verified no-op completion slot (`1100:0fe3`); other completion targets remain unsupported. Immediate timer/keyboard interrupts, early-stop/group advance/table-maintenance tails, and general vtable dispatch remain unported. |
| `Kernel_11d0_19b5` (`11d0:19b5`), `Kernel_11d0_0445` (`11d0:0445`) | Active-group writer and empty-group highest-ordinary-group selection translated; invoked after diagnostic scans in harness/window, CTest checks change flag and groups 30/31 exclusion | Exported globals initialize active group `DS:39c9` to 1 and pending byte `DS:39a2` to 0. Writer marks pending only when group changes; selector scans all occupied process slots (including terminated entries until cleanup), ignores groups 30/31 for the maximum, then clears pending. Host rejects invalid group IDs and uses explicit group counters; original group-table allocation, mid-scan early stop, and runtime traces remain unported. |
| `Item_CreateProcess` (`10a0:0020`), `ItemProcess_Run` (`10a0:0078`), `Item_Release` (`10a0:2a06`) | Owned 0x32-byte item process constructed and advanced by the scheduler from a staged retail map record; release request, event-body queueing, task state, termination, and presence cleanup are exercised by the diagnostic host | Live disassembly confirms function-table root `0x102f`, item number at `+0x04`, event type `0xf1` at `+0x06`, then `Item_Release` followed unconditionally by the vtable terminate slot. The host callback receives mask `0x200` and `UC_Release` ordinal `9`, resolves an eligible retail body, and queues it in the host VM task registry. Only supported opcodes/services execute; unsupported paths halt the task. This remains a diagnostic trigger, not the original `Item_Grab` path; child teardown and general vtable dispatch remain unported. |
| `Item_GetUsecodeClassId` (`1420:0dc5`), `Usecode_ItemCallEvent` (`1420:0e3a`) | Class selection and owner-row event-mask gate translated into `remorse_core`; retail and synthetic CTest checks, harness/window release selection, and host task execution | The item selector chooses regular shape, NPC number plus startup NPC base `0x800` (unless status bit 1), or unknown-egg quality plus startup base `0x900`. FLEX entry 1 supplies 13-byte owner rows (size callback `1220:01bb`, materialization callback `1240:02a8`). The diagnostic host resolves the selected release body and runs it through the subset VM. This is not the original `Usecode_ItemCallEvent`/`CreateFromSlotIndex` dispatcher or `EntityVmContext`; classless map items remain valid, and the first staged map-1 item (shape 16) has no matching class. |
| `Process_Sleep` (`11e0:0320`), `EntityDispatchEntry::Unlink` (`11e0:0353`) | Flag and 32-bit timer writes/clear translated; exact byte offsets and wake deadline tested | Live sleep ORs `0x1000` at `+0x18`, snapshots timer into `+0x0a/+0x0c`, writes duration to `+0x0e/+0x10`; unlink clears the flag and those four words. Host receives a tick instead of reading the original timer-process pointer. |
| `NPCActionProcess::Create` (`1100:0000`), `StandProcess::CreateProcess` (`1100:02ed`) | Owned 0x42-byte Stand entry registered and run in harness; constructor fields, item number, and presence-bit transitions tested | Live chain stamps `+0x16 |= 0x300`, clears derived words `+0x32..0x3e`, stores NPC number at `+0x40`, ORs `0x101` at `+0x32`, sets Stand vtable `0x1f0f`, process name `Stand`, and event `0x258`. Host marks the item bit on registration and refreshes it after terminating a zero-child-state Stand, following `Item_MarkProcessPresent`/`Item_RefreshProcessPresenceFlag` (`11d0:3e0b/3e7f`). Item animation/cache reset, nonempty child-list destruction, and real NPC item ownership remain unported. |
| `NPC_StartBehaviorInField0x8IfCanSeeControlledNPC` (`1100:026e`), `StandProcess::Run` (`1100:0359`) | Compiled NPC decision/Stand run branches; tests cover off-screen sleep, visible behavior start, already-current sleep, and strict wake | Live `1100:0274-02e9` reads NPC number from `+0x40`, tests entirely-on-screen, nonzero field-8 activity, not-current activity `0x71`, can-see-controlled-NPC, and starts the next behavior; `1100:035c-0382` sleeps 60 on false. `1478:1f0f` starts with far `Run` pointer `1100:0359`. Host services supply visibility/activity/item effects and timer tick; no real NPC item, general vtable resolver, or binary trace parity. |
| `SystemTimerProcess_CreateProcess` (`11c0:0000`), `Process_RegisterForTimerEvents` (`11e0:19ba`), `Kernel_RegisterProcForTimerEvents` (`11d0:2dd8`), `SystemTimerProcess_Increment` (`11c0:00f8`) | Partial 0x4a-byte owned constructor and registered counter linked to harness and Windows diagnostic scheduler; zero initialization, 16-bit carry, uniqueness, process flags, registration gate, and strict Stand wake boundary tested | Exported `ConstructVtable3AD2/3AA6` (`11e0:14fb/1814`) sets interrupt/realtime flags and zeros the periodic tail; constructor stores period `0x3c` at `+0x36`, tail bit `2` at `+0x32`, and waiting/daemon/active-counter flags. Registration sets `Proc_GetTimerEvents` (`0x400`) and records the process ID; host delivery requires both. Increment carries from `+0x40` to `+0x42`. Original randomized reschedule, event type, active-counter globals, general timer list/dispatch, DOS interrupt source, and general timer teardown remain unported. |
| `KeyboardProcess_CreateProcess` (`11b8:02e1`), `Process_RegisterForKeyboardEvents` (`11e0:172a`), `Kernel_RegisterForKeyboardEvents` (`11d0:3b74`), `Process_SetKeyboardInterruptFlag` (`11e0:17a4`), `KeyboardProcess_HandleKeyEvent` (`11b8:03ad`) | Partial owned 0x36-byte keyboard process registered by harness and diagnostic window; layout, flags, singleton, exhaustion, teardown refusal, and accepted/rejected callback copies tested | Inherits `ConstructVtable3AD2` (`11e0:14fb`) interrupt flag `0x100`, registers `ExtProc_KeyboardEvents` (`0x80`) once, sets `Proc_Waiting|Proc_Daemon` (`0x3`) and `ExtProc_KeyboardInterrupt` (`0x100`). Live disassembly at `11b8:03c5-0418` and bytes `11b8:041a-041f` confirm filter pair `0x10,0`; a nonzero character and field `+0x08` copy 12 bytes from `g_lastKeyEvent` to the supplied event and clear tail `+0x32 & ~0x10`. Window `WM_CHAR` supplies a host-synthesized event for the diagnostic count only; original callback registry, key event queue, modifier state, and player-input routing remain unported. |
| `KeyDaemon_CreateProcess` (`11b8:0000`) | Partial owned 0x40-byte constructor invoked after keyboard registration in harness and window; layout, singleton, and teardown refusal tested | Inherits `ConstructVtable3AD2/3AA6` (`11e0:14fb/1814`) interrupt/realtime flags `0x300`, sets `Proc_Daemon|Proc_Waiting` (`0x3`), `Proc_ImmediateTimer` (`0x2000`), timer-event bit `0x400`, derived tail `+0x32 |= 2`, and period `0x2d` at `+0x36`. The randomized schedule, timer list dispatch, held-key repeat callback, and DOS input state are not linked. |
Live Ghidra MCP decompilation and disassembly have resolved local stack ABI, scheduler gates, and call order, not runtime state parity. Do not promote the Stand harness trace to gameplay behavior until its host-supplied NPC services and remaining tick services can be checked against execution.
`Kernel_InitProcessTables` (`11d0:1aae`) allocates and clears the separate `DS:3a04` presence bitmap (`0x480` bytes) and `DS:3a08` process-type bytes (`0x2400` bytes), as confirmed in the live NE decompilation. These lookup tables index item IDs through `0x23ff`, even though the item cache initialized by `ItemCache_InitAndLoadFixedDat` (`10a8:163a`) has a wider free-item range. The host kernel now rejects source/NPC item IDs above the lookup-table limit before changing process state; the Windows diagnostic reports an out-of-range candidate rather than queuing it. This is a bound for the modeled process tables, not an assertion that the whole item cache stops there. Tests cover `0x23ff` and `0x2400`. `Kernel_Init` (`11d0:000c`) calls the table initializer before registering timer and keyboard processes, but its DOS interrupt, real-segment, and mouse setup remain unported.
The exported free-item path can issue `0x2400` from its `0x100..0x27ff` range, and a staged synthetic map reaches that ID; retail map 1 remains inside the kernel lookup limit. Exported `SetSourceType` (`11e0:01b6`) calls the presence/type-table writers without a visible range guard. This does not prove how a live run handles such an ID: preserve the host guard and investigate the original allocation/use path before allowing out-of-range process ownership.
`FUN_11d0_31cf` (`11d0:31cf`) is a caller of the scheduler scan at `11d0:0255`. Its one-pass prefix snapshots the registered SystemTimer, scans runnable processes, then invokes an optional callback. The host compiles and calls that ordered pass from the harness and Windows diagnostic, returning elapsed ticks after the callback; tests verify that a timer event delivered by the callback cannot wake a process in the already-started scan. At the end of the scan, the host now reproduces the source group transition: if the active group has no live processes, select the highest occupied group except 30/31, set the pending flag only on change, then clear it as `Kernel_11d0_0445` (`11d0:0445`) does. The original infinite loop, interval wait, DOS interrupt delivery, `11d0:04cd` resize maintenance, and runtime group-transition parity remain unported or unverified.
The first search-side dependency is compiled and tested in isolation: `ItemFind_10c0_14c9` (`10c0:14c9`) classifies a candidate as match type 1 (candidate Z equals origin top) or type 2 (candidate top equals origin Z), using TYPEFLAG-derived footprint widths and height, with type 1 taking priority. The host receives staged item fields and decoded shape metadata explicitly. This is **not** a complete port of `ItemFind_StartSearchAroundItem` (`10c0:0f73`) or the `10c0:1637` iterator; live item state and general loop-script evaluation remain absent, and the classifier is not used to select a window item.
The area-search setup translates the rectangle around the origin (`10c0:0f73`), signed-coordinate normalization (`10c0:1099`), and `64 x 64` block order with 512-unit cells (`10c0:072e/0c50`). `ItemCache_10a8_00a0` (`10a8:00a0`) inserts directly placed records at the head of each block's `g_itemNext` chain, and the `10c0:1637` iterator follows that chain before advancing blocks. The staged host now reconstructs those heads/links from non-contained item records, rejects duplicate/out-of-range IDs and coordinates, and visits candidates in source block order. Synthetic tests distinguish chain order from record order; retail map 1 yields eight staged candidates in four search blocks around the first item.
A separate diagnostic applies the exported Z/footprint classifier in chain order, yielding one script-free match for the retail origin with both Z flags enabled. Live `Item_Grab` (`10a0:2970`) pushes script pointer `DS:102d`, script length **1**, and Z flags **3**; callee `10c0:0f73` reads the flags at `[BP+0x12]`, correcting misleading export parameter names. The byte at `DS:102d` is `$`, which selects the `0x5000` fast iterator in `ItemFind_AreaSearch2` (`10c0:1099`). Live `10c8:0385` walks item-next links and X-first blocks, accepting only candidates whose X/Y coordinates lie inside the inclusive search rectangle, before the Z classifier. The host's bounded `Item_Grab` search applies these gates to staged, directly placed items; a test excludes an out-of-rectangle item whose footprint would otherwise pass. Retail map 1 yields one candidate for its first staged item.
Contained placement has a separate source-derived diagnostic: for nonzero maps, nonempty contained records consume free IDs, encode nesting depth in the fixed-record X field, ascend the parent link when depth falls, and append children only to container/monster-egg families (`10a8:05e3`, `10a8:2533`, `10a0:0e32`). Synthetic nested/sibling and invalid-parent tests pass; retail map 1 contains no nonzero-shape contained records, so it cannot verify those links. The stage is not a live container cache or a runtime ID-order trace. The shape loader exposes TYPEFLAG row byte 7 as weight, and the `Item_Fall` (`1038:1334`) gate requires a drawable, nonzero-weight shape. The action planner preserves `Item_Grab`'s type-1 fall versus type-2 flag-checked process decision in source order; the first retail origin produces zero actions.
The bounded staged dispatcher can now issue those actions against the host process kernel. `Process_GetProcessForItemAndType` (`11d0:13a4`) scans live slots from 3, ignores terminated entries, and supports item/type wildcards; the host mirrors those rules. `Item_Hurl` (`1038:12a6`) reuses an existing type-`0x203` gravity process and adds velocity, or creates a `0x42`-byte process (`1038:0395`) with zero velocity, gravity 2, and a 20-tick sleep for a fall request. Tests cover both branches, duplicate item-process requests, strict wake, ownership and ID-limit rejection, and teardown/reuse. Staged dispatch rejects any out-of-range action before starting; the Windows `F` key is still a separate release fixture. A host-owned `LiveFixedMapItems` copy now supports ID lookup, bounded position changes, and `Item_Grab` dispatch against current item positions; the window owns this copy for nearby-item lookup. `Item_LegalMoveToPointWithCollisionInfo` (`10a0:1841`) calls `Item_Grab` before `AreaSearch_CollideMove` on its successful path; `moveApprovedItem` preserves that ordering once a caller has approved the move, and tests distinguish old-position requests from post-move search. Synthetic move/dispatch and retail-map ownership tests pass. This is not the original item cache, does not yet provide a legal-move collision event or update rendered sprites, and does not include live contained items. `runUnobstructedGravity` moves an owned item and advances/sleeps its owned process in the nonzero-vertical-speed branch after explicit caller-supplied approval of the full pre-sweep target. A refused or missing sweep makes no mutation on that path. On the zero-Z horizontal path, it requests `Item_Grab` before sweep approval, so a refused sweep may still leave a process request. The stationary zero-speed fall search, collision responses, live fast-area state, and automatic scheduler tick remain unported. The original `AreaSearch_SweepTestItem` (`10e0:1151`) forwards into `AreaSearch_SweepTestPt` (`10e0:0b39`); the host has bounded fast-area and item-iterator gates but not resolved collision points. Runtime ID and search-order parity remain unverified and are not a current gate.
The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied item IDs can also be inserted at a block head. The host free-ID allocator uses the source `0x100..0x27ff` range, skips staged direct and contained records, and fails without mutation when exhausted. The window reserves staged contained IDs and retains their parent links; placing one in the world clears its parent while its children remain linked. Synthetic nested/exhaustion and retail-map tests pass. A follow-up item-cache slice now models returned IDs as a LIFO free list (`ItemCache_10a8_1aef`, `10a8:1aef`), initial contained sibling order (`ItemCache_PopToEnd`, `10a8:2533`), family-6 head insertion (`ItemCache_PopToContainer`, `10a8:2369`), and transfers that preserve nested children. Release refuses active-process ownership, nonempty items, hatched glob eggs, and IDs above the `0x23ff` process-table boundary. Synthetic tests cover sibling ordering, cycle rejection, process ownership, and free-ID reuse. Runtime parity, cache-status/fast-area effects, family-7 transfer, and viewport writes remain unverified.
The supported horizontal `GravityProcess_Run` path now issues `Item_Grab` at the old item position when Z speed is zero and X/Y speed is nonzero, then asks the injected sweep to approve movement. As in the source order, a refused sweep can leave a newly requested item process behind while the item stays put. The earlier no-mutation guarantee for a refused sweep applies only to the nonzero-Z path, which does not issue that request. This callback-based unobstructed runner does not handle the stationary zero-speed fall search or collision response; a caller must provide shapes, group counts, and sweep approval.
Live `Item_SetQIfContainerType` (`10a0:0f78`) writes a family-6/7 parent quality field to its first contained child, and `ItemCache_10a8_1949` (`10a8:1949`) advances that field when unlinking the head. The host now mirrors the head ID during initial contained staging and runtime head insertion/removal, including nested parents; family-6 and family-7 staging and the quality transitions have focused regressions. This does not port the `Item_PopToEnd` free-item-to-tail path or the separate item-status/fast-area effects.
Live Ghidra decompilation shows that vertical `GravityProcess_Run` impacts use sweep mode 4, then `AreaSearch_CollideMove`, and branch on `Item_IsCurrentControlledNPC` plus masks from the separate `g_itemStatus` table. Those branches include callback/termination paths and controlled-item rebound behavior using `RandomVal`; collision movement can also create hit/got-hit storage processes. `FixedMapEntry::flags` is not a verified substitute for `g_itemStatus` and already carries modeled fixed-item flags such as flip. Keep vertical response, status/cache writes, and collision-event creation deferred until those runtime states and side effects are represented.
The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. The source's `World_MapBlockInFastArea` (`10a8:0000`) rotated block predicate and eight-corner start/destination footprint gate are testable with an explicit fast-area range. `World_CalcFastAreaLimits` (`10a8:0048`) now supplies the source sum ±5 / difference ±3 block window from a world center. The window refreshes a player-centered host range after movement and dispatches any owned gravity processes through its timed scheduler; it still does not create gravity entries or repaint moved map items in the static preview. The sweep's item-iterator rectangle and live candidate query follow inclusive X/Y filtering and Y-then-X block order. The per-item sweep uses 16-unit X/Y extents, 8-unit Z extents with the source zero-height fallback, and six axis-face tests that report one-unit-before-contact points and failed-direction bits. A read-only live collector combines those tests with candidate order, shape solidity and flip flags. The host selects a solid hit in source order when any axis is strictly closer, retains the earlier hit on a tie, and accumulates direction bits across contacts. Damaging-only face contacts are recorded in candidate order without blocking the resolved point. With an explicitly enabled floor-gap limit, the host also identifies the closest solid support beneath the destination footprint for source limits 0 and 9; this support metadata does not change the destination. The resolved sweep now reports fast-area failure at the original point with direction bits 1/2 and clamps out-of-range Z with bit 4; the gravity runner conservatively rejects these unsupported responses before mutation. `runResolvedGravity` moves an owned item to a solid-hit point after its strict process wake, damps and reverses horizontal speed on collision, and sleeps the process again. `scanResolvedGravity` dispatches this bounded runner through the host scheduler; tests verify a wall impact, a later move away, and no repeat within the same tick. The remaining gaps are vertical collision response, item status/cache writes, collision events, stationary fall search, and an actual window gravity producer and moving-item renderer. Original runtime parity remains unverified.
## First Interactive Windows Game Shell
`rebuild/remorse/out/build/Debug/remorse_game.exe` is the first windowed application target in the Debug configuration. It locates the game data root from its own executable path (or the current directory), defaults to map 1, and accepts either an optional fixed-map index from 0 through 255 or the original-style direct warp options.
The default window now opens directly onto the retail-map traversal test with no diagnostic HUD, synthetic Stand/keyboard processes, or `F` release shortcut. Its map-1 host startup follows the staging egg `0x1e` through active trigger `0x63` to destination egg item 6812 at `(30328, 29656, 16)` before rendering. Pass `--diagnostics` (before or after the map number) to restore the diagnostic harness and its HUD. The map-1 startup midpoint is checked against the same collision bodies as the window, with at least one legal neighboring move. This is a **retail-data movement test**, not yet the real game: the player is host-created, rendering uses a static map preview, movement uses host polling/step policy, and neither the original startup/game loop nor item USECODE/mission interactions are running. Do not use this mode split as the roadmap's playable-game exit criterion.
From the repository root:
```powershell
rebuild\remorse\build_msvc.cmd Debug
.\rebuild\remorse\out\build\Debug\remorse_game.exe 1
```
For a direct coordinate warp, use `-warp <mission> <x> <y> <z> [-mapoff <delta>]`. The target map is the retail mission-table base plus the offset; the coordinates are staged world coordinates, and the normal map-1 teleporter startup is bypassed. This verified command starts on map 1 at the chest/computer test area:
```powershell
.\rebuild\remorse\out\build\Debug\remorse_game.exe -warp 0 30463 29951 0 -mapoff 1
```
The window title reports the resolved map and direct coordinates. Coordinates must be X/Y `0..32767` and Z `0..255`.
The application builds the selected retail map scene and player assets on a worker thread, then displays a resizable Win32 window with the game palette and dependency-sorted map art. Shape 1 uses `ANIM.DAT` actions 0 (stand), 1 (walk), and 3 (unarmed run); frame metadata selects the `SHAPES.FLX` pose, horizontal flip, and movement delta. The original keypad direction mapping is supported alongside WASD/arrows and diagonal combinations. Shift and Caps Lock select walk/run using the controller's same-state rule. A 40 Hz host simulation tick advances frame steps against fixed-map and expanded-glob solid volumes; it now catches up after long paints instead of discarding all elapsed time beyond 50 ms. The retail signed displacement decoder is unchanged. The prototype's forward-only host movement step skips the small backward stride on walk frames 4 and 12 of directions 6/7/10/11, which had made both actor and following camera reverse mid-stride. This comfort policy and host tick rate are not recovered controller behavior. The persistent GDI back buffer avoids painting each moving frame directly to the window. The opt-in diagnostic HUD shows map, world position, facing, and locomotion state. Collision is an axis-aligned TYPEFLAG approximation; it does not reproduce original AreaSearch shape sweeps or step-up behavior, and the fixed-map record bounds remain the outer movement limit.
The second HUD row is an observable, separate process-runtime diagnostic: the host 40 Hz step delivers a registered SystemTimer event, advances the recovered scheduler scan, and runs an owned Stand entry through its verified off-screen sleep branch. Tick, remaining sleep ticks, and wake count update while the window is active. Three base entries reserve the low process IDs; the Stand entry and NPC number are diagnostic fixtures, not map NPCs or the player process. Host tick frequency is not the original DOS timer interrupt rate.
The diagnostic kernel also registers a partial KeyboardProcess and KeyDaemon at startup. Text-capable Win32 key messages exercise the recovered keyboard filter/copy callback and update the key-event count on the HUD. The daemon does not receive timer events yet. The visible WASD/keypad controls still use host polling; these processes do not yet deliver player input.
### First Map-Derived Item/Process Tick
The Phase 4 diagnostic now stages directly placed, nonzero-shape `FIXED.DAT` records into item-numbered state using the initial free-list head `0x100` and capacity `0x2700` from `ItemCache_InitAndLoadFixedDat` (`10a8:163a`). It skips zero-shape records, accounts for contained records consuming an ID without staging them as world items, and clears the status low bit for directly placed records as `ItemCache_10a8_00a0` does. Map 1 has 7,547 source records; the harness constructs an `ItemProcess` for the first eligible staged record (shape 16, diagnostic ID 256), advances a scheduler tick, records the `UC_Release` request, and verifies the process is removed. The window waits for `F` near a staged item before scheduling the one-shot path and showing its result on a separate diagnostic HUD row. Retail-data and two-tick regression tests check shape/record provenance, release-request count, process removal, and item-presence/group-count cleanup.
This is an integration checkpoint, **not the Phase 4 exit criterion or a playable interaction**: the host starts this item process as a diagnostic fixture, not via the original `Item_Grab`/search trigger; it selects eligible USECODE bytes but does not create the original VM context, run the interpreter, mutate the item through `Item_Release`, or implement live contained-item placement, shape-flag cache-out, or verified runtime item IDs. The staged direct-placement block chains and separate contained-parent diagnostic are read-only, not a live item cache. Staged X/Y reverse the preview loader's display scale to retain the original fixed-record words. NPC item IDs `1..255` are reserved separately and must not be conflated with staged map-item IDs.
The Windows diagnostic no longer schedules the first staged item on scene load. `F` now selects a staged fixed-map record within 48 world units of the host-controlled actor (nearest in X/Y, using the fixed-record display scale), then runs the existing `ItemProcess` release callback on the next scheduler tick. The HUD reports the candidate and callback result; a synthetic proximity test and the MSVC/CTest gate cover selection and the existing process lifecycle. This is a one-shot diagnostic with no item-type filtering, vertical reach, USECODE event execution, or visible item-state change. Exported `Item_Grab` (`10a0:2970`) uses `ItemFind` search and an item-cache status guard before creating item processes; exported `Item_Release` (`10a0:2a06`) calls `Usecode_ItemCallEvent` with `UC_Release`. Neither original trigger nor the event executor is ported, so this change does not meet the playable-game milestone.
The `Item_Grab` creation branch applies the verified `FUN_11d0_3f95(itemNumber, -0xf)` item-cache flag-1 check to staged item flags before a type-2 process request. Live disassembly at `10a0:29c5-29e3` confirms the branch; a separate search-result type 1 calls `Item_Fall`, whose hurl request now creates or merges a sleeping gravity entry in the host. The Ghidra export's zero-initialized `npcno` loop is a decompiler artifact, not evidence that the search never iterates. The window still uses proximity instead of original `ItemFind`, does not model live item-cache mutations or gravity movement, and must not treat process-presence bookkeeping as the checked item flag.
The first Phase 6 resource slice is compiled into `remorse_core`: a bounded `EUSECODE.FLX` class/name/event-body reader follows the owner-loaded `classId + 2`, 13-byte name-table, `+0x14` six-byte row, and `codeBase + relativeOffset - 1` body rules verified in `docs/raw-000a-000d.md`. Retail tests confirm `EVENT` (`class 0x361`, slot `0x0a`, code base `0xd4`, body length `0x1fd6`) and `RECHFLNS` (`class 0x138`, release slot `9`, body length `102`, owner mask `0x200`). Raw extracted `CARD_NS`, `BOX_NS`, and `RECHFLNS` bodies confirm a 14-byte metadata prefix followed by the first opcode at offset `0x0e`; its exact field meanings remain unknown. The named offset is shared by the host task runner and tested against these retail bodies. Retail integration tests execute `CARD_NS` spawning `SWITCH` and `BOX_NS` through timer yields to a changed item frame and rendered scene. The Windows diagnostic release callback also resolves and queues an eligible body, but this is host-side dispatch and task initialization, not `Usecode_ItemCallEvent` or `EntityVmContext::CreateFromSlotIndex`. The interpreter covers only a subset of opcodes/services, and unsupported operations halt tasks; original context memory, far-pointer execution, general event dispatch, and runtime parity remain open. The recovered `CreateFromSlotIndex` call selects a class/slot and passes a four-byte parameter into `Inter_1418_0244` (`1418:0244`) and `Interpreter_1418_00e8` (`1418:00e8`). Even the short `RECHFLNS` release event branches through item surface-weight logic and `FREE.slot_33`; the current host service table does not complete that path.
The Windows controller slice now consumes queued key events through the registered host keyboard-process subscription. It preserves the original event-mode (`KeyEvent +0x08`) and press/release (`+0x09`) bytes, translates Shift/Caps Lock and Alt/Ctrl modifier bits, and implements the recovered Num Lock-off eight-direction mappings plus Num Lock-on relative turns and facing-aligned forward/reverse requests. Walk/run selection follows `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. The current action subset maps the recovered Alt/Ctrl animation indices, loads the corresponding player clips from ANIM.DAT, advances valid stationary animation frames, and retires one-shot animation processes on clip completion or blocked movement. Focused tests cover event transitions, modifier isolation, Num Lock modes, action selection, and retail clip/frame references. This remains a host controller model: `Controller_PickNextAnimByKeyevent`'s full NPC busy/dead/stasis branches, weapon-dependent paired actions, crosshair/target updates, complete turn handling, original controller process dispatch, vertical jump response, and exact original collision response are not ported. Host 40 Hz timing and map collision remain approximations; the source scheduler does not yet drive this player path.
On Windows, `remorse_game.exe`, `remorse_rebuild.exe`, and `remorse_map_preview.exe` configure crash reports at startup. All CTest binaries now link a test-only startup initializer for the same diagnostics, so an assertion before `main` cannot open an Abort/Retry/Debug modal that blocks the build terminal. The timeout-bounded child probes exercise both a Debug CRT assertion and C++ termination, verifying prompt-free nonzero exits. The terminate handler reports active C++ exception messages to the Visual Studio Debug output and stderr when available. Escaped/unhandled Windows exceptions log their code/address and suppress the fault popup. The GUI executable has no console stderr by default, so attach a debugger to see that output. This does not replace a full crash dump or catch process termination that bypasses user-mode handlers.
This is the first interactive gameplay slice, not yet a playable game: movement uses approximate host collision rather than the original actor response, and there are no live enemies, triggers, sound, saves, or USECODE execution. The rendered map is the retail static scene, not a live simulation.
The `Controller_HandleKeyEvent` (`1130:2211`) prior-fire-sleep guard is now a dedicated compiled `remorse_core` slice: when that state is true, nonzero-mode Space events and Ins releases are suppressed, while Ins presses remain eligible. Focused tests cover the condition matrix. The Windows loop does not yet populate the state because `Crusader_TryToFireWeapon` and the original global-state update path remain unported, so this closes the gate implementation but not runtime weapon firing parity. The busy in-place-turn model also remains incomplete: `Anim_1130_0f94` (`1130:0f94`) rate-limits walk/run direction updates when `1478:6046` is set, using the system timer and mouse-speed configuration; the host does not yet model that state or throttle.
## Import-Slice Tool
The first source-conversion helper is `rebuild/remorse/tools/import_export_slice.py`.
Its job is intentionally modest: copy one folder from `exports/src_remorse/functions/` into ignored staging output under `rebuild/remorse/imported/`, rewrite Ghidra's direct `CRUSADER.EXE.h` include to `remorse/export_prelude.h`, convert known 16-bit calling-convention tokens to compatibility macros, and write an import report listing cleanup signals such as `unaff_SS`, `unaff_CS`, `CONCAT22`, and hidden return-storage parameters.
Example:
```powershell
python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispatchEntry
```
The generated staging files are not linked into `remorse_rebuild`. They are a workbench for turning one exported subsystem into hand-maintained source.
The first run against `classes/Remorse/EntityDispatchEntry` staged 24 files, replaced 62 calling-convention tokens, preserved 46 namespace-qualified references, and reported `CONCAT22`, `unaff_CS`, and `unaff_SS` as cleanup signals.
## Windows Runtime Work Needed
To run on Windows, the rebuild needs replacement layers for these original services:
- process startup and command-line/config parsing
- DOS file APIs and search paths
- Phar Lap / DOS extender memory services
- segmented far-pointer memory model, at least as a compatibility abstraction
- VGA/SVGA video mode setup, palette writes, bank switching, and blitting
- keyboard, mouse, and joystick input
- timer/tick scheduling
- audio device and mixer services
- movie playback and RIFF/audio frame handling
- save/load paths and user-writable data locations
- game data discovery for retail install layouts and repository fixtures
The first Windows runtime should prefer clear host abstractions over direct Win32 calls where possible. SDL or another portability layer is a reasonable later choice for graphics, input, timing, and audio, but that should be selected after the first resource-loading and render smoke tests are defined.
## Recommended First Subsystems
Keep source slices small enough to compile and test while following original call edges, not independently designing a replacement engine.
1. Finish the `EntityDispatchEntry`/`Process` constructor, group-table, and scheduler path, including its globals and kernel calls; `SetGroupId` alone is only a partial foothold.
2. Trace original startup and tick entrypoints into the process/player call chain, recording each address and the exact host service boundary it reaches.
3. Port resource/file functions actually called by that chain, mapping only DOS-facing calls to the existing host file service.
4. Port the original item/draw-list and render functions that consume the live process state; reuse decoded retail assets as parity fixtures.
5. Lift the input, movement, interaction, and VM calls reachable from the playable path, replacing prototype logic when original code becomes available.
## First Hand-Maintained Game Skeleton
The first manually maintained game-shaped source is `EntityDispatchEntry`.
Current evidence used:
- live export folder: `exports/src_remorse/functions/classes/Remorse/EntityDispatchEntry/`
- base initializer: `InitBase@11e0_0000.c`
- older note anchor recorded in the decompiler comment: `0008:ba00`
- allocation size visible in the decompiled initializer: `0x32` bytes
The current rebuild skeleton preserves the 0x32-byte object size, translates group-ID counter transitions, and translates the table word stamps, scalar writes, and group-seed call from base init. A host-owned path now registers and reclaims itemless entries with first-free IDs, allocation-size/name bookkeeping, and the post-registration sync predicate. Source/item update and event/proc-type update remain stand-ins. The first confirmed offsets are: source item at `+0x04`, event/proc type at `+0x06`, and group ID in the low five bits at `+0x08`. The remaining item callbacks, kernel branches, and scheduler must be lifted before the process family can drive gameplay.
## First Windows Runtime Shim
The first platform-replacement layer is a host file-system shim.
Current behavior:
- inspects a candidate root for `CRUSADER.EXE`, `CRUSADER.CFG`, `STATIC`, and `USECODE`
- walks upward from the current directory until it finds a usable game-data root
- resolves game-data-relative paths case-insensitively for ASCII DOS-style names
- blocks parent traversal through `..`
- reads binary files into host byte buffers
- reports the root path from the host harness
- adds a CTest target that expects the repository root to contain the retail executable and data folders, then reads `STATIC/GAMEPAL.PAL`
This starts replacing the original DOS install-directory assumptions with explicit modern path discovery. It is intentionally narrow; file handles, writable save paths, and retail/install-layout variants are still to come.
## First Data Parser
The first parsed retail data asset is `STATIC/GAMEPAL.PAL`.
Current behavior:
- resolves `STATIC/GAMEPAL.PAL` through the host file-system shim
- requires exactly 768 bytes
- parses the file into 256 RGB triples
- reports the parsed color count from the host harness
- validates the path through `palette_tests`
This gives the future renderer a tiny but real data pipeline: host path discovery, binary load, format validation, and typed in-memory representation.
## First Archive Parser
The first archive parser handles the standard Crusader FLEX directory used by files such as `COMBAT.DAT`, `GLOB.FLX`, `SHAPES.FLX`, and `EUSECODE.FLX`.
Current behavior:
- reads the entry count at file offset `0x54`
- reads 8-byte directory rows at file offset `0x80`
- treats rows as little-endian `<u32 offset, u32 size>`
- skips empty rows and rejects out-of-file entries
- extracts individual populated entries by index
- validates `STATIC/COMBAT.DAT` as 14 populated records with entry 0 named `Dumb`
This is the first reusable loader shared by AI tactics, glob objects, shapes, and usecode archives.
## First Typed Archive Consumer
The first typed FLEX consumer is `COMBAT.DAT`.
Current behavior:
- loads the outer FLEX directory through `loadFlexArchive`
- parses each populated record's 16-byte NUL-padded tactic name
- reads four little-endian block offsets
- exposes the remaining bytes as tactic bytecode
- validates the shipped archive as 14 tactics, with entry 0 named `Dumb` and block offsets `0x002c` / `0x0031`
This is not yet the combat bytecode interpreter, but it establishes the pattern for moving from raw archive chunks to typed subsystem inputs.
## First Fixed-Map Loader
`FIXED.DAT` is now the next typed world-data input.
Current behavior:
- reads the map count at file offset `0x54`
- reads 8-byte map table rows at file offset `0x80`
- treats each row as little-endian `<u32 offset, u32 size>`
- parses 16-byte fixed-item records into typed fields
- applies the verified Crusader coordinate scale: disk `x/y * 2`
- validates all map table rows parse, at least one map is non-empty, and out-of-range map indices are rejected
This is the first step toward a host-side map scene assembled from retail data.
## First Glob Loader
`GLOB.FLX` is now parsed as the companion object-expansion archive for fixed maps.
Current behavior:
- loads the outer FLEX directory through `loadFlexArchive`
- reads each glob object as `u16 count` followed by repeated 6-byte entries
- parses each entry as `x:u8`, `y:u8`, `z:u8`, `shape:u16`, `frame:u8`
- validates the archive contains at least one glob object with entries
This prepares the next step: expanding fixed-map glob eggs into concrete world objects using the coordinate rules in `docs/map-rendering.md`.
## First Typeflag Loader
`TYPEFLAG.DAT` is now parsed as the shape-family metadata source needed by map expansion and rendering.
Current behavior:
- requires 9-byte records
- decodes the 20-bit typeflag field using the same byte layout as the Python map renderer
- decodes shape family, footpad dimensions, and animation type
- validates the shipped file contains 2,048 shape records and includes glob-family shapes
This is the shape metadata layer needed before fixed-map records can be classified as drawables, glob eggs, triggers, roofs, editor objects, or other family-specific runtime objects.
## First Shape Decoder
`SHAPES.FLX` is now parsed as the first renderable art source.
Current behavior:
- loads the outer FLEX directory through `loadFlexArchive`
- parses the Crusader shape header and 8-byte per-frame table
- reads 28-byte frame bodies, per-line RLE offsets, frame dimensions, and draw offsets
- decodes row RLE into transparent-or-palette-index pixels
- validates the shipped archive can decode at least one visible frame
This completes the remaining Phase 2 requirement needed for a minimal map image: fixed records, glob records, shape metadata, palette, and decoded shape pixels.
## First Visual Preview Renderer
Phase 3 now has its first concrete artifact: `remorse_map_preview` writes a 24-bit BMP preview using only the source-port rebuild code and the shipped retail data.
Current behavior:
- defaults to map 1, the first non-empty fixed-map table entry in this data set
- expands first-level glob eggs using `GLOB.FLX`
- filters hidden marker/egg/roof families by default, matching the offline map-rendering workbench's first-pass policy
- decodes visible `SHAPES.FLX` frames and paints them with `GAMEPAL.PAL`
- writes a dependency-free BMP image under `rebuild/remorse/out/preview/`
Validated preview:
- command: `rebuild\remorse\out\build\Debug\remorse_map_preview.exe rebuild\remorse\out\preview\map1-preview.bmp 1`
- output: `rebuild/remorse/out/preview/map1-preview.bmp`
- image size: 1600x900
- raw fixed records: 7,547
- render items after filters/globs: 15,318
- decoded items: 15,318
- painted items in the preview crop: 178
- full scene bounds: 30,977 x 15,617
This is still a smoke renderer, not the final game renderer. It now derives world boxes from `TYPEFLAG.DAT`, resolves overlapping sprite bounds with the engine-style dependency graph, and applies the recovered `below()` ordering and occlusion rules. Runtime-only sprite sorting and specialized cases remain outside this host preview.
The next renderer work is to validate window presentation and roof/hidden-object policy, then replace the debug marker with recovered player art and process behavior.
## Immediate Build Loop
The first chosen Windows toolchain is Visual Studio Build Tools plus CMake. That means the expected compiler is MSVC `cl.exe`, usually reached through a Developer PowerShell or Developer Command Prompt.
Until CMake and MSVC are available in PATH, the source scaffold can be edited and syntax-checked by VS Code, but it cannot be built locally from this shell.
Current local toolchain finding:
- `vswhere` selects the registered Visual Studio Community 2026 installation at `C:\Program Files\Microsoft Visual Studio\18\Community`; the existing `out/build` cache points at an older `I:\Apps\VS\18\Community` path that CMake cannot resolve as an installed instance.
- `vcvars64.bat`, MSVC `19.51.36246.0`, and VS-bundled CMake `4.2.3` are usable through the registered Visual Studio developer environment.
- Plain `cmake` is still not available before the Visual Studio environment is initialized. `build_msvc.cmd` initializes MSVC with `vswhere`/`vcvars64.bat` and configures the Visual Studio build under `out/build`.
### Host Harness
From `rebuild/remorse/`, the intended host build loop is:
```powershell
cmake -S . -B out/build
cmake --build out/build
ctest --test-dir out/build -C Debug --output-on-failure
.\out\build\Debug\remorse_rebuild.exe ..\..\exports\src_remorse\export_manifest.json
```
For single-config generators, the executable may be under `out/build/remorse_rebuild.exe` instead of `out/build/Debug/`.
From the repository root, the repeatable MSVC path is:
```powershell
rebuild\remorse\build_msvc.cmd Debug
```
The wrapper reuses the Visual Studio generator tree under `rebuild/remorse/out/build/`; configuration-specific executables are written under `out/build/Debug/` or the selected configuration directory.
### Staging One Export Slice
From the repository root:
```powershell
python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispatchEntry
```
## What Is Done
- **Build foundation:** `remorse_core`, the Windows game, MSVC/CMake build entry point, and focused CTest targets are in place.
- **Retail data:** loaders cover the resources used by the current map, rendering, item, and USECODE slices. The preview renderer and Win32 window remain diagnostic infrastructure.
- **Process and world state:** partial scheduler/process behavior, staged item placement/search, and selected item-cache operations are compiled and tested. The host does not yet run the original game loop or item runtime.
- **Teleporter startup slice:** live Ghidra evidence confirms `TeleporterProcess` is `0x36` bytes, with vtable `0x0f3a`, target map at `+0x32`, and egg ID at `+0x34`. The host kernel owns this typed process and models its same-map run by resolving a family-8/frame-1 destination whose quality low byte matches the requested ID, then moving item 1. It also models the `0x33`-byte clear-avatar-stasis process and one wait dependency: the first scheduler scan clears prior stasis, and the next runs and retires the teleporter. A retail regression verifies item 1 stays at the origin until the wait completes, then reaches egg `0x1e`. This is not the original `Process_WaitFor` linked-list implementation or `Game_Start`; cross-map camera/NPC setup, collision/fall, sound, and original scheduler dispatch remain unported.
- **USECODE:** class/event parsing, a tested opcode subset, task lifecycle, and bounded `CreateFromSlotIndex` context construction are implemented. The window's use request now searches nearby item candidates, applies owner-row event selection, creates a context-backed task, and mirrors the context bytes into the process entry. A retail `BOX_NS` regression follows candidate search through context ownership and VM execution, checks six frame transitions and a rendered pixel change, then verifies output-pointer and allocation cleanup. This remains host-side dispatch with fixture-provided VM services, not original dispatcher parity or a verified interaction from the map-1 spawn.
- **Runtime chunks:** the host now models the 0x16-byte `UProcess_1420_0000` record, bounded far-memory allocations for chunk/process buffers, the doubly linked loaded-process list, descriptor-pointer replacement/restoration, and zero-count eviction. Retail `EVENT` and `NPCTRIG` plus a two-node fixture cover load, reuse, release, reload, and unlink behavior. The host materializer reads archive-backed class bytes; parity with the original owner-resource callback and allocator remains unverified.
## Later Scope
After the first source-backed interaction, complete the original player/item loop, save/load, combat, mission flow, audio, frontend, and retail-map coverage. Keep the current preview and window as test hosts until recovered runtime behavior replaces their stand-ins.
## Track B Recovery Work Order
Use this sequence to move the normal Windows launch path from host-modeled behavior back to the intended decompiled-source port. Keep the current executable, data readers, preview, and tests; treat host gameplay implementations as temporary until their original call paths replace them.
2026-10-07 00:20:26 +02:00
### Normal-Path Classification (2026-10-07)
**Step 1 complete:** freeze further host-only gameplay additions to the default path and classify its current implementation. The default executable is `remorse_game`; `--diagnostics` adds separate fixtures and HUD behavior. The table distinguishes translated rules from an integrated original call path. The current CMake target builds hand-maintained `remorse_core` sources; exported function slices remain staging input and are not directly linked.
| Path | Current normal-path implementation | Original path and status | Host boundary and recovery target |
|---|---|---|---|
| Startup and spawn | [`loadSceneAsync`](../rebuild/remorse/src/windowed_game_main.cpp#L471) loads retail data and calls `startFreshGameMapOne` in `remorse_core` for normal map-1 startup; direct warp and diagnostics remain separate. | A fresh-game `Game_Start` slice initializes the avatar, executes the `1/0x1e` teleporter process, and follows the verified active `0x63` level-start trigger. Full `Game_Start`, original `Process_WaitFor` list semantics, and original item/NPC cache initialization are not integrated. | Keep data-root/file access and worker/window notification at the host edge. Replace the staged item and wait-list models with source-derived cache/process state. |
| Tick and scheduler | [`updatePlayer`](../rebuild/remorse/src/windowed_game_main.cpp#L1084) receives Win32 timer/performance-counter events; movement animation advances through a bounded `remorse_core` scheduler pass. | A retail boot-and-tick regression verifies timer delivery, scheduler dispatch, and avatar animation-state advancement. The scan gate/group selector are compiled source-derived slices; `Kernel_11d0_31cf`'s infinite loop, timer interrupt delivery, original keyboard/controller dispatch, and general vtable resolver remain absent. | Keep Win32 timing/input as adapters and continue replacing host callback/process behavior with recovered core dispatch. |
| Input | [`windowProcedure`](../rebuild/remorse/src/windowed_game_main.cpp#L1345) adapts Win32 key-down/up messages into `KeyEvent`s; `remorse_core` now runs them through the source-derived subscriber queue/gates in `kernel_keyboard_interrupt_dispatch.cpp`. | Registration and interrupt fanout rules are partially ported, and a retail test routes an Up event into movement selection before a scheduler tick. The original process-vtable callback resolver and controller behavior remain unported; movement still uses the host `ControllerMovementState` adapter. | Keep Win32 message translation at the host edge. Identify and port the actual game input consumer; do not treat subscriber fanout alone as original player-input parity. |
2026-10-07 00:20:26 +02:00
| Movement and animation | [`updatePlayer`](../rebuild/remorse/src/windowed_game_main.cpp#L1084) drives `ControllerMovementState`, host animation processes, and approximate TYPEFLAG collision against the shared mutable item 1. | Some direction/modifier rules are **translated**, but the original controller/process call chain, actor collision response, and scheduler-driven player update are **stand-ins/unported**. | Keep world rules and input-to-action behavior in the core; replace the step policy and approximate collision with recovered actor, animation, and collision paths. |
| Interaction | [`startNearbyUsecode`](../rebuild/remorse/src/windowed_game_main.cpp#L287) and [`runUsecodeTasks`](../rebuild/remorse/src/windowed_game_main.cpp#L319) still perform host candidate selection, context/task setup, and a bounded VM subset. | A retail regression reaches item 6747 (`CHEST_EW`), dispatches a nested `FREE` event, and verifies shape/frame `1360/0 -> 1355/1` with changed target pixels. Original `Item_Grab` (`10a0:2970`), `Usecode_ItemCallEvent` (`1420:0e3a`), the later `0x70` loot search, and normal-window interaction integration remain **unported**. | Keep archive/resource reads and memory allocation behind host services; replace the regression's host path with recovered search, dispatch, and VM behavior in the core. |
2026-10-07 00:20:26 +02:00
| Presentation | [`paintWindow`](../rebuild/remorse/src/windowed_game_main.cpp#L884) crops a rendered fixed-map image and composites a separately rendered live-player patch; the renderer refreshes that patch and sometimes rebuilds the full scene. | Retail asset decoding and host sorting are implemented, but the original live draw-list, source order, and camera path are **not ported**; this remains preview-style presentation. | Keep pixel buffers and projection platform-neutral; isolate GDI presentation, then replace static-scene recentering with recovered live rendering. |
2. **Prove the source-to-build pipeline (four compiled slices):** `EntityDispatchEntry::SetGroupId` (`11e0:02a8`) and `IncrementGroupId` (`11e0:0405`) live in a separately compiled `remorse_core` translation unit derived from their exported functions. The corrected signatures pass the entry, 32-element group-count table, and `ProcessKernel` explicitly. The host boundary retains exception-based assertion handling; the compiled transitions update the low-five-bit group identity/counts, enforce the active-group and group-29 gates, and notify the kernel so its selection-pending flag changes only when the active group changes. The scan now calls separately compiled partial slices from `FUN_11d0_0255` and `Kernel_11d0_0445`: per-entry run eligibility/one-pass syncing and highest ordinary-group selection. `entity_dispatch_entry_tests` covers these slices and the existing group transition cases. These are four compiled source-derived slices, not full-function translations, general export compatibility, or original-loop parity. The remaining scan iteration, wait/sleep lifecycle, timer and keyboard interrupts, early exit, and process maintenance remain host-owned or unported; the import helper remains staging only.
3. **Restore the original startup and tick path (basic threshold reached):** the normal Windows map-1 loader calls a core fresh-start entry that follows the reduced `Game_Start` path through teleporter `0x1e` and the verified active `0x63` trigger. A retail integration test then delivers a timer event and runs the bounded scheduler pass to advance an animation process owned by that same avatar. This establishes a basic rebuilt-code boot-and-tick prototype, not full `Game_Start`, original wait-list semantics, or `Kernel_11d0_31cf` parity. Next replace host wait-list/stasis and item-cache models, then move input and process behavior onto recovered keyboard/controller dispatch.
4. **Move player behavior onto that path:** replace host-created avatar/controller state, movement-step policy, and approximate collision with the recovered item, keyboard, controller, animation, and collision call chain. Feed Win32 input and timing into explicit host-service adapters; the game logic must not depend directly on Win32 APIs.
5. **Reconnect presentation and interaction:** the first reachable map-1 interaction now passes a retail-data regression through host item search, owner-row selection, nested VM dispatch, and a pixel-verified chest mutation. This closes the initial interaction milestone only; integrate original `Item_Grab`/`Usecode_ItemCallEvent`, implement the later `0x70` loot search, and connect live rendering to recovered draw-list/order and camera behavior. Keep the static preview as a regression oracle, not the normal gameplay renderer.
6. **Gate each replacement:** for every slice, record source address, exported function, unresolved decompiler assumptions, host substitutions, and tests; verify it is compiled into and called by `remorse_game`. Remove a stand-in from the normal path only after deterministic behavior checks pass. Update the function counts and parity status in this roadmap as slices land.
7. **Preserve the portability path:** keep recovered game logic and resource formats platform-neutral, with Win32 window/input/timing services behind replaceable interfaces. Once the original loop works through those interfaces, select and validate a portable host such as SDL; do not count the current Win32-only window as multi-platform support.
## Near-Term Next Actions
1. **Extend the reachable event path:** `flex_archive_tests` now reaches retail `CHEST_EW` item 6747 from the destination pad by a 295-step route, selects its `use` event through host item search and owner-row selection, executes nested VM dispatch, and verifies shape/frame `1360/0 -> 1355/1` with a target-only pixel change and no earlier VM error. Integrate original `Item_Grab`/`Usecode_ItemCallEvent`, then recover the later `0x70` nearby-loot search before claiming full chest-event parity. The test intentionally stops at the first visible mutation, before that optional loot scan; the BOX_NS fixture regression remains separate evidence.
2. **Continue integrating the map-1 loop:** the normal window calls the `remorse_core` fresh-game entry; the retail test queues an Up event through the source-derived keyboard fanout, creates the requested animation process, and advances it on a timer-driven scheduler pass. The boot entry is a reduced `Game_Start` translation; waiter links and map/NPC cache initialization remain host models. The event fanout still ends at a host callback, so recover the original process callback/consumer and controller path next. The full playable vertical slice still requires source-backed movement, live rendering, and a reachable interaction.
## Current Bottom Line
### Destination-Pad Interaction Search (2026-10-07)
The retail `flex_archive_tests` startup path now runs the existing source-derived `Item_Grab` search after the modeled two-hop startup places item 1 at item 6812. It asserts the six search results in source order and runs each through the retail USECODE owner-row/event selector; all six reject `use` event 1. This resolves the roadmap's stale staging-point search question only. No reachable event target, original event dispatcher, or interaction is established.
The host now materializes archive-backed USECODE chunks and builds tested 0x124-byte contexts with bounded source pointers and an initialized 0x82-byte call stack. Its window routes use-request candidates through owner-row selection into a context-backed task; the BOX_NS regression verifies VM-driven frame changes, rendered output, and cleanup. Retail tests now verify the complete map-1 startup placement from egg `0x1e` through active trigger item 1598/ID `0x63` to destination egg item 6812 at `(30328, 29656, 16)`, with item 1 and persistent runtime processes intact. The normal window has been confirmed at that destination, and the player sprite anchor was aligned with map-object rendering. The no-eligible-event result at egg `0x1e` describes only the former staging point; the destination search now confirms six nearby items and no eligible event. A deterministic host input/tick test verifies that the item-owned animation process moves item 1. Original `Game_Start`, full `Process_WaitFor` parity, cross-map teleporter lifecycle, `Usecode_ItemCallEvent`/context-dispatch, owner-resource callback parity, a reachable retail interaction, and original loop/render parity remain incomplete. Whole-game and playable-game acceptance remain unmet.
### Scheduler Port Slices (2026-10-07)
The `11d0:0255` decompilation's per-entry dispatch gate is now compiled in `remorse_core` and called by `ProcessKernel::scanRunnableProcesses`. It consumes the one-pass syncing flag and applies the sleep, linked-state (`+0x24/+0x26`), waiting, group, and daemon gates. Host wait-list readiness is passed explicitly; the host still owns scan iteration, sleep/wait processing, vtable callbacks, and cleanup. The `Kernel_11d0_0445` highest-group selection loop is also a compiled helper called when the host observes an empty active group; the wrapper applies the selected group and clears its pending flag. Tests preserve source behavior for occupied terminated slots and exclusions of groups 30/31. The MSVC build, all 15 CTests, and rebuild harness pass. These slices improve the compiled runtime used by the window but do not integrate the original scheduler loop or establish binary runtime parity.
### Basic Map Boot And Tick (2026-10-07)
The normal `remorse_game` launch now calls `startFreshGameMapOne` in `remorse_core`. This reduced fresh-start translation initializes the live avatar, creates/runs the source-shaped `TeleporterProcess` for map 1 egg `0x1e`, resolves the retail active trigger `0x63`, and runs the second teleporter process to item 6812 at `(30328, 29656, 16)`. The retail integration test continues from that same state: it creates an owned animation process, delivers one system-timer event, runs `runTimedSchedulerPass`, and verifies the avatar animation frame advances. The Windows target builds and all 15 CTests plus the harness pass.
This reaches the narrow basic-build threshold: a normal Windows map-1 boot reaches the level-start area and rebuilt source-derived process code advances the avatar runtime on a tick. The retail test now sends an Up scan-code event through the compiled keyboard fanout and uses its host movement adapter to select the animation; the clip remains a deterministic fixture and does not prove retail movement/collision parity. It is not a playable source port. `Game_Start`'s surrounding initialization, original wait-list linked structures, item/NPC cache ownership, continuous `Kernel_11d0_31cf` loop, original input/controller consumer, and full process vtable routing remain incomplete or host-adapted.
### Keyboard Interrupt Fanout Slice (2026-10-07)
The `Kernel_CallProcKeyboardInterrupts` behavior is now isolated in `remorse_core` as `kernel_keyboard_interrupt_dispatch.cpp`. It drains the host-fed event queue, walks registered subscriber IDs, applies the source-derived allocation/flag/group gate, copies each queued 12-byte event for the subscriber, and calls the injected handler with selector `0x10` and filter `0`. The Win32 adapter supplies key scan codes/modifiers; `flex_archive_tests` boots map 1, sends Up through this fanout, verifies a walk request, delivers a timer event, and confirms the resulting avatar animation process advances. The build, all 15 CTests, and the harness pass.
This does not yet dispatch through the original per-process function table. Live Ghidra shows the `Controller` vtable's `+0x28` slot is a no-op; the movement callback used by the window/test is explicitly host-side. `KeyboardProcess_HandleKeyEvent` and the original controller input consumer still need to be placed on their true runtime paths before claiming source-backed player input.
### Reachable Retail Interaction (2026-10-08)
The retail integration test reaches item 6747 (`CHEST_EW`) from the level-start area in 295 route steps (296 expanded nodes), selects its `use` event, and executes the replacement sequence through nested VM dispatch. At the clean checkpoint the target changes from shape/frame `1360/0` to `1355/1`; rendering the isolated target before and after confirms different pixels. The assertion requires nested dispatch, no VM error before the checkpoint, and the actual pixel difference. The test reports one nested event (`2572/50`); the full MSVC gate passes all 15 CTests and the rebuild/export harness.
This closes the reachable visible-mutation milestone, not original runtime parity. Search, context creation, and task scheduling remain host-integrated rather than calls through original `Item_Grab` and `Usecode_ItemCallEvent`; the later chest `0x70` loot search and broader VM/list semantics are still unimplemented. The regression stops at the first visible mutation, and normal-window interaction wiring, original startup/scheduler, and source rendering remain outstanding.