Refactor USECODE tooling documentation and enhance map-viewer decompiler
- Updated the USECODE Tool Improvement Plan to focus on the map-viewer decompiler/editor, emphasizing its role as the primary development target for USECODE editing and recompilation. - Revised the tooling comparison document to include the newer map-viewer decompiler, clarifying its purpose and distinguishing it from the Python parser. - Introduced a new ClearAvatarInStasisProcessEntry structure in the entity dispatch entry header, along with related process creation and execution logic in the ProcessKernel. - Implemented the setItemShape method in LiveFixedMapItems to allow dynamic shape updates for items. - Enhanced the teleporter process to handle avatar stasis and integrated it into the game main loop, ensuring proper process management and state handling. - Added tests for the new functionality, including shape setting and teleporter process behavior, to ensure correctness and stability.
This commit is contained in:
parent
0771c86043
commit
6d4972933f
17 changed files with 1868 additions and 114 deletions
|
|
@ -1,4 +1,4 @@
|
|||
# USECODE Round-Trip IR Plan
|
||||
# USECODE Decompiler/Recompiler Roadmap
|
||||
|
||||
## Purpose
|
||||
|
||||
|
|
@ -6,6 +6,61 @@ This note records the current evidence-backed path from Crusader USECODE bytes t
|
|||
|
||||
It is intentionally conservative. ScummVM gives strong external anchors for the container layout, class/event numbering, and intrinsic naming, but it is not a symbol map for the DOS binary and it is not a ready-made round-trip compiler.
|
||||
|
||||
## Current Status
|
||||
|
||||
There is a useful but incomplete decompilation pipeline; there is not yet a USECODE recompiler in this workspace.
|
||||
|
||||
### Development Home
|
||||
|
||||
The primary product path for the USECODE editor/decompiler/recompiler is the newer map-viewer decompiler in the adjacent `crusader_map_viewer` repository, especially [usecode-decompiler.js](../../crusader_map_viewer/map_renderer/src/lib/usecode-decompiler.js) and its regression suite at `map_renderer/scripts/test-usecode-structuring.mjs`. Continue developing that implementation into the user-facing tool: improve its decompilation, then add safe source/IR editing, compilation, and archive rebuilding there.
|
||||
|
||||
Do not grow `tools/poc_crusader_usecode_parser.py` into a competing editor/compiler. Keep this repository's extractor, corpus, Python parser, and reverse-engineering notes as evidence sources, fixture generators, and cross-checks for the map-viewer implementation. The `rebuild/remorse` runtime model is also separate; it is not the product path for authoring or recompiling scripts.
|
||||
|
||||
Implemented:
|
||||
|
||||
- `tools/extract_eusecode_flx.py` extracts and indexes the owner-loaded FLEX/USECODE data, class headers, event rows, and derived body ranges. It also generates family reports and regression baselines.
|
||||
- `tools/poc_crusader_usecode_parser.py` produces per-slot JSON IR, byte-oriented listings, script-like output, and pseudocode. It preserves raw instruction bytes when decoding stops and has focused Python structuring tests.
|
||||
- The map-viewer decompiler already has newer structured-control-flow rendering and JavaScript regression tests. Treat that code as the primary implementation to improve; it currently does not provide the complete editable-source and recompilation path.
|
||||
- `rebuild/remorse` contains a runtime/archive model and interpreter work. It does not currently provide a USECODE source assembler or archive writer.
|
||||
|
||||
Not implemented yet:
|
||||
|
||||
- A complete archive/class-level editable source format and editor workflow. The map viewer now has an initial versioned per-event JSON source-document prototype, but it is not yet a complete editing contract.
|
||||
- A deterministic writer that rebuilds class records and FLEX archives.
|
||||
- An end-to-end test proving a modified compiled script runs correctly in Remorse or Regret.
|
||||
|
||||
The existing JSON and pseudocode outputs are analysis artifacts, not yet a supported edit-and-recompile format. Full VM semantic recovery is not a prerequisite for the first round-trip milestone: unknown bytes can remain opaque, provided their positions and any affected offsets are preserved or safely relocated.
|
||||
|
||||
## Milestones To Reach A Working In-Game Round Trip
|
||||
|
||||
Treat these as acceptance gates, not merely research topics. Keep Remorse and Regret variant-specific data separate where formats or intrinsic tables differ.
|
||||
|
||||
- [x] **M0 — Extract and index the source data.** Enumerate archive entries, class names/ids, raw headers, event rows, and body windows with bounds checks. Existing extractor outputs and repeated-family regression data cover this foundation.
|
||||
- [x] **M1 — Produce useful per-body decompilation artifacts.** Emit a machine-readable per-slot representation plus readable listing/pseudocode, and retain undecoded bytes instead of silently discarding them. Existing parsers/renderers provide these initial views; continue improving the map-viewer renderer as the primary decompiler.
|
||||
- [ ] **M2 — Freeze a versioned, lossless editable IR/source contract in the map viewer.** Versioned archive and per-event snapshots now preserve exact bytes, class/event/body offsets, variant identity, and name-hint provenance; the per-event v2 overlay supports guarded fixed-width immediate edits. JSON parse/serialize equality and no-op byte restoration are tested on both game archives, with per-event coverage for Remorse (`TRIGGER` slot `0x20`) and Regret (`BRIDGE` slot `0x22`). Extend and test the overlay for the edit operations the editor will expose, then connect the contract to the editor-facing workflow before closing the milestone.
|
||||
- [ ] **M3 — Turn the map-viewer decompiler into an editor and bounded compiler/assembler.** Add a user-facing way to edit source or structured IR; encode supported instructions and operands; resolve labels and relative branches; preserve opaque regions only when edits cannot invalidate their encoding or location. Reject unsupported/ambiguous edits with actionable errors.
|
||||
- [ ] **M4 — Rebuild class records and FLEX archives from the map-viewer workflow.** Recalculate code offsets, event rows, class-size/header fields, entry lengths/offsets, and affected metadata while preserving ordering, sparse ids, untouched entries, and unknown bytes. Keep original inputs unchanged and write to a separate output.
|
||||
- [ ] **M5 — Prove binary round trips and edit behavior with automated tests in the map-viewer path.** Require byte-for-byte identity for unchanged files and classes; add edited fixtures covering immediate-width changes, branch movement, strings, debug/local trailers, opaque opcodes, and both game variants. Reopen rebuilt outputs with an independent parser.
|
||||
- [ ] **M6 — Validate modified output in the game.** Start with a controlled, low-risk script change in a disposable game copy. Verify the intended behavior in game, check load/startup paths, and confirm unrelated scripts and archives still work. Repeat for each supported variant.
|
||||
- [ ] **M7 — Make the workflow repeatable for modders.** Provide documented commands, input/output safety checks, clear diagnostics, a supported-feature matrix, and a regression corpus so a user can decompile, edit, rebuild, and validate without manual binary surgery.
|
||||
|
||||
**Final objective is met only when M2–M7 pass:** an unchanged archive round-trips exactly, a supported script edit compiles into a rebuilt archive, and the modified game exhibits the intended behavior without breaking the target build.
|
||||
|
||||
The M2–M5 implementation and user workflow belong in the map-viewer USECODE decompiler/editor. This repository should continue supplying validated samples and independent checks, not a second end-user authoring pipeline.
|
||||
|
||||
### Versioned Source Snapshot Contract
|
||||
|
||||
The map-viewer currently has two complementary JSON snapshot forms:
|
||||
|
||||
- `crusader-usecode-archive-source` v1 stores the complete original FLEX file once as canonical base64, its byte length and SHA-256, the FLEX entry directory, and derived class/event/body index records.
|
||||
- `crusader-usecode-source` v2 stores one selected class/event view, including the exact original class bytes, six-byte event row, body bytes, game variant, descriptive decompilation IR, and an edit overlay.
|
||||
|
||||
The archive document owns the authoritative untouched source bytes. Directory records refer to exact byte positions in those bytes: event-table and body offsets are recorded both relative to their class and relative to the archive. Class names carry provenance (`owner_name_table` or `generated_fallback`); event labels explicitly carry hint provenance. The per-event document uses lowercase hex for preserved class/event/body byte slices; the archive document uses base64 for the single complete source archive. Archive SHA-256 and body SHA-1 values detect accidental mismatch; neither is a replacement for byte comparison.
|
||||
|
||||
For both forms, raw bytes and offsets are authoritative. Decoded instructions, intrinsic/event names, parsed strings, local/debug symbols, and field tags are descriptive metadata; the raw source still owns exact encoding, terminators, trailers, and unknown data. The v2 per-event overlay is separate from the immutable baseline and currently supports only guarded replacement of fixed-width `push_byte_immediate`, `push_word_immediate`, and `push_dword_immediate` operands. Each change is anchored to the original body digest, instruction offset, exact original instruction bytes, and original operand value, with width/range checks. An edited-IR preview applies these operands for rendering but explicitly retains the original raw bytes; it is not compiled output. Unsupported edit kinds must be rejected rather than silently approximated.
|
||||
|
||||
Tests currently verify JSON parse/serialize equality and exact byte restoration for real Remorse and Regret archives, plus consistency checks tying event/body metadata and immediate-edit overlays back to the preserved bytes. M2 remains open until overlays cover the intended editor operations (including strings and structured/debug metadata) and are connected to an editor-facing workflow. The overlay is not yet applied to rebuilt bytecode.
|
||||
|
||||
## Externally Anchored Pieces
|
||||
|
||||
### Container and class layout
|
||||
|
|
@ -30,7 +85,7 @@ ScummVM also makes one implementation choice explicit that matters for the curre
|
|||
|
||||
### Binary-side validation against owner-loaded classes
|
||||
|
||||
The first direct local validation pass against sampled owner-loaded EUSECODE class records now splits the ScummVM model into two parts: one part is confirmed, and one part still needs reconciliation.
|
||||
Direct local validation against sampled owner-loaded EUSECODE class records confirms the archive/class indexing and event-table structure, while narrowing the remaining disagreement to the interpretation of the header count/base arithmetic.
|
||||
|
||||
Confirmed on sampled records (`EVENT`, `NPCTRIG`, `SURCAMNS`, `JELYHACK`, `REE_BOOT`, `SURCAMEW`, `SFXTRIG`):
|
||||
|
||||
|
|
@ -115,25 +170,24 @@ The first script IR should preserve exact recompilation inputs before it tries t
|
|||
|
||||
## Current Parser Views
|
||||
|
||||
The current proof-of-concept parser now emits three complementary views for a single class/slot body:
|
||||
The Python proof-of-concept parser emits complementary research views for a single class/slot body. They are reference artifacts for the map-viewer product path, not a declaration that the map viewer already consumes this JSON as its editor/compiler format:
|
||||
|
||||
- JSON IR: the authoritative machine-facing output for tooling and any future assembler.
|
||||
- JSON IR: the machine-facing output for current research tools and a candidate schema source for the future editable map-viewer IR.
|
||||
- Flat text listing: a byte-faithful decode with offsets, raw bytes, and trailer sections.
|
||||
- Script view: a more readable block-labeled decompilation with locals, labels, and stack-VM statements.
|
||||
- Pseudocode view: a higher-level decompilation that tries to collapse common compare ladders and stack expressions into programming-language-like control flow.
|
||||
|
||||
The script and pseudocode views are intentionally descriptive rather than authoritative. They are meant to help read bodies like `NPCTRIG 0x0A` or `EVENT 0x0A` without losing the exact JSON IR that a round-trip compiler will need.
|
||||
The script and pseudocode views are intentionally descriptive rather than authoritative. They help inspect bodies like `NPCTRIG 0x0A` or `EVENT 0x0A`; the map-viewer implementation still needs a formally specified lossless editable representation before any compiler can rely on it.
|
||||
|
||||
## Deferred Readability Follow-Ups
|
||||
## Current Decompiler Boundary
|
||||
|
||||
Keep these parser-facing readability tasks for later while the current focus stays on broad pseudocode export and class-family understanding:
|
||||
The parser/renderer is a readability layer over partially decoded bytecode, not a semantic source-of-truth. Structured `if`/loop/switch output and intrinsic/event labels are helpful, but should not be used to regenerate bytes until the compiler contract and instruction encodings are specified.
|
||||
|
||||
1. Replace unresolved `class_XXXX_slot_YY` call labels with behavior-backed names where the compiled/runtime evidence is strong enough.
|
||||
2. Replace placeholder argument names such as `arg_06` with semantic names inferred from stable usage patterns.
|
||||
3. Detect more control-flow shapes beyond compare ladders, especially simple loops and early-return guards.
|
||||
4. Collapse common spawn/setup idioms into more domain-specific statements when the stack pattern is consistent.
|
||||
5. Run the pseudocode renderer across larger families like `EVENT`, `_BOOT`, and `SURCAM*` and tighten the heuristics where they still leak VM structure.
|
||||
6. Add small behavior-level comments only where they help explain gameplay meaning rather than VM mechanics.
|
||||
Remaining decompiler work should be driven by concrete corpus failures and semantic regressions, rather than the old open-ended readability list. In particular:
|
||||
|
||||
- Keep unresolved calls, locals, and event labels neutral unless binary evidence supports stronger names.
|
||||
- Grow opcode and operand coverage using known-good fixtures, with exact raw-byte preservation for unsupported forms.
|
||||
- Track control-flow rendering gaps as decompiler issues, independently from compiler/round-trip milestones.
|
||||
|
||||
### Unit of decompilation
|
||||
|
||||
|
|
@ -767,43 +821,21 @@ For the current owner-loaded EUSECODE and round-trip IR work, the safest reversi
|
|||
- If the divisibility or bounds checks fail, keep the class opaque and preserve raw bytes rather than forcing a guessed event count.
|
||||
- `tools/extract_eusecode_flx.py` now implements this rule directly for the current owner-loaded EUSECODE work and emits `class_layout_index.tsv` plus `class_event_index.tsv` so raw header/event rows can be consumed by later IR tooling without re-deriving the arithmetic from prose.
|
||||
|
||||
## Remaining Binary-Side Gaps
|
||||
|
||||
The main blockers for a real round-trip compiler are still on the binary side:
|
||||
## Open Format And Runtime Questions
|
||||
|
||||
- The meaning of the first two bytes in each 6-byte Crusader event record is still unverified.
|
||||
- The exact provenance of ScummVM's current `get_class_event_count()` arithmetic is still unverified; current local evidence says the owner-loaded/raw records fit `raw_u32_at_8_11 = first_code_byte_offset`, while the ScummVM count formula appears sign-shifted relative to that layout.
|
||||
- The exact provenance of ScummVM's `get_class_event_count()` arithmetic is still unverified; local owner-loaded records fit `raw_u32_at_8_11 = first_code_byte_offset`, while the ScummVM count formula appears sign-shifted relative to that layout. Preserve raw fields and use the locally validated bounds rule for now.
|
||||
- The upstream writer for selector local `[BP-0x32]` in the `000d:ebe3` sequencer is still unresolved.
|
||||
- The full control-flow opcode set and branch encoding are not yet recovered.
|
||||
- The full control-flow opcode set and branch encoding are not yet recovered. This limits safe semantic edits, but does not prevent a first opaque-preserving, bounded assembler.
|
||||
- The exact on-disk source format behind `entity_vm_runtime_owner_resource_create` is still not identified.
|
||||
- No direct descriptor-family to slot-mask mapping is proven yet.
|
||||
- Callback/eventTrigger descriptors still do not have a callback-specific opcode family.
|
||||
|
||||
## Best Current Path
|
||||
These questions matter for deeper semantic decompilation and broader editing support. They are not all gates for a byte-preserving no-op round trip; the compiler milestones above define the required acceptance tests.
|
||||
|
||||
The strongest present path to a usable compiler/decompiler is:
|
||||
## Historical Decompiler Work (completed milestones; not a current task list)
|
||||
|
||||
1. Parse classes/events exactly as ScummVM does.
|
||||
2. Keep the class/object indexing and event-entry layout from ScummVM, but use the conservative local event-count rule above for owner-loaded/raw class parsing until a main USECODE sample proves otherwise.
|
||||
3. Decompile only the proven operator families into structured IR.
|
||||
4. Preserve unknown bytes verbatim in place.
|
||||
5. Attach ScummVM event and intrinsic names as hints, not as truth.
|
||||
6. Recompile by rebuilding the original class header and event table layout first, then re-emitting decoded and opaque ops together.
|
||||
|
||||
That gets to a reversible editor sooner than waiting for a full semantic VM recovery.
|
||||
|
||||
## **Recent Research (2026-03-26)**
|
||||
|
||||
- **Root Cause:**: The structuring pass left forward/back-edge loops and counted-loop headers detached in fallback output, which produced unstructured pseudocode for some bodies (notably BART slot 0x0F).
|
||||
- **Renderer Fixes:**: Added a conservative loop-lifting helper and a restricted infinite-loop lift in the partial fallback renderer to fold loops into structured blocks where safe. See the modified renderer at [tools/poc_crusader_usecode_parser.py](tools/poc_crusader_usecode_parser.py).
|
||||
- **Validator Added:**: A lightweight pseudocode syntax/label validator was added to detect brace mismatches and missing goto/label targets before exporting pseudocode.
|
||||
- **Tests:**: Added and adjusted unit tests in [tools/tests/test_usecode_structuring.py](tools/tests/test_usecode_structuring.py) to guard loop-lifting behavior and fallback conservatism.
|
||||
- **Corpus Validation:**: Ran a corpus-wide render+validator pass over 977 decoded bodies; result: `TOTAL_BODIES=977, FAILURES=0` (no syntax/label failures).
|
||||
- **Real-World Output:**: Regenerated the BART pseudocode file — [USECODE/EUSECODE_extracted/pseudocode/BART/slot_0F_enterFastArea.txt](USECODE/EUSECODE_extracted/pseudocode/BART/slot_0F_enterFastArea.txt) now shows an outer `while(true)` with nested structured branches and counted loops instead of detached labels.
|
||||
- **Scope & Safety:**: Fully-structured renderer remains conservative; the loop-lifting helper is reused where safe. The outer infinite-loop lift was narrowed to partial fallback after tests revealed regressions when it was too broad.
|
||||
- **Remaining Semantic Gap:**: Expression/comparison operand polarity still needs correction (some counted-loop conditions show inverted comparisons). Next work: fix operand ordering in the expression builder so loop headers reflect correct comparison direction.
|
||||
- **Next Steps:**: (1) Implement compare-direction fix in the expression builder and add small semantic regression tests, (2) re-run unit tests and a corpus-wide render+validate sweep, (3) regenerate affected pseudocode files for inspection.
|
||||
- **Files of Interest:**: [tools/poc_crusader_usecode_parser.py](tools/poc_crusader_usecode_parser.py), [tools/tests/test_usecode_structuring.py](tools/tests/test_usecode_structuring.py), [USECODE/EUSECODE_extracted/pseudocode/BART/slot_0F_enterFastArea.txt](USECODE/EUSECODE_extracted/pseudocode/BART/slot_0F_enterFastArea.txt).
|
||||
The 2026-03-26 renderer pass added conservative loop lifting, a syntax/label validator, and corpus export checks (the then-current export contained 977 bodies). Subsequent work corrected comparison/branch semantics and added further renderer regressions; the comparison-polarity action item from that pass is closed.
|
||||
|
||||
## **Recent Renderer Work (2026-03-31)**
|
||||
|
||||
|
|
@ -811,7 +843,7 @@ That gets to a reversible editor sooner than waiting for a full semantic VM reco
|
|||
- **VM Semantics Fix:**: The JS renderer in [src/lib/usecode-decompiler.js](k:/ghidra/crusader_map_viewer/map_renderer/src/lib/usecode-decompiler.js) now follows the Pentagram/ScummVM VM for two core cases: opcode `0x24 cmp` is equality, not inequality, and opcode `0x51 IF` is a relative branch on false, not on true.
|
||||
- **Readability Impact:**: False branches are now emitted with the negated high-level condition, so the existing structurer can recover counted loops as `while (counter <= limit)` instead of the previously inverted `while (counter > limit)` pattern.
|
||||
- **Regression Coverage:**: Added a focused renderer-side regression script at [scripts/test-usecode-structuring.mjs](k:/ghidra/crusader_map_viewer/map_renderer/scripts/test-usecode-structuring.mjs) to guard one equality-based selector case and one counted-loop case.
|
||||
- **Next Steps:**: Rebuild a fresh renderer usecode cache and inspect representative families like `BART`, `_BOOT`, and `EVENT` for any remaining cases where other compare producers still leak VM-oriented phrasing.
|
||||
The follow-up work below continued across the representative families; treat any remaining renderer gaps as corpus-specific issues, not as an open task to rebuild that cache.
|
||||
|
||||
## **Recent Renderer Work (2026-04-01)**
|
||||
|
||||
|
|
@ -833,7 +865,6 @@ That gets to a reversible editor sooner than waiting for a full semantic VM reco
|
|||
- **Renderer Fixes:**: [src/lib/usecode-decompiler.js](k:/ghidra/crusader_map_viewer/map_renderer/src/lib/usecode-decompiler.js) now lifts `create_list` into list literals such as `[item]` and `append_list` into list concatenation expressions instead of leaving raw comment placeholders. That closes the common temporary-worklist patterns in bridge/trigger/free scripts where the old output showed `/* create_list */` and `/* append_list */` immediately before an assignment.
|
||||
- **False-Branch Fix:**: The same renderer pass now treats compound boolean expressions conservatively when inverting Crusader's `0x51` false-branch. For simple comparisons it still flips the operator directly, but for composed `&&` / `||` expressions it now emits a whole-expression negation rather than corrupting the leftmost compare. This fixes the broken `BRO_BOOT.slot_0F` entry test that previously rendered as `global[0x001f] != 2 || global[0x001f] == 3 ...` even though the bytecode is a plain OR-chain of equality compares.
|
||||
- **Selector Readability:**: Long same-selector equality ladders that share one join target now render as `switch (...)` blocks when every branch is a simple equality case. The immediate real-data win is [BRO_BOOT/slot_0A_equip.txt](k:/ghidra/crusader_map_viewer/map_renderer/.cache/usecode/remorse/EUSECODE/pseudocode/BRO_BOOT/slot_0A_equip.txt), whose repeated `global[0x001f] == N` movie dispatch chain now decompiles as a switch instead of six `else if` arms.
|
||||
- **BRO_BOOT Structuring Impact:**: With the compound-condition fix in place, [BRO_BOOT/slot_0F_enterFastArea.txt](k:/ghidra/crusader_map_viewer/map_renderer/.cache/usecode/remorse/EUSECODE/pseudocode/BRO_BOOT/slot_0F_enterFastArea.txt) is expected to collapse into one structured `if/else` around the two `SPANEL` scans plus the trailing infinite animation loop, instead of keeping `entry:` / `block_0454`-style fallbacks.
|
||||
- **Regression Coverage:**: [scripts/test-usecode-structuring.mjs](k:/ghidra/crusader_map_viewer/map_renderer/scripts/test-usecode-structuring.mjs) now adds synthetic regressions for list-literal lifting, compound false-branch negation, and switch rendering, plus real-data regressions for `BRO_BOOT.slot_0A` and `BRO_BOOT.slot_0F`.
|
||||
|
||||
## **Recent Renderer Work (2026-04-02, CHANGER selector close)**
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue