From 08a907f322afb1d5a63148f30d04d43feefef80c Mon Sep 17 00:00:00 2001 From: Maddo Date: Sun, 4 Oct 2026 18:11:16 +0200 Subject: [PATCH] Add comprehensive tests for ProcessKernel and Usecode VM functionality - Implemented tests for ProcessKernel in entity_dispatch_entry_tests.cpp, covering process creation, termination, and scanning of runnable processes. - Enhanced fixed_map_tests.cpp with tests for item allocation and release, including recycling of items and process ownership. - Expanded flex_archive_tests.cpp to validate the interaction between usecode events and item processes, ensuring correct behavior of spawned tasks and rendering. - Introduced usecode_vm_tests.cpp to thoroughly test the UsecodeInterpreterState and UsecodeProcessTask functionalities, including stack operations and opcode services. --- ...entity-vm-runtime-owner-resource-layout.md | 10 + docs/remorse-windows-rebuild-roadmap.md | 32 +- rebuild/remorse/CMakeLists.txt | 12 +- .../include/remorse/entity_dispatch_entry.h | 9 + rebuild/remorse/include/remorse/fixed_map.h | 15 + rebuild/remorse/include/remorse/usecode_vm.h | 99 +++- rebuild/remorse/src/entity_dispatch_entry.cpp | 62 ++- rebuild/remorse/src/fixed_map.cpp | 254 ++++++++- rebuild/remorse/src/usecode_vm.cpp | 503 +++++++++++++++++- rebuild/remorse/src/windowed_game_main.cpp | 242 ++++++++- .../tests/entity_dispatch_entry_tests.cpp | 37 ++ rebuild/remorse/tests/fixed_map_tests.cpp | 60 +++ rebuild/remorse/tests/flex_archive_tests.cpp | 349 ++++++++++++ rebuild/remorse/tests/usecode_vm_tests.cpp | 134 +++++ 14 files changed, 1784 insertions(+), 34 deletions(-) create mode 100644 rebuild/remorse/tests/usecode_vm_tests.cpp diff --git a/docs/entity-vm-runtime-owner-resource-layout.md b/docs/entity-vm-runtime-owner-resource-layout.md index aa1927c..7f3b30c 100644 --- a/docs/entity-vm-runtime-owner-resource-layout.md +++ b/docs/entity-vm-runtime-owner-resource-layout.md @@ -52,7 +52,9 @@ Live runtime-helper classification added during the 2026-04-05 MCP-upgrade pass: - seeds the sentinel-filled chunk-state array used by later lazy chunk loads - `1420:19fd Remorse::EntityVmRuntime::EnsureSlotChunkLoaded` - lazily materializes one indexed owner chunk for a slot into runtime memory + - obtains the chunk through `UProcess_1420_0000` using the owner-row offset/size, materializes it through the owner-resource helper, and caches the returned far pointer in the slot entry - marks the chunk present through the slot-local state arrays and updates the runtime-wide budget counters + - `GetSlotChunkPtrAtOffset` (`1420:1d72`) returns that allocator-produced pointer plus the caller's intra-chunk offset; it does not expose a stable file/archive address - `1420:1f24 entity_vm_runtime_apply_to_matching_owner_rows` - runtime-owned iterator over the owner list, used both for broad cleanup and for filtered slot/category work - `1420:2040 entity_vm_slot_entry_create_or_clear` @@ -123,10 +125,18 @@ Current layout claims that matter for class lifting: - `+0x36` embeds the mini-VM/state object - `+0xd6/+0xd8` hold the seeded source/control stream lane - `+0x102` is the backward-growing local payload/buffer lane +- `+0x11f` stores the context-relative offset of the saved parameter-stack pointer when `ucparam` is non-null and mode flags are nonzero +- `+0x121` stores the low mode-flags byte, and `+0x122` is initialized to zero by `CreateFromSlotIndex` - `+0x10c/+0x10e` store a derived low/high pair reused by save/load - `+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. + +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. + Current caution: - context dispatch semantics are still active work, so this object should be modeled around lifecycle and data ownership first, not around final method names for every opcode-facing helper. diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index aa7898e..499ec8b 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -27,7 +27,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`; opcode execution is not implemented. These are partial translations of steps 1-4, **not completed steps**: `Game_Start` (`1020:0000`), teleporter scheduling, complete item cache, controller actions beyond directional movement, original camera/draw-list integration, and USECODE execution remain open. Collision is approximate; no visible scripted world mutation or deterministic end-to-end interaction acceptance exists. Steps 5-6 remain open. +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. @@ -69,7 +69,7 @@ Current scaffold files: - `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, `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/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. @@ -97,7 +97,7 @@ Current scaffold files: - `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, partial scheduler scan/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. +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. ## Why The Export Does Not Compile Yet @@ -318,8 +318,8 @@ First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a | `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/termination/presence cleanup checked over two ticks, harness/window invoke the same path | 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 compiled release boundary now passes mask `0x200` and `UC_Release` ordinal `9` to the host callback, both asserted by CTest. It still does not execute the USECODE event. Instance is a diagnostic, not an original `Item_Grab` trigger; original item process child teardown and general vtable dispatch remain unported. | -| `Item_GetUsecodeClassId` (`1420:0dc5`), `Usecode_ItemCallEvent` (`1420:0e3a`) | Class selection and owner-row event-mask gate translated into `remorse_core`; retail and synthetic CTest checks, harness and window release-request lookup | The item selector chooses regular shape, NPC number plus startup NPC base `0x800` (unless status bit 1), or unknown-egg quality plus startup base `0x900`. FLEX entry 1 supplies 13-byte owner rows (size callback `1220:01bb`, materialization callback `1240:02a8`). The window retains TYPEFLAG families and EUSECODE data to check release eligibility and report body availability, without creating a VM context or executing the body. Classless map items are normal; the first staged map-1 item (shape 16) has no matching class. | +| `Item_CreateProcess` (`10a0:0020`), `ItemProcess_Run` (`10a0:0078`), `Item_Release` (`10a0:2a06`) | Owned 0x32-byte item process constructed and advanced by the scheduler from a staged retail map record; release request, event-body queueing, task state, termination, and presence cleanup are exercised by the diagnostic host | Live disassembly confirms function-table root `0x102f`, item number at `+0x04`, event type `0xf1` at `+0x06`, then `Item_Release` followed unconditionally by the vtable terminate slot. The host callback receives mask `0x200` and `UC_Release` ordinal `9`, resolves an eligible retail body, and queues it in the host VM task registry. Only supported opcodes/services execute; unsupported paths halt the task. This remains a diagnostic trigger, not the original `Item_Grab` path; child teardown and general vtable dispatch remain unported. | +| `Item_GetUsecodeClassId` (`1420:0dc5`), `Usecode_ItemCallEvent` (`1420:0e3a`) | Class selection and owner-row event-mask gate translated into `remorse_core`; retail and synthetic CTest checks, harness/window release selection, and host task execution | The item selector chooses regular shape, NPC number plus startup NPC base `0x800` (unless status bit 1), or unknown-egg quality plus startup base `0x900`. FLEX entry 1 supplies 13-byte owner rows (size callback `1220:01bb`, materialization callback `1240:02a8`). The diagnostic host resolves the selected release body and runs it through the subset VM. This is not the original `Usecode_ItemCallEvent`/`CreateFromSlotIndex` dispatcher or `EntityVmContext`; classless map items remain valid, and the first staged map-1 item (shape 16) has no matching class. | | `Process_Sleep` (`11e0:0320`), `EntityDispatchEntry::Unlink` (`11e0:0353`) | Flag and 32-bit timer writes/clear translated; exact byte offsets and wake deadline tested | Live sleep ORs `0x1000` at `+0x18`, snapshots timer into `+0x0a/+0x0c`, writes duration to `+0x0e/+0x10`; unlink clears the flag and those four words. Host receives a tick instead of reading the original timer-process pointer. | | `NPCActionProcess::Create` (`1100:0000`), `StandProcess::CreateProcess` (`1100:02ed`) | Owned 0x42-byte Stand entry registered and run in harness; constructor fields, item number, and presence-bit transitions tested | Live chain stamps `+0x16 |= 0x300`, clears derived words `+0x32..0x3e`, stores NPC number at `+0x40`, ORs `0x101` at `+0x32`, sets Stand vtable `0x1f0f`, process name `Stand`, and event `0x258`. Host marks the item bit on registration and refreshes it after terminating a zero-child-state Stand, following `Item_MarkProcessPresent`/`Item_RefreshProcessPresenceFlag` (`11d0:3e0b/3e7f`). Item animation/cache reset, nonempty child-list destruction, and real NPC item ownership remain unported. | | `NPC_StartBehaviorInField0x8IfCanSeeControlledNPC` (`1100:026e`), `StandProcess::Run` (`1100:0359`) | Compiled NPC decision/Stand run branches; tests cover off-screen sleep, visible behavior start, already-current sleep, and strict wake | Live `1100:0274-02e9` reads NPC number from `+0x40`, tests entirely-on-screen, nonzero field-8 activity, not-current activity `0x71`, can-see-controlled-NPC, and starts the next behavior; `1100:035c-0382` sleeps 60 on false. `1478:1f0f` starts with far `Run` pointer `1100:0359`. Host services supply visibility/activity/item effects and timer tick; no real NPC item, general vtable resolver, or binary trace parity. | @@ -333,7 +333,7 @@ Live Ghidra MCP decompilation and disassembly have resolved local stack ABI, sch The exported free-item path can issue `0x2400` from its `0x100..0x27ff` range, and a staged synthetic map reaches that ID; retail map 1 remains inside the kernel lookup limit. Exported `SetSourceType` (`11e0:01b6`) calls the presence/type-table writers without a visible range guard. This does not prove how a live run handles such an ID: preserve the host guard and investigate the original allocation/use path before allowing out-of-range process ownership. -`FUN_11d0_31cf` (`11d0:31cf`) is a caller of the scheduler scan at `11d0:0255`. Its one-pass prefix snapshots the registered SystemTimer, scans runnable processes, then invokes an optional callback. The host now compiles and calls that ordered pass from the harness and Windows diagnostic, returning elapsed ticks after the callback; tests verify that a timer event delivered by the callback cannot wake a process in the already-started scan. The original infinite loop, interval wait, DOS interrupt delivery, and live group-transition trace remain unported. +`FUN_11d0_31cf` (`11d0:31cf`) is a caller of the scheduler scan at `11d0:0255`. Its one-pass prefix snapshots the registered SystemTimer, scans runnable processes, then invokes an optional callback. The host compiles and calls that ordered pass from the harness and Windows diagnostic, returning elapsed ticks after the callback; tests verify that a timer event delivered by the callback cannot wake a process in the already-started scan. At the end of the scan, the host now reproduces the source group transition: if the active group has no live processes, select the highest occupied group except 30/31, set the pending flag only on change, then clear it as `Kernel_11d0_0445` (`11d0:0445`) does. The original infinite loop, interval wait, DOS interrupt delivery, `11d0:04cd` resize maintenance, and runtime group-transition parity remain unported or unverified. The first search-side dependency is compiled and tested in isolation: `ItemFind_10c0_14c9` (`10c0:14c9`) classifies a candidate as match type 1 (candidate Z equals origin top) or type 2 (candidate top equals origin Z), using TYPEFLAG-derived footprint widths and height, with type 1 taking priority. The host receives staged item fields and decoded shape metadata explicitly. This is **not** a complete port of `ItemFind_StartSearchAroundItem` (`10c0:0f73`) or the `10c0:1637` iterator; live item state and general loop-script evaluation remain absent, and the classifier is not used to select a window item. @@ -345,10 +345,14 @@ Contained placement has a separate source-derived diagnostic: for nonzero maps, The bounded staged dispatcher can now issue those actions against the host process kernel. `Process_GetProcessForItemAndType` (`11d0:13a4`) scans live slots from 3, ignores terminated entries, and supports item/type wildcards; the host mirrors those rules. `Item_Hurl` (`1038:12a6`) reuses an existing type-`0x203` gravity process and adds velocity, or creates a `0x42`-byte process (`1038:0395`) with zero velocity, gravity 2, and a 20-tick sleep for a fall request. Tests cover both branches, duplicate item-process requests, strict wake, ownership and ID-limit rejection, and teardown/reuse. Staged dispatch rejects any out-of-range action before starting; the Windows `F` key is still a separate release fixture. A host-owned `LiveFixedMapItems` copy now supports ID lookup, bounded position changes, and `Item_Grab` dispatch against current item positions; the window owns this copy for nearby-item lookup. `Item_LegalMoveToPointWithCollisionInfo` (`10a0:1841`) calls `Item_Grab` before `AreaSearch_CollideMove` on its successful path; `moveApprovedItem` preserves that ordering once a caller has approved the move, and tests distinguish old-position requests from post-move search. Synthetic move/dispatch and retail-map ownership tests pass. This is not the original item cache, does not yet provide a legal-move collision event or update rendered sprites, and does not include live contained items. `runUnobstructedGravity` moves an owned item and advances/sleeps its owned process in the nonzero-vertical-speed branch after explicit caller-supplied approval of the full pre-sweep target. A refused or missing sweep makes no mutation on that path. On the zero-Z horizontal path, it requests `Item_Grab` before sweep approval, so a refused sweep may still leave a process request. The stationary zero-speed fall search, collision responses, live fast-area state, and automatic scheduler tick remain unported. The original `AreaSearch_SweepTestItem` (`10e0:1151`) forwards into `AreaSearch_SweepTestPt` (`10e0:0b39`); the host has bounded fast-area and item-iterator gates but not resolved collision points. Runtime ID and search-order parity remain unverified and are not a current gate. -The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied item IDs can also be inserted at a block head. The host free-ID allocator uses the source `0x100..0x27ff` range, skips staged direct and contained records, and fails without mutation when exhausted. The window reserves staged contained IDs and retains their parent links; placing one in the world clears its parent while its children remain linked. Synthetic nested/exhaustion and retail-map tests pass. This does not yet implement returning freed IDs to the list, live inventory/container transfers, fast-area status, or viewport side effects. +The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied item IDs can also be inserted at a block head. The host free-ID allocator uses the source `0x100..0x27ff` range, skips staged direct and contained records, and fails without mutation when exhausted. The window reserves staged contained IDs and retains their parent links; placing one in the world clears its parent while its children remain linked. Synthetic nested/exhaustion and retail-map tests pass. A follow-up item-cache slice now models returned IDs as a LIFO free list (`ItemCache_10a8_1aef`, `10a8:1aef`), initial contained sibling order (`ItemCache_PopToEnd`, `10a8:2533`), family-6 head insertion (`ItemCache_PopToContainer`, `10a8:2369`), and transfers that preserve nested children. Release refuses active-process ownership, nonempty items, hatched glob eggs, and IDs above the `0x23ff` process-table boundary. Synthetic tests cover sibling ordering, cycle rejection, process ownership, and free-ID reuse. Runtime parity, cache-status/fast-area effects, family-7 transfer, and viewport writes remain unverified. The supported horizontal `GravityProcess_Run` path now issues `Item_Grab` at the old item position when Z speed is zero and X/Y speed is nonzero, then asks the injected sweep to approve movement. As in the source order, a refused sweep can leave a newly requested item process behind while the item stays put. The earlier no-mutation guarantee for a refused sweep applies only to the nonzero-Z path, which does not issue that request. This callback-based unobstructed runner does not handle the stationary zero-speed fall search or collision response; a caller must provide shapes, group counts, and sweep approval. +Live `Item_SetQIfContainerType` (`10a0:0f78`) writes a family-6/7 parent quality field to its first contained child, and `ItemCache_10a8_1949` (`10a8:1949`) advances that field when unlinking the head. The host now mirrors the head ID during initial contained staging and runtime head insertion/removal, including nested parents; family-6 and family-7 staging and the quality transitions have focused regressions. This does not port the `Item_PopToEnd` free-item-to-tail path or the separate item-status/fast-area effects. + +Live Ghidra decompilation shows that vertical `GravityProcess_Run` impacts use sweep mode 4, then `AreaSearch_CollideMove`, and branch on `Item_IsCurrentControlledNPC` plus masks from the separate `g_itemStatus` table. Those branches include callback/termination paths and controlled-item rebound behavior using `RandomVal`; collision movement can also create hit/got-hit storage processes. `FixedMapEntry::flags` is not a verified substitute for `g_itemStatus` and already carries modeled fixed-item flags such as flip. Keep vertical response, status/cache writes, and collision-event creation deferred until those runtime states and side effects are represented. + The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. The source's `World_MapBlockInFastArea` (`10a8:0000`) rotated block predicate and eight-corner start/destination footprint gate are testable with an explicit fast-area range. `World_CalcFastAreaLimits` (`10a8:0048`) now supplies the source sum ±5 / difference ±3 block window from a world center. The window refreshes a player-centered host range after movement and dispatches any owned gravity processes through its timed scheduler; it still does not create gravity entries or repaint moved map items in the static preview. The sweep's item-iterator rectangle and live candidate query follow inclusive X/Y filtering and Y-then-X block order. The per-item sweep uses 16-unit X/Y extents, 8-unit Z extents with the source zero-height fallback, and six axis-face tests that report one-unit-before-contact points and failed-direction bits. A read-only live collector combines those tests with candidate order, shape solidity and flip flags. The host selects a solid hit in source order when any axis is strictly closer, retains the earlier hit on a tie, and accumulates direction bits across contacts. Damaging-only face contacts are recorded in candidate order without blocking the resolved point. With an explicitly enabled floor-gap limit, the host also identifies the closest solid support beneath the destination footprint for source limits 0 and 9; this support metadata does not change the destination. The resolved sweep now reports fast-area failure at the original point with direction bits 1/2 and clamps out-of-range Z with bit 4; the gravity runner conservatively rejects these unsupported responses before mutation. `runResolvedGravity` moves an owned item to a solid-hit point after its strict process wake, damps and reverses horizontal speed on collision, and sleeps the process again. `scanResolvedGravity` dispatches this bounded runner through the host scheduler; tests verify a wall impact, a later move away, and no repeat within the same tick. The remaining gaps are vertical collision response, item status/cache writes, collision events, stationary fall search, and an actual window gravity producer and moving-item renderer. Original runtime parity remains unverified. 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. @@ -356,12 +360,12 @@ Original DOS debugging and runtime verification are postponed indefinitely until 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. Port the remaining scheduler interval/group transitions behind host timing boundaries using static code evidence, with runtime parity explicitly deferred. -3. Port free-ID return/reuse and live container transfers while preserving contained parent/child links and process ownership. -4. Carry source sweep mode flags through callers and implement vertical collision responses for supported item/status branches; bounds and fast-area failures are now explicit but conservatively rejected by gravity. +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 its interpreter initialization; keep release event-body lookup diagnostic until the VM executes it. +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 @@ -391,7 +395,7 @@ The Windows diagnostic no longer schedules the first staged item on scene load. The `Item_Grab` creation branch applies the verified `FUN_11d0_3f95(itemNumber, -0xf)` item-cache flag-1 check to staged item flags before a type-2 process request. Live disassembly at `10a0:29c5-29e3` confirms the branch; a separate search-result type 1 calls `Item_Fall`, whose hurl request now creates or merges a sleeping gravity entry in the host. The Ghidra export's zero-initialized `npcno` loop is a decompiler artifact, not evidence that the search never iterates. The window still uses proximity instead of original `ItemFind`, does not model live item-cache mutations or gravity movement, and must not treat process-presence bookkeeping as the checked item flag. -The first Phase 6 resource slice is compiled into `remorse_core`: a bounded `EUSECODE.FLX` class/name/event-body reader follows the owner-loaded `classId + 2`, 13-byte name-table, `+0x14` six-byte row, and `codeBase + relativeOffset - 1` body rules verified in `docs/raw-000a-000d.md`. Retail tests confirm `EVENT` (`class 0x361`, slot `0x0a`, code base `0xd4`, body length `0x1fd6`) and `RECHFLNS` (`class 0x138`, release slot `9`, body length `102`, owner mask `0x200`). The harness resolves and reports the `EVENT` body (8,150 bytes). `Item_GetUsecodeClassId` selects a class from item identity and startup class bases; `Usecode_ItemCallEvent` gates on the owner row. Map-1 tests cover both its classless first staged item and at least one actual staged item with an eligible release body. The window applies both checks to the nearest staged item's release request and labels eligible bytes NOT RUN. This remains lookup, not bytecode interpretation or a live owner-loaded item system. The next original call is `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`, mode 2, selected class/slot and a four-byte parameter), which initializes an interpreter through `Inter_1418_0244` (`1418:0244`) and `Interpreter_1418_00e8` (`1418:00e8`). No context, interpreter dispatch, or item side effect is ported. Even the short `RECHFLNS` release event branches through item surface-weight logic and `FREE.slot_33`; an isolated opcode stub would not complete that call chain. +The first Phase 6 resource slice is compiled into `remorse_core`: a bounded `EUSECODE.FLX` class/name/event-body reader follows the owner-loaded `classId + 2`, 13-byte name-table, `+0x14` six-byte row, and `codeBase + relativeOffset - 1` body rules verified in `docs/raw-000a-000d.md`. Retail tests confirm `EVENT` (`class 0x361`, slot `0x0a`, code base `0xd4`, body length `0x1fd6`) and `RECHFLNS` (`class 0x138`, release slot `9`, body length `102`, owner mask `0x200`). Raw extracted `CARD_NS`, `BOX_NS`, and `RECHFLNS` bodies confirm a 14-byte metadata prefix followed by the first opcode at offset `0x0e`; its exact field meanings remain unknown. The named offset is shared by the host task runner and tested against these retail bodies. Retail integration tests execute `CARD_NS` spawning `SWITCH` and `BOX_NS` through timer yields to a changed item frame and rendered scene. The Windows diagnostic release callback also resolves and queues an eligible body, but this is host-side dispatch and task initialization, not `Usecode_ItemCallEvent` or `EntityVmContext::CreateFromSlotIndex`. The interpreter covers only a subset of opcodes/services, and unsupported operations halt tasks; original context memory, far-pointer execution, general event dispatch, and runtime parity remain open. The recovered `CreateFromSlotIndex` call selects a class/slot and passes a four-byte parameter into `Inter_1418_0244` (`1418:0244`) and `Interpreter_1418_00e8` (`1418:00e8`). Even the short `RECHFLNS` release event branches through item surface-weight logic and `FREE.slot_33`; the current host service table does not complete that path. The walk/run modifier choice is the isolated branch from `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. The same selector's Num Lock-off directional scan branch (`0x47/48/49/4b/4d/4f/50/51`) is now compiled in the controls helper, regression-tested across all eight mappings, and called by Win32 movement polling. Win32 still supplies modifiers and held-key state; NPC state, weapon-dependent actions, original keyboard events, and the remainder of the controller selector are not ported. Retail ANIM.DAT regression checks retain the signed reverse steps in the decoder while testing the host-only forward movement filter across all four affected walk directions. @@ -708,8 +712,8 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat 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. Port `CreateFromSlotIndex` and the `Inter_1418_0244`/`Interpreter_1418_00e8` initialization path with checked stack, parameter, and program-counter state, then execute one selected retail event through original opcode handlers and verify its 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. +7. Port `EnsureSlotChunkLoaded` (`1420:19fd`), its `UProcess_1420_0000` allocation and owner-helper materialization path, and the slot cache's far-pointer ownership. Then extend the host's segment-0 item-memory mapping to that runtime-owned code region, finish `CreateFromSlotIndex`/`Inter_1418_0244` context wiring, and execute one 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. ## Current Bottom Line -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 now runs an item process bound to a staged retail map record, selects any eligible release-script bytes, and runs a Stand entry under the host tick. This is a map-derived process integration checkpoint, **not** a complete Phase 4 or gameplay milestone: original item cache/block IDs, actual release USECODE execution, real NPC ownership/services, nonempty-child teardown, DOS timer/keyboard interrupts, full scheduler, original startup/player chain, renderer item output, and interactions remain unported. The next measures of gameplay progress are an executed retail event with a verified live item mutation and a real item-linked Stand/NPC instance on the original call chain with state trace parity. +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. diff --git a/rebuild/remorse/CMakeLists.txt b/rebuild/remorse/CMakeLists.txt index 9a37b5c..119a7d5 100644 --- a/rebuild/remorse/CMakeLists.txt +++ b/rebuild/remorse/CMakeLists.txt @@ -157,13 +157,21 @@ target_link_libraries(combat_tactics_tests PRIVATE remorse_core) add_test(NAME combat_tactics_tests COMMAND combat_tactics_tests) +add_executable(usecode_vm_tests + tests/usecode_vm_tests.cpp +) + +target_link_libraries(usecode_vm_tests PRIVATE remorse_core) + +add_test(NAME usecode_vm_tests COMMAND usecode_vm_tests) + add_library(remorse_test_crash_setup OBJECT tests/test_crash_setup.cpp) target_link_libraries(remorse_test_crash_setup PRIVATE remorse_core) foreach(test_target IN ITEMS entity_dispatch_entry_tests file_system_tests palette_tests flex_archive_tests fixed_map_tests glob_archive_tests type_flags_tests shape_archive_tests map_renderer_tests map_sorter_tests isometric_controls_tests - animation_archive_tests collision_tests combat_tactics_tests) + animation_archive_tests collision_tests combat_tactics_tests usecode_vm_tests) target_sources(${test_target} PRIVATE $) endforeach() @@ -175,6 +183,7 @@ if(MSVC) target_compile_options(isometric_controls_tests PRIVATE /W4 /permissive-) target_compile_options(animation_archive_tests PRIVATE /W4 /permissive-) target_compile_options(collision_tests PRIVATE /W4 /permissive-) + target_compile_options(usecode_vm_tests PRIVATE /W4 /permissive-) target_compile_options(remorse_map_preview PRIVATE /W4 /permissive-) if(WIN32) target_compile_options(remorse_game PRIVATE /W4 /permissive-) @@ -196,6 +205,7 @@ else() target_compile_options(isometric_controls_tests PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(animation_archive_tests PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(collision_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(usecode_vm_tests PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(remorse_map_preview PRIVATE -Wall -Wextra -Wpedantic) if(WIN32) target_compile_options(remorse_game PRIVATE -Wall -Wextra -Wpedantic) diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index b993856..7e06929 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -56,6 +56,11 @@ struct AnimPrimitiveProcessEntry { u8 extra[0x29]; } CR_PACKED; +struct EntityVmContextProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0xf2]; +} CR_PACKED; + struct KeyEvent { u8 character; u8 scanCode; @@ -80,6 +85,7 @@ static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size m 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(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"); struct NpcBehaviorServices { @@ -115,6 +121,7 @@ public: ControllerProcessEntry* createControllerProcess(u8 activeGroup, 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]); bool startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items, const AnimationClip& clip, u8 frameSkip = 0); std::optional advanceGroundedAnimPrimitive(u16 processId, LiveFixedMapItems& items, @@ -141,6 +148,7 @@ public: void clearTerminatedProcesses(); void setProcessSourceType(EntityDispatchEntryBase& entry, u16 itemNumber); void setProcessEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType); + bool setProcessInfo(u16 processId, u16 eventType, u16 sourceItem); void scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, u32 timerTick = 0); u32 runTimedSchedulerPass(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, void (*afterScan)(void*) = nullptr, void* afterContext = nullptr); @@ -166,6 +174,7 @@ private: std::vector> ownedStandProcesses_; std::vector> ownedGravityProcesses_; std::vector> ownedAnimPrimitiveProcesses_; + std::vector> ownedUsecodeProcesses_; std::unique_ptr systemTimerProcess_; std::unique_ptr keyboardProcess_; std::unique_ptr keyDaemonProcess_; diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index 3b7bd42..ca1ecc7 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -41,6 +41,7 @@ struct StagedContainedFixedMapItem { u16 itemNumber = 0; u16 parentItemNumber = 0; std::size_t recordIndex = 0; + FixedMapEntry data; }; struct ItemFindArea { @@ -119,13 +120,19 @@ public: const NpcAnimationState* findNpcAnimation(u16 itemNumber) const; NpcAnimationState* editNpcAnimation(u16 itemNumber); u16 containedParent(u16 itemNumber) const; + std::vector containedChildren(u16 parentItemNumber) const; std::optional nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const; std::optional> sweepCandidateIds(const WorldRect& area, u16 excludedItemNumber) const; std::optional allocateItem(StagedFixedMapItem item); bool insertItem(StagedFixedMapItem item); + bool moveItemIntoContainer(u16 itemNumber, u16 containerItemNumber, + const std::vector& shapes); + bool moveContainedItemToWorld(u16 itemNumber, u16 x, u16 y, u8 z); + bool releaseItem(u16 itemNumber, const ProcessKernel& kernel); std::optional> hatchGlobEgg(u16 eggItemNumber, const GlobObject& glob, const std::vector& shapes); bool isGlobHatched(u16 eggItemNumber) const; + bool setItemFrame(u16 itemNumber, u8 frame); bool moveItem(u16 itemNumber, u16 x, u16 y, u8 z); std::optional> grabItem(u16 itemNumber, const std::vector& shapes, ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick) const; @@ -134,12 +141,20 @@ public: u16 (&groupCounts)[32], u32 timerTick); private: + bool unlinkContainedItem(u16 itemNumber); + void refreshContainerQuality(u16 parentItemNumber); + bool insertContainedItemAtHead(u16 parentItemNumber, u16 itemNumber); std::vector items_; std::optional avatar_; std::vector npcAnimations_; std::vector allocatedIds_; std::vector hatchedGlobIds_; std::vector parentById_; + std::vector> containedItemData_; + std::vector containedNextById_; + std::vector containedHeadById_; + std::vector containedTailById_; + std::vector freeItemIds_; u16 nextFreeItemNumber_ = 0x100; }; diff --git a/rebuild/remorse/include/remorse/usecode_vm.h b/rebuild/remorse/include/remorse/usecode_vm.h index 1d59e25..7dbdd45 100644 --- a/rebuild/remorse/include/remorse/usecode_vm.h +++ b/rebuild/remorse/include/remorse/usecode_vm.h @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include @@ -9,22 +11,115 @@ namespace remorse { +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 usecodeContextSlotIndexOffset = 0x32; +constexpr std::size_t usecodeContextValueAddOffset = 0x34; +constexpr std::size_t usecodeContextOwnerSourceOffset = 0x11b; +constexpr std::size_t usecodeContextParameterOffset = 0x11f; +constexpr std::size_t usecodeContextModeFlagsOffset = 0x121; +constexpr std::size_t usecodeContextActiveFlagOffset = 0x122; + struct UsecodeCallFrame { u16 offset = 0; u16 segment = 0; }; +enum class UsecodeStepResult { + Advanced, + Returned, + SetInfo, + Spawned, + Yielded, + UnsupportedOpcode, + InvalidInstruction, + StackFault, + ServiceRejected +}; + +struct UsecodeOpcodeServices { + std::function(u16 offset, u16 segment)> readFarWord; + std::function setInfo; + std::function processCount; + std::function(u16 classId, u16 eventSlot, u8 extraArgumentBytes, + u8 itemArgumentSize, u16 itemArgument, const u8* extraArguments)> spawn; + std::function(u16 ordinal, u8 argumentBytes, const u8* arguments)> callIntrinsic; + std::function currentProcessId; +}; + class UsecodeInterpreterState { public: static std::optional initialize( - const std::vector& itemParameter); + const std::vector& itemParameter, const std::vector& contextParameter = {}, + u16 modeFlags = 0); bool pushCodeAddress(u16 offset, u16 segment); + bool pushWord(u16 value); + bool pushDword(u32 value); + std::optional popWord(); + std::optional popDword(); + UsecodeStepResult step(const std::vector& code, std::size_t& programCounter, + std::vector& frame, const UsecodeOpcodeServices& services); + std::optional> lastSetInfoOperands; std::array valueStack{}; std::size_t stackTop = 0xcc; + std::size_t stackHighWatermark = 0xcc; std::array callFrames{}; u16 callFrameCount = 0; - u16 stackLimit = 199; + u16 stackLimit = usecodeInterpreterStackLimit; + u16 temporaryWord = 0; + std::optional contextParameterOffset; + bool processExcluded = false; + u16 currentProcessId = 0; + u16 impliedProcessId = 0; +}; + +struct UsecodeProcessTask { + static std::optional create(u16 processId, u16 classId, + u16 eventSlot, u16 sourceItem, std::vector code, + u8 itemArgumentSize = 2, std::vector extraArguments = {}, + std::vector contextParameter = {}); + UsecodeStepResult step(const UsecodeOpcodeServices& services); + + u16 processId = 0; + u16 classId = 0; + u16 eventSlot = 0; + u16 sourceItem = 0; + std::vector code; + std::vector frame; + std::vector itemMemory; + UsecodeInterpreterState interpreter; + std::size_t programCounter = usecodeEventBytecodeOffset; + bool halted = false; + bool timerDelayProcess = false; + u32 wakeTick = 0; + + std::optional readMappedItemWord(FarPtr16 address) const; +}; + +struct UsecodeContextFactoryFields { + FarPtr16 ownerSource{}; + u16 modeFlags = 0; + u16 slotIndex = 0; + u16 valueAddOffset = 0; + u16 parameterOffset = 0; +}; + +bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize, + const UsecodeContextFactoryFields& fields); + +class UsecodeTaskRegistry { +public: + bool add(UsecodeProcessTask task); + UsecodeProcessTask* find(u16 processId); + const UsecodeProcessTask* find(u16 processId) const; + bool remove(u16 processId); + std::size_t size() const noexcept { return tasks_.size(); } + +private: + std::map tasks_; }; } // 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 829e83a..e5724ea 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -170,6 +170,37 @@ AnimPrimitiveProcessEntry* ProcessKernel::createAnimPrimitiveProcess(u8 activeGr return result; } +EntityVmContextProcessEntry* ProcessKernel::createUsecodeProcess(u8 activeGroup, + 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); + } + ownedUsecodeProcesses_.reserve(ownedUsecodeProcesses_.size() + 1); + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + setLastAllocationSize(sizeof(EntityVmContextProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "Usecode"; + if (syncEnabled_) { + EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_); + if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) { + current->bytes[0x18] |= 0x04; + } + if (id > currentProcessId_) { + process->base.bytes[0x16] |= 0x40; + } + } + EntityVmContextProcessEntry* result = process.get(); + ownedUsecodeProcesses_.push_back(std::move(process)); + return result; +} + bool ProcessKernel::startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items, const AnimationClip& clip, u8 frameSkip) { @@ -645,6 +676,12 @@ void ProcessKernel::releaseOwnedProcess(u16 id) ownedAnimPrimitiveProcesses_.erase(animation); return; } + const auto usecode = std::find_if(ownedUsecodeProcesses_.begin(), ownedUsecodeProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (usecode != ownedUsecodeProcesses_.end()) { + ownedUsecodeProcesses_.erase(usecode); + return; + } const auto owned = std::find_if(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; }); ownedProcesses_.erase(owned); @@ -681,13 +718,17 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) const bool ownedItemProcess = readLe16(*entry, 0x00) == ItemProcess::vtableOffset && std::any_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; }); + const bool ownedUsecodeProcess = std::any_of(ownedUsecodeProcesses_.begin(), + ownedUsecodeProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess && - !ownedGravityProcess && !ownedAnimationProcess || id < 3 || + !ownedGravityProcess && !ownedAnimationProcess && !ownedUsecodeProcess || id < 3 || readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 || readLe16(*entry, 0x2e) != 0 || readLe16(*entry, 0x30) != 0)) { throw std::logic_error("item process child cleanup is not ported"); } if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && !ownedAnimationProcess && + !ownedUsecodeProcess && 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"); @@ -793,6 +834,18 @@ void ProcessKernel::setProcessEventTypeChecked(EntityDispatchEntryBase& entry, u } } +bool ProcessKernel::setProcessInfo(u16 processId, u16 eventType, u16 sourceItem) +{ + EntityDispatchEntryBase* entry = processAt(processId); + if (entry == nullptr || processId < 3 || (entry->bytes[0x16] & 0x08) != 0 || + eventType > 0x0fff || sourceItem > maxTrackedItemNumber) { + return false; + } + setProcessEventTypeChecked(*entry, eventType); + setProcessSourceType(*entry, sourceItem); + return true; +} + void ProcessKernel::clearTerminatedProcesses() { for (std::size_t id = 3; id < processes_.size() && terminatedProcessCount_ != 0; ++id) { @@ -852,6 +905,13 @@ void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDisp } clearTerminatedProcesses(); } + u16 activeGroupCounts[32]{}; + for (const EntityDispatchEntryBase* entry : processes_) { + if (entry != nullptr && (readLe16(*entry, 0x16) & 0x08) == 0) { + ++activeGroupCounts[entry->bytes[0x08] & 0x1f]; + } + } + refreshActiveGroup(activeGroupCounts); } catch (...) { syncEnabled_ = priorSyncEnabled; currentProcessId_ = priorProcessId; diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index c13b6fa..e419081 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -209,7 +209,7 @@ std::optional> stageContainedFixedMapIt return std::nullopt; } parentById[itemNumber] = currentParent; - contained.push_back({itemNumber, currentParent, index}); + contained.push_back({itemNumber, currentParent, index, record}); } else { currentParent = 0; currentDepth = 0; @@ -433,8 +433,11 @@ std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& LiveFixedMapItems::LiveFixedMapItems(std::vector items, std::vector containedItems) - : items_(std::move(items)), allocatedIds_(0x2800), hatchedGlobIds_(0x2800), parentById_(0x2800) + : items_(std::move(items)), allocatedIds_(0x2800), hatchedGlobIds_(0x2800), parentById_(0x2800), + containedItemData_(0x2800), containedNextById_(0x2800), containedHeadById_(0x2800), + containedTailById_(0x2800) { + freeItemIds_.reserve(allocatedIds_.size()); if (!buildStagedItemBlockChains(items_)) { throw std::invalid_argument("invalid live item IDs or coordinates"); } @@ -454,6 +457,15 @@ LiveFixedMapItems::LiveFixedMapItems(std::vector items, throw std::invalid_argument("invalid contained parent ID"); } parentById_[contained.itemNumber] = contained.parentItemNumber; + containedItemData_[contained.itemNumber] = contained.data; + const u16 previousTail = containedTailById_[contained.parentItemNumber]; + if (previousTail == 0) { + containedHeadById_[contained.parentItemNumber] = contained.itemNumber; + } else { + containedNextById_[previousTail] = contained.itemNumber; + } + containedTailById_[contained.parentItemNumber] = contained.itemNumber; + refreshContainerQuality(contained.parentItemNumber); } } @@ -513,6 +525,97 @@ u16 LiveFixedMapItems::containedParent(u16 itemNumber) const return itemNumber < parentById_.size() ? parentById_[itemNumber] : 0; } +std::vector LiveFixedMapItems::containedChildren(u16 parentItemNumber) const +{ + std::vector children; + if (parentItemNumber >= containedHeadById_.size()) { + return children; + } + for (u16 itemNumber = containedHeadById_[parentItemNumber]; itemNumber != 0; + itemNumber = containedNextById_[itemNumber]) { + if (itemNumber >= containedNextById_.size() || + parentById_[itemNumber] != parentItemNumber || children.size() >= containedNextById_.size()) { + children.clear(); + return children; + } + children.push_back(itemNumber); + } + return children; +} + +bool LiveFixedMapItems::unlinkContainedItem(u16 itemNumber) +{ + if (itemNumber >= parentById_.size()) { + return false; + } + const u16 parentItemNumber = parentById_[itemNumber]; + if (parentItemNumber == 0 || parentItemNumber >= containedHeadById_.size()) { + return false; + } + u16 previousItemNumber = 0; + u16 currentItemNumber = containedHeadById_[parentItemNumber]; + while (currentItemNumber != 0 && currentItemNumber != itemNumber) { + if (currentItemNumber >= containedNextById_.size()) { + return false; + } + previousItemNumber = currentItemNumber; + currentItemNumber = containedNextById_[currentItemNumber]; + } + if (currentItemNumber != itemNumber) { + return false; + } + const u16 nextItemNumber = containedNextById_[itemNumber]; + if (previousItemNumber == 0) { + containedHeadById_[parentItemNumber] = nextItemNumber; + } else { + containedNextById_[previousItemNumber] = nextItemNumber; + } + if (containedTailById_[parentItemNumber] == itemNumber) { + containedTailById_[parentItemNumber] = previousItemNumber; + } + if (containedHeadById_[parentItemNumber] == 0) { + containedTailById_[parentItemNumber] = 0; + } + parentById_[itemNumber] = 0; + containedNextById_[itemNumber] = 0; + refreshContainerQuality(parentItemNumber); + return true; +} + +void LiveFixedMapItems::refreshContainerQuality(u16 parentItemNumber) +{ + if (parentItemNumber >= containedHeadById_.size()) { + return; + } + const u16 firstChild = containedHeadById_[parentItemNumber]; + const auto worldParent = std::find_if(items_.begin(), items_.end(), [parentItemNumber](const auto& item) { + return item.itemNumber == parentItemNumber; + }); + if (worldParent != items_.end()) { + worldParent->data.quality = firstChild; + } else if (containedItemData_[parentItemNumber]) { + containedItemData_[parentItemNumber]->quality = firstChild; + } +} + +bool LiveFixedMapItems::insertContainedItemAtHead(u16 parentItemNumber, u16 itemNumber) +{ + if (parentItemNumber >= allocatedIds_.size() || itemNumber >= allocatedIds_.size() || + parentItemNumber == itemNumber || !allocatedIds_[parentItemNumber] || !allocatedIds_[itemNumber] || + parentById_[itemNumber] != 0 || containedNextById_[itemNumber] != 0) { + return false; + } + const u16 previousHead = containedHeadById_[parentItemNumber]; + containedNextById_[itemNumber] = previousHead; + containedHeadById_[parentItemNumber] = itemNumber; + if (previousHead == 0) { + containedTailById_[parentItemNumber] = itemNumber; + } + parentById_[itemNumber] = parentItemNumber; + refreshContainerQuality(parentItemNumber); + return true; +} + std::optional LiveFixedMapItems::nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const { @@ -552,6 +655,19 @@ std::optional LiveFixedMapItems::allocateItem(StagedFixedMapItem item) if (item.data.x > 0x7fff || item.data.y > 0x7fff) { return std::nullopt; } + while (!freeItemIds_.empty()) { + const u16 itemNumber = freeItemIds_.back(); + freeItemIds_.pop_back(); + if (itemNumber >= allocatedIds_.size() || allocatedIds_[itemNumber]) { + continue; + } + item.itemNumber = itemNumber; + if (insertItem(item)) { + return itemNumber; + } + freeItemIds_.push_back(itemNumber); + return std::nullopt; + } while (nextFreeItemNumber_ < allocatedIds_.size() && allocatedIds_[nextFreeItemNumber_]) { ++nextFreeItemNumber_; } @@ -565,14 +681,132 @@ std::optional LiveFixedMapItems::allocateItem(StagedFixedMapItem item) bool LiveFixedMapItems::insertItem(StagedFixedMapItem item) { - if (item.itemNumber < 0x100 || item.itemNumber >= 0x2800 || item.data.x > 0x7fff || + if (item.itemNumber < 0x100 || item.itemNumber >= allocatedIds_.size() || item.data.x > 0x7fff || item.data.y > 0x7fff || findItem(item.itemNumber)) { return false; } + const bool wasContained = parentById_[item.itemNumber] != 0 && + containedItemData_[item.itemNumber].has_value(); + if (parentById_[item.itemNumber] != 0 && !wasContained) { + return false; + } + if (allocatedIds_[item.itemNumber] != wasContained) { + return false; + } + if (wasContained) { + item.data.flags &= static_cast(~8u); + } item.data.z = std::min(item.data.z, 0xfa); items_.push_back(item); + if (wasContained && !unlinkContainedItem(item.itemNumber)) { + items_.pop_back(); + return false; + } + containedItemData_[item.itemNumber].reset(); + const auto freeItem = std::find(freeItemIds_.begin(), freeItemIds_.end(), item.itemNumber); + if (freeItem != freeItemIds_.end()) { + freeItemIds_.erase(freeItem); + } allocatedIds_[item.itemNumber] = true; - parentById_[item.itemNumber] = 0; + return true; +} + +bool LiveFixedMapItems::moveItemIntoContainer(u16 itemNumber, u16 containerItemNumber, + const std::vector& shapes) +{ + if (itemNumber < 0x100 || containerItemNumber < 0x100 || itemNumber == containerItemNumber || + itemNumber >= allocatedIds_.size() || containerItemNumber >= allocatedIds_.size() || + !allocatedIds_[itemNumber] || !allocatedIds_[containerItemNumber]) { + return false; + } + const auto worldContainer = std::find_if(items_.begin(), items_.end(), [containerItemNumber](const auto& item) { + return item.itemNumber == containerItemNumber; + }); + const FixedMapEntry* containerData = worldContainer == items_.end() + ? (containedItemData_[containerItemNumber] ? &*containedItemData_[containerItemNumber] : nullptr) + : &worldContainer->data; + if (containerData == nullptr || containerData->shape >= shapes.size() || + shapes[containerData->shape].family != 6) { + return false; + } + if (parentById_[itemNumber] == containerItemNumber) { + return true; + } + for (u16 ancestor = containerItemNumber; ancestor != 0; ancestor = parentById_[ancestor]) { + if (ancestor == itemNumber || ancestor >= parentById_.size()) { + return false; + } + } + + const auto worldItem = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& item) { + return item.itemNumber == itemNumber; + }); + const bool wasContained = worldItem == items_.end() && parentById_[itemNumber] != 0 && + containedItemData_[itemNumber].has_value(); + if (worldItem == items_.end() && !wasContained) { + return false; + } + FixedMapEntry itemData = worldItem == items_.end() ? *containedItemData_[itemNumber] : worldItem->data; + if (wasContained && !unlinkContainedItem(itemNumber)) { + return false; + } + if (worldItem != items_.end()) { + items_.erase(worldItem); + } + itemData.flags |= 8; + containedItemData_[itemNumber] = itemData; + return insertContainedItemAtHead(containerItemNumber, itemNumber); +} + +bool LiveFixedMapItems::moveContainedItemToWorld(u16 itemNumber, u16 x, u16 y, u8 z) +{ + if (itemNumber < 0x100 || itemNumber >= allocatedIds_.size() || !allocatedIds_[itemNumber] || + parentById_[itemNumber] == 0 || !containedItemData_[itemNumber] || x > 0x7fff || y > 0x7fff) { + return false; + } + FixedMapEntry itemData = *containedItemData_[itemNumber]; + itemData.x = x; + itemData.y = y; + itemData.z = std::min(z, 0xfa); + itemData.flags &= static_cast(~9u); + items_.push_back({itemNumber, static_cast(-1), itemData}); + if (!unlinkContainedItem(itemNumber)) { + items_.pop_back(); + return false; + } + containedItemData_[itemNumber].reset(); + return true; +} + +bool LiveFixedMapItems::releaseItem(u16 itemNumber, const ProcessKernel& kernel) +{ + if (itemNumber < 0x100 || itemNumber > ProcessKernel::maxTrackedItemNumber || + itemNumber >= allocatedIds_.size() || !allocatedIds_[itemNumber] || + kernel.itemHasProcess(itemNumber) || containedHeadById_[itemNumber] != 0 || + hatchedGlobIds_[itemNumber]) { + return false; + } + const auto worldItem = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& item) { + return item.itemNumber == itemNumber; + }); + const bool wasContained = worldItem == items_.end() && parentById_[itemNumber] != 0 && + containedItemData_[itemNumber].has_value(); + if (worldItem == items_.end() && !wasContained) { + return false; + } + if (wasContained && !unlinkContainedItem(itemNumber)) { + return false; + } + if (worldItem != items_.end()) { + items_.erase(worldItem); + } + containedItemData_[itemNumber].reset(); + containedNextById_[itemNumber] = 0; + containedHeadById_[itemNumber] = 0; + containedTailById_[itemNumber] = 0; + parentById_[itemNumber] = 0; + allocatedIds_[itemNumber] = false; + freeItemIds_.push_back(itemNumber); return true; } @@ -620,6 +854,18 @@ bool LiveFixedMapItems::isGlobHatched(u16 eggItemNumber) const return eggItemNumber < hatchedGlobIds_.size() && hatchedGlobIds_[eggItemNumber]; } +bool LiveFixedMapItems::setItemFrame(u16 itemNumber, u8 frame) +{ + const auto item = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& candidate) { + return candidate.itemNumber == itemNumber; + }); + if (item == items_.end()) { + return false; + } + item->data.frame = frame; + return true; +} + bool LiveFixedMapItems::moveItem(u16 itemNumber, u16 x, u16 y, u8 z) { if (x > 0x7fff || y > 0x7fff) { diff --git a/rebuild/remorse/src/usecode_vm.cpp b/rebuild/remorse/src/usecode_vm.cpp index 86d6d81..3abfc65 100644 --- a/rebuild/remorse/src/usecode_vm.cpp +++ b/rebuild/remorse/src/usecode_vm.cpp @@ -5,15 +5,28 @@ namespace remorse { std::optional UsecodeInterpreterState::initialize( - const std::vector& itemParameter) + const std::vector& itemParameter, const std::vector& contextParameter, + u16 modeFlags) { - if (itemParameter.size() > 0xcc) { + const bool saveStackPointer = !contextParameter.empty() && modeFlags != 0; + const std::size_t savedPointerBytes = saveStackPointer ? sizeof(FarPtr16) : 0; + if (itemParameter.size() > usecodeInterpreterStackLimit || + contextParameter.size() > usecodeInterpreterStackLimit - itemParameter.size() || + savedPointerBytes > usecodeInterpreterStackLimit - itemParameter.size() - contextParameter.size()) { return std::nullopt; } UsecodeInterpreterState state; - state.stackTop -= itemParameter.size(); - std::copy(itemParameter.begin(), itemParameter.end(), - state.valueStack.begin() + state.stackTop); + state.stackHighWatermark = state.valueStack.size(); + const auto pushBytes = [&state](const std::vector& bytes) { + state.stackTop -= bytes.size(); + std::copy(bytes.begin(), bytes.end(), state.valueStack.begin() + state.stackTop); + }; + pushBytes(itemParameter); + pushBytes(contextParameter); + if (saveStackPointer) { + state.stackTop -= savedPointerBytes; + state.contextParameterOffset = static_cast(state.stackTop - sizeof(u16) * 2); + } return state; } @@ -26,4 +39,484 @@ bool UsecodeInterpreterState::pushCodeAddress(u16 offset, u16 segment) return true; } +bool UsecodeInterpreterState::pushWord(u16 value) +{ + if (stackTop < sizeof(value)) { + return false; + } + stackTop -= sizeof(value); + valueStack[stackTop] = static_cast(value); + valueStack[stackTop + 1] = static_cast(value >> 8); + return true; +} + +bool UsecodeInterpreterState::pushDword(u32 value) +{ + if (stackTop < sizeof(value)) { + return false; + } + stackTop -= sizeof(value); + for (std::size_t index = 0; index < sizeof(value); ++index) { + valueStack[stackTop + index] = static_cast(value >> (index * 8)); + } + return true; +} + +std::optional UsecodeInterpreterState::popWord() +{ + if (stackTop > stackHighWatermark || stackHighWatermark > valueStack.size() || + stackHighWatermark - stackTop < sizeof(u16)) { + return std::nullopt; + } + const u16 value = static_cast(valueStack[stackTop] | + (static_cast(valueStack[stackTop + 1]) << 8)); + stackTop += sizeof(u16); + return value; +} + +std::optional UsecodeInterpreterState::popDword() +{ + if (stackTop > stackHighWatermark || stackHighWatermark > valueStack.size() || + stackHighWatermark - stackTop < sizeof(u32)) { + return std::nullopt; + } + u32 value = 0; + for (std::size_t index = 0; index < sizeof(value); ++index) { + value |= static_cast(valueStack[stackTop + index]) << (index * 8); + } + stackTop += sizeof(value); + return value; +} + +UsecodeStepResult UsecodeInterpreterState::step(const std::vector& code, + std::size_t& programCounter, std::vector& frame, + const UsecodeOpcodeServices& services) +{ + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const u8 opcode = code[programCounter++]; + if (opcode == 0x00 || opcode == 0x01 || opcode == 0x3e || opcode == 0x3f) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const auto rawOffset = static_cast(code[programCounter]); + const auto localIndex = static_cast(usecodeFrameBaseOffset) + rawOffset; + const bool byteOperation = opcode == 0x00 || opcode == 0x3e; + const std::size_t valueSize = byteOperation ? sizeof(u8) : sizeof(u16); + if (localIndex < 0 || static_cast(localIndex) > frame.size() || + frame.size() - static_cast(localIndex) < valueSize) { + return UsecodeStepResult::InvalidInstruction; + } + const std::size_t localOffset = static_cast(localIndex); + if (opcode == 0x3e) { + ++programCounter; + return pushWord(frame[localOffset]) + ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x3f) { + ++programCounter; + const u16 value = static_cast(frame[localOffset] | + (static_cast(frame[localOffset + 1]) << 8)); + return pushWord(value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (stackTop > valueStack.size() - sizeof(u16)) { + return UsecodeStepResult::StackFault; + } + ++programCounter; + if (opcode == 0x00) { + frame[localOffset] = valueStack[stackTop]; + } else { + frame[localOffset] = valueStack[stackTop]; + frame[localOffset + 1] = valueStack[stackTop + 1]; + } + return popWord() ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x0a) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const auto value = static_cast(static_cast(code[programCounter++])); + return pushWord(static_cast(value)) + ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x0c) { + if (code.size() - programCounter < sizeof(u32)) { + return UsecodeStepResult::InvalidInstruction; + } + u32 value = 0; + for (std::size_t index = 0; index < sizeof(value); ++index) { + value |= static_cast(code[programCounter + index]) << (index * 8); + } + programCounter += sizeof(value); + return pushDword(value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x0f) { + const std::size_t instructionStart = programCounter - 1; + if (code.size() - programCounter < 3) { + return UsecodeStepResult::InvalidInstruction; + } + const u8 argumentBytes = code[programCounter]; + const u16 ordinal = static_cast(code[programCounter + 1] | + (static_cast(code[programCounter + 2]) << 8)); + if (!services.callIntrinsic) { + programCounter = instructionStart; + return UsecodeStepResult::UnsupportedOpcode; + } + if (argumentBytes > valueStack.size() - stackTop) { + return UsecodeStepResult::StackFault; + } + const auto result = services.callIntrinsic(ordinal, argumentBytes, + valueStack.data() + stackTop); + if (!result) { + programCounter = instructionStart; + return UsecodeStepResult::ServiceRejected; + } + programCounter += 3; + temporaryWord = *result; + return UsecodeStepResult::Advanced; + } + if (opcode == 0x14 || opcode == 0x1c || opcode == 0x24 || opcode == 0x2a || + opcode == 0x2c || opcode == 0x36) { + const auto right = popWord(); + const auto left = right ? popWord() : std::nullopt; + if (!left || !right) { + if (right) pushWord(*right); + return UsecodeStepResult::StackFault; + } + u16 result = 0; + if (opcode == 0x14) result = static_cast(*left + *right); + else if (opcode == 0x1c) result = static_cast(*left - *right); + else if (opcode == 0x24) result = static_cast(*left == *right); + else if (opcode == 0x2a) result = static_cast(*left <= *right); + else if (opcode == 0x2c) result = static_cast(static_cast(*left) > static_cast(*right)); + else result = static_cast(*left != *right); + return pushWord(result) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x51 || opcode == 0x52) { + if (code.size() - programCounter < sizeof(u16)) { + return UsecodeStepResult::InvalidInstruction; + } + const s16 relativeOffset = static_cast(code[programCounter] | + (static_cast(code[programCounter + 1]) << 8)); + programCounter += sizeof(u16); + bool shouldJump = opcode == 0x52; + if (opcode == 0x51) { + const auto condition = popWord(); + if (!condition) { + return UsecodeStepResult::StackFault; + } + shouldJump = *condition == 0; + } + if (shouldJump) { + const auto target = static_cast(programCounter) + relativeOffset; + if (target < 0 || static_cast(target) >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + programCounter = static_cast(target); + } + return UsecodeStepResult::Advanced; + } + if (opcode == 0x53) { + return UsecodeStepResult::Yielded; + } + if (opcode == 0x54) { + if (code.size() - programCounter < 2) { + return UsecodeStepResult::InvalidInstruction; + } + programCounter += 2; + if (!popWord()) { + return UsecodeStepResult::StackFault; + } + if (temporaryWord >= 3) { + impliedProcessId = temporaryWord; + } + return UsecodeStepResult::Advanced; + } + if (opcode == 0x59) { + if (!services.currentProcessId) { + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; + } + currentProcessId = services.currentProcessId(); + return pushWord(currentProcessId) + ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x5d) { + return pushWord(static_cast(temporaryWord)) + ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x6e) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const auto adjustment = static_cast(code[programCounter++]); + const auto newTop = static_cast(stackTop) - adjustment; + if (newTop < 0 || newTop > static_cast(valueStack.size())) { + return UsecodeStepResult::StackFault; + } + stackTop = static_cast(newTop); + stackHighWatermark = std::max(stackHighWatermark, stackTop); + return UsecodeStepResult::Advanced; + } + if (opcode == 0x12) { + const auto value = popWord(); + if (!value) { + return UsecodeStepResult::StackFault; + } + temporaryWord = *value; + return UsecodeStepResult::Advanced; + } + if (opcode == 0x0b) { + if (code.size() - programCounter < 2) { + return UsecodeStepResult::InvalidInstruction; + } + const u16 value = static_cast(code[programCounter] | + (static_cast(code[programCounter + 1]) << 8)); + programCounter += 2; + return pushWord(value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x40) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const std::size_t localOffset = code[programCounter++]; + const std::size_t localIndex = usecodeFrameBaseOffset + localOffset; + if (localIndex > frame.size() || frame.size() - localIndex < sizeof(u32)) { + return UsecodeStepResult::InvalidInstruction; + } + const u32 value = static_cast(frame[localIndex]) | + (static_cast(frame[localIndex + 1]) << 8) | + (static_cast(frame[localIndex + 2]) << 16) | + (static_cast(frame[localIndex + 3]) << 24); + return pushDword(value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x4c) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const std::size_t valueSize = code[programCounter++]; + if (valueSize != sizeof(u16)) { + return UsecodeStepResult::UnsupportedOpcode; + } + const auto address = popDword(); + if (!address) { + return UsecodeStepResult::StackFault; + } + if (!services.readFarWord) { + pushDword(*address); + return UsecodeStepResult::ServiceRejected; + } + const auto value = services.readFarWord(static_cast(*address), + static_cast(*address >> 16)); + if (!value) { + pushDword(*address); + return UsecodeStepResult::InvalidInstruction; + } + return pushWord(*value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x77) { + if (!services.setInfo) { + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; + } + const auto first = popWord(); + const auto second = first ? popWord() : std::nullopt; + if (!first || !second) { + if (first) pushWord(*first); + return UsecodeStepResult::StackFault; + } + lastSetInfoOperands = std::array{*first, *second}; + if (!services.setInfo(*second, *first)) { + pushWord(*second); + pushWord(*first); + return UsecodeStepResult::ServiceRejected; + } + return UsecodeStepResult::SetInfo; + } + if (opcode == 0x50) { + return UsecodeStepResult::Returned; + } + if (opcode == 0x57) { + const std::size_t instructionStart = programCounter - 1; + if (code.size() - programCounter < 6) { + return UsecodeStepResult::InvalidInstruction; + } + const u8 extraArgumentBytes = code[programCounter]; + const u8 itemArgumentSize = code[programCounter + 1]; + const u16 classId = static_cast(code[programCounter + 2] | + (static_cast(code[programCounter + 3]) << 8)); + const u16 eventSlot = static_cast(code[programCounter + 4] | + (static_cast(code[programCounter + 5]) << 8)); + if ((itemArgumentSize != 0 && itemArgumentSize != sizeof(u16)) || + stackTop > valueStack.size() - sizeof(u32) || + extraArgumentBytes > valueStack.size() - stackTop - sizeof(u32)) { + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; + } + if (!services.spawn || (itemArgumentSize != 0 && !services.readFarWord)) { + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; + } + const auto itemPointer = popDword(); + if (!itemPointer) { + return UsecodeStepResult::StackFault; + } + u16 itemArgument = 0; + if (itemArgumentSize == sizeof(u16)) { + const auto value = services.readFarWord(static_cast(*itemPointer), + static_cast(*itemPointer >> 16)); + if (!value) { + pushDword(*itemPointer); + programCounter = instructionStart; + return UsecodeStepResult::InvalidInstruction; + } + itemArgument = *value; + } + const u8* extraArguments = valueStack.data() + stackTop; + programCounter += 6; + const auto processId = services.spawn(classId, eventSlot, extraArgumentBytes, + itemArgumentSize, itemArgument, extraArguments); + if (!processId) { + pushDword(*itemPointer); + programCounter = instructionStart; + return UsecodeStepResult::ServiceRejected; + } + temporaryWord = *processId; + return UsecodeStepResult::Spawned; + } + if (opcode == 0x5b) { + if (code.size() - programCounter < 2) { + return UsecodeStepResult::InvalidInstruction; + } + programCounter += 2; + return UsecodeStepResult::Advanced; + } + if (opcode == 0x5c) { + constexpr std::size_t symbolInfoBytes = 11; + if (code.size() - programCounter < symbolInfoBytes) { + return UsecodeStepResult::InvalidInstruction; + } + programCounter += symbolInfoBytes; + return UsecodeStepResult::Advanced; + } + if (opcode == 0x5e) { + return pushWord(temporaryWord) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x78) { + if (!services.processCount) { + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; + } + processExcluded = services.processCount() > 1; + return UsecodeStepResult::Advanced; + } + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; +} + +std::optional UsecodeProcessTask::create(u16 processId, u16 classId, + u16 eventSlot, u16 sourceItem, std::vector code, u8 itemArgumentSize, + std::vector extraArguments, std::vector contextParameter) +{ + if (processId < 3 || code.size() <= usecodeEventBytecodeOffset || + (itemArgumentSize != 0 && itemArgumentSize != sizeof(u16))) { + return std::nullopt; + } + const std::vector itemParameter = itemArgumentSize == 0 ? std::vector{} + : std::vector{static_cast(sourceItem), static_cast(sourceItem >> 8)}; + auto interpreter = UsecodeInterpreterState::initialize(itemParameter, contextParameter, + itemArgumentSize); + if (!interpreter) { + return std::nullopt; + } + UsecodeProcessTask task; + task.processId = processId; + task.classId = classId; + task.eventSlot = eventSlot; + task.sourceItem = sourceItem; + task.code = std::move(code); + task.frame.resize(0x80); + task.itemMemory.resize(0x102); + task.itemMemory[0x100] = static_cast(sourceItem); + task.itemMemory[0x101] = static_cast(sourceItem >> 8); + std::size_t argumentOffset = usecodeFrameBaseOffset + 6; + if (itemArgumentSize == sizeof(u16)) { + task.frame[argumentOffset] = 0x00; + task.frame[argumentOffset + 1] = 0x01; + argumentOffset += sizeof(u32); + } + if (extraArguments.size() > task.frame.size() - argumentOffset) { + return std::nullopt; + } + std::copy(extraArguments.begin(), extraArguments.end(), task.frame.begin() + argumentOffset); + task.interpreter = std::move(*interpreter); + return task; +} + +std::optional UsecodeProcessTask::readMappedItemWord(FarPtr16 address) const +{ + if (address.segment != 0 || address.offset > itemMemory.size() || + itemMemory.size() - address.offset < sizeof(u16)) { + return std::nullopt; + } + return static_cast(itemMemory[address.offset] | + (static_cast(itemMemory[address.offset + 1]) << 8)); +} + +bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize, + const UsecodeContextFactoryFields& fields) +{ + if (processBytes == nullptr || processSize < usecodeContextProcessSize) { + return false; + } + const auto writeWord = [processBytes](std::size_t offset, u16 value) { + processBytes[offset] = static_cast(value); + processBytes[offset + 1] = static_cast(value >> 8); + }; + writeWord(usecodeContextSlotIndexOffset, fields.slotIndex); + writeWord(usecodeContextValueAddOffset, fields.valueAddOffset); + writeWord(usecodeContextOwnerSourceOffset, fields.ownerSource.offset); + writeWord(usecodeContextOwnerSourceOffset + sizeof(u16), fields.ownerSource.segment); + writeWord(usecodeContextParameterOffset, fields.parameterOffset); + processBytes[usecodeContextModeFlagsOffset] = static_cast(fields.modeFlags); + processBytes[usecodeContextActiveFlagOffset] = 0; + return true; +} + +UsecodeStepResult UsecodeProcessTask::step(const UsecodeOpcodeServices& services) +{ + if (halted) { + return UsecodeStepResult::Returned; + } + const auto result = interpreter.step(code, programCounter, frame, services); + halted = result == UsecodeStepResult::Returned; + return result; +} + +bool UsecodeTaskRegistry::add(UsecodeProcessTask task) +{ + if (task.processId < 3) { + return false; + } + return tasks_.emplace(task.processId, std::move(task)).second; +} + +UsecodeProcessTask* UsecodeTaskRegistry::find(u16 processId) +{ + const auto found = tasks_.find(processId); + return found == tasks_.end() ? nullptr : &found->second; +} + +const UsecodeProcessTask* UsecodeTaskRegistry::find(u16 processId) const +{ + const auto found = tasks_.find(processId); + return found == tasks_.end() ? nullptr : &found->second; +} + +bool UsecodeTaskRegistry::remove(u16 processId) +{ + return tasks_.erase(processId) != 0; +} + } // 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 6027077..acf676f 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -15,6 +15,7 @@ #include "remorse/shape_archive.h" #include "remorse/type_flags.h" #include "remorse/usecode_archive.h" +#include "remorse/usecode_vm.h" #include #include @@ -47,6 +48,10 @@ struct AppState { bool diagnostics = false; remorse::ProcessKernel diagnosticKernel; remorse::u16 diagnosticGroupCounts[32]{}; + remorse::UsecodeTaskRegistry usecodeTasks; + bool useRequested = false; + bool usecodeWorldMutationPending = false; + std::uint64_t heldKeycards = 0; remorse::StandProcessEntry* diagnosticStand = nullptr; remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr; remorse::ControllerMovementState controllerMovement; @@ -55,6 +60,7 @@ struct AppState { std::optional diagnosticItem; remorse::u16 diagnosticItemProcessId = 0; remorse::u16 diagnosticReleaseEventItem = 0; + remorse::u16 diagnosticReleaseProcessId = 0; std::string diagnosticReleaseClass; std::size_t diagnosticReleaseBodyBytes = 0; bool diagnosticItemCompleted = false; @@ -142,6 +148,208 @@ remorse::WorldPoint avatarWorld(const AppState& state) bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range); +std::optional queueUsecodeTask(AppState& state, remorse::u16 classId, + remorse::u16 eventSlot, remorse::u16 sourceItem, std::vector code, + remorse::u8 itemArgumentSize = 2, std::vector extraArguments = {}) +{ + auto* process = state.diagnosticKernel.createUsecodeProcess( + state.diagnosticKernel.activeGroup(), state.diagnosticGroupCounts); + const remorse::u16 processId = static_cast(process->base.bytes[2] | + (static_cast(process->base.bytes[3]) << 8)); + 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(); + 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(); + return std::nullopt; + } + return processId; +} + +bool startNearbyUsecode(AppState& state) +{ + if (!state.liveItems || !state.usecodeArchive || state.usecodeOwnerRows.empty()) { + return false; + } + const auto* origin = state.liveItems->findItem(1); + if (origin == nullptr || origin->data.shape >= state.shapeTypes.size()) { + return false; + } + const auto candidates = remorse::itemGrabSearchCandidates(*origin, + state.liveItems->mapItems(), state.shapeTypes); + if (!candidates) { + return false; + } + for (const auto& candidate : *candidates) { + const auto* item = state.liveItems->findItem(candidate.itemNumber); + if (item == nullptr || item->data.shape >= state.shapeTypes.size()) { + continue; + } + const auto& shape = state.shapeTypes[item->data.shape]; + const remorse::UsecodeItemIdentity identity{item->itemNumber, item->data.shape, + item->data.flags, item->data.quality, shape.family, false}; + const auto eligible = remorse::selectEligibleUsecodeEvent(*state.usecodeArchive, + state.usecodeOwnerRows, identity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); + if (eligible) { + return queueUsecodeTask(state, eligible->classId, 1, item->itemNumber, + eligible->body.bytes).has_value(); + } + } + return false; +} + +void runUsecodeTasks(AppState& state) +{ + state.diagnosticKernel.scanRunnableProcesses(state.diagnosticKernel.activeGroup(), + [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& app = *static_cast(context); + const remorse::u16 processId = static_cast(process.bytes[2] | + (static_cast(process.bytes[3]) << 8)); + auto* task = app.usecodeTasks.find(processId); + if (!task || task->halted) { + return; + } + if (task->timerDelayProcess) { + if (app.diagnosticKernel.systemTimerTick() >= task->wakeTick) { + app.diagnosticKernel.terminateProcess(processId, app.diagnosticGroupCounts); + } + return; + } + if (task->interpreter.impliedProcessId != 0) { + if (app.diagnosticKernel.processAt(task->interpreter.impliedProcessId) != nullptr) { + return; + } + task->interpreter.impliedProcessId = 0; + } + remorse::UsecodeOpcodeServices services; + services.readFarWord = [task](remorse::u16 offset, remorse::u16 segment) + -> std::optional { + return task->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + services.setInfo = [&app, processId](remorse::u16 eventType, remorse::u16 sourceItem) { + return app.diagnosticKernel.setProcessInfo(processId, eventType, sourceItem); + }; + services.processCount = [&app]() { return app.diagnosticKernel.processCount(); }; + services.currentProcessId = [processId]() { return processId; }; + services.callIntrinsic = [&app, task](remorse::u16 ordinal, remorse::u8 argumentBytes, + const remorse::u8* arguments) -> std::optional { + if (ordinal == 0x00 && argumentBytes == 0) { + return remorse::u16{0}; + } + if (ordinal == 0xfd && argumentBytes == 2) { + const remorse::u16 keycard = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + return static_cast(keycard < 64 && + (app.heldKeycards & (std::uint64_t{1} << keycard)) != 0); + } + if (ordinal == 0x15 && argumentBytes == 6) { + return remorse::u16{0}; + } + if (ordinal == 0x3a && argumentBytes == 6) { + return remorse::u16{0}; + } + if (argumentBytes < 4) { + return std::nullopt; + } + const remorse::u16 offset = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + const remorse::u16 segment = static_cast(arguments[2] | + (static_cast(arguments[3]) << 8)); + const auto itemNumber = task->readMappedItemWord(remorse::FarPtr16{offset, segment}); + if (!itemNumber) { + return std::nullopt; + } + if (ordinal == 0xea && argumentBytes == 4) { + const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; + return item ? std::optional{static_cast(item->data.quality & 0xff)} + : std::nullopt; + } + if (ordinal == 0x01 && argumentBytes == 4) { + const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; + return item ? std::optional{item->data.frame} : std::nullopt; + } + if (ordinal == 0x03 && argumentBytes == 4) { + const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; + return item ? std::optional{item->data.mapNumber} : std::nullopt; + } + if (ordinal == 0x59 && argumentBytes == 6) { + std::lock_guard lock(app.sceneMutex); + const remorse::u8 frame = static_cast(arguments[4] | + (static_cast(arguments[5]) << 8)); + if (!app.liveItems || !app.liveItems->setItemFrame(*itemNumber, frame)) { + return std::nullopt; + } + app.usecodeWorldMutationPending = true; + return remorse::u16{0}; + } + return std::nullopt; + }; + services.spawn = [&app](remorse::u16 classId, remorse::u16 eventSlot, + remorse::u8 extraArgumentBytes, remorse::u8 itemArgumentSize, + remorse::u16 itemArgument, const remorse::u8* extraArguments) + -> std::optional { + if (!app.usecodeArchive) { + return std::nullopt; + } + const auto usecodeClass = remorse::loadUsecodeClass(*app.usecodeArchive, classId); + const auto body = usecodeClass + ? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt; + if (!body) { + return std::nullopt; + } + std::vector arguments; + if (extraArgumentBytes != 0) { + arguments.assign(extraArguments, extraArguments + extraArgumentBytes); + } + const auto childId = queueUsecodeTask(app, classId, eventSlot, + itemArgument, body->bytes, itemArgumentSize, std::move(arguments)); + if (!childId) { + return std::nullopt; + } + auto* registeredChild = app.usecodeTasks.find(*childId); + if (registeredChild && classId == 0x0a0c && eventSlot == 0x32 && + itemArgumentSize == 0 && extraArgumentBytes == 2) { + const remorse::u16 delay = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + registeredChild->timerDelayProcess = true; + registeredChild->wakeTick = app.diagnosticKernel.systemTimerTick() + delay; + } + return childId; + }; + for (std::size_t instructionCount = 0; instructionCount < 256; ++instructionCount) { + const auto result = task->step(services); + if (result == remorse::UsecodeStepResult::Returned) { + app.diagnosticKernel.terminateProcess(processId, app.diagnosticGroupCounts); + break; + } + if (result == remorse::UsecodeStepResult::Yielded) { + break; + } + if (result != remorse::UsecodeStepResult::Advanced && + result != remorse::UsecodeStepResult::SetInfo && + result != remorse::UsecodeStepResult::Spawned) { + task->halted = true; + break; + } + } + }, &state, state.diagnosticKernel.systemTimerTick()); + state.diagnosticKernel.clearTerminatedProcesses(); + for (std::size_t processId = 3; processId < 1020; ++processId) { + const auto id = static_cast(processId); + if (state.usecodeTasks.find(id) && state.diagnosticKernel.processAt(id) == nullptr) { + state.usecodeTasks.remove(id); + } + } +} + void loadSceneAsync(HWND window, AppState& state) { state.sceneThread = std::thread([window, &state]() { @@ -659,12 +867,18 @@ void paintWindow(HWND window, AppState& state) playerWorld.x, playerWorld.y, diagnosticItemRange) : std::nullopt; if (state.diagnosticItem || nearbyItem) { const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem; + const auto* releaseTask = state.diagnosticReleaseProcessId != 0 + ? state.usecodeTasks.find(state.diagnosticReleaseProcessId) : nullptr; + const std::wstring releaseStatus = state.diagnosticReleaseProcessId == 0 ? L"NOT QUEUED" : + releaseTask == nullptr ? L"COMPLETE" : releaseTask->halted ? L"HALTED" : + releaseTask->programCounter == remorse::usecodeEventBytecodeOffset ? L"QUEUED" : L"RUNNING"; std::wostringstream itemStatus; itemStatus << L"MAP ITEM " << displayItem->itemNumber << L" | SHAPE " << displayItem->data.shape << L" | RELEASE REQUEST " << state.diagnosticReleaseEventItem << L" | " << (state.diagnosticReleaseBodyBytes != 0 - ? widen(state.diagnosticReleaseClass) + L" SCRIPT " + std::to_wstring(state.diagnosticReleaseBodyBytes) + L" BYTES (NOT RUN)" + ? widen(state.diagnosticReleaseClass) + L" SCRIPT " + std::to_wstring(state.diagnosticReleaseBodyBytes) + + L" BYTES (" + releaseStatus + L")" : L"NO RELEASE SCRIPT") << L" | PROCESS " << (state.diagnosticItemCompleted ? L"DONE" : state.diagnosticItemProcessId != 0 ? L"QUEUED" : @@ -708,6 +922,11 @@ void updatePlayer(HWND window, AppState& state) app.controllerMovement.handleDirectionalKey(event.scanCode, event.modifiers, event.field8 != 0); } }, &state); + if (state.useRequested) { + state.useRequested = false; + changed = startNearbyUsecode(state) || changed; + } + runUsecodeTasks(state); const auto movement = state.controllerMovement.request(); state.diagnosticKernel.deliverSystemTimerEvent(); if (state.diagnostics) { @@ -724,17 +943,21 @@ void updatePlayer(HWND window, AppState& state) [](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* releaseContext) { auto& app = *static_cast(releaseContext); app.diagnosticReleaseEventItem = itemNumber; - if (app.diagnosticItem && app.usecodeArchive && - app.diagnosticItem->data.shape < app.shapeTypes.size()) { - const auto& item = *app.diagnosticItem; - const remorse::UsecodeItemIdentity identity{item.itemNumber, item.data.shape, - item.data.flags, item.data.quality, app.shapeTypes[item.data.shape].family, false}; + app.diagnosticReleaseProcessId = 0; + app.diagnosticReleaseClass.clear(); + app.diagnosticReleaseBodyBytes = 0; + const auto* item = app.liveItems ? app.liveItems->findItem(itemNumber) : nullptr; + if (item && app.usecodeArchive && item->data.shape < app.shapeTypes.size()) { + const remorse::UsecodeItemIdentity identity{item->itemNumber, item->data.shape, + item->data.flags, item->data.quality, app.shapeTypes[item->data.shape].family, false}; const remorse::UsecodeClassBases bases{0, 0x800, 0x900}; const auto eligible = remorse::selectEligibleUsecodeEvent(*app.usecodeArchive, app.usecodeOwnerRows, identity, bases, eventMask, eventId); if (eligible) { app.diagnosticReleaseClass = eligible->className; app.diagnosticReleaseBodyBytes = eligible->body.bytes.size(); + app.diagnosticReleaseProcessId = queueUsecodeTask(app, + eligible->classId, eventId, itemNumber, eligible->body.bytes).value_or(0); } } }, &app); @@ -814,7 +1037,9 @@ void updatePlayer(HWND window, AppState& state) avatar->data.z != beforeMove.z; const bool hatched = moved && hatchGlobsInFastArea( *state.liveItems, *state.renderer, remorse::calculateFastAreaRange(avatarWorld(state))); - if (state.renderThread.joinable() && (moved || hatched)) { + const bool usecodeMutation = state.usecodeWorldMutationPending; + state.usecodeWorldMutationPending = false; + if (state.renderThread.joinable() && (moved || hatched || usecodeMutation)) { state.renderRequested = true; state.renderWake.notify_one(); } @@ -859,6 +1084,9 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA DestroyWindow(window); return 0; } + if (wParam == 'E' && message == WM_KEYDOWN) { + state->useRequested = true; + } { remorse::KeyEvent event{}; event.scanCode = static_cast((lParam >> 16) & 0xff); diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index 177f96f..9a4ee99 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -151,6 +151,33 @@ int main() assert(createdKernel.processAt(2) == syncing && createdGroups[2] == 3); assert(syncing->bytes[0x16] == 0x40 && syncing->bytes[0x17] == 0); + remorse::ProcessKernel usecodeKernel; + remorse::u16 usecodeGroups[32]{}; + for (int index = 0; index < 3; ++index) { + usecodeKernel.createProcess(1, usecodeGroups); + } + auto* usecodeContext = usecodeKernel.createUsecodeProcess(1, usecodeGroups); + const remorse::u16 usecodeProcessId = static_cast( + usecodeContext->base.bytes[2] | (static_cast(usecodeContext->base.bytes[3]) << 8)); + assert(usecodeKernel.allocationSizeAt(usecodeProcessId) == 0x124 && + std::strcmp(usecodeKernel.processNameAt(usecodeProcessId), "Usecode") == 0); + assert(usecodeKernel.setProcessInfo(usecodeProcessId, 0x0207, 0x1234)); + int usecodeRuns = 0; + usecodeKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& scan = *static_cast(context); + if (process.bytes[2] == 3 && process.bytes[3] == 0) { + ++scan; + } + }, &usecodeRuns); + assert(usecodeRuns == 1 && usecodeKernel.processAt(usecodeProcessId) == &usecodeContext->base); + usecodeKernel.terminateProcess(usecodeProcessId, usecodeGroups); + assert(usecodeKernel.processAt(usecodeProcessId) == &usecodeContext->base && + (usecodeContext->base.bytes[0x16] & 0x08) != 0 && + usecodeKernel.processCount() == 3 && usecodeGroups[1] == 3); + usecodeKernel.clearTerminatedProcesses(); + assert(usecodeKernel.processAt(usecodeProcessId) == nullptr && + usecodeKernel.terminatedProcessCount() == 0); + createdKernel.setSyncContext(true, 1); next->bytes[0x18] |= 0x02; auto* retiring = createdKernel.createProcess(2, createdGroups); @@ -269,6 +296,16 @@ int main() assert((ran == std::vector{2, 3})); assert(specialGroup->bytes[0x08] == 30); + remorse::ProcessKernel automaticGroupKernel; + remorse::u16 automaticGroupCounts[32]{}; + automaticGroupKernel.createProcess(3, automaticGroupCounts); + std::vector automaticGroupRuns; + automaticGroupKernel.scanRunnableProcesses(2, recordRun, &automaticGroupRuns); + assert(automaticGroupRuns.empty() && automaticGroupKernel.activeGroup() == 3 && + !automaticGroupKernel.groupSelectionPending()); + automaticGroupKernel.scanRunnableProcesses(3, recordRun, &automaticGroupRuns); + assert((automaticGroupRuns == std::vector{0})); + remorse::ProcessKernel spawningKernel; remorse::u16 spawningGroups[32]{}; spawningKernel.createProcess(1, spawningGroups); diff --git a/rebuild/remorse/tests/fixed_map_tests.cpp b/rebuild/remorse/tests/fixed_map_tests.cpp index 9be0fa8..f4b84a2 100644 --- a/rebuild/remorse/tests/fixed_map_tests.cpp +++ b/rebuild/remorse/tests/fixed_map_tests.cpp @@ -236,6 +236,13 @@ int main() assert(allocatedItems.allocateItem(newItem) == 0x107); newItem.data.x = 0x8000; assert(!allocatedItems.allocateItem(newItem) && !allocatedItems.findItem(0x108)); + newItem.data.x = 511; + remorse::ProcessKernel recyclingKernel; + assert(allocatedItems.releaseItem(0x106, recyclingKernel)); + assert(allocatedItems.releaseItem(0x107, recyclingKernel)); + assert(allocatedItems.allocateItem(newItem) == 0x107); + assert(allocatedItems.allocateItem(newItem) == 0x106); + remorse::StagedFixedMapItem globEgg; globEgg.itemNumber = 0x100; globEgg.data.x = 0x403; @@ -254,6 +261,24 @@ int main() assert(child->data.x == 0x405 && child->data.y == 0x60b && child->data.z == 15); assert(child->data.flags == 0x82 && child->data.frame == 2); assert(hatchedItems.isGlobHatched(0x100) && !hatchedItems.hatchGlobEgg(0x100, glob, globShapes)); + + remorse::LiveFixedMapItems processOwnedItems({globEgg}); + remorse::ProcessKernel itemOwnerKernel; + remorse::u16 itemOwnerGroups[32]{}; + for (int index = 0; index < 3; ++index) { + itemOwnerKernel.createProcess(1, itemOwnerGroups); + } + auto* itemOwner = itemOwnerKernel.createItemProcess(1, 0x100, itemOwnerGroups); + assert(itemOwnerKernel.itemHasProcess(0x100)); + assert(!processOwnedItems.releaseItem(0x100, itemOwnerKernel)); + const remorse::u16 itemOwnerProcessId = static_cast( + itemOwner->bytes[0x02] | (static_cast(itemOwner->bytes[0x03]) << 8)); + itemOwnerKernel.terminateProcess(itemOwnerProcessId, itemOwnerGroups); + itemOwnerKernel.clearTerminatedProcesses(); + assert(!itemOwnerKernel.itemHasProcess(0x100)); + assert(processOwnedItems.releaseItem(0x100, itemOwnerKernel)); + assert(processOwnedItems.allocateItem(globEgg) == 0x100); + remorse::LiveFixedMapItems movingItems(blockItems); remorse::ProcessKernel movingKernel; remorse::u16 movingGroups[32]{}; @@ -372,16 +397,51 @@ int main() assert((*contained)[2].itemNumber == 0x103 && (*contained)[2].parentItemNumber == 0x100); const auto directContainerItems = remorse::stageFixedMapItems(containedMap); assert(directContainerItems && directContainerItems->size() == 2); + auto monsterEggShapes = containerShapes; + monsterEggShapes[1].family = 7; + const auto monsterEggContents = remorse::stageContainedFixedMapItems(containedMap, monsterEggShapes); + assert(monsterEggContents && monsterEggContents->size() == 3 && + (*monsterEggContents)[0].parentItemNumber == 0x100 && + (*monsterEggContents)[1].parentItemNumber == 0x101 && + (*monsterEggContents)[2].parentItemNumber == 0x100); + remorse::LiveFixedMapItems monsterEggItems(*directContainerItems, *monsterEggContents); + assert((monsterEggItems.containedChildren(0x100) == std::vector{0x101, 0x103})); + assert(monsterEggItems.findItem(0x100)->data.quality == 0x101); + assert(!monsterEggItems.moveItemIntoContainer(0x104, 0x100, monsterEggShapes)); + assert(monsterEggItems.moveContainedItemToWorld(0x101, 600, 700, 12)); + assert(monsterEggItems.findItem(0x101)->data.quality == 0x102 && + monsterEggItems.findItem(0x100)->data.quality == 0x103); remorse::LiveFixedMapItems nestedItems(*directContainerItems, *contained); assert(nestedItems.containedParent(0x101) == 0x100 && nestedItems.containedParent(0x102) == 0x101 && nestedItems.containedParent(0x103) == 0x100); + assert((nestedItems.containedChildren(0x100) == std::vector{0x101, 0x103})); + assert((nestedItems.containedChildren(0x101) == std::vector{0x102})); + assert(nestedItems.findItem(0x100)->data.quality == 0x101); + assert(!nestedItems.moveItemIntoContainer(0x100, 0x102, containerShapes)); + assert(nestedItems.moveItemIntoContainer(0x104, 0x100, containerShapes)); + assert((nestedItems.containedChildren(0x100) == std::vector{0x104, 0x101, 0x103})); + assert(nestedItems.findItem(0x100)->data.quality == 0x104); + assert(!nestedItems.findItem(0x104) && nestedItems.containedParent(0x104) == 0x100); + assert(nestedItems.moveContainedItemToWorld(0x104, 700, 800, 12)); + assert((nestedItems.containedChildren(0x100) == std::vector{0x101, 0x103})); + assert(nestedItems.findItem(0x100)->data.quality == 0x101); + assert(nestedItems.findItem(0x104)->data.x == 700 && nestedItems.findItem(0x104)->data.y == 800); + assert(nestedItems.containedParent(0x102) == 0x101); remorse::StagedFixedMapItem nestedNewItem = directContainerItems->front(); assert(nestedItems.allocateItem(nestedNewItem) == 0x105); + remorse::ProcessKernel noItemProcesses; + assert(nestedItems.releaseItem(0x105, noItemProcesses)); + assert(!nestedItems.findItem(0x105)); + assert(nestedItems.allocateItem(nestedNewItem) == 0x105); assert(!nestedItems.findItem(0x101) && !nestedItems.findItem(0x102) && !nestedItems.findItem(0x103) && nestedItems.findItem(0x105)); nestedNewItem.itemNumber = 0x101; assert(nestedItems.insertItem(nestedNewItem)); + assert(nestedItems.findItem(0x100)->data.quality == 0x103); assert(nestedItems.containedParent(0x101) == 0 && nestedItems.containedParent(0x102) == 0x101); + assert((nestedItems.containedChildren(0x100) == std::vector{0x103})); + assert((nestedItems.containedChildren(0x101) == std::vector{0x102})); + assert(!nestedItems.releaseItem(0x101, noItemProcesses)); std::vector fullItemRange; for (remorse::u16 itemNumber = 0x101; itemNumber < 0x2800; ++itemNumber) { fullItemRange.push_back({itemNumber, 0x100, 0}); diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index a828602..0d04ad6 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -1,17 +1,28 @@ #include "remorse/collision.h" +#include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" #include "remorse/flex_archive.h" #include "remorse/fixed_map.h" #include "remorse/glob_archive.h" +#include "remorse/map_renderer.h" #include "remorse/type_flags.h" #include "remorse/usecode_archive.h" #include "remorse/usecode_vm.h" +#include +#include #include +#include #include int main() { + const auto hasRetailEventEntry = [](const std::vector& body, + const std::array& prefix) { + return body.size() > remorse::usecodeEventBytecodeOffset && + std::equal(prefix.begin(), prefix.end(), body.begin()) && + body[remorse::usecodeEventBytecodeOffset] == 0x0b; + }; const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); assert(root.has_value()); @@ -52,6 +63,9 @@ int main() assert(rechargeClass && rechargeClass->name == "RECHFLNS"); const auto releaseBody = remorse::readUsecodeEventBody(*rechargeClass, 9); assert(releaseBody && releaseBody->length == 102 && releaseBody->relativeOffset == 0x256); + const std::array releasePrefix{ + 0x5a, 0x02, 0x5c, 0x49, 0x00, 'R', 'E', 'C', 'H', 'F', 'L', 'N', 'S', 0x00}; + assert(hasRetailEventEntry(releaseBody->bytes, releasePrefix)); assert(remorse::ownerRowAllowsEvent(*retailOwnerRows, 0x138, 0x200)); const remorse::UsecodeClassBases bases{0x200, 0x400, 0x600}; remorse::UsecodeItemIdentity identity{7, 0x45, 0, 0x1278, 4, true}; @@ -74,6 +88,27 @@ int main() assert(stagedItems && !stagedItems->empty()); const auto spawnEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x1e); assert(spawnEgg); + unsigned eligibleMapUseItems = 0; + unsigned keycardUseItems = 0; + std::optional boxItem; + for (const auto& item : *stagedItems) { + if (item.data.shape >= typeFlags->size()) continue; + const auto& shape = (*typeFlags)[item.data.shape]; + const remorse::UsecodeItemIdentity mapItemIdentity{item.itemNumber, item.data.shape, + item.data.flags, item.data.quality, shape.family, false}; + const auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + mapItemIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); + if (eligible) { + ++eligibleMapUseItems; + if (eligible->classId == 0x031d || eligible->classId == 0x031e) { + ++keycardUseItems; + } + if (eligible->className == "BOX_NS" && item.data.frame == 0 && !boxItem) { + boxItem = item; + } + } + } + assert(eligibleMapUseItems == 218 && keycardUseItems == 10 && boxItem); const auto globPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GLOB.FLX"); const auto globs = globPath ? remorse::loadGlobObjects(*globPath) : std::nullopt; assert(globs); @@ -147,6 +182,320 @@ int main() assert(!interpreter->pushCodeAddress(0xffff, 0)); assert(interpreter->callFrameCount == 0x1f && interpreter->callFrames[31].offset == 0); assert(!remorse::UsecodeInterpreterState::initialize(std::vector(0xcd))); + const auto cardClass = remorse::loadUsecodeClass(*usecode, 0x31d); + const auto cardUse = cardClass ? remorse::readUsecodeEventBody(*cardClass, 1) : std::nullopt; + assert(cardClass && cardClass->name == "CARD_NS" && cardUse && cardUse->bytes.size() == 56); + const std::array cardPrefix{ + 0x5a, 0x00, 0x5c, 0x24, 0x00, 'C', 'A', 'R', 'D', '_', 'N', 'S', 0x00, 0x00}; + assert(hasRetailEventEntry(cardUse->bytes, cardPrefix)); + std::vector frame(0x80); + frame[remorse::usecodeFrameBaseOffset + 6] = 0x00; + frame[remorse::usecodeFrameBaseOffset + 7] = 0x01; + std::vector itemMemory(0x102); + itemMemory[0x100] = 0x34; + itemMemory[0x101] = 0x12; + remorse::ProcessKernel vmKernel; + remorse::u16 vmGroupCounts[32]{}; + for (int index = 0; index < 3; ++index) { + vmKernel.createProcess(1, vmGroupCounts); + } + auto* vmProcess = vmKernel.createUsecodeProcess(1, vmGroupCounts); + const remorse::u16 vmProcessId = static_cast( + vmProcess->base.bytes[2] | (static_cast(vmProcess->base.bytes[3]) << 8)); + auto cardTask = remorse::UsecodeProcessTask::create(vmProcessId, 0x31d, 1, 0x1234, + cardUse->bytes); + assert(cardTask && cardTask->programCounter == remorse::usecodeEventBytecodeOffset && + cardTask->frame.size() == 0x80 && + cardTask->frame[remorse::usecodeFrameBaseOffset + 7] == 1 && + cardTask->itemMemory[0x100] == 0x34 && + cardTask->itemMemory[0x101] == 0x12); + remorse::UsecodeTaskRegistry taskRegistry; + assert(taskRegistry.add(std::move(*cardTask)) && taskRegistry.size() == 1); + cardTask.reset(); + auto* registeredCardTask = taskRegistry.find(vmProcessId); + assert(registeredCardTask && registeredCardTask->classId == 0x31d && + registeredCardTask->eventSlot == 1 && registeredCardTask->sourceItem == 0x1234); + assert(!taskRegistry.add(*registeredCardTask)); + const auto switchClass = remorse::loadUsecodeClass(*usecode, 0x0a16); + const auto switchUse = switchClass ? remorse::readUsecodeEventBody(*switchClass, 0x21) : std::nullopt; + assert(switchClass && switchClass->name == "SWITCH" && switchUse); + remorse::UsecodeOpcodeServices opcodeServices; + opcodeServices.readFarWord = [registeredCardTask](remorse::u16 offset, remorse::u16 segment) + -> std::optional { + return registeredCardTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + opcodeServices.setInfo = [&vmKernel, vmProcessId](remorse::u16 eventType, + remorse::u16 sourceItem) { + return vmKernel.setProcessInfo(vmProcessId, eventType, sourceItem); + }; + std::optional> spawnedUsecode; + remorse::u16 spawnedProcessId = 0; + opcodeServices.processCount = [&vmKernel]() { return vmKernel.processCount(); }; + opcodeServices.spawn = [&spawnedUsecode, &spawnedProcessId, &vmKernel, &vmGroupCounts, + &taskRegistry, &switchUse](remorse::u16 classId, remorse::u16 eventSlot, + remorse::u8 extraArgumentBytes, remorse::u8 itemArgumentSize, + remorse::u16 itemArgument, const remorse::u8*) -> std::optional { + assert(extraArgumentBytes == 0 && itemArgumentSize == 2); + spawnedUsecode = std::array{classId, eventSlot, itemArgument}; + auto* child = vmKernel.createUsecodeProcess(1, vmGroupCounts); + spawnedProcessId = static_cast( + child->base.bytes[2] | (static_cast(child->base.bytes[3]) << 8)); + auto childTask = remorse::UsecodeProcessTask::create(spawnedProcessId, classId, + eventSlot, itemArgument, switchUse->bytes); + if (!childTask || !taskRegistry.add(std::move(*childTask))) { + vmKernel.terminateProcess(spawnedProcessId, vmGroupCounts); + vmKernel.clearTerminatedProcesses(); + return std::nullopt; + } + return spawnedProcessId; + }; + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 17); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 19); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 21); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::SetInfo && + registeredCardTask->programCounter == 22); + assert(registeredCardTask->interpreter.lastSetInfoOperands && + (*registeredCardTask->interpreter.lastSetInfoOperands)[0] == 0x1234 && + (*registeredCardTask->interpreter.lastSetInfoOperands)[1] == 0x0207); + assert(vmKernel.processAt(vmProcessId)->bytes[0x04] == 0x34 && + vmKernel.processAt(vmProcessId)->bytes[0x05] == 0x12 && + vmKernel.processAt(vmProcessId)->bytes[0x06] == 0x07 && + vmKernel.processAt(vmProcessId)->bytes[0x07] == 0x02); + opcodeServices.setInfo = [](remorse::u16, remorse::u16) { return false; }; + const auto stackTopBeforeRejectedInfo = registeredCardTask->interpreter.stackTop; + assert(registeredCardTask->interpreter.pushWord(0x1234) && + registeredCardTask->interpreter.pushWord(0x0207)); + const auto stackTopWithRejectedInfo = registeredCardTask->interpreter.stackTop; + registeredCardTask->programCounter = 21; + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::ServiceRejected && + registeredCardTask->programCounter == 22); + assert(registeredCardTask->interpreter.stackTop == stackTopWithRejectedInfo && + registeredCardTask->interpreter.popWord() == 0x0207 && + registeredCardTask->interpreter.popWord() == 0x1234); + registeredCardTask->interpreter.stackTop = stackTopBeforeRejectedInfo; + registeredCardTask->programCounter = 22; + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 23 && registeredCardTask->interpreter.processExcluded); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 26); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 28); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Spawned && + registeredCardTask->programCounter == 35); + assert(spawnedUsecode && (*spawnedUsecode)[0] == 0x0a16 && + (*spawnedUsecode)[1] == 0x21 && (*spawnedUsecode)[2] == 0x1234); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 36); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 37 && + registeredCardTask->interpreter.temporaryWord == spawnedProcessId); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 40); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Returned && + registeredCardTask->programCounter == 41); + auto* registeredSwitchTask = taskRegistry.find(spawnedProcessId); + assert(registeredSwitchTask && registeredSwitchTask->classId == 0x0a16 && + registeredSwitchTask->eventSlot == 0x21 && registeredSwitchTask->sourceItem == 0x1234 && + vmKernel.processAt(spawnedProcessId) != nullptr); + vmKernel.terminateProcess(vmProcessId, vmGroupCounts); + vmKernel.clearTerminatedProcesses(); + assert(taskRegistry.remove(vmProcessId) && taskRegistry.size() == 1 && + !taskRegistry.find(vmProcessId) && taskRegistry.find(spawnedProcessId) == registeredSwitchTask); + struct SwitchScheduleContext { + remorse::ProcessKernel* kernel; + remorse::UsecodeTaskRegistry* tasks; + remorse::u16 processId; + unsigned runs = 0; + } switchSchedule{&vmKernel, &taskRegistry, spawnedProcessId}; + vmKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& schedule = *static_cast(context); + const remorse::u16 processId = static_cast( + process.bytes[2] | (static_cast(process.bytes[3]) << 8)); + if (processId != schedule.processId) { + return; + } + ++schedule.runs; + auto* task = schedule.tasks->find(processId); + assert(task); + remorse::UsecodeOpcodeServices services; + services.readFarWord = [task](remorse::u16 offset, remorse::u16 segment) + -> std::optional { + return task->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + services.setInfo = [schedule, processId](remorse::u16 eventType, remorse::u16 sourceItem) { + return schedule.kernel->setProcessInfo(processId, eventType, sourceItem); + }; + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->step(services) == remorse::UsecodeStepResult::SetInfo); + }, &switchSchedule); + assert(switchSchedule.runs == 1 && registeredSwitchTask->programCounter == 22 && + vmKernel.processAt(spawnedProcessId)->bytes[0x04] == 0x34 && + vmKernel.processAt(spawnedProcessId)->bytes[0x06] == 0x07); + remorse::StagedFixedMapItem switchItem; + switchItem.itemNumber = 0x1234; + switchItem.data.shape = 0x216; + switchItem.data.quality = 3; + remorse::LiveFixedMapItems switchWorld({switchItem}); + auto switchTask = remorse::UsecodeProcessTask::create(spawnedProcessId, 0x0a16, 0x21, + switchItem.itemNumber, switchUse->bytes); + assert(switchTask); + const std::uint64_t heldKeycards = std::uint64_t{1} << switchItem.data.quality; + remorse::UsecodeOpcodeServices switchServices; + switchServices.readFarWord = [&switchTask](remorse::u16 offset, remorse::u16 segment) + -> std::optional { + return switchTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + switchServices.setInfo = [&vmKernel, spawnedProcessId](remorse::u16 eventType, + remorse::u16 sourceItem) { + return vmKernel.setProcessInfo(spawnedProcessId, eventType, sourceItem); + }; + switchServices.callIntrinsic = [&switchTask, &switchWorld, heldKeycards](remorse::u16 ordinal, + remorse::u8 argumentBytes, const remorse::u8* arguments) -> std::optional { + const auto itemNumber = [&]() -> std::optional { + if (argumentBytes < 4) return std::nullopt; + const remorse::u16 offset = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + const remorse::u16 segment = static_cast(arguments[2] | + (static_cast(arguments[3]) << 8)); + return switchTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + if (ordinal == 0x00 && argumentBytes == 0) return remorse::u16{0}; + if (ordinal == 0xfd && argumentBytes == 2) { + const remorse::u16 keycard = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + return static_cast((heldKeycards & (std::uint64_t{1} << (keycard & 0x1f))) != 0); + } + if (ordinal == 0x18 && argumentBytes == 4) return remorse::u16{0}; + if (ordinal == 0x15 && argumentBytes == 6) return remorse::u16{0}; + const auto source = itemNumber(); + if (!source) return std::nullopt; + const auto* item = switchWorld.findItem(*source); + if (ordinal == 0xea && argumentBytes == 4 && item) { + return static_cast(item->data.quality & 0xff); + } + if (ordinal == 0x01 && argumentBytes == 4 && item) { + return static_cast(item->data.frame); + } + if (ordinal == 0x59 && argumentBytes == 6 && arguments[4] == 4 && item) { + return switchWorld.setItemFrame(*source, arguments[4]) + ? std::optional{remorse::u16{0}} : std::nullopt; + } + return std::nullopt; + }; + bool switchFrameChanged = false; + for (unsigned instruction = 0; instruction < 100 && !switchFrameChanged; ++instruction) { + const auto result = switchTask->step(switchServices); + const auto* item = switchWorld.findItem(switchItem.itemNumber); + switchFrameChanged = item && item->data.frame == 4; + assert(result == remorse::UsecodeStepResult::Advanced || + result == remorse::UsecodeStepResult::SetInfo); + } + assert(switchFrameChanged && switchTask->programCounter < switchUse->bytes.size() && + switchTask->sourceItem == switchItem.itemNumber); + const auto boxClass = remorse::loadUsecodeClass(*usecode, 0x0081); + const auto boxUse = boxClass ? remorse::readUsecodeEventBody(*boxClass, 1) : std::nullopt; + assert(boxClass && boxClass->name == "BOX_NS" && boxUse && boxItem); + const std::array boxPrefix{ + 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 freeClass = remorse::loadUsecodeClass(*usecode, 0x0a0c); + const auto freeTimerBody = freeClass ? remorse::readUsecodeEventBody(*freeClass, 0x32) : std::nullopt; + auto boxRenderer = remorse::loadMapSceneRenderer(*root, 1); + assert(freeClass && freeTimerBody && boxRenderer); + remorse::MapRenderOptions boxRenderOptions; + boxRenderOptions.mapIndex = 1; + boxRenderOptions.maxWidth = 320; + boxRenderOptions.maxHeight = 200; + boxRenderOptions.viewCenter = remorse::WorldPoint{ + boxItem->data.x * 2, boxItem->data.y * 2, boxItem->data.z}; + const auto boxBefore = boxRenderer->render(boxRenderOptions, &boxWorld); + assert(boxBefore); + remorse::UsecodeOpcodeServices boxServices; + boxServices.readFarWord = [&boxTask](remorse::u16 offset, remorse::u16 segment) + -> std::optional { + return boxTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + boxServices.setInfo = [](remorse::u16, remorse::u16) { return true; }; + boxServices.processCount = []() { return remorse::u16{2}; }; + boxServices.currentProcessId = []() { return remorse::u16{0x0340}; }; + boxServices.callIntrinsic = [&boxTask, &boxWorld](remorse::u16 ordinal, + remorse::u8 argumentBytes, const remorse::u8* arguments) -> std::optional { + if ((ordinal == 0x15 || ordinal == 0x3a) && argumentBytes == 6) return remorse::u16{0}; + if (argumentBytes < 4) return std::nullopt; + const remorse::u16 offset = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + const remorse::u16 segment = static_cast(arguments[2] | + (static_cast(arguments[3]) << 8)); + const auto itemNumber = boxTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); + if (!itemNumber) return std::nullopt; + const auto* item = boxWorld.findItem(*itemNumber); + if (ordinal == 0x01 && argumentBytes == 4 && item) return item->data.frame; + if (ordinal == 0x02 && argumentBytes == 6 && item) { + const remorse::u8 frame = static_cast(arguments[4] | + (static_cast(arguments[5]) << 8)); + return boxWorld.setItemFrame(*itemNumber, frame) + ? std::optional{remorse::u16{0}} : std::nullopt; + } + if (ordinal == 0x03 && argumentBytes == 4 && item) return item->data.mapNumber; + return std::nullopt; + }; + remorse::u16 nextTimerProcessId = 0x0350; + remorse::u32 timerTick = 100; + remorse::u16 lastTimerDelay = 0; + std::optional timerTask; + boxServices.spawn = [&nextTimerProcessId, &timerTick, &lastTimerDelay, &timerTask, + &freeTimerBody](remorse::u16 classId, + remorse::u16 eventSlot, remorse::u8 extraArgumentBytes, remorse::u8 itemArgumentSize, + remorse::u16 itemArgument, const remorse::u8* extraArguments) -> std::optional { + if (classId != 0x0a0c || eventSlot != 0x32 || extraArgumentBytes != 2 || + itemArgumentSize != 0 || itemArgument != 0) return std::nullopt; + lastTimerDelay = static_cast(extraArguments[0] | + (static_cast(extraArguments[1]) << 8)); + std::vector timerArguments(extraArguments, extraArguments + extraArgumentBytes); + const remorse::u16 processId = nextTimerProcessId++; + timerTask = remorse::UsecodeProcessTask::create(processId, classId, eventSlot, + itemArgument, freeTimerBody->bytes, itemArgumentSize, std::move(timerArguments)); + if (!timerTask) return std::nullopt; + timerTask->timerDelayProcess = true; + timerTask->wakeTick = timerTick + lastTimerDelay; + return processId; + }; + for (remorse::u8 expectedFrame = 0; expectedFrame < 6; ++expectedFrame) { + bool yielded = false; + for (unsigned instruction = 0; instruction < 500 && !yielded; ++instruction) { + const auto result = boxTask->step(boxServices); + if (result == remorse::UsecodeStepResult::Yielded) { + yielded = true; + break; + } + assert(result == remorse::UsecodeStepResult::Advanced || + result == remorse::UsecodeStepResult::SetInfo || + result == remorse::UsecodeStepResult::Spawned); + } + assert(yielded && lastTimerDelay == 5 && timerTask && + boxTask->interpreter.impliedProcessId == timerTask->processId); + assert(boxWorld.findItem(boxItem->itemNumber)->data.frame == expectedFrame); + assert(timerTask->frame[remorse::usecodeFrameBaseOffset + 6] == 5 && + timerTask->timerDelayProcess && timerTask->wakeTick == timerTick + 5); + timerTick = timerTask->wakeTick; + timerTask.reset(); + boxTask->interpreter.impliedProcessId = 0; + } + const auto boxAfter = boxRenderer->render(boxRenderOptions, &boxWorld); + assert(boxAfter && boxBefore->pixels.size() == boxAfter->pixels.size()); + assert(!std::equal(boxBefore->pixels.begin(), boxBefore->pixels.end(), boxAfter->pixels.begin(), + [](const auto& left, const auto& right) { + return left.red == right.red && left.green == right.green && left.blue == right.blue; + })); 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 new file mode 100644 index 0000000..bd8d993 --- /dev/null +++ b/rebuild/remorse/tests/usecode_vm_tests.cpp @@ -0,0 +1,134 @@ +#include "remorse/usecode_vm.h" + +#include +#include + +int main() +{ + auto emptyStack = remorse::UsecodeInterpreterState::initialize({}); + assert(emptyStack.has_value()); + assert(!emptyStack->popWord().has_value()); + assert(!emptyStack->popDword().has_value()); + assert(emptyStack->pushDword(0x12345678)); + const auto pushedDword = emptyStack->popDword(); + assert(pushedDword.has_value() && *pushedDword == static_cast(0x12345678)); + assert(!emptyStack->popWord().has_value()); + + const std::vector itemParameter{0x34, 0x12}; + const std::vector contextParameter{0xa1, 0xb2, 0xc3, 0xd4}; + auto factoryStack = remorse::UsecodeInterpreterState::initialize( + itemParameter, contextParameter, 2); + assert(factoryStack && factoryStack->stackTop == 194 && + factoryStack->contextParameterOffset == 190); + assert(factoryStack->valueStack[194] == 0 && factoryStack->valueStack[197] == 0 && + factoryStack->valueStack[198] == 0xa1 && factoryStack->valueStack[201] == 0xd4 && + factoryStack->valueStack[202] == 0x34 && factoryStack->valueStack[203] == 0x12); + auto noPointerStack = remorse::UsecodeInterpreterState::initialize( + itemParameter, contextParameter, 0); + assert(noPointerStack && noPointerStack->stackTop == 198 && + !noPointerStack->contextParameterOffset && + noPointerStack->valueStack[198] == 0xa1 && noPointerStack->valueStack[201] == 0xd4); + assert(!remorse::UsecodeInterpreterState::initialize( + itemParameter, std::vector(0xcb), 2)); + auto stackLimitState = remorse::UsecodeInterpreterState::initialize( + {}, std::vector(remorse::usecodeInterpreterStackLimit - 4), 2); + assert(stackLimitState && stackLimitState->stackTop == 5 && + stackLimitState->contextParameterOffset == 1); + assert(!remorse::UsecodeInterpreterState::initialize( + {}, std::vector(remorse::usecodeInterpreterStackLimit - 3), 2)); + + auto frameState = remorse::UsecodeInterpreterState::initialize({}); + assert(frameState.has_value()); + for (int frameIndex = 0; frameIndex < 31; ++frameIndex) { + assert(frameState->pushCodeAddress(static_cast(frameIndex), 0x1418)); + } + assert(!frameState->pushCodeAddress(31, 0x1418)); + + std::array processContext{}; + processContext[0x123] = 0xa5; + const remorse::UsecodeContextFactoryFields factoryFields{ + remorse::FarPtr16{0x5678, 0x1234}, 0x0102, 0x0361, 0x000a, 190}; + assert(remorse::writeUsecodeContextFactoryFields(processContext.data(), processContext.size(), + factoryFields)); + assert(processContext[remorse::usecodeContextSlotIndexOffset] == 0x61 && + processContext[remorse::usecodeContextSlotIndexOffset + 1] == 0x03); + assert(processContext[remorse::usecodeContextValueAddOffset] == 0x0a && + processContext[remorse::usecodeContextValueAddOffset + 1] == 0x00); + assert(processContext[remorse::usecodeContextOwnerSourceOffset] == 0x78 && + processContext[remorse::usecodeContextOwnerSourceOffset + 1] == 0x56 && + processContext[remorse::usecodeContextOwnerSourceOffset + 2] == 0x34 && + processContext[remorse::usecodeContextOwnerSourceOffset + 3] == 0x12); + assert(processContext[remorse::usecodeContextParameterOffset] == 190 && + processContext[remorse::usecodeContextParameterOffset + 1] == 0 && + processContext[remorse::usecodeContextModeFlagsOffset] == 0x02 && + processContext[remorse::usecodeContextActiveFlagOffset] == 0 && + processContext[0x123] == 0xa5); + assert(!remorse::writeUsecodeContextFactoryFields(processContext.data(), + processContext.size() - 1, factoryFields)); + + std::vector code(remorse::usecodeEventBytecodeOffset, 0); + code.insert(code.end(), { + 0x0a, 0x07, + 0x0f, 0x02, 0x34, 0x12, + 0x5e, + 0x77, + 0x50 + }); + auto factoryTask = remorse::UsecodeProcessTask::create(4, 0x361, 0x0a, 0x1234, + std::vector(15, 0), 2, {}, contextParameter); + assert(factoryTask && factoryTask->interpreter.contextParameterOffset == 190 && + factoryTask->interpreter.valueStack[198] == 0xa1 && + factoryTask->interpreter.valueStack[202] == 0x34); + assert(factoryTask->readMappedItemWord(remorse::FarPtr16{0x0100, 0}) == 0x1234 && + !factoryTask->readMappedItemWord(remorse::FarPtr16{0x0100, 1}) && + !factoryTask->readMappedItemWord(remorse::FarPtr16{0x0101, 0})); + auto noItemTask = remorse::UsecodeProcessTask::create(5, 0x361, 0x0a, 0x1234, + std::vector(15, 0), 0); + assert(noItemTask && noItemTask->interpreter.stackTop == 0xcc && + !noItemTask->interpreter.contextParameterOffset); + auto task = remorse::UsecodeProcessTask::create(3, 0x361, 0x0a, 0x1234, + std::move(code)); + assert(task.has_value()); + assert(task->programCounter == remorse::usecodeEventBytecodeOffset); + const auto seededItem = task->interpreter.popWord(); + assert(seededItem.has_value() && *seededItem == static_cast(0x1234)); + assert(!task->interpreter.popWord().has_value()); + assert(task->interpreter.pushWord(0x1234)); + + remorse::UsecodeOpcodeServices services; + services.callIntrinsic = [](remorse::u16 ordinal, remorse::u8 argumentBytes, + const remorse::u8* arguments) -> std::optional { + assert(ordinal == 0x1234); + assert(argumentBytes == 2); + assert(arguments[0] == 7 && arguments[1] == 0); + return static_cast(0x5678); + }; + services.setInfo = [](remorse::u16 eventType, remorse::u16 sourceItem) { + return eventType == 7 && sourceItem == 0x5678; + }; + + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->interpreter.temporaryWord == 0x5678); + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->step(services) == remorse::UsecodeStepResult::SetInfo); + const std::array expectedSetInfoOperands{0x5678, 7}; + assert(task->interpreter.lastSetInfoOperands == expectedSetInfoOperands); + assert(task->step(services) == remorse::UsecodeStepResult::Returned); + assert(task->halted); + const auto returnProgramCounter = task->programCounter; + assert(task->step(services) == remorse::UsecodeStepResult::Returned); + assert(task->programCounter == returnProgramCounter); + + remorse::UsecodeTaskRegistry registry; + assert(registry.add(std::move(*task))); + assert(registry.find(3) != nullptr); + assert(!registry.add(remorse::UsecodeProcessTask{})); + auto duplicateTask = remorse::UsecodeProcessTask::create(3, 0x361, 0x0a, 0x1234, + std::vector(15, 0)); + assert(duplicateTask.has_value()); + assert(!registry.add(std::move(*duplicateTask))); + assert(registry.remove(3)); + assert(registry.find(3) == nullptr); + return 0; +} \ No newline at end of file