diff --git a/docs/entity-vm-runtime-owner-resource-layout.md b/docs/entity-vm-runtime-owner-resource-layout.md index 07ce5ef..94a4a5e 100644 --- a/docs/entity-vm-runtime-owner-resource-layout.md +++ b/docs/entity-vm-runtime-owner-resource-layout.md @@ -133,13 +133,21 @@ Current layout claims that matter for class lifting: - `+0x117/+0x119` cache the owner-linked source pair - `+0x123` behaves as a busy or active flag in the sync/dispatch path -`CreateFromSlotIndex` initializes the embedded interpreter, copies the item parameter only when mode flags are nonzero, copies optional `ucparam` bytes into the backward-growing stack, then reserves four bytes for the prior stack pointer when both are present. The host VM models this order and the `+0x11f` relative offset, but does not synthesize the original segment:offset pointer or map the runtime-owned code and owner buffers yet. +`CreateFromSlotIndex` initializes the embedded interpreter, copies the item parameter only when mode flags are nonzero, copies optional `ucparam` bytes into the backward-growing stack, then reserves four bytes for the prior stack pointer when both are present. `createUsecodeContext` now builds a bounded host context from caller-supplied runtime pointers: it allocates the `0x124` process body and `0x82` call-stack buffer, maps code/owner pointers through `UsecodeRuntimeMemory`, writes the interpreter's stack/base/limit fields, copies only the active stack window, stores the saved pointer at the recovered relative location, and seeds the initial far-call pair. Invalid source ranges and stack overflow fail before leaving partial allocations. `usecode_vm_tests` checks the process bytes, pointer ranges, parameter ordering, call-stack bytes, and cleanup. + +`createUsecodeEventContext` adds the retail owner-row and event-slot inputs. `UsecodeTaskRegistry::addWithContext` owns the resulting context allocations for the task lifetime. The window use-request path now searches nearby item candidates, selects an eligible event through the owner rows, creates the context-backed task, writes its process ID output word, and copies the context bytes into the owned process entry. The retail BOX_NS test exercises candidate-driven selection and VM execution through injected item/timer services; it verifies frame/render changes and releases all context allocations on task removal. + +This is still host-side selection and execution, not the original `Usecode_ItemCallEvent` dispatcher or proven `CreateFromSlotIndex` call chain. The exact runtime meaning of the initial slot/value-add call-frame pair remains unverified, as do original owner-resource callback parity and general far-pointer dispatch. The embedded interpreter initializes its stack limit to 199 bytes; the host bootstrap rejects a combined initial item/context payload and saved-pointer slot above that limit. The host opcode service currently maps segment `0` to the task's item-memory buffer through `UsecodeProcessTask::readMappedItemWord`; all other segments are rejected. This centralizes the existing fixture behavior but is not a general segmented address space. -`UsecodeClass` now reads the first header dword as the extra-slot count. `initializeUsecodeSlotOwnerBuffers` copies the six-byte descriptors from class `+0x14` into a host buffer of `0xc0 + 6 * extraSlotCount` bytes and creates `32 + extraSlotCount` state words initialized to `0xffff`, matching `InitSlotOwnerBuffers`; retail `EVENT` and `NPCTRIG` cover the base and one-extra-slot cases. `UsecodeSlotChunkCache` reads descriptors through this buffer, tracks ensure/release counts, and unloads only at count zero, restoring the state sentinel so a later ensure reloads the body. This remains an archive-backed host model: the 0x16-byte `UProcess_1420_0000` object, owner-helper materialization, runtime loaded-list record, and far-pointer allocation/restoration are not implemented. +`UsecodeClass` now reads the first header dword as the extra-slot count. `initializeUsecodeSlotOwnerBuffers` copies the six-byte descriptors from class `+0x14` into a host buffer of `0xc0 + 6 * extraSlotCount` bytes and creates `32 + extraSlotCount` state words initialized to `0xffff`, matching `InitSlotOwnerBuffers`; retail `EVENT` and `NPCTRIG` cover the base and one-extra-slot cases. + +`UsecodeSlotChunkCache` now models the verified `UProcess_1420_0000` layout as a 0x16-byte record: a 16-bit vtable offset, previous/next far links at `+0x02/+0x06`, chunk-buffer far pointer at `+0x0a`, saved source pair at `+0x0e`, and slot/chunk indices at `+0x12/+0x14`. The host allocates a bounded segment for each process and chunk buffer, initializes the chunk buffer to `0xff`, copies the archive-backed body, replaces the descriptor's source pair with the buffer pointer, and links the process at the loaded-list head. On zero-count eviction it restores the saved source pair, resets state to `0xffff`, unlinks both neighbors, and releases both allocations. Retail `EVENT`/`NPCTRIG` tests and a synthetic two-node list cover reuse, eviction, pointer restoration, and list unlinking. + +`UsecodeRuntimeMemory` currently assigns one bounded region per nonzero segment, with at most 64 KiB per allocation and range-checked reads/writes. This is host address-space scaffolding, not a recovered DOS allocator. Materialization reads from the loaded `UsecodeClass` byte buffer; the original `EntityVmOwnerResource` callback and live runtime allocation/address parity remain unverified. Current caution: diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 9be7b12..548fb34 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -17,9 +17,7 @@ The exported files are evidence, not directly compilable game source. Keep them - 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 -Current progress correction: the long progress paragraph below predates the latest selector change. `E` now walks `itemGrabSearchCandidates` in source order and queues the first candidate with an eligible `use` event; it does not select the nearest eligible item. This remains host-side selection, not the original `Item_Grab`/`Usecode_ItemCallEvent` dispatch. - -The immediate target is a fresh game on retail map 1 at the original starting teleporter, 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-controlled sprite over a frozen map does **not** count. Keep the diagnostic traversal view separate while replacing its behavior; no DOSBox parity gate is required for this Windows milestone. +The immediate target is a fresh game on retail map 1 at the original starting teleporter, 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, not from the map bounds, and prove its coordinates and the spawned avatar/item ID in a retail-data test. 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. @@ -28,13 +26,7 @@ The immediate target is a fresh game on retail map 1 at the original starting te 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, start map 1 at egg `0x1e`, move and interact without a diagnostic shortcut, and 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: the map-1 fixed-map test identifies one family-8/frame-1 item with low quality byte `0x1e` (the teleporter's item-search predicate); startup centers on that egg instead of the map-bounds midpoint. The live item owner reserves avatar item `1` with defaults from `NPC_Init` (`10e8:000c`) and applies the coordinate/map write from `NPC_Teleport` (`10e8:29f2`). Win32 directional events now pass through the kernel keyboard queue to a registered controller entry; an owned `AnimPrimitiveProcess` advances the avatar item on 40 Hz host ticks. A cached map renderer redraws snapshots of mutable map items in source sorter order on a worker thread, while the avatar pose is still drawn in a separate screen overlay. Fast-area GLOB eggs now hatch into numbered live children using the `1098:039c` placement/status rules; the renderer replaces a hatched egg's preview expansion with those items. The interpreter's initial stack and 31-entry code-address stack are compiled and tested against exported `1418:00e8/0244/0000`; the host VM executes a tested opcode subset and task lifecycle. Retail-data tests execute `CARD_NS` spawning `SWITCH` and the `BOX_NS` timer chain through a changed live item frame and rendered scene. The Windows host queues a selected retail release-event body from the item-process callback and reports its task state, but this remains diagnostic: `F` host-selects the nearby item, the original `Item_Grab`/`Usecode_ItemCallEvent` dispatch is not ported, and `E` starts a nearest eligible use event through host selection. The task bytecode offset is now named `usecodeEventBytecodeOffset` (`0x0e`) and verified against raw `CARD_NS`, `BOX_NS`, and `RECHFLNS` bodies: each has a 14-byte prefix followed by opcode `0x0b`; Ghidra shows the selected event chunk pointer is passed with intra-chunk offset zero. The prefix field meanings remain untyped. These are partial translations of steps 1-5, **not completed milestones**: `Game_Start` (`1020:0000`), teleporter scheduling, complete item cache, controller actions beyond directional movement, original camera/draw-list integration, and original USECODE event dispatch remain open. Collision is approximate; no normal-input, end-to-end interaction acceptance exists. Steps 5-6 remain open. - -Retail map-1 probing at the starting egg found four children after fast-area GLOB hatching and no eligible `use` script on those children; no direct fixed-map item within 1,024 staged units has an eligible event body. The nearest direct `use` items are panel/card objects roughly 8,800 staged units away. Their event bodies delegate to `TRIGGER.slot_20` or `SWITCH.slot_21`, which require additional VM, timer, selector, and world-state services. A renderer regression confirms that moving hatched children changes live scene pixels, but this is not script execution or proof that those distant interactions are reachable through the current collision path. - -Control-path evidence for step 3: live `CRUSADER.EXE` disassembly at `1130:224b-226a` compares event selectors against the five words at `1130:273b` (`1, 2, 4, 0x10, 0x100`); the matching CS jump-table words at `1130:274f` target `226e, 2276, 22b6, 22bd, 22b6`. The gameplay-key case at `1130:22bd` copies all 12 bytes of the incoming key event. The exported `Controller_HandleKeyEvent` pseudo-C contains an invalid branch after this table and must not be compiled verbatim. The 32-slot, 12-byte pending-key ring (`11d0:3533/3ad4/3a74/3aad`) and a registered-subscriber dispatch (`11d0:3c4d`) are ported in `ProcessKernel`; tests cover order, full/overflow, wrap, and delivery to a controller entry rather than the excluded keyboard process. The 0x40-byte controller entry mirrors the keyboard registration and daemon/update flags of `ControllerProcess_CreateProcess` (`1130:00e3`), **but the window does not create it or feed its queue**. `Controller_PickNextAnimByKeyevent` (`1130:12d6`) reads two keyboard state arrays through `Keyboard_GetKeyState` (`11d0:39b9`, DS offsets `3652` and `3352`) and selects animation through NPC state and services. `Kernel_11d0_39fb` installs the DOS interrupt-9 keyboard path through `FUN_1218_059b`; exported C exposes the arrays' reads/resets but not their hardware writer. Recover the key-state update semantics from the interrupt path and port the controller's reachable movement branches before replacing host polling; do not guess their edge/held meaning. - -Animation dependency for step 3: live disassembly at `1130:1eda-1ef0` supplies `NPC_DoAnim` (`10e8:0252`) with the controlled NPC item pointer, animation number, direction, and two zero arguments that the exported controller pseudo-C omits. The unarmed walk/run cases allocate `AnimPrimitiveProcess` (`1150:0000`, size `0x5b`); live disassembly at `1150:0033-009c` confirms its normal vtable offset `0x2a57`, event type `0xf0`, and linear-capable setup. A kernel-owned constructor with this layout, item/type registration, direction, and clip metadata now has a byte-level test. `AnimPrimitive_SetStartFrame` (`1150:17b2`) is ported and tested for two-step/looping and controlled-avatar frame-skip branches. Its tick (`1150:1906`) still needs NPC animation-frame state, fast-area/collision behavior, item updates, transitions, and teardown. The Windows host frame counter is not this process. Finish the tick and collision result before swapping the default control path. +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. These are tested host models, not calls through `Game_Start`, `Teleporter_CreateProcessDirect`, or the original kernel loop. A test using the production-equivalent item search at the egg spawn found one candidate and no eligible `use` event. The BOX_NS effect test therefore still uses a fixture origin; a reachable target and original item/event dispatch remain open. Nearby panel/card scripts also require additional VM, timer, selector, and world-state services. ## Current Inputs @@ -43,62 +35,9 @@ Animation dependency for step 3: live disassembly at `1130:1eda-1ef0` supplies ` - `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`. -## First Concrete Scaffold +## Rebuild Scaffold -The first host rebuild scaffold is now under `rebuild/remorse/`. - -It is deliberately separate from `exports/src_remorse/` because the export is generated, ignored by git, and still contains syntax and ABI artifacts that modern compilers cannot accept wholesale. - -Current scaffold files: - -- `rebuild/remorse/CMakeLists.txt`: CMake target for a Windows-friendly C++17 executable named `remorse_rebuild`. -- `rebuild/remorse/build_msvc.cmd`: repeatable MSVC/CMake build, test, and harness-run command. -- `rebuild/remorse/include/remorse/combat_tactics.h`: typed reader for `COMBAT.DAT` tactic records. -- `rebuild/remorse/include/remorse/compat.h`: exact-width aliases, far-pointer placeholders, packing macros, and calling-convention marker macros. -- `rebuild/remorse/include/remorse/export_prelude.h`: temporary bridge types for staged Ghidra-export imports. -- `rebuild/remorse/include/remorse/entity_dispatch_entry.h`: first hand-maintained class-family skeleton, anchored to the `11e0:0000` / older `0008:ba00` allocation evidence. -- `rebuild/remorse/include/remorse/file_system.h`: first host file/path discovery shim for replacing DOS install-path assumptions. -- `rebuild/remorse/include/remorse/flex_archive.h`: standard FLEX archive directory parser. -- `rebuild/remorse/include/remorse/fixed_map.h`: typed `FIXED.DAT` map table and 16-byte item-record reader. -- `rebuild/remorse/include/remorse/glob_archive.h`: typed `GLOB.FLX` object-entry reader. -- `rebuild/remorse/include/remorse/map_renderer.h`: first dependency-free map preview renderer and BMP writer. -- `rebuild/remorse/include/remorse/palette.h`: first game-data parser for 256-color RGB palette files. -- `rebuild/remorse/include/remorse/runtime.h`: minimal runtime/export-manifest surface. -- `rebuild/remorse/include/remorse/shape_archive.h`: typed `SHAPES.FLX` shape-frame parser and row-RLE decoder. -- `rebuild/remorse/include/remorse/animation_archive.h`: bounds-checked raw `ANIM.DAT` lookup, direction/frame metadata, sprite-frame and flip extraction, and authored movement-step decoding. -- `rebuild/remorse/include/remorse/collision.h`: TYPEFLAG-sized collision volumes, swept movement query, and fixed-map/GLOB solid-volume extraction. -- `rebuild/remorse/include/remorse/type_flags.h`: typed `TYPEFLAG.DAT` shape-family and flag decoder. -- `rebuild/remorse/src/combat_tactics.cpp`: parses tactic names, four block offsets, and bytecode payloads from `COMBAT.DAT` entries. -- `rebuild/remorse/src/collision.cpp`: builds conservative solid volumes from fixed-map records and expanded glob children, then sweeps the player footpad against them. -- `rebuild/remorse/src/entity_dispatch_entry.cpp`: partial source translation of process lifecycle, the `11d0:0255` scan and `11d0:0445/19b5` post-scan group selection, `Process_Sleep`/`Unlink`, the 0x42-byte Stand constructor fields, `StandProcess::Run` (`1100:0359`), a kernel-owned SystemTimer constructor/counter (`11c0:0000/00f8`), and partial Keyboard/KeyDaemon registration. The harness executes the NPC decision tree through host services and delivers timer events explicitly; real NPC data, timer interrupts/rescheduling, original keyboard queue/player input, and complete game tick remain unported. -- `rebuild/remorse/src/file_system.cpp`: repository/retail data-root discovery using modern `std::filesystem`. -- `rebuild/remorse/src/flex_archive.cpp`: loader for count-at-`0x54`, table-at-`0x80` FLEX archives. -- `rebuild/remorse/src/fixed_map.cpp`: loader for `FIXED.DAT` map tables and scaled fixed-map item coordinates. -- `rebuild/remorse/src/glob_archive.cpp`: parser for glob object entry lists inside `GLOB.FLX`. -- `rebuild/remorse/src/map_preview_main.cpp`: command-line preview executable for writing a viewable BMP image. -- `rebuild/remorse/src/windowed_game_main.cpp`: native Windows game shell, with async retail map/player/collision loading, shape-1 stand/walk/run sprites, metadata-driven 8-way movement, a following camera, and a position HUD. -- `rebuild/remorse/src/map_renderer.cpp`: combines fixed maps, glob expansion, typeflags, shape frames, and palette data into a painted preview image. -- `rebuild/remorse/src/palette.cpp`: `GAMEPAL.PAL`-style 768-byte palette parser. -- `rebuild/remorse/src/runtime.cpp`: loads a summary from the Ghidra export manifest. -- `rebuild/remorse/src/shape_archive.cpp`: ports the documented Crusader frame-table and row-RLE decode rules. -- `rebuild/remorse/src/animation_archive.cpp`: parses shape-indexed animation tables and direction-major frame metadata from raw `ANIM.DAT`. -- `rebuild/remorse/src/type_flags.cpp`: ports the verified 9-byte Crusader typeflag decode from the map-rendering tool. -- `rebuild/remorse/src/main.cpp`: starts the host harness and prints the export status. -- `rebuild/remorse/tests/combat_tactics_tests.cpp`: checks `COMBAT.DAT` parses to 14 tactics and entry 0 is `Dumb`. -- `rebuild/remorse/tests/entity_dispatch_entry_tests.cpp`: checks entry offsets, group counters, ID assignment, 30-slot growth, lifecycle, scheduler gates/spawn/cleanup, sleep writes, strict wake deadline, the owned Stand layout, NPC-gated `Run` branches, and timer-counter carry. -- `rebuild/remorse/tests/file_system_tests.cpp`: first host-side check that the current repository root can be recognized as a game-data root. -- `rebuild/remorse/tests/flex_archive_tests.cpp`: checks `STATIC/COMBAT.DAT` as a small FLEX archive with 14 populated records. -- `rebuild/remorse/tests/fixed_map_tests.cpp`: checks `STATIC/FIXED.DAT` map count and map 0 item-record loading. -- `rebuild/remorse/tests/glob_archive_tests.cpp`: checks `STATIC/GLOB.FLX` parses into at least one populated glob object. -- `rebuild/remorse/tests/map_renderer_tests.cpp`: checks map 1 can produce a non-empty preview image. -- `rebuild/remorse/tests/palette_tests.cpp`: checks that `STATIC/GAMEPAL.PAL` parses into 256 colors. -- `rebuild/remorse/tests/shape_archive_tests.cpp`: checks `STATIC/SHAPES.FLX` can decode at least one visible frame. -- `rebuild/remorse/tests/animation_archive_tests.cpp`: checks ANIM.DAT parsing, signed displacement and direction rotation, sprite-frame/flip decoding, and retail shape-1 stand/walk/run references. -- `rebuild/remorse/tests/collision_tests.cpp`: checks TYPEFLAG extents, swept obstruction, vertical clearance, flipped footprints, and fixed-map/GLOB placement extraction. -- `rebuild/remorse/tests/type_flags_tests.cpp`: checks `STATIC/TYPEFLAG.DAT` parses 2,048 shape records and includes glob-family records. -- `rebuild/remorse/tools/import_export_slice.py`: stages one exported function folder into `rebuild/remorse/imported/` for manual cleanup review. - -This is not the game yet. It is a buildable diagnostic host with a source-backed itemless process lifecycle, one-pass scheduler scan and post-scan active-group selection, owned Stand process layout, and recovered Stand `Run`/NPC decision and timer-counter branches. It does not have the original NPC service data, DOS timer delivery, keyboard event queue, or game loop. +`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 @@ -130,63 +69,6 @@ It can replace DOS extender, VGA, sound, input, timing, file, and memory service 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. -## Conversion Strategy - -1. Keep `exports/src_remorse/` as generated evidence; keep a function-address ledger of what was translated, what is still a stand-in, and which callers actually execute the translation. -2. Move one original call chain at a time into `rebuild/remorse/` as minimally corrected C/C++ with a documented address mapping and tests for the observed side effects. -3. Compile every moved slice immediately, even before it is runnable game logic. -4. Replace Ghidra pseudo-types with `remorse::u8`, `remorse::u16`, `remorse::u32`, `remorse::FarPtr16`, and explicit packed structs. -5. Convert Ghidra calling-convention tokens into marker macros from `compat.h` until the final host calling surface is chosen. -6. Keep raw address provenance in comments or mapping tables for every imported function. -7. Implement host runtime shims at the DOS/hardware call boundaries encountered by the ported chain; avoid duplicating game logic in the shim. -8. Validate recovered behavior with binary evidence, retail resources, and deterministic trace/state comparisons; connect each port to its caller in the Windows runtime. - -## Full Rebuild Plan - -The practical target is Track B: recompile recovered game logic for Windows and replace the DOS platform boundary. Track A remains an evidence constraint for layout, calling convention, far-pointer provenance, and validation. The phases below describe supporting capabilities, not permission to implement an independent game first: prioritize ported startup -> tick -> player/item process -> renderer/interaction call chains over further standalone host features. - -### Phase 0: Build And Evidence Discipline - -Goal: every step builds, runs tests, and keeps provenance visible. - -Exit criteria: - -- `rebuild\remorse\build_msvc.cmd Debug` passes from the repository root -- every imported subsystem has address/source provenance in code or docs -- generated Ghidra exports remain input evidence, not hand-edited source -- at least one corrected exported function is compiled, tested against its documented side effects, and invoked by a host caller; list remaining placeholder behavior explicitly - -### Phase 1: Host Runtime Foundation - -Goal: replace DOS installation assumptions with modern host services. - -Work: - -- game-data root discovery -- case-insensitive path resolution -- binary reads -- DOS-style file-handle facade -- writable config/save/user-data root -- command-line and config parsing -- logging and fatal-error reporting - -Exit criteria: the harness can find data, open/read assets through the same facade future game code will use, and write test save/config output outside the read-only retail data root. - -### Phase 2: Core Resource Loaders - -Goal: typed loaders for the files needed before gameplay can start. - -Work: - -- palettes: `GAMEPAL.PAL`, misc palettes, palette transforms -- FLEX archives: `COMBAT.DAT`, `GLOB.FLX`, `SHAPES.FLX`, `EUSECODE.FLX`, fonts/gumps/icons -- maps: `FIXED.DAT`, glob expansion, type flags -- shapes: Crusader frame directory and RLE decode -- usecode archive chunk discovery - -Exit criteria: a smoke test can load one map, expand globs, decode referenced shapes, and produce an in-memory scene without executing gameplay. - -### Phase 3: Minimal Renderer Goal: put a real Crusader world image on screen on Windows. @@ -298,25 +180,12 @@ Work: Exit criteria: a clean checkout/build can run against a retail data directory with documented setup steps. -## Current Execution Focus +## Historical Implementation Evidence -The current active work must shift from Phase 3 host presentation to decompiled source conversion and call-chain integration (Phases 0 and 4). Core Phase 2 loaders, the footpad-aware overlap sorter, and the Windows map window are diagnostic infrastructure. The actor uses retail stand/walk/run metadata, authored XYZ displacements, and the original 16-way direction table, but its 20 Hz host tick, conservative TYPEFLAG collision, and fixed-map boundary are not the recovered player process or original AreaSearch. Floor support, step-up/ledge handling, moving items, interactions, and USECODE remain unported. Keep the window as a test host, not as the implementation template for game logic. - -First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a8` (older `0008:bca8`) validates 1..31, updates the group byte at `+0x08`, and adjusts 16-bit counters through the far table pointer at `DS:39c5`. Live disassembly confirms the entry far pointer at `[BP+6]`, group byte at `[BP+0xa]`, and word-sized counter operations; the decompiler's `_group_id` alias is not a real implicit argument. The host receives the entry and table explicitly. `InitBase` at `11e0:0000` stamps the function-table words `0x3b06` (`+0x00`), `0x2d10` (`+0x1e`), `0x3afe` (`+0x28`), initializes the observed scalars, and seeds the group through `SetGroupId`. The seed comes from `DS:39c9` (written by `Kernel_11d0_19b5`); the host receives it as explicit runtime state. The unknown `+0x09` is not deliberately written. The host-owned path performs allocate -> initialize -> register, records default name/new-process metadata, executes the conditional current-process extflag branch, and applies the post-registration sync predicate. Itemless termination and slot reclamation are present. The scheduler scan applies normal-process group/flag gates and timer wake logic at `11d0:0255`, and its callback invokes the compiled `StandProcess::Run` branch for the 0x42-byte host-owned Stand entry. The `1100:026e` NPC decision gates are compiled, with their item/visibility/activity operations passed through host services. Owned Stand entries now maintain the per-item presence bit; the kernel-owned timer and keyboard constructors register their diagnostic processes. This is **not** a complete constructor or process system: stack-segment assertion, nonempty item child teardown, NPC service implementations, DOS timer/keyboard event delivery, end-of-pass work, other process `Run` functions, and far-memory behavior remain absent. Kernel-owned source/type transitions and active-group increment now have focused coverage, but the static source/type setters still lack item-cache context; runtime binary parity is not established. - -### Process Source-Port Ledger +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 | |---|---|---| -| `SetGroupId@11e0_02a8.c` (`0008:bca8`) | Partial translation; invoked from host `InitBase`, CTest transitions and invalid IDs | Live `11e0:02ae-031b`: group byte parameter at `[BP+0xa]`, far entry pointer at `[BP+6]`, 2-byte counter stride via `DS:39c5`, overwrite entire `+0x08` byte when changing group. Host exception replaces `AssertError`; counter-table ownership and runtime trace still need verification. | -| `IncrementGroupId@11e0_0405.c` | Group increment, current-active-group assertion, and 29-to-30 rejection translated; harness and CTest invoke it | Live `11e0:040b-0466` masks the group byte to five bits, checks next group `< 30` and `DS:39c9 == old group`, then calls `SetGroupId` and `Kernel_11d0_19b5`. The host passes the owning kernel and group counts explicitly; assertions become exceptions, without a DOS runtime trace. | -| `SetSourceType@11e0_01b6.c`, `SetEventTypeChecked@11e0_0227.c` | Kernel-owned item source and event-type transitions compiled and exercised by the item-process constructor, CTest reassignment/teardown | Source change stamps `+0x04`, marks the new item's presence bit, refreshes the old bit by searching unterminated processes from slot 3, and moves the type bit when `+0x06` is `0xf0..0xf7`. Type change stamps `+0x06`, sets the new type bit and refreshes the old type; values above `0x0fff` assert after the write. Per-item presence bits (`DS:3a04`) and per-item process-type bytes (`DS:3a08`) are separate host-owned tables. Static setters without kernel context remain partial; other item-cache mutations and binary parity are unverified. | -| `InitBase@11e0_0000.c` (`0008:ba00`) | Function-table/scalar/group-seed subset plus host-owned allocate/register path; harness-invoked, CTest offsets, counters, IDs | Live `11e0:0006-014e`: optional alloc `11e0:014f`, table words `0x3b06/0x2d10/0x3afe`, group from `DS:39c9`, then `SetGroupId`, `Kernel_AddProcess` (`11d0:0aff`), conditional `Kernel_GetSomeProcId_11d0_177c` branch, `Process_11d0_19cd`. Host updates extflags `+0x18 |= 4` on an addressable, unterminated current process with bit `2` set; it still omits stack-segment assertion and segmented-pointer relocation. | -| `Kernel_GetNextFreeProcId` (`11d0:0a97`), `Kernel_11d0_0716` | First-free slot and 30-slot growth translated; registered in host harness and CTest | Live decompile scans far process-pointer slots, grows parallel pointer/size/name arrays by 30 up to 1020 entries. Host stores native pointers, sizes, and default names; the original far-address mapping is not implemented. `Process_GetProcById` (`11d0:0bf3`) treats ID 0 as null even though the raw slot allocator may choose it. | -| `Kernel_AddProcess` (`11d0:0aff`) | Process pointer, ID, allocation-size, count, optional new-process flag/counter, default-name subset translated | Live disassembly stamps `procid` at `+0x02`, consumes `g_kernelLastProcessAllocSize`, increments count, optionally sets `ExtProc_NewlyCreated` (`0x200`), and names the slot `Default`. Host omits initialized-state assertion, far-pointer representation, and runtime parity. | -| `Process_11d0_19cd` / `Process_11d0_19ec` | Sync-flag predicate translated on the host creation path | Live `11d0:19ef-1a07` tests kernel flag and `procid > current ID`; `11d0:19e2-19e5` ORs `0x40` into process flags at `+0x16`. The conditional `InitBase` current-process extflag branch is also translated, without runtime parity. | -| `Kernel_TerminteProcessByPid` (`11d0:18a3`), `Process_SetTerminatedState` | Immediate and deferred termination translated for host-owned base and zero-child-state Stand entries | Live `11d0:18e5-1939`: decrement group count; if extflags `+0x18 & 4`, clear slot and free immediately; otherwise set flags `+0x16 & 8`, increment terminated count; decrement live process count in either case. Host refreshes the per-item bit after termination; child lists, special event callbacks, and teardown for non-owned entries remain unported. | -| `Kernel_ClearProcessSomethingAndName` (`11d0:1972`), `Kernel_11d0_1dcc` | Slot pointer/size/name clear and deferred cleanup for IDs >= 3 translated; ID reuse exercised | Live cleanup scans from ID 3, requires `+0x1a == 0`, clears the slot, frees the entry, and decrements terminated count. The clear helper itself does not decrement live process count. Other scheduler cleanup paths and process destructor dispatch remain unported. | | `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. | @@ -356,18 +225,6 @@ Live Ghidra decompilation shows that vertical `GravityProcess_Run` impacts use s 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. -Original DOS debugging and runtime verification are postponed indefinitely until requested again. The DOSBox-X debugger session has been stopped; do not treat a live trace as a prerequisite for the source-port work below. Keep unverified parity claims labeled as such. - -Next source-port checks, in call-chain order: - -1. Keep the `0x23ff/0x2400` process item boundary until source-derived allocation limits support changing it; do not infer a wider live table from staged map IDs. -2. Keep the original scheduler wait behind a host timing boundary. `11d0:04cd/0575` reallocates and copies three segmented process tables; defer a direct port until the host's vector-backed slot/capacity semantics are explicitly modeled. Post-scan active-group selection is now statically translated, with runtime parity explicitly deferred. -3. Verify and extend the host free-ID/container slice against live runtime traces; synthetic tests now cover family-7 contained-record staging and family-6 runtime insertion, but item-cache status/fast-area effects and the `Item_PopToEnd` runtime append path remain unverified. -4. Port an explicit item-status model before implementing vertical gravity responses; bounds and fast-area failures are explicit but conservatively rejected, and live gravity branches also require controlled-NPC identity and random-response behavior. -5. Extend scheduled gravity with item status/cache writes and collision events; add a real window gravity producer and dynamic item renderer before claiming visible gameplay movement. -6. Connect the approved-move `Item_Grab` path to a ported `Item_LegalMoveToPointWithCollisionInfo` sweep and item-cache lifecycle, without changing the separate Windows `F` release fixture. -7. Lift `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`) and the `Inter_1418_0244` interpreter/context layout, replacing host task setup with the original event-frame and parameter semantics; extend opcode/intrinsic coverage before claiming event parity. - ## First Interactive Windows Game Shell `rebuild/remorse/out/build-nmake/remorse_game.exe` is the first windowed application target. It locates the game data root from its own executable path (or the current directory), defaults to map 1, and accepts an optional fixed-map index from 0 through 255. @@ -645,77 +502,22 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat ## What Is Done -- Established a separate rebuild tree under `rebuild/remorse/`. -- Added a CMake-based C++17 executable target. -- Added an initial compatibility header matching the earlier ABI draft categories. -- Added a temporary export prelude for staged decompiler-source imports. -- Added a minimal runtime harness that reads the exported decompilation manifest and reports the current export scope. -- Added an import-slice tool for staging individual exported function folders without linking them yet. -- Ran the importer on `classes/Remorse/EntityDispatchEntry`; it staged 24 files, replaced 62 calling-convention tokens, and reported `CONCAT22`, `unaff_CS`, and `unaff_SS` as cleanup signals. -- Added the first hand-maintained `EntityDispatchEntry` source skeleton and wired it into the CMake target. -- Translated `11e0:02a8` group-ID validation, counter transitions, and no-op on an unchanged group into the compiled skeleton; other methods still have incomplete or placeholder behavior. -- Replaced `InitBase`'s blanket clear with live-confirmed `11e0:0000` function-table stamps, scalar assignments, and the active-group `SetGroupId` call; seeded-byte tests protect unknown bytes while the rest of the constructor remains unported. -- Added an owned host allocate/init/register call path, porting the first-free ID, 30-slot growth, process-ID/size/count bookkeeping, and `Process_11d0_19cd` syncing predicate. The harness now registers a process (ID 0); this does not run the original scheduler. -- Added default process-name storage, optional `ExtProc_NewlyCreated` flag/counter, immediate and deferred itemless termination, and slot cleanup/ID reuse. The harness also terminates ID 3, cleans its slot, and registers another process at ID 3; normal ID 0 lookup is a special case. -- Ported the conditional `InitBase` current-process extflag branch and the normal-process scan gates of `11d0:0255`. Tests cover group selection, one-pass sync, creation from a run callback, and cleanup during the scan. -- Ported the original `Process_Sleep`/`Unlink` timer writes and wake check, then executed `StandProcess::Run` under the scheduler in the diagnostic harness. It now uses an owned 0x42-byte Stand entry, compiled `1100:026e` NPC decision gates with host-supplied services, and a timer value produced by `SystemTimerProcess_Increment`. CTest checks off-screen sleep, the strict 60-tick deadline, visible behavior start, already-current activity, Stand's no-op completion slot, and timer carry. Host-owned Stand termination now refreshes the per-item bit; tests cover two processes for one item, deferred reclamation, and final immediate removal. Live Ghidra names `Item_MarkProcessPresent`/`Item_ClearProcessPresent`/`Item_RefreshProcessPresenceFlag` at `11d0:3e0b/3e44/3e7f` anchor the port. -- Configured the Windows GUI and console executables to emit CRT and unexpected-exception details to debugger output/stderr instead of modal crash prompts. CTest resets the CRT assert mode to window mode and verifies the installer removes it, then captures a deliberately terminating child process without a popup. -- Split the scaffold into a `remorse_core` library, host executable, and first CTest target for `EntityDispatchEntry` setters. -- Added the first host file-system shim and CTest target for game-data root discovery. -- Extended the host file-system shim with case-insensitive data-path resolution, parent-traversal blocking, and binary file reads. -- Added the first typed game-data parser for 256-color palette files and verified `STATIC/GAMEPAL.PAL` parses to 256 colors. -- Added a standard FLEX archive parser and verified `STATIC/COMBAT.DAT` exposes 14 populated records. -- Added a typed `COMBAT.DAT` tactic parser and verified entry 0 metadata against the existing combat note. -- Added a full staged rebuild plan from current harness through a playable and packaged modern Windows source port. -- Added a typed `FIXED.DAT` map loader for map table and 16-byte fixed-item records. -- Added a typed `GLOB.FLX` object parser for the fixed-map glob-expansion path. -- Added a typed `TYPEFLAG.DAT` parser for shape family, flags, dimensions, and animation metadata. -- Added a typed `SHAPES.FLX` parser and row-RLE decoder for renderable frame pixels. -- Added the first visual map preview renderer and BMP output command. -- Added `remorse_game.exe`, a native Win32 window that asynchronously loads a retail map, displays the graph-sorted scene, and supports bounded WASD/arrow movement with a following camera. -- Added a persistent GDI back buffer and disabled background erase for the window's movement redraw path. -- Mapped keyboard movement to screen-cardinal directions through the inverse isometric transform and added a four-direction projection regression. -- Added a camera-centered render origin and a renderer test covering fixed-size viewport output. -- Documented the windowed app command and clearly scoped its current debug-marker/no-collision limitations. -- Replaced the host preview's scalar paint key with a footpad-aware dependency graph based on the local Ultima 8/Crusader sorter, including pairwise overlap, `below()` rules, and occlusion handling. -- Added a synthetic regression proving vertical separation can override the old `x+y` order, and retained the retail-data map-render smoke test. -- Validated `remorse_map_preview` by rendering map 1 to `rebuild/remorse/out/preview/map1-preview.bmp` from original retail data. -- Verified the scaffold with Visual Studio Community 2026: CMake configure succeeded, MSVC build succeeded, `ctest -C Debug` passed 2/2 tests, and `remorse_rebuild.exe` ran against `exports/src_remorse/export_manifest.json`. -- Added `build_msvc.cmd` so the MSVC build/test/harness loop is repeatable from the repository root; it uses an isolated NMake build tree to avoid the local CMake Visual Studio-instance resolution failure. -- Revalidated the wrapper with MSVC `19.51.36246.0`: all C++ targets built, all 11 CTest tests passed, and the host harness loaded the export manifest and retail resource summaries. -- Documented the current blockers between the Ghidra export and compiler-ready source. -- Split the goal into historical reconstruction and Windows source-port tracks. -- Chose Visual Studio Build Tools plus CMake as the first intended Windows host toolchain. +- **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. Map loading now creates, runs, and retires this process using a local kernel. It does not port `Game_Start`, temporary-stasis wait, cross-map camera/NPC setup, collision/fall, sound, or original scheduler dispatch. +- **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. -## What Is Left To Do +## Later Scope -- Keep the host scaffold building as new source slices are added. -- Lift the confirmed `EntityDispatchEntry` byte offsets into named packed fields once the surrounding `Process` layout is stable. -- Convert the compatibility header from placeholders into enforced layout macros with static assertions. -- Extend the translated `SetGroupId` slice to its original initializer/callers and record the ported function addresses and parity checks. -- Expand the host file-system shim into DOS file-handle replacements and writable save/config locations. -- Model far pointers and segmented memory in a way that can support both trace comparison and Windows execution. -- Normalize Ghidra exported types into valid C++ names without losing address provenance. -- Replace raw global-byte exports with typed data definitions or resource loaders. -- Define resource fixture tests for palette, shape, map, and usecode data. -- Add explicit crop/navigation controls and tests for bounded map previews. -- Validate roof/hidden-object rendering policy against selected retail scenes. -- Keep the current Win32/GDI window as a diagnostic host while lifting the original player/process loop; choose other platform layers only as original DOS/hardware boundaries require them. -- Replace the windowed prototype movement/collision with ported player and AreaSearch behavior, using retail art and the existing renderer for presentation. -- Connect triggers and object interaction to the USECODE runtime after its value/context model is lifted. -- Add CI-style smoke tests once the host toolchain and first resource loader compile reliably. +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. ## Near-Term Next Actions -1. Verify the live `Process` group-table allocation/initialization and compare the compiled active-group writer/selector (`11d0:19b5/0445`) and `11e0:02a8` side effects with an execution trace (including counter ownership and error paths). -2. Complete `InitBase` (`11e0:0000`) and the kernel lifecycle by resolving the segment assertion, conditional kernel branch, item-linked teardown, process destructor dispatch and far-pointer storage; compare the host registry to real process snapshots. -3. Trace `Init_Everything` -> `FUN_11d0_0255` -> the player process and additional vtable `Run` targets; compare the staged map-item/ItemProcess IDs and Stand's presence-bit lifecycle against original snapshots, then port animation-cache and nonempty-child teardown against real NPC state. -4. Port the real timer process and NPC service implementations, then scheduler keyboard, active-group advancement, remaining sleep-completion dispatch and table-maintenance tails; compare deterministic process-order/state traces before connecting the Windows window. -5. Replace DOS file and memory APIs encountered by the ported chain with narrow host adapters; validate far-pointer/layout conversions against live evidence. -6. Port original movement and AreaSearch/collision behavior before promoting the host actor movement from stand-in to gameplay code. -7. Complete runtime chunk materialization before context dispatch: extend the tested archive-backed `UsecodeSlotChunkCache` through `InitSlotOwnerBuffers`/`EnsureSlotChunkLoaded` (`1420:1866/19fd`), port the `0x16`-byte `UProcess_1420_0000` allocation and owner-helper materialization, then model loaded-list ownership, far-pointer restoration, release, and eviction. After that, map runtime-owned code into host VM memory, lift `CreateFromSlotIndex`/`Inter_1418_0244`, and execute a selected retail event with verified item/process side effects before connecting it to the window. Continue through original item/draw-list output, save/load, audio, and frontend chains for playable mission progression. +1. **Close the event path:** identify an eligible retail `use` target reachable from the original map-1 spawn. The exact production-equivalent search at egg `0x1e` currently returns one candidate and no eligible event. Then exercise movement to a real target, owner selection, context creation, and VM execution through supported runtime services, verifying a process/world-state effect. The BOX_NS regression verifies candidate-driven selection and visible frame output from a fixture origin only; it does not close this action or establish `Usecode_ItemCallEvent` parity. +2. **Integrate the map-1 loop:** port `Game_Start` (`1020:0000`) and the teleporter constructor/run lifecycle rather than host initialization; add the stasis wait, original target-map transition and item search, collision/fall, then move input and animation onto the recovered kernel loop. The current tests cover same-map egg resolution, shared item-1 mutation, and host input/scheduler behavior, not those binary lifecycle semantics or source draw-order/camera parity. Keep the normal window on the original path before calling the vertical slice accepted. ## Current Bottom Line -Runtime-cache progress correction: the host now models the extra-slot header, descriptor/state buffers, ensure/release counts, and archive-backed zero-count unload/reload. It still lacks `UProcess_1420_0000` allocation, owner-helper materialization, loaded-list ownership, and runtime far-pointer restoration; complete those prerequisites before far-address integration and the numbered context-dispatch action above. -The project has a buildable diagnostic host, retail resource loaders, partial original scheduler scan, and owned Stand and item-process entries. The Windows diagnostic registry runs an item process bound to a staged retail map record, queues an eligible release body into the subset VM, and runs a Stand entry under the host tick. Retail tests demonstrate script-driven item-frame mutation. The `E` selector now iterates bounded, source-order candidates from `itemGrabSearchCandidates` (the modeled `Item_Grab` query) and queues the first candidate with an eligible `use` body, replacing its earlier nearest-distance choice. This is source-derived candidate selection, not original interaction dispatch: the window still constructs the item identity and queues the event body directly, and no visible before/input/after interaction is proven. The partial `CreateFromSlotIndex` slice writes the verified slot index (`+0x32`), value offset (`+0x34`), owner-source far pointer (`+0x11b`), mode byte (`+0x121`), and cleared parameter/active fields (`+0x11f/+0x122`) into the allocated 0x124-byte context. The VM bootstrap now copies the item parameter only for nonzero mode flags, then optional context bytes, reserves the four-byte saved-stack-pointer slot, and records the context-relative parameter offset; focused tests cover the ordering and zero-mode case. Real segment:offset pointer mapping, runtime code/owner-resource addresses, and embedded interpreter-context execution remain unported. `F` remains a separate release diagnostic. The original item cache/block IDs, full `Item_Grab`/`Usecode_ItemCallEvent`/`CreateFromSlotIndex` chain, real NPC ownership/services, nonempty-child teardown, DOS timer/keyboard interrupts, full scheduler, original startup/player chain, and renderer integration remain open. This is not a playable-game milestone; the next measure is mapping far addresses into the host VM and using them to execute one selected retail event through original context dispatch. +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, while a separate retail test confirms no eligible event at the original spawn. Retail egg selection and placement of item 1 are covered, the typed `TeleporterProcess` performs its tested same-map egg move, and a deterministic host input/tick test verifies that the item-owned animation process moves item 1. Original `Game_Start`, the full 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. diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index 7e06929..7a3eadc 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -51,6 +51,11 @@ struct ControllerProcessEntry { u8 extra[0x0e]; } CR_PACKED; +struct TeleporterProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x04]; +} CR_PACKED; + struct AnimPrimitiveProcessEntry { EntityDispatchEntryBase base; u8 extra[0x29]; @@ -84,6 +89,7 @@ static_assert(sizeof(SystemTimerProcessEntry) == 0x4a, "SystemTimerProcessEntry static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyDaemonProcessEntry) == 0x40, "KeyDaemonProcessEntry size must match allocation evidence"); static_assert(sizeof(ControllerProcessEntry) == 0x40, "ControllerProcessEntry size must match allocation evidence"); +static_assert(sizeof(TeleporterProcessEntry) == 0x36, "TeleporterProcessEntry size must match allocation evidence"); static_assert(sizeof(AnimPrimitiveProcessEntry) == 0x5b, "AnimPrimitiveProcessEntry size must match allocation evidence"); static_assert(sizeof(EntityVmContextProcessEntry) == 0x124, "EntityVmContext process size must match allocation evidence"); static_assert(sizeof(KeyEvent) == 0x0c, "KeyEvent size must match keyboard event copy"); @@ -119,6 +125,8 @@ public: KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]); ControllerProcessEntry* createControllerProcess(u8 activeGroup, u16 (&groupCounts)[32]); + TeleporterProcessEntry* createTeleporterProcess(u8 activeGroup, u16 mapNumber, u16 teleportId, + u16 (&groupCounts)[32]); AnimPrimitiveProcessEntry* createAnimPrimitiveProcess(u8 activeGroup, u16 itemNumber, u16 animationNumber, u8 direction, const AnimationClip& clip, u16 (&groupCounts)[32]); EntityVmContextProcessEntry* createUsecodeProcess(u8 activeGroup, u16 (&groupCounts)[32]); @@ -174,6 +182,7 @@ private: std::vector> ownedStandProcesses_; std::vector> ownedGravityProcesses_; std::vector> ownedAnimPrimitiveProcesses_; + std::vector> ownedTeleporterProcesses_; std::vector> ownedUsecodeProcesses_; std::unique_ptr systemTimerProcess_; std::unique_ptr keyboardProcess_; @@ -237,6 +246,15 @@ public: static void increment(SystemTimerProcessEntry& entry); }; +class TeleporterProcess { +public: + static constexpr u16 vtableOffset = 0x0f3a; + static constexpr u16 mapNumberOffset = 0x32; + static constexpr u16 teleportIdOffset = 0x34; + static bool run(const TeleporterProcessEntry& process, LiveFixedMapItems& items, + u16 currentMapNumber, const std::vector& shapes); +}; + class KeyboardProcess { public: static bool handleKeyEvent(KeyboardProcessEntry& process, u16 selector, u16 filter, diff --git a/rebuild/remorse/include/remorse/usecode_archive.h b/rebuild/remorse/include/remorse/usecode_archive.h index 4d7b136..0e9aa7b 100644 --- a/rebuild/remorse/include/remorse/usecode_archive.h +++ b/rebuild/remorse/include/remorse/usecode_archive.h @@ -2,6 +2,8 @@ #include "remorse/flex_archive.h" +#include +#include #include #include #include @@ -27,20 +29,69 @@ struct UsecodeEventBody { std::vector bytes; }; +struct UsecodeLoadedChunkProcessLayout { + u16 vtableOffset = 0; + FarPtr16 previous{0, 0}; + FarPtr16 next{0, 0}; + FarPtr16 chunkBuffer{0, 0}; + FarPtr16 savedSource{0, 0}; + u16 slotIndex = 0; + u16 chunkIndex = 0; +}; + +static_assert(sizeof(UsecodeLoadedChunkProcessLayout) == 0x16); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, previous) == 0x02); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, next) == 0x06); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, chunkBuffer) == 0x0a); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, savedSource) == 0x0e); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, slotIndex) == 0x12); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, chunkIndex) == 0x14); + +struct UsecodeLoadedChunkProcess { + FarPtr16 processAddress{0, 0}; + UsecodeLoadedChunkProcessLayout layout; + UsecodeEventBody body; +}; + +class UsecodeRuntimeMemory { +public: + std::optional allocate(std::size_t byteCount, u8 initialValue = 0); + bool release(FarPtr16 address) noexcept; + bool contains(FarPtr16 address, std::size_t byteCount) const noexcept; + std::optional> read(FarPtr16 address, std::size_t byteCount) const; + bool write(FarPtr16 address, const std::vector& bytes); + std::size_t allocationCount() const noexcept { return allocations_.size(); } + +private: + u32 nextSegment_ = 1; + std::map> allocations_; +}; + class UsecodeSlotChunkCache { public: explicit UsecodeSlotChunkCache(UsecodeClass usecodeClass); const UsecodeEventBody* ensureLoaded(u16 chunkIndex); bool release(u16 chunkIndex) noexcept; - bool tryUnload(u16 chunkIndex) noexcept; + bool tryUnload(u16 chunkIndex); u16 inUseCount(u16 chunkIndex) const noexcept; + const UsecodeLoadedChunkProcess* loadedProcess(u16 chunkIndex) const noexcept; + std::size_t loadedProcessCount() const noexcept; + FarPtr16 loadedListHead() const noexcept { return loadedListHead_; } std::size_t chunkCount() const noexcept { return chunks_.size(); } const UsecodeSlotOwnerBuffers& ownerBuffers() const noexcept { return ownerBuffers_; } + UsecodeRuntimeMemory& runtimeMemory() noexcept { return runtimeMemory_; } + const UsecodeRuntimeMemory& runtimeMemory() const noexcept { return runtimeMemory_; } private: + UsecodeLoadedChunkProcess* findLoadedProcess(FarPtr16 processAddress) noexcept; + bool unlinkLoadedProcess(FarPtr16 processAddress); + UsecodeClass usecodeClass_; UsecodeSlotOwnerBuffers ownerBuffers_; - std::vector> chunks_; + std::vector> chunks_; + UsecodeRuntimeMemory runtimeMemory_; + FarPtr16 loadedListHead_{0, 0}; + FarPtr16 loadedListTail_{0, 0}; }; struct UsecodeClassBases { diff --git a/rebuild/remorse/include/remorse/usecode_vm.h b/rebuild/remorse/include/remorse/usecode_vm.h index 7dbdd45..4c4063f 100644 --- a/rebuild/remorse/include/remorse/usecode_vm.h +++ b/rebuild/remorse/include/remorse/usecode_vm.h @@ -8,6 +8,7 @@ #include #include "remorse/compat.h" +#include "remorse/usecode_archive.h" namespace remorse { @@ -15,12 +16,20 @@ constexpr std::size_t usecodeEventBytecodeOffset = 14; constexpr std::size_t usecodeFrameBaseOffset = 0x40; constexpr std::size_t usecodeInterpreterStackLimit = 199; constexpr std::size_t usecodeContextProcessSize = 0x124; +constexpr std::size_t usecodeContextInterpreterOffset = 0x36; constexpr std::size_t usecodeContextSlotIndexOffset = 0x32; constexpr std::size_t usecodeContextValueAddOffset = 0x34; +constexpr std::size_t usecodeContextStackPointerOffset = 0x102; +constexpr std::size_t usecodeContextStackBaseOffset = 0x106; +constexpr std::size_t usecodeContextStackLimitOffset = 0x10a; +constexpr std::size_t usecodeContextCodeSourceOffset = 0x10c; +constexpr std::size_t usecodeContextSelfPointerOffset = 0x110; +constexpr std::size_t usecodeContextOwnerRowsOffset = 0x117; constexpr std::size_t usecodeContextOwnerSourceOffset = 0x11b; constexpr std::size_t usecodeContextParameterOffset = 0x11f; constexpr std::size_t usecodeContextModeFlagsOffset = 0x121; constexpr std::size_t usecodeContextActiveFlagOffset = 0x122; +constexpr std::size_t usecodeInterpreterCallStackSize = 0x82; struct UsecodeCallFrame { u16 offset = 0; @@ -53,7 +62,7 @@ class UsecodeInterpreterState { public: static std::optional initialize( const std::vector& itemParameter, const std::vector& contextParameter = {}, - u16 modeFlags = 0); + u16 modeFlags = 0, bool contextParameterPresent = false); bool pushCodeAddress(u16 offset, u16 segment); bool pushWord(u16 value); bool pushDword(u32 value); @@ -71,6 +80,7 @@ public: u16 stackLimit = usecodeInterpreterStackLimit; u16 temporaryWord = 0; std::optional contextParameterOffset; + std::optional contextParameterStackTop; bool processExcluded = false; u16 currentProcessId = 0; u16 impliedProcessId = 0; @@ -107,19 +117,57 @@ struct UsecodeContextFactoryFields { u16 parameterOffset = 0; }; +struct UsecodeContextCreateRequest { + FarPtr16 ownerSource{}; + FarPtr16 codeSource{}; + FarPtr16 ownerRows{}; + std::optional> itemParameter; + std::optional> contextParameter; + u16 modeFlags = 0; + u16 slotIndex = 0; + u16 valueAddOffset = 0; +}; + +struct UsecodeContextInstance { + FarPtr16 processAddress{0, 0}; + FarPtr16 callStackAddress{0, 0}; + std::array processBytes{}; + UsecodeInterpreterState interpreter; +}; + +struct UsecodeEventContext { + UsecodeContextInstance context; + FarPtr16 processIdOutput{0, 0}; + std::vector ownedRegions; +}; + bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize, const UsecodeContextFactoryFields& fields); +std::optional createUsecodeContext(UsecodeRuntimeMemory& memory, + const UsecodeContextCreateRequest& request); +bool destroyUsecodeContext(UsecodeRuntimeMemory& memory, + const UsecodeContextInstance& context) noexcept; +std::optional createUsecodeEventContext(UsecodeRuntimeMemory& memory, + const std::vector& ownerRows, u16 classId, u16 eventSlot, u16 sourceItem, + const std::vector& code, u8 itemArgumentSize); +bool destroyUsecodeEventContext(UsecodeRuntimeMemory& memory, + const UsecodeEventContext& eventContext) noexcept; class UsecodeTaskRegistry { public: + UsecodeRuntimeMemory& runtimeMemory() noexcept { return runtimeMemory_; } bool add(UsecodeProcessTask task); + bool addWithContext(UsecodeProcessTask task, UsecodeEventContext context); UsecodeProcessTask* find(u16 processId); const UsecodeProcessTask* find(u16 processId) const; + const UsecodeEventContext* context(u16 processId) const noexcept; bool remove(u16 processId); std::size_t size() const noexcept { return tasks_.size(); } private: std::map tasks_; + std::map contexts_; + UsecodeRuntimeMemory runtimeMemory_; }; } // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index e5724ea..c813b00 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -170,6 +170,47 @@ AnimPrimitiveProcessEntry* ProcessKernel::createAnimPrimitiveProcess(u8 activeGr return result; } +TeleporterProcessEntry* ProcessKernel::createTeleporterProcess(u8 activeGroup, u16 mapNumber, + u16 teleportId, u16 (&groupCounts)[32]) +{ + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + if (std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + processes_.reserve(processes_.size() + 30); + allocationSizes_.reserve(allocationSizes_.size() + 30); + processNames_.reserve(processNames_.size() + 30); + } + ownedTeleporterProcesses_.reserve(ownedTeleporterProcesses_.size() + 1); + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x00, TeleporterProcess::vtableOffset); + writeLe16(process->base, TeleporterProcess::mapNumberOffset, mapNumber); + writeLe16(process->base, TeleporterProcess::teleportIdOffset, teleportId); + setLastAllocationSize(sizeof(TeleporterProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "Teleporter"; + TeleporterProcessEntry* result = process.get(); + ownedTeleporterProcesses_.push_back(std::move(process)); + return result; +} + +bool TeleporterProcess::run(const TeleporterProcessEntry& process, LiveFixedMapItems& items, + u16 currentMapNumber, const std::vector& shapes) +{ + const auto readWord = [&process](u16 offset) { + return static_cast(process.base.bytes[offset] | + (static_cast(process.base.bytes[offset + 1]) << 8)); + }; + const u16 targetMap = readWord(mapNumberOffset); + if (targetMap != currentMapNumber) { + return false; + } + const auto destination = findTeleportEgg(items.mapItems(), shapes, + static_cast(readWord(teleportIdOffset))); + return destination && items.teleportAvatar(*destination, static_cast(targetMap)); +} + EntityVmContextProcessEntry* ProcessKernel::createUsecodeProcess(u8 activeGroup, u16 (&groupCounts)[32]) { @@ -676,6 +717,12 @@ void ProcessKernel::releaseOwnedProcess(u16 id) ownedAnimPrimitiveProcesses_.erase(animation); return; } + const auto teleporter = std::find_if(ownedTeleporterProcesses_.begin(), ownedTeleporterProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (teleporter != ownedTeleporterProcesses_.end()) { + ownedTeleporterProcesses_.erase(teleporter); + return; + } const auto usecode = std::find_if(ownedUsecodeProcesses_.begin(), ownedUsecodeProcesses_.end(), [entry](const auto& process) { return &process->base == entry; }); if (usecode != ownedUsecodeProcesses_.end()) { @@ -721,6 +768,9 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) const bool ownedUsecodeProcess = std::any_of(ownedUsecodeProcesses_.begin(), ownedUsecodeProcesses_.end(), [entry](const auto& process) { return &process->base == entry; }); + const bool ownedTeleporterProcess = std::any_of(ownedTeleporterProcesses_.begin(), + ownedTeleporterProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess && !ownedGravityProcess && !ownedAnimationProcess && !ownedUsecodeProcess || id < 3 || readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 || @@ -728,7 +778,7 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) throw std::logic_error("item process child cleanup is not ported"); } if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && !ownedAnimationProcess && - !ownedUsecodeProcess && + !ownedUsecodeProcess && !ownedTeleporterProcess && std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; })) { throw std::logic_error("external process ownership is not ported"); diff --git a/rebuild/remorse/src/usecode_archive.cpp b/rebuild/remorse/src/usecode_archive.cpp index dfbdb3c..98e4cfc 100644 --- a/rebuild/remorse/src/usecode_archive.cpp +++ b/rebuild/remorse/src/usecode_archive.cpp @@ -1,5 +1,7 @@ #include "remorse/usecode_archive.h" +#include +#include #include namespace remorse { @@ -16,6 +18,34 @@ u32 readDword(const std::vector& bytes, std::size_t offset) (static_cast(bytes[offset + 2]) << 16) | (static_cast(bytes[offset + 3]) << 24); } +void writeWord(std::vector& bytes, std::size_t offset, u16 value) +{ + bytes[offset] = static_cast(value); + bytes[offset + 1] = static_cast(value >> 8); +} + +void writeDword(std::vector& bytes, std::size_t offset, u32 value) +{ + writeWord(bytes, offset, static_cast(value)); + writeWord(bytes, offset + 2, static_cast(value >> 16)); +} + +bool isNull(FarPtr16 address) noexcept +{ + return address.offset == 0 && address.segment == 0; +} + +bool sameAddress(FarPtr16 left, FarPtr16 right) noexcept +{ + return left.offset == right.offset && left.segment == right.segment; +} + +std::vector serialize(const UsecodeLoadedChunkProcessLayout& layout) +{ + const auto* first = reinterpret_cast(&layout); + return std::vector(first, first + sizeof(layout)); +} + std::optional readEventBodyFromDescriptors(const UsecodeClass& usecodeClass, const std::vector& descriptors, std::size_t descriptorOffset, u32 eventId) { @@ -41,6 +71,54 @@ std::optional readEventBodyFromDescriptors(const UsecodeClass& } // namespace +std::optional UsecodeRuntimeMemory::allocate(std::size_t byteCount, u8 initialValue) +{ + constexpr std::size_t maxSegmentBytes = static_cast(std::numeric_limits::max()) + 1; + if (byteCount == 0 || byteCount > maxSegmentBytes || nextSegment_ > std::numeric_limits::max()) { + return std::nullopt; + } + const auto segment = static_cast(nextSegment_++); + allocations_.emplace(segment, std::vector(byteCount, initialValue)); + return FarPtr16{0, segment}; +} + +bool UsecodeRuntimeMemory::release(FarPtr16 address) noexcept +{ + return address.offset == 0 && address.segment != 0 && allocations_.erase(address.segment) != 0; +} + +bool UsecodeRuntimeMemory::contains(FarPtr16 address, std::size_t byteCount) const noexcept +{ + const auto allocation = allocations_.find(address.segment); + return address.segment != 0 && allocation != allocations_.end() && + address.offset <= allocation->second.size() && + byteCount <= allocation->second.size() - address.offset; +} + +std::optional> UsecodeRuntimeMemory::read(FarPtr16 address, std::size_t byteCount) const +{ + const auto allocation = allocations_.find(address.segment); + if (address.segment == 0 || allocation == allocations_.end() || + address.offset > allocation->second.size() || + byteCount > allocation->second.size() - address.offset) { + return std::nullopt; + } + return std::vector(allocation->second.begin() + address.offset, + allocation->second.begin() + address.offset + byteCount); +} + +bool UsecodeRuntimeMemory::write(FarPtr16 address, const std::vector& bytes) +{ + const auto allocation = allocations_.find(address.segment); + if (address.segment == 0 || allocation == allocations_.end() || + address.offset > allocation->second.size() || + bytes.size() > allocation->second.size() - address.offset) { + return false; + } + std::copy(bytes.begin(), bytes.end(), allocation->second.begin() + address.offset); + return true; +} + u16 selectUsecodeClassId(const UsecodeItemIdentity& item, const UsecodeClassBases& bases) { if (item.isNpc && (item.status & 2) == 0) { @@ -141,17 +219,73 @@ const UsecodeEventBody* UsecodeSlotChunkCache::ensureLoaded(u16 chunkIndex) if (chunkIndex >= chunks_.size()) { return nullptr; } - auto& body = chunks_[chunkIndex]; + auto& process = chunks_[chunkIndex]; auto& state = ownerBuffers_.chunkStates[chunkIndex]; - if (!body) { - if (state != 0xffff) { + if (!process) { + if (state != 0xffff || usecodeClass_.classId > std::numeric_limits::max()) { return nullptr; } auto loadedBody = readEventBodyFromDescriptors(usecodeClass_, ownerBuffers_.descriptors, 0, chunkIndex); if (!loadedBody) { return nullptr; } - chunks_[chunkIndex] = std::move(*loadedBody); + + auto processAddress = runtimeMemory_.allocate(sizeof(UsecodeLoadedChunkProcessLayout)); + if (!processAddress) { + return nullptr; + } + auto chunkBuffer = runtimeMemory_.allocate(loadedBody->bytes.size(), 0xff); + if (!chunkBuffer) { + runtimeMemory_.release(*processAddress); + return nullptr; + } + + UsecodeLoadedChunkProcess loadedProcess; + loadedProcess.processAddress = *processAddress; + loadedProcess.layout.vtableOffset = 0x673c; + loadedProcess.layout.previous = loadedListHead_; + loadedProcess.layout.chunkBuffer = *chunkBuffer; + const std::size_t descriptorOffset = static_cast(chunkIndex) * 6; + const u32 sourceOffset = readDword(ownerBuffers_.descriptors, descriptorOffset + 2); + loadedProcess.layout.savedSource = FarPtr16{ + static_cast(sourceOffset), static_cast(sourceOffset >> 16)}; + loadedProcess.layout.slotIndex = static_cast(usecodeClass_.classId); + loadedProcess.layout.chunkIndex = chunkIndex; + loadedProcess.body = std::move(*loadedBody); + + if (!runtimeMemory_.write(loadedProcess.layout.chunkBuffer, loadedProcess.body.bytes) || + !runtimeMemory_.write(loadedProcess.processAddress, serialize(loadedProcess.layout))) { + runtimeMemory_.release(loadedProcess.layout.chunkBuffer); + runtimeMemory_.release(loadedProcess.processAddress); + return nullptr; + } + + chunks_[chunkIndex] = std::move(loadedProcess); + if (isNull(loadedListHead_)) { + loadedListTail_ = *processAddress; + } else { + auto* oldHead = findLoadedProcess(loadedListHead_); + if (oldHead == nullptr) { + runtimeMemory_.release(chunks_[chunkIndex]->layout.chunkBuffer); + runtimeMemory_.release(chunks_[chunkIndex]->processAddress); + chunks_[chunkIndex].reset(); + return nullptr; + } + oldHead->layout.next = *processAddress; + if (!runtimeMemory_.write(oldHead->processAddress, serialize(oldHead->layout))) { + oldHead->layout.next = FarPtr16{0, 0}; + runtimeMemory_.write(oldHead->processAddress, serialize(oldHead->layout)); + runtimeMemory_.release(chunks_[chunkIndex]->layout.chunkBuffer); + runtimeMemory_.release(chunks_[chunkIndex]->processAddress); + chunks_[chunkIndex].reset(); + return nullptr; + } + } + loadedListHead_ = *processAddress; + const auto& loadedProcessState = *chunks_[chunkIndex]; + writeDword(ownerBuffers_.descriptors, descriptorOffset + 2, + static_cast(loadedProcessState.layout.chunkBuffer.offset) | + (static_cast(loadedProcessState.layout.chunkBuffer.segment) << 16)); state = 1; } else { if (state >= 29999) { @@ -159,7 +293,7 @@ const UsecodeEventBody* UsecodeSlotChunkCache::ensureLoaded(u16 chunkIndex) } ++state; } - return &*chunks_[chunkIndex]; + return &chunks_[chunkIndex]->body; } bool UsecodeSlotChunkCache::release(u16 chunkIndex) noexcept @@ -172,13 +306,28 @@ bool UsecodeSlotChunkCache::release(u16 chunkIndex) noexcept return true; } -bool UsecodeSlotChunkCache::tryUnload(u16 chunkIndex) noexcept +bool UsecodeSlotChunkCache::tryUnload(u16 chunkIndex) { - if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] != 0) { + if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] != 0 || !chunks_[chunkIndex]) { return false; } - chunks_[chunkIndex].reset(); + + auto& process = *chunks_[chunkIndex]; + const std::size_t descriptorOffset = static_cast(chunkIndex) * 6; + writeDword(ownerBuffers_.descriptors, descriptorOffset + 2, + static_cast(process.layout.savedSource.offset) | + (static_cast(process.layout.savedSource.segment) << 16)); ownerBuffers_.chunkStates[chunkIndex] = 0xffff; + if (!unlinkLoadedProcess(process.processAddress)) { + writeDword(ownerBuffers_.descriptors, descriptorOffset + 2, + static_cast(process.layout.chunkBuffer.offset) | + (static_cast(process.layout.chunkBuffer.segment) << 16)); + ownerBuffers_.chunkStates[chunkIndex] = 0; + return false; + } + runtimeMemory_.release(process.layout.chunkBuffer); + runtimeMemory_.release(process.processAddress); + chunks_[chunkIndex].reset(); return true; } @@ -190,6 +339,65 @@ u16 UsecodeSlotChunkCache::inUseCount(u16 chunkIndex) const noexcept return ownerBuffers_.chunkStates[chunkIndex]; } +const UsecodeLoadedChunkProcess* UsecodeSlotChunkCache::loadedProcess(u16 chunkIndex) const noexcept +{ + if (chunkIndex >= chunks_.size() || !chunks_[chunkIndex]) { + return nullptr; + } + return &*chunks_[chunkIndex]; +} + +std::size_t UsecodeSlotChunkCache::loadedProcessCount() const noexcept +{ + std::size_t count = 0; + for (const auto& process : chunks_) { + count += process.has_value() ? 1 : 0; + } + return count; +} + +UsecodeLoadedChunkProcess* UsecodeSlotChunkCache::findLoadedProcess(FarPtr16 processAddress) noexcept +{ + for (auto& process : chunks_) { + if (process && sameAddress(process->processAddress, processAddress)) { + return &*process; + } + } + return nullptr; +} + +bool UsecodeSlotChunkCache::unlinkLoadedProcess(FarPtr16 processAddress) +{ + auto* process = findLoadedProcess(processAddress); + if (process == nullptr) { + return false; + } + auto* older = isNull(process->layout.previous) ? nullptr : findLoadedProcess(process->layout.previous); + auto* newer = isNull(process->layout.next) ? nullptr : findLoadedProcess(process->layout.next); + if ((!isNull(process->layout.previous) && older == nullptr) || + (!isNull(process->layout.next) && newer == nullptr)) { + return false; + } + + if (older != nullptr) { + older->layout.next = process->layout.next; + if (!runtimeMemory_.write(older->processAddress, serialize(older->layout))) { + return false; + } + } else { + loadedListTail_ = process->layout.next; + } + if (newer != nullptr) { + newer->layout.previous = process->layout.previous; + if (!runtimeMemory_.write(newer->processAddress, serialize(newer->layout))) { + return false; + } + } else { + loadedListHead_ = process->layout.previous; + } + return true; +} + std::optional selectEligibleUsecodeEvent(const FlexArchive& archive, const std::vector& ownerRows, const UsecodeItemIdentity& item, const UsecodeClassBases& bases, u32 eventMask, u16 eventId) diff --git a/rebuild/remorse/src/usecode_vm.cpp b/rebuild/remorse/src/usecode_vm.cpp index 3abfc65..23f02f0 100644 --- a/rebuild/remorse/src/usecode_vm.cpp +++ b/rebuild/remorse/src/usecode_vm.cpp @@ -1,14 +1,30 @@ #include "remorse/usecode_vm.h" +#include "remorse/usecode_archive.h" #include namespace remorse { +namespace { + +void writeWord(u8* bytes, std::size_t offset, u16 value) +{ + bytes[offset] = static_cast(value); + bytes[offset + 1] = static_cast(value >> 8); +} + +void writeFarPointer(u8* bytes, std::size_t offset, FarPtr16 pointer) +{ + writeWord(bytes, offset, pointer.offset); + writeWord(bytes, offset + sizeof(u16), pointer.segment); +} + +} // namespace std::optional UsecodeInterpreterState::initialize( const std::vector& itemParameter, const std::vector& contextParameter, - u16 modeFlags) + u16 modeFlags, bool contextParameterPresent) { - const bool saveStackPointer = !contextParameter.empty() && modeFlags != 0; + const bool saveStackPointer = (!contextParameter.empty() || contextParameterPresent) && modeFlags != 0; const std::size_t savedPointerBytes = saveStackPointer ? sizeof(FarPtr16) : 0; if (itemParameter.size() > usecodeInterpreterStackLimit || contextParameter.size() > usecodeInterpreterStackLimit - itemParameter.size() || @@ -22,10 +38,12 @@ std::optional UsecodeInterpreterState::initialize( std::copy(bytes.begin(), bytes.end(), state.valueStack.begin() + state.stackTop); }; pushBytes(itemParameter); + const std::size_t stackTopBeforeContextParameter = state.stackTop; pushBytes(contextParameter); if (saveStackPointer) { state.stackTop -= savedPointerBytes; state.contextParameterOffset = static_cast(state.stackTop - sizeof(u16) * 2); + state.contextParameterStackTop = static_cast(stackTopBeforeContextParameter); } return state; } @@ -484,6 +502,190 @@ bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize, return true; } +std::optional createUsecodeContext(UsecodeRuntimeMemory& memory, + const UsecodeContextCreateRequest& request) +{ + const bool hasOwnerSource = request.ownerSource.offset != 0 || request.ownerSource.segment != 0; + if (!memory.contains(request.codeSource, 1) || !memory.contains(request.ownerRows, 9) || + (hasOwnerSource && !memory.contains(request.ownerSource, 1))) { + return std::nullopt; + } + + std::vector itemParameter; + if (request.modeFlags != 0 && request.itemParameter) { + if (request.itemParameter->size() != request.modeFlags) { + return std::nullopt; + } + itemParameter = *request.itemParameter; + } + const std::vector contextParameter = request.contextParameter.value_or(std::vector{}); + auto interpreter = UsecodeInterpreterState::initialize(itemParameter, contextParameter, + request.modeFlags, request.contextParameter.has_value()); + if (!interpreter || !interpreter->pushCodeAddress(request.slotIndex, request.valueAddOffset)) { + return std::nullopt; + } + + const auto processAddress = memory.allocate(usecodeContextProcessSize); + if (!processAddress) { + return std::nullopt; + } + const auto callStackAddress = memory.allocate(usecodeInterpreterCallStackSize); + if (!callStackAddress) { + memory.release(*processAddress); + return std::nullopt; + } + + UsecodeContextInstance context; + context.processAddress = *processAddress; + context.callStackAddress = *callStackAddress; + writeFarPointer(context.processBytes.data(), usecodeContextInterpreterOffset, *callStackAddress); + std::copy(interpreter->valueStack.begin() + interpreter->stackTop, interpreter->valueStack.end(), + context.processBytes.begin() + usecodeContextInterpreterOffset + interpreter->stackTop); + + const auto stackTopOffset = static_cast(processAddress->offset) + + usecodeContextInterpreterOffset + static_cast(interpreter->stackTop); + const auto stackBaseOffset = static_cast(processAddress->offset) + usecodeContextStackPointerOffset; + if (stackTopOffset > 0xffff || stackBaseOffset > 0xffff) { + memory.release(*callStackAddress); + memory.release(*processAddress); + return std::nullopt; + } + writeFarPointer(context.processBytes.data(), usecodeContextStackPointerOffset, + FarPtr16{static_cast(stackTopOffset), processAddress->segment}); + writeFarPointer(context.processBytes.data(), usecodeContextStackBaseOffset, + FarPtr16{static_cast(stackBaseOffset), processAddress->segment}); + writeWord(context.processBytes.data(), usecodeContextStackLimitOffset, interpreter->stackLimit); + writeFarPointer(context.processBytes.data(), usecodeContextCodeSourceOffset, request.codeSource); + writeFarPointer(context.processBytes.data(), usecodeContextSelfPointerOffset, *processAddress); + writeFarPointer(context.processBytes.data(), usecodeContextOwnerRowsOffset, request.ownerRows); + + const UsecodeContextFactoryFields fields{request.ownerSource, request.modeFlags, + request.slotIndex, request.valueAddOffset, interpreter->contextParameterOffset.value_or(0)}; + if (!writeUsecodeContextFactoryFields(context.processBytes.data(), context.processBytes.size(), fields)) { + memory.release(*callStackAddress); + memory.release(*processAddress); + return std::nullopt; + } + if (interpreter->contextParameterStackTop) { + const std::size_t savedPointerOffset = usecodeContextInterpreterOffset + interpreter->stackTop; + const u32 savedStackOffset = static_cast(processAddress->offset) + + usecodeContextInterpreterOffset + *interpreter->contextParameterStackTop; + if (savedPointerOffset > context.processBytes.size() - sizeof(FarPtr16) || savedStackOffset > 0xffff) { + memory.release(*callStackAddress); + memory.release(*processAddress); + return std::nullopt; + } + writeFarPointer(context.processBytes.data(), savedPointerOffset, + FarPtr16{static_cast(savedStackOffset), processAddress->segment}); + } + + std::vector callStackBytes(usecodeInterpreterCallStackSize, 0); + for (u16 index = 0; index < interpreter->callFrameCount; ++index) { + const std::size_t frameOffset = static_cast(index) * 2 * sizeof(u16); + writeWord(callStackBytes.data(), frameOffset, interpreter->callFrames[index].offset); + writeWord(callStackBytes.data(), frameOffset + sizeof(u16), interpreter->callFrames[index].segment); + } + writeWord(callStackBytes.data(), 0x80, interpreter->callFrameCount); + + const std::vector processBytes(context.processBytes.begin(), context.processBytes.end()); + if (!memory.write(*processAddress, processBytes) || !memory.write(*callStackAddress, callStackBytes)) { + memory.release(*callStackAddress); + memory.release(*processAddress); + return std::nullopt; + } + context.interpreter = std::move(*interpreter); + return context; +} + +bool destroyUsecodeContext(UsecodeRuntimeMemory& memory, const UsecodeContextInstance& context) noexcept +{ + const bool callStackReleased = memory.release(context.callStackAddress); + const bool processReleased = memory.release(context.processAddress); + return callStackReleased && processReleased; +} + +std::optional createUsecodeEventContext(UsecodeRuntimeMemory& memory, + const std::vector& ownerRows, u16 classId, u16 eventSlot, u16 sourceItem, + const std::vector& code, u8 itemArgumentSize) +{ + constexpr std::size_t ownerRowSize = 13; + const std::size_t ownerRowOffset = static_cast(classId) * ownerRowSize; + if (code.size() <= usecodeEventBytecodeOffset || + (itemArgumentSize != 0 && itemArgumentSize != sizeof(u16)) || + ownerRowOffset > ownerRows.size() || ownerRows.size() - ownerRowOffset < ownerRowSize) { + return std::nullopt; + } + + UsecodeEventContext eventContext; + const auto allocateRegion = [&memory, &eventContext](const std::vector& bytes) + -> std::optional { + auto region = memory.allocate(bytes.size()); + if (!region) { + return std::nullopt; + } + if (!memory.write(*region, bytes)) { + memory.release(*region); + return std::nullopt; + } + eventContext.ownedRegions.push_back(*region); + return region; + }; + + const auto codeRegion = allocateRegion(code); + const std::vector ownerRow(ownerRows.begin() + ownerRowOffset, + ownerRows.begin() + ownerRowOffset + ownerRowSize); + const auto ownerRowRegion = codeRegion ? allocateRegion(ownerRow) : std::nullopt; + const auto outputRegion = ownerRowRegion ? memory.allocate(sizeof(u16)) : std::nullopt; + if (!codeRegion || !ownerRowRegion || !outputRegion) { + if (outputRegion) { + memory.release(*outputRegion); + } + for (const auto region : eventContext.ownedRegions) { + memory.release(region); + } + return std::nullopt; + } + eventContext.processIdOutput = *outputRegion; + eventContext.ownedRegions.push_back(*outputRegion); + + std::vector contextParameter{ + static_cast(outputRegion->offset), + static_cast(outputRegion->offset >> 8), + static_cast(outputRegion->segment), + static_cast(outputRegion->segment >> 8) + }; + UsecodeContextCreateRequest request; + request.codeSource = *codeRegion; + request.ownerRows = FarPtr16{4, ownerRowRegion->segment}; + if (itemArgumentSize == sizeof(u16)) { + request.itemParameter = std::vector{static_cast(sourceItem), + static_cast(sourceItem >> 8)}; + } + request.contextParameter = std::move(contextParameter); + request.modeFlags = itemArgumentSize; + request.slotIndex = classId; + request.valueAddOffset = eventSlot; + auto context = createUsecodeContext(memory, request); + if (!context) { + for (const auto region : eventContext.ownedRegions) { + memory.release(region); + } + return std::nullopt; + } + eventContext.context = std::move(*context); + return eventContext; +} + +bool destroyUsecodeEventContext(UsecodeRuntimeMemory& memory, + const UsecodeEventContext& eventContext) noexcept +{ + bool released = destroyUsecodeContext(memory, eventContext.context); + for (const auto region : eventContext.ownedRegions) { + released = memory.release(region) && released; + } + return released; +} + UsecodeStepResult UsecodeProcessTask::step(const UsecodeOpcodeServices& services) { if (halted) { @@ -502,6 +704,19 @@ bool UsecodeTaskRegistry::add(UsecodeProcessTask task) return tasks_.emplace(task.processId, std::move(task)).second; } +bool UsecodeTaskRegistry::addWithContext(UsecodeProcessTask task, UsecodeEventContext context) +{ + const u16 processId = task.processId; + if (processId < 3 || tasks_.find(processId) != tasks_.end() || contexts_.find(processId) != contexts_.end()) { + destroyUsecodeEventContext(runtimeMemory_, context); + return false; + } + task.interpreter = context.context.interpreter; + tasks_.emplace(processId, std::move(task)); + contexts_.emplace(processId, std::move(context)); + return true; +} + UsecodeProcessTask* UsecodeTaskRegistry::find(u16 processId) { const auto found = tasks_.find(processId); @@ -514,9 +729,25 @@ const UsecodeProcessTask* UsecodeTaskRegistry::find(u16 processId) const return found == tasks_.end() ? nullptr : &found->second; } +const UsecodeEventContext* UsecodeTaskRegistry::context(u16 processId) const noexcept +{ + const auto found = contexts_.find(processId); + return found == contexts_.end() ? nullptr : &found->second; +} + bool UsecodeTaskRegistry::remove(u16 processId) { - return tasks_.erase(processId) != 0; + const auto task = tasks_.find(processId); + if (task == tasks_.end()) { + return false; + } + const auto context = contexts_.find(processId); + if (context != contexts_.end()) { + destroyUsecodeEventContext(runtimeMemory_, context->second); + contexts_.erase(context); + } + tasks_.erase(task); + return true; } } // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index acf676f..10f9be6 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -156,21 +156,40 @@ std::optional queueUsecodeTask(AppState& state, remorse::u16 class state.diagnosticKernel.activeGroup(), state.diagnosticGroupCounts); const remorse::u16 processId = static_cast(process->base.bytes[2] | (static_cast(process->base.bytes[3]) << 8)); + + const auto terminateProcess = [&state, processId]() { + state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts); + state.diagnosticKernel.clearTerminatedProcesses(); + }; + auto eventContext = remorse::createUsecodeEventContext(state.usecodeTasks.runtimeMemory(), + state.usecodeOwnerRows, classId, eventSlot, sourceItem, code, itemArgumentSize); + if (!eventContext) { + terminateProcess(); + return std::nullopt; + } + const std::vector processIdBytes{ + static_cast(processId), static_cast(processId >> 8)}; + if (!state.usecodeTasks.runtimeMemory().write(eventContext->processIdOutput, processIdBytes)) { + remorse::destroyUsecodeEventContext(state.usecodeTasks.runtimeMemory(), *eventContext); + terminateProcess(); + return std::nullopt; + } + auto task = remorse::UsecodeProcessTask::create(processId, classId, eventSlot, sourceItem, std::move(code), itemArgumentSize, std::move(extraArguments)); - if (!task) { - state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts); - state.diagnosticKernel.clearTerminatedProcesses(); + if (!task || !state.usecodeTasks.addWithContext(std::move(*task), std::move(*eventContext))) { + terminateProcess(); return std::nullopt; } - const remorse::UsecodeContextFactoryFields factoryFields{{0, 0}, itemArgumentSize, - classId, eventSlot, task->interpreter.contextParameterOffset.value_or(0)}; - if (!remorse::writeUsecodeContextFactoryFields(reinterpret_cast(process), - sizeof(*process), factoryFields) || !state.usecodeTasks.add(std::move(*task))) { - state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts); - state.diagnosticKernel.clearTerminatedProcesses(); + const auto* registeredContext = state.usecodeTasks.context(processId); + if (registeredContext == nullptr) { + state.usecodeTasks.remove(processId); + terminateProcess(); return std::nullopt; } + std::copy(registeredContext->context.processBytes.begin() + remorse::usecodeContextSlotIndexOffset, + registeredContext->context.processBytes.end(), + reinterpret_cast(process) + remorse::usecodeContextSlotIndexOffset); return processId; } @@ -501,12 +520,32 @@ void loadSceneAsync(HWND window, AppState& state) options.viewCenter = spawn; remorse::LiveFixedMapItems liveItems(std::move(*stagedItems), std::move(containedItems)); liveItems.initializeAvatar(); - remorse::StagedFixedMapItem diagnosticStart; - diagnosticStart.data.x = static_cast(spawn.x / 2); - diagnosticStart.data.y = static_cast(spawn.y / 2); - diagnosticStart.data.z = static_cast(spawn.z); - liveItems.teleportAvatar(startingEgg ? *startingEgg : diagnosticStart, - static_cast(state.mapIndex)); + if (startingEgg) { + remorse::ProcessKernel teleporterKernel; + remorse::u16 teleporterGroupCounts[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + teleporterKernel.createProcess(1, teleporterGroupCounts); + } + auto* teleporter = teleporterKernel.createTeleporterProcess(1, + static_cast(state.mapIndex), 0x1e, teleporterGroupCounts); + const remorse::u16 processId = static_cast(teleporter->base.bytes[2] | + (static_cast(teleporter->base.bytes[3]) << 8)); + const bool teleported = remorse::TeleporterProcess::run(*teleporter, liveItems, + static_cast(state.mapIndex), *shapeTypes); + teleporter->base.bytes[0x18] |= 4; + teleporterKernel.terminateProcess(processId, teleporterGroupCounts); + if (!teleported) { + setLoadFailure(state, L"The teleporter process could not resolve its map and egg destination."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + } else { + remorse::StagedFixedMapItem diagnosticStart; + diagnosticStart.data.x = static_cast(spawn.x / 2); + diagnosticStart.data.y = static_cast(spawn.y / 2); + diagnosticStart.data.z = static_cast(spawn.z); + liveItems.teleportAvatar(diagnosticStart, static_cast(state.mapIndex)); + } auto renderer = remorse::loadMapSceneRenderer(state.root, state.mapIndex); if (renderer) { hatchGlobsInFastArea(liveItems, *renderer, remorse::calculateFastAreaRange(spawn)); diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index 9a4ee99..38ce7aa 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -1050,5 +1050,101 @@ int main() assert(animationKernel.processAt(6) == nullptr && animationKernel.allocationSizeAt(6) == 0); assert(animationGroups[1] == 6 && animationKernel.itemHasProcess(1)); + remorse::ProcessKernel movementKernel; + remorse::u16 movementGroups[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + movementKernel.createProcess(1, movementGroups); + } + assert(movementKernel.createSystemTimerProcess(1, movementGroups)); + assert(movementKernel.createKeyboardProcess(1, movementGroups)); + assert(movementKernel.createControllerProcess(1, movementGroups)); + remorse::KeyEvent movementKey{}; + movementKey.scanCode = 0x48; + movementKey.field8 = 1; + assert(movementKernel.queuePendingKeyEvent(movementKey)); + remorse::ControllerMovementState movementController; + movementKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process, + remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { + if (process.bytes[0] == 0xa6 && process.bytes[1] == 0x3a) { + assert(selector == 0x10 && filter == 0); + static_cast(context)->handleDirectionalKey( + event.scanCode, event.modifiers, event.field8 != 0); + } + }, &movementController); + const auto movementRequest = movementController.request(); + assert(movementRequest.animation == 1 && movementRequest.direction == 14); + + remorse::AnimationClip controllerWalk{}; + controllerWalk.header = {17, 4, 0, 0}; + controllerWalk.frameCount = 17; + controllerWalk.frames.resize(17 * 8); + auto& controllerStep = controllerWalk.frames[7 * 17 + 1]; + controllerStep.bytes[4] = 1; + controllerStep.bytes[5] = 2; + remorse::LiveFixedMapItems movementItems({}); + assert(movementItems.initializeAvatar()); + remorse::StagedFixedMapItem movementSpawn{}; + movementSpawn.data.x = 512; + movementSpawn.data.y = 512; + assert(movementItems.teleportAvatar(movementSpawn, 1)); + std::vector movementShapes(2); + movementShapes[1].x = movementShapes[1].y = movementShapes[1].z = 2; + auto* controllerAnimation = movementKernel.createAnimPrimitiveProcess(1, 1, + movementRequest.animation, movementRequest.direction, controllerWalk, movementGroups); + assert(controllerAnimation); + const remorse::u16 controllerAnimationId = static_cast( + controllerAnimation->base.bytes[2] | (static_cast(controllerAnimation->base.bytes[3]) << 8)); + assert(movementKernel.startAnimPrimitiveProcess(controllerAnimationId, movementItems, controllerWalk)); + struct ControllerTickContext { + remorse::ProcessKernel* kernel; + remorse::LiveFixedMapItems* items; + const remorse::AnimationClip* clip; + const std::vector* shapes; + remorse::FastAreaRange fastArea; + remorse::u16 processId; + std::optional advanced; + } controllerTick{&movementKernel, &movementItems, &controllerWalk, &movementShapes, + remorse::calculateFastAreaRange({512, 512, 0}), controllerAnimationId}; + movementKernel.runTimedSchedulerPass(1, [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& tick = *static_cast(context); + if (&process == tick.kernel->processAt(tick.processId)) { + tick.advanced = tick.kernel->advanceGroundedAnimPrimitive(tick.processId, + *tick.items, *tick.clip, *tick.shapes, tick.fastArea); + } + }, &controllerTick); + assert(controllerTick.advanced == true && movementKernel.itemHasProcess(1)); + assert(movementItems.findItem(1)->data.x == 510 && movementItems.findItem(1)->data.y == 510 && + movementItems.findNpcAnimation(1)->frame == 1); + movementKey.field8 = 0; + assert(movementKernel.queuePendingKeyEvent(movementKey)); + movementKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process, + remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { + if (process.bytes[0] == 0xa6 && process.bytes[1] == 0x3a) { + assert(selector == 0x10 && filter == 0); + static_cast(context)->handleDirectionalKey( + event.scanCode, event.modifiers, event.field8 != 0); + } + }, &movementController); + assert(movementController.request().animation == 0 && movementController.request().direction == 14); + + remorse::ProcessKernel teleporterKernel; + remorse::u16 teleporterGroups[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + teleporterKernel.createProcess(1, teleporterGroups); + } + auto* teleporter = teleporterKernel.createTeleporterProcess(1, 1, 0x1e, teleporterGroups); + const remorse::u16 teleporterProcessId = static_cast( + teleporter->base.bytes[2] | (static_cast(teleporter->base.bytes[3]) << 8)); + assert(teleporterKernel.processAt(teleporterProcessId) == &teleporter->base && + teleporterKernel.allocationSizeAt(teleporterProcessId) == 0x36 && + std::strcmp(teleporterKernel.processNameAt(teleporterProcessId), "Teleporter") == 0); + assert(teleporter->base.bytes[0] == 0x3a && teleporter->base.bytes[1] == 0x0f && + teleporter->base.bytes[0x32] == 1 && teleporter->base.bytes[0x33] == 0 && + teleporter->base.bytes[0x34] == 0x1e && teleporter->base.bytes[0x35] == 0); + teleporter->base.bytes[0x18] |= 4; + teleporterKernel.terminateProcess(teleporterProcessId, teleporterGroups); + assert(teleporterKernel.processAt(teleporterProcessId) == nullptr && + teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 3); + return 0; } diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index b020a0f..64a41ff 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -23,6 +23,26 @@ int main() std::equal(prefix.begin(), prefix.end(), body.begin()) && body[remorse::usecodeEventBytecodeOffset] == 0x0b; }; + const auto readDescriptorPointer = [](const std::vector& descriptors, + std::size_t chunkIndex) { + const std::size_t offset = chunkIndex * 6 + 2; + return static_cast(descriptors[offset]) | + (static_cast(descriptors[offset + 1]) << 8) | + (static_cast(descriptors[offset + 2]) << 16) | + (static_cast(descriptors[offset + 3]) << 24); + }; + + remorse::UsecodeRuntimeMemory boundedMemory; + assert(!boundedMemory.allocate(0)); + assert(!boundedMemory.allocate(0x10001)); + const auto fullSegment = boundedMemory.allocate(0x10000, 0x5a); + assert(fullSegment); + const auto finalSegmentByte = boundedMemory.read({0xffff, fullSegment->segment}, 1); + assert(finalSegmentByte && finalSegmentByte->size() == 1 && finalSegmentByte->front() == 0x5a); + assert(!boundedMemory.read({0xffff, fullSegment->segment}, 2)); + assert(!boundedMemory.read({0, 0xffff}, 1)); + assert(boundedMemory.release(*fullSegment) && boundedMemory.allocationCount() == 0); + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); assert(root.has_value()); @@ -66,6 +86,36 @@ int main() [](remorse::u16 state) { return state == 0xffff; })); assert(std::equal(npcTriggerOwnerBuffers->descriptors.begin(), npcTriggerOwnerBuffers->descriptors.end(), npcTriggerClass->bytes.begin() + 20)); + remorse::UsecodeSlotChunkCache npcTriggerChunkCache(*npcTriggerClass); + const auto originalNpcTriggerDescriptors = npcTriggerChunkCache.ownerBuffers().descriptors; + std::optional npcTriggerChunkIndex; + for (remorse::u16 chunkIndex = 0; chunkIndex < npcTriggerChunkCache.chunkCount(); ++chunkIndex) { + if (npcTriggerChunkCache.ensureLoaded(chunkIndex)) { + npcTriggerChunkIndex = chunkIndex; + break; + } + } + assert(npcTriggerChunkIndex); + const auto npcTriggerSourcePointer = readDescriptorPointer( + originalNpcTriggerDescriptors, *npcTriggerChunkIndex); + const auto* loadedNpcTriggerProcess = npcTriggerChunkCache.loadedProcess(*npcTriggerChunkIndex); + assert(loadedNpcTriggerProcess && loadedNpcTriggerProcess->layout.slotIndex == 0x363 && + loadedNpcTriggerProcess->layout.chunkIndex == *npcTriggerChunkIndex && + loadedNpcTriggerProcess->layout.savedSource.offset == static_cast(npcTriggerSourcePointer) && + loadedNpcTriggerProcess->layout.savedSource.segment == static_cast(npcTriggerSourcePointer >> 16)); + const auto loadedNpcTriggerBytes = npcTriggerChunkCache.runtimeMemory().read( + loadedNpcTriggerProcess->layout.chunkBuffer, loadedNpcTriggerProcess->body.length); + assert(loadedNpcTriggerBytes && *loadedNpcTriggerBytes == loadedNpcTriggerProcess->body.bytes && + readDescriptorPointer(npcTriggerChunkCache.ownerBuffers().descriptors, *npcTriggerChunkIndex) == + (static_cast(loadedNpcTriggerProcess->layout.chunkBuffer.offset) | + (static_cast(loadedNpcTriggerProcess->layout.chunkBuffer.segment) << 16))); + assert(npcTriggerChunkCache.release(*npcTriggerChunkIndex)); + assert(npcTriggerChunkCache.tryUnload(*npcTriggerChunkIndex)); + assert(npcTriggerChunkCache.loadedProcessCount() == 0 && + npcTriggerChunkCache.runtimeMemory().allocationCount() == 0 && + readDescriptorPointer(npcTriggerChunkCache.ownerBuffers().descriptors, *npcTriggerChunkIndex) == + npcTriggerSourcePointer); + auto inconsistentOwnerHeader = *eventClass; inconsistentOwnerHeader.extraSlotCount = 1; assert(!remorse::initializeUsecodeSlotOwnerBuffers(inconsistentOwnerHeader)); @@ -74,9 +124,24 @@ int main() assert(eventBody->bytes.size() == 0x1fd6 && eventBody->bytes.front() == eventClass->bytes[0xd4]); remorse::UsecodeSlotChunkCache eventChunkCache(*eventClass); assert(eventChunkCache.chunkCount() == 32); + const auto sourceEventPointer = readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a); const auto* loadedEventChunk = eventChunkCache.ensureLoaded(0x0a); assert(loadedEventChunk && loadedEventChunk->bytes == eventBody->bytes && eventChunkCache.inUseCount(0x0a) == 1); + const auto* loadedEventProcess = eventChunkCache.loadedProcess(0x0a); + assert(loadedEventProcess && loadedEventProcess->layout.vtableOffset == 0x673c && + loadedEventProcess->layout.slotIndex == 0x361 && loadedEventProcess->layout.chunkIndex == 0x0a && + loadedEventProcess->layout.savedSource.offset == static_cast(sourceEventPointer) && + loadedEventProcess->layout.savedSource.segment == static_cast(sourceEventPointer >> 16)); + const auto loadedEventBytes = eventChunkCache.runtimeMemory().read( + loadedEventProcess->layout.chunkBuffer, loadedEventProcess->body.length); + assert(loadedEventBytes && *loadedEventBytes == loadedEventProcess->body.bytes && + eventChunkCache.loadedListHead().offset == loadedEventProcess->processAddress.offset && + eventChunkCache.loadedListHead().segment == loadedEventProcess->processAddress.segment && + eventChunkCache.loadedProcessCount() == 1 && eventChunkCache.runtimeMemory().allocationCount() == 2); + assert(readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a) == + (static_cast(loadedEventProcess->layout.chunkBuffer.offset) | + (static_cast(loadedEventProcess->layout.chunkBuffer.segment) << 16))); const auto* reusedEventChunk = eventChunkCache.ensureLoaded(0x0a); assert(reusedEventChunk == loadedEventChunk && eventChunkCache.inUseCount(0x0a) == 2); assert(eventChunkCache.release(0x0a) && eventChunkCache.inUseCount(0x0a) == 1); @@ -85,6 +150,9 @@ int main() assert(!eventChunkCache.release(0x0a)); assert(eventChunkCache.tryUnload(0x0a)); assert(eventChunkCache.ownerBuffers().chunkStates[0x0a] == 0xffff); + assert(eventChunkCache.loadedProcessCount() == 0 && eventChunkCache.runtimeMemory().allocationCount() == 0 && + eventChunkCache.loadedListHead().offset == 0 && eventChunkCache.loadedListHead().segment == 0 && + readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a) == sourceEventPointer); const auto* reloadedEventChunk = eventChunkCache.ensureLoaded(0x0a); assert(reloadedEventChunk && reloadedEventChunk->bytes == eventBody->bytes && eventChunkCache.inUseCount(0x0a) == 1); @@ -95,6 +163,49 @@ int main() assert(eventChunkCache.inUseCount(0x0a) == 29999); assert(eventChunkCache.ensureLoaded(0x0a) == nullptr && eventChunkCache.inUseCount(0x0a) == 29999); assert(eventChunkCache.ensureLoaded(0x20) == nullptr && eventChunkCache.inUseCount(0x20) == 0); + + remorse::UsecodeClass syntheticOwnerClass; + syntheticOwnerClass.classId = 0x123; + syntheticOwnerClass.name = "SYNTHETIC"; + syntheticOwnerClass.codeBase = 0xd4; + syntheticOwnerClass.bytes.resize(syntheticOwnerClass.codeBase + 2); + syntheticOwnerClass.bytes[20] = 1; + syntheticOwnerClass.bytes[22] = 1; + syntheticOwnerClass.bytes[26] = 1; + syntheticOwnerClass.bytes[28] = 2; + syntheticOwnerClass.bytes[syntheticOwnerClass.codeBase] = 0xaa; + syntheticOwnerClass.bytes[syntheticOwnerClass.codeBase + 1] = 0xbb; + remorse::UsecodeSlotChunkCache syntheticChunkCache(std::move(syntheticOwnerClass)); + const auto syntheticSourceDescriptors = syntheticChunkCache.ownerBuffers().descriptors; + const auto* firstSyntheticBody = syntheticChunkCache.ensureLoaded(0); + const auto* secondSyntheticBody = syntheticChunkCache.ensureLoaded(1); + assert(firstSyntheticBody && firstSyntheticBody->bytes == std::vector{0xaa} && + secondSyntheticBody && secondSyntheticBody->bytes == std::vector{0xbb}); + const auto* firstSyntheticProcess = syntheticChunkCache.loadedProcess(0); + const auto* secondSyntheticProcess = syntheticChunkCache.loadedProcess(1); + assert(firstSyntheticProcess && secondSyntheticProcess && + secondSyntheticProcess->layout.previous.offset == firstSyntheticProcess->processAddress.offset && + secondSyntheticProcess->layout.previous.segment == firstSyntheticProcess->processAddress.segment && + firstSyntheticProcess->layout.next.offset == secondSyntheticProcess->processAddress.offset && + firstSyntheticProcess->layout.next.segment == secondSyntheticProcess->processAddress.segment && + syntheticChunkCache.loadedListHead().offset == secondSyntheticProcess->processAddress.offset && + syntheticChunkCache.loadedListHead().segment == secondSyntheticProcess->processAddress.segment); + const auto firstSyntheticSourcePointer = readDescriptorPointer( + syntheticSourceDescriptors, 0); + const auto secondSyntheticSourcePointer = readDescriptorPointer( + syntheticSourceDescriptors, 1); + assert(syntheticChunkCache.release(0) && syntheticChunkCache.tryUnload(0)); + assert(syntheticChunkCache.loadedProcessCount() == 1 && + syntheticChunkCache.loadedListHead().offset == secondSyntheticProcess->processAddress.offset && + syntheticChunkCache.loadedListHead().segment == secondSyntheticProcess->processAddress.segment && + syntheticChunkCache.loadedProcess(1)->layout.previous.offset == 0 && + syntheticChunkCache.loadedProcess(1)->layout.previous.segment == 0 && + readDescriptorPointer(syntheticChunkCache.ownerBuffers().descriptors, 0) == firstSyntheticSourcePointer); + assert(syntheticChunkCache.release(1) && syntheticChunkCache.tryUnload(1)); + assert(syntheticChunkCache.loadedProcessCount() == 0 && syntheticChunkCache.runtimeMemory().allocationCount() == 0 && + syntheticChunkCache.loadedListHead().offset == 0 && syntheticChunkCache.loadedListHead().segment == 0 && + readDescriptorPointer(syntheticChunkCache.ownerBuffers().descriptors, 1) == secondSyntheticSourcePointer); + assert(!remorse::readUsecodeEventBody(*eventClass, 0x20)); assert(!remorse::loadUsecodeClass(*usecode, usecode->entryCount)); auto truncated = *eventClass; @@ -132,6 +243,48 @@ int main() assert(stagedItems && !stagedItems->empty()); const auto spawnEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x1e); assert(spawnEgg); + remorse::LiveFixedMapItems spawnSearchWorld(*stagedItems); + assert(spawnSearchWorld.initializeAvatar()); + remorse::ProcessKernel teleporterKernel; + remorse::u16 teleporterGroups[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + teleporterKernel.createProcess(1, teleporterGroups); + } + auto* teleporterProcess = teleporterKernel.createTeleporterProcess(1, 1, 0x1e, teleporterGroups); + const remorse::u16 teleporterProcessId = static_cast( + teleporterProcess->base.bytes[2] | (static_cast(teleporterProcess->base.bytes[3]) << 8)); + assert(!remorse::TeleporterProcess::run(*teleporterProcess, spawnSearchWorld, 2, *typeFlags)); + assert(spawnSearchWorld.findItem(1)->data.x == 0 && spawnSearchWorld.findItem(1)->data.y == 0); + assert(remorse::TeleporterProcess::run(*teleporterProcess, spawnSearchWorld, 1, *typeFlags)); + teleporterProcess->base.bytes[0x18] |= 4; + teleporterKernel.terminateProcess(teleporterProcessId, teleporterGroups); + assert(teleporterKernel.processAt(teleporterProcessId) == nullptr && + teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 3); + assert(spawnEgg->recordIndex < fixedMap->entries.size()); + const auto& startingEggRecord = fixedMap->entries[spawnEgg->recordIndex]; + const auto* spawnedAvatar = spawnSearchWorld.findItem(1); + assert(spawnEgg->data.x == startingEggRecord.x / 2 && + spawnEgg->data.y == startingEggRecord.y / 2 && spawnEgg->data.z == startingEggRecord.z); + assert(spawnedAvatar && spawnedAvatar->itemNumber == 1 && + spawnedAvatar->data.x == spawnEgg->data.x && spawnedAvatar->data.y == spawnEgg->data.y && + spawnedAvatar->data.z == spawnEgg->data.z && spawnedAvatar->data.mapNumber == 1); + const auto spawnUseCandidates = remorse::itemGrabSearchCandidates( + *spawnedAvatar, spawnSearchWorld.mapItems(), *typeFlags); + assert(spawnUseCandidates); + unsigned eligibleSpawnUses = 0; + for (const auto& candidate : *spawnUseCandidates) { + const auto* item = spawnSearchWorld.findItem(candidate.itemNumber); + if (!item || item->data.shape >= typeFlags->size()) continue; + const auto& shape = (*typeFlags)[item->data.shape]; + const remorse::UsecodeItemIdentity spawnIdentity{item->itemNumber, item->data.shape, + item->data.flags, item->data.quality, shape.family, false}; + const auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + spawnIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); + if (eligible) { + ++eligibleSpawnUses; + } + } + assert(eligibleSpawnUses == 0); unsigned eligibleMapUseItems = 0; unsigned keycardUseItems = 0; std::optional boxItem; @@ -448,9 +601,46 @@ int main() 0x5a, 0x02, 0x5c, 0xd6, 0x01, 'B', 'O', 'X', '_', 'N', 'S', 0x00, 0x00, 0x00}; assert(hasRetailEventEntry(boxUse->bytes, boxPrefix)); remorse::LiveFixedMapItems boxWorld(*stagedItems); - auto boxTask = remorse::UsecodeProcessTask::create(0x0340, 0x0081, 1, - boxItem->itemNumber, boxUse->bytes); - assert(boxTask); + const auto& boxShape = (*typeFlags)[boxItem->data.shape]; + const remorse::u8 boxHeight = boxShape.z == 0 && (boxShape.flags & 1) == 0 + ? 1 : static_cast(boxShape.z * 8); + assert(static_cast(boxItem->data.z) + boxHeight <= 0xff); + remorse::StagedFixedMapItem boxSearchOrigin; + boxSearchOrigin.itemNumber = 1; + boxSearchOrigin.data.shape = 1; + boxSearchOrigin.data.x = boxItem->data.x; + boxSearchOrigin.data.y = boxItem->data.y; + boxSearchOrigin.data.z = static_cast(boxItem->data.z + boxHeight); + const auto boxCandidates = remorse::itemGrabSearchCandidates(boxSearchOrigin, + boxWorld.mapItems(), *typeFlags); + assert(boxCandidates); + const auto boxCandidate = std::find_if(boxCandidates->begin(), boxCandidates->end(), + [boxItem](const auto& candidate) { return candidate.itemNumber == boxItem->itemNumber; }); + assert(boxCandidate != boxCandidates->end()); + const auto* selectedBoxItem = boxWorld.findItem(boxCandidate->itemNumber); + assert(selectedBoxItem && selectedBoxItem->data.shape < typeFlags->size()); + const remorse::UsecodeItemIdentity boxIdentity{selectedBoxItem->itemNumber, selectedBoxItem->data.shape, + selectedBoxItem->data.flags, selectedBoxItem->data.quality, + (*typeFlags)[selectedBoxItem->data.shape].family, false}; + const auto selectedBoxEvent = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + boxIdentity, retailBases, 0x02, 1); + assert(selectedBoxEvent && selectedBoxEvent->classId == 0x0081 && + selectedBoxEvent->className == "BOX_NS" && selectedBoxEvent->body.bytes == boxUse->bytes); + remorse::UsecodeTaskRegistry boxTasks; + auto boxContext = remorse::createUsecodeEventContext(boxTasks.runtimeMemory(), *retailOwnerRows, + selectedBoxEvent->classId, 1, boxItem->itemNumber, selectedBoxEvent->body.bytes, 2); + assert(boxContext && boxContext->context.interpreter.callFrameCount == 1 && + boxContext->ownedRegions.size() == 3 && boxTasks.runtimeMemory().allocationCount() == 5); + const std::vector boxProcessIdBytes{0x40, 0x03}; + assert(boxTasks.runtimeMemory().write(boxContext->processIdOutput, boxProcessIdBytes)); + auto boxTaskValue = remorse::UsecodeProcessTask::create(0x0340, selectedBoxEvent->classId, 1, + boxItem->itemNumber, selectedBoxEvent->body.bytes, 2); + assert(boxTaskValue && boxTasks.addWithContext(std::move(*boxTaskValue), std::move(*boxContext))); + auto* boxTask = boxTasks.find(0x0340); + const auto* registeredBoxContext = boxTasks.context(0x0340); + assert(boxTask && registeredBoxContext && boxTask->sourceItem == boxItem->itemNumber && + boxTask->interpreter.callFrameCount == 1 && registeredBoxContext->context.processBytes[ + remorse::usecodeContextSlotIndexOffset] == 0x81); const auto freeClass = remorse::loadUsecodeClass(*usecode, 0x0a0c); const auto freeTimerBody = freeClass ? remorse::readUsecodeEventBody(*freeClass, 0x32) : std::nullopt; auto boxRenderer = remorse::loadMapSceneRenderer(*root, 1); @@ -540,6 +730,12 @@ int main() [](const auto& left, const auto& right) { return left.red == right.red && left.green == right.green && left.blue == right.blue; })); + const auto boxProcessIdOutput = boxTasks.runtimeMemory().read(registeredBoxContext->processIdOutput, + sizeof(remorse::u16)); + assert(boxProcessIdOutput && (*boxProcessIdOutput)[0] == 0x40 && + (*boxProcessIdOutput)[1] == 0x03 && boxTasks.runtimeMemory().allocationCount() == 5); + assert(boxTasks.remove(0x0340) && boxTasks.size() == 0 && boxTasks.context(0x0340) == nullptr && + boxTasks.runtimeMemory().allocationCount() == 0); assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, rechargeItem, retailBases, 0, 9)); std::vector ownerRows(26); diff --git a/rebuild/remorse/tests/usecode_vm_tests.cpp b/rebuild/remorse/tests/usecode_vm_tests.cpp index bd8d993..7126950 100644 --- a/rebuild/remorse/tests/usecode_vm_tests.cpp +++ b/rebuild/remorse/tests/usecode_vm_tests.cpp @@ -1,4 +1,5 @@ #include "remorse/usecode_vm.h" +#include "remorse/usecode_archive.h" #include #include @@ -66,6 +67,96 @@ int main() assert(!remorse::writeUsecodeContextFactoryFields(processContext.data(), processContext.size() - 1, factoryFields)); + remorse::UsecodeRuntimeMemory contextMemory; + const auto contextOwnerSource = contextMemory.allocate(8, 0x11); + const auto contextCodeBytes = contextMemory.allocate(16, 0x22); + const auto contextOwnerRows = contextMemory.allocate(13, 0x33); + assert(contextOwnerSource && contextCodeBytes && contextOwnerRows && + contextMemory.contains({1, contextOwnerSource->segment}, 1) && + !contextMemory.contains({8, contextOwnerSource->segment}, 1)); + remorse::UsecodeContextCreateRequest contextRequest; + contextRequest.ownerSource = remorse::FarPtr16{1, contextOwnerSource->segment}; + contextRequest.codeSource = remorse::FarPtr16{2, contextCodeBytes->segment}; + contextRequest.ownerRows = remorse::FarPtr16{4, contextOwnerRows->segment}; + contextRequest.itemParameter = std::vector{0x34, 0x12}; + contextRequest.contextParameter = contextParameter; + contextRequest.modeFlags = 2; + contextRequest.slotIndex = 0x000a; + contextRequest.valueAddOffset = 0x0020; + const auto contextInstance = remorse::createUsecodeContext(contextMemory, contextRequest); + assert(contextInstance && contextMemory.allocationCount() == 5 && + contextInstance->interpreter.callFrameCount == 1 && + contextInstance->interpreter.callFrames[0].offset == 0x000a && + contextInstance->interpreter.callFrames[0].segment == 0x0020); + const auto contextMemoryBytes = contextMemory.read(contextInstance->processAddress, + remorse::usecodeContextProcessSize); + assert(contextMemoryBytes && std::equal(contextMemoryBytes->begin(), contextMemoryBytes->end(), + contextInstance->processBytes.begin())); + const auto contextCallStack = contextMemory.read(contextInstance->callStackAddress, + remorse::usecodeInterpreterCallStackSize); + assert(contextCallStack && (*contextCallStack)[0] == 0x0a && (*contextCallStack)[1] == 0 && + (*contextCallStack)[2] == 0x20 && (*contextCallStack)[3] == 0 && + (*contextCallStack)[0x80] == 1 && (*contextCallStack)[0x81] == 0); + assert(contextInstance->processBytes[remorse::usecodeContextInterpreterOffset] == + static_cast(contextInstance->callStackAddress.offset) && + contextInstance->processBytes[remorse::usecodeContextInterpreterOffset + 2] == + static_cast(contextInstance->callStackAddress.segment)); + assert(contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset] == 2 && + contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 1] == 0 && + contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 2] == + static_cast(contextCodeBytes->segment) && + contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 3] == 0); + assert(contextInstance->processBytes[remorse::usecodeContextSelfPointerOffset] == + static_cast(contextInstance->processAddress.offset) && + contextInstance->processBytes[remorse::usecodeContextSelfPointerOffset + 2] == + static_cast(contextInstance->processAddress.segment)); + assert(contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset] == 4 && + contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 1] == 0 && + contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 2] == + static_cast(contextOwnerRows->segment) && + contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 3] == 0); + assert(contextInstance->processBytes[remorse::usecodeContextOwnerSourceOffset] == 1 && + contextInstance->processBytes[remorse::usecodeContextOwnerSourceOffset + 2] == + static_cast(contextOwnerSource->segment) && + contextInstance->processBytes[remorse::usecodeContextParameterOffset] == 190 && + contextInstance->processBytes[remorse::usecodeContextModeFlagsOffset] == 2 && + contextInstance->processBytes[remorse::usecodeContextActiveFlagOffset] == 0); + const std::size_t savedPointerLocation = remorse::usecodeContextInterpreterOffset + + contextInstance->interpreter.stackTop; + assert(contextInstance->processBytes[savedPointerLocation] == 0x00 && + contextInstance->processBytes[savedPointerLocation + 1] == 0x01 && + contextInstance->processBytes[savedPointerLocation + 2] == + static_cast(contextInstance->processAddress.segment) && + contextInstance->processBytes[savedPointerLocation + 3] == 0 && + contextInstance->processBytes[0x100] == 0x34 && contextInstance->processBytes[0x101] == 0x12 && + contextInstance->processBytes[0xfc] == 0xa1 && contextInstance->processBytes[0xfd] == 0xb2 && + contextInstance->processBytes[0xfe] == 0xc3 && contextInstance->processBytes[0xff] == 0xd4); + assert(contextInstance->processBytes[remorse::usecodeContextStackPointerOffset] == 0xf8 && + contextInstance->processBytes[remorse::usecodeContextStackPointerOffset + 2] == + static_cast(contextInstance->processAddress.segment) && + contextInstance->processBytes[remorse::usecodeContextStackBaseOffset] == 0x02 && + contextInstance->processBytes[remorse::usecodeContextStackBaseOffset + 1] == 0x01 && + contextInstance->processBytes[remorse::usecodeContextStackLimitOffset] == 199); + assert(remorse::destroyUsecodeContext(contextMemory, *contextInstance) && + contextMemory.allocationCount() == 3); + + remorse::UsecodeContextCreateRequest emptyContextRequest = contextRequest; + emptyContextRequest.contextParameter = std::vector{}; + const auto emptyContextInstance = remorse::createUsecodeContext(contextMemory, emptyContextRequest); + assert(emptyContextInstance && emptyContextInstance->interpreter.contextParameterOffset == 194 && + emptyContextInstance->processBytes[remorse::usecodeContextParameterOffset] == 194); + assert(remorse::destroyUsecodeContext(contextMemory, *emptyContextInstance)); + remorse::UsecodeContextCreateRequest invalidContextRequest = contextRequest; + invalidContextRequest.itemParameter = std::vector{0x34}; + assert(!remorse::createUsecodeContext(contextMemory, invalidContextRequest) && + contextMemory.allocationCount() == 3); + invalidContextRequest = contextRequest; + invalidContextRequest.codeSource = remorse::FarPtr16{0xffff, 0xfffe}; + assert(!remorse::createUsecodeContext(contextMemory, invalidContextRequest) && + contextMemory.allocationCount() == 3); + assert(contextMemory.release(*contextOwnerSource) && contextMemory.release(*contextCodeBytes) && + contextMemory.release(*contextOwnerRows) && contextMemory.allocationCount() == 0); + std::vector code(remorse::usecodeEventBytecodeOffset, 0); code.insert(code.end(), { 0x0a, 0x07,