diff --git a/.github/agents/ghidra-coverage-batch-director.agent.md b/.github/agents/ghidra-coverage-batch-director.agent.md index 5c8d959..55535e1 100644 --- a/.github/agents/ghidra-coverage-batch-director.agent.md +++ b/.github/agents/ghidra-coverage-batch-director.agent.md @@ -1,12 +1,14 @@ --- -description: 'User-facing GPT-5.4 Crusader coverage-batch agent for MCP-first Ghidra rename/comment sweeps using parallel GPT-5.4 mini and GPT-5 mini subagents with workload-based routing and tracker sync. Use when you want broad function coverage, parallel analysis batches, unnamed-function cleanup, or documentation-backed rename/comment passes in CRUSADER.EXE.' +description: 'User-facing GPT-6 Luna Crusader coverage-batch agent for MCP-first Ghidra rename/comment sweeps using parallel GPT-5.6 Luna subagents with workload-based routing and tracker sync. Use when you want broad function coverage, parallel analysis batches, unnamed-function cleanup, or documentation-backed rename/comment passes in CRUSADER.EXE.' name: 'Ghidra Coverage Batch Director' -model: 'GPT-5.4' +model: 'GPT-6 Luna' target: 'vscode' --- # Ghidra Coverage Batch Director +**Reasoning effort:** Extra High. + You are the user-facing Crusader coverage-batch agent for broad, evidence-backed Ghidra progress. ## Required Context @@ -19,7 +21,7 @@ Use them to anchor target selection, naming rigor, and documentation behavior. ## Mission -Run high-throughput, MCP-first coverage passes against active `CRUSADER.EXE` by coordinating parallel GPT-5.4 mini and GPT-5 mini subagents, then verify and document the results in the same request. +Run high-throughput, MCP-first coverage passes against active `CRUSADER.EXE` by coordinating parallel GPT-5.6 Luna subagents at Extra High reasoning effort, then verify and document the results in the same request. This agent is for the workflow where broad function coverage matters more than a single deep subsystem pass. @@ -68,8 +70,8 @@ For broad coverage sweeps, prefer `6` parallel bundles as the normal starting sh Use two execution lanes: -- `Ghidra Coverage Mini` on `GPT-5.4 mini` for normal coverage bundles -- `Ghidra Decomp Mini` on `GPT-5 mini` only for genuinely smaller workloads +- `Ghidra Coverage Mini` on `GPT-5.6 Luna` at Extra High reasoning effort for normal coverage bundles +- `Ghidra Decomp Mini` on `GPT-5.6 Luna` at Extra High reasoning effort only for genuinely smaller workloads Default to `Ghidra Coverage Mini` unless the workload is clearly below the normal coverage threshold. @@ -87,9 +89,9 @@ Do not ask mini agents to update repository-wide tracker files. Subagents should Use this routing rule: -- about `4` target functions per subagent is calibrated for `GPT-5.4 mini` -- only smaller bundles, usually `1` to `3` lightweight functions or pure bookkeeping/evidence-collation tasks, should go to `GPT-5 mini` -- if a bundle is ambiguous but still medium-grain, reduce its size before dropping it to `GPT-5 mini` +- about `4` target functions per subagent is calibrated for `GPT-5.6 Luna` at Extra High reasoning effort +- only smaller bundles, usually `1` to `3` lightweight functions or pure bookkeeping/evidence-collation tasks, should go to `GPT-5.6 Luna` +- if a bundle is ambiguous but still medium-grain, reduce its size before routing it to `GPT-5.6 Luna` If one bundle is clearly much harder than the others, reduce that bundle size rather than letting one subagent stall the batch. @@ -147,12 +149,12 @@ Before closing the batch: ## Adaptive Behavior -Use `4` functions per subagent as the default planning center for `GPT-5.4 mini`, not as a hard rule. +Use `4` functions per subagent as the default planning center for `GPT-5.6 Luna`, not as a hard rule. Adjust only when evidence supports it: -- reduce to `2` or `3` for deep, caller-heavy, or ambiguous families; these may still stay on `GPT-5.4 mini` -- route only genuinely smaller workloads to `GPT-5 mini` +- reduce to `2` or `3` for deep, caller-heavy, or ambiguous families; these may still stay on `GPT-5.6 Luna` +- route only genuinely smaller workloads to `GPT-5.6 Luna` - increase to `5` or `6` only for thin wrappers, list helpers, or repetitive search helpers when the current run justifies it Also adapt bundle count: diff --git a/.github/agents/ghidra-coverage-mini.agent.md b/.github/agents/ghidra-coverage-mini.agent.md index e888fff..ea0d360 100644 --- a/.github/agents/ghidra-coverage-mini.agent.md +++ b/.github/agents/ghidra-coverage-mini.agent.md @@ -1,14 +1,16 @@ --- -description: 'Internal GPT-5.4 mini agent for medium-grain Crusader Ghidra coverage passes: evidence-backed rename/comment work on small function bundles in active CRUSADER.EXE.' +description: 'Internal GPT-5.6 Luna agent for medium-grain Crusader Ghidra coverage passes: evidence-backed rename/comment work on small function bundles in active CRUSADER.EXE.' name: 'Ghidra Coverage Mini' -model: 'GPT-5.4 mini' +model: 'GPT-5.6 Luna' target: 'vscode' user-invocable: false --- # Ghidra Coverage Mini -You are the internal GPT-5.4 mini execution agent for Crusader Ghidra coverage batches. +**Reasoning effort:** Extra High. + +You are the internal GPT-5.6 Luna execution agent for Crusader Ghidra coverage batches. ## Required Reads diff --git a/.github/agents/ghidra-decomp-chain-runner.agent.md b/.github/agents/ghidra-decomp-chain-runner.agent.md index 92bf407..f6f9956 100644 --- a/.github/agents/ghidra-decomp-chain-runner.agent.md +++ b/.github/agents/ghidra-decomp-chain-runner.agent.md @@ -1,13 +1,15 @@ --- -description: 'Internal GPT-5.4 chain-runner that orchestrates repeated Crusader decompilation passes in one request' +description: 'Internal GPT-6 Luna chain-runner that orchestrates repeated Crusader decompilation passes in one request' name: 'Ghidra Decomp Chain Runner' -model: 'GPT-5.4' +model: 'GPT-6 Luna' target: 'vscode' user-invocable: false --- # Ghidra Decomp Chain Runner +**Reasoning effort:** Extra High. + You are the internal chain-running subagent for Crusader decompilation work. ## Required Reads @@ -27,9 +29,9 @@ Do not stop after a single pass unless the request is solved, the work becomes b ## Routing Model -- Use `Ghidra Decomp Mini` on `GPT-5 mini` for low-complexity prep, bookkeeping, evidence collation, small tracker updates, and progress-estimate support work. -- Use `Ghidra Decomp Pass` on `GPT-5.3-Codex` for each mid-complexity pass in the chain. -- Keep high-complexity arbitration, continuation selection, ambiguity resolution, and final batch synthesis inside this `GPT-5.4` chain-runner. +- Use `Ghidra Decomp Mini` on `GPT-5.6 Luna` at Extra High reasoning effort for low-complexity prep, bookkeeping, evidence collation, small tracker updates, and progress-estimate support work. +- Use `Ghidra Decomp Pass` on `GPT-6 Luna` at Extra High reasoning effort for each mid-complexity pass in the chain. +- Keep high-complexity arbitration, continuation selection, ambiguity resolution, and final batch synthesis inside this `GPT-6 Luna` chain-runner at Extra High reasoning effort. ## Pass Count diff --git a/.github/agents/ghidra-decomp-director.agent.md b/.github/agents/ghidra-decomp-director.agent.md index f790937..a16456a 100644 --- a/.github/agents/ghidra-decomp-director.agent.md +++ b/.github/agents/ghidra-decomp-director.agent.md @@ -1,12 +1,14 @@ --- -description: 'User-facing GPT-5.4 Crusader decompilation director that launches one internal chain-running subagent' +description: 'User-facing GPT-6 Luna Crusader decompilation director that launches one internal chain-running subagent' name: 'Ghidra Decomp Director' -model: 'GPT-5.4' +model: 'GPT-6 Luna' target: 'vscode' --- # Ghidra Decomp Director +**Reasoning effort:** Extra High. + You are the single user-facing Crusader decompilation agent. ## Required Context @@ -24,11 +26,11 @@ Take the user's decompilation request, then immediately invoke one internal chai Do not rely on manual handoff buttons or require the user to start another custom agent file. The internal chain-runner must continue automatically through its own subagent sequence until the request is satisfied or a real blocker is reached. -Use this routing model: +Use this routing model at Extra High reasoning effort: -- `GPT-5 mini` for low-complexity prep, bookkeeping, evidence collation, and lightweight tracker work. -- `GPT-5.3-Codex` for mid-complexity decompilation execution passes. -- `GPT-5.4` for high-complexity task selection, ambiguity resolution, cross-pass arbitration, and final synthesis. +- `GPT-5.6 Luna` for low-complexity prep, bookkeeping, evidence collation, and lightweight tracker work. +- `GPT-6 Luna` for mid-complexity decompilation execution passes. +- `GPT-6 Luna` for high-complexity task selection, ambiguity resolution, cross-pass arbitration, and final synthesis. ## Workflow diff --git a/.github/agents/ghidra-decomp-mini.agent.md b/.github/agents/ghidra-decomp-mini.agent.md index b64fa46..98a657e 100644 --- a/.github/agents/ghidra-decomp-mini.agent.md +++ b/.github/agents/ghidra-decomp-mini.agent.md @@ -1,13 +1,15 @@ --- -description: 'GPT-5 mini agent for low-complexity Crusader decompilation prep, bookkeeping, and evidence collation' +description: 'GPT-5.6 Luna agent for low-complexity Crusader decompilation prep, bookkeeping, and evidence collation' name: 'Ghidra Decomp Mini' -model: 'GPT-5 mini' +model: 'GPT-5.6 Luna' target: 'vscode' user-invocable: false --- # Ghidra Decomp Mini +**Reasoning effort:** Extra High. + You handle low-complexity tasks in the Crusader decompilation workflow. ## Required Reads @@ -19,7 +21,7 @@ Read these before acting when the task depends on project state: ## Mission -Handle small, well-bounded tasks that do not need codex-style execution depth or GPT-5.4 batch arbitration. +Handle small, well-bounded tasks that do not need GPT-6 Luna execution depth or high-complexity batch arbitration. ## Good Fit Tasks diff --git a/.github/agents/ghidra-decomp-pass.agent.md b/.github/agents/ghidra-decomp-pass.agent.md index 6a8f030..7b2cbd7 100644 --- a/.github/agents/ghidra-decomp-pass.agent.md +++ b/.github/agents/ghidra-decomp-pass.agent.md @@ -1,13 +1,15 @@ --- -description: 'Reusable GPT-5.3-Codex mid-complexity pass agent for Crusader decompilation chains' +description: 'Reusable GPT-6 Luna mid-complexity pass agent for Crusader decompilation chains' name: 'Ghidra Decomp Pass' -model: 'GPT-5.3-Codex' +model: 'GPT-6 Luna' target: 'vscode' user-invocable: false --- # Ghidra Decomp Pass +**Reasoning effort:** Extra High. + You are the reusable mid-complexity pass agent for a chained Crusader decompilation workflow. ## Required Reads @@ -38,7 +40,7 @@ This agent is reusable across pass number `N`. Treat the provided iteration numb If more work remains, do not stop at a vague future-work list. Return a numbered continuation section with 1 to 3 concrete next tasks. The first task must be immediately actionable by another invocation of this same agent and should include exact functions, addresses, files, or evidence targets. -This agent is intended for repeated internal invocation by `Ghidra Decomp Chain Runner`, not for manual user step-through. +This agent is intended for repeated internal invocation by `Ghidra Decomp Chain Runner` at Extra High reasoning effort, not for manual user step-through. ## Return Format diff --git a/Crusader.rep/idata/00/~0000000a.db/change.data.gbf b/Crusader.rep/idata/00/~0000000a.db/change.data.gbf new file mode 100644 index 0000000..5552a4d Binary files /dev/null and b/Crusader.rep/idata/00/~0000000a.db/change.data.gbf differ diff --git a/Crusader.rep/idata/00/~0000000a.db/change.map.gbf b/Crusader.rep/idata/00/~0000000a.db/change.map.gbf new file mode 100644 index 0000000..3d7b0c4 Binary files /dev/null and b/Crusader.rep/idata/00/~0000000a.db/change.map.gbf differ diff --git a/Crusader.rep/idata/00/~0000000a.db/db.14.gbf b/Crusader.rep/idata/00/~0000000a.db/db.17.gbf similarity index 98% rename from Crusader.rep/idata/00/~0000000a.db/db.14.gbf rename to Crusader.rep/idata/00/~0000000a.db/db.17.gbf index cdd28f7..4e93427 100644 Binary files a/Crusader.rep/idata/00/~0000000a.db/db.14.gbf and b/Crusader.rep/idata/00/~0000000a.db/db.17.gbf differ diff --git a/Crusader.rep/idata/00/~0000000a.db/db.13.gbf b/Crusader.rep/idata/00/~0000000a.db/db.18.gbf similarity index 98% rename from Crusader.rep/idata/00/~0000000a.db/db.13.gbf rename to Crusader.rep/idata/00/~0000000a.db/db.18.gbf index 764fc01..608654d 100644 Binary files a/Crusader.rep/idata/00/~0000000a.db/db.13.gbf and b/Crusader.rep/idata/00/~0000000a.db/db.18.gbf differ diff --git a/Crusader.rep/projectState b/Crusader.rep/projectState index d2e135c..c47ab92 100644 --- a/Crusader.rep/projectState +++ b/Crusader.rep/projectState @@ -3,6 +3,7 @@ + @@ -11,107 +12,107 @@ - + - - - + + + - + - + - + - + - + - + - - - - - - - - + + + + + + + + - + - + - - + + - + - + - + - + - + - + - + - + - + - + @@ -121,27 +122,27 @@ - + - + - + - + - + @@ -149,86 +150,1646 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - - - - - + + + + + + - + - - - - - - + - + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + + - + - - - - - - - - + - - - - - + + + + + + + + + + + + + + + + + + + + + + + + - + - + - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -239,7 +1800,7 @@ - + @@ -248,47 +1809,45 @@ - + - - - - + + + + - - - + + - + - + - + - + - - - - + + + + - - - + + - + @@ -304,23 +1863,22 @@ - + - - + + - - - - - + + + + + - - - + + - + diff --git a/Crusader.rep/user/00/~00000008.db/db.68.gbf b/Crusader.rep/user/00/~00000008.db/db.70.gbf similarity index 99% rename from Crusader.rep/user/00/~00000008.db/db.68.gbf rename to Crusader.rep/user/00/~00000008.db/db.70.gbf index 2185550..a50efca 100644 Binary files a/Crusader.rep/user/00/~00000008.db/db.68.gbf and b/Crusader.rep/user/00/~00000008.db/db.70.gbf differ diff --git a/Crusader.rep/user/00/~0000000a.db/db.11.gbf b/Crusader.rep/user/00/~0000000a.db/db.13.gbf similarity index 99% rename from Crusader.rep/user/00/~0000000a.db/db.11.gbf rename to Crusader.rep/user/00/~0000000a.db/db.13.gbf index 7c07eff..219c109 100644 Binary files a/Crusader.rep/user/00/~0000000a.db/db.11.gbf and b/Crusader.rep/user/00/~0000000a.db/db.13.gbf differ diff --git a/docs/regret-hidden-debugger-investigation.md b/docs/regret-hidden-debugger-investigation.md index 6c6e757..9d00551 100644 --- a/docs/regret-hidden-debugger-investigation.md +++ b/docs/regret-hidden-debugger-investigation.md @@ -14,6 +14,53 @@ Current best read: No Regret still contains the hidden usecode debugger as a rea This is the most important cross-build finding so far for the retail unlock problem. In retail `CRUSADER.EXE`, the current blocker is that fresh live recovery still finds reads but no recovered writer for `1478:659c/659e`, and the retail break-state object still points at inert vtable slots. In `REGRET.EXE`, the analogous global at `1480:712c/712e` has both many debugger-side reads and one direct write from a compact constructor/store stub at `1398:0000`, and that same bootstrap rewires the freshly created object away from the inert base vtable and onto a live frontend vtable whose slot `0` is `usecode_debugger_open_for_current_unit`. +## Latest Ghidra Coverage Sweep (2026-10-07) + +The earlier conclusion that the two current-entry push helpers had no callers was an analysis-boundary artifact and is superseded by this pass. The interpreter hook at `13f0:038b` dispatches bytecode through an indirect near jump at `13f0:0457`, indexed by a 122-word table at `13f0:3d9f` for opcodes `0x00..0x79`. Ghidra originally had the hook's min/max span but only two disjoint body ranges; most switch-case instructions were not in its listing or function body, so caller recovery missed their calls. + +The table was decoded and all 122 entries mapped to 106 distinct handler targets. Those targets now contribute 4,624 decoded instructions in 22 non-overlapping address ranges attached to the hook function. The whole-hook decompiler request still exceeds the MCP read timeout, so the case bodies were analyzed from disassembly and call/reference data. This was an analysis-only Ghidra change; program bytes were not patched. + +The recovered debugger lifecycle is: + +- Opcode `0x5b` reads the line word and calls `usecode_debugger_break_state_update_line_and_maybe_break` at `13f0:04b5`. +- Opcode `0x5c` calls `usecode_debugger_break_state_push_current_entry` at `13f0:051d`, assembling the record from live unit/source/frame context. +- Opcode `0x57` snapshots and pops the parent record at `13f0:2a56`, creates the child process context, then pushes a copy at `13f0:2ab9` when debugger state is active. +- Opcode `0x50` pops a current-entry record on return at `13f0:3378`; the hook also has its guarded final unwind at `13f0:3d78`. + +Thus Regret does have a statically connected producer and the intended interpreter push/pop lifecycle. The `.unk` file is still only the displayed source; the bytecode handlers and live VM context supply the line and frame record. Runtime balance and payload values still need validation. The bootstrap's ordinary activation path and the exact trigger for opening the UI in an unmodified play session also remain unknown. A few virtual UI callbacks and indirect VM targets are incompletely characterized. + +### Debugger UI Vtable Sweep (2026-10-07) + +A second UI pass recovered the callback registration that direct-call searches missed. The Ghidra vtable helper treated the data as two-byte pointers, but the raw bytes and constructors show tables of 18 four-byte far pointers, stored as little-endian code offset followed by code segment. The three UI roots are contiguous at `1480:689a`, `1480:68e2`, and `1480:692a`, each separated by `0x48` bytes. The `1398:193f` entry at source-pane slot `+0x08` matches the already recovered source-pane click handler, validating this decode. + +| UI table | Root | Recovered debugger overrides | +| --- | --- | --- | +| Main debugger gump | `1480:689a` | `+0x00` `usecode_debugger_gump_destroy`; `+0x10` `ui_gump_reposition_after_parent_move`; `+0x14` `usecode_debugger_forward_child_event`; `+0x18` `usecode_debugger_translate_registered_event`; `+0x30` `usecode_debugger_gump_forward_base_event_if_clean`; `+0x34` shared UI dispatcher at `1360:0cb2`. | +| Auxiliary child control | `1480:68e2` | `+0x00` `usecode_debugger_aux_control_destroy`; `+0x08` source-line click handler `usecode_debugger_source_pane_handle_click`; `+0x10` shared parent-move handler; `+0x30` `usecode_debugger_aux_control_draw_line_rows`; `+0x34` shared UI dispatcher. Click, selected-row, and draw behavior identify it as a source-line selection/rendering control; exact screen layout remains uncertain. | +| Source pane | `1480:692a` | `+0x00` `usecode_debugger_source_pane_destroy`; `+0x04` `usecode_debugger_source_pane_forward_event_to_pointer_handler`; `+0x08` `usecode_debugger_source_pane_handle_event_type_2`; `+0x10` pointer handler `usecode_debugger_source_pane_handle_pointer_event`; `+0x14` `usecode_debugger_source_pane_on_layout_change`; `+0x18` command handler `usecode_debugger_source_pane_handle_command`; `+0x30` visible-line draw `usecode_debugger_source_pane_draw_visible_lines`; `+0x34` shared UI dispatcher. | + +The tables also share their framework defaults: slot `+0x0c` is `1008:3db1`; slots `+0x1c`, `+0x20`, `+0x24`, `+0x28`, and `+0x2c` are `1008:3db6`, `3dbb`, `3dc0`, `3dc5`, and `3dca` respectively (the last returns zero). Their common tail is `+0x34` `ui_gump_dispatch_event`, `+0x38` `1008:3dd1`, `+0x3c` `1360:12ee`, `+0x40` `1008:3de6`, and `+0x44` `1008:3deb`. Thus the override lists above plus these shared slots account for all 18 entries in each UI table. + +The shared dispatcher at `1360:0cb2` translates UI event codes `1`, `2`, `4`, `8`, `0x10`, and `0x20` to vtable byte offsets `+0x04` through `+0x18`; its `0x40` lane iterates child callbacks at `+0x34`, and `0x100` dispatches at `+0x24`. This establishes why `1398:0ef9`, `1398:0e81`, and `1398:0aa1` had no direct callers: they are reached through source-pane table slots, not direct call instructions. The `0ef9` thunk forwards the pane and event to that same pane's slot `+0x10`, resolved to `1398:0f16`; it does not call a separate nested widget. The parent debugger event handler at `1398:2243` reads the auxiliary control's selected row at `+0x47` for event `0x0d` and clears the corresponding marker byte in the ten-row table at `1480:64f0 + row*0x29 + 9`, linking the child selection control to breakpoint-marker handling. + +`1398:0e81` was absent from the function database despite being a source-pane vtable target. Its raw body is now defined through the far return at `1398:0ef8`, immediately before the next function at `1398:0ef9`, and named `usecode_debugger_source_pane_handle_event_type_2`. It tests event-structure field `+0x0c`: value `1` installs the widget pointer in shared graphics-context globals, sets widget flag bits `0x09`, and invokes the pane's own virtual slot `+0x10`; value `3` clears that shared context and those flag bits. The callback target is `1398:0f16`; the user-gesture meanings of event values `1` and `3` remain unknown. + +The bootstrap override table at `1480:6972` begins with two confirmed far-pointer entries: slot `+0x00` opens the current-unit debugger and slot `+0x04` formats an expression into the shared buffer. The following bytes are not treated as further vtable entries; the neighboring UI tables were identified independently from their constructor vptr stores and complete 18-entry layouts. + +### Remaining Nearby Gaps + +The debugger-owned UI/source-buffer code, the three adjacent UI vtables, all `13e0` break-state helpers, the full table-dispatched `13f0` hook body, and the adjacent `13f8` context factory/wrapper path are now mapped to a bounded level. Remaining questions are narrower: + +- `1398:16ee` constructs the auxiliary source-line selection/rendering control. Its click, selected-row field, and line-row draw behavior are established; exact screen geometry and draw ordering remain unknown. +- The event values handled by `1398:0e81` are established, but their user-gesture meanings are not. `1398:0ef9` forwards the same pane/event to pointer handler `1398:0f16`. +- `1398:304b` and `1398:305c` have no callers or address-taken references. They wrap shared `1250:056a/06eb` setup/cleanup with key `0x95ff` and the item-cache path at `1480:1476+0x0a`; a cache/resource role is likely, but debugger ownership and runtime reachability are unproven. +- `1398:306f` is another unreferenced destructor-style thunk through shared UI cleanup `1360:046e`, absent from the three recovered debugger vtables. The class owner is unresolved. The neighboring destructor entries `1398:30a9`, `1398:30e3`, and `1398:311d` are now mapped to the main gump, auxiliary child, and source pane respectively. +- The interpreter has three indirect far calls, now classified by opcode. Opcode `0x0f` calls through runtime table `1480:96e6`, built by `usecode_interpreter_load_intrinsic_table` (`13f8:062f`) during usecode startup; target values depend on loaded records. Opcode `0x70` has static sub-operations `2..6` at `13f0:3468`, `3539`, `3610`, `3695`, and `3720`, converging on `13f0:38a3` through a runtime object's `+0x04` field. Opcode `0x73` calls through a stack-selected object's `+0x02` field at `13f0:3975`. These final targets remain runtime-dependent and none is needed to explain the direct opcode `0x5c` record producer. +- `usecode_debugger_bootstrap_init`, `usecode_debugger_open_modal`, and `usecode_debugger_open_for_current_unit` have no recovered static callers. The bootstrap also has no recovered raw far-call encoding or far-pointer copy. The ordinary usecode startup chain `13f8:0cdf -> 13f8:1499 -> 13f8:062f` installs the interpreter wrapper/hook and builds runtime tables, but no static bridge to the debugger bootstrap was found. Examined cheat/input paths likewise have no references to the debugger openers, so normal-session bootstrap and deliberate UI activation remain runtime questions. +- Segment:offset labels are program-specific. In `REGRET.EXE`, `13a0:01ee` and `13a0:0361` are item operations, not the similarly addressed debugger formatter functions documented for `CRUSADER.EXE`. + +These are bounded UI/dispatch and runtime questions, not an unlocated second debugger subsystem or a missing producer. The remaining high-value checks are dynamic: verify the bootstrap is reached, capture the opcode `0x5c` record fields, and observe breakpoint/open/resume behavior in a live session. + ## Verified Regret Findings ### 1. The broad hidden cheat/debug framework still exists @@ -38,6 +85,7 @@ These functions are now renamed live in the active `REGRET.EXE` database: - `1398:0086` = `usecode_debugger_open_for_current_unit` - `1398:020d` = `usecode_debugger_open_modal` - `1398:0291` = `usecode_debugger_format_expression_to_shared_buffer` +- `1398:045c` = `usecode_debugger_format_descriptor_expression` - `1398:088f` = `usecode_debugger_source_pane_create` - `1398:0ba7` = `usecode_debugger_source_pane_handle_command` - `1398:0f16` = `usecode_debugger_source_pane_handle_pointer_event` @@ -45,9 +93,13 @@ These functions are now renamed live in the active `REGRET.EXE` database: - `1398:1118` = `usecode_debugger_source_pane_draw_visible_lines` - `1398:1413` = `usecode_debugger_source_pane_clamp_viewport` - `1398:15ac` = `usecode_debugger_source_pane_load_file` -- `1398:1791` = `usecode_debugger_source_pane_draw` +- `1398:1791` = `usecode_debugger_aux_control_draw_line_rows` - `1398:193f` = `usecode_debugger_source_pane_handle_click` - `1398:19b1` = `usecode_debugger_gump_create` +- `1398:0ae8` = `usecode_debugger_source_pane_init_current_line` +- `1398:0b06` = `usecode_debugger_source_pane_set_line_position` +- `1398:0b52` = `usecode_debugger_source_pane_center_on_line` +- `1398:2882` = `usecode_debugger_gump_build_menus` - `1398:1c2c` = `usecode_debugger_translate_registered_event` - `1398:1dc6` = `usecode_debugger_forward_child_event` - `1398:1df3` = `usecode_debugger_handle_event` @@ -67,10 +119,15 @@ These functions are now renamed live in the active `REGRET.EXE` database: - `13e0:0474` = `usecode_debugger_break_state_vtable_slot1_return_zero` - `13f0:0000` = `interpreter_push_saved_farptr` - `13f0:003c` = `interpreter_pop_saved_farptr` +- `13f0:00b8` = `usecode_interpreter_get_intrinsic_table_entry` - `13f0:00e8` = `usecode_interpreter_context_init` +- `13f0:01c7` = `usecode_interpreter_reserve_stack_bytes` - `13f0:0244` = `usecode_interpreter_context_create` +- `13f0:034f` = `usecode_interpreter_advance_source_cursor` - `13f0:035f` = `usecode_interpreter_context_load_source_cursor_from_global_unit` - `13f0:038b` = `usecode_debugger_interpreter_hook` +- `13f8:062f` = `usecode_interpreter_load_intrinsic_table` +- `13f8:0eec` = `usecode_interpreter_create_process_context` - `13f8:10da` = `usecode_interpreter_run_context_with_debugger_hook` - `13f8:1d72` = `entity_vm_runtime_get_slot_chunk_ptr_at_offset` - `1398:2c2e` = `usecode_debugger_source_buffer_create_from_path` @@ -79,6 +136,16 @@ These functions are now renamed live in the active `REGRET.EXE` database: - `1398:2e0a` = `usecode_debugger_source_buffer_load_text` - `1398:2f4f` = `usecode_debugger_source_buffer_split_lines_in_place` - `1398:301d` = `usecode_debugger_source_buffer_get_line_ptr` +- `1398:0aa1` = `usecode_debugger_source_pane_on_layout_change` +- `1398:0e81` = `usecode_debugger_source_pane_handle_event_type_2` +- `1398:0ef9` = `usecode_debugger_source_pane_forward_event_to_pointer_handler` +- `1398:16ee` = `usecode_debugger_aux_control_create` +- `1398:1c08` = `usecode_debugger_gump_forward_base_event_if_clean` +- `1398:30a9` = `usecode_debugger_gump_destroy` +- `1398:30e3` = `usecode_debugger_aux_control_destroy` +- `1398:311d` = `usecode_debugger_source_pane_destroy` +- `1328:00d7` = `ui_gump_reposition_after_parent_move` +- `1360:0cb2` = `ui_gump_dispatch_event` Why `1398:0086` matches the current-unit wrapper: @@ -101,7 +168,8 @@ Newly closed helper roles in this pass: - `usecode_debugger_source_pane_draw_visible_lines` is the stronger local draw body for visible source rows, including current-line highlight and breakpoint marks. - `usecode_debugger_source_pane_clamp_viewport` constrains the source viewport and syncs the pane against child scrollbars. - `usecode_debugger_source_pane_load_file` is the common file-load path used both by the current-unit opener and by the file-open event lane. -- `usecode_debugger_source_pane_draw` renders the visible source pane from the loaded `.unk` buffer and overlays debugger-side markers. +- `usecode_debugger_aux_control_draw_line_rows` renders the ten-row line table, selected-row highlight, and per-row markers through the debugger frontend formatter. +- `usecode_debugger_source_pane_draw_visible_lines` renders text from the loaded `.unk` buffer and overlays debugger-side markers; it is distinct from the auxiliary line-row renderer. - `usecode_debugger_source_pane_handle_click` maps mouse position back to a visible line index. - `usecode_debugger_break_state_add_breakpoint`, `remove_breakpoint`, `find_breakpoint_or_next_index`, and `has_breakpoint` close the breakpoint-table maintenance cluster. - `usecode_debugger_break_state_push_current_entry`, `push_current_entry_copy`, and `pop_current_entry` close the current-entry stack helper cluster enough to stop treating it as anonymous storage logic. @@ -222,11 +290,16 @@ The wrapper at `13f8:10da` now makes that path clearer: That is not the shape of a manual debugger launcher. It is the shape of ordinary VM execution with an optional debugger sidecar. -The final direct-xref closure in Regret is now tighter than the earlier pass: +The initial direct-xref closure was incomplete because the hook's computed opcode targets were not part of its Ghidra function body. After decoding the table and extending the body to the recovered handler blocks: -- exhaustive `1480:712c/712e` data-use recovery now shows only the already-named bootstrap/open/format/draw/event functions plus `usecode_debugger_interpreter_hook`; no extra hidden debugger-object consumers surfaced outside that cluster -- direct address searches for the helper entry points also stayed narrow: `usecode_debugger_break_state_clear_runtime_break_flags` is only called from the hook prologue, `usecode_debugger_break_state_pop_current_entry` is only called from the hook unwind, `usecode_debugger_interpreter_hook` is only called from `usecode_interpreter_run_context_with_debugger_hook`, and `usecode_interpreter_context_create` is only called from the upstream usecode-process/context factory path at `13f8:0eec` -- that means the remaining uncertainty is no longer broad subsystem discovery; it is the exact location of the missing current-entry push inside an already-identified interpreter/runtime path +- `usecode_debugger_break_state_push_current_entry` has a caller at `13f0:051d` in opcode `0x5c`. +- `usecode_debugger_break_state_push_current_entry_copy` has a caller at `13f0:2ab9` in opcode `0x57`. +- `usecode_debugger_break_state_pop_current_entry` has callers at `13f0:2a56` (opcode `0x57` parent/child transition), `13f0:3378` (opcode `0x50` return), and `13f0:3d78` (hook final unwind). +- `usecode_debugger_break_state_update_line_and_maybe_break` has a caller at `13f0:04b5` in opcode `0x5b`. +- the hook's global references now include its line, push, child-context, return, and unwind handlers. `1480:712c/712e` still has only one recovered write, from `usecode_debugger_bootstrap_init` at `1398:0064`. +- `usecode_interpreter_create_process_context` is called by `Usecode_ItemCallEvent` and by two interpreter opcode paths at `13f0:2a8b` and `13f0:2bed`. + +The producer is therefore directly wired into the bytecode interpreter; no runtime-synthesized call is needed to explain record creation. The remaining indirect calls in the hook are ordinary intrinsic/object callback dispatches and are not the current-entry producer sites. ### 8. No Regret appears to keep an auto-open-on-break path that retail No Remorse lacks @@ -256,7 +329,7 @@ Current direct-caller state in the live database: - no normal direct callers to `usecode_debugger_open_modal` - `usecode_debugger_handle_event` is reached only through debugger callback wrappers (`usecode_debugger_translate_registered_event` and `usecode_debugger_forward_child_event`) - `usecode_debugger_interpreter_hook` is called from `usecode_interpreter_run_context_with_debugger_hook`, which looks like a real runtime/interpreter-side consumer -- no normal direct callers are yet recovered for `usecode_debugger_break_state_push_current_entry` or `usecode_debugger_break_state_push_current_entry_copy` +- the current-entry push/copy helpers are called from opcode `0x5c` and opcode `0x57` handlers inside the interpreter hook So the current best distinction is: @@ -265,39 +338,41 @@ So the current best distinction is: In other words, No Regret looks better wired than retail No Remorse, but still not yet proven to expose a deliberate user-facing launcher. -### 10. The required seeding currently looks engine-side, not like a compiled-usecode feature +### 10. The required seeding is engine-side bytecode dispatch, not a UI or `.unk` feature This pass materially tightens the `who seeds the records?` question. What the new names and caller map now support: -- `usecode_debugger_break_state_pop_current_entry` has a direct caller in `usecode_debugger_interpreter_hook` +- opcode `0x5b` updates the current line through `usecode_debugger_break_state_update_line_and_maybe_break` +- opcode `0x5c` calls `usecode_debugger_break_state_push_current_entry` with live interpreter inputs +- opcode `0x57` snapshots/pops the parent record around child-context creation, then pushes the copied record into the child debugger state +- opcode `0x50` pops a current-entry record during interpreter return +- the hook epilogue has an additional guarded pop when interpreter execution unwinds - `usecode_interpreter_run_context_with_debugger_hook` wraps an ordinary interpreter execution path, not a debugger-only path -- the hook clears runtime break flags on entry, runs the interpreter loop, and unwinds debugger current-entry depth on exit -- the current-entry push helpers still have no recovered script-visible or UI-visible callers -- the new source-buffer/file-load chain is only consumed by debugger UI and current-unit open paths, not by the interpreter-side seeding path +- the hook clears runtime break flags on entry and dispatches bytecode through a jump table; source loading remains a separate UI concern -Caller-recovery status after the wider disassembly pass: +Caller-recovery status after the complete table-driven disassembly pass: -- the direct caller of `usecode_debugger_break_state_push_current_entry` is still not surfaced as a normal xref in the current Regret database -- the strongest current structural candidate remains an unrecovered or still-overlapped interpreter-side producer analogous to retail `Interpreter_NextUsecodeOp` -- the deeper recovered Regret chain is now explicit: `Usecode_ItemCallEvent -> 13f8:0eec -> usecode_interpreter_context_create -> usecode_interpreter_context_init / interpreter_push_saved_farptr -> usecode_debugger_interpreter_hook` -- that outer factory path also explains where the debugger-side source cursor comes from: `13f8:0eec` and `usecode_interpreter_context_load_source_cursor_from_global_unit` both use `entity_vm_runtime_get_slot_chunk_ptr_at_offset` against the current live usecode root at `1480:71a1/71a3` -- the nearby `13f0` context/setup helpers seed the live interpreter object's source-stream and frame-base lanes (`+0xd6/+0xd8` and `+0xda/+0xdc`), but the visible direct call path there still reaches stack/context helpers rather than the debugger push helper itself +- the direct callers now show the exact producer/copy/pop lifecycle instead of only the hook epilogue +- the context-creation chain is explicit: `Usecode_ItemCallEvent -> usecode_interpreter_create_process_context -> usecode_interpreter_context_create`; opcode `0x57` and `0x58` also call the process-context factory +- the context factory and `usecode_interpreter_context_load_source_cursor_from_global_unit` resolve source data through `entity_vm_runtime_get_slot_chunk_ptr_at_offset` against the current live usecode root at `1480:71a1/71a3` +- the interpreter context carries source-stream and frame lanes at `+0xd6/+0xd8` and `+0xda/+0xdc`; opcode `0x5c` serializes the relevant live values into the debugger record - a seemingly promising `1458:` lane that writes fields at `+0x72/+0x74/+0x76/+0x78/+0x7a/+0x7c` turned out to be the RIFF/animation parser family, not the debugger, so it should be treated as a false structural cousin rather than as debugger seeding evidence What this now rules out with fairly high confidence: - there is no additional large unnamed Regret-side debugger subsystem still hiding outside the already recovered `1398` / `13e0` / `13f0` / `13f8` lanes - there is no second recovered writer or alternate global-owner path for the debugger object beyond `usecode_debugger_bootstrap_init` -- there is no recovered direct UI/source-buffer-side path that seeds the current-entry stack before `RUN` -- there is no ordinary standalone caller of `usecode_debugger_break_state_push_current_entry` waiting to be found by one more basic xref sweep +- current-entry seeding is not performed by the `.unk` loader or source-pane UI; it occurs in interpreter bytecode handlers +- the producer calls are in the opcode switch body, not separate standalone functions Current best read from that combination: -- current-entry seeding is part of engine-side interpreter bookkeeping around live usecode execution +- the record format, producer calls, matching spawn/return pops, and source/frame inputs all exist in the recovered interpreter path +- record creation is gated by the debugger global and relevant bytecode paths; a manually opened modal still does not manufacture a running VM context - it is not currently evidenced as a direct feature toggled by `.unk` contents -- it is not currently evidenced as a distinct compiled-usecode opcode that scripts can invoke to manufacture debugger state +- the `0x5b`/`0x5c` handlers are bytecode dispatch cases; exact toolchain behavior and how often retail scripts emit them still need runtime/corpus validation Compiled usecode still matters, but in a narrower way: @@ -305,7 +380,7 @@ Compiled usecode still matters, but in a narrower way: - it provides the runtime activity that naturally flows through the interpreter wrapper/hook path - but the actual debugger-object and current-entry stack ownership still appears to live in executable-side VM code -So the current answer to `is there an automated mechanism?` is `yes, probably`, but the mechanism currently looks like ordinary interpreter-side debug bookkeeping rather than a dedicated source-file or script-level launcher feature. +So the current answer to `does this executable statically automate current-entry seeding?` is **yes**: opcode `0x5c` pushes the record; opcode `0x57` propagates it across child-process creation; opcode `0x50` and the hook unwind pop it. The ordinary debugger activation path and live-runtime behavior still need testing. ### 11. What the seeding record actually is, and what that implies for simulation @@ -316,14 +391,14 @@ The current-entry push helpers are now explicit enough to answer the practical ` - `+0x00..+0x08` = inline unit-name string, asserted to fit in `8` bytes plus terminator - `+0x09..+0x0c` = first runtime far pointer - `+0x0d..+0x10` = second runtime far pointer -- `+0x11..+0x14` = third runtime far pointer +- `+0x11..+0x14` = third far-pointer field; the shipped opcode `0x5c` producer currently supplies `0:0` The important part is not the string. It is what the debugger later does with the payload dwords. Known current consumers: - `usecode_debugger_open_for_current_unit` uses the inline unit name to build the `.unk` path under `s_usecode` -- `usecode_debugger_format_expression_to_shared_buffer` resolves the top current-entry record and passes entry `+0x09` and `+0x0d` into `FUN_1398_045c` +- `usecode_debugger_format_expression_to_shared_buffer` resolves the top current-entry record and passes entry `+0x09` and `+0x0d` into `usecode_debugger_format_descriptor_expression` - the formatter helper then dereferences those payload dwords as live source/descriptor and frame/evaluation context, not as inert metadata That means the debugger seeding issue is **not** `how do we invent filenames or line numbers`. It is `how do we capture a valid live VM snapshot and serialize it into the break-state stack`. @@ -332,10 +407,24 @@ The recovered interpreter-side precursor path now explains where that snapshot d - `usecode_interpreter_context_create` seeds the live interpreter context with source-stream cursor at `+0xd6/+0xd8` - the same helper seeds a second live lane at `+0xda/+0xdc` that the hook immediately dereferences as a frame/stream-adjacent context root -- `+0xe1/+0xe3` is the strongest current candidate for the third current-entry dword, though that trailing entry field still lacks a live consumer in Regret +- `+0xe1/+0xe3` is initialized as another interpreter-context lane, but the audited opcode `0x5c` producer does not read it; that producer explicitly supplies `0:0` for record field `+0x11`, and no static consumer of that field was found in the audited formatter path - `usecode_interpreter_context_load_source_cursor_from_global_unit` and the upstream `13f8:0eec` factory both derive the source cursor from the current usecode root at `1480:71a1/71a3` through `entity_vm_runtime_get_slot_chunk_ptr_at_offset` -So the seeding data is already present in ordinary in-process runtime state. The missing piece is the serializer/call site that pushes it into the debugger break-state object. +The first two record pointers are derived from live interpreter state: the first is the current source-stream segment with its cursor offset advanced by the line operand; the second is the interpreter segment with the context offset plus `context[+0xd4] + 4`. Opcode `0x5c` passes those pointers to the shipped record-writing helper and explicitly passes `0:0` for the third field. No external serializer or new producer call is required for the recovered interpreter path. The intended meaning of the unused third field, any alternate runtime writer, and the ordinary debugger bootstrap/launch path remain unresolved. + +#### Recovered producer check and simulation answer + +The current Ghidra evidence on `REGRET.EXE` is: + +- The opcode switch at `13f0:0457` has 122 table entries and 106 distinct decoded destinations. +- The `0x5c` destination calls `13e0:02f5`; the `0x57` destination calls `13e0:03b0` after saving the parent record. +- The matching pop calls are at `13f0:2a56`, `13f0:3378`, and `13f0:3d78`. +- Opcode `0x5b` updates the break-state line at `13f0:04b5`. +- The debugger global at `1480:712c/712e` still has one recovered write at bootstrap `1398:0064`; the interpreter handlers read it to gate these operations. + +Therefore, the executable contains and statically connects the debugger record format, producer, child-context propagation, line update, and return/unwind behavior. The first two pointer fields are computed from transient VM state, not recovered from `.unk`; the shipped opcode `0x5c` producer writes zero to the third field. What remains unproven is runtime behavior: the actual first-two pointer values at execution, whether another path writes the third field, whether the active build's ordinary bootstrap initializes the global in a normal session, and whether the debugger reaches the expected pause/open flow without a patch. + +The rebuild can simulate the record without reproducing 16-bit segmented addresses literally. `UsecodeProcessTask` already carries class/event identity, bytecode and program counter, a value stack, routine/call frames, and a process frame; the context factory also models source/owner pointers in emulated runtime memory. A debugger layer can derive a structured current-entry stack from those values and balance it on nested calls/returns. That is enough to model line/callstack/breakpoint state. It is **not** yet enough to claim full original debugger parity: `UsecodeInterpreterState::step()` implements only a subset of opcodes, and watch/inspect formatting still needs descriptor evaluation and intrinsic/runtime coverage. ### 12. Existing data versus live memory: what has to be true for the debugger to work @@ -381,13 +470,13 @@ What an external helper **would** have to do if it existed: That is possible in principle for a development-only DOS memory poking tool, but it would still be a **live memory injector**, not an external source-file preprocessor. -The stronger current explanation is simpler: +The table-driven handler recovery changes the earlier explanation: - the game already has all the required data in-process - Regret still has the debugger object, hook, open path, and stack helpers -- the missing visible push is most likely inside a table-driven, overlapped, or otherwise not-cleanly-recovered interpreter path rather than in a separate external system +- opcode `0x5c` calls the record pusher and opcode `0x57` copies a saved record into a child process context -So the external-process hypothesis is not impossible, but it is not needed to explain the current evidence and currently looks less likely than an internal interpreter-side producer. +An external-process hypothesis is still unsupported and is not needed to explain record creation. An external writer could still be used for experiments, but the executable already contains a statically recovered producer path. ### 14. How we can simulate the seeding today @@ -397,18 +486,19 @@ There are three realistic simulation strategies, and they are not equally good. This is the most promising route. -The recovered Regret path already creates the live context data we need: +The recovered Regret path already creates and serializes the live context data we need: -- `Usecode_ItemCallEvent -> 13f8:0eec -> usecode_interpreter_context_create -> usecode_debugger_interpreter_hook` +- `Usecode_ItemCallEvent -> usecode_interpreter_create_process_context` +- opcode `0x5c` updates the line/entry state; opcodes `0x57` and `0x50` handle child-context and return transitions -So the smallest high-confidence simulation is to add or re-enable a push at an existing in-process point where all ingredients are already live: +For ordinary interpreter execution, the record producer is already wired. A patch is not needed to add that call. The unproven patch question is instead how the hidden debugger object is bootstrapped or deliberately opened in a normal session. For a controlled experiment, the relevant live inputs at opcode `0x5c` are: - current unit name - source-stream cursor - frame payload pointer - debugger object pointer -Conceptually, this means restoring the missing `push_current_entry` behavior near the interpreter-context creation / hook handoff instead of inventing new data. +Conceptually, a runtime experiment should break at the recovered opcode `0x5c` callsite and capture the existing record, rather than insert a duplicate producer. Why this is strongest: @@ -425,9 +515,9 @@ For a minimal one-shot debugger open, the injected state would need at least: - debugger object at `1480:712c/712e` already valid - depth `+0x7a >= 1` - inline unit-name record at `+0x7c` -- entry `+0x09` = valid live source cursor far pointer -- entry `+0x0d` = valid live frame payload far pointer -- entry `+0x11` = probably safe as zero or borrowed from the third interpreter lane unless a new consumer proves otherwise +- entry `+0x09` = source-stream segment:`source_cursor_offset + line_operand`, as assembled by opcode `0x5c` +- entry `+0x0d` = interpreter segment:`context_offset + context[+0xd4] + 4`, as assembled by opcode `0x5c` +- entry `+0x11` = `0:0` in the shipped opcode `0x5c` producer; the audited formatter does not consume it, and borrowing `+0xe1/+0xe3` is unsupported by the static producer evidence - current line `+0x72` set coherently enough for the source pane and breakpoint checks This could probably make `open_for_current_unit` and some expression/inspect flows work if the payload pointers are borrowed from a real live interpreter context. @@ -450,37 +540,31 @@ This is useful, but it does not solve the seeding problem by itself. So offline-only work is supportive, not sufficient. -### 15. What an in-process patch would actually do +### 15. What an in-process patch would still need to do -The safest current model is **not** `hex-edit the EXE until it behaves`. It is `restore one missing debugger-side serialization step at a point where the game already has all required live data`. +The producer itself should not be patched: the opcode `0x5c` path already calls it, and opcode `0x57`/`0x50` provide context transition and return pops. Any patch experiment should target only a demonstrated remaining gap, such as making the existing bootstrap reachable or exposing a deliberate debugger-open command. -The candidate in-process patch is small in *behavioral* scope even if it still has to be handled carefully at the byte level: +The candidate launcher patch should preserve the recovered interpreter lifecycle: - leave the existing debugger object/bootstrap path alone - leave the existing UI/event/gump code alone - leave the existing interpreter context creation path alone -- add or re-enable one call into `usecode_debugger_break_state_push_current_entry` or `...push_current_entry_copy` at a point where the current unit name and the three payload dwords already exist live +- route an intentional input or debug trigger to the existing open/break-state path only after confirming the bootstrap and live interpreter context are valid -In concrete terms, the best current patch window is the already-recovered handoff around: +The recovered handoff to observe (not duplicate) is: -- `Usecode_ItemCallEvent` -- `13f8:0eec` -- `usecode_interpreter_context_create` -- `usecode_debugger_interpreter_hook` +- opcode `0x5b` line update at `13f0:04b5` +- opcode `0x5c` record push at `13f0:051d` +- opcode `0x57` child-context record propagation at `13f0:2a56/2ab9` +- opcode `0x50` return pop at `13f0:3378` -That is the narrowest place where all of these are already true at once: +These sites already establish that: -- a live interpreter/process object exists -- the source-stream cursor is already computed -- the frame/evaluation payload lane already exists -- the debugger object global can already be tested +- the debugger global is checked before record operations +- live source/frame context is available to the producer +- nested process and return paths maintain debugger-entry depth -So an in-process patch would most likely mean one of these two designs: - -1. restore a missing direct push call near context creation or immediately before the debugger hook runs -2. synthesize the equivalent `0x15`-byte record in-place and then increment debugger depth exactly once per entered debugged frame - -The first design is strongly preferred because it reuses the shipped helper and keeps the later pop/unwind behavior matched. +If a patch is later needed, first capture the bootstrap and modal-open call paths; do not add another push without evidence of a missing transition, or the existing pop paths may become unbalanced. ### 16. Why this should be done in Ghidra on a writable patch target, not by blind hex editing @@ -582,7 +666,7 @@ Why watch/inspect depend on seeding: - the dispatcher routes both commands through the debugger object's formatter callback - `usecode_debugger_format_expression_to_shared_buffer` resolves the top current-entry record from the break-state stack -- it passes entry `+0x09` and `+0x0d` into `FUN_1398_045c` +- it passes entry `+0x09` and `+0x0d` into `usecode_debugger_format_descriptor_expression` - that helper dereferences those values as live descriptor/source and frame/evaluation context So watch and inspect are not a workaround for missing seeding. They are actually one of the strongest proofs that seeding must be correct. @@ -629,23 +713,24 @@ So the extra debugger commands help a lot in narrowing validation order, but the Current best path, in order of likelihood and engineering sanity: 1. Create a writable Regret patch target and keep the reference `REGRET.EXE` untouched. -2. Identify the smallest concrete callsite near `13f8:0eec -> usecode_interpreter_context_create -> usecode_debugger_interpreter_hook` where a debugger push can be added with minimal byte disruption. -3. Prefer a patch that calls the shipped `usecode_debugger_break_state_push_current_entry` helper rather than reimplementing the record layout by hand. -4. If a direct call will not fit cleanly, use a tiny detour/trampoline into spare writable code space on the patch target rather than forcing a larger inline rewrite. -5. Validate the patch first by opening the debugger and exercising file open, goto-line, search, and `change globals`. -6. Only then test `watch` and `inspect`, because they are the first strong consumers of the seeded runtime payload. -7. Only after those work, test `RUN`, then `break next`, then `single step`, because the pop-on-unwind behavior means resume features are stricter than one-shot UI success. +2. In the live session, break at the recovered opcode `0x5b` line update and opcode `0x5c` push; capture the record, all three dwords, line, and stack depth. +3. Confirm opcode `0x57` child-context copying and opcode `0x50`/hook unwind pops keep depth balanced. +4. Verify whether the bootstrap runs in an ordinary session and identify how break-next/single-step becomes armed. +5. Validate the existing path first with source open, goto-line, search, and `change globals`. +6. Then test `watch` and `inspect` against the captured runtime pointers. +7. Finally test `RUN`, `break next`, and `single step` across a complete execution/unwind cycle. What is *less* likely to be the winning path: - offline `.unk` or line-number work alone - a large multi-site executable rewrite - blind direct hex editing of the reference binary -- an external helper unless it is effectively a smart live-memory injector that reads the real interpreter context +- adding another current-entry push call; the `0x5c` producer is already present and statically called +- an external helper unless it is being used for controlled live-state capture/injection So the most likely route to working debug functionality is: -- **small in-process patch on a writable Regret copy** +- **runtime validation of the existing interpreter producer, followed only if needed by a small launcher/bootstrap patch on a writable Regret copy** - **reuse shipped helper(s) and existing VM context data** - **validate in stages, with `change globals` before `watch/inspect`, and `watch/inspect` before full resume/step** @@ -674,7 +759,7 @@ Known remaining risk in this prototype: - it assumes one current-entry push per wrapped hook invocation is the right balance for the later pop-on-unwind path - it assumes the `g_processNames` entry is the correct unit-name source in this lane -- it assumes the third current-entry dword can be borrowed from `+0xe1/+0xe3` without harming current consumers +- the 2026-10-08 static reconciliation supersedes this assumption: the shipped opcode `0x5c` producer passes `0:0`, while this prototype copies `+0xe1/+0xe3`. The prototype therefore diverges from the normal producer and is not evidence that the third field should contain that context lane; runtime effects remain untested. So this should be treated as a tightly scoped runtime experiment, not as a final debugger restoration. @@ -1429,6 +1514,8 @@ Under the user's current stability constraint, the strongest recommendation is t ## What The `.unk` File Actually Looks Like +> The consolidated `.unk` evidence, unresolved questions, and reverse-engineering plan are maintained in [usecode-unk-format.md](./usecode-unk-format.md). This section preserves the original Regret debugger investigation and experiment history; update the dedicated note when format status changes. + Now that the patched Regret build can open the hidden debugger menu, the next blocker is the file-open prompt. The immediate practical question is whether that prompt wants one of the stock `UNK*.DAT` files or some other artifact. Current best answer: the debugger does **not** appear to want `UNKDS.DAT` directly. It wants a per-unit `.unk` file under the `USECODE` root, and that file is expected to be a plain text source-style listing, not a small binary metadata blob. @@ -1716,28 +1803,21 @@ Current safest interpretation: ### 3. Who seeds the records -This answer is now partly verified and partly inferred. +The current-entry helpers have direct callers in the decoded bytecode-dispatch body: -What is directly verified: +- `usecode_debugger_bootstrap_init` seeds the **object itself** and stores it into `1480:712c/712e`. +- `13e0:02f5` pushes a new record from the opcode `0x5c` handler at `13f0:051d`. +- `13e0:03b0` copies a saved `0x15`-byte record from the opcode `0x57` handler at `13f0:2ab9`. +- `13e0:03f7` pops at `13f0:2a56` during the parent/child transition, at `13f0:3378` on opcode `0x50` return, and at `13f0:3d78` during hook unwind. +- Opcode `0x5b` calls `usecode_debugger_break_state_update_line_and_maybe_break` at `13f0:04b5`. -- `usecode_debugger_bootstrap_init` seeds the **object itself** and stores it into `1480:712c/712e` -- `13e0:02f5` seeds a **new current-entry record** from `(unit name, three runtime dwords)` -- `13e0:03b0` seeds a **new current-entry record** by copying an already-built `0x15`-byte record wholesale -- `13e0:03f7` pops one current-entry record on interpreter-side unwind -- `usecode_debugger_interpreter_hook` is the live interpreter-side consumer that owns the pop on exit +The earlier zero-caller result came from an incomplete function body: the indirect opcode table at `13f0:0457` had not been decoded, leaving the case instructions outside the hook's Ghidra body. After mapping the case blocks, Ghidra resolves the callers to `usecode_debugger_interpreter_hook`. -What is not yet fully recovered as a normal xref in the current MCP session: +What remains unproven is runtime behavior, not the static producer: whether the bootstrap runs in an ordinary session, what exact values all three dwords carry at runtime, and whether the expected break/open/resume path is reached without a patch. -- the exact direct callsite that invokes `13e0:02f5` or `13e0:03b0` +So the current answer to `who seeds the records?` is: -Current best evidence-based conclusion anyway: - -- the record seeding is almost certainly performed by interpreter-side instrumentation around real usecode entry, not by the source loader and not by the modal-open wrapper -- the push/pop pairing strongly points to a runtime-enter / runtime-leave model: enter usecode context -> push record -> run -> unwind -> pop record - -So the current best answer to `who seeds the records?` is: - -> the debugger bootstrap seeds the object, but a separate interpreter-side runtime path seeds the current-entry records. The exact static caller of `13e0:02f5` / `13e0:03b0` is still not recovered cleanly in the present database, but the runtime ownership is clearly on the interpreter side rather than on the file-loader side. +> The debugger bootstrap creates the object. During interpreter execution, opcode `0x5c` pushes the live current-entry record; opcode `0x57` carries it across child-context creation; opcode `0x50` and the hook unwind pop it. The `.unk` loader does not seed this state. ### 4. Why `open_modal` is not enough @@ -1818,16 +1898,16 @@ Current safest read: - manual synthetic seeding is plausible, but it needs **captured real runtime values** from a live interpreter context, not invented placeholders -#### Tier C: let the interpreter seed the record naturally, then open the debugger +#### Tier C: let the recovered interpreter producer seed naturally -This is now the strongest practical route. +This is now the strongest practical route. The producer is already present in opcode `0x5c`; no call needs to be added. The key remaining runtime question is whether the debugger object is bootstrapped and the expected line/context data are valid in an ordinary session. Desired sequence: 1. bootstrap the debugger object 2. arm break-next or single-step in the object 3. allow one real usecode/interpreter pass to run -4. let the interpreter-side debugger path push a genuine current-entry record +4. let opcode `0x5c` push a genuine current-entry record, then verify its fields and depth 5. open through the normal current-unit path or let the slot-`0` auto-open path fire Why this is stronger than manual record fabrication: @@ -1841,13 +1921,17 @@ Why this is stronger than manual record fabrication: If the immediate goal is `make the debugger work properly`, the best current manual recipe is no longer `generate a better .unk` by itself. The better recipe is: 1. keep the current JS exporter and synthetic Regret line floor so source load stays stable -2. capture one real current-entry record from a live interpreter-side seed point +2. either capture one real current-entry record at a verified or instrumented seed point, or wire a push where the live context is available 3. reuse those captured values either: - by manual object seeding, or - - by patching the launcher so the interpreter seeds them naturally before open + - by explicitly patching the interpreter path to call the shipped helper before open -Current candidate capture points: +Candidate capture points for a live run: +- opcode `0x5b` line update at `13f0:04b5` +- opcode `0x5c` record push at `13f0:051d` +- opcode `0x57` parent pop/copy push at `13f0:2a56` and `13f0:2ab9` +- opcode `0x50` return pop at `13f0:3378` - breakpoint on `13e0:02f5` - breakpoint on `13e0:03b0` - breakpoint on `13e0:03f7` to see the matching pop side @@ -1868,17 +1952,17 @@ That would immediately answer the remaining unknowns that static decompilation h The path to a fully working debugger session now looks like this. -### Phase 1. Finish the record-seeding recovery +### Phase 1. Validate the recovered record lifecycle at runtime Goal: -- confirm the exact interpreter-side caller that reaches `13e0:02f5` / `13e0:03b0` +- confirm the record fields and depth transitions at the recovered opcode handlers Concrete actions: -1. use runtime breakpoints on `13e0:02f5`, `13e0:03b0`, and `13e0:03f7` +1. use runtime breakpoints on `13f0:04b5`, `13f0:051d`, `13f0:2a56`, `13f0:2ab9`, and `13f0:3378` 2. trigger ordinary usecode activity while the debugger object is live -3. capture caller addresses and arguments +3. capture the current-entry record, line value, caller opcode, and depth before/after each transition 4. map the three packed dwords to concrete runtime structures Deliverable: @@ -1912,9 +1996,9 @@ Goal: Concrete actions: -1. patch a hidden input lane only far enough to bootstrap the object and arm break-next / single-step +1. first verify whether the existing bootstrap is reached in an ordinary session; patch a hidden input lane only if it is not 2. do **not** open only through `open_modal` -3. let the next real interpreter pass seed the current-entry record stack +3. let opcode `0x5c` seed the current-entry record stack during real interpreter execution 4. open through `usecode_debugger_open_for_current_unit` or the slot-`0` auto-open path Deliverable: @@ -1952,20 +2036,21 @@ Current safest answer to `what does it take for the debugger to work properly?` Current safest answer to `who seeds the records?` is: - bootstrap seeds the object -- interpreter-side runtime logic seeds the current-entry records -- the exact push caller is still not fully recovered as a named xref, but the push/pop ownership is now clearly on the interpreter side, not on the source loader side +- opcode `0x5c` calls the record pusher with live interpreter context +- opcode `0x57` copies the record across child-context creation, and opcode `0x50` plus hook unwind pop it +- the source/frame inputs are live VM values; no fixed data file is missing Current safest answer to `how can we do it manually?` is: - not by `.unk` text alone -- by either capturing and writing one real current-entry record into the break-state object, or by patching a launcher path that lets the interpreter seed that record naturally before opening the debugger +- by observing the existing `0x5c` producer in a live session and capturing the record, or by injecting a captured valid record for a one-shot experiment ## Open Questions After This Pass 1. Does retail No Remorse still contain a dormant analogue of the Regret vtable override, not just the writer/bootstrap? -2. Are there any Regret-side callsites outside the current xref model that still seed break/step state intentionally for the debugger? -3. Does any hidden Regret cheat/debug key or menu path manipulate the break-state bytes at `+0x74/+0x75/+0x76/+0x78` or otherwise force the slot-`0` auto-open path? -4. Is `usecode_debugger_bootstrap_init` a real segment-load initializer, and if so where exactly is that load boundary controlled? +2. What runtime values do the first two opcode `0x5c` pointers take, and does any alternate runtime path ever write a nonzero value to entry `+0x11`? +3. Does the normal Regret bootstrap execute in a retail session, and what input/menu/debug path arms break-next or reaches the slot-`0` auto-open? +4. Which runtime-loaded intrinsic targets and VM-object callbacks are reached at `13f0:30ab`, `38a3`, and `3975`? Their opcode roles and dynamic lookup mechanisms are now statically mapped, but the target values require runtime tracing. ## Recommended Next Step diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 7c98382..a7b5a88 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -40,7 +40,7 @@ Current blocker: the normal host window resolves egg `0x1e` from map 1 and place ### Current Blocker -Recompute `Item_Grab` candidates and eligible usecode events from item 1 at the destination pad, then prove reachability and implement one visible, original-script-backed mutation. The staging-point scan below is historical. The original startup call chain, game scheduler, and full source draw/camera behavior also remain incomplete. +The first reachable map-1 retail interaction now passes a deterministic host regression through item search, owner-row event selection, nested VM dispatch, and a rendered chest-frame mutation. Original `Item_Grab` and `Usecode_ItemCallEvent` are still not integrated into normal gameplay, and the chest's later `0x70` loot search and full script completion remain unsupported. The original startup call chain, game scheduler, and source draw/camera behavior are also incomplete. ## Current Inputs @@ -140,14 +140,19 @@ Exit criteria: deterministic tests cover camera projection/inverse bounds, zoom Goal: execute game scripts from original `EUSECODE.FLX`. +Current foundation: `UsecodeProcessTask` already tracks class/event identity, bytecode PC, process frame, value stack, and nested routine/call frames. The context factory also models owner/source pointers in emulated runtime memory. Opcode support remains partial, so this is a VM foundation rather than full execution or debugger parity. + Work: - import and type `EntityVmRuntime`, owner-resource, context, and slot-entry families - parse usecode chunks and dispatch tables - implement VM value stack, globals, calls, and event dispatch +- add an optional debugger state derived from VM tasks: unit/class/event, bytecode PC and available line metadata, source cursor, frame/evaluation context, and a balanced current-entry stack across nested calls and returns +- implement breakpoint and single-step hooks against that structured state; emulate segmented pointers only where binary parity requires them +- add descriptor/watch evaluation only as the corresponding source metadata and VM services become supported - cross-check against existing usecode extraction tools -Exit criteria: selected map triggers and object interactions execute through the host VM with traceable parity against known extracted usecode behavior. +Exit criteria: selected map triggers and object interactions execute through the host VM with traceable parity against known extracted usecode behavior. When debugger support is enabled, supported instructions produce deterministic line/call-stack snapshots and balanced entry/return transitions; unsupported opcodes and unavailable source metadata are reported rather than guessed. This does not claim full watch/inspect or original VM parity until descriptor evaluation and required runtime services are implemented. ### Phase 7: Gameplay Systems @@ -254,7 +259,7 @@ The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to ## First Interactive Windows Game Shell -`rebuild/remorse/out/build-nmake/remorse_game.exe` is the first windowed application target. It locates the game data root from its own executable path (or the current directory), defaults to map 1, and accepts either an optional fixed-map index from 0 through 255 or the original-style direct warp options. +`rebuild/remorse/out/build/Debug/remorse_game.exe` is the first windowed application target in the Debug configuration. It locates the game data root from its own executable path (or the current directory), defaults to map 1, and accepts either an optional fixed-map index from 0 through 255 or the original-style direct warp options. The default window now opens directly onto the retail-map traversal test with no diagnostic HUD, synthetic Stand/keyboard processes, or `F` release shortcut. Its map-1 host startup follows the staging egg `0x1e` through active trigger `0x63` to destination egg item 6812 at `(30328, 29656, 16)` before rendering. Pass `--diagnostics` (before or after the map number) to restore the diagnostic harness and its HUD. The map-1 startup midpoint is checked against the same collision bodies as the window, with at least one legal neighboring move. This is a **retail-data movement test**, not yet the real game: the player is host-created, rendering uses a static map preview, movement uses host polling/step policy, and neither the original startup/game loop nor item USECODE/mission interactions are running. Do not use this mode split as the roadmap's playable-game exit criterion. @@ -262,13 +267,13 @@ From the repository root: ```powershell rebuild\remorse\build_msvc.cmd Debug -.\rebuild\remorse\out\build-nmake\remorse_game.exe 1 +.\rebuild\remorse\out\build\Debug\remorse_game.exe 1 ``` For a direct coordinate warp, use `-warp [-mapoff ]`. The target map is the retail mission-table base plus the offset; the coordinates are staged world coordinates, and the normal map-1 teleporter startup is bypassed. This verified command starts on map 1 at the chest/computer test area: ```powershell -.\rebuild\remorse\out\build-nmake\remorse_game.exe -warp 0 30463 29951 0 -mapoff 1 +.\rebuild\remorse\out\build\Debug\remorse_game.exe -warp 0 30463 29951 0 -mapoff 1 ``` The window title reports the resolved map and direct coordinates. Coordinates must be X/Y `0..32767` and Z `0..255`. @@ -296,6 +301,8 @@ On Windows, `remorse_game.exe`, `remorse_rebuild.exe`, and `remorse_map_preview. This is the first interactive gameplay slice, not yet a playable game: movement uses approximate host collision rather than the original actor response, and there are no live enemies, triggers, sound, saves, or USECODE execution. The rendered map is the retail static scene, not a live simulation. +The `Controller_HandleKeyEvent` (`1130:2211`) prior-fire-sleep guard is now a dedicated compiled `remorse_core` slice: when that state is true, nonzero-mode Space events and Ins releases are suppressed, while Ins presses remain eligible. Focused tests cover the condition matrix. The Windows loop does not yet populate the state because `Crusader_TryToFireWeapon` and the original global-state update path remain unported, so this closes the gate implementation but not runtime weapon firing parity. The busy in-place-turn model also remains incomplete: `Anim_1130_0f94` (`1130:0f94`) rate-limits walk/run direction updates when `1478:6046` is set, using the system timer and mouse-speed configuration; the host does not yet model that state or throttle. + ## Import-Slice Tool The first source-conversion helper is `rebuild/remorse/tools/import_export_slice.py`. @@ -504,7 +511,7 @@ Current local toolchain finding: - `vswhere` selects the registered Visual Studio Community 2026 installation at `C:\Program Files\Microsoft Visual Studio\18\Community`; the existing `out/build` cache points at an older `I:\Apps\VS\18\Community` path that CMake cannot resolve as an installed instance. - `vcvars64.bat`, MSVC `19.51.36246.0`, and VS-bundled CMake `4.2.3` are usable through the registered Visual Studio developer environment. -- Plain `cmake` is still not available before the Visual Studio environment is initialized. `build_msvc.cmd` initializes MSVC with `vswhere`/`vcvars64.bat` and configures a separate NMake build under `out/build-nmake`. +- Plain `cmake` is still not available before the Visual Studio environment is initialized. `build_msvc.cmd` initializes MSVC with `vswhere`/`vcvars64.bat` and configures the Visual Studio build under `out/build`. ### Host Harness @@ -525,7 +532,7 @@ From the repository root, the repeatable MSVC path is: rebuild\remorse\build_msvc.cmd Debug ``` -The wrapper's NMake build writes `remorse_rebuild.exe` directly under `rebuild/remorse/out/build-nmake/`; it leaves the existing Visual Studio generator cache under `out/build/` untouched. +The wrapper reuses the Visual Studio generator tree under `rebuild/remorse/out/build/`; configuration-specific executables are written under `out/build/Debug/` or the selected configuration directory. ### Staging One Export Slice @@ -558,24 +565,24 @@ Use this sequence to move the normal Windows launch path from host-modeled behav | Path | Current normal-path implementation | Original path and status | Host boundary and recovery target | |---|---|---|---| -| Startup and spawn | [`loadSceneAsync`](../rebuild/remorse/src/windowed_game_main.cpp#L471) loads retail data, creates the host avatar/item state, then models the two teleports to map 1's level-start pad. | `Game_Start` (`1020:0000`), `Teleporter_CreateProcessDirect`, and original wait-list lifecycle are **not integrated**; spawn is host-modeled. | Keep data-root/file access and worker/window notification at the host edge. Port the startup/teleporter call chain and initialize world ownership through it. | -| Tick and scheduler | [`updatePlayer`](../rebuild/remorse/src/windowed_game_main.cpp#L1084) is driven by Win32 `WM_TIMER`/performance-counter timing and calls the host `ProcessKernel`. Selected scheduler predicates and process behavior are translated, but the original loop and general vtable dispatch are absent. | `Kernel_11d0_31cf` / scan `11d0:0255` are **partial translations, not original-loop parity**; normal simulation remains host-driven. | Inject elapsed ticks through a replaceable clock/timer adapter; move scheduling and process dispatch into the recovered core path. | -| Input | [`windowProcedure`](../rebuild/remorse/src/windowed_game_main.cpp#L1345) maps Win32 key messages and modifier state into synthesized `KeyEvent`s queued on the host kernel. The recovered keyboard filter/copy behavior is only partial and does not provide the original input pipeline. | Keyboard process/registration functions (`11b8:02e1`, `11b8:03ad`, `11e0:172a`, `11d0:3b74`) are **partially translated**; original queue, interrupt, daemon, and controller dispatch are not integrated. | Keep Win32 message handling as an input adapter; pass normalized events into platform-neutral queue and recovered handlers. | +| Startup and spawn | [`loadSceneAsync`](../rebuild/remorse/src/windowed_game_main.cpp#L471) loads retail data and calls `startFreshGameMapOne` in `remorse_core` for normal map-1 startup; direct warp and diagnostics remain separate. | A fresh-game `Game_Start` slice initializes the avatar, executes the `1/0x1e` teleporter process, and follows the verified active `0x63` level-start trigger. Full `Game_Start`, original `Process_WaitFor` list semantics, and original item/NPC cache initialization are not integrated. | Keep data-root/file access and worker/window notification at the host edge. Replace the staged item and wait-list models with source-derived cache/process state. | +| Tick and scheduler | [`updatePlayer`](../rebuild/remorse/src/windowed_game_main.cpp#L1084) receives Win32 timer/performance-counter events; movement animation advances through a bounded `remorse_core` scheduler pass. | A retail boot-and-tick regression verifies timer delivery, scheduler dispatch, and avatar animation-state advancement. The scan gate/group selector are compiled source-derived slices; `Kernel_11d0_31cf`'s infinite loop, timer interrupt delivery, original keyboard/controller dispatch, and general vtable resolver remain absent. | Keep Win32 timing/input as adapters and continue replacing host callback/process behavior with recovered core dispatch. | +| Input | [`windowProcedure`](../rebuild/remorse/src/windowed_game_main.cpp#L1345) adapts Win32 key-down/up messages into `KeyEvent`s; `remorse_core` now runs them through the source-derived subscriber queue/gates in `kernel_keyboard_interrupt_dispatch.cpp`. | Registration and interrupt fanout rules are partially ported, and a retail test routes an Up event into movement selection before a scheduler tick. The original process-vtable callback resolver and controller behavior remain unported; movement still uses the host `ControllerMovementState` adapter. | Keep Win32 message translation at the host edge. Identify and port the actual game input consumer; do not treat subscriber fanout alone as original player-input parity. | | Movement and animation | [`updatePlayer`](../rebuild/remorse/src/windowed_game_main.cpp#L1084) drives `ControllerMovementState`, host animation processes, and approximate TYPEFLAG collision against the shared mutable item 1. | Some direction/modifier rules are **translated**, but the original controller/process call chain, actor collision response, and scheduler-driven player update are **stand-ins/unported**. | Keep world rules and input-to-action behavior in the core; replace the step policy and approximate collision with recovered actor, animation, and collision paths. | -| Interaction | [`startNearbyUsecode`](../rebuild/remorse/src/windowed_game_main.cpp#L287) and [`runUsecodeTasks`](../rebuild/remorse/src/windowed_game_main.cpp#L319) perform host candidate selection, context/task setup, and a bounded VM subset. | Item search has source-derived/translated pieces, but original `Item_Grab` (`10a0:2970`), `Usecode_ItemCallEvent` (`1420:0e3a`), and event dispatch are **not integrated end to end**; no verified reachable spawn interaction yet. | Keep archive/resource reads and memory allocation behind host services; execute recovered search, dispatch, and VM behavior in the core. | +| Interaction | [`startNearbyUsecode`](../rebuild/remorse/src/windowed_game_main.cpp#L287) and [`runUsecodeTasks`](../rebuild/remorse/src/windowed_game_main.cpp#L319) still perform host candidate selection, context/task setup, and a bounded VM subset. | A retail regression reaches item 6747 (`CHEST_EW`), dispatches a nested `FREE` event, and verifies shape/frame `1360/0 -> 1355/1` with changed target pixels. Original `Item_Grab` (`10a0:2970`), `Usecode_ItemCallEvent` (`1420:0e3a`), the later `0x70` loot search, and normal-window interaction integration remain **unported**. | Keep archive/resource reads and memory allocation behind host services; replace the regression's host path with recovered search, dispatch, and VM behavior in the core. | | Presentation | [`paintWindow`](../rebuild/remorse/src/windowed_game_main.cpp#L884) crops a rendered fixed-map image and composites a separately rendered live-player patch; the renderer refreshes that patch and sometimes rebuilds the full scene. | Retail asset decoding and host sorting are implemented, but the original live draw-list, source order, and camera path are **not ported**; this remains preview-style presentation. | Keep pixel buffers and projection platform-neutral; isolate GDI presentation, then replace static-scene recentering with recovered live rendering. | -2. **Prove the source-to-build pipeline (complete for one primitive):** `EntityDispatchEntry::SetGroupId` (`11e0:02a8`) is now a separately compiled `remorse_core` translation unit derived from `exports/src_remorse/functions/classes/Remorse/EntityDispatchEntry/SetGroupId@11e0_02a8.c`. Its corrected host signature receives the entry and 32-element count table explicitly; the existing `EntityDispatchEntry::setGroupId` boundary preserves the host exception for invalid IDs and delegates the verified low-five-bit update/count transitions to the compiled body. `entity_dispatch_entry_tests` passes through initialization, same-group preservation, reassignment, and count updates. This proves one source-to-build integration slice, not general export compatibility or binary runtime parity. Continue with a stateful scheduler primitive whose globals and call path can be represented explicitly; the import helper remains staging only. -3. **Restore the original startup and tick path:** port the minimum dependency chain for `Game_Start` (`1020:0000`), teleporter placement/waiting, kernel scheduler, timer, and item/NPC ownership. Route normal startup and simulation through these compiled functions; retain modeled startup and host polling only as diagnostics until parity checks pass. +2. **Prove the source-to-build pipeline (four compiled slices):** `EntityDispatchEntry::SetGroupId` (`11e0:02a8`) and `IncrementGroupId` (`11e0:0405`) live in a separately compiled `remorse_core` translation unit derived from their exported functions. The corrected signatures pass the entry, 32-element group-count table, and `ProcessKernel` explicitly. The host boundary retains exception-based assertion handling; the compiled transitions update the low-five-bit group identity/counts, enforce the active-group and group-29 gates, and notify the kernel so its selection-pending flag changes only when the active group changes. The scan now calls separately compiled partial slices from `FUN_11d0_0255` and `Kernel_11d0_0445`: per-entry run eligibility/one-pass syncing and highest ordinary-group selection. `entity_dispatch_entry_tests` covers these slices and the existing group transition cases. These are four compiled source-derived slices, not full-function translations, general export compatibility, or original-loop parity. The remaining scan iteration, wait/sleep lifecycle, timer and keyboard interrupts, early exit, and process maintenance remain host-owned or unported; the import helper remains staging only. +3. **Restore the original startup and tick path (basic threshold reached):** the normal Windows map-1 loader calls a core fresh-start entry that follows the reduced `Game_Start` path through teleporter `0x1e` and the verified active `0x63` trigger. A retail integration test then delivers a timer event and runs the bounded scheduler pass to advance an animation process owned by that same avatar. This establishes a basic rebuilt-code boot-and-tick prototype, not full `Game_Start`, original wait-list semantics, or `Kernel_11d0_31cf` parity. Next replace host wait-list/stasis and item-cache models, then move input and process behavior onto recovered keyboard/controller dispatch. 4. **Move player behavior onto that path:** replace host-created avatar/controller state, movement-step policy, and approximate collision with the recovered item, keyboard, controller, animation, and collision call chain. Feed Win32 input and timing into explicit host-service adapters; the game logic must not depend directly on Win32 APIs. -5. **Reconnect presentation and interaction:** render the live mutable world through recovered draw-list/order and camera behavior, then complete one reachable map-1 interaction through original item search, event dispatch, VM execution, and a visible world mutation. Keep the static preview as a regression oracle, not the normal gameplay renderer. +5. **Reconnect presentation and interaction:** the first reachable map-1 interaction now passes a retail-data regression through host item search, owner-row selection, nested VM dispatch, and a pixel-verified chest mutation. This closes the initial interaction milestone only; integrate original `Item_Grab`/`Usecode_ItemCallEvent`, implement the later `0x70` loot search, and connect live rendering to recovered draw-list/order and camera behavior. Keep the static preview as a regression oracle, not the normal gameplay renderer. 6. **Gate each replacement:** for every slice, record source address, exported function, unresolved decompiler assumptions, host substitutions, and tests; verify it is compiled into and called by `remorse_game`. Remove a stand-in from the normal path only after deterministic behavior checks pass. Update the function counts and parity status in this roadmap as slices land. 7. **Preserve the portability path:** keep recovered game logic and resource formats platform-neutral, with Win32 window/input/timing services behind replaceable interfaces. Once the original loop works through those interfaces, select and validate a portable host such as SDL; do not count the current Win32-only window as multi-platform support. ## Near-Term Next Actions -1. **Close the event path:** identify and reach an eligible retail `use` target from the actual level-start pad at `(30328, 29656, 16)`. The retail `Item_Grab` search now has a regression at that destination: it returns items `6812, 6811, 6810, 6804, 6786, 6785` in source order, and none has eligible `use` event 1. This replaces the historical staging-point candidate result but does not establish reachability beyond the six-item search area. Map-wide evidence includes the inactive/map-array `PANELNS`, a `CARD_NS` whose authorized state requires keycard 6, and a frame-0 `CHEST_EW` at staged `(1087, 2559, 0)` whose recovered handler attempts a legal shape swap to `0x054b` before animating. The host implements `Item.setShape` (`0x24`), but `FREE.slot_2d`'s family check, `Item.legal_create`, and temporary-item lifecycle are still missing; the chest's collision route is unverified. Next trace candidate searches along a verified movement route from the pad, then implement only the required recovered services and exercise owner selection, context creation, VM execution, and a process/world-state effect. The BOX_NS regression still verifies candidate-driven selection and visible frame output from a fixture origin only; it does not close this action or establish `Usecode_ItemCallEvent` parity. -2. **Integrate the map-1 loop:** port `Game_Start` (`1020:0000`) and replace host initialization; the window now models the clear-stasis waiter and both same-map teleports to the level-start pad, but does not implement the original wait lists or call chain. Next port the original target-map transition and item search, collision/fall, then move input and animation onto the recovered kernel loop. The current tests cover egg resolution and host stasis ordering, shared item-1 mutation, and host input/scheduler behavior, not binary lifecycle parity or source draw-order/camera behavior. Keep the normal window on the original path before calling the vertical slice accepted. +1. **Extend the reachable event path:** `flex_archive_tests` now reaches retail `CHEST_EW` item 6747 from the destination pad by a 295-step route, selects its `use` event through host item search and owner-row selection, executes nested VM dispatch, and verifies shape/frame `1360/0 -> 1355/1` with a target-only pixel change and no earlier VM error. Integrate original `Item_Grab`/`Usecode_ItemCallEvent`, then recover the later `0x70` nearby-loot search before claiming full chest-event parity. The test intentionally stops at the first visible mutation, before that optional loot scan; the BOX_NS fixture regression remains separate evidence. +2. **Continue integrating the map-1 loop:** the normal window calls the `remorse_core` fresh-game entry; the retail test queues an Up event through the source-derived keyboard fanout, creates the requested animation process, and advances it on a timer-driven scheduler pass. The boot entry is a reduced `Game_Start` translation; waiter links and map/NPC cache initialization remain host models. The event fanout still ends at a host callback, so recover the original process callback/consumer and controller path next. The full playable vertical slice still requires source-backed movement, live rendering, and a reachable interaction. ## Current Bottom Line @@ -584,3 +591,25 @@ Use this sequence to move the normal Windows launch path from host-modeled behav The retail `flex_archive_tests` startup path now runs the existing source-derived `Item_Grab` search after the modeled two-hop startup places item 1 at item 6812. It asserts the six search results in source order and runs each through the retail USECODE owner-row/event selector; all six reject `use` event 1. This resolves the roadmap's stale staging-point search question only. No reachable event target, original event dispatcher, or interaction is established. The host now materializes archive-backed USECODE chunks and builds tested 0x124-byte contexts with bounded source pointers and an initialized 0x82-byte call stack. Its window routes use-request candidates through owner-row selection into a context-backed task; the BOX_NS regression verifies VM-driven frame changes, rendered output, and cleanup. Retail tests now verify the complete map-1 startup placement from egg `0x1e` through active trigger item 1598/ID `0x63` to destination egg item 6812 at `(30328, 29656, 16)`, with item 1 and persistent runtime processes intact. The normal window has been confirmed at that destination, and the player sprite anchor was aligned with map-object rendering. The no-eligible-event result at egg `0x1e` describes only the former staging point; the destination search now confirms six nearby items and no eligible event. A deterministic host input/tick test verifies that the item-owned animation process moves item 1. Original `Game_Start`, full `Process_WaitFor` parity, cross-map teleporter lifecycle, `Usecode_ItemCallEvent`/context-dispatch, owner-resource callback parity, a reachable retail interaction, and original loop/render parity remain incomplete. Whole-game and playable-game acceptance remain unmet. + +### Scheduler Port Slices (2026-10-07) + +The `11d0:0255` decompilation's per-entry dispatch gate is now compiled in `remorse_core` and called by `ProcessKernel::scanRunnableProcesses`. It consumes the one-pass syncing flag and applies the sleep, linked-state (`+0x24/+0x26`), waiting, group, and daemon gates. Host wait-list readiness is passed explicitly; the host still owns scan iteration, sleep/wait processing, vtable callbacks, and cleanup. The `Kernel_11d0_0445` highest-group selection loop is also a compiled helper called when the host observes an empty active group; the wrapper applies the selected group and clears its pending flag. Tests preserve source behavior for occupied terminated slots and exclusions of groups 30/31. The MSVC build, all 15 CTests, and rebuild harness pass. These slices improve the compiled runtime used by the window but do not integrate the original scheduler loop or establish binary runtime parity. + +### Basic Map Boot And Tick (2026-10-07) + +The normal `remorse_game` launch now calls `startFreshGameMapOne` in `remorse_core`. This reduced fresh-start translation initializes the live avatar, creates/runs the source-shaped `TeleporterProcess` for map 1 egg `0x1e`, resolves the retail active trigger `0x63`, and runs the second teleporter process to item 6812 at `(30328, 29656, 16)`. The retail integration test continues from that same state: it creates an owned animation process, delivers one system-timer event, runs `runTimedSchedulerPass`, and verifies the avatar animation frame advances. The Windows target builds and all 15 CTests plus the harness pass. + +This reaches the narrow basic-build threshold: a normal Windows map-1 boot reaches the level-start area and rebuilt source-derived process code advances the avatar runtime on a tick. The retail test now sends an Up scan-code event through the compiled keyboard fanout and uses its host movement adapter to select the animation; the clip remains a deterministic fixture and does not prove retail movement/collision parity. It is not a playable source port. `Game_Start`'s surrounding initialization, original wait-list linked structures, item/NPC cache ownership, continuous `Kernel_11d0_31cf` loop, original input/controller consumer, and full process vtable routing remain incomplete or host-adapted. + +### Keyboard Interrupt Fanout Slice (2026-10-07) + +The `Kernel_CallProcKeyboardInterrupts` behavior is now isolated in `remorse_core` as `kernel_keyboard_interrupt_dispatch.cpp`. It drains the host-fed event queue, walks registered subscriber IDs, applies the source-derived allocation/flag/group gate, copies each queued 12-byte event for the subscriber, and calls the injected handler with selector `0x10` and filter `0`. The Win32 adapter supplies key scan codes/modifiers; `flex_archive_tests` boots map 1, sends Up through this fanout, verifies a walk request, delivers a timer event, and confirms the resulting avatar animation process advances. The build, all 15 CTests, and the harness pass. + +This does not yet dispatch through the original per-process function table. Live Ghidra shows the `Controller` vtable's `+0x28` slot is a no-op; the movement callback used by the window/test is explicitly host-side. `KeyboardProcess_HandleKeyEvent` and the original controller input consumer still need to be placed on their true runtime paths before claiming source-backed player input. + +### Reachable Retail Interaction (2026-10-08) + +The retail integration test reaches item 6747 (`CHEST_EW`) from the level-start area in 295 route steps (296 expanded nodes), selects its `use` event, and executes the replacement sequence through nested VM dispatch. At the clean checkpoint the target changes from shape/frame `1360/0` to `1355/1`; rendering the isolated target before and after confirms different pixels. The assertion requires nested dispatch, no VM error before the checkpoint, and the actual pixel difference. The test reports one nested event (`2572/50`); the full MSVC gate passes all 15 CTests and the rebuild/export harness. + +This closes the reachable visible-mutation milestone, not original runtime parity. Search, context creation, and task scheduling remain host-integrated rather than calls through original `Item_Grab` and `Usecode_ItemCallEvent`; the later chest `0x70` loot search and broader VM/list semantics are still unimplemented. The regression stops at the first visible mutation, and normal-window interaction wiring, original startup/scheduler, and source rendering remain outstanding. diff --git a/docs/standalone-usecode-debugger.md b/docs/standalone-usecode-debugger.md new file mode 100644 index 0000000..acb92c2 --- /dev/null +++ b/docs/standalone-usecode-debugger.md @@ -0,0 +1,172 @@ +# Standalone Crusader USECODE Debugger + +**Status:** Feasibility and architecture proposal +**Last evaluated:** 2026-10-07 +**Scope:** No Remorse and No Regret USECODE archives and debugger workflows + +## Executive conclusion + +A standalone debugger is feasible, but it should be treated as a new debugger application built from the recovered behavior and data formats, not as a direct extraction of the game's 16-bit debugger code. + +The in-game debugger is a front end attached to the game's live interpreter. Its `RUN` command resumes that interpreter; it does not parse the displayed `.unk` file or execute it. A standalone tool that can actually run scripts therefore needs its own execution engine or a bridge to a compatible game runtime. Recreating the source pane and menus alone will not provide execution, stepping, or meaningful watches. + +There are two useful definitions of “standalone”: + +1. **Offline USECODE debugger:** opens an archive, decodes bytecode, and runs it in a controlled VM with logged or simulated native calls. This is achievable without the game executable, but scripts that depend on world state or native intrinsics will be limited by the simulation. +2. **Game-faithful debugger:** executes scripts against the same process, world state, scheduler, and native services as the game. This requires integrating a compatible runtime such as the ScummVM Ultima 8/Crusader engine, or building a live bridge/instrumentation path. It is a substantially larger project. + +The recommended host is the existing Crusader map viewer JavaScript application. Add a debugger workspace to its USECODE tab, reuse its game selection, class/event navigation, and decompiler, and put execution in a separate VM/session layer. Start with an offline VM and an explicit intrinsic-provider boundary. Treat live-game parity as a later integration decision, not a prerequisite for the first useful debugger. + +## What the in-game debugger actually does + +The recovered menu and event paths expose a substantial debugger workflow: + +- Open a unit or text file, view source, search, and navigate to a line. +- Continue/run, break-next, single-step, run to cursor, step over, and run until return. +- Set and remove line breakpoints. +- Inspect values, maintain watches, and change globals. +- Display the current source line and debugger call stack. +- Break to TDP; the exact behavior and dependencies of this command remain unresolved. + +The source pane reads line-oriented `.unk` text. That text is for display and source navigation; it is distinct from the compiled event bodies stored in `EUSECODE.FLX`. In the recovered Regret event handler, `RUN` clears debugger break/step latches and resumes through the Gump callback. It does not compile or interpret the visible source text. + +The live debugger also relies on state that exists only during real interpreter execution. Its break-state object stores the current unit and line, breakpoints, step flags, and a stack of current-entry records. Those records include runtime pointers used by watch/inspect formatting. Opening the modal UI and loading a `.unk` file does not create a valid interpreter frame. + +This explains the current Regret result: the UI and source file can be made to open, but `RUN` can still crash when the debugger lacks a genuine current-entry record and valid runtime context. The recovered Regret bootstrap and interpreter hook are stronger than Remorse's dormant path, but the current-entry seeding path is not fully closed. See [the Regret debugger investigation](./regret-hidden-debugger-investigation.md) and [the break-state layout](./usecode-debugger-break-state-layout.md). + +## What can be reused + +The executable work provides a behavioral specification, not a portable source tree. Useful recovered material includes: + +- The debugger command/menu surface, event routing, breakpoint and step-state behavior, and source/watch pane behavior. +- The break-state layout, breakpoint entries, callstack entries, and expression-formatting evidence. +- The Crusader archive, class, event, and bytecode layouts in the [USECODE format specification](./usecode-format-specification.md). +- Existing extractors, parser fixtures, per-event source snapshots, and the map-viewer decompiler. +- ScummVM's Crusader-capable USECODE runtime as a candidate implementation to evaluate for runtime reuse. + +Directly lifting the 16-bit routines would retain dependencies on segmented far pointers, the game's Gump/event framework, global memory, allocators, and native services. A portable application should reimplement the recovered semantics behind ordinary interfaces and use the original routines as evidence and comparison points. + +The generated pseudocode and `.unk` files are not original compiler source and are not yet a complete editable/recompilable representation. The current map-viewer source snapshots preserve bytes and support limited immediate-edit previews, but there is not yet a deterministic archive writer or a proven edited-script runtime loop. See [the round-trip roadmap](./usecode-roundtrip-ir.md). + +## Target Host: Map Viewer + +The map viewer already has a natural home for this feature: + +- `ViewportPanel.vue` provides the `USECODE` tab and mounts `UsecodeViewer.vue`. +- `UsecodeViewer.vue` already has a class/event tree, source search, syntax-colored code view, and scene-driven open-target events. +- `usecode-browser.js` loads the index and rendered text. In dynamic mode these come from `/api/usecode/:game` and `/api/usecode/:game/raw`; static mode reads the corresponding exported cache files. +- The Node-side `usecode-decompiler.js` reads original archive files and builds the cache. The current cache contains an index, pseudocode text, and generated `.unk` files. It does not publish the original archive or the versioned archive-source document as a browser execution input. + +The current viewer is therefore a strong navigation and presentation base, but not yet a VM host. Its browser UI receives derived text, while the debugger needs authoritative bytecode, instruction offsets, class/event identities, and variant metadata. Add an explicit archive-source loading path: either serve a read-only archive/source snapshot from the dynamic server and include the equivalent in static exports, or let the user load a local archive. Do not make execution depend on scraping pseudocode text. + +The decompiler module is Node-oriented and imports `node:crypto`, `node:fs`, `node:path`, and uses `Buffer`. It should not be imported directly into the browser bundle. Separate a portable byte-reader/parser/IR core from Node cache and filesystem adapters, or provide the browser with a validated structured snapshot. A Web Worker is the preferred place for VM execution so long-running scripts cannot freeze the map viewer, its canvas, or the debugger controls. + +Keep the existing USECODE tab and add a browse/debug mode within it. The class/event tree and map-to-usecode navigation remain shared. A selected event should open a session at its first executable instruction; the right side can show source/decompilation and bytecode, with adjacent runtime panes for current instruction, call stack, locals/globals, watches, breakpoints, and VM output. This integrates the debugger into the existing app without creating a second product shell. + +## Feature parity and dependencies + +| In-game capability | Standalone equivalent | Main dependency or caveat | +|---|---|---| +| Open unit/file and browse source | Open archive class/event; show decoded listing, pseudocode, or `.unk` text | Must map displayed lines to bytecode offsets. `.unk` is display data, not executable code. | +| Search and go to line | Search source/listing and navigate to mapped instruction | Original debug-line coverage differs by variant. Current extraction finds line markers throughout Remorse, but none in the examined Regret corpus. Synthetic listing lines are possible, but are not original line numbers. | +| Continue, break-next, single-step | Control a VM instruction/event loop | Requires a VM with defined stop points and resumable execution state. | +| Step over, run until return | Track call depth and event/process boundaries | Must define behavior across class/event calls, spawned processes, and suspension. | +| Breakpoints | Bind breakpoints to class/event plus bytecode offset or mapped source line | Class names and source lines alone are not stable identities; retain class ID, event ID, and body digest/offset. | +| Watch and inspect | Evaluate supported expressions against VM frames and values | Requires correct local/member/global, string/list/reference, and call-frame semantics. Game-backed values require native runtime state. | +| Change global | Edit VM global state | A sandbox can edit its own state. Matching game behavior requires variant-correct global layout and runtime integration. | +| Break to TDP | Reproduce after its contract is recovered | Do not claim parity until its host/tool dependency and observable behavior are known. | + +## Proposed architecture + +Keep the debugger engine independent of the GUI and of any particular game runtime. + +### 1. Archive and source model + +- Load the correct Remorse or Regret archive and preserve all original bytes. +- Index classes, event slots, bodies, and raw offsets using the locally validated format rules. +- Decode instructions to an addressable listing while retaining unknown instructions and trailer bytes. +- Maintain source maps from displayed rows and any available `LINE_NUMBER` metadata to class/event/body offsets. +- Identify every debug position by variant, archive identity, class ID, event ID, and instruction/body offset; treat names as labels. + +### 2. Debuggable VM core + +- Represent VM values, evaluation stack, locals, members, globals, event frames, and process state explicitly. +- Execute supported bytecode with a program counter that can pause and resume at instruction boundaries. +- Implement class/event dispatch, process spawn, suspend/resume, return, and the control-flow forms needed by real scripts. +- Emit trace events for instruction entry/exit, calls, returns, intrinsic calls, state changes, and errors. +- Store breakpoints and step plans in debugger-session state rather than in GUI widgets. + +Unknown opcodes or value semantics must stop with an actionable diagnostic or remain opaque in static views. The VM must not silently guess instruction lengths or side effects. + +### 3. Intrinsic providers + +Define a variant-specific interface for native calls. Start with a sandbox provider that records arguments and returns configured values or explicit “unsupported” results. Add deterministic implementations for low-risk services, then a game-backed provider if runtime parity is required. + +Remorse and Regret must use separate ordinal/signature metadata. A matching ordinal number is not evidence of matching behavior. Intrinsics that mutate world state should be visibly marked and disabled or simulated by default in offline sessions. + +### 4. Debugger session and UI + +Build the front end around the VM session API inside the existing map viewer's USECODE tab. Reuse its game/version selection, class/event tree, `open-usecode-target` event, decompiler view, and existing generated-source paths. Add an explicit debug-session state that is separate from selected-map state and viewer history. + +A first useful UI needs a disassembly/source view, current instruction, call stack, locals/globals, breakpoint list, watch list, and VM output/error log. Add run, pause, step-into, step-over, and run-to-return controls only as their semantics become implemented. Preserve recovered commands where their semantics are known; label unsupported or unresolved operations instead of presenting them as working controls. + +The UI need not imitate the game's Gump rendering. Reproducing the debugger's capabilities and state transitions is the goal; a desktop UI can provide a clearer view of bytecode addresses, raw bytes, and unsupported operations than the original screen allowed. + +### 5. Browser/runtime boundary + +- Give the VM a browser-safe input contract based on `Uint8Array` or a validated archive-source document; keep Node filesystem access in cache/build adapters. +- Reuse the existing decompiler IR for labels and explanatory views, but execute decoded instructions from preserved bytecode and retain each instruction's exact body offset and raw bytes. +- Put VM stepping in a Web Worker with messages for start, pause, step, breakpoint hit, trace, result, and error. Keep UI controls responsive and make runaway scripts interruptible. +- Keep static deployment viable by exporting the same read-only archive input used by the dynamic server. The current static export copies the generated usecode cache, which is not sufficient until that cache contains execution input. +- Keep archive selection, VM session, breakpoint/watch state, and map selection as separate state domains. A map click may select an event, but must not silently start or mutate a running session. + +## `.unk` Format Investigation + +The canonical evidence inventory, open questions, and step-by-step investigation plan now live in [usecode-unk-format.md](./usecode-unk-format.md). The key boundary for the standalone debugger remains that `.unk` is display/source-mapping data; execution and breakpoints must be anchored to compiled event bytecode and valid VM state. Keep authentic, generated, and synthetic `.unk` files explicitly distinguished. + +## Implementation stages + +1. **Create the browser input contract.** Deliver original archive bytes or a validated archive-source snapshot to both dynamic and static map-viewer builds. Keep the API read-only and variant-specific. +2. **Separate portable decode from Node I/O.** Extract the archive reader and instruction/IR model into browser-safe code; keep filesystem, cache generation, and Node hashing behind adapters. Add exact byte-offset navigation from the existing pseudocode view. +3. **Build a read-only debugger workspace.** Extend the existing USECODE tab with bytecode view, raw bytes, class/event metadata, and source/bytecode navigation. Do not imply execution yet. +4. **Investigate and validate `.unk`.** Recover the text-loader contract and authentic source mapping; retain explicit provenance for authentic versus generated `.unk` files. +5. **Add a worker-hosted bounded VM.** Begin with a small, testable opcode subset and sandboxed intrinsics. Add breakpoints, continue, instruction stepping, call-stack display, trace output, and explicit unsupported-op reporting. +6. **Expand runtime semantics.** Add class/event calls, spawned processes, suspend/resume, managed values, and the variant-specific intrinsic contracts needed by selected corpus scripts. +7. **Add watch/inspect and source mapping.** Support a documented expression subset and map any authentic `.unk` rows and generated listing rows to bytecode offsets. Never label synthetic Regret rows as original source lines. +8. **Evaluate game-backed parity.** Compare the custom VM against ScummVM's Crusader runtime or another compatible host before implementing a second complete world/intrinsic layer. Keep this evaluation in the map-viewer app; a separate emulator/process bridge is an optional later project, not the initial product. +9. **Prove behavior incrementally.** Use known scripts and traces, verify pause/resume and breakpoints around calls and yields, compare Remorse and Regret independently, and record unsupported commands and intrinsics. + +## Effort Estimate + +These are rough engineering estimates for one engineer familiar with the map viewer, the current decoder, and the recovered debugger notes. They assume a sandboxed offline VM for the first release and do not include implementing all game intrinsics or reproducing game-world behavior. + +| Workstream | Estimate | Main uncertainty | +|---|---:|---| +| Browser archive input, portable decoder boundary, and basic Vue session integration | 1-2 weeks | Whether the static exporter should package raw FLEX bytes or a validated snapshot; expected archive transfer/storage size. | +| First `.unk` investigation and validator fixtures | 1-2 weeks | Availability of authentic `.unk` files and a repeatable game-side test path. | +| VM core for a useful, bounded opcode subset | 4-8 weeks | Value ownership, stack semantics, branches, and how much real corpus behavior must execute in the first cut. | +| Worker controls, breakpoints, stepping, trace, and basic call-stack integration | 2-4 weeks | Correct process/call behavior for spawn, suspend, and nested event dispatch. | +| Watch/inspect, source mapping, variant regression, and hardening | 3-6 weeks | Expression semantics, missing Regret line markers, and intrinsic requirements of target scripts. | + +Some work can overlap. A read-only bytecode debugger inside the current tab is a much smaller first milestone, roughly **2-4 weeks**. A useful sandboxed debugger that actually runs a documented subset is approximately **10-18 engineer-weeks**. A claim of broad game-faithful parity is a **multi-month** effort with no defensible upper bound until a ScummVM/runtime-reuse spike establishes how much world and intrinsic behavior can be reused. The parity spike itself should be time-boxed to **1-2 weeks** and end with a written integration decision. + +The highest-risk work is not the Vue layout. It is defining and testing a correct runtime state/value model, supplying original bytecode to the browser, and deciding whether intrinsic behavior is simulated or borrowed from a game runtime. + +## Acceptance criteria + +Call the first release a **standalone USECODE debugger** when it can load both supported archive variants, navigate bytecode, run the documented supported subset, pause/resume/step deterministically, maintain breakpoints and call stacks, inspect supported VM values, and report every unsupported opcode/intrinsic without corrupting state. + +Claim **in-game debugger parity** only when the supported menu actions have equivalent behavior and scripts can execute against compatible native/world services. A VM with stub intrinsics is useful, but it is not equivalent to the game's live debugger for gameplay-dependent scripts. + +For modified archives, require byte-identical no-op round trips, independent parse validation, and disposable-copy in-game tests. The existing editor roadmap's M2–M7 gates remain prerequisites for a reliable authoring-and-rebuild workflow; they are related to, but separate from, implementing a standalone execution debugger. + +## Related investigations + +- [Retail debugger entry options](./retail-debugger-entry-options.md) +- [No Regret hidden debugger investigation](./regret-hidden-debugger-investigation.md) +- [Debugger break-state layout](./usecode-debugger-break-state-layout.md) +- [USECODE format specification](./usecode-format-specification.md) +- [USECODE decompiler/recompiler roadmap](./usecode-roundtrip-ir.md) +- [Retail `-debug` argument](./retail-debug-arg.md) +- Map viewer USECODE UI: [UsecodeViewer.vue](../../crusader_map_viewer/map_renderer/src/vue/components/UsecodeViewer.vue), [ViewportPanel.vue](../../crusader_map_viewer/map_renderer/src/vue/components/ViewportPanel.vue), and [usecode-browser.js](../../crusader_map_viewer/map_renderer/src/shared/usecode-browser.js) +- Map viewer decode/cache implementation: [usecode-decompiler.js](../../crusader_map_viewer/map_renderer/src/lib/usecode-decompiler.js), [usecode-unk-exporter.js](../../crusader_map_viewer/map_renderer/src/lib/usecode-unk-exporter.js), and [USECODE regression tests](../../crusader_map_viewer/map_renderer/scripts/test-usecode-structuring.mjs) \ No newline at end of file diff --git a/docs/usecode-unk-format.md b/docs/usecode-unk-format.md new file mode 100644 index 0000000..1eedf6c --- /dev/null +++ b/docs/usecode-unk-format.md @@ -0,0 +1,121 @@ +# Crusader USECODE `.unk` Format and Reverse-Engineering Plan + +**Status:** Evidence-backed working note; original file grammar remains unresolved +**Last reviewed:** 2026-10-07 +**Scope:** Per-unit `.unk` files consumed by the hidden USECODE debugger in No Remorse and No Regret + +## Executive Summary + +There was no document dedicated to `.unk` reverse engineering. This is now the canonical summary and investigation plan. The most important current conclusion is that `.unk` is a line-oriented text sidecar loaded by the debugger's source pane, not compiled USECODE and not the input that the game's `RUN` command executes. + +The game's loader behavior is much better understood than the contents of an authentic `.unk` file. No authentic retail `.unk` sample is currently documented in the workspace. Existing map-viewer `.unk` outputs are synthesized from extracted bytecode and pseudocode; they prove that the file loader can display suitable text, but they do not recover the original source grammar or conventions. + +The immediate goal should be to recover the loader contract and obtain or construct controlled samples. Keep source-display format work separate from VM execution, interpreter state, and any proposed bytecode line-marker injection. + +## Current Understanding + +### `.unk` is a per-unit text sidecar + +The debugger's current-unit path obtains the active unit name from its break-state callstack, appends `.unk`, and resolves the result under the `s_usecode` root. The expected name is therefore of the form `USECODE\\.unk`, rather than a fixed shared filename such as `UNKDS.DAT`. + +The recovered source-loading path opens the file, reads it into a memory buffer, checks that it looks like text, splits it into lines, and keeps pointers for indexed line access. The source pane, search, go-to-line, click handling, and breakpoint marks use that line table. + +This is direct evidence for a text viewer. It is not evidence that `.unk` contains executable bytecode or that the debugger compiles it. In the recovered debugger event handler, `RUN` clears break/step state and resumes the live interpreter; it does not parse the visible `.unk` text. + +### Related files are distinct + +| File | Current evidence-backed interpretation | Confidence and open point | +|---|---|---| +| `.unk` | Per-unit text loaded by the debugger source pane. | Text-loading behavior and filename construction are directly recovered; original grammar is unknown. | +| `UNKCOFF.DAT` | Fixed table of 4-byte values interpreted by existing `tools/unkcoffs` scripts as NE far addresses, aligned with intrinsic/function name tables. Remorse is 1,244 bytes (311 entries); Regret is 1,400 bytes (350 entries). | The representation and tool use are observed. Its exact runtime role and full relationship to USECODE remain to be confirmed. It is not the per-unit text file. | +| `UNKDS.DAT` | Small file opened by a separate fixed-name loader in the older usecode/debug support path. Remorse is 66 bytes; Regret is 36 bytes. | Separate loading path and sizes are observed; its internal structure and role remain unknown. It is not a substitute for `.unk`. | +| `UNKOFF.DAT` | No separate file with this exact name is evidenced in the inspected workspace/game files. | Likely a typo or shorthand for `UNKCOFF.DAT`; keep the names distinct until a sample proves otherwise. | + +### Loader behavior and safe-file constraints + +The following points are known or strongly supported by recovered loader code and the existing controlled experiments: + +- The debugger reads the whole source file into memory and rejects content that fails a text-like sanity check. +- The line splitter searches for `LF` and writes a NUL byte to the byte immediately before each `LF`. +- `CRLF` is the safe observed form: the overwritten byte is `CR`, leaving the line text intact. With bare `LF`, the preceding visible character is overwritten. A file beginning with bare `LF` can write before the start of the input buffer. +- The source-line table is bounded at 5,999 lines in the current debugger/exporter analysis. +- Existing Regret testing reports rejection near an average line length of `0x84` bytes. The exact check, whether this is a strict average, and its relation to total file size still need to be verified. +- The current JS exporter writes ASCII with `CRLF`, avoids a leading blank line, and keeps generated output under the 5,999-line limit. This is a conservative compatibility profile, not a proven complete specification. + +Do not infer that all printable DOS bytes, tabs, empty lines, or line-ending styles are accepted merely because the loader has a text path. Their acceptance has not been systematically tested. + +## Existing `.unk` Experiments + +The map-viewer implementation is the active generated-file path: + +- [usecode-unk-exporter.js](../../crusader_map_viewer/map_renderer/src/lib/usecode-unk-exporter.js) constructs per-class text files. +- [usecode-decompiler.js](../../crusader_map_viewer/map_renderer/src/lib/usecode-decompiler.js) writes them under `.cache/usecode///.data/` and indexes them in the usecode cache. +- [test-usecode-structuring.mjs](../../crusader_map_viewer/map_renderer/scripts/test-usecode-structuring.mjs) tests generated sparse-line and no-debug-line cases, including `CRLF` and the no-leading-newline safety condition. +- [generate_usecode_unk.py](../tools/generate_usecode_unk.py) is the earlier Python generator and remains useful as historical reference; ongoing changes should follow the JS exporter. + +The current generated layout is a research format, not recovered original source: + +1. The file name is the uppercased class/unit name, sanitized to at most eight characters, plus `.unk`. +2. Where compiled `LINE_NUMBER` operations are available, the exporter groups decoded instruction summaries by line number and emits sparse line entries. Missing lines are filled with `//` placeholders. +3. The exporter appends a clearly labeled pseudocode appendix for the class's event bodies. +4. Where no line markers exist, a requested dense synthetic line floor can be emitted before the appendix. Regret currently uses a 2,991-line floor for debugger experiments. +5. A generated manifest records whether the line table is recovered, synthetic, or appendix-only. + +The current Regret cache contains 477 generated `.unk` files. The manufactured files open in the tested Regret debugger path when the synthetic line floor is present. That confirms useful text-loader compatibility for those files only. `RUN` still crashes because the debugger lacks a valid interpreter-seeded current-entry record and runtime context; changing `.unk` text alone does not fix that separate state problem. + +### Compiled line metadata differs by game + +The current parser pass finds: + +- Remorse: `LINE_NUMBER` operations in all 977 parsed event bodies, with a highest recovered line number of 2,991. +- Regret: no recovered `LINE_NUMBER` operations in the 1,152 parsed event bodies. + +Consequently, Remorse can currently provide a bytecode-derived line-number basis, while Regret's generated dense line floor is synthetic. Do not present synthetic Regret rows as original source lines or claim exact source correspondence. + +Adding `LINE_NUMBER` opcodes to Regret bytecode is a separate possible experiment, not `.unk` format reconstruction. It would require decoding and rewriting event bodies, adjusting relative branches and event offsets, rebuilding the archive, and testing behavior. Even correct line markers would not create the missing live debugger callstack/runtime state required by `RUN`. + +## What Remains Unknown + +### File and text representation + +- Whether an authentic file uses source code, assembly-like listings, annotated decompilation, or multiple sections. +- Accepted character encodings/code pages, high-bit bytes, tabs, control characters, embedded NULs, and maximum individual-line length. +- Whether `CRLF` is required or merely the safe option implied by the splitter; whether a final newline, blank first/last lines, empty file, or LF-only input is accepted. +- Exact limits and checks for total bytes, line count, average line length, and the reported `0x84` threshold. +- Whether the loader recognizes directives or structured records, or treats every line as display text. + +### Source mapping and debugger semantics + +- How a compiled `LINE_NUMBER` value maps to a particular row in an authentic `.unk` file. +- How sparse, duplicate, repeated, or out-of-order line markers are represented and resolved. +- Whether several class event slots share one unit listing and how generated/source lines are partitioned among those slots. +- Which operations use file path plus 1-based row, which store a zero-based current-line value, and how that relates to the interpreter's line marker. The break-state stores the current line minus one in at least one recovered path; verify all conversions end to end. +- Whether watch/inspect expressions are parsed from `.unk` text, from compiled debug descriptors, or from both. The formatter also consumes live interpreter frame/source pointers, so file text alone is not sufficient for evaluation. +- The exact relationship between `.unk`, `UNKCOFF.DAT`, `UNKDS.DAT`, symbols, and the current compiled archive. +- Whether original `.unk` files were shipped in any retail, demo, regional, or development release, or were produced only by an internal toolchain. + +## Reverse-Engineering Plan + +Keep every result qualified by game, executable/archive version, and evidence type. Preserve authentic files unchanged and run file-mutation experiments only against disposable copies. + +1. **Find authentic samples.** Search retail, demo, regional, patch, and development media/install layouts for `USECODE\\*.unk`, archives containing `.unk` entries, and build-tool outputs. Record exact provenance, path, size, hash, timestamps if meaningful, and the matching executable/archive. If none are found, explicitly limit conclusions to the game's text-loader contract. +2. **Close the static loader path.** In both available executable families, trace path construction, open/read, text sanity checks, line splitting, line-pointer lookup, drawing, search, go-to-line, breakpoint display/toggle, and source-buffer destruction. Recover exact arithmetic and bounds for file size, line count, average/individual line lengths, allocation, terminators, and error cases. +3. **Build a controlled input matrix.** In a disposable game copy, vary one property at a time: ASCII/high-bit bytes, CRLF/LF, final newline, empty file, leading/trailing blank lines, tabs, embedded NUL, long lines, line count, average length, and total size. Record whether the file opens, renders without corruption, supports search/navigation, and survives breakpoint operations. An open-only test is not full acceptance. +4. **Recover the line contract.** Use Remorse bytecode with known `LINE_NUMBER` markers and controlled debugger breakpoints. Compare the runtime marker, break-state line field, requested source row, highlighted row, and breakpoint row. Verify zero/one-based conversions, gaps, duplicate markers, and behavior past the final mapped line. +5. **Separate source text from expression/debug metadata.** Trace watch, inspect, symbol lookup, and current-frame formatting. Identify which inputs come from `.unk`, which come from compiled descriptors or tables, and which require live frame pointers. Do not invent source directives to explain data that is actually held elsewhere. +6. **Use Regret as a distinct case.** First establish whether authentic Regret `.unk` samples or debug-line metadata exist. Keep the current synthetic 2,991-line scaffold labeled as synthetic. If testing injected `LINE_NUMBER` opcodes, use a separate bytecode-rewriter experiment and verify branch/event relocation independently. +7. **Implement a validator and fixtures.** Add a small parser/validator in the map-viewer tooling only after the observed grammar is stable. Fixtures should cover accepted and rejected files, exact line offsets, encoding/newline cases, limits, and provenance (`authentic`, `generated`, `synthetic`). Continue testing generated output separately from authentic-file compatibility. +8. **Publish a versioned format note.** Record confirmed rules, unresolved hypotheses, sample hashes, and test results. Promote a rule from “inferred” to “observed” only when supported by an authentic sample, direct executable behavior, or a repeatable runtime test. + +### First-pass effort + +The first loader-and-source-mapping pass is estimated at **1-2 engineer-weeks** with access to the existing Ghidra analysis and a controllable game test. Authentic sample discovery is the main schedule risk. If original samples remain unavailable, static and black-box work can still establish safe text constraints, but cannot recover the original source grammar, symbol naming, or compiler conventions. + +## Evidence and Related Work + +- [Regret hidden debugger investigation](./regret-hidden-debugger-investigation.md): source loader, generated corpus, Regret open/RUN experiments, and debugger-state boundary. +- [Retail debugger entry options](./retail-debugger-entry-options.md): Remorse source pane, line navigation, breakpoint, and watch behavior. +- [Standalone debugger proposal](./standalone-usecode-debugger.md): map-viewer integration and VM effort plan. +- [USECODE format specification](./usecode-format-specification.md): archive, class/event, bytecode, and `LINE_NUMBER` evidence. +- [USECODE decompiler/recompiler roadmap](./usecode-roundtrip-ir.md): source snapshots, archive round trips, and current tooling limits. +- [UNKCOFF translation utility](../tools/unkcoffs/unk_translate.py): interpretation of `UNKCOFF.DAT` entries as far addresses. \ No newline at end of file diff --git a/rebuild/remorse/CMakeLists.txt b/rebuild/remorse/CMakeLists.txt index ae09248..c7a2e70 100644 --- a/rebuild/remorse/CMakeLists.txt +++ b/rebuild/remorse/CMakeLists.txt @@ -14,7 +14,13 @@ add_library(remorse_core src/map_renderer.cpp src/map_sorter.cpp src/palette.cpp + src/ported/controller_fire_sleep_gate.cpp src/ported/entity_dispatch_entry_set_group_id.cpp + src/ported/game_start_fresh_map.cpp + src/ported/kernel_keyboard_interrupt_dispatch.cpp + src/ported/kernel_scheduler_group_selection.cpp + src/ported/kernel_keyboard_interrupt_gate.cpp + src/ported/kernel_scheduler_runnable_gate.cpp src/runtime.cpp src/shape_archive.cpp src/type_flags.cpp diff --git a/rebuild/remorse/build_msvc.cmd b/rebuild/remorse/build_msvc.cmd index af799b1..4b0bd68 100644 --- a/rebuild/remorse/build_msvc.cmd +++ b/rebuild/remorse/build_msvc.cmd @@ -30,12 +30,12 @@ call "%VCVARS%" || exit /b 2 cd /d "%REPO_ROOT%" || exit /b 2 -set "BUILD_DIR=rebuild/remorse/out/build-nmake" -cmake -S rebuild/remorse -B "%BUILD_DIR%" -G "NMake Makefiles" -DCMAKE_BUILD_TYPE="%CONFIG%" || exit /b 1 -cmake --build "%BUILD_DIR%" || exit /b 1 -ctest --test-dir "%BUILD_DIR%" --output-on-failure || exit /b 1 +set "BUILD_DIR=rebuild/remorse/out/build" +cmake -S rebuild/remorse -B "%BUILD_DIR%" -DCMAKE_GENERATOR_INSTANCE="%VSINSTALL%" || exit /b 1 +cmake --build "%BUILD_DIR%" --config "%CONFIG%" || exit /b 1 +ctest --test-dir "%BUILD_DIR%" -C "%CONFIG%" --output-on-failure || exit /b 1 -set "EXE=%BUILD_DIR%\remorse_rebuild.exe" +set "EXE=%BUILD_DIR%\%CONFIG%\remorse_rebuild.exe" if not exist "%EXE%" ( echo Built executable was not found at "%EXE%". exit /b 1 diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index e2469ba..1e2eb99 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -44,6 +44,8 @@ struct StagedContainedFixedMapItem { FixedMapEntry data; }; +constexpr u16 liveItemEtherealFlag = 0x0800; + struct ItemFindArea { u16 minX = 0; u16 minY = 0; @@ -129,6 +131,12 @@ public: std::optional> sweepCandidateIds(const WorldRect& area, u16 excludedItemNumber) const; std::optional allocateItem(StagedFixedMapItem item); bool insertItem(StagedFixedMapItem item); + bool pushItemToEtherealVoid(u16 itemNumber); + std::optional popItemFromEtherealVoid(); + std::optional popItemToCoords(u16 x, u16 y, u8 z); + bool destroyItem(u16 itemNumber); + bool canCreateItemAt(u16 shape, u16 x, u16 y, u8 z, + const std::vector& shapes) const; bool moveItemIntoContainer(u16 itemNumber, u16 containerItemNumber, const std::vector& shapes); bool moveContainedItemToWorld(u16 itemNumber, u16 x, u16 y, u8 z); @@ -153,6 +161,7 @@ private: std::optional avatar_; std::vector npcAnimations_; std::vector allocatedIds_; + std::vector destroyedIds_; std::vector hatchedGlobIds_; std::vector parentById_; std::vector> containedItemData_; @@ -160,6 +169,7 @@ private: std::vector containedHeadById_; std::vector containedTailById_; std::vector freeItemIds_; + std::vector etherealStack_; u16 nextFreeItemNumber_ = 0x100; }; diff --git a/rebuild/remorse/include/remorse/game_start.h b/rebuild/remorse/include/remorse/game_start.h new file mode 100644 index 0000000..e655bf0 --- /dev/null +++ b/rebuild/remorse/include/remorse/game_start.h @@ -0,0 +1,16 @@ +#pragma once + +#include "remorse/compat.h" + +#include + +namespace remorse { + +class LiveFixedMapItems; +class ProcessKernel; +struct ShapeTypeInfo; + +bool startFreshGameMapOne(ProcessKernel& kernel, LiveFixedMapItems& items, + const std::vector& shapes, u16 (&groupCounts)[32]); + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/include/remorse/isometric_controls.h b/rebuild/remorse/include/remorse/isometric_controls.h index 59fdc44..f68306a 100644 --- a/rebuild/remorse/include/remorse/isometric_controls.h +++ b/rebuild/remorse/include/remorse/isometric_controls.h @@ -25,6 +25,9 @@ inline bool controllerWalkRequested(u16 modifiers) return shiftDown == capsLockOn; } +bool controllerFireAttemptSuppressed(bool previousAttemptSlept, u8 scanCode, + u8 eventMode, u8 keyState); + inline bool controllerAllowsInPlaceDirectionUpdate(u8 animation) { switch (animation) { @@ -112,6 +115,7 @@ struct ControllerActorState { bool kneeling = false; bool activeWeapon = false; bool busy = false; + bool lastFireAttemptWentToSleep = false; bool lastAnimationNotCombat = true; bool avatarSomethingCombatty = false; }; @@ -144,6 +148,10 @@ public: if (eventMode == 0) { return; } + if (controllerFireAttemptSuppressed(actor_.lastFireAttemptWentToSleep, + scanCode, eventMode, keyState)) { + return; + } if (keyState != 0 && keyAction == 1 && actor_.npcNumber == 1 && (scanCode == 0x0f || scanCode == 0x24)) { if (!actor_.busy || (actor_.lastAnimation != 56 && diff --git a/rebuild/remorse/include/remorse/usecode_vm.h b/rebuild/remorse/include/remorse/usecode_vm.h index 4c4063f..7ea1c71 100644 --- a/rebuild/remorse/include/remorse/usecode_vm.h +++ b/rebuild/remorse/include/remorse/usecode_vm.h @@ -50,6 +50,7 @@ enum class UsecodeStepResult { struct UsecodeOpcodeServices { std::function(u16 offset, u16 segment)> readFarWord; + std::function(u16 classId, u16 eventSlot)> callEvent; std::function setInfo; std::function processCount; std::function(u16 classId, u16 eventSlot, u8 extraArgumentBytes, @@ -58,18 +59,29 @@ struct UsecodeOpcodeServices { std::function currentProcessId; }; +struct UsecodeRoutineFrame { + u16 classId = 0; + u16 eventSlot = 0; + std::vector code; + std::vector frame; + std::size_t frameBaseOffset = usecodeFrameBaseOffset; + std::size_t returnProgramCounter = 0; +}; + class UsecodeInterpreterState { public: static std::optional initialize( const std::vector& itemParameter, const std::vector& contextParameter = {}, u16 modeFlags = 0, bool contextParameterPresent = false); bool pushCodeAddress(u16 offset, u16 segment); + bool pushByte(u8 value); 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::vector& frame, std::size_t frameBaseOffset, + const UsecodeOpcodeServices& services); std::optional> lastSetInfoOperands; std::array valueStack{}; @@ -102,10 +114,14 @@ struct UsecodeProcessTask { std::vector itemMemory; UsecodeInterpreterState interpreter; std::size_t programCounter = usecodeEventBytecodeOffset; + std::size_t frameBaseOffset = usecodeFrameBaseOffset; + std::vector routineFrames; bool halted = false; bool timerDelayProcess = false; u32 wakeTick = 0; + std::optional readMappedFarWord(FarPtr16 address) const; + bool writeMappedFarWord(FarPtr16 address, u16 value); std::optional readMappedItemWord(FarPtr16 address) const; }; diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index a9778e0..744bcf8 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -776,15 +776,7 @@ void ProcessKernel::refreshActiveGroup(const u16 (&groupCounts)[32]) if (groupCounts[activeGroup_] != 0) { return; } - u8 highestGroup = 1; - for (const EntityDispatchEntryBase* entry : processes_) { - if (entry != nullptr) { - const u8 groupId = entry->bytes[0x08] & 0x1f; - if (groupId > highestGroup && groupId != 30 && groupId != 31) { - highestGroup = groupId; - } - } - } + const u8 highestGroup = ported::selectHighestOrdinaryProcessGroup(processes_.data(), processes_.size()); setActiveGroup(highestGroup); groupSelectionPending_ = false; } @@ -1103,18 +1095,10 @@ void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDisp EntityDispatchEntry::unlinkSleep(*entry); } } - if ((readLe16(*entry, 0x16) & 0x40) != 0) { - writeLe16(*entry, 0x16, static_cast(readLe16(*entry, 0x16) & ~0x40)); - } else { - const u8 groupId = entry->bytes[0x08] & 0x1f; - const u16 flags = readLe16(*entry, 0x16); - if ((readLe16(*entry, 0x18) & 0x1000) == 0 && readLe16(*entry, 0x24) == 0 && - readLe16(*entry, 0x26) == 0 && (flags & 1) == 0 && - ((flags & 2) != 0 || groupId == activeGroup_ || groupId == 30 || groupId == 31)) { - currentProcessId_ = static_cast(id); - run(*entry, context); - currentProcessId_ = 0; - } + if (ported::prepareProcessForSchedulerRun(*entry, activeGroup_, waitingForProcess)) { + currentProcessId_ = static_cast(id); + run(*entry, context); + currentProcessId_ = 0; } } clearTerminatedProcesses(); @@ -1236,13 +1220,7 @@ void EntityDispatchEntry::setGroupId(EntityDispatchEntryBase& entry, u8 groupId, void EntityDispatchEntry::incrementGroupId(EntityDispatchEntryBase& entry, ProcessKernel& kernel, u16 (&groupCounts)[32]) { - const u8 previousGroup = entry.bytes[groupIdOffset] & 0x1f; - const u8 nextGroup = static_cast(previousGroup + 1); - if (nextGroup >= 30 || kernel.activeGroup() != previousGroup) { - throw std::invalid_argument("process group cannot advance from the current active group"); - } - setGroupId(entry, nextGroup, groupCounts); - kernel.setActiveGroup(nextGroup); + ported::incrementEntityDispatchEntryGroupId(entry, kernel, groupCounts); } void EntityDispatchEntry::setSourceType(EntityDispatchEntryBase& entry, u16 sourceType) @@ -1375,24 +1353,4 @@ bool ProcessKernel::pendingKeyEventOverflowed() const return pendingKeyEventOverflowed_; } -void ProcessKernel::dispatchPendingKeyEvents( - void (*deliver)(EntityDispatchEntryBase&, u16, u16, KeyEvent&, void*), void* context) -{ - while (auto event = popPendingKeyEvent()) { - const std::size_t subscriberCount = keyboardSubscriberIds_.size(); - for (std::size_t index = 0; index < subscriberCount; ++index) { - const u16 id = keyboardSubscriberIds_[index]; - auto* process = processAt(id); - if (!process || allocationSizeAt(id) < 0x34 || - (readLe16(*process, 0x16) & 0x08) != 0 || - (readLe16(*process, 0x18) & 0x180) != 0x80 || - (reinterpret_cast(process)[0x32] & 0x10) == 0) { - continue; - } - KeyEvent copy = *event; - deliver(*process, 0x10, 0, copy, context); - } - } -} - } // namespace remorse diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index 9ab9dd8..71f9b54 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -1,4 +1,5 @@ #include "remorse/fixed_map.h" +#include "remorse/collision.h" #include "remorse/glob_archive.h" #include "remorse/entity_dispatch_entry.h" @@ -377,6 +378,9 @@ std::optional> collectZMatches(const StagedFixed const auto area = itemFindAreaAroundItem(origin, shapes[origin.data.shape]); for (const auto itemNumber : itemFindCandidateOrder(area, *chains)) { const auto& candidate = *byId[itemNumber]; + if ((candidate.data.flags & liveItemEtherealFlag) != 0) { + continue; + } if (checkRectangle && (candidate.data.x < area.minX || candidate.data.x > area.maxX || candidate.data.y < area.minY || candidate.data.y > area.maxY)) { continue; @@ -455,7 +459,8 @@ 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), destroyedIds_(0x2800), + hatchedGlobIds_(0x2800), parentById_(0x2800), containedItemData_(0x2800), containedNextById_(0x2800), containedHeadById_(0x2800), containedTailById_(0x2800) { @@ -734,6 +739,112 @@ bool LiveFixedMapItems::insertItem(StagedFixedMapItem item) return true; } +bool LiveFixedMapItems::pushItemToEtherealVoid(u16 itemNumber) +{ + const auto item = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& candidate) { + return candidate.itemNumber == itemNumber; + }); + if (item == items_.end()) { + return false; + } + if ((item->data.flags & liveItemEtherealFlag) == 0) { + item->data.flags |= liveItemEtherealFlag; + etherealStack_.push_back(itemNumber); + } + return true; +} + +std::optional LiveFixedMapItems::popItemFromEtherealVoid() +{ + while (!etherealStack_.empty()) { + const u16 itemNumber = etherealStack_.back(); + etherealStack_.pop_back(); + const auto item = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& candidate) { + return candidate.itemNumber == itemNumber; + }); + if (item == items_.end()) { + continue; + } + item->data.flags &= static_cast(~liveItemEtherealFlag); + return itemNumber; + } + return std::nullopt; +} + +std::optional LiveFixedMapItems::popItemToCoords(u16 x, u16 y, u8 z) +{ + if (x > 0x7fff || y > 0x7fff) { + return std::nullopt; + } + const auto itemNumber = popItemFromEtherealVoid(); + if (!itemNumber) { + return std::nullopt; + } + const auto* item = findItem(*itemNumber); + if (item && item->data.shape == 1408 && z > 0) { + --z; + } + return moveItem(*itemNumber, x, y, z) ? itemNumber : std::nullopt; +} + +bool LiveFixedMapItems::destroyItem(u16 itemNumber) +{ + if (itemNumber < 0x100 || itemNumber >= allocatedIds_.size() || !allocatedIds_[itemNumber] || + destroyedIds_[itemNumber] || containedHeadById_[itemNumber] != 0) { + 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; + parentById_[itemNumber] = 0; + destroyedIds_[itemNumber] = true; + return true; +} + +bool LiveFixedMapItems::canCreateItemAt(u16 shape, u16 x, u16 y, u8 z, + const std::vector& shapes) const +{ + constexpr u32 blockingShapeFlags = 0x0002 | 0x0004; + if (shape >= shapes.size() || x > 0x7fff || y > 0x7fff) { + return false; + } + const auto& createdShape = shapes[shape]; + if ((createdShape.flags & blockingShapeFlags) == 0) { + return true; + } + const auto createdBody = makeCollisionBody(WorldPoint{static_cast(x) * crusaderCoordinateScale, + static_cast(y) * crusaderCoordinateScale, z}, createdShape); + for (const auto& item : items_) { + if ((item.data.flags & liveItemEtherealFlag) != 0 || item.data.shape >= shapes.size()) { + continue; + } + const auto& obstacleShape = shapes[item.data.shape]; + if ((obstacleShape.flags & blockingShapeFlags) == 0) { + continue; + } + const WorldPoint itemLocation{static_cast(item.data.x) * crusaderCoordinateScale, + static_cast(item.data.y) * crusaderCoordinateScale, item.data.z}; + if (collisionBodiesOverlap(createdBody, makeCollisionBody(itemLocation, obstacleShape, + (item.data.flags & 0x0020) != 0))) { + return false; + } + } + return true; +} + bool LiveFixedMapItems::moveItemIntoContainer(u16 itemNumber, u16 containerItemNumber, const std::vector& shapes) { @@ -809,6 +920,12 @@ bool LiveFixedMapItems::releaseItem(u16 itemNumber, const ProcessKernel& kernel) hatchedGlobIds_[itemNumber]) { return false; } + if (destroyedIds_[itemNumber]) { + destroyedIds_[itemNumber] = false; + allocatedIds_[itemNumber] = false; + freeItemIds_.push_back(itemNumber); + return true; + } const auto worldItem = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& item) { return item.itemNumber == itemNumber; }); diff --git a/rebuild/remorse/src/map_renderer.cpp b/rebuild/remorse/src/map_renderer.cpp index 81a894c..3943af9 100644 --- a/rebuild/remorse/src/map_renderer.cpp +++ b/rebuild/remorse/src/map_renderer.cpp @@ -16,6 +16,7 @@ namespace { constexpr u16 flagInvisible = 0x0010; constexpr u16 flagFlipped = 0x0020; +constexpr u16 flagEthereal = liveItemEtherealFlag; constexpr u32 siSolid = 0x0002; constexpr u32 siLand = 0x0008; constexpr u32 siOccl = 0x0010; @@ -135,6 +136,9 @@ std::vector collectSceneItems( if ((item.flags & flagInvisible) != 0 && !options.includeHiddenMarkers) { continue; } + if ((item.flags & flagEthereal) != 0) { + continue; + } if ((info.flags & siRoof) != 0 && !options.includeRoofs) { continue; } diff --git a/rebuild/remorse/src/ported/controller_fire_sleep_gate.cpp b/rebuild/remorse/src/ported/controller_fire_sleep_gate.cpp new file mode 100644 index 0000000..b09df32 --- /dev/null +++ b/rebuild/remorse/src/ported/controller_fire_sleep_gate.cpp @@ -0,0 +1,12 @@ +#include "remorse/isometric_controls.h" + +namespace remorse { + +bool controllerFireAttemptSuppressed(bool previousAttemptSlept, u8 scanCode, + u8 eventMode, u8 keyState) +{ + return previousAttemptSlept && eventMode != 0 && + (scanCode == 0x39 || (scanCode == 0x52 && keyState == 0)); +} + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/ported/entity_dispatch_entry_port.h b/rebuild/remorse/src/ported/entity_dispatch_entry_port.h index 4b69c69..d3a4a03 100644 --- a/rebuild/remorse/src/ported/entity_dispatch_entry_port.h +++ b/rebuild/remorse/src/ported/entity_dispatch_entry_port.h @@ -6,5 +6,13 @@ namespace remorse::ported { void setEntityDispatchEntryGroupId(EntityDispatchEntryBase& entry, u8 groupId, u16 (&groupCounts)[32]); +void incrementEntityDispatchEntryGroupId(EntityDispatchEntryBase& entry, ProcessKernel& kernel, + u16 (&groupCounts)[32]); +bool prepareProcessForSchedulerRun(EntityDispatchEntryBase& entry, u8 activeGroup, + bool waitingForProcess); +u8 selectHighestOrdinaryProcessGroup(EntityDispatchEntryBase* const* processes, + std::size_t processCount); +bool isKeyboardInterruptDispatchEligible(const EntityDispatchEntryBase& process, + std::size_t allocationSize, u8 activeGroup); } // namespace remorse::ported \ No newline at end of file diff --git a/rebuild/remorse/src/ported/entity_dispatch_entry_set_group_id.cpp b/rebuild/remorse/src/ported/entity_dispatch_entry_set_group_id.cpp index f80f3df..c9b4ffb 100644 --- a/rebuild/remorse/src/ported/entity_dispatch_entry_set_group_id.cpp +++ b/rebuild/remorse/src/ported/entity_dispatch_entry_set_group_id.cpp @@ -1,5 +1,7 @@ #include "entity_dispatch_entry_port.h" +#include + namespace remorse::ported { void setEntityDispatchEntryGroupId(EntityDispatchEntryBase& entry, u8 groupId, @@ -15,4 +17,19 @@ void setEntityDispatchEntryGroupId(EntityDispatchEntryBase& entry, u8 groupId, } } +void incrementEntityDispatchEntryGroupId(EntityDispatchEntryBase& entry, ProcessKernel& kernel, + u16 (&groupCounts)[32]) +{ + const u8 previousGroup = entry.bytes[0x08] & 0x1f; + const u8 nextGroup = static_cast(previousGroup + 1); + if (nextGroup >= 30) { + throw std::invalid_argument("process group cannot advance beyond group 29"); + } + if (kernel.activeGroup() != previousGroup) { + throw std::invalid_argument("process group must match the active group"); + } + setEntityDispatchEntryGroupId(entry, nextGroup, groupCounts); + kernel.setActiveGroup(nextGroup); +} + } // namespace remorse::ported \ No newline at end of file diff --git a/rebuild/remorse/src/ported/game_start_fresh_map.cpp b/rebuild/remorse/src/ported/game_start_fresh_map.cpp new file mode 100644 index 0000000..6e1933f --- /dev/null +++ b/rebuild/remorse/src/ported/game_start_fresh_map.cpp @@ -0,0 +1,29 @@ +#include "remorse/game_start.h" + +#include "remorse/entity_dispatch_entry.h" +#include "remorse/fixed_map.h" + +namespace remorse { + +bool startFreshGameMapOne(ProcessKernel& kernel, LiveFixedMapItems& items, + const std::vector& shapes, u16 (&groupCounts)[32]) +{ + if (!items.initializeAvatar() || + !runFreshGameTeleporterStartup(kernel, items, 1, 0x1e, shapes, groupCounts)) { + return false; + } + + const StagedFixedMapItem* avatar = items.findItem(1); + if (avatar == nullptr) { + return false; + } + const auto stagingTeleporter = findNearbyActiveTeleportEgg(*avatar, items.mapItems(), shapes, 1); + if (!stagingTeleporter) { + return false; + } + + return runFreshGameTeleporterStartup(kernel, items, stagingTeleporter->data.mapNumber, + static_cast(stagingTeleporter->data.quality & 0xff), shapes, groupCounts); +} + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/ported/kernel_keyboard_interrupt_dispatch.cpp b/rebuild/remorse/src/ported/kernel_keyboard_interrupt_dispatch.cpp new file mode 100644 index 0000000..3978f6e --- /dev/null +++ b/rebuild/remorse/src/ported/kernel_keyboard_interrupt_dispatch.cpp @@ -0,0 +1,25 @@ +#include "remorse/entity_dispatch_entry.h" +#include "entity_dispatch_entry_port.h" + +namespace remorse { + +void ProcessKernel::dispatchPendingKeyEvents( + void (*deliver)(EntityDispatchEntryBase&, u16, u16, KeyEvent&, void*), void* context) +{ + while (auto event = popPendingKeyEvent()) { + const std::size_t subscriberCount = keyboardSubscriberIds_.size(); + for (std::size_t index = 0; index < subscriberCount; ++index) { + const u16 processId = keyboardSubscriberIds_[index]; + auto* process = processAt(processId); + if (process == nullptr || !ported::isKeyboardInterruptDispatchEligible( + *process, allocationSizeAt(processId), activeGroup_)) { + continue; + } + + KeyEvent processEvent = *event; + deliver(*process, 0x10, 0, processEvent, context); + } + } +} + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/ported/kernel_keyboard_interrupt_gate.cpp b/rebuild/remorse/src/ported/kernel_keyboard_interrupt_gate.cpp new file mode 100644 index 0000000..7b47b1b --- /dev/null +++ b/rebuild/remorse/src/ported/kernel_keyboard_interrupt_gate.cpp @@ -0,0 +1,26 @@ +#include "entity_dispatch_entry_port.h" + +namespace remorse::ported { +namespace { + +u16 readLe16(const EntityDispatchEntryBase& process, u16 offset) +{ + return static_cast(process.bytes[offset] | + (static_cast(process.bytes[offset + 1]) << 8)); +} + +} + +bool isKeyboardInterruptDispatchEligible(const EntityDispatchEntryBase& process, + std::size_t allocationSize, u8 activeGroup) +{ + const u16 processFlags = readLe16(process, 0x16); + const u16 extensionFlags = readLe16(process, 0x18); + const u8 processGroup = process.bytes[0x08] & 0x1f; + return allocationSize >= 0x34 && (processFlags & 0x08) == 0 && + (extensionFlags & 0x180) == 0x80 && + (process.bytes[0x32] & 0x10) != 0 && + (processGroup >= activeGroup || processGroup == 30 || processGroup == 31); +} + +} // namespace remorse::ported \ No newline at end of file diff --git a/rebuild/remorse/src/ported/kernel_scheduler_group_selection.cpp b/rebuild/remorse/src/ported/kernel_scheduler_group_selection.cpp new file mode 100644 index 0000000..b3c27ce --- /dev/null +++ b/rebuild/remorse/src/ported/kernel_scheduler_group_selection.cpp @@ -0,0 +1,23 @@ +#include "entity_dispatch_entry_port.h" + +namespace remorse::ported { + +u8 selectHighestOrdinaryProcessGroup(EntityDispatchEntryBase* const* processes, + std::size_t processCount) +{ + u8 highestGroup = 1; + for (std::size_t processId = 0; processId < processCount; ++processId) { + const EntityDispatchEntryBase* process = processes[processId]; + if (process == nullptr) { + continue; + } + + const u8 groupId = process->bytes[0x08] & 0x1f; + if (groupId > highestGroup && groupId != 30 && groupId != 31) { + highestGroup = groupId; + } + } + return highestGroup; +} + +} // namespace remorse::ported \ No newline at end of file diff --git a/rebuild/remorse/src/ported/kernel_scheduler_runnable_gate.cpp b/rebuild/remorse/src/ported/kernel_scheduler_runnable_gate.cpp new file mode 100644 index 0000000..afe34e0 --- /dev/null +++ b/rebuild/remorse/src/ported/kernel_scheduler_runnable_gate.cpp @@ -0,0 +1,35 @@ +#include "entity_dispatch_entry_port.h" + +namespace remorse::ported { +namespace { + +u16 readLe16(const EntityDispatchEntryBase& entry, u16 offset) +{ + return static_cast(entry.bytes[offset] | (static_cast(entry.bytes[offset + 1]) << 8)); +} + +void writeLe16(EntityDispatchEntryBase& entry, u16 offset, u16 value) +{ + entry.bytes[offset] = static_cast(value & 0xff); + entry.bytes[offset + 1] = static_cast(value >> 8); +} + +} + +bool prepareProcessForSchedulerRun(EntityDispatchEntryBase& entry, u8 activeGroup, + bool waitingForProcess) +{ + const u16 processFlags = readLe16(entry, 0x16); + if ((processFlags & 0x40) != 0) { + writeLe16(entry, 0x16, static_cast(processFlags & ~0x40)); + return false; + } + + const u8 groupId = entry.bytes[0x08] & 0x1f; + return !waitingForProcess && (processFlags & 0x08) == 0 && + (readLe16(entry, 0x18) & 0x1000) == 0 && readLe16(entry, 0x24) == 0 && + readLe16(entry, 0x26) == 0 && (processFlags & 1) == 0 && + ((processFlags & 2) != 0 || groupId == activeGroup || groupId == 30 || groupId == 31); +} + +} // namespace remorse::ported \ No newline at end of file diff --git a/rebuild/remorse/src/usecode_vm.cpp b/rebuild/remorse/src/usecode_vm.cpp index 23f02f0..874da26 100644 --- a/rebuild/remorse/src/usecode_vm.cpp +++ b/rebuild/remorse/src/usecode_vm.cpp @@ -68,6 +68,15 @@ bool UsecodeInterpreterState::pushWord(u16 value) return true; } +bool UsecodeInterpreterState::pushByte(u8 value) +{ + if (stackTop == 0) { + return false; + } + valueStack[--stackTop] = value; + return true; +} + bool UsecodeInterpreterState::pushDword(u32 value) { if (stackTop < sizeof(value)) { @@ -107,7 +116,7 @@ std::optional UsecodeInterpreterState::popDword() } UsecodeStepResult UsecodeInterpreterState::step(const std::vector& code, - std::size_t& programCounter, std::vector& frame, + std::size_t& programCounter, std::vector& frame, std::size_t frameBaseOffset, const UsecodeOpcodeServices& services) { if (programCounter >= code.size()) { @@ -119,7 +128,7 @@ UsecodeStepResult UsecodeInterpreterState::step(const std::vector& code, return UsecodeStepResult::InvalidInstruction; } const auto rawOffset = static_cast(code[programCounter]); - const auto localIndex = static_cast(usecodeFrameBaseOffset) + rawOffset; + const auto localIndex = static_cast(frameBaseOffset) + 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() || @@ -194,7 +203,7 @@ UsecodeStepResult UsecodeInterpreterState::step(const std::vector& code, temporaryWord = *result; return UsecodeStepResult::Advanced; } - if (opcode == 0x14 || opcode == 0x1c || opcode == 0x24 || opcode == 0x2a || + if (opcode == 0x14 || opcode == 0x1c || opcode == 0x1e || opcode == 0x24 || opcode == 0x2a || opcode == 0x2c || opcode == 0x36) { const auto right = popWord(); const auto left = right ? popWord() : std::nullopt; @@ -205,6 +214,8 @@ UsecodeStepResult UsecodeInterpreterState::step(const std::vector& code, u16 result = 0; if (opcode == 0x14) result = static_cast(*left + *right); else if (opcode == 0x1c) result = static_cast(*left - *right); + else if (opcode == 0x1e) result = static_cast( + static_cast(*left) * static_cast(*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)); @@ -277,6 +288,13 @@ UsecodeStepResult UsecodeInterpreterState::step(const std::vector& code, stackHighWatermark = std::max(stackHighWatermark, stackTop); return UsecodeStepResult::Advanced; } + if (opcode == 0x74) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const u8 value = code[programCounter++]; + return pushByte(value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } if (opcode == 0x12) { const auto value = popWord(); if (!value) { @@ -298,17 +316,36 @@ UsecodeStepResult UsecodeInterpreterState::step(const std::vector& code, 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)) { + const std::size_t operandOffset = code[programCounter++]; + const auto localIndex = static_cast(frameBaseOffset) + operandOffset; + if (localIndex < 0 || static_cast(localIndex) > frame.size() || + frame.size() - static_cast(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); + const std::size_t localOffset = static_cast(localIndex); + const u32 value = static_cast(frame[localOffset]) | + (static_cast(frame[localOffset + 1]) << 8) | + (static_cast(frame[localOffset + 2]) << 16) | + (static_cast(frame[localOffset + 3]) << 24); return pushDword(value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; } + if (opcode == 0x4b) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + if (!services.currentProcessId) { + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; + } + const auto displacement = static_cast(code[programCounter++]); + const auto localIndex = static_cast(frameBaseOffset) + displacement; + if (localIndex < 0 || static_cast(localIndex) >= frame.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const u32 address = (static_cast(services.currentProcessId()) << 16) | + static_cast(localIndex); + return pushDword(address) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } if (opcode == 0x4c) { if (programCounter >= code.size()) { return UsecodeStepResult::InvalidInstruction; @@ -482,6 +519,35 @@ std::optional UsecodeProcessTask::readMappedItemWord(FarPtr16 address) cons (static_cast(itemMemory[address.offset + 1]) << 8)); } +std::optional UsecodeProcessTask::readMappedFarWord(FarPtr16 address) const +{ + if (address.segment == processId) { + if (address.offset > frame.size() || frame.size() - address.offset < sizeof(u16)) { + return std::nullopt; + } + return static_cast(frame[address.offset] | + (static_cast(frame[address.offset + 1]) << 8)); + } + return readMappedItemWord(address); +} + +bool UsecodeProcessTask::writeMappedFarWord(FarPtr16 address, u16 value) +{ + std::vector* memory = nullptr; + if (address.segment == processId) { + memory = &frame; + } else if (address.segment == 0) { + memory = &itemMemory; + } + if (memory == nullptr || address.offset > memory->size() || + memory->size() - address.offset < sizeof(u16)) { + return false; + } + (*memory)[address.offset] = static_cast(value); + (*memory)[address.offset + 1] = static_cast(value >> 8); + return true; +} + bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize, const UsecodeContextFactoryFields& fields) { @@ -691,7 +757,62 @@ UsecodeStepResult UsecodeProcessTask::step(const UsecodeOpcodeServices& services if (halted) { return UsecodeStepResult::Returned; } - const auto result = interpreter.step(code, programCounter, frame, services); + if (programCounter < code.size() && code[programCounter] == 0x11) { + if (code.size() - programCounter < 5) { + return UsecodeStepResult::InvalidInstruction; + } + const u16 calleeClassId = static_cast(code[programCounter + 1] | + (static_cast(code[programCounter + 2]) << 8)); + const u16 calleeEventSlot = static_cast(code[programCounter + 3] | + (static_cast(code[programCounter + 4]) << 8)); + if (!services.callEvent) { + return UsecodeStepResult::UnsupportedOpcode; + } + if (routineFrames.size() >= 31) { + return UsecodeStepResult::StackFault; + } + auto calleeBody = services.callEvent(calleeClassId, calleeEventSlot); + if (!calleeBody || calleeBody->bytes.size() <= usecodeEventBytecodeOffset) { + return UsecodeStepResult::ServiceRejected; + } + constexpr std::size_t callFrameBytes = 3 * sizeof(u16); + if (frameBaseOffset < callFrameBytes) { + return UsecodeStepResult::StackFault; + } + routineFrames.push_back({classId, eventSlot, std::move(code), frame, frameBaseOffset, + programCounter + 5}); + if (!interpreter.pushCodeAddress(calleeClassId, calleeEventSlot)) { + code = std::move(routineFrames.back().code); + frame = std::move(routineFrames.back().frame); + routineFrames.pop_back(); + return UsecodeStepResult::StackFault; + } + const std::size_t calleeArgumentOffset = frameBaseOffset; + classId = calleeClassId; + eventSlot = calleeEventSlot; + frameBaseOffset -= callFrameBytes; + std::fill(frame.begin(), frame.end(), u8{0}); + const std::size_t copiedArgumentBytes = std::min(frame.size() - calleeArgumentOffset, + interpreter.valueStack.size() - interpreter.stackTop); + std::copy_n(interpreter.valueStack.begin() + interpreter.stackTop, + copiedArgumentBytes, frame.begin() + calleeArgumentOffset); + code = std::move(calleeBody->bytes); + programCounter = usecodeEventBytecodeOffset; + return UsecodeStepResult::Advanced; + } + const auto result = interpreter.step(code, programCounter, frame, frameBaseOffset, services); + if (result == UsecodeStepResult::Returned && !routineFrames.empty()) { + UsecodeRoutineFrame caller = std::move(routineFrames.back()); + routineFrames.pop_back(); + --interpreter.callFrameCount; + classId = caller.classId; + eventSlot = caller.eventSlot; + frameBaseOffset = caller.frameBaseOffset; + frame = std::move(caller.frame); + code = std::move(caller.code); + programCounter = caller.returnProgramCounter; + return UsecodeStepResult::Advanced; + } halted = result == UsecodeStepResult::Returned; return result; } diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index 3acb299..7970fe5 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -7,6 +7,7 @@ #include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" #include "remorse/fixed_map.h" +#include "remorse/game_start.h" #include "remorse/glob_archive.h" #include "remorse/isometric_controls.h" #include "remorse/map_renderer.h" @@ -342,7 +343,16 @@ void runUsecodeTasks(AppState& state) remorse::UsecodeOpcodeServices services; services.readFarWord = [task](remorse::u16 offset, remorse::u16 segment) -> std::optional { - return task->readMappedItemWord(remorse::FarPtr16{offset, segment}); + return task->readMappedFarWord(remorse::FarPtr16{offset, segment}); + }; + services.callEvent = [&app](remorse::u16 classId, remorse::u16 eventSlot) + -> std::optional { + if (!app.usecodeArchive) { + return std::nullopt; + } + const auto usecodeClass = remorse::loadUsecodeClass(*app.usecodeArchive, classId); + return usecodeClass + ? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt; }; services.setInfo = [&app, processId](remorse::u16 eventType, remorse::u16 sourceItem) { return app.diagnosticKernel.setProcessInfo(processId, eventType, sourceItem); @@ -360,6 +370,12 @@ void runUsecodeTasks(AppState& state) return static_cast(keycard < 64 && (app.heldKeycards & (std::uint64_t{1} << keycard)) != 0); } + if (ordinal == 0xac && argumentBytes == 2) { + const remorse::u16 shape = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + return shape < app.shapeTypes.size() + ? std::optional{app.shapeTypes[shape].family} : std::nullopt; + } if (ordinal == 0x15 && argumentBytes == 6) { return remorse::u16{0}; } @@ -373,10 +389,88 @@ void runUsecodeTasks(AppState& state) (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 (ordinal == 0x0a && argumentBytes == 4) { + const auto itemNumber = task->readMappedFarWord(remorse::FarPtr16{offset, segment}); + if (itemNumber && app.liveItems && app.liveItems->destroyItem(*itemNumber)) { + app.usecodeWorldMutationPending = true; + } + return remorse::u16{0}; + } + if (ordinal == 0x30 && argumentBytes == 4) { + const auto poppedItem = app.liveItems + ? app.liveItems->popItemFromEtherealVoid() : std::nullopt; + if (poppedItem) { + app.usecodeWorldMutationPending = true; + } + return poppedItem.value_or(0); + } + if (ordinal == 0x20 && argumentBytes == 10) { + const remorse::u16 x = static_cast(arguments[4] | + (static_cast(arguments[5]) << 8)); + const remorse::u16 y = static_cast(arguments[6] | + (static_cast(arguments[7]) << 8)); + const auto poppedItem = app.liveItems + ? app.liveItems->popItemToCoords(x, y, arguments[8]) : std::nullopt; + if (poppedItem) { + app.usecodeWorldMutationPending = true; + } + return poppedItem.value_or(0); + } + if (ordinal == 0x19 && argumentBytes == 14) { + const remorse::u16 shape = static_cast(arguments[4] | + (static_cast(arguments[5]) << 8)); + const remorse::u16 frame = static_cast(arguments[6] | + (static_cast(arguments[7]) << 8)); + const remorse::u16 x = static_cast(arguments[8] | + (static_cast(arguments[9]) << 8)); + const remorse::u16 y = static_cast(arguments[10] | + (static_cast(arguments[11]) << 8)); + const remorse::u8 z = arguments[12]; + if (!app.liveItems || frame > 0xff || + !app.liveItems->canCreateItemAt(shape, x, y, z, app.shapeTypes)) { + return remorse::u16{0}; + } + remorse::StagedFixedMapItem createdItem; + createdItem.recordIndex = static_cast(-1); + createdItem.data.x = x; + createdItem.data.y = y; + createdItem.data.z = z; + createdItem.data.shape = shape; + createdItem.data.frame = static_cast(frame); + const auto itemNumber = app.liveItems->allocateItem(createdItem); + if (!itemNumber || !task->writeMappedFarWord( + remorse::FarPtr16{offset, segment}, *itemNumber)) { + return remorse::u16{0}; + } + app.usecodeWorldMutationPending = true; + return remorse::u16{1}; + } + const auto itemNumber = task->readMappedFarWord(remorse::FarPtr16{offset, segment}); + if (ordinal == 0x10 && argumentBytes == 4) { + const auto* item = itemNumber && app.liveItems + ? app.liveItems->findItem(*itemNumber) : nullptr; + return item ? static_cast(item->data.quality & 0xff) + : remorse::u16{0}; + } if (!itemNumber) { return std::nullopt; } + if (ordinal == 0x3c && argumentBytes == 4) { + const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; + return item && item->data.shape < app.shapeTypes.size() + ? std::optional{app.shapeTypes[item->data.shape].family} + : std::nullopt; + } + if (ordinal == 0x22 && argumentBytes == 4) { + if (!app.liveItems || !app.liveItems->pushItemToEtherealVoid(*itemNumber)) { + return std::nullopt; + } + app.usecodeWorldMutationPending = true; + return remorse::u16{0}; + } + if (ordinal == 0x25) { + return remorse::u16{0}; + } 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)} @@ -390,6 +484,18 @@ void runUsecodeTasks(AppState& state) const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item ? std::optional{item->data.mapNumber} : std::nullopt; } + if (ordinal == 0x09 && argumentBytes == 4) { + const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; + return item ? std::optional{item->data.z} : std::nullopt; + } + if (ordinal == 0x13 && argumentBytes == 4) { + const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; + return item ? std::optional{item->data.x} : std::nullopt; + } + if (ordinal == 0x14 && argumentBytes == 4) { + const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; + return item ? std::optional{item->data.y} : std::nullopt; + } if (ordinal == 0x24 && argumentBytes == 6) { const remorse::u16 shape = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); @@ -399,7 +505,7 @@ void runUsecodeTasks(AppState& state) app.usecodeWorldMutationPending = true; return remorse::u16{0}; } - if (ordinal == 0x59 && argumentBytes == 6) { + if ((ordinal == 0x02 || ordinal == 0x59) && argumentBytes == 6) { const remorse::u8 frame = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); if (!app.liveItems || !app.liveItems->setItemFrame(*itemNumber, frame)) { @@ -621,32 +727,24 @@ void loadSceneAsync(HWND window, AppState& state) : remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0}; remorse::MapRenderOptions options = fullSceneOptions(state.mapIndex, spawn); remorse::LiveFixedMapItems liveItems(std::move(*stagedItems), std::move(containedItems)); - liveItems.initializeAvatar(); if (startingEgg) { std::lock_guard kernelLock(state.kernelMutex); - if (!remorse::runFreshGameTeleporterStartup(state.diagnosticKernel, liveItems, - static_cast(state.mapIndex), 0x1e, *shapeTypes, - state.diagnosticGroupCounts)) { - setLoadFailure(state, L"The teleporter process could not resolve its map and egg destination."); + if (state.mapIndex != 1 || !remorse::startFreshGameMapOne(state.diagnosticKernel, + liveItems, *shapeTypes, state.diagnosticGroupCounts)) { + setLoadFailure(state, L"The source-derived fresh-game start could not resolve map 1's level destination."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } const auto* avatar = liveItems.findItem(1); - const auto stagingTeleporter = avatar ? remorse::findNearbyActiveTeleportEgg( - *avatar, liveItems.mapItems(), *shapeTypes, static_cast(state.mapIndex)) - : std::nullopt; - if (!stagingTeleporter || !remorse::runFreshGameTeleporterStartup( - state.diagnosticKernel, liveItems, stagingTeleporter->data.mapNumber, - static_cast(stagingTeleporter->data.quality & 0xff), *shapeTypes, - state.diagnosticGroupCounts)) { - setLoadFailure(state, L"The staging teleporter could not resolve its level destination."); - PostMessageW(window, sceneReadyMessage, 0, 0); - return; - } avatar = liveItems.findItem(1); spawn = remorse::WorldPoint{avatar->data.x * 2, avatar->data.y * 2, avatar->data.z}; options.viewCenter = spawn; } else { + if (!liveItems.initializeAvatar()) { + setLoadFailure(state, L"The player item could not be initialized."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } remorse::StagedFixedMapItem directStart; directStart.data.x = static_cast(spawn.x / 2); directStart.data.y = static_cast(spawn.y / 2); diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index 3998fb2..b25dd79 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -271,6 +271,15 @@ int main() groupKernel.refreshActiveGroup(groupTable); assert(groupKernel.activeGroup() == 30 && groupKernel.groupSelectionPending()); + remorse::ProcessKernel retainedGroupKernel; + remorse::u16 retainedGroups[32]{}; + retainedGroupKernel.createProcess(2, retainedGroups); + retainedGroupKernel.createProcess(5, retainedGroups); + retainedGroupKernel.terminateProcess(1, retainedGroups); + retainedGroupKernel.setActiveGroup(3); + retainedGroupKernel.refreshActiveGroup(retainedGroups); + assert(retainedGroupKernel.activeGroup() == 5 && !retainedGroupKernel.groupSelectionPending()); + remorse::ProcessKernel scheduler; remorse::u16 scheduledGroups[32]{}; assert(scheduler.activeGroup() == 1 && !scheduler.groupSelectionPending()); @@ -296,6 +305,21 @@ int main() assert((ran == std::vector{2, 3})); assert(specialGroup->bytes[0x08] == 30); + remorse::ProcessKernel gateKernel; + remorse::u16 gateGroups[32]{}; + auto* linkedAt24 = gateKernel.createProcess(2, gateGroups); + auto* linkedAt26 = gateKernel.createProcess(2, gateGroups); + auto* readyProcess = gateKernel.createProcess(2, gateGroups); + auto* daemonProcess = gateKernel.createProcess(3, gateGroups); + linkedAt24->bytes[0x24] = 1; + linkedAt26->bytes[0x26] = 1; + daemonProcess->bytes[0x16] |= 2; + std::vector gatedRuns; + gateKernel.scanRunnableProcesses(2, recordRun, &gatedRuns); + assert(gatedRuns.size() == 2); + assert(gateKernel.processAt(gatedRuns[0]) == readyProcess); + assert(gateKernel.processAt(gatedRuns[1]) == daemonProcess); + remorse::ProcessKernel automaticGroupKernel; remorse::u16 automaticGroupCounts[32]{}; automaticGroupKernel.createProcess(3, automaticGroupCounts); @@ -965,6 +989,29 @@ int main() event.scanCode, event.modifiers, event.field8 != 0); }, &deliveredMovement); assert(deliveredMovement.request().animation == 1 && deliveredMovement.request().direction == 14); + inputKernel.setActiveGroup(2); + std::vector groupFilteredScans; + assert(inputKernel.queuePendingKeyEvent(wrapped)); + inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase&, + remorse::u16, remorse::u16, remorse::KeyEvent& event, void* context) { + static_cast*>(context)->push_back(event.scanCode); + }, &groupFilteredScans); + assert(groupFilteredScans.empty()); + remorse::EntityDispatchEntry::setGroupId(inputController->base, 2, inputGroups); + assert(inputKernel.queuePendingKeyEvent(wrapped)); + inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase&, + remorse::u16, remorse::u16, remorse::KeyEvent& event, void* context) { + static_cast*>(context)->push_back(event.scanCode); + }, &groupFilteredScans); + assert((groupFilteredScans == std::vector{0x48})); + inputKernel.setActiveGroup(31); + remorse::EntityDispatchEntry::setGroupId(inputController->base, 30, inputGroups); + assert(inputKernel.queuePendingKeyEvent(wrapped)); + inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase&, + remorse::u16, remorse::u16, remorse::KeyEvent& event, void* context) { + static_cast*>(context)->push_back(event.scanCode); + }, &groupFilteredScans); + assert((groupFilteredScans == std::vector{0x48, 0x48})); wrapped.field8 = 0; assert(inputKernel.queuePendingKeyEvent(wrapped)); inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase&, diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index 133d850..d04d086 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -1,9 +1,12 @@ #include "remorse/collision.h" +#include "remorse/animation_archive.h" #include "remorse/entity_dispatch_entry.h" +#include "remorse/game_start.h" #include "remorse/file_system.h" #include "remorse/flex_archive.h" #include "remorse/fixed_map.h" #include "remorse/glob_archive.h" +#include "remorse/isometric_controls.h" #include "remorse/map_renderer.h" #include "remorse/type_flags.h" #include "remorse/usecode_archive.h" @@ -14,6 +17,11 @@ #include #include #include +#include +#include +#include +#include +#include int main() { @@ -360,6 +368,80 @@ int main() integratedStartupKernel.processAt(processIdOf(integratedTimer)) == &integratedTimer->base && integratedStartupKernel.processAt(processIdOf(integratedKeyboard)) == &integratedKeyboard->base && integratedStartupKernel.processAt(processIdOf(integratedController)) == &integratedController->base); + remorse::LiveFixedMapItems freshGameWorld(*stagedItems); + remorse::ProcessKernel freshGameKernel; + remorse::u16 freshGameGroups[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + freshGameKernel.createProcess(1, freshGameGroups); + } + auto* freshGameTimer = freshGameKernel.createSystemTimerProcess(1, freshGameGroups); + auto* freshGameKeyboard = freshGameKernel.createKeyboardProcess(1, freshGameGroups); + auto* freshGameController = freshGameKernel.createControllerProcess(1, freshGameGroups); + assert(remorse::startFreshGameMapOne(freshGameKernel, freshGameWorld, *typeFlags, freshGameGroups)); + const auto* freshGameAvatar = freshGameWorld.findItem(1); + const auto* expectedLevelStart = freshGameWorld.findItem(6812); + assert(freshGameAvatar && expectedLevelStart && freshGameAvatar->data.x == expectedLevelStart->data.x && + freshGameAvatar->data.y == expectedLevelStart->data.y && freshGameAvatar->data.z == expectedLevelStart->data.z && + freshGameAvatar->data.mapNumber == 1 && freshGameGroups[1] == 6 && freshGameTimer && + freshGameKeyboard && freshGameController && + freshGameKernel.processAt(processIdOf(freshGameTimer)) == &freshGameTimer->base && + freshGameKernel.processAt(processIdOf(freshGameKeyboard)) == &freshGameKeyboard->base && + freshGameKernel.processAt(processIdOf(freshGameController)) == &freshGameController->base); + remorse::ControllerActorState bootTickActor; + bootTickActor.mapNumber = 1; + bootTickActor.direction = 14; + remorse::ControllerMovementState bootTickController; + bootTickController.setActorState(bootTickActor); + remorse::KeyEvent bootInput{}; + bootInput.scanCode = 0x48; + bootInput.field8 = 1; + bootInput.field9 = 1; + bootInput.fieldA = 1; + assert(freshGameKernel.queuePendingKeyEvent(bootInput)); + freshGameKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process, + remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { + if (process.bytes[0] == 0xa6 && process.bytes[1] == 0x3a && selector == 0x10 && filter == 0) { + static_cast(context)->handleKeyEvent( + event.scanCode, event.modifiers, event.field8, event.field9, + event.fieldA, event.field6); + } + }, &bootTickController); + const auto bootMovement = bootTickController.request(); + assert(bootMovement.animation == 1 && bootMovement.direction == 14); + remorse::AnimationClip bootTickAnimation{}; + bootTickAnimation.header = {17, 4, 0, 0}; + bootTickAnimation.frameCount = 17; + bootTickAnimation.frames.resize(17 * 8); + auto* bootTickProcess = freshGameKernel.createAnimPrimitiveProcess(1, 1, + bootMovement.animation, bootMovement.direction, + bootTickAnimation, freshGameGroups); + const remorse::u16 bootTickProcessId = static_cast(bootTickProcess->base.bytes[2] | + (static_cast(bootTickProcess->base.bytes[3]) << 8)); + assert(freshGameKernel.startAnimPrimitiveProcess(bootTickProcessId, freshGameWorld, bootTickAnimation)); + struct FreshGameTickContext { + remorse::ProcessKernel& kernel; + remorse::LiveFixedMapItems& items; + const remorse::AnimationClip& clip; + const std::vector& shapes; + remorse::u16 processId; + std::optional advanced; + } freshGameTick{freshGameKernel, freshGameWorld, bootTickAnimation, *typeFlags, bootTickProcessId}; + freshGameKernel.deliverSystemTimerEvent(); + freshGameKernel.runTimedSchedulerPass(freshGameKernel.activeGroup(), + [](remorse::EntityDispatchEntryBase& process, void* opaque) { + auto& tick = *static_cast(opaque); + if (&process == tick.kernel.processAt(tick.processId)) { + const auto* avatar = tick.items.findItem(1); + assert(avatar); + tick.advanced = tick.kernel.advanceGroundedAnimPrimitive(tick.processId, + tick.items, tick.clip, tick.shapes, + remorse::calculateFastAreaRange({avatar->data.x * 2, avatar->data.y * 2, + avatar->data.z})); + } + }, &freshGameTick); + assert(freshGameKernel.systemTimerTick() == 1 && freshGameTick.advanced == true && + freshGameWorld.findNpcAnimation(1)->frame == 1 && + freshGameWorld.findItem(1)->itemNumber == 1); const auto destinationUseCandidates = remorse::itemGrabSearchCandidates( *integratedAvatar, integratedStartupWorld.mapItems(), *typeFlags); assert(destinationUseCandidates); @@ -417,6 +499,530 @@ int main() } } assert(eligibleMapUseItems == 218 && keycardUseItems == 10 && boxItem); + struct RankedUseTarget { + remorse::u32 distance = 0; + remorse::u16 itemNumber = 0; + remorse::u16 classId = 0; + std::string className; + }; + std::vector rankedUseTargets; + for (const auto& item : *stagedItems) { + if (item.data.shape >= typeFlags->size()) continue; + const auto& shape = (*typeFlags)[item.data.shape]; + const remorse::UsecodeItemIdentity targetIdentity{item.itemNumber, item.data.shape, + item.data.flags, item.data.quality, shape.family, false}; + const auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + targetIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); + if (!eligible) continue; + const remorse::s32 targetX = item.data.x; + const remorse::s32 targetY = item.data.y; + const remorse::s32 startX = integratedAvatar->data.x; + const remorse::s32 startY = integratedAvatar->data.y; + const auto absDelta = [](remorse::s32 left, remorse::s32 right) { + return left < right ? right - left : left - right; + }; + rankedUseTargets.push_back({static_cast( + absDelta(targetX, startX) + absDelta(targetY, startY)), item.itemNumber, + eligible->classId, eligible->className}); + } + std::sort(rankedUseTargets.begin(), rankedUseTargets.end(), [](const auto& left, const auto& right) { + return left.distance < right.distance; + }); + std::cout << "Nearest map-1 use targets from destination pad:\n"; + for (std::size_t index = 0; index < std::min(12, rankedUseTargets.size()); ++index) { + const auto& target = rankedUseTargets[index]; + const auto* item = integratedStartupWorld.findItem(target.itemNumber); + assert(item); + std::cout << " item " << target.itemNumber << " distance " << target.distance << " xy " + << item->data.x << ',' << item->data.y << ',' << static_cast(item->data.z) + << " shape/frame/quality/flags " << item->data.shape << '/' << static_cast(item->data.frame) + << '/' << item->data.quality << '/' << item->data.flags << " class " << target.className + << " (" << target.classId << ")\n"; + } + constexpr remorse::s32 routeStep = 16; + constexpr remorse::s32 routeRadius = 8192; + constexpr remorse::s32 routeSide = routeRadius * 2 / routeStep + 1; + constexpr remorse::s32 routeCenter = routeRadius / routeStep; + constexpr std::size_t maximumExpandedNodes = 30000; + remorse::LiveFixedMapItems approachWorld(*stagedItems); + assert(approachWorld.initializeAvatar() && approachWorld.teleportAvatar(*levelStartEgg, 1)); + const auto* approachAvatar = approachWorld.findItem(1); + assert(approachAvatar); + const remorse::StagedFixedMapItem searchOrigin = *approachAvatar; + const remorse::WorldPoint routeStart{searchOrigin.data.x, searchOrigin.data.y, searchOrigin.data.z}; + std::vector elevationCompatibleTargets; + for (const auto& target : rankedUseTargets) { + const auto* item = approachWorld.findItem(target.itemNumber); + assert(item); + if (remorse::classifyItemFindZMatch(searchOrigin, (*typeFlags)[searchOrigin.data.shape], + *item, (*typeFlags)[item->data.shape], 3) != 0) { + elevationCompatibleTargets.push_back(item); + } + } + std::cout << "Use targets matching spawn elevation: " << elevationCompatibleTargets.size() << '\n'; + for (std::size_t index = 0; index < std::min(12, elevationCompatibleTargets.size()); ++index) { + const auto* item = elevationCompatibleTargets[index]; + std::cout << " item " << item->itemNumber << " at " << item->data.x << ',' << item->data.y + << ',' << static_cast(item->data.z) << '\n'; + } + struct RouteGoalArea { + remorse::s32 minX; + remorse::s32 maxX; + remorse::s32 minY; + remorse::s32 maxY; + }; + const auto& avatarShape = (*typeFlags)[searchOrigin.data.shape]; + std::vector routeGoalAreas; + for (const auto* target : elevationCompatibleTargets) { + const auto& targetShape = (*typeFlags)[target->data.shape]; + const remorse::s32 minX = std::max({static_cast(target->data.x) - 0x100, + static_cast(target->data.x) - static_cast(targetShape.x) * 16 + 1, 0}); + const remorse::s32 maxX = std::min(static_cast(target->data.x) + + static_cast(avatarShape.x) * 16 - 1, 0x7fff); + const remorse::s32 minY = std::max({static_cast(target->data.y) - 0x100, + static_cast(target->data.y) - static_cast(targetShape.y) * 16 + 1, 0}); + const remorse::s32 maxY = std::min(static_cast(target->data.y) + + static_cast(avatarShape.y) * 16 - 1, 0x7fff); + if (minX <= maxX && minY <= maxY) { + routeGoalAreas.push_back({minX, maxX, minY, maxY}); + } + } + const auto routeCell = [&](const remorse::WorldPoint& point) { + const remorse::s32 gridX = (point.x - routeStart.x) / routeStep + routeCenter; + const remorse::s32 gridY = (point.y - routeStart.y) / routeStep + routeCenter; + assert(gridX >= 0 && gridX < routeSide && gridY >= 0 && gridY < routeSide); + return static_cast(gridY * routeSide + gridX); + }; + const auto pointForRouteCell = [&](int cell) { + const auto index = static_cast(cell); + const remorse::s32 gridX = static_cast(index % routeSide) - routeCenter; + const remorse::s32 gridY = static_cast(index / routeSide) - routeCenter; + return remorse::WorldPoint{routeStart.x + gridX * routeStep, + routeStart.y + gridY * routeStep, routeStart.z}; + }; + const auto distanceToRange = [](remorse::s32 value, remorse::s32 minimum, remorse::s32 maximum) { + return value < minimum ? minimum - value : value > maximum ? value - maximum : 0; + }; + const auto routeHeuristic = [&](const remorse::WorldPoint& point) { + remorse::s32 bestDistance = std::numeric_limits::max(); + for (const auto& area : routeGoalAreas) { + const remorse::s32 distance = distanceToRange(point.x, area.minX, area.maxX) + + distanceToRange(point.y, area.minY, area.maxY); + bestDistance = std::min(bestDistance, (distance + routeStep - 1) / routeStep); + } + return bestDistance == std::numeric_limits::max() ? 0 : bestDistance; + }; + struct RouteOpenEntry { + remorse::s32 estimate; + remorse::s32 distance; + int cell; + }; + struct RouteOpenOrder { + bool operator()(const RouteOpenEntry& left, const RouteOpenEntry& right) const + { + if (left.estimate != right.estimate) return left.estimate > right.estimate; + return left.distance < right.distance; + } + }; + const std::size_t routeCellCount = static_cast(routeSide * routeSide); + std::vector routeDistances(routeCellCount, std::numeric_limits::max()); + std::vector routeParents(routeCellCount, -2); + const int startCell = static_cast(routeCell(routeStart)); + routeDistances[static_cast(startCell)] = 0; + routeParents[static_cast(startCell)] = -1; + std::priority_queue, RouteOpenOrder> openRoutes; + openRoutes.push({routeHeuristic(routeStart), 0, startCell}); + int targetCell = -1; + remorse::u16 approachTargetItem = 0; + std::size_t expandedNodes = 0; + constexpr std::array, 4> routeDirections{{ + {routeStep, 0}, {-routeStep, 0}, {0, routeStep}, {0, -routeStep}}}; + while (!openRoutes.empty() && targetCell < 0 && expandedNodes < maximumExpandedNodes) { + const RouteOpenEntry entry = openRoutes.top(); + openRoutes.pop(); + const std::size_t currentCellIndex = static_cast(entry.cell); + if (entry.distance != routeDistances[currentCellIndex]) continue; + ++expandedNodes; + const remorse::WorldPoint current = pointForRouteCell(entry.cell); + remorse::StagedFixedMapItem currentOrigin = searchOrigin; + currentOrigin.data.x = static_cast(current.x); + currentOrigin.data.y = static_cast(current.y); + const auto& originShape = (*typeFlags)[currentOrigin.data.shape]; + const auto interactionArea = remorse::itemFindAreaAroundItem(currentOrigin, originShape); + const auto targetCandidate = std::find_if(elevationCompatibleTargets.begin(), + elevationCompatibleTargets.end(), [&](const auto* candidate) { + return candidate->data.x >= interactionArea.minX && candidate->data.x <= interactionArea.maxX && + candidate->data.y >= interactionArea.minY && candidate->data.y <= interactionArea.maxY && + remorse::classifyItemFindZMatch(currentOrigin, originShape, *candidate, + (*typeFlags)[candidate->data.shape], 3) != 0; + }); + if (targetCandidate != elevationCompatibleTargets.end()) { + approachTargetItem = (*targetCandidate)->itemNumber; + targetCell = entry.cell; + break; + } + assert(approachWorld.moveItem(1, static_cast(current.x), + static_cast(current.y), static_cast(current.z))); + for (const auto [deltaX, deltaY] : routeDirections) { + const remorse::WorldPoint destination{current.x + deltaX, current.y + deltaY, current.z}; + if (destination.x < 0 || destination.x > 0x7fff || destination.y < 0 || destination.y > 0x7fff || + destination.x < routeStart.x - routeRadius || destination.x > routeStart.x + routeRadius || + destination.y < routeStart.y - routeRadius || destination.y > routeStart.y + routeRadius) { + continue; + } + const std::size_t cell = routeCell(destination); + const int nextDistance = entry.distance + 1; + if (nextDistance >= routeDistances[cell]) continue; + const auto sweep = remorse::resolveSolidLiveSweep(approachWorld, 1, destination, + *typeFlags, remorse::calculateFastAreaRange(current)); + if (!sweep || sweep->failed || sweep->failedDirections != 0 || + sweep->destination.x != destination.x || sweep->destination.y != destination.y || + sweep->destination.z != destination.z) { + continue; + } + routeDistances[cell] = nextDistance; + routeParents[cell] = entry.cell; + openRoutes.push({nextDistance + routeHeuristic(destination), nextDistance, + static_cast(cell)}); + } + } + std::cout << "Route search expanded " << expandedNodes << " nodes\n"; + assert(targetCell >= 0); + std::vector approachRoute; + for (int cell = targetCell; cell >= 0;) { + approachRoute.push_back(pointForRouteCell(cell)); + cell = routeParents[static_cast(cell)]; + } + std::reverse(approachRoute.begin(), approachRoute.end()); + const remorse::u16 routeGoalItem = approachTargetItem; + assert(approachWorld.teleportAvatar(*levelStartEgg, 1)); + for (std::size_t index = 1; index < approachRoute.size(); ++index) { + const auto& current = approachRoute[index - 1]; + const auto& destination = approachRoute[index]; + const auto sweep = remorse::resolveSolidLiveSweep(approachWorld, 1, destination, + *typeFlags, remorse::calculateFastAreaRange(current)); + assert(sweep && !sweep->failed && sweep->failedDirections == 0 && + sweep->destination.x == destination.x && sweep->destination.y == destination.y && + sweep->destination.z == destination.z); + assert(approachWorld.moveItem(1, static_cast(destination.x), + static_cast(destination.y), static_cast(destination.z))); + } + const auto* endpointAvatar = approachWorld.findItem(1); + assert(endpointAvatar); + const auto endpointCandidates = remorse::itemGrabSearchCandidates(*endpointAvatar, + approachWorld.mapItems(), *typeFlags); + assert(endpointCandidates && std::any_of(endpointCandidates->begin(), endpointCandidates->end(), + [&](const auto& candidate) { return candidate.itemNumber == routeGoalItem; })); + std::optional approachEvent; + approachTargetItem = 0; + for (const auto& candidate : *endpointCandidates) { + const auto* item = approachWorld.findItem(candidate.itemNumber); + if (item == nullptr || item->data.shape >= typeFlags->size()) continue; + const auto& shape = (*typeFlags)[item->data.shape]; + const remorse::UsecodeItemIdentity interactionIdentity{item->itemNumber, item->data.shape, + item->data.flags, item->data.quality, shape.family, false}; + auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + interactionIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); + if (eligible) { + approachTargetItem = item->itemNumber; + approachEvent = std::move(*eligible); + break; + } + } + assert(approachEvent); + const auto* approachTarget = approachWorld.findItem(approachTargetItem); + assert(approachTarget); + auto targetRenderer = remorse::loadMapSceneRenderer(*root, 1); + assert(targetRenderer); + remorse::MapRenderOptions targetRenderOptions; + targetRenderOptions.mapIndex = 1; + targetRenderOptions.maxWidth = 320; + targetRenderOptions.maxHeight = 200; + const remorse::WorldPoint targetWorldLocation{approachTarget->data.x * 2, + approachTarget->data.y * 2, approachTarget->data.z}; + targetRenderOptions.viewCenter = targetWorldLocation; + targetRenderOptions.worldRect = remorse::WorldRect{targetWorldLocation.x - 1, + targetWorldLocation.y - 1, targetWorldLocation.x + 1, targetWorldLocation.y + 1}; + const auto targetBefore = targetRenderer->render(targetRenderOptions, &approachWorld); + assert(targetBefore); + const remorse::u16 originalTargetShape = approachTarget->data.shape; + const remorse::u8 originalTargetFrame = approachTarget->data.frame; + constexpr remorse::u16 interactionProcessId = 0x0340; + remorse::UsecodeTaskRegistry interactionTasks; + auto interactionContext = remorse::createUsecodeEventContext(interactionTasks.runtimeMemory(), + *retailOwnerRows, approachEvent->classId, 1, approachTargetItem, approachEvent->body.bytes, 2); + auto interactionTaskValue = remorse::UsecodeProcessTask::create(interactionProcessId, + approachEvent->classId, 1, approachTargetItem, approachEvent->body.bytes, 2); + assert(interactionContext && interactionTaskValue); + const std::vector interactionProcessIdBytes{0x40, 0x03}; + assert(interactionTasks.runtimeMemory().write(interactionContext->processIdOutput, + interactionProcessIdBytes)); + assert(interactionTasks.addWithContext(std::move(*interactionTaskValue), std::move(*interactionContext))); + auto* interactionTask = interactionTasks.find(interactionProcessId); + assert(interactionTask); + remorse::UsecodeOpcodeServices interactionServices; + interactionServices.readFarWord = [interactionTask](remorse::u16 offset, remorse::u16 segment) + -> std::optional { + return interactionTask->readMappedFarWord(remorse::FarPtr16{offset, segment}); + }; + interactionServices.setInfo = [](remorse::u16, remorse::u16) { return true; }; + interactionServices.processCount = []() { return remorse::u16{2}; }; + interactionServices.currentProcessId = []() { return interactionProcessId; }; + std::optional> rejectedEvent; + interactionServices.callEvent = [&usecode, interactionTask, &rejectedEvent]( + remorse::u16 classId, remorse::u16 eventSlot) + -> std::optional { + std::cout << "Nested event call from " << interactionTask->classId << '/' + << interactionTask->eventSlot << " pc " << interactionTask->programCounter + << " BP " << interactionTask->frameBaseOffset << " stack " + << interactionTask->interpreter.stackTop << ':'; + for (std::size_t index = interactionTask->interpreter.stackTop; + index < std::min(interactionTask->interpreter.valueStack.size(), + interactionTask->interpreter.stackTop + 12); ++index) { + std::cout << ' ' << static_cast(interactionTask->interpreter.valueStack[index]); + } + std::cout << " frame:"; + for (std::size_t index = 0x30; index < 0x50; ++index) { + std::cout << ' ' << static_cast(interactionTask->frame[index]); + } + std::cout << '\n'; + const auto usecodeClass = remorse::loadUsecodeClass(*usecode, classId); + auto body = usecodeClass + ? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt; + if (!body) rejectedEvent = std::pair{classId, eventSlot}; + return body; + }; + remorse::u16 nextInteractionChildId = 0x0350; + std::vector> spawnedInteractionEvents; + std::optional> rejectedSpawn; + interactionServices.spawn = [&usecode, &nextInteractionChildId, &spawnedInteractionEvents, + &rejectedSpawn](remorse::u16 classId, + remorse::u16 eventSlot, remorse::u8, remorse::u8, remorse::u16, const remorse::u8*) + -> std::optional { + const auto usecodeClass = remorse::loadUsecodeClass(*usecode, classId); + const auto body = usecodeClass + ? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt; + if (!body) { + rejectedSpawn = std::pair{classId, eventSlot}; + return std::nullopt; + } + spawnedInteractionEvents.emplace_back(classId, eventSlot); + return nextInteractionChildId++; + }; + std::optional rejectedIntrinsic; + std::vector> interactionIntrinsics; + std::vector> queriedShapeFamilies; + std::vector> queriedItemFamilies; + interactionServices.callIntrinsic = [interactionTask, &approachWorld, &typeFlags, + &rejectedIntrinsic, &interactionIntrinsics, &queriedShapeFamilies, + &queriedItemFamilies]( + remorse::u16 ordinal, remorse::u8 argumentBytes, const remorse::u8* arguments) + -> std::optional { + interactionIntrinsics.emplace_back(ordinal, argumentBytes); + if (ordinal == 0x00 && argumentBytes == 0) return remorse::u16{0}; + if (ordinal == 0xfd && argumentBytes == 2) return remorse::u16{0}; + if (ordinal == 0xac && argumentBytes == 2) { + const remorse::u16 shape = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + if (shape >= typeFlags->size()) return std::nullopt; + const remorse::u16 family = (*typeFlags)[shape].family; + queriedShapeFamilies.emplace_back(shape, family); + return family; + } + if ((ordinal == 0x15 || ordinal == 0x3a) && argumentBytes == 6) return remorse::u16{0}; + if (argumentBytes < 4) { + rejectedIntrinsic = ordinal; + 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)); + if (ordinal == 0x0a && argumentBytes == 4) { + const auto itemNumber = interactionTask->readMappedFarWord(remorse::FarPtr16{offset, segment}); + if (itemNumber) approachWorld.destroyItem(*itemNumber); + return remorse::u16{0}; + } + if (ordinal == 0x30 && argumentBytes == 4) { + return approachWorld.popItemFromEtherealVoid().value_or(0); + } + if (ordinal == 0x20 && argumentBytes == 10) { + const remorse::u16 x = static_cast(arguments[4] | + (static_cast(arguments[5]) << 8)); + const remorse::u16 y = static_cast(arguments[6] | + (static_cast(arguments[7]) << 8)); + return approachWorld.popItemToCoords(x, y, arguments[8]).value_or(0); + } + if (ordinal == 0x19 && argumentBytes == 14) { + const remorse::u16 shape = static_cast(arguments[4] | + (static_cast(arguments[5]) << 8)); + const remorse::u16 frame = static_cast(arguments[6] | + (static_cast(arguments[7]) << 8)); + const remorse::u16 x = static_cast(arguments[8] | + (static_cast(arguments[9]) << 8)); + const remorse::u16 y = static_cast(arguments[10] | + (static_cast(arguments[11]) << 8)); + const remorse::u8 z = arguments[12]; + const bool legalPosition = frame <= 0xff && + approachWorld.canCreateItemAt(shape, x, y, z, *typeFlags); + if (!legalPosition) { + return remorse::u16{0}; + } + remorse::StagedFixedMapItem createdItem; + createdItem.recordIndex = static_cast(-1); + createdItem.data.x = x; + createdItem.data.y = y; + createdItem.data.z = z; + createdItem.data.shape = shape; + createdItem.data.frame = static_cast(frame); + const auto itemNumber = approachWorld.allocateItem(createdItem); + if (!itemNumber || !interactionTask->writeMappedFarWord( + remorse::FarPtr16{offset, segment}, *itemNumber)) { + return remorse::u16{0}; + } + return remorse::u16{1}; + } + const auto itemNumber = interactionTask->readMappedFarWord(remorse::FarPtr16{offset, segment}); + if (ordinal == 0x10 && argumentBytes == 4) { + const auto* item = itemNumber ? approachWorld.findItem(*itemNumber) : nullptr; + return item ? static_cast(item->data.quality & 0xff) : remorse::u16{0}; + } + if (!itemNumber) return std::nullopt; + const auto* item = approachWorld.findItem(*itemNumber); + if (ordinal == 0x3c && argumentBytes == 4 && item && item->data.shape < typeFlags->size()) { + const remorse::u16 family = (*typeFlags)[item->data.shape].family; + queriedItemFamilies.emplace_back(*itemNumber, family); + return family; + } + if (ordinal == 0x22 && argumentBytes == 4 && item) { + return approachWorld.pushItemToEtherealVoid(*itemNumber) + ? std::optional{remorse::u16{0}} : std::nullopt; + } + if (ordinal == 0x25) return remorse::u16{0}; + if (ordinal == 0xea && argumentBytes == 4 && item) { + return static_cast(item->data.quality & 0xff); + } + if (ordinal == 0x01 && argumentBytes == 4 && item) return item->data.frame; + if (ordinal == 0x03 && argumentBytes == 4 && item) return item->data.mapNumber; + if (ordinal == 0x09 && argumentBytes == 4 && item) return item->data.z; + if (ordinal == 0x13 && argumentBytes == 4 && item) return item->data.x; + if (ordinal == 0x14 && argumentBytes == 4 && item) return item->data.y; + if (ordinal == 0x24 && argumentBytes == 6) { + const remorse::u16 shape = static_cast(arguments[4] | + (static_cast(arguments[5]) << 8)); + return approachWorld.setItemShape(*itemNumber, shape) + ? std::optional{remorse::u16{0}} : std::nullopt; + } + if ((ordinal == 0x02 || ordinal == 0x59) && argumentBytes == 6) { + const remorse::u8 frame = static_cast(arguments[4] | + (static_cast(arguments[5]) << 8)); + return approachWorld.setItemFrame(*itemNumber, frame) + ? std::optional{remorse::u16{0}} : std::nullopt; + } + rejectedIntrinsic = ordinal; + return std::nullopt; + }; + remorse::UsecodeStepResult lastInteractionResult = remorse::UsecodeStepResult::Advanced; + bool interactionStoppedOnError = false; + bool reachedInteractionMilestone = false; + bool targetVisualChanged = false; + const remorse::u16 originalTargetFlags = approachTarget->data.flags; + const std::size_t originalWorldItemCount = approachWorld.mapItems().size(); + const auto targetRenderHasChanged = [&]() { + const auto image = targetRenderer->render(targetRenderOptions, &approachWorld); + return image && image->pixels.size() == targetBefore->pixels.size() && + !std::equal(targetBefore->pixels.begin(), targetBefore->pixels.end(), image->pixels.begin(), + image->pixels.end(), [](const auto& left, const auto& right) { + return left.red == right.red && left.green == right.green && left.blue == right.blue; + }); + }; + for (unsigned tick = 0; tick < 8 && !reachedInteractionMilestone && !interactionTask->halted && + !interactionStoppedOnError; ++tick) { + interactionTask->interpreter.impliedProcessId = 0; + for (unsigned instruction = 0; instruction < 256; ++instruction) { + lastInteractionResult = interactionTask->step(interactionServices); + const auto* item = approachWorld.findItem(approachTargetItem); + targetVisualChanged = !item || item->data.shape != originalTargetShape || + item->data.frame != originalTargetFrame; + if (lastInteractionResult == remorse::UsecodeStepResult::Advanced || + lastInteractionResult == remorse::UsecodeStepResult::SetInfo || + lastInteractionResult == remorse::UsecodeStepResult::Spawned) { + if (!spawnedInteractionEvents.empty() && targetRenderHasChanged()) { + targetVisualChanged = true; + reachedInteractionMilestone = true; + break; + } + continue; + } + if (lastInteractionResult != remorse::UsecodeStepResult::Yielded && + lastInteractionResult != remorse::UsecodeStepResult::Returned) { + interactionStoppedOnError = true; + } + break; + } + } + const auto* finalInteractionTarget = approachWorld.findItem(approachTargetItem); + targetVisualChanged = targetVisualChanged || finalInteractionTarget == nullptr || + finalInteractionTarget->data.shape != originalTargetShape || + finalInteractionTarget->data.frame != originalTargetFrame || + finalInteractionTarget->data.flags != originalTargetFlags || + approachWorld.mapItems().size() != originalWorldItemCount; + std::cout << "Reachable target use event: class " << approachEvent->className << " (" + << approachEvent->classId << ") shape/frame " << originalTargetShape << '/' + << static_cast(originalTargetFrame) << " body bytes " << approachEvent->body.bytes.size() + << " VM result " << static_cast(lastInteractionResult) << " PC " + << interactionTask->programCounter << " class/event " << interactionTask->classId << '/' + << interactionTask->eventSlot << " call depth " << interactionTask->routineFrames.size() + << " rejected intrinsic " << rejectedIntrinsic.value_or(0xffff) << " rejected event " + << (rejectedEvent ? rejectedEvent->first : 0xffff) << '/' + << (rejectedEvent ? rejectedEvent->second : 0xffff) << " rejected spawn " + << (rejectedSpawn ? rejectedSpawn->first : 0xffff) << '/' + << (rejectedSpawn ? rejectedSpawn->second : 0xffff) << " spawned " + << spawnedInteractionEvents.size() << " changed " << targetVisualChanged << '\n'; + std::cout << "Selected target item " << approachTargetItem << " quality/flags " + << (finalInteractionTarget ? finalInteractionTarget->data.quality : 0) << '/' + << (finalInteractionTarget ? finalInteractionTarget->data.flags : 0) << '\n'; + for (const auto& [classId, eventSlot] : spawnedInteractionEvents) { + std::cout << " spawned usecode " << classId << '/' << eventSlot << '\n'; + } + std::cout << "Executed intrinsics:"; + for (const auto& [ordinal, argumentBytes] : interactionIntrinsics) { + std::cout << ' ' << ordinal << '/' << static_cast(argumentBytes); + } + std::cout << '\n'; + for (const auto& [shape, family] : queriedShapeFamilies) { + std::cout << " shape family " << shape << '=' << family << '\n'; + } + for (const auto& [itemNumber, family] : queriedItemFamilies) { + std::cout << " item family " << itemNumber << '=' << family << '\n'; + } + if (lastInteractionResult == remorse::UsecodeStepResult::UnsupportedOpcode) { + const std::size_t windowStart = interactionTask->programCounter > 4 + ? interactionTask->programCounter - 4 : remorse::usecodeEventBytecodeOffset; + const std::size_t windowEnd = std::min(interactionTask->code.size(), + interactionTask->programCounter + 8); + std::cout << "Unsupported usecode bytes:"; + for (std::size_t index = windowStart; index < windowEnd; ++index) { + std::cout << ' ' << index << ':' << static_cast(interactionTask->code[index]); + } + std::cout << '\n'; + } + assert(reachedInteractionMilestone && targetVisualChanged && !interactionStoppedOnError); + const auto targetAfter = targetRenderer->render(targetRenderOptions, &approachWorld); + assert(targetAfter && targetBefore->pixels.size() == targetAfter->pixels.size()); + const bool targetPixelsChanged = !std::equal(targetBefore->pixels.begin(), targetBefore->pixels.end(), + targetAfter->pixels.begin(), targetAfter->pixels.end(), [](const auto& left, const auto& right) { + return left.red == right.red && left.green == right.green && left.blue == right.blue; + }); + assert(targetPixelsChanged); + std::cout << "Visible target mutation: shape/frame " + << (finalInteractionTarget ? finalInteractionTarget->data.shape : 0xffff) << '/' + << (finalInteractionTarget ? static_cast(finalInteractionTarget->data.frame) : 0xff) + << " pixels changed " << targetPixelsChanged << '\n'; + std::cout << "Reachable target Item_Grab route: item " << approachTargetItem + << " steps " << approachRoute.size() - 1 << " expanded " << expandedNodes << " endpoint " + << approachRoute.back().x + << ',' << approachRoute.back().y << ',' << approachRoute.back().z << '\n'; const auto globPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GLOB.FLX"); const auto globs = globPath ? remorse::loadGlobObjects(*globPath) : std::nullopt; assert(globs); diff --git a/rebuild/remorse/tests/isometric_controls_tests.cpp b/rebuild/remorse/tests/isometric_controls_tests.cpp index 36bee98..8f8a074 100644 --- a/rebuild/remorse/tests/isometric_controls_tests.cpp +++ b/rebuild/remorse/tests/isometric_controls_tests.cpp @@ -51,6 +51,18 @@ int main() assert(commandController.takeCommandRequest()->command == remorse::ControllerCommand::OpenInventory); commandController.handleKeyEvent(0x39, 0, 1, 1, 0); assert(!commandController.takeCommandRequest()); + assert(remorse::controllerFireAttemptSuppressed(true, 0x39, 1, 1)); + assert(remorse::controllerFireAttemptSuppressed(true, 0x52, 1, 0)); + assert(!remorse::controllerFireAttemptSuppressed(true, 0x52, 1, 1)); + assert(!remorse::controllerFireAttemptSuppressed(true, 0x39, 0, 1)); + remorse::ControllerActorState sleepingFireActor; + sleepingFireActor.lastFireAttemptWentToSleep = true; + remorse::ControllerMovementState sleepingFireController; + sleepingFireController.setActorState(sleepingFireActor); + sleepingFireController.handleKeyEvent(0x39, 0, 1, 1, 1); + assert(!sleepingFireController.takeCommandRequest()); + sleepingFireController.handleKeyEvent(0x52, 0, 1, 1, 1); + assert(sleepingFireController.takeCommandRequest()->command == remorse::ControllerCommand::FireWeapon); remorse::ControllerActorState restrictedCommandActor; restrictedCommandActor.mapNumber = 0x40; commandController.setActorState(restrictedCommandActor); diff --git a/rebuild/remorse/tests/usecode_vm_tests.cpp b/rebuild/remorse/tests/usecode_vm_tests.cpp index 7126950..318db9e 100644 --- a/rebuild/remorse/tests/usecode_vm_tests.cpp +++ b/rebuild/remorse/tests/usecode_vm_tests.cpp @@ -10,6 +10,26 @@ int main() assert(emptyStack.has_value()); assert(!emptyStack->popWord().has_value()); assert(!emptyStack->popDword().has_value()); + auto loopScriptState = remorse::UsecodeInterpreterState::initialize({}); + assert(loopScriptState); + std::size_t loopScriptPc = 0; + std::vector loopScriptCode{0x74, 0x24}; + std::vector loopScriptFrame; + remorse::UsecodeOpcodeServices loopScriptServices; + assert(loopScriptState->step(loopScriptCode, loopScriptPc, loopScriptFrame, + remorse::usecodeFrameBaseOffset, loopScriptServices) == remorse::UsecodeStepResult::Advanced); + assert(loopScriptPc == 2 && loopScriptState->stackTop == 0xcb && + loopScriptState->valueStack[0xcb] == 0x24); + + auto multiplyState = remorse::UsecodeInterpreterState::initialize({}); + assert(multiplyState && multiplyState->pushWord(7) && multiplyState->pushWord(6)); + std::size_t multiplyPc = 0; + std::vector multiplyCode{0x1e}; + std::vector multiplyFrame; + assert(multiplyState->step(multiplyCode, multiplyPc, multiplyFrame, + remorse::usecodeFrameBaseOffset, loopScriptServices) == remorse::UsecodeStepResult::Advanced); + assert(multiplyState->popWord() == 42); + assert(emptyStack->pushDword(0x12345678)); const auto pushedDword = emptyStack->popDword(); assert(pushedDword.has_value() && *pushedDword == static_cast(0x12345678)); @@ -173,6 +193,21 @@ int main() assert(factoryTask->readMappedItemWord(remorse::FarPtr16{0x0100, 0}) == 0x1234 && !factoryTask->readMappedItemWord(remorse::FarPtr16{0x0100, 1}) && !factoryTask->readMappedItemWord(remorse::FarPtr16{0x0101, 0})); + std::vector addressCode(remorse::usecodeEventBytecodeOffset, 0); + addressCode.insert(addressCode.end(), {0x4b, 0xfe, 0x4c, 0x02, 0x50}); + auto addressTask = remorse::UsecodeProcessTask::create(6, 0x361, 0x0a, 0x1234, + std::move(addressCode), 0); + assert(addressTask); + addressTask->frame[remorse::usecodeFrameBaseOffset - 2] = 0x78; + addressTask->frame[remorse::usecodeFrameBaseOffset - 1] = 0x56; + remorse::UsecodeOpcodeServices addressServices; + addressServices.currentProcessId = [addressTask]() { return addressTask->processId; }; + addressServices.readFarWord = [addressTask](remorse::u16 offset, remorse::u16 segment) { + return addressTask->readMappedFarWord(remorse::FarPtr16{offset, segment}); + }; + assert(addressTask->step(addressServices) == remorse::UsecodeStepResult::Advanced); + assert(addressTask->step(addressServices) == remorse::UsecodeStepResult::Advanced); + assert(addressTask->interpreter.popWord() == 0x5678); auto noItemTask = remorse::UsecodeProcessTask::create(5, 0x361, 0x0a, 0x1234, std::vector(15, 0), 0); assert(noItemTask && noItemTask->interpreter.stackTop == 0xcc && diff --git a/rebuild/remorse/tools/clean-old-build-artifacts.ps1 b/rebuild/remorse/tools/clean-old-build-artifacts.ps1 new file mode 100644 index 0000000..1d952b4 --- /dev/null +++ b/rebuild/remorse/tools/clean-old-build-artifacts.ps1 @@ -0,0 +1,56 @@ +[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] +param( + [switch]$Apply +) + +$repoRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..\..')) +$outputRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\out')) +$allowedBuildDirectories = @('build-nmake', 'build-track-b') + +if (-not (Test-Path -LiteralPath $outputRoot -PathType Container)) { + throw "Expected generated output directory was not found: $outputRoot" +} + +$outputRootInfo = Get-Item -LiteralPath $outputRoot -Force +if (($outputRootInfo.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { + throw "Refusing to use a reparse-point output directory: $outputRoot" +} + +$repoPrefix = $repoRoot.TrimEnd('\') + '\' +if (-not $outputRoot.StartsWith($repoPrefix, [System.StringComparison]::OrdinalIgnoreCase)) { + throw "Output directory is outside the repository: $outputRoot" +} + +$outputPrefix = $outputRoot.TrimEnd('\') + '\' +$targets = [System.Collections.Generic.List[System.IO.DirectoryInfo]]::new() +foreach ($directoryName in $allowedBuildDirectories) { + $targetPath = [System.IO.Path]::GetFullPath((Join-Path $outputRoot $directoryName)) + if (-not $targetPath.StartsWith($outputPrefix, [System.StringComparison]::OrdinalIgnoreCase)) { + throw "Refusing to process a path outside the generated output directory: $targetPath" + } + if (-not (Test-Path -LiteralPath $targetPath -PathType Container)) { + Write-Output "Skip (not present): $targetPath" + continue + } + + $targetInfo = Get-Item -LiteralPath $targetPath -Force + if (($targetInfo.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { + throw "Refusing to remove a reparse-point build directory: $targetPath" + } + if (-not (Test-Path -LiteralPath (Join-Path $targetPath 'CMakeCache.txt') -PathType Leaf)) { + throw "Refusing to remove a directory without a CMake cache: $targetPath" + } + $targets.Add($targetInfo) +} + +foreach ($target in $targets) { + if (-not $Apply) { + Write-Output "Dry run; would remove generated CMake build directory: $($target.FullName)" + continue + } + + if ($PSCmdlet.ShouldProcess($target.FullName, 'Remove generated CMake build directory')) { + Remove-Item -LiteralPath $target.FullName -Recurse -Force + Write-Output "Removed: $($target.FullName)" + } +} \ No newline at end of file