From 8907604b843156e59acafcfc78f7e09b6f8a7e8a Mon Sep 17 00:00:00 2001 From: MaddoScientisto Date: Mon, 27 Apr 2026 21:15:01 +0200 Subject: [PATCH 01/14] Add core functionality for loading and processing game assets - Implemented palette loading from binary files in `palette.cpp`. - Added runtime utilities for reading text and JSON files in `runtime.cpp`. - Created shape archive handling in `shape_archive.cpp`, including frame parsing and pixel decoding. - Introduced type flag loading functionality in `type_flags.cpp`. - Developed tests for combat tactics, entity dispatch entries, file system operations, fixed maps, flex archives, glob archives, map rendering, palette loading, shape archives, and type flags. - Added a Python script for importing Ghidra-exported function slices with reporting capabilities. --- .gitignore | 2 + docs/remorse-windows-rebuild-roadmap.md | 561 ++++++++++++++++++ rebuild/remorse/CMakeLists.txt | 144 +++++ rebuild/remorse/build_msvc.cmd | 43 ++ .../remorse/include/remorse/combat_tactics.h | 22 + rebuild/remorse/include/remorse/compat.h | 48 ++ .../include/remorse/entity_dispatch_entry.h | 31 + .../remorse/include/remorse/export_prelude.h | 20 + rebuild/remorse/include/remorse/file_system.h | 24 + rebuild/remorse/include/remorse/fixed_map.h | 37 ++ .../remorse/include/remorse/flex_archive.h | 26 + .../remorse/include/remorse/glob_archive.h | 26 + .../remorse/include/remorse/map_renderer.h | 47 ++ rebuild/remorse/include/remorse/palette.h | 23 + rebuild/remorse/include/remorse/runtime.h | 24 + .../remorse/include/remorse/shape_archive.h | 35 ++ rebuild/remorse/include/remorse/type_flags.h | 22 + rebuild/remorse/src/combat_tactics.cpp | 58 ++ rebuild/remorse/src/entity_dispatch_entry.cpp | 49 ++ rebuild/remorse/src/file_system.cpp | 145 +++++ rebuild/remorse/src/fixed_map.cpp | 119 ++++ rebuild/remorse/src/flex_archive.cpp | 83 +++ rebuild/remorse/src/glob_archive.cpp | 56 ++ rebuild/remorse/src/main.cpp | 69 +++ rebuild/remorse/src/map_preview_main.cpp | 51 ++ rebuild/remorse/src/map_renderer.cpp | 362 +++++++++++ rebuild/remorse/src/palette.cpp | 23 + rebuild/remorse/src/runtime.cpp | 79 +++ rebuild/remorse/src/shape_archive.cpp | 205 +++++++ rebuild/remorse/src/type_flags.cpp | 38 ++ .../remorse/tests/combat_tactics_tests.cpp | 23 + .../tests/entity_dispatch_entry_tests.cpp | 26 + rebuild/remorse/tests/file_system_tests.cpp | 24 + rebuild/remorse/tests/fixed_map_tests.cpp | 37 ++ rebuild/remorse/tests/flex_archive_tests.cpp | 27 + rebuild/remorse/tests/glob_archive_tests.cpp | 28 + rebuild/remorse/tests/map_renderer_tests.cpp | 25 + rebuild/remorse/tests/palette_tests.cpp | 19 + rebuild/remorse/tests/shape_archive_tests.cpp | 30 + rebuild/remorse/tests/type_flags_tests.cpp | 28 + rebuild/remorse/tools/import_export_slice.py | 150 +++++ 41 files changed, 2889 insertions(+) create mode 100644 docs/remorse-windows-rebuild-roadmap.md create mode 100644 rebuild/remorse/CMakeLists.txt create mode 100644 rebuild/remorse/build_msvc.cmd create mode 100644 rebuild/remorse/include/remorse/combat_tactics.h create mode 100644 rebuild/remorse/include/remorse/compat.h create mode 100644 rebuild/remorse/include/remorse/entity_dispatch_entry.h create mode 100644 rebuild/remorse/include/remorse/export_prelude.h create mode 100644 rebuild/remorse/include/remorse/file_system.h create mode 100644 rebuild/remorse/include/remorse/fixed_map.h create mode 100644 rebuild/remorse/include/remorse/flex_archive.h create mode 100644 rebuild/remorse/include/remorse/glob_archive.h create mode 100644 rebuild/remorse/include/remorse/map_renderer.h create mode 100644 rebuild/remorse/include/remorse/palette.h create mode 100644 rebuild/remorse/include/remorse/runtime.h create mode 100644 rebuild/remorse/include/remorse/shape_archive.h create mode 100644 rebuild/remorse/include/remorse/type_flags.h create mode 100644 rebuild/remorse/src/combat_tactics.cpp create mode 100644 rebuild/remorse/src/entity_dispatch_entry.cpp create mode 100644 rebuild/remorse/src/file_system.cpp create mode 100644 rebuild/remorse/src/fixed_map.cpp create mode 100644 rebuild/remorse/src/flex_archive.cpp create mode 100644 rebuild/remorse/src/glob_archive.cpp create mode 100644 rebuild/remorse/src/main.cpp create mode 100644 rebuild/remorse/src/map_preview_main.cpp create mode 100644 rebuild/remorse/src/map_renderer.cpp create mode 100644 rebuild/remorse/src/palette.cpp create mode 100644 rebuild/remorse/src/runtime.cpp create mode 100644 rebuild/remorse/src/shape_archive.cpp create mode 100644 rebuild/remorse/src/type_flags.cpp create mode 100644 rebuild/remorse/tests/combat_tactics_tests.cpp create mode 100644 rebuild/remorse/tests/entity_dispatch_entry_tests.cpp create mode 100644 rebuild/remorse/tests/file_system_tests.cpp create mode 100644 rebuild/remorse/tests/fixed_map_tests.cpp create mode 100644 rebuild/remorse/tests/flex_archive_tests.cpp create mode 100644 rebuild/remorse/tests/glob_archive_tests.cpp create mode 100644 rebuild/remorse/tests/map_renderer_tests.cpp create mode 100644 rebuild/remorse/tests/palette_tests.cpp create mode 100644 rebuild/remorse/tests/shape_archive_tests.cpp create mode 100644 rebuild/remorse/tests/type_flags_tests.cpp create mode 100644 rebuild/remorse/tools/import_export_slice.py diff --git a/.gitignore b/.gitignore index ca901c9..d1c86ac 100644 --- a/.gitignore +++ b/.gitignore @@ -46,6 +46,8 @@ exports/** out/** binary/** psx-map-exporter/.output-render/** +rebuild/**/out/** +rebuild/**/imported/** # JavaScript / Node **/node_modules/** diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md new file mode 100644 index 0000000..55d24d5 --- /dev/null +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -0,0 +1,561 @@ +# Remorse Windows Rebuild Roadmap + +## Purpose + +This note records the current effort to turn the live Ghidra analysis and the exported C decompilation of `CRUSADER.EXE` into a source tree that can be recompiled and eventually run on Windows, including modern Windows. + +The short version: the project now has enough decompiled coverage to start a real rebuild lane, but the exported files are still evidence, not directly compilable game source. The safest path is to keep the export as an input corpus and move cleaned, subsystem-sized slices into a separate host rebuild tree with explicit ABI and platform boundaries. + +## Current Inputs + +- `exports/src_remorse/export_manifest.json` reports `CRUSADER.EXE`, 2,984 exported function files, 9 fallback function files, 57 global buckets, and 15,403 global definitions. +- `exports/src_remorse/CRUSADER.EXE.h` contains the bulk Ghidra data types and provisional structure definitions. +- `exports/src_remorse/functions/` contains split function bodies, including class-like folders such as `Remorse/EntityDispatchEntry`, `Remorse/SpriteNode`, `Remorse/EntityVmRuntime`, and related process families. +- Existing rebuild planning is in `docs/remorse-cpp-decompilation-plan.md`, `docs/remorse-rebuild-abi-notes.md`, and `docs/remorse-cpp-compatibility-header-draft.md`. + +## First Concrete Scaffold + +The first host rebuild scaffold is now under `rebuild/remorse/`. + +It is deliberately separate from `exports/src_remorse/` because the export is generated, ignored by git, and still contains syntax and ABI artifacts that modern compilers cannot accept wholesale. + +Current scaffold files: + +- `rebuild/remorse/CMakeLists.txt`: CMake target for a Windows-friendly C++17 executable named `remorse_rebuild`. +- `rebuild/remorse/build_msvc.cmd`: repeatable MSVC/CMake build, test, and harness-run command. +- `rebuild/remorse/include/remorse/combat_tactics.h`: typed reader for `COMBAT.DAT` tactic records. +- `rebuild/remorse/include/remorse/compat.h`: exact-width aliases, far-pointer placeholders, packing macros, and calling-convention marker macros. +- `rebuild/remorse/include/remorse/export_prelude.h`: temporary bridge types for staged Ghidra-export imports. +- `rebuild/remorse/include/remorse/entity_dispatch_entry.h`: first hand-maintained class-family skeleton, anchored to the `11e0:0000` / older `0008:ba00` allocation evidence. +- `rebuild/remorse/include/remorse/file_system.h`: first host file/path discovery shim for replacing DOS install-path assumptions. +- `rebuild/remorse/include/remorse/flex_archive.h`: standard FLEX archive directory parser. +- `rebuild/remorse/include/remorse/fixed_map.h`: typed `FIXED.DAT` map table and 16-byte item-record reader. +- `rebuild/remorse/include/remorse/glob_archive.h`: typed `GLOB.FLX` object-entry reader. +- `rebuild/remorse/include/remorse/map_renderer.h`: first dependency-free map preview renderer and BMP writer. +- `rebuild/remorse/include/remorse/palette.h`: first game-data parser for 256-color RGB palette files. +- `rebuild/remorse/include/remorse/runtime.h`: minimal runtime/export-manifest surface. +- `rebuild/remorse/include/remorse/shape_archive.h`: typed `SHAPES.FLX` shape-frame parser and row-RLE decoder. +- `rebuild/remorse/include/remorse/type_flags.h`: typed `TYPEFLAG.DAT` shape-family and flag decoder. +- `rebuild/remorse/src/combat_tactics.cpp`: parses tactic names, four block offsets, and bytecode payloads from `COMBAT.DAT` entries. +- `rebuild/remorse/src/entity_dispatch_entry.cpp`: minimal host-side `EntityDispatchEntry` behavior stubs for compile-time shape and early probing. +- `rebuild/remorse/src/file_system.cpp`: repository/retail data-root discovery using modern `std::filesystem`. +- `rebuild/remorse/src/flex_archive.cpp`: loader for count-at-`0x54`, table-at-`0x80` FLEX archives. +- `rebuild/remorse/src/fixed_map.cpp`: loader for `FIXED.DAT` map tables and scaled fixed-map item coordinates. +- `rebuild/remorse/src/glob_archive.cpp`: parser for glob object entry lists inside `GLOB.FLX`. +- `rebuild/remorse/src/map_preview_main.cpp`: command-line preview executable for writing a viewable BMP image. +- `rebuild/remorse/src/map_renderer.cpp`: combines fixed maps, glob expansion, typeflags, shape frames, and palette data into a painted preview image. +- `rebuild/remorse/src/palette.cpp`: `GAMEPAL.PAL`-style 768-byte palette parser. +- `rebuild/remorse/src/runtime.cpp`: loads a summary from the Ghidra export manifest. +- `rebuild/remorse/src/shape_archive.cpp`: ports the documented Crusader frame-table and row-RLE decode rules. +- `rebuild/remorse/src/type_flags.cpp`: ports the verified 9-byte Crusader typeflag decode from the map-rendering tool. +- `rebuild/remorse/src/main.cpp`: starts the host harness and prints the export status. +- `rebuild/remorse/tests/combat_tactics_tests.cpp`: checks `COMBAT.DAT` parses to 14 tactics and entry 0 is `Dumb`. +- `rebuild/remorse/tests/entity_dispatch_entry_tests.cpp`: first host-side check for the confirmed `EntityDispatchEntry` offsets. +- `rebuild/remorse/tests/file_system_tests.cpp`: first host-side check that the current repository root can be recognized as a game-data root. +- `rebuild/remorse/tests/flex_archive_tests.cpp`: checks `STATIC/COMBAT.DAT` as a small FLEX archive with 14 populated records. +- `rebuild/remorse/tests/fixed_map_tests.cpp`: checks `STATIC/FIXED.DAT` map count and map 0 item-record loading. +- `rebuild/remorse/tests/glob_archive_tests.cpp`: checks `STATIC/GLOB.FLX` parses into at least one populated glob object. +- `rebuild/remorse/tests/map_renderer_tests.cpp`: checks map 1 can produce a non-empty preview image. +- `rebuild/remorse/tests/palette_tests.cpp`: checks that `STATIC/GAMEPAL.PAL` parses into 256 colors. +- `rebuild/remorse/tests/shape_archive_tests.cpp`: checks `STATIC/SHAPES.FLX` can decode at least one visible frame. +- `rebuild/remorse/tests/type_flags_tests.cpp`: checks `STATIC/TYPEFLAG.DAT` parses 2,048 shape records and includes glob-family records. +- `rebuild/remorse/tools/import_export_slice.py`: stages one exported function folder into `rebuild/remorse/imported/` for manual cleanup review. + +This is not the game yet. It is the first buildable shell that future cleaned subsystems can link into without mutating the raw Ghidra export. + +## Why The Export Does Not Compile Yet + +The current exported C is very valuable, but it is not compiler-ready source for either DOS or Windows. + +Known blockers visible in the export: + +- C++ namespace-qualified function names appear inside `.c` files, for example `Remorse::EntityDispatchEntry::InitBase`. +- Ghidra calling-convention spellings such as `__cdecl16far`, `__cdecl16near`, `__stdcall16far`, and `__regcall` are not portable host compiler syntax. +- Ghidra undefined-width types and decompiler temporaries (`undefined`, `undefined2`, `undefined4`, `unaff_SS`, `unaff_CS`, synthetic stack variables, and return-storage pointers) need type and calling-convention cleanup. +- Header output includes invalid or provisional C declarations such as structure names containing spaces. +- Switch-table and global-byte exports are emitted as raw `undefined` objects that need relocation-aware or data-layout-aware modeling. +- Some functions still rely on segmented pointer reconstruction through expressions such as `CONCAT22`, not host pointers. +- The original binary is a DOS protected-mode `MZ -> NE` program using Phar Lap 286 extender behavior and far calls, so a modern Windows build needs a platform/runtime replacement rather than a simple relink. + +## Rebuild Tracks + +### Track A: Historical Executable Reconstruction + +This track tries to rebuild something close to the original DOS protected-mode executable model. + +It must preserve segmented pointers, far-call provenance, original-style packing, external runtime calls, and NE/Phar Lap assumptions. It is the hardest path and is not the primary route to modern Windows compatibility, but it remains important because it keeps the reverse-engineered ABI honest. + +### Track B: Windows Source Port + +This track uses the recovered source, object layouts, and resource formats to build a behaviorally equivalent Windows program. + +It can replace DOS extender, VGA, sound, input, timing, file, and memory services with host implementations, but it should initially preserve exact-width data layouts and far-pointer provenance so behavior can be compared back to the original. + +For the stated goal of running on modern Windows, Track B is the practical primary track. Track A should still guide early type cleanup so the port does not accidentally erase evidence. + +## Conversion Strategy + +1. Keep `exports/src_remorse/` as generated evidence. +2. Move one subsystem at a time into `rebuild/remorse/` as cleaned C++. +3. Compile every moved slice immediately, even before it is runnable game logic. +4. Replace Ghidra pseudo-types with `remorse::u8`, `remorse::u16`, `remorse::u32`, `remorse::FarPtr16`, and explicit packed structs. +5. Convert Ghidra calling-convention tokens into marker macros from `compat.h` until the final host calling surface is chosen. +6. Keep raw address provenance in comments or mapping tables for every imported function. +7. Build host runtime shims for platform services before trying to run gameplay. +8. Validate behavior with extracted resources and deterministic smoke tests. + +## Full Rebuild Plan + +The practical target is Track B first: a modern Windows source port that loads original data and reproduces gameplay behavior. Track A remains an evidence constraint for layout, calling convention, far-pointer provenance, and validation. + +### Phase 0: Build And Evidence Discipline + +Goal: every step builds, runs tests, and keeps provenance visible. + +Exit criteria: + +- `rebuild\remorse\build_msvc.cmd Debug` passes from the repository root +- every imported subsystem has address/source provenance in code or docs +- generated Ghidra exports remain input evidence, not hand-edited source + +### Phase 1: Host Runtime Foundation + +Goal: replace DOS installation assumptions with modern host services. + +Work: + +- game-data root discovery +- case-insensitive path resolution +- binary reads +- DOS-style file-handle facade +- writable config/save/user-data root +- command-line and config parsing +- logging and fatal-error reporting + +Exit criteria: the harness can find data, open/read assets through the same facade future game code will use, and write test save/config output outside the read-only retail data root. + +### Phase 2: Core Resource Loaders + +Goal: typed loaders for the files needed before gameplay can start. + +Work: + +- palettes: `GAMEPAL.PAL`, misc palettes, palette transforms +- FLEX archives: `COMBAT.DAT`, `GLOB.FLX`, `SHAPES.FLX`, `EUSECODE.FLX`, fonts/gumps/icons +- maps: `FIXED.DAT`, glob expansion, type flags +- shapes: Crusader frame directory and RLE decode +- usecode archive chunk discovery + +Exit criteria: a smoke test can load one map, expand globs, decode referenced shapes, and produce an in-memory scene without executing gameplay. + +### Phase 3: Minimal Renderer + +Goal: put a real Crusader world image on screen on Windows. + +Work: + +- choose initial graphics layer, likely SDL for window/input/timing/audio portability +- convert paletted frames to host pixels +- implement deterministic fixed-map painter first +- add debug overlay/status console for loaded map and camera position + +Exit criteria: running the host executable opens a window and displays a recognizable fixed-map scene from retail data. + +### Phase 4: Process, Item, And Entity Runtime + +Goal: lift the core object/process model into host source. + +Work: + +- typed `Process` / `EntityDispatchEntry` layout +- item allocation, fixed-format conversion, map item cache +- scheduler/process list +- sprite-node/draw-list families +- core entity fields and update lanes + +Exit criteria: the host runtime can instantiate map items/entities and advance a deterministic tick without requiring the full original VM yet. + +### Phase 5: Input, Camera, And Player Loop + +Goal: make the rendered world navigable. + +Work: + +- keyboard/mouse abstraction +- camera scroll/viewport state +- cursor/selection state +- player/avatar process skeleton +- collision/line-of-sight primitives as needed + +Exit criteria: the user can launch the host build, view a map, move the camera/avatar test object, and observe stable tick/update behavior. + +### Phase 6: USECODE / VM Runtime + +Goal: execute game scripts from original `EUSECODE.FLX`. + +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 +- 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. + +### Phase 7: Gameplay Systems + +Goal: make core No Remorse gameplay work. + +Work: + +- actor movement and animation +- combat tactic interpreter from `COMBAT.DAT` +- projectiles and hit resolution +- inventory/equipment +- doors, elevators, panels, triggers, movable walls +- save/load state + +Exit criteria: a small scenario can be played end to end with movement, combat, interaction, and persistence. + +### Phase 8: Media And Presentation + +Goal: reach production game flow rather than only a debug map runner. + +Work: + +- menu/frontend flow +- fonts/gumps/icons/HUD +- music/audio mixer +- flic/movie playback +- cutscene and mission transition behavior + +Exit criteria: the host build can boot through a recognizable frontend and enter gameplay using retail resources. + +### Phase 9: Whole-Game Integration And Parity + +Goal: turn subsystem success into a working game. + +Work: + +- mission progression +- all retail maps/resource variants +- error recovery and missing-data handling +- deterministic trace comparisons for high-risk systems +- long-run smoke tests + +Exit criteria: the game can be started, played across mission transitions, saved, loaded, and exited on modern Windows. + +### Phase 10: Packaging And Modernization + +Goal: make it usable outside the development repo. + +Work: + +- data-root picker or command-line root selection +- per-user config/save directory +- release build profile +- crash logs +- user documentation +- optional quality-of-life settings that do not obscure parity bugs + +Exit criteria: a clean checkout/build can run against a retail data directory with documented setup steps. + +## Current Execution Focus + +The current active phase is Phase 2, core resource loaders. The immediate path is `FIXED.DAT` map table and item-record loading, then glob expansion, then shape-frame decoding, then a minimal map scene smoke test. + +## Import-Slice Tool + +The first source-conversion helper is `rebuild/remorse/tools/import_export_slice.py`. + +Its job is intentionally modest: copy one folder from `exports/src_remorse/functions/` into ignored staging output under `rebuild/remorse/imported/`, rewrite Ghidra's direct `CRUSADER.EXE.h` include to `remorse/export_prelude.h`, convert known 16-bit calling-convention tokens to compatibility macros, and write an import report listing cleanup signals such as `unaff_SS`, `unaff_CS`, `CONCAT22`, and hidden return-storage parameters. + +Example: + +```powershell +python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispatchEntry +``` + +The generated staging files are not linked into `remorse_rebuild`. They are a workbench for turning one exported subsystem into hand-maintained source. + +The first run against `classes/Remorse/EntityDispatchEntry` staged 24 files, replaced 62 calling-convention tokens, preserved 46 namespace-qualified references, and reported `CONCAT22`, `unaff_CS`, and `unaff_SS` as cleanup signals. + +## Windows Runtime Work Needed + +To run on Windows, the rebuild needs replacement layers for these original services: + +- process startup and command-line/config parsing +- DOS file APIs and search paths +- Phar Lap / DOS extender memory services +- segmented far-pointer memory model, at least as a compatibility abstraction +- VGA/SVGA video mode setup, palette writes, bank switching, and blitting +- keyboard, mouse, and joystick input +- timer/tick scheduling +- audio device and mixer services +- movie playback and RIFF/audio frame handling +- save/load paths and user-writable data locations +- game data discovery for retail install layouts and repository fixtures + +The first Windows runtime should prefer clear host abstractions over direct Win32 calls where possible. SDL or another portability layer is a reasonable later choice for graphics, input, timing, and audio, but that should be selected after the first resource-loading and render smoke tests are defined. + +## Recommended First Subsystems + +The first source slices should be small enough to compile and test without the entire game loop. + +1. Compatibility/runtime layer: exact types, packed layout helpers, far-pointer wrappers, host file paths, and logging. +2. Resource/file loading helpers from the low segments, with DOS file calls replaced by host file services. +3. Palette and fixed-format data structures, validated against known assets. +4. `EntityDispatchEntry` as the first class-like family because it already has a named export folder and prior class-lifting notes. +5. Sprite/node or map rendering data structures after basic resource loading is stable. + +## First Hand-Maintained Game Skeleton + +The first manually maintained game-shaped source is `EntityDispatchEntry`. + +Current evidence used: + +- live export folder: `exports/src_remorse/functions/classes/Remorse/EntityDispatchEntry/` +- base initializer: `InitBase@11e0_0000.c` +- older note anchor recorded in the decompiler comment: `0008:ba00` +- allocation size visible in the decompiled initializer: `0x32` bytes + +The current rebuild skeleton preserves the 0x32-byte object size and provides host-side stubs for base init, group-id update, source/item update, and event/proc-type update. The first confirmed offsets from the exported setter bodies are: source item at `+0x04`, event/proc type at `+0x06`, and group id in the low five bits at `+0x08`. These names are still conservative because the surrounding `Process` layout is not fully lifted into typed fields yet. + +## First Windows Runtime Shim + +The first platform-replacement layer is a host file-system shim. + +Current behavior: + +- inspects a candidate root for `CRUSADER.EXE`, `CRUSADER.CFG`, `STATIC`, and `USECODE` +- walks upward from the current directory until it finds a usable game-data root +- resolves game-data-relative paths case-insensitively for ASCII DOS-style names +- blocks parent traversal through `..` +- reads binary files into host byte buffers +- reports the root path from the host harness +- adds a CTest target that expects the repository root to contain the retail executable and data folders, then reads `STATIC/GAMEPAL.PAL` + +This starts replacing the original DOS install-directory assumptions with explicit modern path discovery. It is intentionally narrow; file handles, writable save paths, and retail/install-layout variants are still to come. + +## First Data Parser + +The first parsed retail data asset is `STATIC/GAMEPAL.PAL`. + +Current behavior: + +- resolves `STATIC/GAMEPAL.PAL` through the host file-system shim +- requires exactly 768 bytes +- parses the file into 256 RGB triples +- reports the parsed color count from the host harness +- validates the path through `palette_tests` + +This gives the future renderer a tiny but real data pipeline: host path discovery, binary load, format validation, and typed in-memory representation. + +## First Archive Parser + +The first archive parser handles the standard Crusader FLEX directory used by files such as `COMBAT.DAT`, `GLOB.FLX`, `SHAPES.FLX`, and `EUSECODE.FLX`. + +Current behavior: + +- reads the entry count at file offset `0x54` +- reads 8-byte directory rows at file offset `0x80` +- treats rows as little-endian `` +- skips empty rows and rejects out-of-file entries +- extracts individual populated entries by index +- validates `STATIC/COMBAT.DAT` as 14 populated records with entry 0 named `Dumb` + +This is the first reusable loader shared by AI tactics, glob objects, shapes, and usecode archives. + +## First Typed Archive Consumer + +The first typed FLEX consumer is `COMBAT.DAT`. + +Current behavior: + +- loads the outer FLEX directory through `loadFlexArchive` +- parses each populated record's 16-byte NUL-padded tactic name +- reads four little-endian block offsets +- exposes the remaining bytes as tactic bytecode +- validates the shipped archive as 14 tactics, with entry 0 named `Dumb` and block offsets `0x002c` / `0x0031` + +This is not yet the combat bytecode interpreter, but it establishes the pattern for moving from raw archive chunks to typed subsystem inputs. + +## First Fixed-Map Loader + +`FIXED.DAT` is now the next typed world-data input. + +Current behavior: + +- reads the map count at file offset `0x54` +- reads 8-byte map table rows at file offset `0x80` +- treats each row as little-endian `` +- parses 16-byte fixed-item records into typed fields +- applies the verified Crusader coordinate scale: disk `x/y * 2` +- validates all map table rows parse, at least one map is non-empty, and out-of-range map indices are rejected + +This is the first step toward a host-side map scene assembled from retail data. + +## First Glob Loader + +`GLOB.FLX` is now parsed as the companion object-expansion archive for fixed maps. + +Current behavior: + +- loads the outer FLEX directory through `loadFlexArchive` +- reads each glob object as `u16 count` followed by repeated 6-byte entries +- parses each entry as `x:u8`, `y:u8`, `z:u8`, `shape:u16`, `frame:u8` +- validates the archive contains at least one glob object with entries + +This prepares the next step: expanding fixed-map glob eggs into concrete world objects using the coordinate rules in `docs/map-rendering.md`. + +## First Typeflag Loader + +`TYPEFLAG.DAT` is now parsed as the shape-family metadata source needed by map expansion and rendering. + +Current behavior: + +- requires 9-byte records +- decodes the 20-bit typeflag field using the same byte layout as the Python map renderer +- decodes shape family, footpad dimensions, and animation type +- validates the shipped file contains 2,048 shape records and includes glob-family shapes + +This is the shape metadata layer needed before fixed-map records can be classified as drawables, glob eggs, triggers, roofs, editor objects, or other family-specific runtime objects. + +## First Shape Decoder + +`SHAPES.FLX` is now parsed as the first renderable art source. + +Current behavior: + +- loads the outer FLEX directory through `loadFlexArchive` +- parses the Crusader shape header and 8-byte per-frame table +- reads 28-byte frame bodies, per-line RLE offsets, frame dimensions, and draw offsets +- decodes row RLE into transparent-or-palette-index pixels +- validates the shipped archive can decode at least one visible frame + +This completes the remaining Phase 2 requirement needed for a minimal map image: fixed records, glob records, shape metadata, palette, and decoded shape pixels. + +## First Visual Preview Renderer + +Phase 3 now has its first concrete artifact: `remorse_map_preview` writes a 24-bit BMP preview using only the source-port rebuild code and the shipped retail data. + +Current behavior: + +- defaults to map 1, the first non-empty fixed-map table entry in this data set +- expands first-level glob eggs using `GLOB.FLX` +- filters hidden marker/egg/roof families by default, matching the offline map-rendering workbench's first-pass policy +- decodes visible `SHAPES.FLX` frames and paints them with `GAMEPAL.PAL` +- writes a dependency-free BMP image under `rebuild/remorse/out/preview/` + +Validated preview: + +- command: `rebuild\remorse\out\build\Debug\remorse_map_preview.exe rebuild\remorse\out\preview\map1-preview.bmp 1` +- output: `rebuild/remorse/out/preview/map1-preview.bmp` +- image size: 1600x900 +- raw fixed records: 7,547 +- render items after filters/globs: 15,318 +- decoded items: 15,318 +- painted items in the preview crop: 178 +- full scene bounds: 30,977 x 15,617 + +This is still a smoke renderer, not the final game renderer. It uses a simple stable paint order rather than the full engine/item-sorter dependency graph, but it proves the rebuild tree can now load original resources and produce a visible world image. + +After reviewing the first preview, the chosen next direction is render correctness: port fuller item sorting, improve roof/hidden-object policy, and add better crop/navigation controls before moving to an interactive runtime. + +## Immediate Build Loop + +The first chosen Windows toolchain is Visual Studio Build Tools plus CMake. That means the expected compiler is MSVC `cl.exe`, usually reached through a Developer PowerShell or Developer Command Prompt. + +Until CMake and MSVC are available in PATH, the source scaffold can be edited and syntax-checked by VS Code, but it cannot be built locally from this shell. + +Current local toolchain finding: + +- Visual Studio Community 2026 is installed at `I:\Apps\VS\18\Community`. +- After installing the Desktop C++ workload, `vcvars64.bat`, MSVC `19.50.35729.0`, and VS-bundled CMake `4.2.3` are usable through the Visual Studio developer environment. +- Plain `cmake` is still not available before the Visual Studio environment is initialized, so `build_msvc.cmd` uses `vswhere` and `vcvars64.bat` before invoking CMake. + +### Host Harness + +From `rebuild/remorse/`, the intended host build loop is: + +```powershell +cmake -S . -B out/build +cmake --build out/build +ctest --test-dir out/build -C Debug --output-on-failure +.\out\build\Debug\remorse_rebuild.exe ..\..\exports\src_remorse\export_manifest.json +``` + +For single-config generators, the executable may be under `out/build/remorse_rebuild.exe` instead of `out/build/Debug/`. + +From the repository root, the repeatable MSVC path is: + +```powershell +rebuild\remorse\build_msvc.cmd Debug +``` + +### Staging One Export Slice + +From the repository root: + +```powershell +python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispatchEntry +``` + +## What Is Done + +- Established a separate rebuild tree under `rebuild/remorse/`. +- Added a CMake-based C++17 executable target. +- Added an initial compatibility header matching the earlier ABI draft categories. +- Added a temporary export prelude for staged decompiler-source imports. +- Added a minimal runtime harness that reads the exported decompilation manifest and reports the current export scope. +- Added an import-slice tool for staging individual exported function folders without linking them yet. +- Ran the importer on `classes/Remorse/EntityDispatchEntry`; it staged 24 files, replaced 62 calling-convention tokens, and reported `CONCAT22`, `unaff_CS`, and `unaff_SS` as cleanup signals. +- Added the first hand-maintained `EntityDispatchEntry` source skeleton and wired it into the CMake target. +- Split the scaffold into a `remorse_core` library, host executable, and first CTest target for `EntityDispatchEntry` setters. +- Added the first host file-system shim and CTest target for game-data root discovery. +- Extended the host file-system shim with case-insensitive data-path resolution, parent-traversal blocking, and binary file reads. +- Added the first typed game-data parser for 256-color palette files and verified `STATIC/GAMEPAL.PAL` parses to 256 colors. +- Added a standard FLEX archive parser and verified `STATIC/COMBAT.DAT` exposes 14 populated records. +- Added a typed `COMBAT.DAT` tactic parser and verified entry 0 metadata against the existing combat note. +- Added a full staged rebuild plan from current harness through a playable and packaged modern Windows source port. +- Added a typed `FIXED.DAT` map loader for map table and 16-byte fixed-item records. +- Added a typed `GLOB.FLX` object parser for the fixed-map glob-expansion path. +- Added a typed `TYPEFLAG.DAT` parser for shape family, flags, dimensions, and animation metadata. +- Added a typed `SHAPES.FLX` parser and row-RLE decoder for renderable frame pixels. +- Added the first visual map preview renderer and BMP output command. +- Validated `remorse_map_preview` by rendering map 1 to `rebuild/remorse/out/preview/map1-preview.bmp` from original retail data. +- Verified the scaffold with Visual Studio Community 2026: CMake configure succeeded, MSVC build succeeded, `ctest -C Debug` passed 2/2 tests, and `remorse_rebuild.exe` ran against `exports/src_remorse/export_manifest.json`. +- Added `build_msvc.cmd` so the working build/test/harness loop is repeatable from the repository root. +- Documented the current blockers between the Ghidra export and compiler-ready source. +- Split the goal into historical reconstruction and Windows source-port tracks. +- Chose Visual Studio Build Tools plus CMake as the first intended Windows host toolchain. + +## What Is Left To Do + +- Keep the host scaffold building as new source slices are added. +- Lift the confirmed `EntityDispatchEntry` byte offsets into named packed fields once the surrounding `Process` layout is stable. +- Convert the compatibility header from placeholders into enforced layout macros with static assertions. +- Pick the first real subsystem slice and move it into `rebuild/remorse/`. +- Expand the host file-system shim into DOS file-handle replacements and writable save/config locations. +- Model far pointers and segmented memory in a way that can support both trace comparison and Windows execution. +- Normalize Ghidra exported types into valid C++ names without losing address provenance. +- Replace raw global-byte exports with typed data definitions or resource loaders. +- Define resource fixture tests for palette, shape, map, and usecode data. +- Replace the current preview painter's simple ordering with a fuller item-sorter dependency graph. +- Decide whether the first interactive window should use SDL, raw Win32/GDI, or another host layer. +- Decide the graphics/input/audio platform layer for the Windows runtime. +- Add CI-style smoke tests once the host toolchain and first resource loader compile reliably. + +## Near-Term Next Actions + +1. Open a Developer PowerShell with MSVC and CMake available, then run the CMake scaffold build. +2. Replace the current `EntityDispatchEntry` byte-array fields with named packed fields as evidence allows. +3. Add a small host-side test for the confirmed `+0x04`, `+0x06`, and `+0x08` setters once the MSVC/CMake toolchain is available. +4. Map the first old DOS file functions onto the new host file-system shim. +5. Add writable save/config path handling. +6. Add layout assertions for the first recovered packed structs. +7. Start a render/runtime decision note once the first resource smoke test passes. + +## Current Bottom Line + +The project is now at the start of the recompilation lane: there is a buildable host target scaffold, a compatibility surface, and a documented path for importing cleaned decompiler output. The major remaining work is systematic conversion, platform replacement, and behavior validation, not another bulk export. diff --git a/rebuild/remorse/CMakeLists.txt b/rebuild/remorse/CMakeLists.txt new file mode 100644 index 0000000..6ab261d --- /dev/null +++ b/rebuild/remorse/CMakeLists.txt @@ -0,0 +1,144 @@ +cmake_minimum_required(VERSION 3.20) + +project(remorse_rebuild LANGUAGES CXX) + +add_library(remorse_core + src/combat_tactics.cpp + src/entity_dispatch_entry.cpp + src/file_system.cpp + src/flex_archive.cpp + src/fixed_map.cpp + src/glob_archive.cpp + src/map_renderer.cpp + src/palette.cpp + src/runtime.cpp + src/shape_archive.cpp + src/type_flags.cpp +) + +target_compile_features(remorse_core PUBLIC cxx_std_17) +target_include_directories(remorse_core PUBLIC include) + +add_executable(remorse_rebuild + src/main.cpp +) + +target_link_libraries(remorse_rebuild PRIVATE remorse_core) + +add_executable(remorse_map_preview + src/map_preview_main.cpp +) + +target_link_libraries(remorse_map_preview PRIVATE remorse_core) + +enable_testing() + +add_executable(entity_dispatch_entry_tests + tests/entity_dispatch_entry_tests.cpp +) + +target_link_libraries(entity_dispatch_entry_tests PRIVATE remorse_core) + +add_test(NAME entity_dispatch_entry_tests COMMAND entity_dispatch_entry_tests) + +add_executable(file_system_tests + tests/file_system_tests.cpp +) + +target_link_libraries(file_system_tests PRIVATE remorse_core) + +add_test(NAME file_system_tests COMMAND file_system_tests) + +add_executable(palette_tests + tests/palette_tests.cpp +) + +target_link_libraries(palette_tests PRIVATE remorse_core) + +add_test(NAME palette_tests COMMAND palette_tests) + +add_executable(flex_archive_tests + tests/flex_archive_tests.cpp +) + +target_link_libraries(flex_archive_tests PRIVATE remorse_core) + +add_test(NAME flex_archive_tests COMMAND flex_archive_tests) + +add_executable(fixed_map_tests + tests/fixed_map_tests.cpp +) + +target_link_libraries(fixed_map_tests PRIVATE remorse_core) + +add_test(NAME fixed_map_tests COMMAND fixed_map_tests) + +add_executable(glob_archive_tests + tests/glob_archive_tests.cpp +) + +target_link_libraries(glob_archive_tests PRIVATE remorse_core) + +add_test(NAME glob_archive_tests COMMAND glob_archive_tests) + +add_executable(type_flags_tests + tests/type_flags_tests.cpp +) + +target_link_libraries(type_flags_tests PRIVATE remorse_core) + +add_test(NAME type_flags_tests COMMAND type_flags_tests) + +add_executable(shape_archive_tests + tests/shape_archive_tests.cpp +) + +target_link_libraries(shape_archive_tests PRIVATE remorse_core) + +add_test(NAME shape_archive_tests COMMAND shape_archive_tests) + +add_executable(map_renderer_tests + tests/map_renderer_tests.cpp +) + +target_link_libraries(map_renderer_tests PRIVATE remorse_core) + +add_test(NAME map_renderer_tests COMMAND map_renderer_tests) + +add_executable(combat_tactics_tests + tests/combat_tactics_tests.cpp +) + +target_link_libraries(combat_tactics_tests PRIVATE remorse_core) + +add_test(NAME combat_tactics_tests COMMAND combat_tactics_tests) + +if(MSVC) + target_compile_options(remorse_core PRIVATE /W4 /permissive-) + target_compile_options(combat_tactics_tests PRIVATE /W4 /permissive-) + target_compile_options(map_renderer_tests PRIVATE /W4 /permissive-) + target_compile_options(remorse_map_preview PRIVATE /W4 /permissive-) + target_compile_options(remorse_rebuild PRIVATE /W4 /permissive-) + target_compile_options(entity_dispatch_entry_tests PRIVATE /W4 /permissive-) + target_compile_options(file_system_tests PRIVATE /W4 /permissive-) + target_compile_options(flex_archive_tests PRIVATE /W4 /permissive-) + target_compile_options(fixed_map_tests PRIVATE /W4 /permissive-) + target_compile_options(glob_archive_tests PRIVATE /W4 /permissive-) + target_compile_options(palette_tests PRIVATE /W4 /permissive-) + target_compile_options(shape_archive_tests PRIVATE /W4 /permissive-) + target_compile_options(type_flags_tests PRIVATE /W4 /permissive-) +else() + target_compile_options(remorse_core PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(combat_tactics_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(map_renderer_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(remorse_map_preview PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(remorse_rebuild PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(entity_dispatch_entry_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(file_system_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(flex_archive_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(fixed_map_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(glob_archive_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(palette_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(shape_archive_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(type_flags_tests PRIVATE -Wall -Wextra -Wpedantic) +endif() diff --git a/rebuild/remorse/build_msvc.cmd b/rebuild/remorse/build_msvc.cmd new file mode 100644 index 0000000..3b75561 --- /dev/null +++ b/rebuild/remorse/build_msvc.cmd @@ -0,0 +1,43 @@ +@echo off +setlocal + +set "CONFIG=%~1" +if "%CONFIG%"=="" set "CONFIG=Debug" + +set "REPO_ROOT=%~dp0..\.." +for %%I in ("%REPO_ROOT%") do set "REPO_ROOT=%%~fI" + +set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" +if not exist "%VSWHERE%" ( + echo vswhere.exe was not found at "%VSWHERE%". + exit /b 2 +) + +for /f "usebackq delims=" %%I in (`"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "VSINSTALL=%%I" + +if "%VSINSTALL%"=="" ( + echo Visual Studio with MSVC x64 tools was not found. + exit /b 2 +) + +set "VCVARS=%VSINSTALL%\VC\Auxiliary\Build\vcvars64.bat" +if not exist "%VCVARS%" ( + echo vcvars64.bat was not found at "%VCVARS%". + exit /b 2 +) + +call "%VCVARS%" || exit /b 2 + +cd /d "%REPO_ROOT%" || exit /b 2 + +cmake -S rebuild/remorse -B rebuild/remorse/out/build || exit /b 1 +cmake --build rebuild/remorse/out/build --config "%CONFIG%" || exit /b 1 +ctest --test-dir rebuild/remorse/out/build -C "%CONFIG%" --output-on-failure || exit /b 1 + +set "EXE=rebuild\remorse\out\build\%CONFIG%\remorse_rebuild.exe" +if not exist "%EXE%" ( + echo Built executable was not found at "%EXE%". + exit /b 1 +) + +"%EXE%" exports\src_remorse\export_manifest.json || exit /b 1 diff --git a/rebuild/remorse/include/remorse/combat_tactics.h b/rebuild/remorse/include/remorse/combat_tactics.h new file mode 100644 index 0000000..58f4d5e --- /dev/null +++ b/rebuild/remorse/include/remorse/combat_tactics.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "remorse/compat.h" + +namespace remorse { + +struct CombatTactic { + u32 index = 0; + std::string name; + std::array blockOffsets{}; + std::vector bytecode; +}; + +std::optional> loadCombatTactics(const std::filesystem::path& path); + +} // namespace remorse diff --git a/rebuild/remorse/include/remorse/compat.h b/rebuild/remorse/include/remorse/compat.h new file mode 100644 index 0000000..b614839 --- /dev/null +++ b/rebuild/remorse/include/remorse/compat.h @@ -0,0 +1,48 @@ +#pragma once + +namespace remorse { + +using u8 = unsigned char; +using s8 = signed char; +using u16 = unsigned short; +using s16 = signed short; +using u32 = unsigned int; +using s32 = signed int; + +static_assert(sizeof(u8) == 1, "u8 must be 8 bits"); +static_assert(sizeof(u16) == 2, "u16 must be 16 bits"); +static_assert(sizeof(u32) == 4, "u32 must be 32 bits"); + +struct FarPtr16 { + u16 offset; + u16 segment; +}; + +template +struct FarPtr { + u16 offset; + u16 segment; + + constexpr FarPtr16 raw() const noexcept + { + return FarPtr16{offset, segment}; + } +}; + +#if defined(_MSC_VER) +#define CR_PACK_PUSH_1 __pragma(pack(push, 1)) +#define CR_PACK_POP __pragma(pack(pop)) +#define CR_PACKED +#else +#define CR_PACK_PUSH_1 _Pragma("pack(push, 1)") +#define CR_PACK_POP _Pragma("pack(pop)") +#define CR_PACKED __attribute__((packed)) +#endif + +#define CR_CDECL +#define CR_STDCALL +#define CR_THISCALL +#define CR_FARCALL +#define CR_VSLOT(index) + +} // namespace remorse diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h new file mode 100644 index 0000000..b838ab3 --- /dev/null +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -0,0 +1,31 @@ +#pragma once + +#include "remorse/compat.h" + +namespace remorse { + +CR_PACK_PUSH_1 +struct EntityDispatchEntryBase { + u8 bytes[0x32]; +} CR_PACKED; + +struct EntityDispatchEntryRuntimeState { + u8 bytes[0x18]; +} CR_PACKED; +CR_PACK_POP + +static_assert(sizeof(EntityDispatchEntryBase) == 0x32, "EntityDispatchEntryBase size must match allocation evidence"); + +class EntityDispatchEntry { +public: + static constexpr u16 initBaseSegment = 0x11e0; + static constexpr u16 initBaseOffset = 0x0000; + + static EntityDispatchEntryBase* initBase(EntityDispatchEntryBase* entry); + static void setGroupId(EntityDispatchEntryBase& entry, u8 groupId); + static void incrementGroupId(EntityDispatchEntryBase& entry); + static void setSourceType(EntityDispatchEntryBase& entry, u16 sourceType); + static void setEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType); +}; + +} // namespace remorse diff --git a/rebuild/remorse/include/remorse/export_prelude.h b/rebuild/remorse/include/remorse/export_prelude.h new file mode 100644 index 0000000..c8a257c --- /dev/null +++ b/rebuild/remorse/include/remorse/export_prelude.h @@ -0,0 +1,20 @@ +#pragma once + +#include "remorse/compat.h" + +using remorse::s16; +using remorse::s32; +using remorse::s8; +using remorse::u16; +using remorse::u32; +using remorse::u8; + +using undefined = u8; +using undefined1 = u8; +using undefined2 = u16; +using undefined4 = u32; +using byte = u8; +using word = u16; +using uint = unsigned int; +using ulong = unsigned long; +using dword = u32; diff --git a/rebuild/remorse/include/remorse/file_system.h b/rebuild/remorse/include/remorse/file_system.h new file mode 100644 index 0000000..2cf1c19 --- /dev/null +++ b/rebuild/remorse/include/remorse/file_system.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include + +#include "remorse/compat.h" + +namespace remorse { + +struct GameDataRoot { + std::filesystem::path path; + bool hasExecutable = false; + bool hasConfig = false; + bool hasStaticData = false; + bool hasUsecode = false; +}; + +GameDataRoot inspectGameDataRoot(const std::filesystem::path& root); +std::optional findGameDataRoot(const std::filesystem::path& start); +std::optional resolveGameDataPath(const GameDataRoot& root, const std::filesystem::path& relativePath); +std::optional> readBinaryFile(const std::filesystem::path& path); + +} // namespace remorse diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h new file mode 100644 index 0000000..cb4b068 --- /dev/null +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include + +#include "remorse/compat.h" + +namespace remorse { + +struct FixedMapEntry { + u16 x = 0; + u16 y = 0; + u8 z = 0; + u16 shape = 0; + u8 frame = 0; + u16 flags = 0; + u16 quality = 0; + u8 npcNumber = 0; + u8 mapNumber = 0; + u16 next = 0; +}; + +struct FixedMap { + u32 index = 0; + std::vector entries; +}; + +struct FixedMapArchive { + u32 mapCount = 0; + std::vector bytes; +}; + +std::optional loadFixedMapArchive(const std::filesystem::path& path); +std::optional loadFixedMap(const FixedMapArchive& archive, u32 mapIndex); + +} // namespace remorse diff --git a/rebuild/remorse/include/remorse/flex_archive.h b/rebuild/remorse/include/remorse/flex_archive.h new file mode 100644 index 0000000..bf5ed91 --- /dev/null +++ b/rebuild/remorse/include/remorse/flex_archive.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include + +#include "remorse/compat.h" + +namespace remorse { + +struct FlexEntry { + u32 index = 0; + u32 offset = 0; + u32 size = 0; +}; + +struct FlexArchive { + u32 entryCount = 0; + std::vector populatedEntries; + std::vector bytes; +}; + +std::optional loadFlexArchive(const std::filesystem::path& path); +std::optional> readFlexEntry(const FlexArchive& archive, u32 index); + +} // namespace remorse diff --git a/rebuild/remorse/include/remorse/glob_archive.h b/rebuild/remorse/include/remorse/glob_archive.h new file mode 100644 index 0000000..92ae36c --- /dev/null +++ b/rebuild/remorse/include/remorse/glob_archive.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include + +#include "remorse/compat.h" + +namespace remorse { + +struct GlobObjectEntry { + u8 x = 0; + u8 y = 0; + u8 z = 0; + u16 shape = 0; + u8 frame = 0; +}; + +struct GlobObject { + u32 index = 0; + std::vector entries; +}; + +std::optional> loadGlobObjects(const std::filesystem::path& path); + +} // namespace remorse diff --git a/rebuild/remorse/include/remorse/map_renderer.h b/rebuild/remorse/include/remorse/map_renderer.h new file mode 100644 index 0000000..c5dcaaf --- /dev/null +++ b/rebuild/remorse/include/remorse/map_renderer.h @@ -0,0 +1,47 @@ +#pragma once + +#include +#include +#include + +#include "remorse/compat.h" +#include "remorse/file_system.h" +#include "remorse/palette.h" + +namespace remorse { + +struct WorldRect { + s32 minX = 0; + s32 minY = 0; + s32 maxX = 0; + s32 maxY = 0; +}; + +struct MapRenderOptions { + u32 mapIndex = 1; + u32 maxWidth = 1600; + u32 maxHeight = 900; + bool expandGlobs = true; + bool includeRoofs = false; + bool includeHiddenMarkers = false; + std::optional worldRect; +}; + +struct RenderedMapImage { + u32 width = 0; + u32 height = 0; + u32 rawItemCount = 0; + u32 renderItemCount = 0; + u32 decodedItemCount = 0; + u32 paintedItemCount = 0; + s32 sourceLeft = 0; + s32 sourceTop = 0; + s32 fullWidth = 0; + s32 fullHeight = 0; + std::vector pixels; +}; + +std::optional renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options); +bool writeBmp24(const std::filesystem::path& path, const RenderedMapImage& image); + +} // namespace remorse diff --git a/rebuild/remorse/include/remorse/palette.h b/rebuild/remorse/include/remorse/palette.h new file mode 100644 index 0000000..b4d8cbf --- /dev/null +++ b/rebuild/remorse/include/remorse/palette.h @@ -0,0 +1,23 @@ +#pragma once + +#include +#include +#include + +#include "remorse/compat.h" + +namespace remorse { + +struct RgbColor { + u8 red = 0; + u8 green = 0; + u8 blue = 0; +}; + +struct Palette256 { + std::array colors{}; +}; + +std::optional loadPalette256(const std::filesystem::path& path); + +} // namespace remorse diff --git a/rebuild/remorse/include/remorse/runtime.h b/rebuild/remorse/include/remorse/runtime.h new file mode 100644 index 0000000..89172aa --- /dev/null +++ b/rebuild/remorse/include/remorse/runtime.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include + +#include "remorse/compat.h" + +namespace remorse { + +struct ExportManifestSummary { + std::string program; + std::filesystem::path outputRoot; + u32 functionFiles = 0; + u32 fallbackFunctionFiles = 0; + u32 globalBuckets = 0; + u32 globalDefinitions = 0; +}; + +std::optional loadExportManifestSummary(const std::filesystem::path& manifestPath); +std::filesystem::path defaultManifestPath(const std::filesystem::path& currentPath); +void printStartupReport(const ExportManifestSummary& manifest); + +} // namespace remorse diff --git a/rebuild/remorse/include/remorse/shape_archive.h b/rebuild/remorse/include/remorse/shape_archive.h new file mode 100644 index 0000000..dcd574c --- /dev/null +++ b/rebuild/remorse/include/remorse/shape_archive.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include +#include + +#include "remorse/compat.h" +#include "remorse/flex_archive.h" + +namespace remorse { + +struct ShapeFrame { + bool compressed = false; + u32 width = 0; + u32 height = 0; + s32 xOffset = 0; + s32 yOffset = 0; + std::vector lineOffsets; + std::vector rleData; +}; + +struct DecodedShapeFrame { + ShapeFrame frame; + std::vector pixels; +}; + +struct ShapeArchive { + FlexArchive archive; +}; + +std::optional loadShapeArchive(const std::filesystem::path& path); +std::optional> loadShapeFrames(const ShapeArchive& archive, u32 shapeIndex); +std::optional decodeShapeFrame(const ShapeArchive& archive, u32 shapeIndex, u32 frameIndex); + +} // namespace remorse diff --git a/rebuild/remorse/include/remorse/type_flags.h b/rebuild/remorse/include/remorse/type_flags.h new file mode 100644 index 0000000..9abd84a --- /dev/null +++ b/rebuild/remorse/include/remorse/type_flags.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include + +#include "remorse/compat.h" + +namespace remorse { + +struct ShapeTypeInfo { + u8 family = 0; + u32 flags = 0; + u8 x = 0; + u8 y = 0; + u8 z = 0; + u8 animationType = 0; +}; + +std::optional> loadTypeFlags(const std::filesystem::path& path); + +} // namespace remorse diff --git a/rebuild/remorse/src/combat_tactics.cpp b/rebuild/remorse/src/combat_tactics.cpp new file mode 100644 index 0000000..9c868af --- /dev/null +++ b/rebuild/remorse/src/combat_tactics.cpp @@ -0,0 +1,58 @@ +#include "remorse/combat_tactics.h" + +#include "remorse/flex_archive.h" + +namespace remorse { +namespace { + +constexpr u32 tacticNameSize = 16; +constexpr u32 tacticBlockOffsetCount = 4; +constexpr u32 tacticHeaderSize = tacticNameSize + tacticBlockOffsetCount * 2; + +u16 readU16Le(const std::vector& bytes, u32 offset) +{ + return static_cast(bytes[offset] | (static_cast(bytes[offset + 1]) << 8)); +} + +std::string readNullPaddedName(const std::vector& bytes) +{ + std::string name; + for (u32 index = 0; index < tacticNameSize; ++index) { + if (bytes[index] == 0) { + break; + } + name.push_back(static_cast(bytes[index])); + } + return name; +} + +} // namespace + +std::optional> loadCombatTactics(const std::filesystem::path& path) +{ + const auto archive = loadFlexArchive(path); + if (!archive) { + return std::nullopt; + } + + std::vector tactics; + for (const FlexEntry& entry : archive->populatedEntries) { + const auto entryBytes = readFlexEntry(*archive, entry.index); + if (!entryBytes || entryBytes->size() < tacticHeaderSize) { + return std::nullopt; + } + + CombatTactic tactic; + tactic.index = entry.index; + tactic.name = readNullPaddedName(*entryBytes); + for (u32 offsetIndex = 0; offsetIndex < tacticBlockOffsetCount; ++offsetIndex) { + tactic.blockOffsets[offsetIndex] = readU16Le(*entryBytes, tacticNameSize + offsetIndex * 2); + } + tactic.bytecode.assign(entryBytes->begin() + tacticHeaderSize, entryBytes->end()); + tactics.push_back(tactic); + } + + return tactics; +} + +} // namespace remorse diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp new file mode 100644 index 0000000..15500fb --- /dev/null +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -0,0 +1,49 @@ +#include "remorse/entity_dispatch_entry.h" + +namespace remorse { + +namespace { +constexpr u16 sourceItemOffset = 0x04; +constexpr u16 eventTypeOffset = 0x06; +constexpr u16 groupIdOffset = 0x08; + +void writeLe16(EntityDispatchEntryBase& entry, u16 offset, u16 value) +{ + entry.bytes[offset] = static_cast(value & 0xff); + entry.bytes[offset + 1] = static_cast(value >> 8); +} +} + +EntityDispatchEntryBase* EntityDispatchEntry::initBase(EntityDispatchEntryBase* entry) +{ + if (entry == nullptr) { + return nullptr; + } + + for (u8& byte : entry->bytes) { + byte = 0; + } + return entry; +} + +void EntityDispatchEntry::setGroupId(EntityDispatchEntryBase& entry, u8 groupId) +{ + entry.bytes[groupIdOffset] = static_cast((entry.bytes[groupIdOffset] & 0xe0) | (groupId & 0x1f)); +} + +void EntityDispatchEntry::incrementGroupId(EntityDispatchEntryBase& entry) +{ + ++entry.bytes[groupIdOffset]; +} + +void EntityDispatchEntry::setSourceType(EntityDispatchEntryBase& entry, u16 sourceType) +{ + writeLe16(entry, sourceItemOffset, sourceType); +} + +void EntityDispatchEntry::setEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType) +{ + writeLe16(entry, eventTypeOffset, eventType); +} + +} // namespace remorse diff --git a/rebuild/remorse/src/file_system.cpp b/rebuild/remorse/src/file_system.cpp new file mode 100644 index 0000000..454d33e --- /dev/null +++ b/rebuild/remorse/src/file_system.cpp @@ -0,0 +1,145 @@ +#include "remorse/file_system.h" + +#include +#include + +namespace remorse { +namespace { + +bool pathExists(const std::filesystem::path& path) +{ + return std::filesystem::exists(path); +} + +std::optional parentPath(const std::filesystem::path& path) +{ + const std::filesystem::path parent = path.parent_path(); + if (parent.empty() || parent == path) { + return std::nullopt; + } + return parent; +} + +char toLowerAscii(char value) +{ + if (value < 'A' || value > 'Z') { + return value; + } + return static_cast(value - 'A' + 'a'); +} + +std::string lowerAscii(std::string value) +{ + for (char& character : value) { + character = toLowerAscii(character); + } + return value; +} + +bool equalAsciiCaseInsensitive(const std::filesystem::path& left, const std::filesystem::path& right) +{ + return lowerAscii(left.filename().string()) == lowerAscii(right.filename().string()); +} + +std::optional resolveChildCaseInsensitive(const std::filesystem::path& parent, const std::filesystem::path& child) +{ + const std::filesystem::path exact = parent / child; + if (pathExists(exact)) { + return exact; + } + + if (!std::filesystem::is_directory(parent)) { + return std::nullopt; + } + + for (const std::filesystem::directory_entry& entry : std::filesystem::directory_iterator(parent)) { + if (equalAsciiCaseInsensitive(entry.path(), child)) { + return entry.path(); + } + } + return std::nullopt; +} + +} // namespace + +GameDataRoot inspectGameDataRoot(const std::filesystem::path& root) +{ + GameDataRoot result; + result.path = root; + result.hasExecutable = pathExists(root / "CRUSADER.EXE"); + result.hasConfig = pathExists(root / "CRUSADER.CFG"); + result.hasStaticData = pathExists(root / "STATIC"); + result.hasUsecode = pathExists(root / "USECODE"); + return result; +} + +std::optional findGameDataRoot(const std::filesystem::path& start) +{ + std::filesystem::path cursor = std::filesystem::absolute(start); + if (std::filesystem::is_regular_file(cursor)) { + cursor = cursor.parent_path(); + } + + while (true) { + GameDataRoot candidate = inspectGameDataRoot(cursor); + if (candidate.hasExecutable && candidate.hasStaticData && candidate.hasUsecode) { + return candidate; + } + + const auto parent = parentPath(cursor); + if (!parent) { + return std::nullopt; + } + cursor = *parent; + } +} + +std::optional resolveGameDataPath(const GameDataRoot& root, const std::filesystem::path& relativePath) +{ + if (relativePath.empty() || relativePath.is_absolute()) { + return std::nullopt; + } + + std::filesystem::path cursor = root.path; + for (const std::filesystem::path& component : relativePath) { + if (component == ".") { + continue; + } + if (component == "..") { + return std::nullopt; + } + + const auto next = resolveChildCaseInsensitive(cursor, component); + if (!next) { + return std::nullopt; + } + cursor = *next; + } + return cursor; +} + +std::optional> readBinaryFile(const std::filesystem::path& path) +{ + std::ifstream input(path, std::ios::binary); + if (!input) { + return std::nullopt; + } + + input.seekg(0, std::ios::end); + const std::streamoff size = input.tellg(); + if (size < 0) { + return std::nullopt; + } + input.seekg(0, std::ios::beg); + + std::vector bytes(static_cast(size)); + if (!bytes.empty()) { + input.read(reinterpret_cast(bytes.data()), size); + if (!input) { + return std::nullopt; + } + } + return bytes; +} + +} // namespace remorse diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp new file mode 100644 index 0000000..9c981db --- /dev/null +++ b/rebuild/remorse/src/fixed_map.cpp @@ -0,0 +1,119 @@ +#include "remorse/fixed_map.h" + +#include "remorse/file_system.h" + +namespace remorse { +namespace { + +constexpr u32 fixedMapCountOffset = 0x54; +constexpr u32 fixedMapTableOffset = 0x80; +constexpr u32 fixedMapTableRowSize = 8; +constexpr u32 fixedMapRecordSize = 16; +constexpr u16 crusaderCoordinateScale = 2; + +std::optional readU16Le(const std::vector& bytes, u32 offset) +{ + if (offset + 2 > bytes.size()) { + return std::nullopt; + } + return static_cast(bytes[offset] | (static_cast(bytes[offset + 1]) << 8)); +} + +std::optional readU32Le(const std::vector& bytes, u32 offset) +{ + if (offset + 4 > bytes.size()) { + return std::nullopt; + } + return static_cast(bytes[offset]) | + (static_cast(bytes[offset + 1]) << 8) | + (static_cast(bytes[offset + 2]) << 16) | + (static_cast(bytes[offset + 3]) << 24); +} + +std::optional readFixedMapEntry(const std::vector& bytes, u32 offset) +{ + if (offset + fixedMapRecordSize > bytes.size()) { + return std::nullopt; + } + + const auto diskX = readU16Le(bytes, offset); + const auto diskY = readU16Le(bytes, offset + 2); + const auto shape = readU16Le(bytes, offset + 5); + const auto flags = readU16Le(bytes, offset + 8); + const auto quality = readU16Le(bytes, offset + 10); + const auto next = readU16Le(bytes, offset + 14); + if (!diskX || !diskY || !shape || !flags || !quality || !next) { + return std::nullopt; + } + + FixedMapEntry entry; + entry.x = static_cast(*diskX * crusaderCoordinateScale); + entry.y = static_cast(*diskY * crusaderCoordinateScale); + entry.z = bytes[offset + 4]; + entry.shape = *shape; + entry.frame = bytes[offset + 7]; + entry.flags = *flags; + entry.quality = *quality; + entry.npcNumber = bytes[offset + 12]; + entry.mapNumber = bytes[offset + 13]; + entry.next = *next; + return entry; +} + +} // namespace + +std::optional loadFixedMapArchive(const std::filesystem::path& path) +{ + auto bytes = readBinaryFile(path); + if (!bytes) { + return std::nullopt; + } + + const auto mapCount = readU16Le(*bytes, fixedMapCountOffset); + if (!mapCount) { + return std::nullopt; + } + + const u32 tableEnd = fixedMapTableOffset + (static_cast(*mapCount) * fixedMapTableRowSize); + if (tableEnd > bytes->size()) { + return std::nullopt; + } + + FixedMapArchive archive; + archive.mapCount = *mapCount; + archive.bytes = *bytes; + return archive; +} + +std::optional loadFixedMap(const FixedMapArchive& archive, u32 mapIndex) +{ + if (mapIndex >= archive.mapCount) { + return std::nullopt; + } + + const u32 tableOffset = fixedMapTableOffset + (mapIndex * fixedMapTableRowSize); + const auto mapOffset = readU32Le(archive.bytes, tableOffset); + const auto mapSize = readU32Le(archive.bytes, tableOffset + 4); + if (!mapOffset || !mapSize) { + return std::nullopt; + } + if (*mapOffset > archive.bytes.size() || *mapSize > archive.bytes.size() - *mapOffset) { + return std::nullopt; + } + if ((*mapSize % fixedMapRecordSize) != 0) { + return std::nullopt; + } + + FixedMap map; + map.index = mapIndex; + for (u32 offset = *mapOffset; offset < *mapOffset + *mapSize; offset += fixedMapRecordSize) { + const auto entry = readFixedMapEntry(archive.bytes, offset); + if (!entry) { + return std::nullopt; + } + map.entries.push_back(*entry); + } + return map; +} + +} // namespace remorse diff --git a/rebuild/remorse/src/flex_archive.cpp b/rebuild/remorse/src/flex_archive.cpp new file mode 100644 index 0000000..ee74447 --- /dev/null +++ b/rebuild/remorse/src/flex_archive.cpp @@ -0,0 +1,83 @@ +#include "remorse/flex_archive.h" + +#include "remorse/file_system.h" + +namespace remorse { +namespace { + +constexpr u32 flexCountOffset = 0x54; +constexpr u32 flexTableOffset = 0x80; +constexpr u32 flexEntrySize = 8; + +std::optional readU32Le(const std::vector& bytes, u32 offset) +{ + if (offset + 4 > bytes.size()) { + return std::nullopt; + } + + return static_cast(bytes[offset]) | + (static_cast(bytes[offset + 1]) << 8) | + (static_cast(bytes[offset + 2]) << 16) | + (static_cast(bytes[offset + 3]) << 24); +} + +} // namespace + +std::optional loadFlexArchive(const std::filesystem::path& path) +{ + auto bytes = readBinaryFile(path); + if (!bytes) { + return std::nullopt; + } + + const auto entryCount = readU32Le(*bytes, flexCountOffset); + if (!entryCount) { + return std::nullopt; + } + + const u32 tableEnd = flexTableOffset + (*entryCount * flexEntrySize); + if (tableEnd > bytes->size()) { + return std::nullopt; + } + + FlexArchive archive; + archive.entryCount = *entryCount; + archive.bytes = *bytes; + + for (u32 index = 0; index < archive.entryCount; ++index) { + const u32 tableOffset = flexTableOffset + (index * flexEntrySize); + const auto dataOffset = readU32Le(archive.bytes, tableOffset); + const auto dataSize = readU32Le(archive.bytes, tableOffset + 4); + if (!dataOffset || !dataSize) { + return std::nullopt; + } + + if (*dataOffset == 0 && *dataSize == 0) { + continue; + } + if (*dataOffset == 0 || *dataSize == 0) { + continue; + } + if (*dataOffset > archive.bytes.size() || *dataSize > archive.bytes.size() - *dataOffset) { + continue; + } + + archive.populatedEntries.push_back(FlexEntry{index, *dataOffset, *dataSize}); + } + + return archive; +} + +std::optional> readFlexEntry(const FlexArchive& archive, u32 index) +{ + for (const FlexEntry& entry : archive.populatedEntries) { + if (entry.index == index) { + const auto begin = archive.bytes.begin() + entry.offset; + const auto end = begin + entry.size; + return std::vector(begin, end); + } + } + return std::nullopt; +} + +} // namespace remorse diff --git a/rebuild/remorse/src/glob_archive.cpp b/rebuild/remorse/src/glob_archive.cpp new file mode 100644 index 0000000..7680f8b --- /dev/null +++ b/rebuild/remorse/src/glob_archive.cpp @@ -0,0 +1,56 @@ +#include "remorse/glob_archive.h" + +#include "remorse/flex_archive.h" + +namespace remorse { +namespace { + +constexpr u32 globCountSize = 2; +constexpr u32 globEntrySize = 6; + +u16 readU16Le(const std::vector& bytes, u32 offset) +{ + return static_cast(bytes[offset] | (static_cast(bytes[offset + 1]) << 8)); +} + +} // namespace + +std::optional> loadGlobObjects(const std::filesystem::path& path) +{ + const auto archive = loadFlexArchive(path); + if (!archive) { + return std::nullopt; + } + + std::vector objects; + for (const FlexEntry& flexEntry : archive->populatedEntries) { + const auto bytes = readFlexEntry(*archive, flexEntry.index); + if (!bytes || bytes->size() < globCountSize) { + return std::nullopt; + } + + const u16 entryCount = readU16Le(*bytes, 0); + const u32 expectedSize = globCountSize + static_cast(entryCount) * globEntrySize; + if (expectedSize > bytes->size()) { + return std::nullopt; + } + + GlobObject object; + object.index = flexEntry.index; + for (u32 index = 0; index < entryCount; ++index) { + const u32 offset = globCountSize + index * globEntrySize; + GlobObjectEntry entry; + entry.x = (*bytes)[offset]; + entry.y = (*bytes)[offset + 1]; + entry.z = (*bytes)[offset + 2]; + entry.shape = readU16Le(*bytes, offset + 3); + entry.frame = (*bytes)[offset + 5]; + object.entries.push_back(entry); + } + objects.push_back(object); + } + + return objects; +} + +} // namespace remorse diff --git a/rebuild/remorse/src/main.cpp b/rebuild/remorse/src/main.cpp new file mode 100644 index 0000000..64d862a --- /dev/null +++ b/rebuild/remorse/src/main.cpp @@ -0,0 +1,69 @@ +#include "remorse/combat_tactics.h" +#include "remorse/entity_dispatch_entry.h" +#include "remorse/file_system.h" +#include "remorse/flex_archive.h" +#include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" +#include "remorse/palette.h" +#include "remorse/runtime.h" +#include "remorse/type_flags.h" + +#include +#include + +int main(int argc, char** argv) +{ + const std::filesystem::path manifestPath = argc > 1 + ? std::filesystem::path(argv[1]) + : remorse::defaultManifestPath(std::filesystem::current_path()); + + const auto manifest = remorse::loadExportManifestSummary(manifestPath); + if (!manifest) { + std::cerr << "Could not read export manifest: " << manifestPath.string() << '\n'; + return 2; + } + + remorse::printStartupReport(*manifest); + remorse::EntityDispatchEntryBase entry{}; + remorse::EntityDispatchEntry::initBase(&entry); + remorse::EntityDispatchEntry::setGroupId(entry, 1); + + const auto gameDataRoot = remorse::findGameDataRoot(std::filesystem::current_path()); + std::cout << "Game data root: " << (gameDataRoot ? gameDataRoot->path.string() : "not found") << '\n'; + if (gameDataRoot) { + const auto palettePath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("STATIC") / "GAMEPAL.PAL"); + const auto paletteBytes = palettePath ? remorse::readBinaryFile(*palettePath) : std::nullopt; + std::cout << "GAMEPAL.PAL bytes: " << (paletteBytes ? paletteBytes->size() : 0) << '\n'; + const auto palette = palettePath ? remorse::loadPalette256(*palettePath) : std::nullopt; + std::cout << "GAMEPAL.PAL colors: " << (palette ? palette->colors.size() : 0) << '\n'; + + const auto combatPath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("STATIC") / "COMBAT.DAT"); + const auto combatArchive = combatPath ? remorse::loadFlexArchive(*combatPath) : std::nullopt; + std::cout << "COMBAT.DAT populated entries: " << (combatArchive ? combatArchive->populatedEntries.size() : 0) << '\n'; + const auto combatTactics = combatPath ? remorse::loadCombatTactics(*combatPath) : std::nullopt; + std::cout << "COMBAT.DAT tactics: " << (combatTactics ? combatTactics->size() : 0) << '\n'; + + const auto fixedPath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("STATIC") / "FIXED.DAT"); + const auto fixedArchive = fixedPath ? remorse::loadFixedMapArchive(*fixedPath) : std::nullopt; + std::cout << "FIXED.DAT maps: " << (fixedArchive ? fixedArchive->mapCount : 0) << '\n'; + if (fixedArchive) { + for (remorse::u32 index = 0; index < fixedArchive->mapCount; ++index) { + const auto map = remorse::loadFixedMap(*fixedArchive, index); + if (map && !map->entries.empty()) { + std::cout << "FIXED.DAT first non-empty map: " << index << '\n'; + std::cout << "FIXED.DAT first non-empty entries: " << map->entries.size() << '\n'; + break; + } + } + } + + const auto globPath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("STATIC") / "GLOB.FLX"); + const auto globObjects = globPath ? remorse::loadGlobObjects(*globPath) : std::nullopt; + std::cout << "GLOB.FLX objects: " << (globObjects ? globObjects->size() : 0) << '\n'; + + const auto typeFlagPath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); + const auto typeFlags = typeFlagPath ? remorse::loadTypeFlags(*typeFlagPath) : std::nullopt; + std::cout << "TYPEFLAG.DAT shapes: " << (typeFlags ? typeFlags->size() : 0) << '\n'; + } + return 0; +} diff --git a/rebuild/remorse/src/map_preview_main.cpp b/rebuild/remorse/src/map_preview_main.cpp new file mode 100644 index 0000000..973b0f4 --- /dev/null +++ b/rebuild/remorse/src/map_preview_main.cpp @@ -0,0 +1,51 @@ +#include "remorse/file_system.h" +#include "remorse/map_renderer.h" + +#include +#include +#include + +int main(int argc, char** argv) +{ + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); + if (!root) { + std::cerr << "Could not locate Crusader game data root.\n"; + return 2; + } + + remorse::MapRenderOptions options; + std::filesystem::path outputPath = std::filesystem::path("rebuild") / "remorse" / "out" / "preview" / "map-preview.bmp"; + if (argc > 1) { + outputPath = argv[1]; + } + if (argc > 2) { + options.mapIndex = static_cast(std::stoul(argv[2], nullptr, 0)); + } + if (argc == 7) { + options.worldRect = remorse::WorldRect{ + std::stoi(argv[3], nullptr, 0), + std::stoi(argv[4], nullptr, 0), + std::stoi(argv[5], nullptr, 0), + std::stoi(argv[6], nullptr, 0)}; + } + + const auto image = remorse::renderMapPreview(*root, options); + if (!image) { + std::cerr << "Could not render map preview.\n"; + return 1; + } + if (!remorse::writeBmp24(outputPath, *image)) { + std::cerr << "Could not write preview BMP: " << outputPath.string() << '\n'; + return 1; + } + + std::cout << "Preview: " << outputPath.string() << '\n'; + std::cout << "Map: " << options.mapIndex << '\n'; + std::cout << "Raw fixed items: " << image->rawItemCount << '\n'; + std::cout << "Render items after filters/globs: " << image->renderItemCount << '\n'; + std::cout << "Decoded items: " << image->decodedItemCount << '\n'; + std::cout << "Painted items in crop: " << image->paintedItemCount << '\n'; + std::cout << "Image size: " << image->width << "x" << image->height << '\n'; + std::cout << "Full scene bounds: " << image->fullWidth << "x" << image->fullHeight << '\n'; + return 0; +} diff --git a/rebuild/remorse/src/map_renderer.cpp b/rebuild/remorse/src/map_renderer.cpp new file mode 100644 index 0000000..a205dbc --- /dev/null +++ b/rebuild/remorse/src/map_renderer.cpp @@ -0,0 +1,362 @@ +#include "remorse/map_renderer.h" + +#include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" +#include "remorse/shape_archive.h" +#include "remorse/type_flags.h" + +#include +#include +#include + +namespace remorse { +namespace { + +constexpr u16 flagInvisible = 0x0010; +constexpr u16 flagFlipped = 0x0020; +constexpr u32 siRoof = 0x0400; +constexpr s32 globCoordMask = ~0x3ff; +constexpr s32 globCoordShift = 2; +constexpr s32 globCoordOffset = 2; + +struct SceneItem { + s32 x = 0; + s32 y = 0; + s32 z = 0; + u16 shape = 0; + u8 frame = 0; + u16 flags = 0; + u16 quality = 0; + u8 mapNumber = 0; + bool fromFixed = true; +}; + +struct RenderNode { + SceneItem item; + DecodedShapeFrame decoded; + s32 left = 0; + s32 top = 0; + s32 right = 0; + s32 bottom = 0; +}; + +bool isEggFamily(u8 family) +{ + return family == 3 || family == 4 || family == 7 || family == 8; +} + +bool inWorldRect(const SceneItem& item, const std::optional& rect) +{ + if (!rect) { + return true; + } + return item.x >= rect->minX && item.x <= rect->maxX && item.y >= rect->minY && item.y <= rect->maxY; +} + +RgbColor scalePaletteColor(const RgbColor& color) +{ + RgbColor scaled; + scaled.red = static_cast((static_cast(color.red) * 255) / 63); + scaled.green = static_cast((static_cast(color.green) * 255) / 63); + scaled.blue = static_cast((static_cast(color.blue) * 255) / 63); + return scaled; +} + +std::optional findGlobObject(const std::vector& globs, u32 index) +{ + for (const GlobObject& object : globs) { + if (object.index == index) { + return object; + } + } + return std::nullopt; +} + +std::vector collectSceneItems( + const FixedMap& fixedMap, + const std::vector& typeFlags, + const std::vector& globs, + const MapRenderOptions& options) +{ + std::vector pending; + pending.reserve(fixedMap.entries.size()); + for (const FixedMapEntry& entry : fixedMap.entries) { + pending.push_back(SceneItem{ + static_cast(entry.x), + static_cast(entry.y), + static_cast(entry.z), + entry.shape, + entry.frame, + entry.flags, + entry.quality, + entry.mapNumber, + true}); + } + + std::vector items; + for (std::size_t index = 0; index < pending.size(); ++index) { + const SceneItem item = pending[index]; + if (!inWorldRect(item, options.worldRect)) { + continue; + } + if (item.shape >= typeFlags.size()) { + continue; + } + const ShapeTypeInfo& info = typeFlags[item.shape]; + if ((item.flags & flagInvisible) != 0 && !options.includeHiddenMarkers) { + continue; + } + if ((info.flags & siRoof) != 0 && !options.includeRoofs) { + continue; + } + if (options.expandGlobs && info.family == 3 && item.fromFixed) { + const auto glob = findGlobObject(globs, item.quality); + if (glob) { + for (const GlobObjectEntry& entry : glob->entries) { + pending.push_back(SceneItem{ + (item.x & globCoordMask) + (static_cast(entry.x) << globCoordShift) + globCoordOffset, + (item.y & globCoordMask) + (static_cast(entry.y) << globCoordShift) + globCoordOffset, + item.z + entry.z, + entry.shape, + entry.frame, + 0, + 0, + item.mapNumber, + false}); + } + } + if (!options.includeHiddenMarkers) { + continue; + } + } + if (isEggFamily(info.family) && !options.includeHiddenMarkers) { + continue; + } + items.push_back(item); + } + return items; +} + +s32 screenX(const SceneItem& item) +{ + return (item.x - item.y) / 4; +} + +s32 screenY(const SceneItem& item) +{ + return (item.x + item.y) / 8 - item.z; +} + +std::optional cachedDecode( + const ShapeArchive& archive, + std::map, DecodedShapeFrame>& cache, + u32 shape, + u32 frame) +{ + const auto key = std::make_pair(shape, frame); + const auto found = cache.find(key); + if (found != cache.end()) { + return found->second; + } + const auto decoded = decodeShapeFrame(archive, shape, frame); + if (!decoded) { + return std::nullopt; + } + cache.emplace(key, *decoded); + return decoded; +} + +std::vector prepareRenderNodes(const std::vector& items, const ShapeArchive& shapeArchive) +{ + std::map, DecodedShapeFrame> cache; + std::vector nodes; + for (const SceneItem& item : items) { + const auto decoded = cachedDecode(shapeArchive, cache, item.shape, item.frame); + if (!decoded) { + continue; + } + + const s32 bottomX = screenX(item); + const s32 bottomY = screenY(item); + const bool flipped = (item.flags & flagFlipped) != 0; + RenderNode node; + node.item = item; + node.decoded = *decoded; + node.left = flipped + ? bottomX + node.decoded.frame.xOffset - static_cast(node.decoded.frame.width) + : bottomX - node.decoded.frame.xOffset; + node.top = bottomY - node.decoded.frame.yOffset; + node.right = node.left + static_cast(node.decoded.frame.width); + node.bottom = node.top + static_cast(node.decoded.frame.height); + nodes.push_back(node); + } + + std::sort(nodes.begin(), nodes.end(), [](const RenderNode& left, const RenderNode& right) { + const s32 leftKey = left.item.x + left.item.y; + const s32 rightKey = right.item.x + right.item.y; + if (leftKey != rightKey) { + return leftKey < rightKey; + } + if (left.item.z != right.item.z) { + return left.item.z < right.item.z; + } + if (left.item.y != right.item.y) { + return left.item.y < right.item.y; + } + return left.item.x < right.item.x; + }); + return nodes; +} + +void paintNode(RenderedMapImage& image, const RenderNode& node, const Palette256& palette) +{ + const bool flipped = (node.item.flags & flagFlipped) != 0; + for (u32 sourceY = 0; sourceY < node.decoded.frame.height; ++sourceY) { + const s32 destY = node.top - image.sourceTop + static_cast(sourceY); + if (destY < 0 || destY >= static_cast(image.height)) { + continue; + } + const std::size_t sourceRow = static_cast(sourceY) * node.decoded.frame.width; + for (u32 sourceX = 0; sourceX < node.decoded.frame.width; ++sourceX) { + const u32 actualSourceX = flipped ? node.decoded.frame.width - 1 - sourceX : sourceX; + const s16 colorIndex = node.decoded.pixels[sourceRow + actualSourceX]; + if (colorIndex < 0 || colorIndex >= 256) { + continue; + } + const s32 destX = node.left - image.sourceLeft + static_cast(sourceX); + if (destX < 0 || destX >= static_cast(image.width)) { + continue; + } + image.pixels[static_cast(destY) * image.width + destX] = scalePaletteColor(palette.colors[colorIndex]); + } + } +} + +void writeLe16(std::ofstream& output, u16 value) +{ + output.put(static_cast(value & 0xff)); + output.put(static_cast((value >> 8) & 0xff)); +} + +void writeLe32(std::ofstream& output, u32 value) +{ + output.put(static_cast(value & 0xff)); + output.put(static_cast((value >> 8) & 0xff)); + output.put(static_cast((value >> 16) & 0xff)); + output.put(static_cast((value >> 24) & 0xff)); +} + +} // namespace + +std::optional renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options) +{ + const auto fixedPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "FIXED.DAT"); + const auto globPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "GLOB.FLX"); + const auto shapePath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "SHAPES.FLX"); + const auto palettePath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "GAMEPAL.PAL"); + const auto typeFlagPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); + if (!fixedPath || !globPath || !shapePath || !palettePath || !typeFlagPath) { + return std::nullopt; + } + + const auto fixedArchive = loadFixedMapArchive(*fixedPath); + const auto fixedMap = fixedArchive ? loadFixedMap(*fixedArchive, options.mapIndex) : std::nullopt; + const auto globs = loadGlobObjects(*globPath); + const auto shapeArchive = loadShapeArchive(*shapePath); + const auto palette = loadPalette256(*palettePath); + const auto typeFlags = loadTypeFlags(*typeFlagPath); + if (!fixedMap || !globs || !shapeArchive || !palette || !typeFlags) { + return std::nullopt; + } + + const auto items = collectSceneItems(*fixedMap, *typeFlags, *globs, options); + auto nodes = prepareRenderNodes(items, *shapeArchive); + if (nodes.empty()) { + return std::nullopt; + } + + s32 minLeft = nodes[0].left; + s32 minTop = nodes[0].top; + s32 maxRight = nodes[0].right; + s32 maxBottom = nodes[0].bottom; + for (const RenderNode& node : nodes) { + minLeft = std::min(minLeft, node.left); + minTop = std::min(minTop, node.top); + maxRight = std::max(maxRight, node.right); + maxBottom = std::max(maxBottom, node.bottom); + } + + RenderedMapImage image; + image.rawItemCount = static_cast(fixedMap->entries.size()); + image.renderItemCount = static_cast(items.size()); + image.decodedItemCount = static_cast(nodes.size()); + image.sourceLeft = nodes[0].left; + image.sourceTop = nodes[0].top; + image.fullWidth = maxRight - minLeft; + image.fullHeight = maxBottom - minTop; + image.width = std::min(options.maxWidth, static_cast(std::max(1, image.fullWidth))); + image.height = std::min(options.maxHeight, static_cast(std::max(1, image.fullHeight))); + image.pixels.assign( + static_cast(image.width) * image.height, + RgbColor{static_cast(10), static_cast(12), static_cast(18)}); + + for (const RenderNode& node : nodes) { + if (node.right < image.sourceLeft || node.bottom < image.sourceTop || + node.left >= image.sourceLeft + static_cast(image.width) || + node.top >= image.sourceTop + static_cast(image.height)) { + continue; + } + paintNode(image, node, *palette); + ++image.paintedItemCount; + } + return image; +} + +bool writeBmp24(const std::filesystem::path& path, const RenderedMapImage& image) +{ + if (image.width == 0 || image.height == 0 || image.pixels.size() != static_cast(image.width) * image.height) { + return false; + } + std::filesystem::create_directories(path.parent_path()); + std::ofstream output(path, std::ios::binary); + if (!output) { + return false; + } + + const u32 rowStride = ((image.width * 3 + 3) / 4) * 4; + const u32 pixelBytes = rowStride * image.height; + const u32 fileSize = 54 + pixelBytes; + + output.put('B'); + output.put('M'); + writeLe32(output, fileSize); + writeLe16(output, 0); + writeLe16(output, 0); + writeLe32(output, 54); + writeLe32(output, 40); + writeLe32(output, image.width); + writeLe32(output, image.height); + writeLe16(output, 1); + writeLe16(output, 24); + writeLe32(output, 0); + writeLe32(output, pixelBytes); + writeLe32(output, 2835); + writeLe32(output, 2835); + writeLe32(output, 0); + writeLe32(output, 0); + + std::vector row(rowStride, 0); + for (s32 y = static_cast(image.height) - 1; y >= 0; --y) { + std::fill(row.begin(), row.end(), static_cast(0)); + for (u32 x = 0; x < image.width; ++x) { + const RgbColor& pixel = image.pixels[static_cast(y) * image.width + x]; + row[x * 3] = pixel.blue; + row[x * 3 + 1] = pixel.green; + row[x * 3 + 2] = pixel.red; + } + output.write(reinterpret_cast(row.data()), row.size()); + } + return static_cast(output); +} + +} // namespace remorse diff --git a/rebuild/remorse/src/palette.cpp b/rebuild/remorse/src/palette.cpp new file mode 100644 index 0000000..5f49d97 --- /dev/null +++ b/rebuild/remorse/src/palette.cpp @@ -0,0 +1,23 @@ +#include "remorse/palette.h" + +#include "remorse/file_system.h" + +namespace remorse { + +std::optional loadPalette256(const std::filesystem::path& path) +{ + const auto bytes = readBinaryFile(path); + if (!bytes || bytes->size() != 256 * 3) { + return std::nullopt; + } + + Palette256 palette; + for (std::size_t index = 0; index < palette.colors.size(); ++index) { + palette.colors[index].red = (*bytes)[index * 3]; + palette.colors[index].green = (*bytes)[index * 3 + 1]; + palette.colors[index].blue = (*bytes)[index * 3 + 2]; + } + return palette; +} + +} // namespace remorse diff --git a/rebuild/remorse/src/runtime.cpp b/rebuild/remorse/src/runtime.cpp new file mode 100644 index 0000000..3114f8c --- /dev/null +++ b/rebuild/remorse/src/runtime.cpp @@ -0,0 +1,79 @@ +#include "remorse/runtime.h" + +#include +#include +#include +#include + +namespace remorse { +namespace { + +std::string readTextFile(const std::filesystem::path& path) +{ + std::ifstream input(path, std::ios::binary); + if (!input) { + return {}; + } + + std::ostringstream buffer; + buffer << input.rdbuf(); + return buffer.str(); +} + +std::optional readJsonString(const std::string& json, const char* key) +{ + const std::regex pattern(std::string("\\\"") + key + "\\\"\\s*:\\s*\\\"([^\\\"]*)\\\""); + std::smatch match; + if (!std::regex_search(json, match, pattern)) { + return std::nullopt; + } + return match[1].str(); +} + +u32 readJsonU32(const std::string& json, const char* key) +{ + const std::regex pattern(std::string("\\\"") + key + "\\\"\\s*:\\s*([0-9]+)"); + std::smatch match; + if (!std::regex_search(json, match, pattern)) { + return 0; + } + return static_cast(std::stoul(match[1].str())); +} + +} // namespace + +std::optional loadExportManifestSummary(const std::filesystem::path& manifestPath) +{ + const std::string json = readTextFile(manifestPath); + if (json.empty()) { + return std::nullopt; + } + + ExportManifestSummary summary; + summary.program = readJsonString(json, "program").value_or("unknown"); + summary.outputRoot = readJsonString(json, "outputRoot").value_or(""); + summary.functionFiles = readJsonU32(json, "functionFiles"); + summary.fallbackFunctionFiles = readJsonU32(json, "fallbackFunctionFiles"); + summary.globalBuckets = readJsonU32(json, "globalBuckets"); + summary.globalDefinitions = readJsonU32(json, "globalDefinitions"); + return summary; +} + +std::filesystem::path defaultManifestPath(const std::filesystem::path& currentPath) +{ + return currentPath / "exports" / "src_remorse" / "export_manifest.json"; +} + +void printStartupReport(const ExportManifestSummary& manifest) +{ + std::cout << "Crusader: No Remorse rebuild harness\n"; + std::cout << "Program: " << manifest.program << '\n'; + std::cout << "Export root: " << manifest.outputRoot.string() << '\n'; + std::cout << "Function files: " << manifest.functionFiles << '\n'; + std::cout << "Fallback function files: " << manifest.fallbackFunctionFiles << '\n'; + std::cout << "Global buckets: " << manifest.globalBuckets << '\n'; + std::cout << "Global definitions: " << manifest.globalDefinitions << '\n'; + std::cout << "Status: host runtime scaffold is alive; exported game code is not linked yet.\n"; +} + +} // namespace remorse diff --git a/rebuild/remorse/src/shape_archive.cpp b/rebuild/remorse/src/shape_archive.cpp new file mode 100644 index 0000000..5e4faef --- /dev/null +++ b/rebuild/remorse/src/shape_archive.cpp @@ -0,0 +1,205 @@ +#include "remorse/shape_archive.h" + +namespace remorse { +namespace { + +std::optional readU16Le(const std::vector& bytes, u32 offset) +{ + if (offset + 2 > bytes.size()) { + return std::nullopt; + } + return static_cast(bytes[offset] | (static_cast(bytes[offset + 1]) << 8)); +} + +std::optional readU24Le(const std::vector& bytes, u32 offset) +{ + if (offset + 3 > bytes.size()) { + return std::nullopt; + } + return static_cast(bytes[offset]) | + (static_cast(bytes[offset + 1]) << 8) | + (static_cast(bytes[offset + 2]) << 16); +} + +std::optional readU32Le(const std::vector& bytes, u32 offset) +{ + if (offset + 4 > bytes.size()) { + return std::nullopt; + } + return static_cast(bytes[offset]) | + (static_cast(bytes[offset + 1]) << 8) | + (static_cast(bytes[offset + 2]) << 16) | + (static_cast(bytes[offset + 3]) << 24); +} + +std::optional readS32Le(const std::vector& bytes, u32 offset) +{ + const auto value = readU32Le(bytes, offset); + if (!value) { + return std::nullopt; + } + return static_cast(*value); +} + +std::optional parseFrame(const std::vector& bytes, u32 frameOffset, u32 frameSize) +{ + if (frameOffset > bytes.size() || frameSize > bytes.size() - frameOffset || frameSize < 28) { + return std::nullopt; + } + + std::vector frameBytes(bytes.begin() + frameOffset, bytes.begin() + frameOffset + frameSize); + const auto compressed = readU32Le(frameBytes, 8); + const auto width = readU32Le(frameBytes, 12); + const auto height = readU32Le(frameBytes, 16); + const auto xOffset = readS32Le(frameBytes, 20); + const auto yOffset = readS32Le(frameBytes, 24); + if (!compressed || !width || !height || !xOffset || !yOffset) { + return std::nullopt; + } + + const u32 lineTableSize = *height * 4; + if (*height == 0 || *width == 0 || 28 + lineTableSize > frameBytes.size()) { + return std::nullopt; + } + + ShapeFrame frame; + frame.compressed = *compressed != 0; + frame.width = *width; + frame.height = *height; + frame.xOffset = *xOffset; + frame.yOffset = *yOffset; + const u32 rleOffset = 28 + lineTableSize; + for (u32 row = 0; row < frame.height; ++row) { + const auto storedOffset = readU32Le(frameBytes, 28 + row * 4); + if (!storedOffset) { + return std::nullopt; + } + const u32 rowFixup = (frame.height - row) * 4; + if (*storedOffset < rowFixup) { + return std::nullopt; + } + frame.lineOffsets.push_back(*storedOffset - rowFixup); + } + frame.rleData.assign(frameBytes.begin() + rleOffset, frameBytes.end()); + return frame; +} + +std::optional> decodePixels(const ShapeFrame& frame) +{ + if (frame.width == 0 || frame.height == 0 || frame.width > 4096 || frame.height > 4096) { + return std::nullopt; + } + + std::vector pixels(static_cast(frame.width) * frame.height, -1); + for (u32 row = 0; row < frame.height; ++row) { + if (row >= frame.lineOffsets.size()) { + return std::nullopt; + } + u32 pos = frame.lineOffsets[row]; + u32 x = 0; + while (x < frame.width) { + if (pos >= frame.rleData.size()) { + return std::nullopt; + } + x += frame.rleData[pos++]; + if (x == frame.width) { + break; + } + if (x > frame.width || pos >= frame.rleData.size()) { + return std::nullopt; + } + + u32 runLength = frame.rleData[pos++]; + u32 runType = 0; + if (frame.compressed) { + runType = runLength & 1; + runLength >>= 1; + } + if (runLength == 0 || x + runLength > frame.width) { + return std::nullopt; + } + + const std::size_t rowBase = static_cast(row) * frame.width + x; + if (runType == 0) { + if (pos + runLength > frame.rleData.size()) { + return std::nullopt; + } + for (u32 index = 0; index < runLength; ++index) { + pixels[rowBase + index] = frame.rleData[pos + index]; + } + pos += runLength; + } else { + if (pos >= frame.rleData.size()) { + return std::nullopt; + } + const s16 color = frame.rleData[pos++]; + for (u32 index = 0; index < runLength; ++index) { + pixels[rowBase + index] = color; + } + } + x += runLength; + } + } + return pixels; +} + +} // namespace + +std::optional loadShapeArchive(const std::filesystem::path& path) +{ + const auto flex = loadFlexArchive(path); + if (!flex) { + return std::nullopt; + } + ShapeArchive shapeArchive; + shapeArchive.archive = *flex; + return shapeArchive; +} + +std::optional> loadShapeFrames(const ShapeArchive& archive, u32 shapeIndex) +{ + const auto bytes = readFlexEntry(archive.archive, shapeIndex); + if (!bytes || bytes->size() < 6) { + return std::nullopt; + } + + const auto frameCount = readU16Le(*bytes, 4); + if (!frameCount || 6 + static_cast(*frameCount) * 8 > bytes->size()) { + return std::nullopt; + } + + std::vector frames; + for (u32 index = 0; index < *frameCount; ++index) { + const u32 headerOffset = 6 + index * 8; + const auto frameOffset = readU24Le(*bytes, headerOffset); + const auto frameSize = readU32Le(*bytes, headerOffset + 4); + if (!frameOffset || !frameSize) { + return std::nullopt; + } + const auto frame = parseFrame(*bytes, *frameOffset, *frameSize); + if (!frame) { + return std::nullopt; + } + frames.push_back(*frame); + } + return frames; +} + +std::optional decodeShapeFrame(const ShapeArchive& archive, u32 shapeIndex, u32 frameIndex) +{ + const auto frames = loadShapeFrames(archive, shapeIndex); + if (!frames || frameIndex >= frames->size()) { + return std::nullopt; + } + const auto pixels = decodePixels((*frames)[frameIndex]); + if (!pixels) { + return std::nullopt; + } + + DecodedShapeFrame decoded; + decoded.frame = (*frames)[frameIndex]; + decoded.pixels = *pixels; + return decoded; +} + +} // namespace remorse diff --git a/rebuild/remorse/src/type_flags.cpp b/rebuild/remorse/src/type_flags.cpp new file mode 100644 index 0000000..abe64fd --- /dev/null +++ b/rebuild/remorse/src/type_flags.cpp @@ -0,0 +1,38 @@ +#include "remorse/type_flags.h" + +#include "remorse/file_system.h" + +namespace remorse { + +std::optional> loadTypeFlags(const std::filesystem::path& path) +{ + const auto bytes = readBinaryFile(path); + if (!bytes || (bytes->size() % 9) != 0) { + return std::nullopt; + } + + std::vector infos; + for (u32 offset = 0; offset < bytes->size(); offset += 9) { + const u8 byte0 = (*bytes)[offset]; + const u8 byte1 = (*bytes)[offset + 1]; + const u8 byte2 = (*bytes)[offset + 2]; + const u8 byte3 = (*bytes)[offset + 3]; + const u8 byte4 = (*bytes)[offset + 4]; + const u8 byte6 = (*bytes)[offset + 6]; + + ShapeTypeInfo info; + info.flags = static_cast(byte0) | + (static_cast(byte1 & 0x0f) << 8) | + (static_cast(byte6) << 12); + info.family = static_cast((byte1 >> 4) + ((byte2 & 1) << 4)); + info.x = static_cast(((byte3 << 3) | (byte2 >> 5)) & 0x1f); + info.y = static_cast((byte3 >> 2) & 0x1f); + info.z = static_cast(((byte4 << 1) | (byte3 >> 7)) & 0x1f); + info.animationType = static_cast(byte4 >> 4); + infos.push_back(info); + } + + return infos; +} + +} // namespace remorse diff --git a/rebuild/remorse/tests/combat_tactics_tests.cpp b/rebuild/remorse/tests/combat_tactics_tests.cpp new file mode 100644 index 0000000..2c76946 --- /dev/null +++ b/rebuild/remorse/tests/combat_tactics_tests.cpp @@ -0,0 +1,23 @@ +#include "remorse/combat_tactics.h" +#include "remorse/file_system.h" + +#include +#include + +int main() +{ + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); + assert(root.has_value()); + + const auto combatPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "COMBAT.DAT"); + assert(combatPath.has_value()); + + const auto tactics = remorse::loadCombatTactics(*combatPath); + assert(tactics.has_value()); + assert(tactics->size() == 14); + assert((*tactics)[0].name == "Dumb"); + assert((*tactics)[0].blockOffsets[0] == 0x002c); + assert((*tactics)[0].blockOffsets[1] == 0x0031); + assert(!(*tactics)[0].bytecode.empty()); + return 0; +} diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp new file mode 100644 index 0000000..dbdd945 --- /dev/null +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -0,0 +1,26 @@ +#include "remorse/entity_dispatch_entry.h" + +#include + +int main() +{ + remorse::EntityDispatchEntryBase entry{}; + remorse::EntityDispatchEntry::initBase(&entry); + + remorse::EntityDispatchEntry::setSourceType(entry, 0x1234); + assert(entry.bytes[0x04] == 0x34); + assert(entry.bytes[0x05] == 0x12); + + remorse::EntityDispatchEntry::setEventTypeChecked(entry, 0x00f2); + assert(entry.bytes[0x06] == 0xf2); + assert(entry.bytes[0x07] == 0x00); + + entry.bytes[0x08] = 0xe0; + remorse::EntityDispatchEntry::setGroupId(entry, 0x23); + assert(entry.bytes[0x08] == 0xe3); + + remorse::EntityDispatchEntry::incrementGroupId(entry); + assert(entry.bytes[0x08] == 0xe4); + + return 0; +} diff --git a/rebuild/remorse/tests/file_system_tests.cpp b/rebuild/remorse/tests/file_system_tests.cpp new file mode 100644 index 0000000..4e9dc6f --- /dev/null +++ b/rebuild/remorse/tests/file_system_tests.cpp @@ -0,0 +1,24 @@ +#include "remorse/file_system.h" + +#include +#include + +int main() +{ + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); + assert(root.has_value()); + assert(root->hasExecutable); + assert(root->hasStaticData); + assert(root->hasUsecode); + + const auto palettePath = remorse::resolveGameDataPath(*root, std::filesystem::path("static") / "gamepal.pal"); + assert(palettePath.has_value()); + + const auto paletteBytes = remorse::readBinaryFile(*palettePath); + assert(paletteBytes.has_value()); + assert(!paletteBytes->empty()); + + const auto blockedParent = remorse::resolveGameDataPath(*root, std::filesystem::path("..") / "CRUSADER.EXE"); + assert(!blockedParent.has_value()); + return 0; +} diff --git a/rebuild/remorse/tests/fixed_map_tests.cpp b/rebuild/remorse/tests/fixed_map_tests.cpp new file mode 100644 index 0000000..fcc14f3 --- /dev/null +++ b/rebuild/remorse/tests/fixed_map_tests.cpp @@ -0,0 +1,37 @@ +#include "remorse/file_system.h" +#include "remorse/fixed_map.h" + +#include +#include + +int main() +{ + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); + assert(root.has_value()); + + const auto fixedPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "FIXED.DAT"); + assert(fixedPath.has_value()); + + const auto archive = remorse::loadFixedMapArchive(*fixedPath); + assert(archive.has_value()); + assert(archive->mapCount > 0); + + const auto firstMap = remorse::loadFixedMap(*archive, 0); + assert(firstMap.has_value()); + assert(firstMap->index == 0); + + bool foundNonEmptyMap = false; + for (remorse::u32 index = 0; index < archive->mapCount; ++index) { + const auto map = remorse::loadFixedMap(*archive, index); + assert(map.has_value()); + if (!map->entries.empty()) { + foundNonEmptyMap = true; + break; + } + } + assert(foundNonEmptyMap); + + const auto outOfRange = remorse::loadFixedMap(*archive, archive->mapCount); + assert(!outOfRange.has_value()); + return 0; +} diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp new file mode 100644 index 0000000..deadc46 --- /dev/null +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -0,0 +1,27 @@ +#include "remorse/file_system.h" +#include "remorse/flex_archive.h" + +#include +#include + +int main() +{ + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); + assert(root.has_value()); + + const auto combatPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "COMBAT.DAT"); + assert(combatPath.has_value()); + + const auto archive = remorse::loadFlexArchive(*combatPath); + assert(archive.has_value()); + assert(archive->populatedEntries.size() == 14); + + const auto firstEntry = remorse::readFlexEntry(*archive, 0); + assert(firstEntry.has_value()); + assert(firstEntry->size() == 0x4f); + assert((*firstEntry)[0] == 'D'); + assert((*firstEntry)[1] == 'u'); + assert((*firstEntry)[2] == 'm'); + assert((*firstEntry)[3] == 'b'); + return 0; +} diff --git a/rebuild/remorse/tests/glob_archive_tests.cpp b/rebuild/remorse/tests/glob_archive_tests.cpp new file mode 100644 index 0000000..1992d05 --- /dev/null +++ b/rebuild/remorse/tests/glob_archive_tests.cpp @@ -0,0 +1,28 @@ +#include "remorse/file_system.h" +#include "remorse/glob_archive.h" + +#include +#include + +int main() +{ + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); + assert(root.has_value()); + + const auto globPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GLOB.FLX"); + assert(globPath.has_value()); + + const auto objects = remorse::loadGlobObjects(*globPath); + assert(objects.has_value()); + assert(!objects->empty()); + + bool foundObjectWithEntries = false; + for (const remorse::GlobObject& object : *objects) { + if (!object.entries.empty()) { + foundObjectWithEntries = true; + break; + } + } + assert(foundObjectWithEntries); + return 0; +} diff --git a/rebuild/remorse/tests/map_renderer_tests.cpp b/rebuild/remorse/tests/map_renderer_tests.cpp new file mode 100644 index 0000000..79cdd3b --- /dev/null +++ b/rebuild/remorse/tests/map_renderer_tests.cpp @@ -0,0 +1,25 @@ +#include "remorse/file_system.h" +#include "remorse/map_renderer.h" + +#include +#include + +int main() +{ + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); + assert(root.has_value()); + + remorse::MapRenderOptions options; + options.mapIndex = 1; + options.maxWidth = 320; + options.maxHeight = 200; + + const auto image = remorse::renderMapPreview(*root, options); + assert(image.has_value()); + assert(image->width > 0); + assert(image->height > 0); + assert(!image->pixels.empty()); + assert(image->decodedItemCount > 0); + assert(image->paintedItemCount > 0); + return 0; +} diff --git a/rebuild/remorse/tests/palette_tests.cpp b/rebuild/remorse/tests/palette_tests.cpp new file mode 100644 index 0000000..543c60b --- /dev/null +++ b/rebuild/remorse/tests/palette_tests.cpp @@ -0,0 +1,19 @@ +#include "remorse/file_system.h" +#include "remorse/palette.h" + +#include +#include + +int main() +{ + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); + assert(root.has_value()); + + const auto palettePath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GAMEPAL.PAL"); + assert(palettePath.has_value()); + + const auto palette = remorse::loadPalette256(*palettePath); + assert(palette.has_value()); + assert(palette->colors.size() == 256); + return 0; +} diff --git a/rebuild/remorse/tests/shape_archive_tests.cpp b/rebuild/remorse/tests/shape_archive_tests.cpp new file mode 100644 index 0000000..4d0197b --- /dev/null +++ b/rebuild/remorse/tests/shape_archive_tests.cpp @@ -0,0 +1,30 @@ +#include "remorse/file_system.h" +#include "remorse/shape_archive.h" + +#include +#include + +int main() +{ + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); + assert(root.has_value()); + + const auto shapesPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "SHAPES.FLX"); + assert(shapesPath.has_value()); + + const auto archive = remorse::loadShapeArchive(*shapesPath); + assert(archive.has_value()); + + bool decodedFrame = false; + for (remorse::u32 shape = 0; shape < archive->archive.entryCount; ++shape) { + const auto frame = remorse::decodeShapeFrame(*archive, shape, 0); + if (frame && !frame->pixels.empty()) { + assert(frame->frame.width > 0); + assert(frame->frame.height > 0); + decodedFrame = true; + break; + } + } + assert(decodedFrame); + return 0; +} diff --git a/rebuild/remorse/tests/type_flags_tests.cpp b/rebuild/remorse/tests/type_flags_tests.cpp new file mode 100644 index 0000000..10cc562 --- /dev/null +++ b/rebuild/remorse/tests/type_flags_tests.cpp @@ -0,0 +1,28 @@ +#include "remorse/file_system.h" +#include "remorse/type_flags.h" + +#include +#include + +int main() +{ + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); + assert(root.has_value()); + + const auto typeFlagPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); + assert(typeFlagPath.has_value()); + + const auto infos = remorse::loadTypeFlags(*typeFlagPath); + assert(infos.has_value()); + assert(infos->size() == 2048); + + bool foundGlobFamily = false; + for (const remorse::ShapeTypeInfo& info : *infos) { + if (info.family == 3) { + foundGlobFamily = true; + break; + } + } + assert(foundGlobFamily); + return 0; +} diff --git a/rebuild/remorse/tools/import_export_slice.py b/rebuild/remorse/tools/import_export_slice.py new file mode 100644 index 0000000..a9b9362 --- /dev/null +++ b/rebuild/remorse/tools/import_export_slice.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 + +from __future__ import annotations + +import argparse +import dataclasses +import pathlib +import re +import shutil +from collections.abc import Iterable + + +CALLING_CONVENTION_REPLACEMENTS = { + "__cdecl16far": "CR_FARCALL", + "__cdecl16near": "CR_CDECL", + "__stdcall16far": "CR_FARCALL", + "__stdcall16near": "CR_STDCALL", + "__cdecl": "CR_CDECL", + "__stdcall": "CR_STDCALL", + "__regcall": "CR_CDECL", +} + +EXPORT_HEADER_INCLUDE_RE = re.compile(r'#include\s+"(?:\.\./)*CRUSADER\.EXE\.h"') + + +@dataclasses.dataclass(frozen=True) +class ImportStats: + files_read: int = 0 + files_written: int = 0 + callconv_replacements: int = 0 + namespace_qualified_functions: int = 0 + unresolved_tokens: tuple[str, ...] = () + + +def normalize_text(text: str) -> tuple[str, int]: + replacement_count = 0 + text = EXPORT_HEADER_INCLUDE_RE.sub('#include "remorse/export_prelude.h"', text) + + for source, target in CALLING_CONVENTION_REPLACEMENTS.items(): + text, count = re.subn(rf"\b{re.escape(source)}\b", target, text) + replacement_count += count + + return text, replacement_count + + +def find_unresolved_tokens(text: str) -> tuple[str, ...]: + tokens = [] + for token in ("unaff_SS", "unaff_CS", "__return_storage_ptr__", "CONCAT22", "BADSPACEBASE"): + if token in text: + tokens.append(token) + return tuple(tokens) + + +def iter_source_files(source_root: pathlib.Path) -> Iterable[pathlib.Path]: + for path in sorted(source_root.rglob("*")): + if path.is_file() and path.suffix.lower() in {".c", ".h"}: + yield path + + +def import_slice(export_root: pathlib.Path, slice_path: pathlib.Path, output_root: pathlib.Path) -> ImportStats: + source_root = export_root / "functions" / slice_path + if not source_root.is_dir(): + raise FileNotFoundError(f"export slice does not exist: {source_root}") + + destination_root = output_root / slice_path + if destination_root.exists(): + shutil.rmtree(destination_root) + destination_root.mkdir(parents=True, exist_ok=True) + + files_read = 0 + files_written = 0 + callconv_replacements = 0 + namespace_qualified_functions = 0 + unresolved_tokens: set[str] = set() + + for source_file in iter_source_files(source_root): + files_read += 1 + relative_path = source_file.relative_to(source_root) + destination_name = relative_path.with_suffix(".cpp") if source_file.suffix.lower() == ".c" else relative_path + destination_file = destination_root / destination_name + destination_file.parent.mkdir(parents=True, exist_ok=True) + + original = source_file.read_text(encoding="utf-8", errors="replace") + normalized, replacement_count = normalize_text(original) + callconv_replacements += replacement_count + namespace_qualified_functions += normalized.count("Remorse::") + unresolved_tokens.update(find_unresolved_tokens(normalized)) + destination_file.write_text(normalized, encoding="utf-8", newline="\n") + files_written += 1 + + return ImportStats( + files_read=files_read, + files_written=files_written, + callconv_replacements=callconv_replacements, + namespace_qualified_functions=namespace_qualified_functions, + unresolved_tokens=tuple(sorted(unresolved_tokens)), + ) + + +def write_report(path: pathlib.Path, slice_path: pathlib.Path, stats: ImportStats) -> None: + lines = [ + "# Export Slice Import Report", + "", + f"Slice: `{slice_path.as_posix()}`", + f"Files read: {stats.files_read}", + f"Files written: {stats.files_written}", + f"Calling-convention replacements: {stats.callconv_replacements}", + f"Namespace-qualified references: {stats.namespace_qualified_functions}", + "", + "## Remaining Cleanup Signals", + "", + ] + + if stats.unresolved_tokens: + lines.extend(f"- `{token}`" for token in stats.unresolved_tokens) + else: + lines.append("- No tracked unresolved tokens found by this importer.") + + lines.extend( + [ + "", + "This is a staging import only. Do not link the generated files into the host rebuild until their types, globals, and segmented-pointer behavior are reviewed.", + "", + ] + ) + path.write_text("\n".join(lines), encoding="utf-8", newline="\n") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Stage one Ghidra-exported function slice for manual Remorse rebuild cleanup.") + parser.add_argument("slice", help="Path under exports/src_remorse/functions, such as classes/Remorse/EntityDispatchEntry") + parser.add_argument("--export-root", type=pathlib.Path, default=pathlib.Path("exports/src_remorse")) + parser.add_argument("--output-root", type=pathlib.Path, default=pathlib.Path("rebuild/remorse/imported")) + parser.add_argument("--report", type=pathlib.Path, default=pathlib.Path("rebuild/remorse/imported/import_report.md")) + return parser.parse_args() + + +def main() -> int: + args = parse_args() + slice_path = pathlib.Path(args.slice) + stats = import_slice(args.export_root, slice_path, args.output_root) + args.report.parent.mkdir(parents=True, exist_ok=True) + write_report(args.report, slice_path, stats) + print(f"Imported {stats.files_written} files from {slice_path.as_posix()} into {args.output_root / slice_path}") + print(f"Report: {args.report}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 202679f8573522cbbd6a629c2ad38bb89885658a Mon Sep 17 00:00:00 2001 From: Maddo Date: Fri, 25 Sep 2026 21:41:20 +0200 Subject: [PATCH 02/14] Add comprehensive tests for collision detection, entity dispatch, file system, isometric controls, map rendering, and sorting - Implemented collision tests to verify overlap and movement logic for collision bodies. - Enhanced entity dispatch entry tests to cover initialization, group ID management, and process handling. - Expanded file system tests to include crash diagnostics and ensure proper game data root detection. - Created isometric controls tests to validate movement requests and screen projection calculations. - Added map renderer tests to check fixed map loading and rendering functionality. - Introduced map sorter tests to confirm correct rendering order for various items. --- docs/remorse-windows-rebuild-roadmap.md | 154 +++- docs/scummvm-crusader-movement-tap-turn.md | 63 ++ rebuild/remorse/CMakeLists.txt | 56 ++ rebuild/remorse/build_msvc.cmd | 9 +- .../include/remorse/animation_archive.h | 47 ++ rebuild/remorse/include/remorse/collision.h | 30 + .../include/remorse/detail/map_sorter.h | 46 ++ .../include/remorse/entity_dispatch_entry.h | 124 ++- .../include/remorse/isometric_controls.h | 42 + .../remorse/include/remorse/map_renderer.h | 13 + rebuild/remorse/include/remorse/runtime.h | 1 + rebuild/remorse/src/animation_archive.cpp | 135 +++ rebuild/remorse/src/collision.cpp | 156 ++++ rebuild/remorse/src/entity_dispatch_entry.cpp | 503 +++++++++++- rebuild/remorse/src/main.cpp | 46 +- rebuild/remorse/src/map_preview_main.cpp | 2 + rebuild/remorse/src/map_renderer.cpp | 101 ++- rebuild/remorse/src/map_sorter.cpp | 316 +++++++ rebuild/remorse/src/runtime.cpp | 69 +- rebuild/remorse/src/windowed_game_main.cpp | 770 ++++++++++++++++++ .../remorse/tests/animation_archive_tests.cpp | 149 ++++ rebuild/remorse/tests/collision_tests.cpp | 72 ++ .../tests/entity_dispatch_entry_tests.cpp | 463 ++++++++++- rebuild/remorse/tests/file_system_tests.cpp | 90 +- .../tests/isometric_controls_tests.cpp | 54 ++ rebuild/remorse/tests/map_renderer_tests.cpp | 30 + rebuild/remorse/tests/map_sorter_tests.cpp | 70 ++ 27 files changed, 3530 insertions(+), 81 deletions(-) create mode 100644 docs/scummvm-crusader-movement-tap-turn.md create mode 100644 rebuild/remorse/include/remorse/animation_archive.h create mode 100644 rebuild/remorse/include/remorse/collision.h create mode 100644 rebuild/remorse/include/remorse/detail/map_sorter.h create mode 100644 rebuild/remorse/include/remorse/isometric_controls.h create mode 100644 rebuild/remorse/src/animation_archive.cpp create mode 100644 rebuild/remorse/src/collision.cpp create mode 100644 rebuild/remorse/src/map_sorter.cpp create mode 100644 rebuild/remorse/src/windowed_game_main.cpp create mode 100644 rebuild/remorse/tests/animation_archive_tests.cpp create mode 100644 rebuild/remorse/tests/collision_tests.cpp create mode 100644 rebuild/remorse/tests/isometric_controls_tests.cpp create mode 100644 rebuild/remorse/tests/map_sorter_tests.cpp diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 55d24d5..cd82591 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -4,7 +4,17 @@ This note records the current effort to turn the live Ghidra analysis and the exported C decompilation of `CRUSADER.EXE` into a source tree that can be recompiled and eventually run on Windows, including modern Windows. -The short version: the project now has enough decompiled coverage to start a real rebuild lane, but the exported files are still evidence, not directly compilable game source. The safest path is to keep the export as an input corpus and move cleaned, subsystem-sized slices into a separate host rebuild tree with explicit ABI and platform boundaries. +The deliverable is a functioning modern Windows game compiled from cleaned, traceable decompiled `CRUSADER.EXE` game code. Replace DOS/Phar Lap and hardware services at their call boundaries; retain and repair the original control flow, data structures, scheduler, rendering, input semantics, and gameplay logic wherever recoverable. This is a source port, not a clean-room engine reconstruction. Modding is a later goal, not an initial acceptance criterion. + +The exported files are evidence, not directly compilable game source. Keep them unchanged and move verified, subsystem-sized function bodies into the rebuild tree, recording each original address and any corrections to decompiler artifacts. Do not substitute a newly designed gameplay implementation for an unported function and call that function complete. + +## Recompilation Gate + +- Every claimed port identifies its original NE address, exported function, unresolved decompiler ambiguities, and host-only substitutions. Distinguish direct translations, behaviorally verified ports, and temporary stand-ins. +- Compile recovered game functions into `remorse_core`; call them from the runtime path that needs them, not only from isolated tests. Tests should compare state transitions, side effects, and error paths with binary/decompiler evidence where possible. +- Keep DOS file, memory, timing, input, video, and audio replacements behind explicit platform boundaries. Resource parsers and the current preview/window remain useful diagnostics, but are not substitutes for porting the original game loop and its callees. +- At each milestone, count original functions translated and exercised in the Windows build, platform calls replaced, and parity checks passed. A rendered scene or a controllable stand-in actor alone does not pass a game-code milestone. +- Do not claim whole-game recompilation until startup, game ticks, interactions, mission flow, save/load, and presentation are driven by ported game code and playable on modern Windows using the original data. ## Current Inputs @@ -35,22 +45,27 @@ Current scaffold files: - `rebuild/remorse/include/remorse/palette.h`: first game-data parser for 256-color RGB palette files. - `rebuild/remorse/include/remorse/runtime.h`: minimal runtime/export-manifest surface. - `rebuild/remorse/include/remorse/shape_archive.h`: typed `SHAPES.FLX` shape-frame parser and row-RLE decoder. +- `rebuild/remorse/include/remorse/animation_archive.h`: bounds-checked raw `ANIM.DAT` lookup, direction/frame metadata, sprite-frame and flip extraction, and authored movement-step decoding. +- `rebuild/remorse/include/remorse/collision.h`: TYPEFLAG-sized collision volumes, swept movement query, and fixed-map/GLOB solid-volume extraction. - `rebuild/remorse/include/remorse/type_flags.h`: typed `TYPEFLAG.DAT` shape-family and flag decoder. - `rebuild/remorse/src/combat_tactics.cpp`: parses tactic names, four block offsets, and bytecode payloads from `COMBAT.DAT` entries. -- `rebuild/remorse/src/entity_dispatch_entry.cpp`: minimal host-side `EntityDispatchEntry` behavior stubs for compile-time shape and early probing. +- `rebuild/remorse/src/collision.cpp`: builds conservative solid volumes from fixed-map records and expanded glob children, then sweeps the player footpad against them. +- `rebuild/remorse/src/entity_dispatch_entry.cpp`: partial source translation of process lifecycle, the `11d0:0255` scan, `Process_Sleep`/`Unlink`, the 0x42-byte Stand constructor fields, `StandProcess::Run` (`1100:0359`), and a kernel-owned SystemTimer constructor/counter (`11c0:0000/00f8`). The harness executes the NPC decision tree through host services and delivers timer events explicitly; real NPC data, timer interrupts/rescheduling, keyboard lane, and complete game tick remain unported. - `rebuild/remorse/src/file_system.cpp`: repository/retail data-root discovery using modern `std::filesystem`. - `rebuild/remorse/src/flex_archive.cpp`: loader for count-at-`0x54`, table-at-`0x80` FLEX archives. - `rebuild/remorse/src/fixed_map.cpp`: loader for `FIXED.DAT` map tables and scaled fixed-map item coordinates. - `rebuild/remorse/src/glob_archive.cpp`: parser for glob object entry lists inside `GLOB.FLX`. - `rebuild/remorse/src/map_preview_main.cpp`: command-line preview executable for writing a viewable BMP image. +- `rebuild/remorse/src/windowed_game_main.cpp`: native Windows game shell, with async retail map/player/collision loading, shape-1 stand/walk/run sprites, metadata-driven 8-way movement, a following camera, and a position HUD. - `rebuild/remorse/src/map_renderer.cpp`: combines fixed maps, glob expansion, typeflags, shape frames, and palette data into a painted preview image. - `rebuild/remorse/src/palette.cpp`: `GAMEPAL.PAL`-style 768-byte palette parser. - `rebuild/remorse/src/runtime.cpp`: loads a summary from the Ghidra export manifest. - `rebuild/remorse/src/shape_archive.cpp`: ports the documented Crusader frame-table and row-RLE decode rules. +- `rebuild/remorse/src/animation_archive.cpp`: parses shape-indexed animation tables and direction-major frame metadata from raw `ANIM.DAT`. - `rebuild/remorse/src/type_flags.cpp`: ports the verified 9-byte Crusader typeflag decode from the map-rendering tool. - `rebuild/remorse/src/main.cpp`: starts the host harness and prints the export status. - `rebuild/remorse/tests/combat_tactics_tests.cpp`: checks `COMBAT.DAT` parses to 14 tactics and entry 0 is `Dumb`. -- `rebuild/remorse/tests/entity_dispatch_entry_tests.cpp`: first host-side check for the confirmed `EntityDispatchEntry` offsets. +- `rebuild/remorse/tests/entity_dispatch_entry_tests.cpp`: checks entry offsets, group counters, ID assignment, 30-slot growth, lifecycle, scheduler gates/spawn/cleanup, sleep writes, strict wake deadline, the owned Stand layout, NPC-gated `Run` branches, and timer-counter carry. - `rebuild/remorse/tests/file_system_tests.cpp`: first host-side check that the current repository root can be recognized as a game-data root. - `rebuild/remorse/tests/flex_archive_tests.cpp`: checks `STATIC/COMBAT.DAT` as a small FLEX archive with 14 populated records. - `rebuild/remorse/tests/fixed_map_tests.cpp`: checks `STATIC/FIXED.DAT` map count and map 0 item-record loading. @@ -58,10 +73,12 @@ Current scaffold files: - `rebuild/remorse/tests/map_renderer_tests.cpp`: checks map 1 can produce a non-empty preview image. - `rebuild/remorse/tests/palette_tests.cpp`: checks that `STATIC/GAMEPAL.PAL` parses into 256 colors. - `rebuild/remorse/tests/shape_archive_tests.cpp`: checks `STATIC/SHAPES.FLX` can decode at least one visible frame. +- `rebuild/remorse/tests/animation_archive_tests.cpp`: checks ANIM.DAT parsing, signed displacement and direction rotation, sprite-frame/flip decoding, and retail shape-1 stand/walk/run references. +- `rebuild/remorse/tests/collision_tests.cpp`: checks TYPEFLAG extents, swept obstruction, vertical clearance, flipped footprints, and fixed-map/GLOB placement extraction. - `rebuild/remorse/tests/type_flags_tests.cpp`: checks `STATIC/TYPEFLAG.DAT` parses 2,048 shape records and includes glob-family records. - `rebuild/remorse/tools/import_export_slice.py`: stages one exported function folder into `rebuild/remorse/imported/` for manual cleanup review. -This is not the game yet. It is the first buildable shell that future cleaned subsystems can link into without mutating the raw Ghidra export. +This is not the game yet. It is a buildable diagnostic host with a source-backed itemless process lifecycle, partial scheduler scan, owned Stand process layout, and recovered Stand `Run`/NPC decision and timer-counter branches. It does not have the original NPC service data, timer interrupt registration, or game loop. ## Why The Export Does Not Compile Yet @@ -87,7 +104,7 @@ It must preserve segmented pointers, far-call provenance, original-style packing ### Track B: Windows Source Port -This track uses the recovered source, object layouts, and resource formats to build a behaviorally equivalent Windows program. +This track compiles corrected decompiled game source, retaining original behavior and object layouts while replacing only the OS/hardware-facing calls needed to run it on Windows. It can replace DOS extender, VGA, sound, input, timing, file, and memory services with host implementations, but it should initially preserve exact-width data layouts and far-pointer provenance so behavior can be compared back to the original. @@ -95,18 +112,18 @@ For the stated goal of running on modern Windows, Track B is the practical prima ## Conversion Strategy -1. Keep `exports/src_remorse/` as generated evidence. -2. Move one subsystem at a time into `rebuild/remorse/` as cleaned C++. +1. Keep `exports/src_remorse/` as generated evidence; keep a function-address ledger of what was translated, what is still a stand-in, and which callers actually execute the translation. +2. Move one original call chain at a time into `rebuild/remorse/` as minimally corrected C/C++ with a documented address mapping and tests for the observed side effects. 3. Compile every moved slice immediately, even before it is runnable game logic. 4. Replace Ghidra pseudo-types with `remorse::u8`, `remorse::u16`, `remorse::u32`, `remorse::FarPtr16`, and explicit packed structs. 5. Convert Ghidra calling-convention tokens into marker macros from `compat.h` until the final host calling surface is chosen. 6. Keep raw address provenance in comments or mapping tables for every imported function. -7. Build host runtime shims for platform services before trying to run gameplay. -8. Validate behavior with extracted resources and deterministic smoke tests. +7. Implement host runtime shims at the DOS/hardware call boundaries encountered by the ported chain; avoid duplicating game logic in the shim. +8. Validate recovered behavior with binary evidence, retail resources, and deterministic trace/state comparisons; connect each port to its caller in the Windows runtime. ## Full Rebuild Plan -The practical target is Track B first: a modern Windows source port that loads original data and reproduces gameplay behavior. Track A remains an evidence constraint for layout, calling convention, far-pointer provenance, and validation. +The practical target is Track B: recompile recovered game logic for Windows and replace the DOS platform boundary. Track A remains an evidence constraint for layout, calling convention, far-pointer provenance, and validation. The phases below describe supporting capabilities, not permission to implement an independent game first: prioritize ported startup -> tick -> player/item process -> renderer/interaction call chains over further standalone host features. ### Phase 0: Build And Evidence Discipline @@ -117,6 +134,7 @@ Exit criteria: - `rebuild\remorse\build_msvc.cmd Debug` passes from the repository root - every imported subsystem has address/source provenance in code or docs - generated Ghidra exports remain input evidence, not hand-edited source +- at least one corrected exported function is compiled, tested against its documented side effects, and invoked by a host caller; list remaining placeholder behavior explicitly ### Phase 1: Host Runtime Foundation @@ -262,7 +280,52 @@ Exit criteria: a clean checkout/build can run against a retail data directory wi ## Current Execution Focus -The current active phase is Phase 2, core resource loaders. The immediate path is `FIXED.DAT` map table and item-record loading, then glob expansion, then shape-frame decoding, then a minimal map scene smoke test. +The current active work must shift from Phase 3 host presentation to decompiled source conversion and call-chain integration (Phases 0 and 4). Core Phase 2 loaders, the footpad-aware overlap sorter, and the Windows map window are diagnostic infrastructure. The actor uses retail stand/walk/run metadata, authored XYZ displacements, and the original 16-way direction table, but its 20 Hz host tick, conservative TYPEFLAG collision, and fixed-map boundary are not the recovered player process or original AreaSearch. Floor support, step-up/ledge handling, moving items, interactions, and USECODE remain unported. Keep the window as a test host, not as the implementation template for game logic. + +First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a8` (older `0008:bca8`) validates 1..31, updates the group byte at `+0x08`, and adjusts 16-bit counters through the far table pointer at `DS:39c5`. Live disassembly confirms the entry far pointer at `[BP+6]`, group byte at `[BP+0xa]`, and word-sized counter operations; the decompiler's `_group_id` alias is not a real implicit argument. The host receives the entry and table explicitly. `InitBase` at `11e0:0000` stamps the function-table words `0x3b06` (`+0x00`), `0x2d10` (`+0x1e`), `0x3afe` (`+0x28`), initializes the observed scalars, and seeds the group through `SetGroupId`. The seed comes from `DS:39c9` (written by `Kernel_11d0_19b5`); the host receives it as explicit runtime state. The unknown `+0x09` is not deliberately written. The host-owned path performs allocate -> initialize -> register, records default name/new-process metadata, executes the conditional current-process extflag branch, and applies the post-registration sync predicate. Itemless termination and slot reclamation are present. The scheduler scan applies normal-process group/flag gates and timer wake logic at `11d0:0255`, and its callback invokes the compiled `StandProcess::Run` branch for the 0x42-byte host-owned Stand entry. The `1100:026e` NPC decision gates are compiled, with their item/visibility/activity operations passed through host services. Owned Stand entries now maintain the per-item presence bit; the kernel-owned timer and keyboard constructors register their diagnostic processes. This is **not** a complete constructor or process system: stack-segment assertion, nonempty item child teardown, NPC service implementations, DOS timer/keyboard event delivery, end-of-pass work, other process `Run` functions, and far-memory behavior remain absent. `IncrementGroupId`, `SetSourceType`, and `SetEventTypeChecked` remain stand-ins; runtime binary parity is not established. + +### Process Source-Port Ledger + +| Exported function | Compiled status | Evidence and remaining boundary | +|---|---|---| +| `SetGroupId@11e0_02a8.c` (`0008:bca8`) | Partial translation; invoked from host `InitBase`, CTest transitions and invalid IDs | Live `11e0:02ae-031b`: group byte parameter at `[BP+0xa]`, far entry pointer at `[BP+6]`, 2-byte counter stride via `DS:39c5`, overwrite entire `+0x08` byte when changing group. Host exception replaces `AssertError`; counter-table ownership and runtime trace still need verification. | +| `InitBase@11e0_0000.c` (`0008:ba00`) | Function-table/scalar/group-seed subset plus host-owned allocate/register path; harness-invoked, CTest offsets, counters, IDs | Live `11e0:0006-014e`: optional alloc `11e0:014f`, table words `0x3b06/0x2d10/0x3afe`, group from `DS:39c9`, then `SetGroupId`, `Kernel_AddProcess` (`11d0:0aff`), conditional `Kernel_GetSomeProcId_11d0_177c` branch, `Process_11d0_19cd`. Host updates extflags `+0x18 |= 4` on an addressable, unterminated current process with bit `2` set; it still omits stack-segment assertion and segmented-pointer relocation. | +| `Kernel_GetNextFreeProcId` (`11d0:0a97`), `Kernel_11d0_0716` | First-free slot and 30-slot growth translated; registered in host harness and CTest | Live decompile scans far process-pointer slots, grows parallel pointer/size/name arrays by 30 up to 1020 entries. Host stores native pointers, sizes, and default names; the original far-address mapping is not implemented. `Process_GetProcById` (`11d0:0bf3`) treats ID 0 as null even though the raw slot allocator may choose it. | +| `Kernel_AddProcess` (`11d0:0aff`) | Process pointer, ID, allocation-size, count, optional new-process flag/counter, default-name subset translated | Live disassembly stamps `procid` at `+0x02`, consumes `g_kernelLastProcessAllocSize`, increments count, optionally sets `ExtProc_NewlyCreated` (`0x200`), and names the slot `Default`. Host omits initialized-state assertion, far-pointer representation, and runtime parity. | +| `Process_11d0_19cd` / `Process_11d0_19ec` | Sync-flag predicate translated on the host creation path | Live `11d0:19ef-1a07` tests kernel flag and `procid > current ID`; `11d0:19e2-19e5` ORs `0x40` into process flags at `+0x16`. The conditional `InitBase` current-process extflag branch is also translated, without runtime parity. | +| `Kernel_TerminteProcessByPid` (`11d0:18a3`), `Process_SetTerminatedState` | Immediate and deferred termination translated for host-owned base and zero-child-state Stand entries | Live `11d0:18e5-1939`: decrement group count; if extflags `+0x18 & 4`, clear slot and free immediately; otherwise set flags `+0x16 & 8`, increment terminated count; decrement live process count in either case. Host refreshes the per-item bit after termination; child lists, special event callbacks, and teardown for non-owned entries remain unported. | +| `Kernel_ClearProcessSomethingAndName` (`11d0:1972`), `Kernel_11d0_1dcc` | Slot pointer/size/name clear and deferred cleanup for IDs >= 3 translated; ID reuse exercised | Live cleanup scans from ID 3, requires `+0x1a == 0`, clears the slot, frees the entry, and decrements terminated count. The clear helper itself does not decrement live process count. Other scheduler cleanup paths and process destructor dispatch remain unported. | +| `FUN_11d0_0255` (`11d0:0255`) | Normal-process scan and timer wake translated; harness callback invokes compiled Stand `Run`, tests cover sleep/wake and scheduler gates | Live `11d0:02b4-03ac`: skip terminated, process sleep via `11e0:0379`, clear `Proc_Syncing` for one pass, skip nonzero `+0x24/+0x26`, `Proc_Waiting`, and off-group entries unless daemon or group 30/31; set current ID around vtable run call. Host receives an explicit timer tick, uses the original strict `start+duration < tick` wake comparison, and recognizes Stand's verified no-op completion slot (`1100:0fe3`); other completion targets remain unsupported. Immediate timer/keyboard interrupts, early-stop/group advance/table-maintenance tails, and general vtable dispatch remain unported. | +| `Process_Sleep` (`11e0:0320`), `EntityDispatchEntry::Unlink` (`11e0:0353`) | Flag and 32-bit timer writes/clear translated; exact byte offsets and wake deadline tested | Live sleep ORs `0x1000` at `+0x18`, snapshots timer into `+0x0a/+0x0c`, writes duration to `+0x0e/+0x10`; unlink clears the flag and those four words. Host receives a tick instead of reading the original timer-process pointer. | +| `NPCActionProcess::Create` (`1100:0000`), `StandProcess::CreateProcess` (`1100:02ed`) | Owned 0x42-byte Stand entry registered and run in harness; constructor fields, item number, and presence-bit transitions tested | Live chain stamps `+0x16 |= 0x300`, clears derived words `+0x32..0x3e`, stores NPC number at `+0x40`, ORs `0x101` at `+0x32`, sets Stand vtable `0x1f0f`, process name `Stand`, and event `0x258`. Host marks the item bit on registration and refreshes it after terminating a zero-child-state Stand, following `Item_MarkProcessPresent`/`Item_RefreshProcessPresenceFlag` (`11d0:3e0b/3e7f`). Item animation/cache reset, nonempty child-list destruction, and real NPC item ownership remain unported. | +| `NPC_StartBehaviorInField0x8IfCanSeeControlledNPC` (`1100:026e`), `StandProcess::Run` (`1100:0359`) | Compiled NPC decision/Stand run branches; tests cover off-screen sleep, visible behavior start, already-current sleep, and strict wake | Live `1100:0274-02e9` reads NPC number from `+0x40`, tests entirely-on-screen, nonzero field-8 activity, not-current activity `0x71`, can-see-controlled-NPC, and starts the next behavior; `1100:035c-0382` sleeps 60 on false. `1478:1f0f` starts with far `Run` pointer `1100:0359`. Host services supply visibility/activity/item effects and timer tick; no real NPC item, general vtable resolver, or binary trace parity. | +| `SystemTimerProcess_CreateProcess` (`11c0:0000`), `Process_RegisterForTimerEvents` (`11e0:19ba`), `Kernel_RegisterProcForTimerEvents` (`11d0:2dd8`), `SystemTimerProcess_Increment` (`11c0:00f8`) | Partial 0x4a-byte owned constructor and registered counter linked to harness and Windows diagnostic scheduler; zero initialization, 16-bit carry, uniqueness, process flags, registration gate, and strict Stand wake boundary tested | Exported `ConstructVtable3AD2/3AA6` (`11e0:14fb/1814`) sets interrupt/realtime flags and zeros the periodic tail; constructor stores period `0x3c` at `+0x36`, tail bit `2` at `+0x32`, and waiting/daemon/active-counter flags. Registration sets `Proc_GetTimerEvents` (`0x400`) and records the process ID; host delivery requires both. Increment carries from `+0x40` to `+0x42`. Original randomized reschedule, event type, active-counter globals, general timer list/dispatch, DOS interrupt source, and general timer teardown remain unported. | +| `KeyboardProcess_CreateProcess` (`11b8:02e1`), `Process_RegisterForKeyboardEvents` (`11e0:172a`), `Kernel_RegisterForKeyboardEvents` (`11d0:3b74`), `Process_SetKeyboardInterruptFlag` (`11e0:17a4`), `KeyboardProcess_HandleKeyEvent` (`11b8:03ad`) | Partial owned 0x36-byte keyboard process registered by harness and diagnostic window; layout, flags, singleton, exhaustion, teardown refusal, and accepted/rejected callback copies tested | Inherits `ConstructVtable3AD2` (`11e0:14fb`) interrupt flag `0x100`, registers `ExtProc_KeyboardEvents` (`0x80`) once, sets `Proc_Waiting|Proc_Daemon` (`0x3`) and `ExtProc_KeyboardInterrupt` (`0x100`). Live disassembly at `11b8:03c5-0418` and bytes `11b8:041a-041f` confirm filter pair `0x10,0`; a nonzero character and field `+0x08` copy 12 bytes from `g_lastKeyEvent` to the supplied event and clear tail `+0x32 & ~0x10`. Window `WM_CHAR` supplies a host-synthesized event for the diagnostic count only; original callback registry, `KeyDaemon`, event queue, modifier state, and player-input routing remain unported. | +| `KeyDaemon_CreateProcess` (`11b8:0000`) | Partial owned 0x40-byte constructor invoked after keyboard registration in harness and window; layout, singleton, and teardown refusal tested | Inherits `ConstructVtable3AD2/3AA6` (`11e0:14fb/1814`) interrupt/realtime flags `0x300`, sets `Proc_Daemon|Proc_Waiting` (`0x3`), `Proc_ImmediateTimer` (`0x2000`), timer-event bit `0x400`, derived tail `+0x32 |= 2`, and period `0x2d` at `+0x36`. The randomized schedule, timer list dispatch, held-key repeat callback, and DOS input state are not linked. | + +Live Ghidra MCP decompilation and disassembly have resolved local stack ABI, scheduler gates, and call order, not runtime state parity. Do not promote the Stand harness trace to gameplay behavior until its host-supplied NPC services and remaining tick services can be checked against execution. + +## First Interactive Windows Game Shell + +`rebuild/remorse/out/build-nmake/remorse_game.exe` is the first windowed application target. It locates the game data root from its own executable path (or the current directory), defaults to map 1, and accepts an optional fixed-map index from 0 through 255. + +From the repository root: + +```powershell +rebuild\remorse\build_msvc.cmd Debug +.\rebuild\remorse\out\build-nmake\remorse_game.exe 1 +``` + +The application builds the selected retail map scene and player assets on a worker thread, then displays a resizable Win32 window with the game palette and dependency-sorted map art. Shape 1 uses `ANIM.DAT` actions 0 (stand), 1 (walk), and 3 (unarmed run); frame metadata selects the `SHAPES.FLX` pose, horizontal flip, and movement delta. The original keypad direction mapping is supported alongside WASD/arrows and diagonal combinations. Shift and Caps Lock select walk/run using the controller's same-state rule. A 40 Hz host simulation tick advances frame steps against fixed-map and expanded-glob solid volumes; it now catches up after long paints instead of discarding all elapsed time beyond 50 ms. The retail signed displacement decoder is unchanged. The prototype's forward-only host movement step skips the small backward stride on walk frames 4 and 12 of directions 6/7/10/11, which had made both actor and following camera reverse mid-stride. This comfort policy and host tick rate are not recovered controller behavior. The persistent GDI back buffer avoids painting each moving frame directly to the window. The HUD shows map, world position, facing, and locomotion state. Collision is an axis-aligned TYPEFLAG approximation; it does not reproduce original AreaSearch shape sweeps or step-up behavior, and the fixed-map record bounds remain the outer movement limit. + +The second HUD row is an observable, separate process-runtime diagnostic: the host 40 Hz step delivers a registered SystemTimer event, advances the recovered scheduler scan, and runs an owned Stand entry through its verified off-screen sleep branch. Tick, remaining sleep ticks, and wake count update while the window is active. Three base entries reserve the low process IDs; the Stand entry and NPC number are diagnostic fixtures, not map NPCs or the player process. Host tick frequency is not the original DOS timer interrupt rate. +The diagnostic kernel also registers a partial KeyboardProcess and KeyDaemon at startup. Text-capable Win32 key messages exercise the recovered keyboard filter/copy callback and update the key-event count on the HUD. The daemon does not receive timer events yet. The visible WASD/keypad controls still use host polling; these processes do not yet deliver player input. + +The walk/run modifier choice is the isolated branch from `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. Win32 supplies modifier bits; NPC state, weapon-dependent actions, original keyboard events, and the remainder of the controller selector are not ported. Retail ANIM.DAT regression checks retain the signed reverse steps in the decoder while testing the host-only forward movement filter across all four affected walk directions. + +On Windows, `remorse_game.exe`, `remorse_rebuild.exe`, and `remorse_map_preview.exe` configure crash reports at startup. Debug CRT assertions do not open Abort/Retry/Ignore windows; the terminate handler reports active C++ exception messages to the Visual Studio Debug output and stderr when available. Escaped/unhandled Windows exceptions log their code/address and suppress the fault popup. The GUI executable has no console stderr by default, so attach a debugger to see that output. A timeout-bounded CTest child process exercises the terminate reporter without a modal prompt. This does not replace a full crash dump or catch process termination that bypasses user-mode handlers. + +This is the first interactive gameplay slice, not yet a playable game: movement has no actor collision response, and there are no enemies, triggers, sound, saves, or USECODE execution. The rendered map is the retail static scene, not a live simulation. ## Import-Slice Tool @@ -300,13 +363,13 @@ The first Windows runtime should prefer clear host abstractions over direct Win3 ## Recommended First Subsystems -The first source slices should be small enough to compile and test without the entire game loop. +Keep source slices small enough to compile and test while following original call edges, not independently designing a replacement engine. -1. Compatibility/runtime layer: exact types, packed layout helpers, far-pointer wrappers, host file paths, and logging. -2. Resource/file loading helpers from the low segments, with DOS file calls replaced by host file services. -3. Palette and fixed-format data structures, validated against known assets. -4. `EntityDispatchEntry` as the first class-like family because it already has a named export folder and prior class-lifting notes. -5. Sprite/node or map rendering data structures after basic resource loading is stable. +1. Finish the `EntityDispatchEntry`/`Process` constructor, group-table, and scheduler path, including its globals and kernel calls; `SetGroupId` alone is only a partial foothold. +2. Trace original startup and tick entrypoints into the process/player call chain, recording each address and the exact host service boundary it reaches. +3. Port resource/file functions actually called by that chain, mapping only DOS-facing calls to the existing host file service. +4. Port the original item/draw-list and render functions that consume the live process state; reuse decoded retail assets as parity fixtures. +5. Lift the input, movement, interaction, and VM calls reachable from the playable path, replacing prototype logic when original code becomes available. ## First Hand-Maintained Game Skeleton @@ -319,7 +382,7 @@ Current evidence used: - older note anchor recorded in the decompiler comment: `0008:ba00` - allocation size visible in the decompiled initializer: `0x32` bytes -The current rebuild skeleton preserves the 0x32-byte object size and provides host-side stubs for base init, group-id update, source/item update, and event/proc-type update. The first confirmed offsets from the exported setter bodies are: source item at `+0x04`, event/proc type at `+0x06`, and group id in the low five bits at `+0x08`. These names are still conservative because the surrounding `Process` layout is not fully lifted into typed fields yet. +The current rebuild skeleton preserves the 0x32-byte object size, translates group-ID counter transitions, and translates the table word stamps, scalar writes, and group-seed call from base init. A host-owned path now registers and reclaims itemless entries with first-free IDs, allocation-size/name bookkeeping, and the post-registration sync predicate. Source/item update and event/proc-type update remain stand-ins. The first confirmed offsets are: source item at `+0x04`, event/proc type at `+0x06`, and group ID in the low five bits at `+0x08`. The remaining item callbacks, kernel branches, and scheduler must be lifted before the process family can drive gameplay. ## First Windows Runtime Shim @@ -458,9 +521,9 @@ Validated preview: - painted items in the preview crop: 178 - full scene bounds: 30,977 x 15,617 -This is still a smoke renderer, not the final game renderer. It uses a simple stable paint order rather than the full engine/item-sorter dependency graph, but it proves the rebuild tree can now load original resources and produce a visible world image. +This is still a smoke renderer, not the final game renderer. It now derives world boxes from `TYPEFLAG.DAT`, resolves overlapping sprite bounds with the engine-style dependency graph, and applies the recovered `below()` ordering and occlusion rules. Runtime-only sprite sorting and specialized cases remain outside this host preview. -After reviewing the first preview, the chosen next direction is render correctness: port fuller item sorting, improve roof/hidden-object policy, and add better crop/navigation controls before moving to an interactive runtime. +The next renderer work is to validate window presentation and roof/hidden-object policy, then replace the debug marker with recovered player art and process behavior. ## Immediate Build Loop @@ -470,9 +533,9 @@ Until CMake and MSVC are available in PATH, the source scaffold can be edited an Current local toolchain finding: -- Visual Studio Community 2026 is installed at `I:\Apps\VS\18\Community`. -- After installing the Desktop C++ workload, `vcvars64.bat`, MSVC `19.50.35729.0`, and VS-bundled CMake `4.2.3` are usable through the Visual Studio developer environment. -- Plain `cmake` is still not available before the Visual Studio environment is initialized, so `build_msvc.cmd` uses `vswhere` and `vcvars64.bat` before invoking CMake. +- `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`. ### Host Harness @@ -493,6 +556,8 @@ 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. + ### Staging One Export Slice From the repository root: @@ -511,6 +576,13 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat - Added an import-slice tool for staging individual exported function folders without linking them yet. - Ran the importer on `classes/Remorse/EntityDispatchEntry`; it staged 24 files, replaced 62 calling-convention tokens, and reported `CONCAT22`, `unaff_CS`, and `unaff_SS` as cleanup signals. - Added the first hand-maintained `EntityDispatchEntry` source skeleton and wired it into the CMake target. +- Translated `11e0:02a8` group-ID validation, counter transitions, and no-op on an unchanged group into the compiled skeleton; other methods still have incomplete or placeholder behavior. +- Replaced `InitBase`'s blanket clear with live-confirmed `11e0:0000` function-table stamps, scalar assignments, and the active-group `SetGroupId` call; seeded-byte tests protect unknown bytes while the rest of the constructor remains unported. +- Added an owned host allocate/init/register call path, porting the first-free ID, 30-slot growth, process-ID/size/count bookkeeping, and `Process_11d0_19cd` syncing predicate. The harness now registers a process (ID 0); this does not run the original scheduler. +- Added default process-name storage, optional `ExtProc_NewlyCreated` flag/counter, immediate and deferred itemless termination, and slot cleanup/ID reuse. The harness also terminates ID 3, cleans its slot, and registers another process at ID 3; normal ID 0 lookup is a special case. +- Ported the conditional `InitBase` current-process extflag branch and the normal-process scan gates of `11d0:0255`. Tests cover group selection, one-pass sync, creation from a run callback, and cleanup during the scan. +- Ported the original `Process_Sleep`/`Unlink` timer writes and wake check, then executed `StandProcess::Run` under the scheduler in the diagnostic harness. It now uses an owned 0x42-byte Stand entry, compiled `1100:026e` NPC decision gates with host-supplied services, and a timer value produced by `SystemTimerProcess_Increment`. CTest checks off-screen sleep, the strict 60-tick deadline, visible behavior start, already-current activity, Stand's no-op completion slot, and timer carry. Host-owned Stand termination now refreshes the per-item bit; tests cover two processes for one item, deferred reclamation, and final immediate removal. Live Ghidra names `Item_MarkProcessPresent`/`Item_ClearProcessPresent`/`Item_RefreshProcessPresenceFlag` at `11d0:3e0b/3e44/3e7f` anchor the port. +- Configured the Windows GUI and console executables to emit CRT and unexpected-exception details to debugger output/stderr instead of modal crash prompts. CTest resets the CRT assert mode to window mode and verifies the installer removes it, then captures a deliberately terminating child process without a popup. - Split the scaffold into a `remorse_core` library, host executable, and first CTest target for `EntityDispatchEntry` setters. - Added the first host file-system shim and CTest target for game-data root discovery. - Extended the host file-system shim with case-insensitive data-path resolution, parent-traversal blocking, and binary file reads. @@ -523,9 +595,17 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat - Added a typed `TYPEFLAG.DAT` parser for shape family, flags, dimensions, and animation metadata. - Added a typed `SHAPES.FLX` parser and row-RLE decoder for renderable frame pixels. - Added the first visual map preview renderer and BMP output command. +- Added `remorse_game.exe`, a native Win32 window that asynchronously loads a retail map, displays the graph-sorted scene, and supports bounded WASD/arrow movement with a following camera. +- Added a persistent GDI back buffer and disabled background erase for the window's movement redraw path. +- Mapped keyboard movement to screen-cardinal directions through the inverse isometric transform and added a four-direction projection regression. +- Added a camera-centered render origin and a renderer test covering fixed-size viewport output. +- Documented the windowed app command and clearly scoped its current debug-marker/no-collision limitations. +- Replaced the host preview's scalar paint key with a footpad-aware dependency graph based on the local Ultima 8/Crusader sorter, including pairwise overlap, `below()` rules, and occlusion handling. +- Added a synthetic regression proving vertical separation can override the old `x+y` order, and retained the retail-data map-render smoke test. - Validated `remorse_map_preview` by rendering map 1 to `rebuild/remorse/out/preview/map1-preview.bmp` from original retail data. - Verified the scaffold with Visual Studio Community 2026: CMake configure succeeded, MSVC build succeeded, `ctest -C Debug` passed 2/2 tests, and `remorse_rebuild.exe` ran against `exports/src_remorse/export_manifest.json`. -- Added `build_msvc.cmd` so the working build/test/harness loop is repeatable from the repository root. +- Added `build_msvc.cmd` so the MSVC build/test/harness loop is repeatable from the repository root; it uses an isolated NMake build tree to avoid the local CMake Visual Studio-instance resolution failure. +- Revalidated the wrapper with MSVC `19.51.36246.0`: all C++ targets built, all 11 CTest tests passed, and the host harness loaded the export manifest and retail resource summaries. - Documented the current blockers between the Ghidra export and compiler-ready source. - Split the goal into historical reconstruction and Windows source-port tracks. - Chose Visual Studio Build Tools plus CMake as the first intended Windows host toolchain. @@ -535,27 +615,29 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat - Keep the host scaffold building as new source slices are added. - Lift the confirmed `EntityDispatchEntry` byte offsets into named packed fields once the surrounding `Process` layout is stable. - Convert the compatibility header from placeholders into enforced layout macros with static assertions. -- Pick the first real subsystem slice and move it into `rebuild/remorse/`. +- Extend the translated `SetGroupId` slice to its original initializer/callers and record the ported function addresses and parity checks. - Expand the host file-system shim into DOS file-handle replacements and writable save/config locations. - Model far pointers and segmented memory in a way that can support both trace comparison and Windows execution. - Normalize Ghidra exported types into valid C++ names without losing address provenance. - Replace raw global-byte exports with typed data definitions or resource loaders. - Define resource fixture tests for palette, shape, map, and usecode data. -- Replace the current preview painter's simple ordering with a fuller item-sorter dependency graph. -- Decide whether the first interactive window should use SDL, raw Win32/GDI, or another host layer. -- Decide the graphics/input/audio platform layer for the Windows runtime. +- Add explicit crop/navigation controls and tests for bounded map previews. +- Validate roof/hidden-object rendering policy against selected retail scenes. +- Keep the current Win32/GDI window as a diagnostic host while lifting the original player/process loop; choose other platform layers only as original DOS/hardware boundaries require them. +- Replace the windowed prototype movement/collision with ported player and AreaSearch behavior, using retail art and the existing renderer for presentation. +- Connect triggers and object interaction to the USECODE runtime after its value/context model is lifted. - Add CI-style smoke tests once the host toolchain and first resource loader compile reliably. ## Near-Term Next Actions -1. Open a Developer PowerShell with MSVC and CMake available, then run the CMake scaffold build. -2. Replace the current `EntityDispatchEntry` byte-array fields with named packed fields as evidence allows. -3. Add a small host-side test for the confirmed `+0x04`, `+0x06`, and `+0x08` setters once the MSVC/CMake toolchain is available. -4. Map the first old DOS file functions onto the new host file-system shim. -5. Add writable save/config path handling. -6. Add layout assertions for the first recovered packed structs. -7. Start a render/runtime decision note once the first resource smoke test passes. +1. Verify the live `Process` group-table allocation/initialization and the active-group writer `11d0:19b5`; compare `11e0:02a8` side effects with an execution trace (including counter ownership and error paths). +2. Complete `InitBase` (`11e0:0000`) and the kernel lifecycle by resolving the segment assertion, conditional kernel branch, item-linked teardown, process destructor dispatch and far-pointer storage; compare the host registry to real process snapshots. +3. Trace `Init_Everything` -> `FUN_11d0_0255` -> the player process and additional vtable `Run` targets; verify Stand's ported presence-bit lifecycle against original snapshots, then port animation-cache and nonempty-child teardown against real NPC state. +4. Port the real timer process and NPC service implementations, then scheduler keyboard, active-group advancement, remaining sleep-completion dispatch and table-maintenance tails; compare deterministic process-order/state traces before connecting the Windows window. +5. Replace DOS file and memory APIs encountered by the ported chain with narrow host adapters; validate far-pointer/layout conversions against live evidence. +6. Port original movement and AreaSearch/collision behavior before promoting the host actor movement from stand-in to gameplay code. +7. Feed original item/draw-list output into the existing renderer, then lift USECODE dispatch, save/load, audio, and frontend chains as required for playable mission progression. ## Current Bottom Line -The project is now at the start of the recompilation lane: there is a buildable host target scaffold, a compatibility surface, and a documented path for importing cleaned decompiler output. The major remaining work is systematic conversion, platform replacement, and behavior validation, not another bulk export. +The project has a buildable diagnostic host, retail resource loaders, a tested process lifecycle for host-owned base and zero-child-state Stand entries, a partial original scheduler scan, and an owned 0x42-byte Stand entry executing recovered NPC-decision and `Run` branches against a source-backed timer counter (`StandProcess Run sleep ticks: 60`, three other host callbacks). Creation and termination update the per-item presence bit, but this is **not** a game milestone: real NPC item ownership, nonempty-child teardown, visibility/activity service implementations, timer-process construction and interrupts, the complete tick, startup, player, renderer, and interaction chains remain unported; `remorse_game.exe` is not connected to this registry. The next measure of progress is a real item-linked Stand/NPC instance running on the original call chain with state trace parity. diff --git a/docs/scummvm-crusader-movement-tap-turn.md b/docs/scummvm-crusader-movement-tap-turn.md new file mode 100644 index 0000000..987ff87 --- /dev/null +++ b/docs/scummvm-crusader-movement-tap-turn.md @@ -0,0 +1,63 @@ +# ScummVM Crusader Movement Tap-Turn Fix + +This note records the ScummVM-side movement fix for Crusader: No Remorse tap-turning while running. + +## Problem + +In ScummVM's Crusader implementation, quickly tapping left or right while holding run/forward could fail to rotate the Silencer. The code already had a pending-turn path for short key taps, but it only applied that path while the last animation was `run`, `combatRunSmallWeapon`, or `walk`. + +That left out the start-run animations and the large-weapon combat-run animation. If a left/right tap arrived while the actor was still in `startRun`, `startRunSmallWeapon`, `startRunLargeWeapon`, or `combatRunLargeWeapon`, the pending turn could be cleared before it was applied. + +## Decompiled Source Evidence + +The exported Ghidra decompilation for retail `CRUSADER.EXE` shows the original controller treats more than plain run/walk as direction-adjustable movement. + +Evidence files: + +- `exports/src_remorse/functions/segments/seg_1130/Controller_PickNextAnimByKeyevent@1130_12d6.c` +- `exports/src_remorse/functions/segments/seg_1130/Controller_UpdateAvatarAngle@1130_10cf.c` +- `exports/src_remorse/functions/segments/seg_1130/Anim_1130_0f94@1130_0f94.c` + +Relevant behavior: + +- Left and right key events use the `0x11` / `0x12` temporary direction markers, then convert them into one direction step right or left according to the target animation's 8-dir or 16-dir mode. +- If the controlled NPC is busy, `Controller_PickNextAnimByKeyevent` still allows a keydown turn to update the active animation direction when `Anim_1130_0f94` says the current animation supports direction updates. +- `Anim_1130_0f94` includes `Anim_Walk`, `Anim_Run`, `Anim_StartRunning`, `Anim_CombatRun_SmallWpn`, `Anim_CombatRun_LargeWpn`, `Anim_StartRun_SmallWpn`, and `Anim_StartRun_LargeWpn` in that supported set. + +So the original behavior does not limit tap-turn handling to only the settled run/walk loops. It also accepts direction changes during run startup and combat-run variants. + +## ScummVM Change + +Updated ScummVM file: + +- `engines/ultima/ultima8/world/actors/cru_avatar_mover_process.cpp` + +The `_isAnimRunningWalking` helper now returns true for: + +- `Animation::run` +- `Animation::startRun` +- `Animation::combatRunSmallWeapon` +- `Animation::combatRunLargeWeapon` +- `Animation::startRunSmallWeapon` +- `Animation::startRunLargeWeapon` +- `Animation::walk` + +This keeps the existing ScummVM pending-turn design, but widens the eligible animation window to match the original controller's supported movement animations. A quick left/right tap while run-forward is active can now be consumed during run startup or either combat-run variant instead of being discarded. + +## Validation + +Static validation performed: + +- Confirmed the changed symbols already exist in ScummVM's Crusader animation enum. +- Confirmed the ScummVM change is limited to the Crusader mover helper that gates pending turn application. + +Runtime validation still needed: + +- Build ScummVM with the Ultima engine enabled. +- Start Crusader: No Remorse. +- Hold run plus forward, tap left/right during run startup and while fully running, and confirm the Silencer rotates one direction step without releasing run/forward. +- Repeat with weapon-ready combat run when possible, including a large weapon if available. + +## Notes + +The live Ghidra MCP bridge was not reachable during this pass, so the evidence above comes from the checked-out exported Ghidra decompilation under `exports/src_remorse/` rather than a fresh live decompile. \ No newline at end of file diff --git a/rebuild/remorse/CMakeLists.txt b/rebuild/remorse/CMakeLists.txt index 6ab261d..454d3a8 100644 --- a/rebuild/remorse/CMakeLists.txt +++ b/rebuild/remorse/CMakeLists.txt @@ -3,13 +3,16 @@ cmake_minimum_required(VERSION 3.20) project(remorse_rebuild LANGUAGES CXX) add_library(remorse_core + src/animation_archive.cpp src/combat_tactics.cpp + src/collision.cpp src/entity_dispatch_entry.cpp src/file_system.cpp src/flex_archive.cpp src/fixed_map.cpp src/glob_archive.cpp src/map_renderer.cpp + src/map_sorter.cpp src/palette.cpp src/runtime.cpp src/shape_archive.cpp @@ -31,6 +34,13 @@ add_executable(remorse_map_preview target_link_libraries(remorse_map_preview PRIVATE remorse_core) +if(WIN32) + add_executable(remorse_game WIN32 + src/windowed_game_main.cpp + ) + target_link_libraries(remorse_game PRIVATE remorse_core user32 gdi32) +endif() + enable_testing() add_executable(entity_dispatch_entry_tests @@ -105,6 +115,38 @@ target_link_libraries(map_renderer_tests PRIVATE remorse_core) add_test(NAME map_renderer_tests COMMAND map_renderer_tests) +add_executable(map_sorter_tests + tests/map_sorter_tests.cpp +) + +target_link_libraries(map_sorter_tests PRIVATE remorse_core) + +add_test(NAME map_sorter_tests COMMAND map_sorter_tests) + +add_executable(isometric_controls_tests + tests/isometric_controls_tests.cpp +) + +target_link_libraries(isometric_controls_tests PRIVATE remorse_core) + +add_test(NAME isometric_controls_tests COMMAND isometric_controls_tests) + +add_executable(animation_archive_tests + tests/animation_archive_tests.cpp +) + +target_link_libraries(animation_archive_tests PRIVATE remorse_core) + +add_test(NAME animation_archive_tests COMMAND animation_archive_tests) + +add_executable(collision_tests + tests/collision_tests.cpp +) + +target_link_libraries(collision_tests PRIVATE remorse_core) + +add_test(NAME collision_tests COMMAND collision_tests) + add_executable(combat_tactics_tests tests/combat_tactics_tests.cpp ) @@ -117,7 +159,14 @@ if(MSVC) target_compile_options(remorse_core PRIVATE /W4 /permissive-) target_compile_options(combat_tactics_tests PRIVATE /W4 /permissive-) target_compile_options(map_renderer_tests PRIVATE /W4 /permissive-) + target_compile_options(map_sorter_tests PRIVATE /W4 /permissive-) + target_compile_options(isometric_controls_tests PRIVATE /W4 /permissive-) + target_compile_options(animation_archive_tests PRIVATE /W4 /permissive-) + target_compile_options(collision_tests PRIVATE /W4 /permissive-) target_compile_options(remorse_map_preview PRIVATE /W4 /permissive-) + if(WIN32) + target_compile_options(remorse_game PRIVATE /W4 /permissive-) + endif() target_compile_options(remorse_rebuild PRIVATE /W4 /permissive-) target_compile_options(entity_dispatch_entry_tests PRIVATE /W4 /permissive-) target_compile_options(file_system_tests PRIVATE /W4 /permissive-) @@ -131,7 +180,14 @@ else() target_compile_options(remorse_core PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(combat_tactics_tests PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(map_renderer_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(map_sorter_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(isometric_controls_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(animation_archive_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(collision_tests PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(remorse_map_preview PRIVATE -Wall -Wextra -Wpedantic) + if(WIN32) + target_compile_options(remorse_game PRIVATE -Wall -Wextra -Wpedantic) + endif() target_compile_options(remorse_rebuild PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(entity_dispatch_entry_tests PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(file_system_tests PRIVATE -Wall -Wextra -Wpedantic) diff --git a/rebuild/remorse/build_msvc.cmd b/rebuild/remorse/build_msvc.cmd index 3b75561..af799b1 100644 --- a/rebuild/remorse/build_msvc.cmd +++ b/rebuild/remorse/build_msvc.cmd @@ -30,11 +30,12 @@ call "%VCVARS%" || exit /b 2 cd /d "%REPO_ROOT%" || exit /b 2 -cmake -S rebuild/remorse -B rebuild/remorse/out/build || exit /b 1 -cmake --build rebuild/remorse/out/build --config "%CONFIG%" || exit /b 1 -ctest --test-dir rebuild/remorse/out/build -C "%CONFIG%" --output-on-failure || exit /b 1 +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 "EXE=rebuild\remorse\out\build\%CONFIG%\remorse_rebuild.exe" +set "EXE=%BUILD_DIR%\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/animation_archive.h b/rebuild/remorse/include/remorse/animation_archive.h new file mode 100644 index 0000000..3af202f --- /dev/null +++ b/rebuild/remorse/include/remorse/animation_archive.h @@ -0,0 +1,47 @@ +#pragma once + +#include +#include +#include +#include + +#include "remorse\compat.h" + +namespace remorse { + +struct AnimationFrameMetadata { + std::array bytes{}; +}; + +struct AnimationClip { + std::array header{}; + u8 frameCount = 0; + u8 directionCount = 8; + std::vector frames; +}; + +struct AnimationArchive { + std::vector bytes; +}; + +struct AnimationDisplacement { + s32 x = 0; + s32 y = 0; + s32 z = 0; + bool onGround = false; +}; + +std::optional loadAnimationArchive(const std::filesystem::path& path); +std::optional loadAnimationClip(const AnimationArchive& archive, u32 shapeIndex, u8 animationIndex); +std::optional getAnimationFrame( + const AnimationClip& clip, + u8 direction, + u8 frameIndex); +u16 getAnimationShapeFrame(const AnimationFrameMetadata& metadata) noexcept; +bool isAnimationFrameFlipped(const AnimationFrameMetadata& metadata) noexcept; +std::optional decodeAnimationDisplacement( + const AnimationFrameMetadata& metadata, + u8 direction, + bool rotateDirection); + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/include/remorse/collision.h b/rebuild/remorse/include/remorse/collision.h new file mode 100644 index 0000000..a8abd2b --- /dev/null +++ b/rebuild/remorse/include/remorse/collision.h @@ -0,0 +1,30 @@ +#pragma once + +#include + +#include "remorse\fixed_map.h" +#include "remorse\glob_archive.h" +#include "remorse\map_renderer.h" +#include "remorse\type_flags.h" + +namespace remorse { + +struct CollisionBody { + WorldPoint location{}; + s32 extentX = 0; + s32 extentY = 0; + s32 extentZ = 0; +}; + +CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped = false); +bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right); +bool canMoveCollisionBody( + const CollisionBody& body, + WorldPoint destination, + const std::vector& obstacles); +std::vector collectMapCollisionBodies( + const FixedMap& map, + const std::vector& shapeTypes, + const std::vector& globObjects); + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/include/remorse/detail/map_sorter.h b/rebuild/remorse/include/remorse/detail/map_sorter.h new file mode 100644 index 0000000..de81dc6 --- /dev/null +++ b/rebuild/remorse/include/remorse/detail/map_sorter.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include + +#include "remorse/compat.h" + +namespace remorse { +namespace detail { + +struct RenderSortItem { + s32 left = 0; + s32 top = 0; + s32 right = 0; + s32 bottom = 0; + s32 x = 0; + s32 xLeft = 0; + s32 y = 0; + s32 yFar = 0; + s32 z = 0; + s32 zTop = 0; + s32 sxLeft = 0; + s32 sxRight = 0; + s32 sxTop = 0; + s32 syTop = 0; + s32 sxBottom = 0; + s32 syBottom = 0; + u16 shape = 0; + u8 frame = 0; + bool bigFlatSquare = false; + bool flat = false; + bool occludes = false; + bool solid = false; + bool draw = false; + bool roof = false; + bool translucent = false; + bool animated = false; + bool land = false; + bool sprite = false; + bool inventoryItem = false; +}; + +std::vector resolveRenderOrder(const std::vector& items); + +} // namespace detail +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index b838ab3..3be351b 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -2,6 +2,10 @@ #include "remorse/compat.h" +#include +#include +#include + namespace remorse { CR_PACK_PUSH_1 @@ -9,23 +13,139 @@ struct EntityDispatchEntryBase { u8 bytes[0x32]; } CR_PACKED; +struct StandProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x10]; +} CR_PACKED; + +struct SystemTimerProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x18]; +} CR_PACKED; + +struct KeyboardProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x04]; +} CR_PACKED; + +struct KeyDaemonProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x0e]; +} CR_PACKED; + +struct KeyEvent { + u8 character; + u8 scanCode; + u16 modifiers; + u16 field4; + u16 field6; + u8 field8; + u8 field9; + u16 fieldA; +} CR_PACKED; + struct EntityDispatchEntryRuntimeState { u8 bytes[0x18]; } CR_PACKED; CR_PACK_POP static_assert(sizeof(EntityDispatchEntryBase) == 0x32, "EntityDispatchEntryBase size must match allocation evidence"); +static_assert(sizeof(StandProcessEntry) == 0x42, "StandProcessEntry size must match allocation evidence"); +static_assert(sizeof(SystemTimerProcessEntry) == 0x4a, "SystemTimerProcessEntry size must match allocation evidence"); +static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size must match allocation evidence"); +static_assert(sizeof(KeyDaemonProcessEntry) == 0x40, "KeyDaemonProcessEntry size must match allocation evidence"); +static_assert(sizeof(KeyEvent) == 0x0c, "KeyEvent size must match keyboard event copy"); + +struct NpcBehaviorServices { + bool (*isEntirelyOnScreen)(u16 npcNumber, void* context); + u16 (*getActivity)(u16 npcNumber, void* context); + bool (*isCurrentActivitySpecifiedBy)(u16 npcNumber, u16 activity, void* context); + bool (*canSeeControlledNPC)(u16 npcNumber, void* context); + void (*startNextBehavior)(u16 npcNumber, u16 activity, void* context); + void* context; +}; + +class ProcessKernel { +public: + EntityDispatchEntryBase* createProcess(u8 activeGroup, u16 (&groupCounts)[32]); + StandProcessEntry* createStandProcess(u8 activeGroup, u16 npcNumber, u16 (&groupCounts)[32]); + SystemTimerProcessEntry* createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]); + KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]); + KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]); + void deliverSystemTimerEvent(); + u32 systemTimerTick() const; + void setSyncContext(bool enabled, u16 currentProcessId); + void setMarkNewProcesses(bool enabled); + void setLastAllocationSize(u16 size); + u16 addProcess(EntityDispatchEntryBase& entry); + void clearProcessSlot(u16 id); + void terminateProcess(u16 id, u16 (&groupCounts)[32]); + void clearTerminatedProcesses(); + void scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, u32 timerTick = 0); + EntityDispatchEntryBase* processAt(u16 id) const; + u16 allocationSizeAt(u16 id) const; + const char* processNameAt(u16 id) const; + bool itemHasProcess(u16 itemNumber) const; + u16 processCount() const; + u16 terminatedProcessCount() const; + u16 newlyCreatedCount() const; + std::size_t capacity() const; + +private: + void releaseOwnedProcess(u16 id); + std::vector processes_; + std::vector allocationSizes_; + std::vector processNames_; + std::vector> ownedProcesses_; + std::vector> ownedStandProcesses_; + std::unique_ptr systemTimerProcess_; + std::unique_ptr keyboardProcess_; + std::unique_ptr keyDaemonProcess_; + u16 systemTimerProcessId_ = 0xffff; + std::vector itemProcessPresence_; + u16 lastAllocationSize_ = 0; + u16 processCount_ = 0; + u16 terminatedProcessCount_ = 0; + u16 newlyCreatedCount_ = 0; + u16 currentProcessId_ = 0; + bool syncEnabled_ = false; + bool markNewProcesses_ = false; +}; class EntityDispatchEntry { public: static constexpr u16 initBaseSegment = 0x11e0; static constexpr u16 initBaseOffset = 0x0000; - static EntityDispatchEntryBase* initBase(EntityDispatchEntryBase* entry); - static void setGroupId(EntityDispatchEntryBase& entry, u8 groupId); + static EntityDispatchEntryBase* initBase(EntityDispatchEntryBase* entry, u8 activeGroup, u16 (&groupCounts)[32]); + static void setGroupId(EntityDispatchEntryBase& entry, u8 groupId, u16 (&groupCounts)[32]); static void incrementGroupId(EntityDispatchEntryBase& entry); static void setSourceType(EntityDispatchEntryBase& entry, u16 sourceType); static void setEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType); + static void sleep(EntityDispatchEntryBase& entry, u32 timerTick, u32 duration); + static void unlinkSleep(EntityDispatchEntryBase& entry); +}; + +class StandProcess { +public: + static constexpr u16 runOffset = 0x0359; + static constexpr u16 vtableOffset = 0x1f0f; + + static void run(EntityDispatchEntryBase& entry, bool (*startBehavior)(const EntityDispatchEntryBase&, void*), + void* context, u32 timerTick); + static void run(StandProcessEntry& entry, const NpcBehaviorServices& services, u32 timerTick); +}; + +class SystemTimerProcess { +public: + static u32 tick(const SystemTimerProcessEntry& entry); + static void increment(SystemTimerProcessEntry& entry); +}; + +class KeyboardProcess { +public: + static bool handleKeyEvent(KeyboardProcessEntry& process, u16 selector, u16 filter, + KeyEvent& event, const KeyEvent& lastEvent); }; } // namespace remorse diff --git a/rebuild/remorse/include/remorse/isometric_controls.h b/rebuild/remorse/include/remorse/isometric_controls.h new file mode 100644 index 0000000..902c14d --- /dev/null +++ b/rebuild/remorse/include/remorse/isometric_controls.h @@ -0,0 +1,42 @@ +#pragma once + +#include "remorse/animation_archive.h" +#include "remorse/compat.h" + +namespace remorse { + +struct WorldPositionD { + double x = 0.0; + double y = 0.0; +}; + +inline bool controllerWalkRequested(u16 modifiers) +{ + const bool shiftDown = (modifiers & 0x03) != 0; + const bool capsLockOn = (modifiers & 0x40) != 0; + return shiftDown == capsLockOn; +} + +inline std::optional hostMovementStep( + const AnimationFrameMetadata& metadata, u8 direction, bool rotateDirection) +{ + auto step = decodeAnimationDisplacement(metadata, direction, rotateDirection); + if (step && (metadata.bytes[5] & 1) != 0) { + step->x = 0; + step->y = 0; + } + return step; +} + +inline WorldPositionD worldPositionAtScreenOffset( + s32 originX, + s32 originY, + double screenOffsetX, + double screenOffsetY) +{ + return WorldPositionD{ + originX + 2.0 * screenOffsetX + 4.0 * screenOffsetY, + originY - 2.0 * screenOffsetX + 4.0 * screenOffsetY}; +} + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/include/remorse/map_renderer.h b/rebuild/remorse/include/remorse/map_renderer.h index c5dcaaf..90510b3 100644 --- a/rebuild/remorse/include/remorse/map_renderer.h +++ b/rebuild/remorse/include/remorse/map_renderer.h @@ -17,6 +17,17 @@ struct WorldRect { s32 maxY = 0; }; +struct WorldPoint { + s32 x = 0; + s32 y = 0; + s32 z = 0; +}; + +struct ScreenPoint { + s32 x = 0; + s32 y = 0; +}; + struct MapRenderOptions { u32 mapIndex = 1; u32 maxWidth = 1600; @@ -24,6 +35,7 @@ struct MapRenderOptions { bool expandGlobs = true; bool includeRoofs = false; bool includeHiddenMarkers = false; + std::optional viewCenter; std::optional worldRect; }; @@ -42,6 +54,7 @@ struct RenderedMapImage { }; std::optional renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options); +ScreenPoint projectToScreen(const WorldPoint& point); bool writeBmp24(const std::filesystem::path& path, const RenderedMapImage& image); } // namespace remorse diff --git a/rebuild/remorse/include/remorse/runtime.h b/rebuild/remorse/include/remorse/runtime.h index 89172aa..9d2e650 100644 --- a/rebuild/remorse/include/remorse/runtime.h +++ b/rebuild/remorse/include/remorse/runtime.h @@ -20,5 +20,6 @@ struct ExportManifestSummary { std::optional loadExportManifestSummary(const std::filesystem::path& manifestPath); std::filesystem::path defaultManifestPath(const std::filesystem::path& currentPath); void printStartupReport(const ExportManifestSummary& manifest); +void installCrashDiagnostics(); } // namespace remorse diff --git a/rebuild/remorse/src/animation_archive.cpp b/rebuild/remorse/src/animation_archive.cpp new file mode 100644 index 0000000..f898135 --- /dev/null +++ b/rebuild/remorse/src/animation_archive.cpp @@ -0,0 +1,135 @@ +#include "remorse/animation_archive.h" + +#include "remorse/file_system.h" + +#include + +namespace remorse { +namespace { + +std::optional readU32Le(const std::vector& bytes, std::size_t offset) +{ + if (offset > bytes.size() || bytes.size() - offset < 4) { + return std::nullopt; + } + return static_cast(bytes[offset]) | + (static_cast(bytes[offset + 1]) << 8) | + (static_cast(bytes[offset + 2]) << 16) | + (static_cast(bytes[offset + 3]) << 24); +} + +} // namespace + +std::optional loadAnimationArchive(const std::filesystem::path& path) +{ + const auto bytes = readBinaryFile(path); + if (!bytes) { + return std::nullopt; + } + return AnimationArchive{*bytes}; +} + +std::optional loadAnimationClip( + const AnimationArchive& archive, + u32 shapeIndex, + u8 animationIndex) +{ + if (shapeIndex > std::numeric_limits::max() / 4) { + return std::nullopt; + } + const auto shapeTableOffset = readU32Le(archive.bytes, static_cast(shapeIndex) * 4); + if (!shapeTableOffset || *shapeTableOffset == 0 || + *shapeTableOffset > archive.bytes.size() || archive.bytes.size() - *shapeTableOffset < 0x400) { + return std::nullopt; + } + + const std::size_t animationOffsetPosition = static_cast(*shapeTableOffset) + + static_cast(animationIndex) * 4; + const auto animationOffset = readU32Le(archive.bytes, animationOffsetPosition); + if (!animationOffset || *animationOffset == 0 || + *animationOffset > archive.bytes.size() || archive.bytes.size() - *animationOffset < 4) { + return std::nullopt; + } + + AnimationClip clip; + for (std::size_t index = 0; index < clip.header.size(); ++index) { + clip.header[index] = archive.bytes[*animationOffset + index]; + } + clip.frameCount = clip.header[0]; + if (clip.frameCount == 0) { + return std::nullopt; + } + clip.directionCount = (clip.header[3] & 0x40) != 0 ? 16 : 8; + const std::size_t metadataSize = static_cast(clip.frameCount) * clip.directionCount * 8; + const std::size_t metadataOffset = static_cast(*animationOffset) + clip.header.size(); + if (metadataOffset > archive.bytes.size() || metadataSize > archive.bytes.size() - metadataOffset) { + return std::nullopt; + } + + clip.frames.resize(static_cast(clip.frameCount) * clip.directionCount); + for (std::size_t index = 0; index < clip.frames.size(); ++index) { + const std::size_t sourceOffset = metadataOffset + index * 8; + for (std::size_t byte = 0; byte < clip.frames[index].bytes.size(); ++byte) { + clip.frames[index].bytes[byte] = archive.bytes[sourceOffset + byte]; + } + } + return clip; +} + +std::optional getAnimationFrame( + const AnimationClip& clip, + u8 direction, + u8 frameIndex) +{ + if (direction > 15 || frameIndex >= clip.frameCount || + (clip.directionCount != 8 && clip.directionCount != 16)) { + return std::nullopt; + } + const std::size_t effectiveDirection = clip.directionCount == 8 ? direction / 2 : direction; + const std::size_t index = effectiveDirection * clip.frameCount + frameIndex; + if (index >= clip.frames.size()) { + return std::nullopt; + } + return clip.frames[index]; +} + +u16 getAnimationShapeFrame(const AnimationFrameMetadata& metadata) noexcept +{ + return static_cast(metadata.bytes[0]) | + (static_cast(metadata.bytes[1] & 0x0f) << 8); +} + +bool isAnimationFrameFlipped(const AnimationFrameMetadata& metadata) noexcept +{ + return (metadata.bytes[1] & 0x80) != 0; +} + +std::optional decodeAnimationDisplacement( + const AnimationFrameMetadata& metadata, + u8 direction, + bool rotateDirection) +{ + if (direction > 15) { + return std::nullopt; + } + + static constexpr s8 directionX[16] = { + 0, 1, 1, 2, 1, 2, 1, 1, 0, -1, -1, -2, -1, -2, -1, -1}; + static constexpr s8 directionY[16] = { + -1, -2, -1, -1, 0, 1, 1, 2, 1, 2, 1, 1, 0, -1, -1, -2}; + + const u8 effectiveDirection = static_cast((direction + (rotateDirection ? 4 : 0)) & 0x0f); + const u16 packedStride = static_cast(metadata.bytes[4]) | + (static_cast(metadata.bytes[5] & 1) << 8); + const s32 signedStride = (packedStride & 0x100) != 0 + ? static_cast(packedStride) - 0x200 + : static_cast(packedStride); + + return AnimationDisplacement{ + static_cast(directionX[effectiveDirection]) * signedStride * 2, + static_cast(directionY[effectiveDirection]) * signedStride * 2, + static_cast(metadata.bytes[2]), + (metadata.bytes[5] & 0x02) != 0}; +} + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/collision.cpp b/rebuild/remorse/src/collision.cpp new file mode 100644 index 0000000..b4cc809 --- /dev/null +++ b/rebuild/remorse/src/collision.cpp @@ -0,0 +1,156 @@ +#include "remorse/collision.h" + +#include +#include + +namespace remorse { +namespace { + +constexpr u32 solidFlag = 0x0002; +constexpr u16 flippedFlag = 0x0020; +constexpr s32 shapeDimensionScale = 32; +constexpr s32 shapeHeightScale = 8; +constexpr s32 sweepStep = 16; +constexpr s32 globCoordMask = ~0x3ff; +constexpr s32 globCoordShift = 2; +constexpr s32 globCoordOffset = 2; + +bool intervalsOverlap(std::int64_t leftMin, std::int64_t leftMax, + std::int64_t rightMin, std::int64_t rightMax) +{ + return leftMin < rightMax && rightMin < leftMax; +} + +std::int64_t overlapVolumeAt(const CollisionBody& body, WorldPoint location, const CollisionBody& obstacle) +{ + if (body.extentX <= 0 || body.extentY <= 0 || body.extentZ <= 0 || + obstacle.extentX <= 0 || obstacle.extentY <= 0 || obstacle.extentZ <= 0) { + return -1; + } + + const std::int64_t overlapX = std::min(location.x, + obstacle.location.x) - std::max( + static_cast(location.x) - body.extentX, + static_cast(obstacle.location.x) - obstacle.extentX); + const std::int64_t overlapY = std::min(location.y, + obstacle.location.y) - std::max( + static_cast(location.y) - body.extentY, + static_cast(obstacle.location.y) - obstacle.extentY); + const std::int64_t overlapZ = std::min( + static_cast(location.z) + body.extentZ, + static_cast(obstacle.location.z) + obstacle.extentZ) - + std::max(location.z, obstacle.location.z); + if (overlapX <= 0 || overlapY <= 0 || overlapZ <= 0) { + return -1; + } + return overlapX * overlapY * overlapZ; +} + +bool overlapsAt(const CollisionBody& body, WorldPoint location, const CollisionBody& obstacle) +{ + return overlapVolumeAt(body, location, obstacle) >= 0; +} + +const GlobObject* findGlob(const std::vector& globObjects, u32 index) +{ + const auto found = std::find_if(globObjects.begin(), globObjects.end(), [index](const GlobObject& object) { + return object.index == index; + }); + return found == globObjects.end() ? nullptr : &*found; +} + +void appendSolidBody(std::vector& bodies, const std::vector& shapeTypes, + u32 shape, WorldPoint location, bool flipped) +{ + if (shape >= shapeTypes.size()) { + return; + } + const ShapeTypeInfo& info = shapeTypes[shape]; + if ((info.flags & solidFlag) == 0) { + return; + } + CollisionBody body = makeCollisionBody(location, info, flipped); + if (body.extentX > 0 && body.extentY > 0 && body.extentZ > 0) { + bodies.push_back(body); + } +} + +} // namespace + +CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped) +{ + const s32 extentX = static_cast(flipped ? shapeInfo.y : shapeInfo.x) * shapeDimensionScale; + const s32 extentY = static_cast(flipped ? shapeInfo.x : shapeInfo.y) * shapeDimensionScale; + return CollisionBody{ + location, + extentX, + extentY, + static_cast(shapeInfo.z) * shapeHeightScale}; +} + +bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right) +{ + return overlapsAt(left, left.location, right); +} + +bool canMoveCollisionBody( + const CollisionBody& body, + WorldPoint destination, + const std::vector& obstacles) +{ + const std::int64_t dx = static_cast(destination.x) - body.location.x; + const std::int64_t dy = static_cast(destination.y) - body.location.y; + const std::int64_t dz = static_cast(destination.z) - body.location.z; + const std::int64_t largestDelta = std::max({std::abs(dx), std::abs(dy), std::abs(dz)}); + const std::int64_t steps = std::max(1, (largestDelta + sweepStep - 1) / sweepStep); + + for (const CollisionBody& obstacle : obstacles) { + const std::int64_t startingOverlap = overlapVolumeAt(body, body.location, obstacle); + for (std::int64_t step = 1; step <= steps; ++step) { + const WorldPoint sample{ + static_cast(body.location.x + dx * step / steps), + static_cast(body.location.y + dy * step / steps), + static_cast(body.location.z + dz * step / steps)}; + const std::int64_t sampleOverlap = overlapVolumeAt(body, sample, obstacle); + if (sampleOverlap >= 0 && (startingOverlap < 0 || sampleOverlap > startingOverlap)) { + return false; + } + } + } + return true; +} + +std::vector collectMapCollisionBodies( + const FixedMap& map, + const std::vector& shapeTypes, + const std::vector& globObjects) +{ + std::vector bodies; + for (const FixedMapEntry& item : map.entries) { + if (item.shape >= shapeTypes.size()) { + continue; + } + const ShapeTypeInfo& info = shapeTypes[item.shape]; + if (info.family == 3) { + const GlobObject* glob = findGlob(globObjects, item.quality); + if (!glob) { + continue; + } + for (const GlobObjectEntry& child : glob->entries) { + const WorldPoint location{ + (static_cast(item.x) & globCoordMask) + + (static_cast(child.x) << globCoordShift) + globCoordOffset, + (static_cast(item.y) & globCoordMask) + + (static_cast(child.y) << globCoordShift) + globCoordOffset, + static_cast(item.z) + child.z}; + appendSolidBody(bodies, shapeTypes, child.shape, location, false); + } + continue; + } + appendSolidBody(bodies, shapeTypes, item.shape, + WorldPoint{item.x, item.y, item.z}, (item.flags & flippedFlag) != 0); + } + return bodies; +} + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index 15500fb..ed2dd79 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -1,5 +1,9 @@ #include "remorse/entity_dispatch_entry.h" +#include +#include +#include + namespace remorse { namespace { @@ -12,23 +16,437 @@ void writeLe16(EntityDispatchEntryBase& entry, u16 offset, u16 value) entry.bytes[offset] = static_cast(value & 0xff); entry.bytes[offset + 1] = static_cast(value >> 8); } + +u16 readLe16(const EntityDispatchEntryBase& entry, u16 offset) +{ + return static_cast(entry.bytes[offset] | (static_cast(entry.bytes[offset + 1]) << 8)); } -EntityDispatchEntryBase* EntityDispatchEntry::initBase(EntityDispatchEntryBase* entry) +void clearBytes(EntityDispatchEntryBase& entry, u16 begin, u16 end) +{ + for (u16 offset = begin; offset < end; ++offset) { + entry.bytes[offset] = 0; + } +} +} + +EntityDispatchEntryBase* ProcessKernel::createProcess(u8 activeGroup, u16 (&groupCounts)[32]) +{ + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + if (std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + processes_.reserve(processes_.size() + 30); + allocationSizes_.reserve(allocationSizes_.size() + 30); + processNames_.reserve(processNames_.size() + 30); + } + ownedProcesses_.reserve(ownedProcesses_.size() + 1); + auto entry = std::make_unique(); + EntityDispatchEntry::initBase(entry.get(), activeGroup, groupCounts); + setLastAllocationSize(sizeof(EntityDispatchEntryBase)); + const u16 id = addProcess(*entry); + if (syncEnabled_) { + EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_); + if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) { + current->bytes[0x18] |= 0x04; + } + if (id > currentProcessId_) { + entry->bytes[0x16] |= 0x40; + } + } + EntityDispatchEntryBase* result = entry.get(); + ownedProcesses_.push_back(std::move(entry)); + return result; +} + +StandProcessEntry* ProcessKernel::createStandProcess(u8 activeGroup, u16 npcNumber, u16 (&groupCounts)[32]) +{ + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + if (std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + processes_.reserve(processes_.size() + 30); + allocationSizes_.reserve(allocationSizes_.size() + 30); + processNames_.reserve(processNames_.size() + 30); + } + ownedStandProcesses_.reserve(ownedStandProcesses_.size() + 1); + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x16, static_cast(readLe16(process->base, 0x16) | 0x300)); + writeLe16(process->base, 0x04, npcNumber); + writeLe16(process->base, 0x06, 0x258); + writeLe16(process->base, 0x00, StandProcess::vtableOffset); + process->extra[0x00] |= 0x01; + process->extra[0x01] |= 0x01; + process->extra[0x0e] = static_cast(npcNumber); + process->extra[0x0f] = static_cast(npcNumber >> 8); + setLastAllocationSize(sizeof(StandProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "Stand"; + if (syncEnabled_) { + EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_); + if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) { + current->bytes[0x18] |= 0x04; + } + if (id > currentProcessId_) { + process->base.bytes[0x16] |= 0x40; + } + } + StandProcessEntry* result = process.get(); + ownedStandProcesses_.push_back(std::move(process)); + const std::size_t itemByte = npcNumber >> 3; + if (itemProcessPresence_.size() <= itemByte) { + itemProcessPresence_.resize(itemByte + 1, 0); + } + itemProcessPresence_[itemByte] |= static_cast(1u << (npcNumber & 7)); + return result; +} + +SystemTimerProcessEntry* ProcessKernel::createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]) +{ + if (systemTimerProcess_ != nullptr) { + throw std::logic_error("system timer process already exists"); + } + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x16, static_cast(readLe16(process->base, 0x16) | 0x300)); + process->extra[0] = 0x02; + process->extra[4] = 0x3c; + setLastAllocationSize(sizeof(SystemTimerProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "SystemTimer"; + writeLe16(process->base, 0x16, static_cast(readLe16(process->base, 0x16) | 0x2403)); + systemTimerProcessId_ = id; + systemTimerProcess_ = std::move(process); + return systemTimerProcess_.get(); +} + +KeyboardProcessEntry* ProcessKernel::createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]) +{ + if (keyboardProcess_ != nullptr) { + throw std::logic_error("keyboard process already exists"); + } + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x16, static_cast(readLe16(process->base, 0x16) | 0x103)); + setLastAllocationSize(sizeof(KeyboardProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "KeyboardProcess"; + writeLe16(process->base, 0x18, static_cast(readLe16(process->base, 0x18) | 0x180)); + keyboardProcess_ = std::move(process); + return keyboardProcess_.get(); +} + +KeyDaemonProcessEntry* ProcessKernel::createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]) +{ + if (keyDaemonProcess_ != nullptr) { + throw std::logic_error("key daemon process already exists"); + } + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x16, static_cast(readLe16(process->base, 0x16) | 0x300)); + process->extra[0] = 0x02; + process->extra[4] = 0x2d; + setLastAllocationSize(sizeof(KeyDaemonProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "KeyDaemon"; + writeLe16(process->base, 0x16, static_cast(readLe16(process->base, 0x16) | 0x2403)); + keyDaemonProcess_ = std::move(process); + return keyDaemonProcess_.get(); +} + +void ProcessKernel::deliverSystemTimerEvent() +{ + if (systemTimerProcess_ == nullptr) { + throw std::logic_error("system timer process is not registered"); + } + if (processAt(systemTimerProcessId_) != &systemTimerProcess_->base || + (readLe16(systemTimerProcess_->base, 0x16) & 0x400) == 0) { + throw std::logic_error("system timer event registration is invalid"); + } + SystemTimerProcess::increment(*systemTimerProcess_); +} + +u32 ProcessKernel::systemTimerTick() const +{ + if (systemTimerProcess_ == nullptr) { + throw std::logic_error("system timer process is not registered"); + } + return SystemTimerProcess::tick(*systemTimerProcess_); +} + +void ProcessKernel::setSyncContext(bool enabled, u16 currentProcessId) +{ + syncEnabled_ = enabled; + currentProcessId_ = currentProcessId; +} + +void ProcessKernel::setMarkNewProcesses(bool enabled) +{ + markNewProcesses_ = enabled; +} + +void ProcessKernel::setLastAllocationSize(u16 size) +{ + lastAllocationSize_ = size; +} + +u16 ProcessKernel::addProcess(EntityDispatchEntryBase& entry) +{ + auto freeSlot = std::find(processes_.begin(), processes_.end(), nullptr); + if (freeSlot == processes_.end()) { + if (processes_.size() + 30 > 1023) { + throw std::overflow_error("process table exhausted"); + } + const std::size_t oldCapacity = processes_.size(); + processes_.resize(oldCapacity + 30, nullptr); + allocationSizes_.resize(oldCapacity + 30, 0); + processNames_.resize(oldCapacity + 30, nullptr); + freeSlot = processes_.begin() + oldCapacity; + } + const u16 id = static_cast(freeSlot - processes_.begin()); + *freeSlot = &entry; + entry.bytes[0x02] = static_cast(id & 0xff); + entry.bytes[0x03] = static_cast(id >> 8); + allocationSizes_[id] = lastAllocationSize_; + lastAllocationSize_ = 0; + ++processCount_; + if (markNewProcesses_) { + ++newlyCreatedCount_; + entry.bytes[0x19] |= 0x02; + } + processNames_[id] = "Default"; + return id; +} + +void ProcessKernel::clearProcessSlot(u16 id) +{ + if (id >= processes_.size()) { + throw std::out_of_range("process ID outside table"); + } + processes_[id] = nullptr; + allocationSizes_[id] = 0; + processNames_[id] = nullptr; +} + +void ProcessKernel::releaseOwnedProcess(u16 id) +{ + EntityDispatchEntryBase* entry = processes_[id]; + clearProcessSlot(id); + const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (stand != ownedStandProcesses_.end()) { + ownedStandProcesses_.erase(stand); + return; + } + const auto owned = std::find_if(ownedProcesses_.begin(), ownedProcesses_.end(), + [entry](const auto& process) { return process.get() == entry; }); + ownedProcesses_.erase(owned); +} + +void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) +{ + EntityDispatchEntryBase* entry = processAt(id); + if (id == 0 || entry == nullptr) { + throw std::out_of_range("process ID is not addressable"); + } + const u16 itemNumber = readLe16(*entry, 0x04); + if (systemTimerProcess_ != nullptr && entry == &systemTimerProcess_->base) { + throw std::logic_error("system timer teardown is not ported"); + } + if (keyboardProcess_ != nullptr && entry == &keyboardProcess_->base) { + throw std::logic_error("keyboard process teardown is not ported"); + } + if (keyDaemonProcess_ != nullptr && entry == &keyDaemonProcess_->base) { + throw std::logic_error("key daemon process teardown is not ported"); + } + const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (itemNumber != 0 && (stand == ownedStandProcesses_.end() || id < 3 || + readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 || + readLe16(*entry, 0x2e) != 0 || readLe16(*entry, 0x30) != 0)) { + throw std::logic_error("item process child cleanup is not ported"); + } + if (stand == ownedStandProcesses_.end() && std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(), + [entry](const auto& process) { return process.get() == entry; })) { + throw std::logic_error("external process ownership is not ported"); + } + const bool immediate = (entry->bytes[0x18] & 0x04) != 0; + if (!immediate && (entry->bytes[0x16] & 0x08) != 0) { + throw std::logic_error("process is already terminated"); + } + --groupCounts[entry->bytes[0x08] & 0x1f]; + if (immediate) { + releaseOwnedProcess(id); + } else { + entry->bytes[0x16] |= 0x08; + ++terminatedProcessCount_; + } + --processCount_; + if (itemNumber != 0) { + const bool stillPresent = std::any_of(processes_.begin() + 3, processes_.end(), + [itemNumber](const EntityDispatchEntryBase* process) { + return process != nullptr && readLe16(*process, 0x04) == itemNumber && + (readLe16(*process, 0x16) & 0x08) == 0; + }); + if (!stillPresent) { + itemProcessPresence_[itemNumber >> 3] &= static_cast(~(1u << (itemNumber & 7))); + } + } +} + +void ProcessKernel::clearTerminatedProcesses() +{ + for (std::size_t id = 3; id < processes_.size() && terminatedProcessCount_ != 0; ++id) { + EntityDispatchEntryBase* entry = processes_[id]; + if (entry == nullptr || (entry->bytes[0x16] & 0x08) == 0) { + continue; + } + if (entry->bytes[0x1a] != 0 || entry->bytes[0x1b] != 0) { + throw std::logic_error("terminated process has linked state"); + } + releaseOwnedProcess(static_cast(id)); + --terminatedProcessCount_; + } +} + +void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, u32 timerTick) +{ + if (run == nullptr) { + throw std::invalid_argument("process run slot is required"); + } + const bool priorSyncEnabled = syncEnabled_; + const u16 priorProcessId = currentProcessId_; + syncEnabled_ = true; + try { + for (std::size_t id = 0; id < processes_.size(); ++id) { + EntityDispatchEntryBase* entry = processes_[id]; + if (entry != nullptr && (readLe16(*entry, 0x16) & 0x08) == 0) { + if ((readLe16(*entry, 0x18) & 0x1000) != 0) { + const u32 sleepStart = readLe16(*entry, 0x0a) | (static_cast(readLe16(*entry, 0x0c)) << 16); + const u32 sleepLength = readLe16(*entry, 0x0e) | (static_cast(readLe16(*entry, 0x10)) << 16); + if (sleepStart + sleepLength < timerTick) { + if ((readLe16(*entry, 0x16) & 0x100) != 0) { + const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (stand == ownedStandProcesses_.end() || + readLe16(*entry, 0x00) != StandProcess::vtableOffset) { + throw std::logic_error("sleep completion dispatch is not ported"); + } + } + 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; + } + } + } + clearTerminatedProcesses(); + } + } catch (...) { + syncEnabled_ = priorSyncEnabled; + currentProcessId_ = priorProcessId; + throw; + } + syncEnabled_ = priorSyncEnabled; + currentProcessId_ = priorProcessId; +} + +EntityDispatchEntryBase* ProcessKernel::processAt(u16 id) const +{ + return id < processes_.size() ? processes_[id] : nullptr; +} + +u16 ProcessKernel::allocationSizeAt(u16 id) const +{ + return id < allocationSizes_.size() ? allocationSizes_[id] : 0; +} + +const char* ProcessKernel::processNameAt(u16 id) const +{ + return id < processNames_.size() ? processNames_[id] : nullptr; +} + +bool ProcessKernel::itemHasProcess(u16 itemNumber) const +{ + const std::size_t itemByte = itemNumber >> 3; + return itemByte < itemProcessPresence_.size() && + (itemProcessPresence_[itemByte] & (1u << (itemNumber & 7))) != 0; +} + +u16 ProcessKernel::processCount() const +{ + return processCount_; +} + +u16 ProcessKernel::terminatedProcessCount() const +{ + return terminatedProcessCount_; +} + +u16 ProcessKernel::newlyCreatedCount() const +{ + return newlyCreatedCount_; +} + +std::size_t ProcessKernel::capacity() const +{ + return processes_.size(); +} + +EntityDispatchEntryBase* EntityDispatchEntry::initBase(EntityDispatchEntryBase* entry, u8 activeGroup, u16 (&groupCounts)[32]) { if (entry == nullptr) { return nullptr; } - for (u8& byte : entry->bytes) { - byte = 0; - } + writeLe16(*entry, 0x00, 0x3b06); + writeLe16(*entry, 0x1e, 0x2d10); + writeLe16(*entry, 0x28, 0x3afe); + clearBytes(*entry, 0x02, 0x06); + writeLe16(*entry, 0x06, 1); + entry->bytes[0x08] = 0; + clearBytes(*entry, 0x0a, 0x1e); + writeLe16(*entry, 0x18, 1); + clearBytes(*entry, 0x20, 0x28); + clearBytes(*entry, 0x2a, 0x32); + setGroupId(*entry, activeGroup, groupCounts); return entry; } -void EntityDispatchEntry::setGroupId(EntityDispatchEntryBase& entry, u8 groupId) +void EntityDispatchEntry::setGroupId(EntityDispatchEntryBase& entry, u8 groupId, u16 (&groupCounts)[32]) { - entry.bytes[groupIdOffset] = static_cast((entry.bytes[groupIdOffset] & 0xe0) | (groupId & 0x1f)); + if (groupId == 0 || groupId > 31) { + throw std::invalid_argument("process group ID must be in 1..31"); + } + const u8 oldGroupId = entry.bytes[groupIdOffset] & 0x1f; + if (oldGroupId == groupId) { + return; + } + if (oldGroupId != 0) { + --groupCounts[oldGroupId]; + } + entry.bytes[groupIdOffset] = groupId; + ++groupCounts[groupId]; } void EntityDispatchEntry::incrementGroupId(EntityDispatchEntryBase& entry) @@ -46,4 +464,77 @@ void EntityDispatchEntry::setEventTypeChecked(EntityDispatchEntryBase& entry, u1 writeLe16(entry, eventTypeOffset, eventType); } +void EntityDispatchEntry::sleep(EntityDispatchEntryBase& entry, u32 timerTick, u32 duration) +{ + writeLe16(entry, 0x18, static_cast(readLe16(entry, 0x18) | 0x1000)); + writeLe16(entry, 0x0a, static_cast(timerTick)); + writeLe16(entry, 0x0c, static_cast(timerTick >> 16)); + writeLe16(entry, 0x0e, static_cast(duration)); + writeLe16(entry, 0x10, static_cast(duration >> 16)); +} + +void EntityDispatchEntry::unlinkSleep(EntityDispatchEntryBase& entry) +{ + writeLe16(entry, 0x18, static_cast(readLe16(entry, 0x18) & ~0x1000)); + clearBytes(entry, 0x0a, 0x12); +} + +void StandProcess::run(EntityDispatchEntryBase& entry, + bool (*startBehavior)(const EntityDispatchEntryBase&, void*), void* context, u32 timerTick) +{ + if (startBehavior == nullptr) { + throw std::invalid_argument("NPC behavior boundary is required"); + } + if (!startBehavior(entry, context)) { + EntityDispatchEntry::sleep(entry, timerTick, 0x3c); + } +} + +void StandProcess::run(StandProcessEntry& entry, const NpcBehaviorServices& services, u32 timerTick) +{ + if (services.isEntirelyOnScreen == nullptr || services.getActivity == nullptr || + services.isCurrentActivitySpecifiedBy == nullptr || services.canSeeControlledNPC == nullptr || + services.startNextBehavior == nullptr) { + throw std::invalid_argument("NPC behavior services are required"); + } + const u16 npcNumber = static_cast(entry.extra[0x0e] | (static_cast(entry.extra[0x0f]) << 8)); + bool started = false; + if (services.isEntirelyOnScreen(npcNumber, services.context) && + services.getActivity(npcNumber, services.context) != 0 && + !services.isCurrentActivitySpecifiedBy(npcNumber, 0x71, services.context) && + services.canSeeControlledNPC(npcNumber, services.context)) { + services.startNextBehavior(npcNumber, 0x71, services.context); + started = true; + } + run(entry.base, [](const EntityDispatchEntryBase&, void* context) { + return *static_cast(context); + }, &started, timerTick); +} + +u32 SystemTimerProcess::tick(const SystemTimerProcessEntry& entry) +{ + return static_cast(entry.extra[0x0e] | (static_cast(entry.extra[0x0f]) << 8)) | + (static_cast(entry.extra[0x10] | (static_cast(entry.extra[0x11]) << 8)) << 16); +} + +void SystemTimerProcess::increment(SystemTimerProcessEntry& entry) +{ + const u32 nextTick = tick(entry) + 1; + entry.extra[0x0e] = static_cast(nextTick); + entry.extra[0x0f] = static_cast(nextTick >> 8); + entry.extra[0x10] = static_cast(nextTick >> 16); + entry.extra[0x11] = static_cast(nextTick >> 24); +} + +bool KeyboardProcess::handleKeyEvent(KeyboardProcessEntry& process, u16 selector, u16 filter, + KeyEvent& event, const KeyEvent& lastEvent) +{ + if (selector != 0x10 || filter != 0 || event.character == 0 || event.field8 == 0) { + return false; + } + std::memcpy(&event, &lastEvent, sizeof(event)); + process.extra[0] &= static_cast(~0x10); + return true; +} + } // namespace remorse diff --git a/rebuild/remorse/src/main.cpp b/rebuild/remorse/src/main.cpp index 64d862a..b3d1ae7 100644 --- a/rebuild/remorse/src/main.cpp +++ b/rebuild/remorse/src/main.cpp @@ -13,6 +13,7 @@ int main(int argc, char** argv) { + remorse::installCrashDiagnostics(); const std::filesystem::path manifestPath = argc > 1 ? std::filesystem::path(argv[1]) : remorse::defaultManifestPath(std::filesystem::current_path()); @@ -24,9 +25,48 @@ int main(int argc, char** argv) } remorse::printStartupReport(*manifest); - remorse::EntityDispatchEntryBase entry{}; - remorse::EntityDispatchEntry::initBase(&entry); - remorse::EntityDispatchEntry::setGroupId(entry, 1); + remorse::ProcessKernel kernel; + remorse::u16 groupCounts[32]{}; + const auto* entry = kernel.createProcess(1, groupCounts); + std::cout << "Registered process ID: " << (entry ? entry->bytes[0x02] : 0) << '\n'; + for (int index = 0; index < 3; ++index) { + kernel.createProcess(1, groupCounts); + } + kernel.createSystemTimerProcess(1, groupCounts); + kernel.createKeyboardProcess(1, groupCounts); + kernel.createKeyDaemonProcess(1, groupCounts); + kernel.terminateProcess(3, groupCounts); + kernel.clearTerminatedProcesses(); + auto* reused = kernel.createStandProcess(1, 1, groupCounts); + std::cout << "Reused Stand process ID: " << (reused ? reused->base.bytes[0x02] : 0) << '\n'; + remorse::NpcBehaviorServices npcServices{ + [](remorse::u16, void*) { return false; }, + [](remorse::u16, void*) -> remorse::u16 { return 0; }, + [](remorse::u16, remorse::u16, void*) { return false; }, + [](remorse::u16, void*) { return false; }, + [](remorse::u16, remorse::u16, void*) {}, + nullptr + }; + struct ScanContext { + remorse::StandProcessEntry* standing; + remorse::NpcBehaviorServices* npcServices; + remorse::u32 timerTick; + int hostCallbacks = 0; + } scanContext{reused, &npcServices, 0}; + for (int tick = 0; tick < 100; ++tick) { + kernel.deliverSystemTimerEvent(); + } + scanContext.timerTick = kernel.systemTimerTick(); + kernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& scan = *static_cast(context); + if (process.bytes[0] == 0x0f && process.bytes[1] == 0x1f) { + remorse::StandProcess::run(*scan.standing, *scan.npcServices, scan.timerTick); + } else { + ++scan.hostCallbacks; + } + }, &scanContext, scanContext.timerTick); + std::cout << "Scheduler scan host callbacks: " << scanContext.hostCallbacks << '\n'; + std::cout << "StandProcess Run sleep ticks: " << static_cast(reused->base.bytes[0x0e]) << '\n'; const auto gameDataRoot = remorse::findGameDataRoot(std::filesystem::current_path()); std::cout << "Game data root: " << (gameDataRoot ? gameDataRoot->path.string() : "not found") << '\n'; diff --git a/rebuild/remorse/src/map_preview_main.cpp b/rebuild/remorse/src/map_preview_main.cpp index 973b0f4..a226f30 100644 --- a/rebuild/remorse/src/map_preview_main.cpp +++ b/rebuild/remorse/src/map_preview_main.cpp @@ -1,5 +1,6 @@ #include "remorse/file_system.h" #include "remorse/map_renderer.h" +#include "remorse/runtime.h" #include #include @@ -7,6 +8,7 @@ int main(int argc, char** argv) { + remorse::installCrashDiagnostics(); const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); if (!root) { std::cerr << "Could not locate Crusader game data root.\n"; diff --git a/rebuild/remorse/src/map_renderer.cpp b/rebuild/remorse/src/map_renderer.cpp index a205dbc..8f2a84b 100644 --- a/rebuild/remorse/src/map_renderer.cpp +++ b/rebuild/remorse/src/map_renderer.cpp @@ -2,6 +2,7 @@ #include "remorse/fixed_map.h" #include "remorse/glob_archive.h" +#include "remorse/detail/map_sorter.h" #include "remorse/shape_archive.h" #include "remorse/type_flags.h" @@ -14,7 +15,12 @@ namespace { constexpr u16 flagInvisible = 0x0010; constexpr u16 flagFlipped = 0x0020; +constexpr u32 siSolid = 0x0002; +constexpr u32 siLand = 0x0008; +constexpr u32 siOccl = 0x0010; +constexpr u32 siDraw = 0x0100; constexpr u32 siRoof = 0x0400; +constexpr u32 siTranslucent = 0x0800; constexpr s32 globCoordMask = ~0x3ff; constexpr s32 globCoordShift = 2; constexpr s32 globCoordOffset = 2; @@ -139,12 +145,12 @@ std::vector collectSceneItems( s32 screenX(const SceneItem& item) { - return (item.x - item.y) / 4; + return projectToScreen(WorldPoint{item.x, item.y, item.z}).x; } s32 screenY(const SceneItem& item) { - return (item.x + item.y) / 8 - item.z; + return projectToScreen(WorldPoint{item.x, item.y, item.z}).y; } std::optional cachedDecode( @@ -166,10 +172,16 @@ std::optional cachedDecode( return decoded; } -std::vector prepareRenderNodes(const std::vector& items, const ShapeArchive& shapeArchive) +std::vector prepareRenderNodes( + const std::vector& items, + const ShapeArchive& shapeArchive, + const std::vector& typeFlags) { std::map, DecodedShapeFrame> cache; std::vector nodes; + std::vector sortItems; + nodes.reserve(items.size()); + sortItems.reserve(items.size()); for (const SceneItem& item : items) { const auto decoded = cachedDecode(shapeArchive, cache, item.shape, item.frame); if (!decoded) { @@ -188,24 +200,52 @@ std::vector prepareRenderNodes(const std::vector& items, node.top = bottomY - node.decoded.frame.yOffset; node.right = node.left + static_cast(node.decoded.frame.width); node.bottom = node.top + static_cast(node.decoded.frame.height); + + const ShapeTypeInfo& info = typeFlags[item.shape]; + const s32 xDimension = static_cast(flipped ? info.y : info.x) * 32; + const s32 yDimension = static_cast(flipped ? info.x : info.y) * 32; + const s32 zDimension = static_cast(info.z) * 8; + detail::RenderSortItem sortItem; + sortItem.left = node.left; + sortItem.top = node.top; + sortItem.right = node.right; + sortItem.bottom = node.bottom; + sortItem.x = item.x; + sortItem.xLeft = item.x - xDimension; + sortItem.y = item.y; + sortItem.yFar = item.y - yDimension; + sortItem.z = item.z; + sortItem.zTop = item.z + zDimension; + sortItem.sxLeft = sortItem.xLeft / 4 - item.y / 4; + sortItem.sxRight = item.x / 4 - sortItem.yFar / 4; + sortItem.sxTop = sortItem.xLeft / 4 - sortItem.yFar / 4; + sortItem.syTop = sortItem.xLeft / 8 + sortItem.yFar / 8 - sortItem.zTop; + sortItem.sxBottom = bottomX; + sortItem.syBottom = bottomY; + sortItem.shape = item.shape; + sortItem.frame = item.frame; + sortItem.bigFlatSquare = xDimension == yDimension && xDimension >= 128; + sortItem.flat = zDimension == 0; + sortItem.translucent = (info.flags & siTranslucent) != 0; + sortItem.animated = info.animationType != 0; + sortItem.occludes = (info.flags & siOccl) != 0 && !sortItem.translucent && + (item.flags & flagInvisible) == 0; + sortItem.solid = (info.flags & siSolid) != 0; + sortItem.draw = (info.flags & siDraw) != 0; + sortItem.roof = (info.flags & siRoof) != 0; + sortItem.land = (info.flags & siLand) != 0; + sortItem.inventoryItem = info.family == 13; nodes.push_back(node); + sortItems.push_back(sortItem); } - std::sort(nodes.begin(), nodes.end(), [](const RenderNode& left, const RenderNode& right) { - const s32 leftKey = left.item.x + left.item.y; - const s32 rightKey = right.item.x + right.item.y; - if (leftKey != rightKey) { - return leftKey < rightKey; - } - if (left.item.z != right.item.z) { - return left.item.z < right.item.z; - } - if (left.item.y != right.item.y) { - return left.item.y < right.item.y; - } - return left.item.x < right.item.x; - }); - return nodes; + const std::vector order = detail::resolveRenderOrder(sortItems); + std::vector orderedNodes; + orderedNodes.reserve(order.size()); + for (const std::size_t index : order) { + orderedNodes.push_back(std::move(nodes[index])); + } + return orderedNodes; } void paintNode(RenderedMapImage& image, const RenderNode& node, const Palette256& palette) @@ -248,6 +288,11 @@ void writeLe32(std::ofstream& output, u32 value) } // namespace +ScreenPoint projectToScreen(const WorldPoint& point) +{ + return ScreenPoint{(point.x - point.y) / 4, (point.x + point.y) / 8 - point.z}; +} + std::optional renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options) { const auto fixedPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "FIXED.DAT"); @@ -270,7 +315,7 @@ std::optional renderMapPreview(const GameDataRoot& root, const } const auto items = collectSceneItems(*fixedMap, *typeFlags, *globs, options); - auto nodes = prepareRenderNodes(items, *shapeArchive); + auto nodes = prepareRenderNodes(items, *shapeArchive, *typeFlags); if (nodes.empty()) { return std::nullopt; } @@ -290,12 +335,22 @@ std::optional renderMapPreview(const GameDataRoot& root, const image.rawItemCount = static_cast(fixedMap->entries.size()); image.renderItemCount = static_cast(items.size()); image.decodedItemCount = static_cast(nodes.size()); - image.sourceLeft = nodes[0].left; - image.sourceTop = nodes[0].top; image.fullWidth = maxRight - minLeft; image.fullHeight = maxBottom - minTop; - image.width = std::min(options.maxWidth, static_cast(std::max(1, image.fullWidth))); - image.height = std::min(options.maxHeight, static_cast(std::max(1, image.fullHeight))); + image.width = options.viewCenter + ? options.maxWidth + : std::min(options.maxWidth, static_cast(std::max(1, image.fullWidth))); + image.height = options.viewCenter + ? options.maxHeight + : std::min(options.maxHeight, static_cast(std::max(1, image.fullHeight))); + if (options.viewCenter) { + const ScreenPoint center = projectToScreen(*options.viewCenter); + image.sourceLeft = center.x - static_cast(image.width / 2); + image.sourceTop = center.y - static_cast(image.height / 2); + } else { + image.sourceLeft = nodes[0].left; + image.sourceTop = nodes[0].top; + } image.pixels.assign( static_cast(image.width) * image.height, RgbColor{static_cast(10), static_cast(12), static_cast(18)}); diff --git a/rebuild/remorse/src/map_sorter.cpp b/rebuild/remorse/src/map_sorter.cpp new file mode 100644 index 0000000..3912059 --- /dev/null +++ b/rebuild/remorse/src/map_sorter.cpp @@ -0,0 +1,316 @@ +#include "remorse/detail/map_sorter.h" + +#include + +namespace remorse { +namespace detail { +namespace { + +struct SortNode { + RenderSortItem item; + std::vector dependencies; + bool occluded = false; + s32 order = -1; +}; + +bool listLessThan(const RenderSortItem& left, const RenderSortItem& right) +{ + if (left.sprite != right.sprite) { + return left.sprite < right.sprite; + } + if (left.z != right.z) { + return left.z < right.z; + } + return left.flat > right.flat; +} + +bool rectIntersects(const RenderSortItem& left, const RenderSortItem& right) +{ + return left.left < right.right && left.right > right.left && + left.top < right.bottom && left.bottom > right.top; +} + +bool rectContains(const RenderSortItem& outer, const RenderSortItem& inner) +{ + return outer.left <= inner.left && outer.top <= inner.top && + outer.right >= inner.right && outer.bottom >= inner.bottom; +} + +bool overlaps(const RenderSortItem& left, const RenderSortItem& right) +{ + if (!rectIntersects(left, right)) { + return false; + } + + const s32 topDiffX = left.sxTop - right.sxBottom; + const s32 topDiffY = left.syTop - right.syBottom; + const s32 bottomDiffX = left.sxBottom - right.sxTop; + const s32 bottomDiffY = left.syBottom - right.syTop; + const bool rightClear = left.sxRight <= right.sxLeft; + const bool leftClear = left.sxLeft >= right.sxRight; + const bool topLeftClear = topDiffX + topDiffY * 2 >= 0; + const bool topRightClear = -topDiffX + topDiffY * 2 >= 0; + const bool bottomLeftClear = bottomDiffX - bottomDiffY * 2 >= 0; + const bool bottomRightClear = -bottomDiffX - bottomDiffY * 2 >= 0; + return !(rightClear || leftClear || topLeftClear || topRightClear || bottomLeftClear || bottomRightClear); +} + +bool occludes(const RenderSortItem& outer, const RenderSortItem& inner) +{ + if (!rectContains(outer, inner)) { + return false; + } + + const s32 topDiffX = outer.sxTop - inner.sxTop; + const s32 topDiffY = outer.syTop - inner.syTop; + const s32 bottomDiffX = outer.sxBottom - inner.sxBottom; + const s32 bottomDiffY = outer.syBottom - inner.syBottom; + const bool rightResult = outer.sxRight >= inner.sxRight; + const bool leftResult = outer.sxLeft <= inner.sxLeft; + const bool topLeftResult = topDiffX + topDiffY * 2 <= 0; + const bool topRightResult = -topDiffX + topDiffY * 2 <= 0; + const bool bottomLeftResult = bottomDiffX - bottomDiffY * 2 <= 0; + const bool bottomRightResult = -bottomDiffX - bottomDiffY * 2 <= 0; + return rightResult && leftResult && topLeftResult && topRightResult && + bottomLeftResult && bottomRightResult; +} + +bool below(const RenderSortItem& left, const RenderSortItem& right) +{ + if (left.sprite != right.sprite) { + return left.sprite < right.sprite; + } + + if (left.flat && right.flat) { + if (left.z != right.z) { + return left.z < right.z; + } + } else if (left.inventoryItem == right.inventoryItem) { + if (left.zTop <= right.z) { + return true; + } + if (left.z >= right.zTop) { + return false; + } + } + + const bool yFlatLeft = left.yFar == left.y; + const bool yFlatRight = right.yFar == right.y; + if (yFlatLeft && yFlatRight) { + if (left.y / 32 != right.y / 32) { + return left.y < right.y; + } + } else { + if (left.y <= right.yFar) { + return true; + } + if (left.yFar >= right.y) { + return false; + } + } + + const bool xFlatLeft = left.xLeft == left.x; + const bool xFlatRight = right.xLeft == right.x; + if (xFlatLeft && xFlatRight) { + if (left.x / 32 != right.x / 32) { + return left.x < right.x; + } + } else { + if (left.x <= right.xLeft) { + return true; + } + if (left.xLeft >= right.x) { + return false; + } + } + + if (left.zTop - 8 <= right.z && left.z < right.zTop - 8) { + return true; + } + if (left.z >= right.zTop - 8 && left.zTop - 8 > right.z) { + return false; + } + + if (yFlatLeft != yFlatRight) { + if (left.y / 32 <= right.yFar / 32) { + return true; + } + if (left.yFar / 32 >= right.y / 32) { + return false; + } + + const s32 yCenterLeft = (left.yFar / 32 + left.y / 32) / 2; + const s32 yCenterRight = (right.yFar / 32 + right.y / 32) / 2; + if (yCenterLeft != yCenterRight) { + return yCenterLeft < yCenterRight; + } + } + + if (xFlatLeft != xFlatRight) { + if (left.x / 32 <= right.xLeft / 32) { + return true; + } + if (left.xLeft / 32 >= right.x / 32) { + return false; + } + + const s32 xCenterLeft = (left.xLeft / 32 + left.x / 32) / 2; + const s32 xCenterRight = (right.xLeft / 32 + right.x / 32) / 2; + if (xCenterLeft != xCenterRight) { + return xCenterLeft < xCenterRight; + } + } + + if (left.flat || right.flat) { + if (left.z != right.z) { + return left.z < right.z; + } + if (left.inventoryItem != right.inventoryItem) { + return left.inventoryItem < right.inventoryItem; + } + if (left.flat != right.flat) { + return left.flat > right.flat; + } + if (left.translucent != right.translucent) { + return left.translucent < right.translucent; + } + if (left.animated != right.animated) { + return left.animated < right.animated; + } + if (left.draw != right.draw) { + return left.draw > right.draw; + } + if (left.solid != right.solid) { + return left.solid > right.solid; + } + if (left.occludes != right.occludes) { + return left.occludes > right.occludes; + } + if (left.bigFlatSquare != right.bigFlatSquare) { + return left.bigFlatSquare > right.bigFlatSquare; + } + } + + if (left.x == right.x && left.y == right.y && left.translucent != right.translucent) { + return left.translucent < right.translucent; + } + if (left.land && right.land && left.roof != right.roof) { + return left.roof < right.roof; + } + if (left.roof != right.roof) { + return left.roof > right.roof; + } + if (left.z != right.z) { + return left.z < right.z; + } + + if (xFlatLeft || xFlatRight || yFlatLeft || yFlatRight) { + if (left.sxLeft != right.sxLeft) { + return left.sxLeft > right.sxLeft; + } + if (left.syBottom != right.syBottom) { + return left.syBottom < right.syBottom; + } + } + + if (left.x + left.y != right.x + right.y) { + return left.x + left.y < right.x + right.y; + } + if (left.xLeft + left.yFar != right.xLeft + right.yFar) { + return left.xLeft + left.yFar < right.xLeft + right.yFar; + } + if (left.y != right.y) { + return left.y < right.y; + } + if (left.x != right.x) { + return left.x < right.x; + } + if (left.shape != right.shape) { + return left.shape < right.shape; + } + return left.frame < right.frame; +} + +void insertDependencySorted(std::vector& nodes, std::size_t owner, std::size_t dependency) +{ + std::vector& dependencies = nodes[owner].dependencies; + for (auto current = dependencies.begin(); current != dependencies.end(); ++current) { + if (*current == dependency) { + return; + } + if (listLessThan(nodes[dependency].item, nodes[*current].item)) { + dependencies.insert(current, dependency); + return; + } + } + dependencies.push_back(dependency); +} + +} // namespace + +std::vector resolveRenderOrder(const std::vector& items) +{ + std::vector nodes; + nodes.reserve(items.size()); + for (const RenderSortItem& item : items) { + nodes.push_back(SortNode{item, {}, false, -1}); + } + + std::vector ordered; + ordered.reserve(nodes.size()); + for (std::size_t index = 0; index < nodes.size(); ++index) { + std::size_t insertAt = ordered.size(); + for (std::size_t otherIndex = 0; otherIndex < ordered.size(); ++otherIndex) { + const std::size_t other = ordered[otherIndex]; + if (insertAt == ordered.size() && listLessThan(nodes[index].item, nodes[other].item)) { + insertAt = otherIndex; + } + if (nodes[other].occluded || !overlaps(nodes[index].item, nodes[other].item)) { + continue; + } + + if (below(nodes[index].item, nodes[other].item)) { + if (nodes[other].item.occludes && occludes(nodes[other].item, nodes[index].item)) { + nodes[index].occluded = true; + break; + } + insertDependencySorted(nodes, other, index); + } else if (nodes[index].item.occludes && occludes(nodes[index].item, nodes[other].item)) { + nodes[other].occluded = true; + } else { + insertDependencySorted(nodes, index, other); + } + } + ordered.insert(ordered.begin() + static_cast(insertAt), index); + } + + std::vector painted; + painted.reserve(nodes.size()); + const auto visit = [&nodes, &painted](const auto& self, std::size_t index) -> void { + SortNode& node = nodes[index]; + if (node.occluded || node.order >= 0) { + return; + } + node.order = -2; + for (const std::size_t dependency : node.dependencies) { + if (nodes[dependency].order == -2) { + break; + } + if (nodes[dependency].order == -1) { + self(self, dependency); + } + } + node.order = static_cast(painted.size()); + painted.push_back(index); + }; + + for (const std::size_t index : ordered) { + if (nodes[index].order == -1) { + visit(visit, index); + } + } + return painted; +} + +} // namespace detail +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/runtime.cpp b/rebuild/remorse/src/runtime.cpp index 3114f8c..df691f8 100644 --- a/rebuild/remorse/src/runtime.cpp +++ b/rebuild/remorse/src/runtime.cpp @@ -5,9 +5,59 @@ #include #include +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include +#include +#endif + namespace remorse { namespace { +#ifdef _WIN32 +void writeCrashMessage(const char* message) +{ + OutputDebugStringA(message); + const HANDLE errorOutput = GetStdHandle(STD_ERROR_HANDLE); + if (errorOutput != nullptr && errorOutput != INVALID_HANDLE_VALUE) { + DWORD written = 0; + WriteFile(errorOutput, message, static_cast(std::strlen(message)), &written, nullptr); + } +} + +LONG WINAPI reportUnhandledException(EXCEPTION_POINTERS* exception) +{ + char message[160]; + std::snprintf(message, sizeof(message), "Unhandled exception 0x%08lX at %p\n", + exception->ExceptionRecord->ExceptionCode, exception->ExceptionRecord->ExceptionAddress); + writeCrashMessage(message); + return EXCEPTION_EXECUTE_HANDLER; +} + +void reportTermination() noexcept +{ + try { + if (const auto error = std::current_exception()) { + std::rethrow_exception(error); + } + } catch (const std::exception& error) { + char message[512]; + std::snprintf(message, sizeof(message), "Unhandled C++ exception: %s\n", error.what()); + writeCrashMessage(message); + std::_Exit(EXIT_FAILURE); + } catch (...) { + writeCrashMessage("Unhandled C++ exception of unknown type\n"); + std::_Exit(EXIT_FAILURE); + } + writeCrashMessage("Program terminated without an active exception\n"); + std::_Exit(EXIT_FAILURE); +} +#endif + std::string readTextFile(const std::filesystem::path& path) { std::ifstream input(path, std::ios::binary); @@ -42,6 +92,23 @@ u32 readJsonU32(const std::string& json, const char* key) } // namespace +void installCrashDiagnostics() +{ +#ifdef _WIN32 + SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); + _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); + _set_error_mode(_OUT_TO_STDERR); +#ifdef _DEBUG + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); + _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); +#endif + SetUnhandledExceptionFilter(reportUnhandledException); + std::set_terminate(reportTermination); +#endif +} + std::optional loadExportManifestSummary(const std::filesystem::path& manifestPath) { const std::string json = readTextFile(manifestPath); @@ -73,7 +140,7 @@ void printStartupReport(const ExportManifestSummary& manifest) std::cout << "Fallback function files: " << manifest.fallbackFunctionFiles << '\n'; std::cout << "Global buckets: " << manifest.globalBuckets << '\n'; std::cout << "Global definitions: " << manifest.globalDefinitions << '\n'; - std::cout << "Status: host runtime scaffold is alive; exported game code is not linked yet.\n"; + std::cout << "Status: StandProcess Run, registered timer, and keyboard diagnostic callback active; original key queue, NPC services, and game loop not linked.\n"; } } // namespace remorse diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp new file mode 100644 index 0000000..25a232e --- /dev/null +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -0,0 +1,770 @@ +#define NOMINMAX +#define WIN32_LEAN_AND_MEAN +#include + +#include "remorse/animation_archive.h" +#include "remorse/collision.h" +#include "remorse/entity_dispatch_entry.h" +#include "remorse/file_system.h" +#include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" +#include "remorse/isometric_controls.h" +#include "remorse/map_renderer.h" +#include "remorse/palette.h" +#include "remorse/runtime.h" +#include "remorse/shape_archive.h" +#include "remorse/type_flags.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr wchar_t windowClassName[] = L"CrusaderRemorseGameWindow"; +constexpr UINT timerId = 1; +constexpr UINT sceneReadyMessage = WM_APP + 1; +constexpr remorse::u32 backingWidth = 2560; +constexpr remorse::u32 backingHeight = 1440; +constexpr int initialClientWidth = 1280; +constexpr int initialClientHeight = 760; +constexpr double simulationTickSeconds = 0.025; + +struct AppState { + remorse::GameDataRoot root; + remorse::u32 mapIndex = 1; + remorse::ProcessKernel diagnosticKernel; + remorse::u16 diagnosticGroupCounts[32]{}; + remorse::StandProcessEntry* diagnosticStand = nullptr; + remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr; + remorse::u32 standWakeCount = 0; + remorse::u32 diagnosticKeyEvents = 0; + std::mutex sceneMutex; + std::optional scene; + std::optional standAnimation; + std::optional walkAnimation; + std::optional runAnimation; + std::vector> playerFrames; + remorse::CollisionBody playerCollisionBody{}; + std::vector collisionBodies; + remorse::Palette256 playerPalette{}; + std::vector dibPixels; + std::vector viewPixels; + remorse::WorldPoint spawn{}; + remorse::WorldPoint playerWorld{}; + remorse::s32 minWorldX = 0; + remorse::s32 minWorldY = 0; + remorse::s32 maxWorldX = 0; + remorse::s32 maxWorldY = 0; + double playerOffsetX = 0.0; + double playerOffsetY = 0.0; + double simulationAccumulator = 0.0; + remorse::u8 playerAnimation = 0; + remorse::u8 playerDirection = 14; + remorse::u8 playerFrame = 0; + std::wstring loadError; + bool sceneLoaded = false; + std::thread sceneThread; + HDC backBufferDc = nullptr; + HBITMAP backBufferBitmap = nullptr; + HBITMAP previousBackBufferBitmap = nullptr; + int backBufferWidth = 0; + int backBufferHeight = 0; + LARGE_INTEGER lastTick{}; + LARGE_INTEGER ticksPerSecond{}; +}; + +remorse::u32 standSleepStart(const remorse::StandProcessEntry& stand) +{ + const auto& bytes = stand.base.bytes; + return bytes[0x0a] | (static_cast(bytes[0x0b]) << 8) | + (static_cast(bytes[0x0c]) << 16) | + (static_cast(bytes[0x0d]) << 24); +} + +std::wstring widen(const std::string& value) +{ + if (value.empty()) { + return {}; + } + const int length = MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast(value.size()), nullptr, 0); + if (length <= 0) { + return L"Map loading failed."; + } + std::wstring result(static_cast(length), L'\0'); + MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast(value.size()), result.data(), length); + return result; +} + +void setLoadFailure(AppState& state, const std::wstring& message) +{ + std::lock_guard lock(state.sceneMutex); + state.loadError = message; + state.sceneLoaded = true; +} + +void loadSceneAsync(HWND window, AppState& state) +{ + state.sceneThread = std::thread([window, &state]() { + try { + const auto fixedPath = remorse::resolveGameDataPath( + state.root, std::filesystem::path("STATIC") / "FIXED.DAT"); + const auto typeFlagsPath = remorse::resolveGameDataPath( + state.root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); + const auto globPath = remorse::resolveGameDataPath( + state.root, std::filesystem::path("STATIC") / "GLOB.FLX"); + if (!fixedPath) { + setLoadFailure(state, L"STATIC\\FIXED.DAT was not found under the game data root."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + if (!typeFlagsPath || !globPath) { + setLoadFailure(state, L"STATIC\\TYPEFLAG.DAT or STATIC\\GLOB.FLX was not found."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + + const auto archive = remorse::loadFixedMapArchive(*fixedPath); + const auto map = archive ? remorse::loadFixedMap(*archive, state.mapIndex) : std::nullopt; + if (!map || map->entries.empty()) { + setLoadFailure(state, L"The selected map could not be loaded or contains no records."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + + const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath); + const auto globObjects = remorse::loadGlobObjects(*globPath); + if (!shapeTypes || !globObjects || shapeTypes->size() <= 1) { + setLoadFailure(state, L"Collision shape metadata could not be loaded."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + auto collisionBodies = remorse::collectMapCollisionBodies(*map, *shapeTypes, *globObjects); + + const auto animationPath = remorse::resolveGameDataPath( + state.root, std::filesystem::path("STATIC") / "ANIM.DAT"); + const auto shapesPath = remorse::resolveGameDataPath( + state.root, std::filesystem::path("STATIC") / "SHAPES.FLX"); + const auto palettePath = remorse::resolveGameDataPath( + state.root, std::filesystem::path("STATIC") / "GAMEPAL.PAL"); + if (!animationPath || !shapesPath || !palettePath) { + setLoadFailure(state, L"The player animation, shape, or palette resource is missing."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + + const auto animationArchive = remorse::loadAnimationArchive(*animationPath); + const auto shapeArchive = remorse::loadShapeArchive(*shapesPath); + const auto palette = remorse::loadPalette256(*palettePath); + const auto standAnimation = animationArchive + ? remorse::loadAnimationClip(*animationArchive, 1, 0) : std::nullopt; + const auto walkAnimation = animationArchive + ? remorse::loadAnimationClip(*animationArchive, 1, 1) : std::nullopt; + const auto runAnimation = animationArchive + ? remorse::loadAnimationClip(*animationArchive, 1, 3) : std::nullopt; + const auto shapeFrames = shapeArchive + ? remorse::loadShapeFrames(*shapeArchive, 1) : std::nullopt; + if (!shapeArchive || !palette || !standAnimation || !walkAnimation || !runAnimation || !shapeFrames) { + setLoadFailure(state, L"The player stand, walk, or run animation could not be loaded."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + + std::vector> playerFrames(shapeFrames->size()); + const auto cacheAnimationFrames = [&](const remorse::AnimationClip& clip) { + for (remorse::u8 direction = 0; direction < 16; ++direction) { + for (remorse::u32 frameIndex = 0; frameIndex < clip.frameCount; ++frameIndex) { + const auto metadata = remorse::getAnimationFrame( + clip, direction, static_cast(frameIndex)); + if (!metadata) { + return false; + } + const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata); + if (shapeFrame >= playerFrames.size()) { + return false; + } + if (!playerFrames[shapeFrame]) { + auto decoded = remorse::decodeShapeFrame(*shapeArchive, 1, shapeFrame); + if (!decoded) { + return false; + } + playerFrames[shapeFrame] = std::move(*decoded); + } + } + } + return true; + }; + if (!cacheAnimationFrames(*standAnimation) || !cacheAnimationFrames(*walkAnimation) || + !cacheAnimationFrames(*runAnimation)) { + setLoadFailure(state, L"A player animation references a missing shape frame."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + + remorse::s32 minX = map->entries.front().x; + remorse::s32 minY = map->entries.front().y; + remorse::s32 maxX = minX; + remorse::s32 maxY = minY; + for (const remorse::FixedMapEntry& entry : map->entries) { + minX = std::min(minX, static_cast(entry.x)); + minY = std::min(minY, static_cast(entry.y)); + maxX = std::max(maxX, static_cast(entry.x)); + maxY = std::max(maxY, static_cast(entry.y)); + } + + const remorse::WorldPoint spawn{(minX + maxX) / 2, (minY + maxY) / 2, 0}; + remorse::MapRenderOptions options; + options.mapIndex = state.mapIndex; + options.maxWidth = backingWidth; + options.maxHeight = backingHeight; + options.viewCenter = spawn; + auto scene = remorse::renderMapPreview(state.root, options); + if (!scene) { + setLoadFailure(state, L"Map graphics or palette data could not be loaded."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + + std::vector dibPixels(scene->pixels.size() * 3); + for (std::size_t index = 0; index < scene->pixels.size(); ++index) { + dibPixels[index * 3] = scene->pixels[index].blue; + dibPixels[index * 3 + 1] = scene->pixels[index].green; + dibPixels[index * 3 + 2] = scene->pixels[index].red; + } + + { + std::lock_guard lock(state.sceneMutex); + state.spawn = spawn; + state.playerWorld = spawn; + state.playerCollisionBody = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]); + state.collisionBodies = std::move(collisionBodies); + state.minWorldX = minX; + state.minWorldY = minY; + state.maxWorldX = maxX; + state.maxWorldY = maxY; + state.scene = std::move(scene); + state.dibPixels = std::move(dibPixels); + state.standAnimation = *standAnimation; + state.walkAnimation = *walkAnimation; + state.runAnimation = *runAnimation; + state.playerFrames = std::move(playerFrames); + state.playerPalette = *palette; + state.sceneLoaded = true; + } + } catch (const std::exception& error) { + setLoadFailure(state, widen(error.what())); + } catch (...) { + setLoadFailure(state, L"An unexpected error occurred while building the map scene."); + } + PostMessageW(window, sceneReadyMessage, 0, 0); + }); +} + +void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLORREF color, HFONT font) +{ + const int saved = SaveDC(device); + SetBkMode(device, TRANSPARENT); + SetTextColor(device, color); + SelectObject(device, font); + DrawTextW(device, text, -1, const_cast(&bounds), DT_CENTER | DT_VCENTER | DT_SINGLELINE); + RestoreDC(device, saved); +} + +bool isKeyDown(int key) +{ + return (GetAsyncKeyState(key) & 0x8000) != 0; +} + +std::optional readMovementDirection() +{ + if (isKeyDown(VK_HOME) || isKeyDown(VK_NUMPAD7) || isKeyDown('Q')) return static_cast(12); + if (isKeyDown(VK_PRIOR) || isKeyDown(VK_NUMPAD9) || isKeyDown('E')) return static_cast(0); + if (isKeyDown(VK_END) || isKeyDown(VK_NUMPAD1) || isKeyDown('Z')) return static_cast(8); + if (isKeyDown(VK_NEXT) || isKeyDown(VK_NUMPAD3) || isKeyDown('C')) return static_cast(4); + + const bool up = isKeyDown(VK_UP) || isKeyDown('W') || isKeyDown(VK_NUMPAD8); + const bool right = isKeyDown(VK_RIGHT) || isKeyDown('D') || isKeyDown(VK_NUMPAD6); + const bool down = isKeyDown(VK_DOWN) || isKeyDown('S') || isKeyDown(VK_NUMPAD2); + const bool left = isKeyDown(VK_LEFT) || isKeyDown('A') || isKeyDown(VK_NUMPAD4); + if (up && left) return static_cast(12); + if (up && right) return static_cast(0); + if (down && left) return static_cast(8); + if (down && right) return static_cast(4); + if (up) return static_cast(14); + if (right) return static_cast(2); + if (down) return static_cast(6); + if (left) return static_cast(10); + return std::nullopt; +} + +bool isWalkRequested() +{ + remorse::u16 modifiers = (GetKeyState(VK_CAPITAL) & 1) != 0 ? 0x40 : 0; + if (isKeyDown(VK_LSHIFT)) modifiers |= 0x01; + if (isKeyDown(VK_RSHIFT)) modifiers |= 0x02; + return remorse::controllerWalkRequested(modifiers); +} + +void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight, + int sourceLeft, int sourceTop, std::size_t viewStride) +{ + const remorse::AnimationClip* clip = nullptr; + if (state.playerAnimation == 1 && state.walkAnimation) { + clip = &*state.walkAnimation; + } else if (state.playerAnimation == 3 && state.runAnimation) { + clip = &*state.runAnimation; + } else if (state.standAnimation) { + clip = &*state.standAnimation; + } + if (!clip || state.playerFrames.empty()) { + return; + } + + const remorse::u8 frameIndex = state.playerAnimation == 0 ? 0 : state.playerFrame; + const auto metadata = remorse::getAnimationFrame(*clip, state.playerDirection, frameIndex); + if (!metadata) { + return; + } + const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata); + if (shapeFrame >= state.playerFrames.size() || !state.playerFrames[shapeFrame]) { + return; + } + + const remorse::DecodedShapeFrame& sprite = *state.playerFrames[shapeFrame]; + const int actorX = static_cast(state.scene->width / 2) + + static_cast(std::lround(state.playerOffsetX)) - sourceLeft; + const int actorY = static_cast(state.scene->height / 2) + + static_cast(std::lround(state.playerOffsetY)) - sourceTop; + const int spriteLeft = actorX + sprite.frame.xOffset; + const int spriteTop = actorY + sprite.frame.yOffset; + const bool flipped = remorse::isAnimationFrameFlipped(*metadata); + + for (remorse::u32 y = 0; y < sprite.frame.height; ++y) { + const int destinationY = spriteTop + static_cast(y); + if (destinationY < 0 || destinationY >= viewHeight) { + continue; + } + for (remorse::u32 x = 0; x < sprite.frame.width; ++x) { + const int destinationX = spriteLeft + static_cast(x); + if (destinationX < 0 || destinationX >= viewWidth) { + continue; + } + const remorse::u32 sourceX = flipped ? sprite.frame.width - 1 - x : x; + const remorse::s16 paletteIndex = sprite.pixels[ + static_cast(y) * sprite.frame.width + sourceX]; + if (paletteIndex < 0) { + continue; + } + const remorse::RgbColor& color = state.playerPalette.colors[ + static_cast(paletteIndex)]; + const std::size_t pixelOffset = static_cast(destinationY) * viewStride + + static_cast(destinationX) * 3; + state.viewPixels[pixelOffset] = static_cast(color.blue * 255 / 63); + state.viewPixels[pixelOffset + 1] = static_cast(color.green * 255 / 63); + state.viewPixels[pixelOffset + 2] = static_cast(color.red * 255 / 63); + } + } + + BITMAPINFO bitmap{}; + bitmap.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + bitmap.bmiHeader.biWidth = viewWidth; + bitmap.bmiHeader.biHeight = -viewHeight; + bitmap.bmiHeader.biPlanes = 1; + bitmap.bmiHeader.biBitCount = 24; + bitmap.bmiHeader.biCompression = BI_RGB; + StretchDIBits(device, 0, 0, viewWidth, viewHeight, 0, 0, viewWidth, viewHeight, + state.viewPixels.data(), &bitmap, DIB_RGB_COLORS, SRCCOPY); +} + +void drawLoadingScreen(HDC device, const RECT& client, const AppState& state) +{ + HBRUSH background = CreateSolidBrush(RGB(13, 23, 28)); + FillRect(device, &client, background); + DeleteObject(background); + + RECT title = client; + title.bottom = title.top + 70; + HFONT titleFont = CreateFontW(-30, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, + DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, + DEFAULT_PITCH | FF_DONTCARE, L"Bahnschrift"); + drawCenteredText(device, title, L"CRUSADER / NO REMORSE", RGB(228, 220, 191), titleFont); + DeleteObject(titleFont); + + RECT status = client; + status.top = title.bottom; + HFONT bodyFont = CreateFontW(-18, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, + DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, + DEFAULT_PITCH | FF_DONTCARE, L"Consolas"); + const std::wstring message = state.loadError.empty() + ? L"Building the retail map scene..." + : state.loadError; + drawCenteredText(device, status, message.c_str(), state.loadError.empty() + ? RGB(74, 207, 184) : RGB(245, 157, 119), bodyFont); + DeleteObject(bodyFont); +} + +void paintWindow(HWND window, AppState& state) +{ + PAINTSTRUCT paint{}; + HDC paintDc = BeginPaint(window, &paint); + RECT client{}; + GetClientRect(window, &client); + + const int clientWidth = static_cast(std::max(1L, client.right - client.left)); + const int clientHeight = static_cast(std::max(1L, client.bottom - client.top)); + if (state.backBufferWidth != clientWidth || state.backBufferHeight != clientHeight) { + if (state.backBufferDc) { + SelectObject(state.backBufferDc, state.previousBackBufferBitmap); + DeleteObject(state.backBufferBitmap); + DeleteDC(state.backBufferDc); + state.backBufferDc = nullptr; + state.backBufferBitmap = nullptr; + state.previousBackBufferBitmap = nullptr; + } + state.backBufferDc = CreateCompatibleDC(paintDc); + if (state.backBufferDc) { + state.backBufferBitmap = CreateCompatibleBitmap(paintDc, clientWidth, clientHeight); + if (state.backBufferBitmap) { + state.previousBackBufferBitmap = static_cast( + SelectObject(state.backBufferDc, state.backBufferBitmap)); + state.backBufferWidth = clientWidth; + state.backBufferHeight = clientHeight; + } else { + DeleteDC(state.backBufferDc); + state.backBufferDc = nullptr; + } + } + } + HDC device = state.backBufferDc ? state.backBufferDc : paintDc; + const auto finishPaint = [&]() { + if (device != paintDc) { + BitBlt(paintDc, 0, 0, clientWidth, clientHeight, device, 0, 0, SRCCOPY); + } + EndPaint(window, &paint); + }; + + std::lock_guard lock(state.sceneMutex); + if (!state.sceneLoaded || !state.scene) { + drawLoadingScreen(device, client, state); + finishPaint(); + return; + } + if (!state.loadError.empty()) { + drawLoadingScreen(device, client, state); + finishPaint(); + return; + } + + HBRUSH clearBrush = CreateSolidBrush(RGB(10, 17, 22)); + FillRect(device, &client, clearBrush); + DeleteObject(clearBrush); + + const int viewWidth = std::min(clientWidth, static_cast(state.scene->width)); + const int viewHeight = std::min(clientHeight, static_cast(state.scene->height)); + const int centeredLeft = static_cast(state.scene->width / 2) + + static_cast(std::lround(state.playerOffsetX)) - viewWidth / 2; + const int centeredTop = static_cast(state.scene->height / 2) + + static_cast(std::lround(state.playerOffsetY)) - viewHeight / 2; + const int sourceLeft = std::clamp(centeredLeft, 0, static_cast(state.scene->width) - viewWidth); + const int sourceTop = std::clamp(centeredTop, 0, static_cast(state.scene->height) - viewHeight); + + const std::size_t viewStride = (static_cast(viewWidth) * 3 + 3) & ~std::size_t(3); + state.viewPixels.resize(viewStride * static_cast(viewHeight)); + const std::size_t sceneStride = static_cast(state.scene->width) * 3; + for (int row = 0; row < viewHeight; ++row) { + const std::size_t sceneOffset = static_cast(sourceTop + row) * sceneStride + + static_cast(sourceLeft) * 3; + const std::size_t viewOffset = static_cast(row) * viewStride; + std::memcpy(state.viewPixels.data() + viewOffset, state.dibPixels.data() + sceneOffset, + static_cast(viewWidth) * 3); + } + compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride); + + RECT hud{0, 0, viewWidth, 62}; + HBRUSH hudBrush = CreateSolidBrush(RGB(14, 24, 29)); + FillRect(device, &hud, hudBrush); + DeleteObject(hudBrush); + HPEN hudLine = CreatePen(PS_SOLID, 1, RGB(43, 204, 178)); + HGDIOBJ oldPen = SelectObject(device, hudLine); + MoveToEx(device, 0, hud.bottom - 1, nullptr); + LineTo(device, viewWidth, hud.bottom - 1); + SelectObject(device, oldPen); + DeleteObject(hudLine); + + std::wostringstream label; + label << L"MAP " << std::setw(3) << std::setfill(L'0') << state.mapIndex + << L" X " << state.playerWorld.x + << L" Y " << state.playerWorld.y + << L" Z " << static_cast(state.playerWorld.z) + << L" DIR " << std::setw(2) << static_cast(state.playerDirection) + << L" " << (state.playerAnimation == 3 ? L"RUN" : state.playerAnimation == 1 ? L"WALK" : L"IDLE") + << L" WASD / KEYPAD SHIFT RUN"; + HFONT hudFont = CreateFontW(-16, 0, 0, 0, FW_MEDIUM, FALSE, FALSE, FALSE, + DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, + DEFAULT_PITCH | FF_DONTCARE, L"Consolas"); + RECT labelBounds{20, 0, viewWidth - 12, 36}; + const int saved = SaveDC(device); + SetBkMode(device, TRANSPARENT); + SetTextColor(device, RGB(224, 229, 214)); + SelectObject(device, hudFont); + DrawTextW(device, label.str().c_str(), -1, &labelBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE); + const remorse::EntityDispatchEntryBase& stand = state.diagnosticStand->base; + const remorse::u32 sleepStart = standSleepStart(*state.diagnosticStand); + const remorse::u32 sleepLength = stand.bytes[0x0e] | (static_cast(stand.bytes[0x0f]) << 8); + std::wostringstream diagnostics; + diagnostics << L"HOST 40Hz | KERNEL TICK " << state.diagnosticKernel.systemTimerTick() + << L" | STAND #" << static_cast(stand.bytes[0x02]) + << L" " << ((stand.bytes[0x19] & 0x10) != 0 ? L"SLEEP " : L"READY ") + << ((stand.bytes[0x19] & 0x10) != 0 + ? static_cast(sleepStart + sleepLength - state.diagnosticKernel.systemTimerTick() + 1) + : 0) + << L" | WAKEUPS " << state.standWakeCount + << L" | KEY EVENTS " << state.diagnosticKeyEvents; + RECT diagnosticsBounds{20, 36, viewWidth - 12, hud.bottom - 1}; + SetTextColor(device, RGB(74, 207, 184)); + DrawTextW(device, diagnostics.str().c_str(), -1, &diagnosticsBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); + RestoreDC(device, saved); + DeleteObject(hudFont); + + finishPaint(); +} + +void updatePlayer(HWND window, AppState& state) +{ + LARGE_INTEGER now{}; + QueryPerformanceCounter(&now); + const double elapsed = std::clamp( + static_cast(now.QuadPart - state.lastTick.QuadPart) / + static_cast(state.ticksPerSecond.QuadPart), + 0.0, 0.25); + state.lastTick = now; + + if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) { + DestroyWindow(window); + return; + } + if (GetForegroundWindow() != window) { + return; + } + std::lock_guard lock(state.sceneMutex); + if (!state.sceneLoaded || !state.scene || !state.loadError.empty()) { + return; + } + + state.simulationAccumulator += elapsed; + const auto direction = readMovementDirection(); + bool changed = false; + while (state.simulationAccumulator >= simulationTickSeconds) { + state.simulationAccumulator -= simulationTickSeconds; + state.diagnosticKernel.deliverSystemTimerEvent(); + const bool wasSleeping = (state.diagnosticStand->base.bytes[0x19] & 0x10) != 0; + const remorse::u32 previousSleepStart = standSleepStart(*state.diagnosticStand); + state.diagnosticKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& entry, void* context) { + auto& app = *static_cast(context); + if (&entry == &app.diagnosticStand->base) { + remorse::StandProcess::run(entry, + [](const remorse::EntityDispatchEntryBase&, void*) { return false; }, + nullptr, app.diagnosticKernel.systemTimerTick()); + } + }, &state, state.diagnosticKernel.systemTimerTick()); + if (wasSleeping && standSleepStart(*state.diagnosticStand) != previousSleepStart) { + ++state.standWakeCount; + } + changed = true; + if (!direction) { + changed = changed || state.playerAnimation != 0 || state.playerFrame != 0; + state.playerAnimation = 0; + state.playerFrame = 0; + continue; + } + + const remorse::u8 requestedAnimation = isWalkRequested() ? 1 : 3; + const remorse::AnimationClip& clip = requestedAnimation == 1 + ? *state.walkAnimation : *state.runAnimation; + if (state.playerAnimation != requestedAnimation) { + state.playerAnimation = requestedAnimation; + state.playerFrame = 0; + } else { + state.playerFrame = static_cast( + (state.playerFrame + 1) % clip.frameCount); + } + state.playerDirection = *direction; + + const auto metadata = remorse::getAnimationFrame(clip, state.playerDirection, state.playerFrame); + if (metadata) { + const auto step = remorse::hostMovementStep( + *metadata, state.playerDirection, (clip.header[2] & 0x10) != 0); + if (step) { + const remorse::WorldPoint destination{ + state.playerWorld.x + step->x, + state.playerWorld.y + step->y, + state.playerWorld.z + step->z}; + const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(destination); + const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn); + const double nextOffsetX = destinationScreen.x - spawnScreen.x; + const double nextOffsetY = destinationScreen.y - spawnScreen.y; + const bool withinMapBounds = destination.x >= state.minWorldX && + destination.x <= state.maxWorldX && destination.y >= state.minWorldY && + destination.y <= state.maxWorldY; + const bool withinSceneBounds = std::abs(nextOffsetX) <= backingWidth / 2 - 16 && + std::abs(nextOffsetY) <= backingHeight / 2 - 16; + if (withinMapBounds && withinSceneBounds && remorse::canMoveCollisionBody( + state.playerCollisionBody, destination, state.collisionBodies)) { + state.playerWorld = destination; + state.playerCollisionBody.location = destination; + state.playerOffsetX = nextOffsetX; + state.playerOffsetY = nextOffsetY; + } + } + } + changed = true; + } + if (changed) { + InvalidateRect(window, nullptr, FALSE); + } +} + +LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARAM lParam) +{ + AppState* state = reinterpret_cast(GetWindowLongPtrW(window, GWLP_USERDATA)); + if (message == WM_NCCREATE) { + const auto* create = reinterpret_cast(lParam); + state = static_cast(create->lpCreateParams); + SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast(state)); + } + if (!state) { + return DefWindowProcW(window, message, wParam, lParam); + } + + switch (message) { + case WM_CREATE: + QueryPerformanceFrequency(&state->ticksPerSecond); + QueryPerformanceCounter(&state->lastTick); + SetTimer(window, timerId, 16, nullptr); + loadSceneAsync(window, *state); + return 0; + case WM_TIMER: + if (wParam == timerId) { + updatePlayer(window, *state); + } + return 0; + case WM_CHAR: + if (wParam > 0 && wParam <= 0xff) { + remorse::KeyEvent lastEvent{}; + lastEvent.character = static_cast(wParam); + lastEvent.scanCode = static_cast((lParam >> 16) & 0xff); + lastEvent.field8 = 1; + remorse::KeyEvent event = lastEvent; + if (remorse::KeyboardProcess::handleKeyEvent(*state->diagnosticKeyboard, 0x10, 0, event, lastEvent)) { + ++state->diagnosticKeyEvents; + InvalidateRect(window, nullptr, FALSE); + } + } + return 0; + case WM_SIZE: + InvalidateRect(window, nullptr, FALSE); + return 0; + case WM_ERASEBKGND: + return 1; + case WM_PAINT: + paintWindow(window, *state); + return 0; + case sceneReadyMessage: + InvalidateRect(window, nullptr, FALSE); + return 0; + case WM_DESTROY: + KillTimer(window, timerId); + if (state->sceneThread.joinable()) { + state->sceneThread.join(); + } + if (state->backBufferDc) { + SelectObject(state->backBufferDc, state->previousBackBufferBitmap); + DeleteObject(state->backBufferBitmap); + DeleteDC(state->backBufferDc); + } + PostQuitMessage(0); + return 0; + default: + return DefWindowProcW(window, message, wParam, lParam); + } +} + +} // namespace + +int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCommand) +{ + remorse::installCrashDiagnostics(); + remorse::u32 mapIndex = 1; + if (commandLine && *commandLine) { + wchar_t* end = nullptr; + const unsigned long parsed = std::wcstoul(commandLine, &end, 0); + if (end != commandLine && parsed <= 255) { + mapIndex = static_cast(parsed); + } + } + + wchar_t executablePath[MAX_PATH]{}; + GetModuleFileNameW(nullptr, executablePath, MAX_PATH); + auto root = remorse::findGameDataRoot(std::filesystem::path(executablePath).parent_path()); + if (!root) { + root = remorse::findGameDataRoot(std::filesystem::current_path()); + } + if (!root) { + MessageBoxW(nullptr, + L"Could not locate CRUSADER.EXE, STATIC, and USECODE. Place this application below the game data folder or launch it from that folder.", + L"Crusader Rebuild", MB_OK | MB_ICONERROR); + return 2; + } + + AppState state; + state.root = *root; + state.mapIndex = mapIndex; + for (int index = 0; index < 3; ++index) { + state.diagnosticKernel.createProcess(1, state.diagnosticGroupCounts); + } + state.diagnosticKernel.createSystemTimerProcess(1, state.diagnosticGroupCounts); + state.diagnosticKeyboard = state.diagnosticKernel.createKeyboardProcess(1, state.diagnosticGroupCounts); + state.diagnosticKernel.createKeyDaemonProcess(1, state.diagnosticGroupCounts); + state.diagnosticStand = state.diagnosticKernel.createStandProcess(1, 1, state.diagnosticGroupCounts); + + WNDCLASSEXW windowClass{}; + windowClass.cbSize = sizeof(windowClass); + windowClass.style = CS_HREDRAW | CS_VREDRAW; + windowClass.lpfnWndProc = windowProcedure; + windowClass.hInstance = instance; + windowClass.hCursor = LoadCursorW(nullptr, MAKEINTRESOURCEW(32512)); + windowClass.hIcon = LoadIconW(nullptr, MAKEINTRESOURCEW(32512)); + windowClass.hbrBackground = reinterpret_cast(COLOR_WINDOW + 1); + windowClass.lpszClassName = windowClassName; + if (!RegisterClassExW(&windowClass)) { + MessageBoxW(nullptr, L"Could not register the game window.", L"Crusader Rebuild", MB_OK | MB_ICONERROR); + return 3; + } + + RECT bounds{0, 0, initialClientWidth, initialClientHeight}; + AdjustWindowRect(&bounds, WS_OVERLAPPEDWINDOW, FALSE); + HWND window = CreateWindowExW(0, windowClassName, L"Crusader: No Remorse | Rebuild", WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, CW_USEDEFAULT, bounds.right - bounds.left, bounds.bottom - bounds.top, + nullptr, nullptr, instance, &state); + if (!window) { + MessageBoxW(nullptr, L"Could not create the game window.", L"Crusader Rebuild", MB_OK | MB_ICONERROR); + return 4; + } + + ShowWindow(window, showCommand); + UpdateWindow(window); + MSG message{}; + while (GetMessageW(&message, nullptr, 0, 0) > 0) { + TranslateMessage(&message); + DispatchMessageW(&message); + } + return static_cast(message.wParam); +} \ No newline at end of file diff --git a/rebuild/remorse/tests/animation_archive_tests.cpp b/rebuild/remorse/tests/animation_archive_tests.cpp new file mode 100644 index 0000000..6795822 --- /dev/null +++ b/rebuild/remorse/tests/animation_archive_tests.cpp @@ -0,0 +1,149 @@ +#include "remorse/animation_archive.h" +#include "remorse/file_system.h" +#include "remorse/isometric_controls.h" +#include "remorse/shape_archive.h" + +#include +#include + +namespace { + +void writeU32Le(std::vector& bytes, std::size_t offset, remorse::u32 value) +{ + for (std::size_t index = 0; index < 4; ++index) { + bytes[offset + index] = static_cast(value >> (index * 8)); + } +} + +remorse::AnimationArchive makeSyntheticArchive() +{ + constexpr remorse::u32 shapeTable = 0x20; + constexpr remorse::u32 clipOffset = 0x440; + std::vector bytes(clipOffset + 4 + 2 * 16 * 8); + writeU32Le(bytes, 4, shapeTable); + writeU32Le(bytes, shapeTable + 4, clipOffset); + bytes[clipOffset] = 2; + bytes[clipOffset + 1] = 5; + bytes[clipOffset + 2] = 0x02; + bytes[clipOffset + 3] = 0x40; + const std::size_t frameOffset = clipOffset + 4 + (5 * 2 + 1) * 8; + bytes[frameOffset] = 0x34; + bytes[frameOffset + 1] = 0x81; + bytes[frameOffset + 2] = 0xfe; + bytes[frameOffset + 4] = 0xff; + bytes[frameOffset + 5] = 0x01; + return remorse::AnimationArchive{std::move(bytes)}; +} + +} // namespace + +int main() +{ + const auto synthetic = makeSyntheticArchive(); + const auto sixteenDirectionClip = remorse::loadAnimationClip(synthetic, 1, 1); + assert(sixteenDirectionClip.has_value()); + assert(sixteenDirectionClip->frameCount == 2); + assert(sixteenDirectionClip->directionCount == 16); + const auto selectedFrame = remorse::getAnimationFrame(*sixteenDirectionClip, 5, 1); + assert(selectedFrame.has_value()); + assert(remorse::getAnimationShapeFrame(*selectedFrame) == 0x134); + assert(remorse::isAnimationFrameFlipped(*selectedFrame)); + const auto rotatedStep = remorse::decodeAnimationDisplacement(*selectedFrame, 5, true); + assert(rotatedStep.has_value()); + assert(rotatedStep->x == 2); + assert(rotatedStep->y == -4); + assert(rotatedStep->z == -2); + assert(!rotatedStep->onGround); + assert(!remorse::getAnimationFrame(*sixteenDirectionClip, 16, 0)); + assert(!remorse::getAnimationFrame(*sixteenDirectionClip, 0, 2)); + + remorse::AnimationFrameMetadata negativeStride; + negativeStride.bytes[4] = 0xff; + negativeStride.bytes[5] = 0x01; + const auto northStep = remorse::decodeAnimationDisplacement(negativeStride, 0, false); + assert(northStep.has_value()); + assert(northStep->x == 0); + assert(northStep->y == 2); + negativeStride.bytes[5] = 0x03; + const auto groundedStep = remorse::decodeAnimationDisplacement(negativeStride, 0, false); + assert(groundedStep.has_value() && groundedStep->onGround); + + remorse::AnimationFrameMetadata positiveStride; + positiveStride.bytes[4] = 1; + const remorse::s32 expectedX[16] = { + 0, 2, 2, 4, 2, 4, 2, 2, 0, -2, -2, -4, -2, -4, -2, -2}; + const remorse::s32 expectedY[16] = { + -2, -4, -2, -2, 0, 2, 2, 4, 2, 4, 2, 2, 0, -2, -2, -4}; + for (remorse::u8 direction = 0; direction < 16; ++direction) { + const auto step = remorse::decodeAnimationDisplacement(positiveStride, direction, false); + assert(step.has_value()); + assert(step->x == expectedX[direction]); + assert(step->y == expectedY[direction]); + } + + remorse::AnimationArchive malformed; + malformed.bytes.resize(8); + writeU32Le(malformed.bytes, 4, 0xfffffff0); + assert(!remorse::loadAnimationClip(malformed, 1, 0)); + + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); + assert(root.has_value()); + const auto animationPath = remorse::resolveGameDataPath( + *root, std::filesystem::path("STATIC") / "ANIM.DAT"); + assert(animationPath.has_value()); + const auto animationArchive = remorse::loadAnimationArchive(*animationPath); + assert(animationArchive.has_value()); + + const auto stand = remorse::loadAnimationClip(*animationArchive, 1, 0); + const auto walk = remorse::loadAnimationClip(*animationArchive, 1, 1); + const auto run = remorse::loadAnimationClip(*animationArchive, 1, 3); + assert(stand.has_value() && stand->frameCount > 0); + assert(walk.has_value() && walk->frameCount == 17); + assert(run.has_value() && run->frameCount == 12); + assert(remorse::getAnimationFrame(*walk, 0, 0).has_value()); + assert(remorse::getAnimationFrame(*run, 15, 11).has_value()); + for (remorse::u8 direction : {remorse::u8{6}, remorse::u8{7}, remorse::u8{10}, remorse::u8{11}}) { + for (remorse::u8 frame : {remorse::u8{4}, remorse::u8{12}}) { + const auto metadata = remorse::getAnimationFrame(*walk, direction, frame); + assert(metadata.has_value() && (metadata->bytes[5] & 1) != 0); + const auto authored = remorse::decodeAnimationDisplacement(*metadata, direction, false); + const auto host = remorse::hostMovementStep(*metadata, direction, false); + assert(authored && (authored->x < 0 || authored->y < 0)); + assert(host && host->x == 0 && host->y == 0); + } + } + const auto runFrame = remorse::getAnimationFrame(*run, 14, 6); + assert(runFrame.has_value()); + const auto hostRun = remorse::hostMovementStep(*runFrame, 14, false); + assert(hostRun && hostRun->x < 0 && hostRun->y < 0); + + const auto shapesPath = remorse::resolveGameDataPath( + *root, std::filesystem::path("STATIC") / "SHAPES.FLX"); + assert(shapesPath.has_value()); + const auto shapeArchive = remorse::loadShapeArchive(*shapesPath); + assert(shapeArchive.has_value()); + const auto playerFrames = remorse::loadShapeFrames(*shapeArchive, 1); + assert(playerFrames.has_value() && playerFrames->size() >= walk->frameCount); + std::vector referencedFrames(playerFrames->size(), false); + for (const remorse::AnimationClip* clip : {&*stand, &*walk, &*run}) { + for (remorse::u8 direction = 0; direction < 16; ++direction) { + for (remorse::u8 frame = 0; frame < clip->frameCount; ++frame) { + const auto metadata = remorse::getAnimationFrame(*clip, direction, frame); + assert(metadata.has_value()); + const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata); + assert(shapeFrame < referencedFrames.size()); + referencedFrames[shapeFrame] = true; + } + } + } + bool decodedReferencedFrame = false; + for (std::size_t frame = 0; frame < referencedFrames.size(); ++frame) { + if (referencedFrames[frame]) { + assert(remorse::decodeShapeFrame(*shapeArchive, 1, static_cast(frame)).has_value()); + decodedReferencedFrame = true; + break; + } + } + assert(decodedReferencedFrame); + return 0; +} \ No newline at end of file diff --git a/rebuild/remorse/tests/collision_tests.cpp b/rebuild/remorse/tests/collision_tests.cpp new file mode 100644 index 0000000..d8fe5c7 --- /dev/null +++ b/rebuild/remorse/tests/collision_tests.cpp @@ -0,0 +1,72 @@ +#include "remorse/collision.h" + +#include + +int main() +{ + const remorse::CollisionBody actor{{100, 100, 0}, 96, 96, 80}; + const remorse::CollisionBody wall{{300, 100, 0}, 64, 96, 128}; + assert(!remorse::collisionBodiesOverlap(actor, wall)); + assert(remorse::canMoveCollisionBody(actor, {200, 100, 0}, {wall})); + assert(!remorse::canMoveCollisionBody(actor, {260, 100, 0}, {wall})); + assert(!remorse::canMoveCollisionBody(actor, {400, 100, 0}, {wall})); + + const remorse::CollisionBody floorBelow{{300, 100, -20}, 64, 96, 20}; + const remorse::CollisionBody overhead{{300, 100, 80}, 64, 96, 32}; + assert(!remorse::collisionBodiesOverlap(actor, floorBelow)); + assert(!remorse::collisionBodiesOverlap(actor, overhead)); + + const remorse::CollisionBody initiallyOverlapping{{250, 100, 0}, 96, 96, 80}; + assert(remorse::canMoveCollisionBody(initiallyOverlapping, {200, 100, 0}, {wall})); + assert(!remorse::canMoveCollisionBody(initiallyOverlapping, {400, 100, 0}, {wall})); + + remorse::ShapeTypeInfo actorInfo; + actorInfo.x = 3; + actorInfo.y = 3; + actorInfo.z = 10; + actorInfo.flags = 0x2; + const remorse::CollisionBody authoredActor = remorse::makeCollisionBody({100, 100, 0}, actorInfo); + assert(authoredActor.extentX == 96); + assert(authoredActor.extentY == 96); + assert(authoredActor.extentZ == 80); + + remorse::ShapeTypeInfo obstacleInfo; + obstacleInfo.x = 2; + obstacleInfo.y = 4; + obstacleInfo.z = 8; + const remorse::CollisionBody flipped = remorse::makeCollisionBody({300, 300, 0}, obstacleInfo, true); + assert(flipped.extentX == 128); + assert(flipped.extentY == 64); + + remorse::FixedMap map; + remorse::FixedMapEntry solid; + solid.x = 500; + solid.y = 600; + solid.shape = 1; + map.entries.push_back(solid); + remorse::FixedMapEntry globParent; + globParent.x = 0x480; + globParent.y = 0x640; + globParent.shape = 2; + globParent.quality = 7; + map.entries.push_back(globParent); + + std::vector shapeTypes(4); + shapeTypes[1] = obstacleInfo; + shapeTypes[1].flags = 0x2; + shapeTypes[2].family = 3; + shapeTypes[2].flags = 0x2; + shapeTypes[3] = obstacleInfo; + shapeTypes[3].flags = 0x2; + + remorse::GlobObject glob; + glob.index = 7; + glob.entries.push_back(remorse::GlobObjectEntry{2, 3, 4, 3, 0}); + const auto bodies = remorse::collectMapCollisionBodies(map, shapeTypes, {glob}); + assert(bodies.size() == 2); + assert(bodies[0].location.x == 500 && bodies[0].location.y == 600); + assert(bodies[1].location.x == (0x480 & ~0x3ff) + 2 * 4 + 2); + assert(bodies[1].location.y == (0x640 & ~0x3ff) + 3 * 4 + 2); + assert(bodies[1].location.z == 4); + return 0; +} \ No newline at end of file diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index dbdd945..d844f3c 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -1,11 +1,30 @@ #include "remorse/entity_dispatch_entry.h" #include +#include +#include +#include int main() { remorse::EntityDispatchEntryBase entry{}; - remorse::EntityDispatchEntry::initBase(&entry); + remorse::u16 groupCounts[32]{}; + for (remorse::u8& byte : entry.bytes) { + byte = 0xa5; + } + assert(remorse::EntityDispatchEntry::initBase(&entry, 1, groupCounts) == &entry); + assert(entry.bytes[0x00] == 0x06 && entry.bytes[0x01] == 0x3b); + assert(entry.bytes[0x09] == 0xa5); + assert(entry.bytes[0x1e] == 0x10 && entry.bytes[0x1f] == 0x2d); + assert(entry.bytes[0x28] == 0xfe && entry.bytes[0x29] == 0x3a); + for (remorse::u16 offset : {remorse::u16{0x02}, remorse::u16{0x04}, remorse::u16{0x0a}, remorse::u16{0x12}, remorse::u16{0x16}, remorse::u16{0x1a}, remorse::u16{0x20}, remorse::u16{0x26}, remorse::u16{0x2a}, remorse::u16{0x30}}) { + assert(entry.bytes[offset] == 0 && entry.bytes[offset + 1] == 0); + } + assert(entry.bytes[0x06] == 1 && entry.bytes[0x07] == 0); + assert(entry.bytes[0x08] == 1 && groupCounts[1] == 1); + assert(entry.bytes[0x18] == 1 && entry.bytes[0x19] == 0); + assert(remorse::EntityDispatchEntry::initBase(nullptr, 1, groupCounts) == nullptr); + assert(groupCounts[1] == 1); remorse::EntityDispatchEntry::setSourceType(entry, 0x1234); assert(entry.bytes[0x04] == 0x34); @@ -15,12 +34,446 @@ int main() assert(entry.bytes[0x06] == 0xf2); assert(entry.bytes[0x07] == 0x00); - entry.bytes[0x08] = 0xe0; - remorse::EntityDispatchEntry::setGroupId(entry, 0x23); - assert(entry.bytes[0x08] == 0xe3); + remorse::EntityDispatchEntry::sleep(entry, 0x12345678, 0x0001003c); + assert(entry.bytes[0x18] == 0x01 && entry.bytes[0x19] == 0x10); + assert(entry.bytes[0x0a] == 0x78 && entry.bytes[0x0b] == 0x56); + assert(entry.bytes[0x0c] == 0x34 && entry.bytes[0x0d] == 0x12); + assert(entry.bytes[0x0e] == 0x3c && entry.bytes[0x0f] == 0x00); + assert(entry.bytes[0x10] == 0x01 && entry.bytes[0x11] == 0x00); + + remorse::EntityDispatchEntry::setGroupId(entry, 3, groupCounts); + assert(groupCounts[1] == 0 && groupCounts[3] == 1); + entry.bytes[0x08] = 0xe3; + remorse::EntityDispatchEntry::setGroupId(entry, 3, groupCounts); + assert(entry.bytes[0x08] == 0xe3 && groupCounts[3] == 1); + + remorse::EntityDispatchEntry::setGroupId(entry, 3, groupCounts); + assert(groupCounts[3] == 1); + + remorse::EntityDispatchEntry::setGroupId(entry, 4, groupCounts); + assert(entry.bytes[0x08] == 4 && groupCounts[3] == 0 && groupCounts[4] == 1); + + for (remorse::u8 invalidId : {remorse::u8{0}, remorse::u8{32}}) { + bool rejected = false; + try { + remorse::EntityDispatchEntry::setGroupId(entry, invalidId, groupCounts); + } catch (const std::invalid_argument&) { + rejected = true; + } + assert(rejected && entry.bytes[0x08] == 4 && groupCounts[4] == 1); + } remorse::EntityDispatchEntry::incrementGroupId(entry); - assert(entry.bytes[0x08] == 0xe4); + assert(entry.bytes[0x08] == 5); + + remorse::ProcessKernel kernel; + kernel.setLastAllocationSize(sizeof(entry)); + assert(kernel.addProcess(entry) == 0); + assert(entry.bytes[0x02] == 0 && entry.bytes[0x03] == 0); + assert(kernel.processAt(0) == &entry); + assert(kernel.allocationSizeAt(0) == 0x32); + assert(kernel.processCount() == 1 && kernel.capacity() == 30); + assert(std::strcmp(kernel.processNameAt(0), "Default") == 0); + remorse::EntityDispatchEntryBase second{}; + kernel.setMarkNewProcesses(true); + assert(kernel.addProcess(second) == 1); + assert(second.bytes[0x02] == 1 && second.bytes[0x03] == 0); + assert(kernel.allocationSizeAt(1) == 0); + assert(second.bytes[0x19] == 0x02 && kernel.newlyCreatedCount() == 1); + kernel.setMarkNewProcesses(false); + kernel.clearProcessSlot(1); + assert(kernel.processAt(1) == nullptr && kernel.allocationSizeAt(1) == 0); + assert(kernel.processNameAt(1) == nullptr && kernel.processCount() == 2); + remorse::EntityDispatchEntryBase reused{}; + assert(kernel.addProcess(reused) == 1 && kernel.processAt(1) == &reused); + std::vector additional(29); + for (auto& process : additional) { + kernel.addProcess(process); + } + assert(kernel.processAt(30) == &additional.back()); + assert(kernel.capacity() == 60 && kernel.processCount() == 32); + + remorse::ProcessKernel createdKernel; + remorse::u16 createdGroups[32]{}; + auto* created = createdKernel.createProcess(2, createdGroups); + assert(created != nullptr && createdKernel.processAt(0) == created); + assert(createdKernel.processCount() == 1 && createdKernel.allocationSizeAt(0) == 0x32); + assert(created->bytes[0x02] == 0 && created->bytes[0x03] == 0); + assert(created->bytes[0x08] == 2 && createdGroups[2] == 1); + createdKernel.setSyncContext(true, 1); + auto* next = createdKernel.createProcess(2, createdGroups); + assert(createdKernel.processAt(1) == next && createdGroups[2] == 2); + assert(next->bytes[0x02] == 1 && next->bytes[0x03] == 0); + assert(next->bytes[0x16] == 0); + createdKernel.setSyncContext(true, 0); + auto* syncing = createdKernel.createProcess(2, createdGroups); + assert(createdKernel.processAt(2) == syncing && createdGroups[2] == 3); + assert(syncing->bytes[0x16] == 0x40 && syncing->bytes[0x17] == 0); + + createdKernel.setSyncContext(true, 1); + next->bytes[0x18] |= 0x02; + auto* retiring = createdKernel.createProcess(2, createdGroups); + assert(createdKernel.processAt(3) == retiring && createdKernel.processCount() == 4); + assert(next->bytes[0x18] == 0x07 && retiring->bytes[0x16] == 0x40); + createdKernel.terminateProcess(3, createdGroups); + assert(createdKernel.processAt(3) == retiring && (retiring->bytes[0x16] & 0x08) != 0); + assert(createdKernel.processCount() == 3 && createdKernel.terminatedProcessCount() == 1); + assert(createdGroups[2] == 3); + bool alreadyTerminated = false; + try { + createdKernel.terminateProcess(3, createdGroups); + } catch (const std::logic_error&) { + alreadyTerminated = true; + } + assert(alreadyTerminated && createdGroups[2] == 3 && createdKernel.terminatedProcessCount() == 1); + createdKernel.setSyncContext(true, 3); + auto* afterTerminated = createdKernel.createProcess(2, createdGroups); + assert((retiring->bytes[0x18] & 0x04) == 0 && (afterTerminated->bytes[0x16] & 0x40) != 0); + createdKernel.terminateProcess(4, createdGroups); + createdKernel.clearTerminatedProcesses(); + assert(createdKernel.processAt(3) == nullptr && createdKernel.allocationSizeAt(3) == 0); + assert(createdKernel.processNameAt(3) == nullptr && createdKernel.terminatedProcessCount() == 0); + auto* recycled = createdKernel.createProcess(2, createdGroups); + assert(createdKernel.processAt(3) == recycled && recycled->bytes[0x02] == 3); + assert(createdKernel.processCount() == 4 && createdGroups[2] == 4); + + auto* immediate = createdKernel.createProcess(2, createdGroups); + immediate->bytes[0x18] |= 0x04; + createdKernel.terminateProcess(4, createdGroups); + assert(createdKernel.processAt(4) == nullptr && createdKernel.processCount() == 4); + assert(createdKernel.terminatedProcessCount() == 0 && createdGroups[2] == 4); + + remorse::ProcessKernel fullKernel; + std::vector fullTable(1020); + for (auto& process : fullTable) { + fullKernel.addProcess(process); + } + remorse::u16 fullGroups[32]{}; + bool exhausted = false; + try { + fullKernel.createProcess(2, fullGroups); + } catch (const std::overflow_error&) { + exhausted = true; + } + assert(exhausted && fullKernel.processCount() == 1020 && fullGroups[2] == 0); + exhausted = false; + try { + fullKernel.createKeyboardProcess(2, fullGroups); + } catch (const std::overflow_error&) { + exhausted = true; + } + assert(exhausted && fullKernel.processCount() == 1020 && fullGroups[2] == 0); + exhausted = false; + try { + fullKernel.createSystemTimerProcess(2, fullGroups); + } catch (const std::overflow_error&) { + exhausted = true; + } + assert(exhausted && fullKernel.processCount() == 1020 && fullGroups[2] == 0); + + remorse::ProcessKernel scheduler; + remorse::u16 scheduledGroups[32]{}; + auto* otherGroup = scheduler.createProcess(1, scheduledGroups); + auto* matching = scheduler.createProcess(2, scheduledGroups); + auto* syncingProcess = scheduler.createProcess(2, scheduledGroups); + auto* specialGroup = scheduler.createProcess(30, scheduledGroups); + syncingProcess->bytes[0x16] = 0x40; + std::vector ran; + auto recordRun = [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& ids = *static_cast*>(context); + ids.push_back(static_cast(process.bytes[0x02] | process.bytes[0x03] << 8)); + }; + scheduler.scanRunnableProcesses(2, recordRun, &ran); + assert((ran == std::vector{1, 3})); + assert(syncingProcess->bytes[0x16] == 0 && otherGroup->bytes[0x16] == 0); + ran.clear(); + matching->bytes[0x16] = 1; + scheduler.scanRunnableProcesses(2, recordRun, &ran); + assert((ran == std::vector{2, 3})); + assert(specialGroup->bytes[0x08] == 30); + + remorse::ProcessKernel spawningKernel; + remorse::u16 spawningGroups[32]{}; + spawningKernel.createProcess(1, spawningGroups); + auto* spawningProcess = spawningKernel.createProcess(2, spawningGroups); + spawningProcess->bytes[0x18] |= 0x02; + struct SpawnContext { + remorse::ProcessKernel* kernel; + remorse::u16 (*groups)[32]; + remorse::EntityDispatchEntryBase* spawned = nullptr; + int runs = 0; + } spawnContext{&spawningKernel, &spawningGroups}; + auto spawnRun = [](remorse::EntityDispatchEntryBase&, void* context) { + auto& state = *static_cast(context); + ++state.runs; + if (state.spawned == nullptr) { + state.spawned = state.kernel->createProcess(2, *state.groups); + } + }; + spawningKernel.scanRunnableProcesses(2, spawnRun, &spawnContext); + assert(spawnContext.runs == 1 && spawnContext.spawned == spawningKernel.processAt(2)); + assert(spawningProcess->bytes[0x18] == 0x07 && spawnContext.spawned->bytes[0x16] == 0); + + remorse::ProcessKernel retiringKernel; + remorse::u16 retiringGroups[32]{}; + for (int index = 0; index < 3; ++index) { + retiringKernel.createProcess(1, retiringGroups); + } + retiringKernel.createProcess(2, retiringGroups); + struct RetireContext { + remorse::ProcessKernel* kernel; + remorse::u16 (*groups)[32]; + } retireContext{&retiringKernel, &retiringGroups}; + auto retireRun = [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& state = *static_cast(context); + state.kernel->terminateProcess(static_cast(process.bytes[0x02]), *state.groups); + }; + retiringKernel.scanRunnableProcesses(2, retireRun, &retireContext); + assert(retiringKernel.processAt(3) == nullptr && retiringKernel.terminatedProcessCount() == 0); + assert(retiringKernel.processCount() == 3 && retiringGroups[2] == 0); + + remorse::ProcessKernel sleepingKernel; + remorse::u16 sleepingGroups[32]{}; + auto* sleeper = sleepingKernel.createProcess(2, sleepingGroups); + remorse::EntityDispatchEntry::sleep(*sleeper, 100, 60); + ran.clear(); + sleepingKernel.scanRunnableProcesses(2, recordRun, &ran, 160); + assert(ran.empty() && sleeper->bytes[0x19] == 0x10); + sleepingKernel.scanRunnableProcesses(2, recordRun, &ran, 161); + assert((ran == std::vector{0})); + assert(sleeper->bytes[0x19] == 0); + for (remorse::u16 offset = 0x0a; offset < 0x12; ++offset) { + assert(sleeper->bytes[offset] == 0); + } + + remorse::ProcessKernel standKernel; + remorse::u16 standGroups[32]{}; + standKernel.createProcess(2, standGroups); + assert(!standKernel.itemHasProcess(0x1234) && !standKernel.itemHasProcess(0x1235)); + auto* standEntry = standKernel.createStandProcess(2, 0x1234, standGroups); + auto* standing = &standEntry->base; + assert(standKernel.processAt(1) == standing && standKernel.allocationSizeAt(1) == 0x42); + assert(std::strcmp(standKernel.processNameAt(1), "Stand") == 0 && standGroups[2] == 2); + assert(standing->bytes[0] == 0x0f && standing->bytes[1] == 0x1f); + assert(standing->bytes[0x04] == 0x34 && standing->bytes[0x05] == 0x12); + assert(standing->bytes[0x06] == 0x58 && standing->bytes[0x07] == 0x02); + assert(standing->bytes[0x17] == 0x03 && standEntry->extra[0] == 0x01 && standEntry->extra[1] == 0x01); + assert(standEntry->extra[0x0e] == 0x34 && standEntry->extra[0x0f] == 0x12); + assert(standKernel.itemHasProcess(0x1234) && !standKernel.itemHasProcess(0x1235)); + bool itemTeardownRejected = false; + try { + standKernel.terminateProcess(1, standGroups); + } catch (const std::logic_error&) { + itemTeardownRejected = true; + } + assert(itemTeardownRejected && standGroups[2] == 2 && standKernel.processAt(1) == standing); + struct StandContext { + remorse::u32 tick; + bool visible; + remorse::u16 activity = 0; + bool currentActivity = false; + bool canSee = false; + remorse::u16 startedNpc = 0; + remorse::u16 startedActivity = 0; + int starts = 0; + int runs = 0; + remorse::StandProcessEntry* entry = nullptr; + remorse::NpcBehaviorServices* services = nullptr; + } standContext{99, false}; + remorse::NpcBehaviorServices standServices{ + [](remorse::u16 npcNumber, void* context) { + assert(npcNumber == 0x1234); + return static_cast(context)->visible; + }, + [](remorse::u16 npcNumber, void* context) { + assert(npcNumber == 0x1234); + return static_cast(context)->activity; + }, + [](remorse::u16 npcNumber, remorse::u16 activity, void* context) { + assert(npcNumber == 0x1234 && activity == 0x71); + return static_cast(context)->currentActivity; + }, + [](remorse::u16 npcNumber, void* context) { + assert(npcNumber == 0x1234); + return static_cast(context)->canSee; + }, + [](remorse::u16 npcNumber, remorse::u16 activity, void* context) { + auto& state = *static_cast(context); + state.startedNpc = npcNumber; + state.startedActivity = activity; + ++state.starts; + }, + &standContext + }; + standContext.entry = standEntry; + standContext.services = &standServices; + auto standRun = [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& state = *static_cast(context); + if (process.bytes[0] != 0x0f || process.bytes[1] != 0x1f) { + return; + } + ++state.runs; + remorse::StandProcess::run(*state.entry, *state.services, state.tick); + }; + standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick); + assert(standContext.runs == 1 && standing->bytes[0x19] == 0x10); + assert(standing->bytes[0x0a] == 99 && standing->bytes[0x0e] == 60); + assert(standContext.starts == 0); + standContext.tick = 159; + standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick); + assert(standContext.runs == 1 && standing->bytes[0x19] == 0x10); + standContext.tick = 160; + standContext.visible = true; + standContext.activity = 0x71; + standContext.canSee = true; + standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick); + assert(standContext.runs == 2 && standing->bytes[0x19] == 0 && standing->bytes[0x0e] == 0); + assert(standContext.starts == 1 && standContext.startedNpc == 0x1234 && standContext.startedActivity == 0x71); + standContext.tick = 161; + standContext.currentActivity = true; + standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick); + assert(standContext.runs == 3 && standContext.starts == 1 && standing->bytes[0x0e] == 60); + + remorse::ProcessKernel itemKernel; + remorse::u16 itemGroups[32]{}; + for (int index = 0; index < 3; ++index) { + itemKernel.createProcess(1, itemGroups); + } + auto* firstStand = itemKernel.createStandProcess(2, 0x1234, itemGroups); + auto* secondStand = itemKernel.createStandProcess(2, 0x1234, itemGroups); + auto* otherStand = itemKernel.createStandProcess(2, 0x1235, itemGroups); + assert(itemKernel.itemHasProcess(0x1234) && itemKernel.itemHasProcess(0x1235)); + itemKernel.terminateProcess(3, itemGroups); + assert(itemKernel.itemHasProcess(0x1234) && itemKernel.processAt(3) == &firstStand->base); + itemKernel.clearTerminatedProcesses(); + assert(itemKernel.processAt(3) == nullptr && itemKernel.itemHasProcess(0x1234)); + secondStand->base.bytes[0x18] |= 0x04; + itemKernel.terminateProcess(4, itemGroups); + assert(itemKernel.processAt(4) == nullptr && !itemKernel.itemHasProcess(0x1234)); + assert(itemKernel.itemHasProcess(0x1235) && itemKernel.processAt(5) == &otherStand->base); + assert(itemGroups[2] == 1 && itemKernel.processCount() == 4); + + remorse::SystemTimerProcessEntry systemTimer{}; + systemTimer.extra[0x0e] = 0xff; + systemTimer.extra[0x0f] = 0xff; + assert(remorse::SystemTimerProcess::tick(systemTimer) == 0xffff); + remorse::SystemTimerProcess::increment(systemTimer); + assert(remorse::SystemTimerProcess::tick(systemTimer) == 0x10000); + assert(systemTimer.extra[0x0e] == 0 && systemTimer.extra[0x0f] == 0); + assert(systemTimer.extra[0x10] == 1 && systemTimer.extra[0x11] == 0); + + remorse::ProcessKernel timerKernel; + remorse::u16 timerGroups[32]{}; + bool missingTimerRejected = false; + try { + timerKernel.deliverSystemTimerEvent(); + } catch (const std::logic_error&) { + missingTimerRejected = true; + } + assert(missingTimerRejected); + for (int index = 0; index < 3; ++index) { + timerKernel.createProcess(1, timerGroups); + } + auto* registeredTimer = timerKernel.createSystemTimerProcess(1, timerGroups); + assert(timerKernel.processAt(3) == ®isteredTimer->base); + assert(timerKernel.allocationSizeAt(3) == 0x4a && timerGroups[1] == 4); + assert(std::strcmp(timerKernel.processNameAt(3), "SystemTimer") == 0); + assert(registeredTimer->base.bytes[0x16] == 3 && registeredTimer->base.bytes[0x17] == 0x27); + assert(registeredTimer->base.bytes[0x18] == 1 && registeredTimer->extra[0] == 2); + assert(registeredTimer->extra[4] == 0x3c && timerKernel.systemTimerTick() == 0); + registeredTimer->base.bytes[0x17] &= static_cast(~0x04); + bool registrationRejected = false; + try { + timerKernel.deliverSystemTimerEvent(); + } catch (const std::logic_error&) { + registrationRejected = true; + } + assert(registrationRejected && timerKernel.systemTimerTick() == 0); + registeredTimer->base.bytes[0x17] |= 0x04; + bool duplicateTimerRejected = false; + try { + timerKernel.createSystemTimerProcess(1, timerGroups); + } catch (const std::logic_error&) { + duplicateTimerRejected = true; + } + assert(duplicateTimerRejected && timerGroups[1] == 4); + bool timerTeardownRejected = false; + try { + timerKernel.terminateProcess(3, timerGroups); + } catch (const std::logic_error&) { + timerTeardownRejected = true; + } + assert(timerTeardownRejected && timerGroups[1] == 4); + auto* timedStand = timerKernel.createStandProcess(1, 7, timerGroups); + remorse::EntityDispatchEntry::sleep(timedStand->base, timerKernel.systemTimerTick(), 60); + for (int tick = 0; tick < 60; ++tick) { + timerKernel.deliverSystemTimerEvent(); + } + ran.clear(); + timerKernel.scanRunnableProcesses(1, recordRun, &ran, timerKernel.systemTimerTick()); + assert(ran.size() == 3 && timedStand->base.bytes[0x19] == 0x10); + timerKernel.deliverSystemTimerEvent(); + ran.clear(); + timerKernel.scanRunnableProcesses(1, recordRun, &ran, timerKernel.systemTimerTick()); + assert((ran == std::vector{0, 1, 2, 4})); + assert(timedStand->base.bytes[0x19] == 0 && timerKernel.systemTimerTick() == 61); + + auto* keyboard = timerKernel.createKeyboardProcess(1, timerGroups); + assert(timerKernel.processAt(5) == &keyboard->base && timerKernel.allocationSizeAt(5) == 0x36); + assert(std::strcmp(timerKernel.processNameAt(5), "KeyboardProcess") == 0); + assert(keyboard->base.bytes[0x16] == 3 && keyboard->base.bytes[0x17] == 1); + assert(keyboard->base.bytes[0x18] == 0x81 && keyboard->base.bytes[0x19] == 1); + assert(keyboard->extra[0] == 0 && keyboard->extra[3] == 0 && timerGroups[1] == 6); + bool duplicateKeyboardRejected = false; + try { + timerKernel.createKeyboardProcess(1, timerGroups); + } catch (const std::logic_error&) { + duplicateKeyboardRejected = true; + } + assert(duplicateKeyboardRejected && timerGroups[1] == 6); + bool keyboardTeardownRejected = false; + try { + timerKernel.terminateProcess(5, timerGroups); + } catch (const std::logic_error&) { + keyboardTeardownRejected = true; + } + assert(keyboardTeardownRejected && timerGroups[1] == 6); + + auto* keyDaemon = timerKernel.createKeyDaemonProcess(1, timerGroups); + assert(timerKernel.processAt(6) == &keyDaemon->base && timerKernel.allocationSizeAt(6) == 0x40); + assert(std::strcmp(timerKernel.processNameAt(6), "KeyDaemon") == 0); + assert(keyDaemon->base.bytes[0x16] == 3 && keyDaemon->base.bytes[0x17] == 0x27); + assert(keyDaemon->extra[0] == 2 && keyDaemon->extra[4] == 0x2d && timerGroups[1] == 7); + bool duplicateDaemonRejected = false; + try { + timerKernel.createKeyDaemonProcess(1, timerGroups); + } catch (const std::logic_error&) { + duplicateDaemonRejected = true; + } + assert(duplicateDaemonRejected && timerGroups[1] == 7); + bool daemonTeardownRejected = false; + try { + timerKernel.terminateProcess(6, timerGroups); + } catch (const std::logic_error&) { + daemonTeardownRejected = true; + } + assert(daemonTeardownRejected && timerGroups[1] == 7); + + remorse::KeyEvent keyboardEvent{0x41, 0x1e, 1, 2, 3, 1, 4, 5}; + const remorse::KeyEvent lastEvent{0x42, 0x30, 6, 7, 8, 9, 10, 11}; + keyboard->extra[0] = 0x31; + assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x11, 0, keyboardEvent, lastEvent)); + assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 1, keyboardEvent, lastEvent)); + assert(keyboardEvent.character == 0x41 && keyboard->extra[0] == 0x31); + keyboardEvent.field8 = 0; + assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent)); + keyboardEvent.field8 = 1; + keyboardEvent.character = 0; + assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent)); + keyboardEvent.character = 0x41; + assert(remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent)); + assert(std::memcmp(&keyboardEvent, &lastEvent, sizeof(keyboardEvent)) == 0); + assert(keyboard->extra[0] == 0x21); return 0; } diff --git a/rebuild/remorse/tests/file_system_tests.cpp b/rebuild/remorse/tests/file_system_tests.cpp index 4e9dc6f..86d6735 100644 --- a/rebuild/remorse/tests/file_system_tests.cpp +++ b/rebuild/remorse/tests/file_system_tests.cpp @@ -1,10 +1,98 @@ #include "remorse/file_system.h" +#include "remorse/runtime.h" #include +#include +#include +#include #include +#include +#include -int main() +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#ifdef _DEBUG +#include +#endif +#endif + +int main(int argc, char** argv) { +#ifdef _WIN32 + if (argc == 2 && std::strcmp(argv[1], "--crash-probe") == 0) { + remorse::installCrashDiagnostics(); + try { + throw std::runtime_error("diagnostic probe"); + } catch (...) { + std::terminate(); + } + } +#ifdef _DEBUG + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_WNDW); + _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW); +#endif + remorse::installCrashDiagnostics(); + assert((GetErrorMode() & SEM_NOGPFAULTERRORBOX) != 0); +#ifdef _DEBUG + assert((_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_REPORT_MODE) & _CRTDBG_MODE_WNDW) == 0); + assert((_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_REPORT_MODE) & _CRTDBG_MODE_DEBUG) != 0); + assert((_CrtSetReportMode(_CRT_ERROR, _CRTDBG_REPORT_MODE) & _CRTDBG_MODE_WNDW) == 0); +#endif + + wchar_t executable[MAX_PATH]{}; + if (GetModuleFileNameW(nullptr, executable, MAX_PATH) == 0) { + return 1; + } + std::wstring commandLine = L"\"" + std::wstring(executable) + L"\" --crash-probe"; + SECURITY_ATTRIBUTES pipeSecurity{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE}; + HANDLE readPipe = nullptr; + HANDLE writePipe = nullptr; + if (!CreatePipe(&readPipe, &writePipe, &pipeSecurity, 0)) { + return 1; + } + if (!SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0)) { + CloseHandle(readPipe); + CloseHandle(writePipe); + return 1; + } + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + startup.dwFlags = STARTF_USESTDHANDLES; + startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + startup.hStdOutput = writePipe; + startup.hStdError = writePipe; + PROCESS_INFORMATION child{}; + if (!CreateProcessW(nullptr, commandLine.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW, + nullptr, nullptr, &startup, &child)) { + CloseHandle(readPipe); + CloseHandle(writePipe); + return 1; + } + CloseHandle(writePipe); + const DWORD waitResult = WaitForSingleObject(child.hProcess, 5000); + if (waitResult == WAIT_TIMEOUT) { + TerminateProcess(child.hProcess, 2); + WaitForSingleObject(child.hProcess, INFINITE); + } + char buffer[512]; + DWORD count = 0; + std::string crashOutput; + while (ReadFile(readPipe, buffer, sizeof(buffer), &count, nullptr) && count != 0) { + crashOutput.append(buffer, count); + } + DWORD exitCode = 0; + const BOOL gotExitCode = GetExitCodeProcess(child.hProcess, &exitCode); + CloseHandle(readPipe); + CloseHandle(child.hThread); + CloseHandle(child.hProcess); + if (!gotExitCode || waitResult != WAIT_OBJECT_0 || exitCode != 1 || + crashOutput.find("Unhandled C++ exception: diagnostic probe") == std::string::npos) { + std::fprintf(stderr, "Crash probe wait=%lu exit=0x%08lX output=%s\n", + waitResult, exitCode, crashOutput.c_str()); + return 1; + } +#endif const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); assert(root.has_value()); assert(root->hasExecutable); diff --git a/rebuild/remorse/tests/isometric_controls_tests.cpp b/rebuild/remorse/tests/isometric_controls_tests.cpp new file mode 100644 index 0000000..92f12d6 --- /dev/null +++ b/rebuild/remorse/tests/isometric_controls_tests.cpp @@ -0,0 +1,54 @@ +#include "remorse/isometric_controls.h" +#include "remorse/map_renderer.h" + +#include + +int main() +{ + assert(remorse::controllerWalkRequested(0)); + assert(!remorse::controllerWalkRequested(0x01)); + assert(!remorse::controllerWalkRequested(0x02)); + assert(!remorse::controllerWalkRequested(0x40)); + assert(remorse::controllerWalkRequested(0x41)); + assert(remorse::controllerWalkRequested(0x42)); + constexpr remorse::s32 originX = 1024; + constexpr remorse::s32 originY = 2048; + const remorse::ScreenPoint origin = remorse::projectToScreen({originX, originY, 0}); + + const auto east = remorse::worldPositionAtScreenOffset(originX, originY, 1.0, 0.0); + const remorse::ScreenPoint eastProjection = remorse::projectToScreen({ + static_cast(east.x), static_cast(east.y), 0}); + assert(eastProjection.x - origin.x == 1); + assert(eastProjection.y - origin.y == 0); + + const auto north = remorse::worldPositionAtScreenOffset(originX, originY, 0.0, -1.0); + const remorse::ScreenPoint northProjection = remorse::projectToScreen({ + static_cast(north.x), static_cast(north.y), 0}); + assert(northProjection.x - origin.x == 0); + assert(northProjection.y - origin.y == -1); + + const auto west = remorse::worldPositionAtScreenOffset(originX, originY, -1.0, 0.0); + const remorse::ScreenPoint westProjection = remorse::projectToScreen({ + static_cast(west.x), static_cast(west.y), 0}); + assert(westProjection.x - origin.x == -1); + assert(westProjection.y - origin.y == 0); + + const auto south = remorse::worldPositionAtScreenOffset(originX, originY, 0.0, 1.0); + const remorse::ScreenPoint southProjection = remorse::projectToScreen({ + static_cast(south.x), static_cast(south.y), 0}); + assert(southProjection.x - origin.x == 0); + assert(southProjection.y - origin.y == 1); + remorse::AnimationFrameMetadata forwardFrame{}; + forwardFrame.bytes[4] = 6; + const auto forward = remorse::hostMovementStep(forwardFrame, 6, false); + assert(forward && forward->x > 0 && forward->y > 0); + remorse::AnimationFrameMetadata reverseFrame{}; + reverseFrame.bytes[4] = 0xfe; + reverseFrame.bytes[5] = 3; + const auto authoredReverse = remorse::decodeAnimationDisplacement(reverseFrame, 6, false); + const auto hostReverse = remorse::hostMovementStep(reverseFrame, 6, false); + assert(authoredReverse && authoredReverse->x < 0 && authoredReverse->y < 0); + assert(hostReverse && hostReverse->x == 0 && hostReverse->y == 0); + assert(hostReverse->z == authoredReverse->z && hostReverse->onGround == authoredReverse->onGround); + return 0; +} \ No newline at end of file diff --git a/rebuild/remorse/tests/map_renderer_tests.cpp b/rebuild/remorse/tests/map_renderer_tests.cpp index 79cdd3b..987e88d 100644 --- a/rebuild/remorse/tests/map_renderer_tests.cpp +++ b/rebuild/remorse/tests/map_renderer_tests.cpp @@ -1,6 +1,8 @@ #include "remorse/file_system.h" +#include "remorse/fixed_map.h" #include "remorse/map_renderer.h" +#include #include #include @@ -21,5 +23,33 @@ int main() assert(!image->pixels.empty()); assert(image->decodedItemCount > 0); assert(image->paintedItemCount > 0); + + const auto fixedPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "FIXED.DAT"); + assert(fixedPath.has_value()); + const auto archive = remorse::loadFixedMapArchive(*fixedPath); + assert(archive.has_value()); + const auto fixedMap = remorse::loadFixedMap(*archive, options.mapIndex); + assert(fixedMap.has_value()); + remorse::s32 minX = fixedMap->entries.front().x; + remorse::s32 minY = fixedMap->entries.front().y; + remorse::s32 maxX = minX; + remorse::s32 maxY = minY; + for (const remorse::FixedMapEntry& entry : fixedMap->entries) { + minX = std::min(minX, static_cast(entry.x)); + minY = std::min(minY, static_cast(entry.y)); + maxX = std::max(maxX, static_cast(entry.x)); + maxY = std::max(maxY, static_cast(entry.y)); + } + options.maxWidth = 1280; + options.maxHeight = 760; + options.viewCenter = remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0}; + const auto centeredImage = remorse::renderMapPreview(*root, options); + assert(centeredImage.has_value()); + assert(centeredImage->paintedItemCount > 0); + assert(centeredImage->width == options.maxWidth); + assert(centeredImage->height == options.maxHeight); + const remorse::ScreenPoint center = remorse::projectToScreen(*options.viewCenter); + assert(centeredImage->sourceLeft == center.x - static_cast(options.maxWidth / 2)); + assert(centeredImage->sourceTop == center.y - static_cast(options.maxHeight / 2)); return 0; } diff --git a/rebuild/remorse/tests/map_sorter_tests.cpp b/rebuild/remorse/tests/map_sorter_tests.cpp new file mode 100644 index 0000000..2c1e00c --- /dev/null +++ b/rebuild/remorse/tests/map_sorter_tests.cpp @@ -0,0 +1,70 @@ +#include "remorse/detail/map_sorter.h" + +#include +#include + +int main() +{ + remorse::detail::RenderSortItem elevated; + elevated.left = 0; + elevated.top = 0; + elevated.right = 64; + elevated.bottom = 64; + elevated.x = 0; + elevated.xLeft = -32; + elevated.y = 0; + elevated.yFar = -32; + elevated.z = 32; + elevated.zTop = 48; + elevated.sxLeft = -100; + elevated.sxRight = 100; + elevated.sxTop = -100; + elevated.syTop = -100; + elevated.sxBottom = 100; + elevated.syBottom = 100; + elevated.shape = 2; + + remorse::detail::RenderSortItem ground; + ground.left = 0; + ground.top = 0; + ground.right = 64; + ground.bottom = 64; + ground.x = 100; + ground.xLeft = 68; + ground.y = 100; + ground.yFar = 68; + ground.z = 0; + ground.zTop = 16; + ground.sxLeft = -100; + ground.sxRight = 100; + ground.sxTop = -100; + ground.syTop = -100; + ground.sxBottom = 100; + ground.syBottom = 100; + ground.shape = 1; + + const std::vector items{elevated, ground}; + const std::vector order = remorse::detail::resolveRenderOrder(items); + assert(order.size() == 2); + assert(order[0] == 1); + assert(order[1] == 0); + + remorse::detail::RenderSortItem animatedFlat = elevated; + animatedFlat.x = 64; + animatedFlat.xLeft = 64; + animatedFlat.y = 64; + animatedFlat.yFar = 64; + animatedFlat.z = 0; + animatedFlat.zTop = 0; + animatedFlat.flat = true; + animatedFlat.animated = true; + + remorse::detail::RenderSortItem staticFlat = animatedFlat; + staticFlat.animated = false; + const std::vector flatItems{animatedFlat, staticFlat}; + const std::vector flatOrder = remorse::detail::resolveRenderOrder(flatItems); + assert(flatOrder.size() == 2); + assert(flatOrder[0] == 1); + assert(flatOrder[1] == 0); + return 0; +} \ No newline at end of file From c346b0e1a7b48210832768c5c50702091db0b0db Mon Sep 17 00:00:00 2001 From: Maddo Date: Sat, 26 Sep 2026 15:36:11 +0200 Subject: [PATCH 03/14] Add comprehensive tests for entity dispatch, file system, fixed map, flex archive, isometric controls, and crash setup - Enhance `entity_dispatch_entry_tests.cpp` with additional assertions for event type checks, group ID increments, and error handling. - Refactor `file_system_tests.cpp` to streamline probe execution and enhance output validation. - Extend `fixed_map_tests.cpp` to cover retail map loading, item classification, and process creation scenarios. - Introduce new checks in `flex_archive_tests.cpp` for usecode loading and event handling, ensuring robust validation of game data. - Add tests in `isometric_controls_tests.cpp` for controller direction mapping based on scan codes. - Implement `test_crash_setup.cpp` to initialize crash diagnostics for improved error handling during tests. --- docs/remorse-windows-rebuild-roadmap.md | 63 ++++-- rebuild/remorse/CMakeLists.txt | 11 + .../include/remorse/entity_dispatch_entry.h | 27 ++- rebuild/remorse/include/remorse/fixed_map.h | 23 ++ .../include/remorse/isometric_controls.h | 16 ++ .../remorse/include/remorse/usecode_archive.h | 54 +++++ rebuild/remorse/src/entity_dispatch_entry.cpp | 204 +++++++++++++++++- rebuild/remorse/src/fixed_map.cpp | 108 ++++++++++ rebuild/remorse/src/main.cpp | 59 ++++- rebuild/remorse/src/usecode_archive.cpp | 109 ++++++++++ rebuild/remorse/src/windowed_game_main.cpp | 125 +++++++++-- .../tests/entity_dispatch_entry_tests.cpp | 168 ++++++++++++++- rebuild/remorse/tests/file_system_tests.cpp | 103 +++++---- rebuild/remorse/tests/fixed_map_tests.cpp | 123 +++++++++++ rebuild/remorse/tests/flex_archive_tests.cpp | 89 ++++++++ .../tests/isometric_controls_tests.cpp | 6 + rebuild/remorse/tests/test_crash_setup.cpp | 11 + 17 files changed, 1207 insertions(+), 92 deletions(-) create mode 100644 rebuild/remorse/include/remorse/usecode_archive.h create mode 100644 rebuild/remorse/src/usecode_archive.cpp create mode 100644 rebuild/remorse/tests/test_crash_setup.cpp diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index cd82591..75bc7f1 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -2,9 +2,9 @@ ## Purpose -This note records the current effort to turn the live Ghidra analysis and the exported C decompilation of `CRUSADER.EXE` into a source tree that can be recompiled and eventually run on Windows, including modern Windows. +This note records the current effort to turn the live Ghidra analysis and the exported C decompilation of `CRUSADER.EXE` into a source tree that can be recompiled and run on modern hosts. Windows is the current development and acceptance target, not the only intended platform: keep recovered game logic and data formats host-independent, isolate Win32 presentation and diagnostics behind replaceable platform boundaries, and plan a portable window/input/timing/audio host when the original runtime call chains require it. Other platforms are a future goal, not a claim of current support. -The deliverable is a functioning modern Windows game compiled from cleaned, traceable decompiled `CRUSADER.EXE` game code. Replace DOS/Phar Lap and hardware services at their call boundaries; retain and repair the original control flow, data structures, scheduler, rendering, input semantics, and gameplay logic wherever recoverable. This is a source port, not a clean-room engine reconstruction. Modding is a later goal, not an initial acceptance criterion. +The first deliverable is a functioning modern Windows game compiled from cleaned, traceable decompiled `CRUSADER.EXE` game code, with a path to multi-platform builds. Replace DOS/Phar Lap and hardware services at their call boundaries; retain and repair the original control flow, data structures, scheduler, rendering, input semantics, and gameplay logic wherever recoverable. This is a source port, not a clean-room engine reconstruction. Modding is a later goal, not an initial acceptance criterion. The exported files are evidence, not directly compilable game source. Keep them unchanged and move verified, subsystem-sized function bodies into the rebuild tree, recording each original address and any corrections to decompiler artifacts. Do not substitute a newly designed gameplay implementation for an unported function and call that function complete. @@ -50,7 +50,7 @@ Current scaffold files: - `rebuild/remorse/include/remorse/type_flags.h`: typed `TYPEFLAG.DAT` shape-family and flag decoder. - `rebuild/remorse/src/combat_tactics.cpp`: parses tactic names, four block offsets, and bytecode payloads from `COMBAT.DAT` entries. - `rebuild/remorse/src/collision.cpp`: builds conservative solid volumes from fixed-map records and expanded glob children, then sweeps the player footpad against them. -- `rebuild/remorse/src/entity_dispatch_entry.cpp`: partial source translation of process lifecycle, the `11d0:0255` scan, `Process_Sleep`/`Unlink`, the 0x42-byte Stand constructor fields, `StandProcess::Run` (`1100:0359`), and a kernel-owned SystemTimer constructor/counter (`11c0:0000/00f8`). The harness executes the NPC decision tree through host services and delivers timer events explicitly; real NPC data, timer interrupts/rescheduling, keyboard lane, and complete game tick remain unported. +- `rebuild/remorse/src/entity_dispatch_entry.cpp`: partial source translation of process lifecycle, the `11d0:0255` scan, `Process_Sleep`/`Unlink`, the 0x42-byte Stand constructor fields, `StandProcess::Run` (`1100:0359`), a kernel-owned SystemTimer constructor/counter (`11c0:0000/00f8`), and partial Keyboard/KeyDaemon registration. The harness executes the NPC decision tree through host services and delivers timer events explicitly; real NPC data, timer interrupts/rescheduling, original keyboard queue/player input, and complete game tick remain unported. - `rebuild/remorse/src/file_system.cpp`: repository/retail data-root discovery using modern `std::filesystem`. - `rebuild/remorse/src/flex_archive.cpp`: loader for count-at-`0x54`, table-at-`0x80` FLEX archives. - `rebuild/remorse/src/fixed_map.cpp`: loader for `FIXED.DAT` map tables and scaled fixed-map item coordinates. @@ -78,7 +78,7 @@ Current scaffold files: - `rebuild/remorse/tests/type_flags_tests.cpp`: checks `STATIC/TYPEFLAG.DAT` parses 2,048 shape records and includes glob-family records. - `rebuild/remorse/tools/import_export_slice.py`: stages one exported function folder into `rebuild/remorse/imported/` for manual cleanup review. -This is not the game yet. It is a buildable diagnostic host with a source-backed itemless process lifecycle, partial scheduler scan, owned Stand process layout, and recovered Stand `Run`/NPC decision and timer-counter branches. It does not have the original NPC service data, timer interrupt registration, or game loop. +This is not the game yet. It is a buildable diagnostic host with a source-backed itemless process lifecycle, partial scheduler scan/group selection, owned Stand process layout, and recovered Stand `Run`/NPC decision and timer-counter branches. It does not have the original NPC service data, DOS timer delivery, keyboard event queue, or game loop. ## Why The Export Does Not Compile Yet @@ -282,13 +282,15 @@ Exit criteria: a clean checkout/build can run against a retail data directory wi The current active work must shift from Phase 3 host presentation to decompiled source conversion and call-chain integration (Phases 0 and 4). Core Phase 2 loaders, the footpad-aware overlap sorter, and the Windows map window are diagnostic infrastructure. The actor uses retail stand/walk/run metadata, authored XYZ displacements, and the original 16-way direction table, but its 20 Hz host tick, conservative TYPEFLAG collision, and fixed-map boundary are not the recovered player process or original AreaSearch. Floor support, step-up/ledge handling, moving items, interactions, and USECODE remain unported. Keep the window as a test host, not as the implementation template for game logic. -First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a8` (older `0008:bca8`) validates 1..31, updates the group byte at `+0x08`, and adjusts 16-bit counters through the far table pointer at `DS:39c5`. Live disassembly confirms the entry far pointer at `[BP+6]`, group byte at `[BP+0xa]`, and word-sized counter operations; the decompiler's `_group_id` alias is not a real implicit argument. The host receives the entry and table explicitly. `InitBase` at `11e0:0000` stamps the function-table words `0x3b06` (`+0x00`), `0x2d10` (`+0x1e`), `0x3afe` (`+0x28`), initializes the observed scalars, and seeds the group through `SetGroupId`. The seed comes from `DS:39c9` (written by `Kernel_11d0_19b5`); the host receives it as explicit runtime state. The unknown `+0x09` is not deliberately written. The host-owned path performs allocate -> initialize -> register, records default name/new-process metadata, executes the conditional current-process extflag branch, and applies the post-registration sync predicate. Itemless termination and slot reclamation are present. The scheduler scan applies normal-process group/flag gates and timer wake logic at `11d0:0255`, and its callback invokes the compiled `StandProcess::Run` branch for the 0x42-byte host-owned Stand entry. The `1100:026e` NPC decision gates are compiled, with their item/visibility/activity operations passed through host services. Owned Stand entries now maintain the per-item presence bit; the kernel-owned timer and keyboard constructors register their diagnostic processes. This is **not** a complete constructor or process system: stack-segment assertion, nonempty item child teardown, NPC service implementations, DOS timer/keyboard event delivery, end-of-pass work, other process `Run` functions, and far-memory behavior remain absent. `IncrementGroupId`, `SetSourceType`, and `SetEventTypeChecked` remain stand-ins; runtime binary parity is not established. +First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a8` (older `0008:bca8`) validates 1..31, updates the group byte at `+0x08`, and adjusts 16-bit counters through the far table pointer at `DS:39c5`. Live disassembly confirms the entry far pointer at `[BP+6]`, group byte at `[BP+0xa]`, and word-sized counter operations; the decompiler's `_group_id` alias is not a real implicit argument. The host receives the entry and table explicitly. `InitBase` at `11e0:0000` stamps the function-table words `0x3b06` (`+0x00`), `0x2d10` (`+0x1e`), `0x3afe` (`+0x28`), initializes the observed scalars, and seeds the group through `SetGroupId`. The seed comes from `DS:39c9` (written by `Kernel_11d0_19b5`); the host receives it as explicit runtime state. The unknown `+0x09` is not deliberately written. The host-owned path performs allocate -> initialize -> register, records default name/new-process metadata, executes the conditional current-process extflag branch, and applies the post-registration sync predicate. Itemless termination and slot reclamation are present. The scheduler scan applies normal-process group/flag gates and timer wake logic at `11d0:0255`, and its callback invokes the compiled `StandProcess::Run` branch for the 0x42-byte host-owned Stand entry. The `1100:026e` NPC decision gates are compiled, with their item/visibility/activity operations passed through host services. Owned Stand entries now maintain the per-item presence bit; the kernel-owned timer and keyboard constructors register their diagnostic processes. This is **not** a complete constructor or process system: stack-segment assertion, nonempty item child teardown, NPC service implementations, DOS timer/keyboard event delivery, end-of-pass work, other process `Run` functions, and far-memory behavior remain absent. Kernel-owned source/type transitions and active-group increment now have focused coverage, but the static source/type setters still lack item-cache context; runtime binary parity is not established. ### Process Source-Port Ledger | Exported function | Compiled status | Evidence and remaining boundary | |---|---|---| | `SetGroupId@11e0_02a8.c` (`0008:bca8`) | Partial translation; invoked from host `InitBase`, CTest transitions and invalid IDs | Live `11e0:02ae-031b`: group byte parameter at `[BP+0xa]`, far entry pointer at `[BP+6]`, 2-byte counter stride via `DS:39c5`, overwrite entire `+0x08` byte when changing group. Host exception replaces `AssertError`; counter-table ownership and runtime trace still need verification. | +| `IncrementGroupId@11e0_0405.c` | Group increment, current-active-group assertion, and 29-to-30 rejection translated; harness and CTest invoke it | Live `11e0:040b-0466` masks the group byte to five bits, checks next group `< 30` and `DS:39c9 == old group`, then calls `SetGroupId` and `Kernel_11d0_19b5`. The host passes the owning kernel and group counts explicitly; assertions become exceptions, without a DOS runtime trace. | +| `SetSourceType@11e0_01b6.c`, `SetEventTypeChecked@11e0_0227.c` | Kernel-owned item source and event-type transitions compiled and exercised by the item-process constructor, CTest reassignment/teardown | Source change stamps `+0x04`, marks the new item's presence bit, refreshes the old bit by searching unterminated processes from slot 3, and moves the type bit when `+0x06` is `0xf0..0xf7`. Type change stamps `+0x06`, sets the new type bit and refreshes the old type; values above `0x0fff` assert after the write. Per-item presence bits (`DS:3a04`) and per-item process-type bytes (`DS:3a08`) are separate host-owned tables. Static setters without kernel context remain partial; other item-cache mutations and binary parity are unverified. | | `InitBase@11e0_0000.c` (`0008:ba00`) | Function-table/scalar/group-seed subset plus host-owned allocate/register path; harness-invoked, CTest offsets, counters, IDs | Live `11e0:0006-014e`: optional alloc `11e0:014f`, table words `0x3b06/0x2d10/0x3afe`, group from `DS:39c9`, then `SetGroupId`, `Kernel_AddProcess` (`11d0:0aff`), conditional `Kernel_GetSomeProcId_11d0_177c` branch, `Process_11d0_19cd`. Host updates extflags `+0x18 |= 4` on an addressable, unterminated current process with bit `2` set; it still omits stack-segment assertion and segmented-pointer relocation. | | `Kernel_GetNextFreeProcId` (`11d0:0a97`), `Kernel_11d0_0716` | First-free slot and 30-slot growth translated; registered in host harness and CTest | Live decompile scans far process-pointer slots, grows parallel pointer/size/name arrays by 30 up to 1020 entries. Host stores native pointers, sizes, and default names; the original far-address mapping is not implemented. `Process_GetProcById` (`11d0:0bf3`) treats ID 0 as null even though the raw slot allocator may choose it. | | `Kernel_AddProcess` (`11d0:0aff`) | Process pointer, ID, allocation-size, count, optional new-process flag/counter, default-name subset translated | Live disassembly stamps `procid` at `+0x02`, consumes `g_kernelLastProcessAllocSize`, increments count, optionally sets `ExtProc_NewlyCreated` (`0x200`), and names the slot `Default`. Host omits initialized-state assertion, far-pointer representation, and runtime parity. | @@ -296,15 +298,38 @@ First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a | `Kernel_TerminteProcessByPid` (`11d0:18a3`), `Process_SetTerminatedState` | Immediate and deferred termination translated for host-owned base and zero-child-state Stand entries | Live `11d0:18e5-1939`: decrement group count; if extflags `+0x18 & 4`, clear slot and free immediately; otherwise set flags `+0x16 & 8`, increment terminated count; decrement live process count in either case. Host refreshes the per-item bit after termination; child lists, special event callbacks, and teardown for non-owned entries remain unported. | | `Kernel_ClearProcessSomethingAndName` (`11d0:1972`), `Kernel_11d0_1dcc` | Slot pointer/size/name clear and deferred cleanup for IDs >= 3 translated; ID reuse exercised | Live cleanup scans from ID 3, requires `+0x1a == 0`, clears the slot, frees the entry, and decrements terminated count. The clear helper itself does not decrement live process count. Other scheduler cleanup paths and process destructor dispatch remain unported. | | `FUN_11d0_0255` (`11d0:0255`) | Normal-process scan and timer wake translated; harness callback invokes compiled Stand `Run`, tests cover sleep/wake and scheduler gates | Live `11d0:02b4-03ac`: skip terminated, process sleep via `11e0:0379`, clear `Proc_Syncing` for one pass, skip nonzero `+0x24/+0x26`, `Proc_Waiting`, and off-group entries unless daemon or group 30/31; set current ID around vtable run call. Host receives an explicit timer tick, uses the original strict `start+duration < tick` wake comparison, and recognizes Stand's verified no-op completion slot (`1100:0fe3`); other completion targets remain unsupported. Immediate timer/keyboard interrupts, early-stop/group advance/table-maintenance tails, and general vtable dispatch remain unported. | +| `Kernel_11d0_19b5` (`11d0:19b5`), `Kernel_11d0_0445` (`11d0:0445`) | Active-group writer and empty-group highest-ordinary-group selection translated; invoked after diagnostic scans in harness/window, CTest checks change flag and groups 30/31 exclusion | Exported globals initialize active group `DS:39c9` to 1 and pending byte `DS:39a2` to 0. Writer marks pending only when group changes; selector scans all occupied process slots (including terminated entries until cleanup), ignores groups 30/31 for the maximum, then clears pending. Host rejects invalid group IDs and uses explicit group counters; original group-table allocation, mid-scan early stop, and runtime traces remain unported. | +| `Item_CreateProcess` (`10a0:0020`), `ItemProcess_Run` (`10a0:0078`), `Item_Release` (`10a0:2a06`) | Owned 0x32-byte item process constructed and advanced by the scheduler from a staged retail map record; release-request/termination/presence cleanup checked over two ticks, harness/window invoke the same path | Live disassembly confirms function-table root `0x102f`, item number at `+0x04`, event type `0xf1` at `+0x06`, then `Item_Release` followed unconditionally by the vtable terminate slot. The compiled release boundary now passes mask `0x200` and `UC_Release` ordinal `9` to the host callback, both asserted by CTest. It still does not execute the USECODE event. Instance is a diagnostic, not an original `Item_Grab` trigger; original item process child teardown and general vtable dispatch remain unported. | +| `Item_GetUsecodeClassId` (`1420:0dc5`), `Usecode_ItemCallEvent` (`1420:0e3a`) | Class selection and owner-row event-mask gate translated into `remorse_core`; retail and synthetic CTest checks, harness and window release-request lookup | The item selector chooses regular shape, NPC number plus startup NPC base `0x800` (unless status bit 1), or unknown-egg quality plus startup base `0x900`. FLEX entry 1 supplies 13-byte owner rows (size callback `1220:01bb`, materialization callback `1240:02a8`). The window retains TYPEFLAG families and EUSECODE data to check release eligibility and report body availability, without creating a VM context or executing the body. Classless map items are normal; the first staged map-1 item (shape 16) has no matching class. | | `Process_Sleep` (`11e0:0320`), `EntityDispatchEntry::Unlink` (`11e0:0353`) | Flag and 32-bit timer writes/clear translated; exact byte offsets and wake deadline tested | Live sleep ORs `0x1000` at `+0x18`, snapshots timer into `+0x0a/+0x0c`, writes duration to `+0x0e/+0x10`; unlink clears the flag and those four words. Host receives a tick instead of reading the original timer-process pointer. | | `NPCActionProcess::Create` (`1100:0000`), `StandProcess::CreateProcess` (`1100:02ed`) | Owned 0x42-byte Stand entry registered and run in harness; constructor fields, item number, and presence-bit transitions tested | Live chain stamps `+0x16 |= 0x300`, clears derived words `+0x32..0x3e`, stores NPC number at `+0x40`, ORs `0x101` at `+0x32`, sets Stand vtable `0x1f0f`, process name `Stand`, and event `0x258`. Host marks the item bit on registration and refreshes it after terminating a zero-child-state Stand, following `Item_MarkProcessPresent`/`Item_RefreshProcessPresenceFlag` (`11d0:3e0b/3e7f`). Item animation/cache reset, nonempty child-list destruction, and real NPC item ownership remain unported. | | `NPC_StartBehaviorInField0x8IfCanSeeControlledNPC` (`1100:026e`), `StandProcess::Run` (`1100:0359`) | Compiled NPC decision/Stand run branches; tests cover off-screen sleep, visible behavior start, already-current sleep, and strict wake | Live `1100:0274-02e9` reads NPC number from `+0x40`, tests entirely-on-screen, nonzero field-8 activity, not-current activity `0x71`, can-see-controlled-NPC, and starts the next behavior; `1100:035c-0382` sleeps 60 on false. `1478:1f0f` starts with far `Run` pointer `1100:0359`. Host services supply visibility/activity/item effects and timer tick; no real NPC item, general vtable resolver, or binary trace parity. | | `SystemTimerProcess_CreateProcess` (`11c0:0000`), `Process_RegisterForTimerEvents` (`11e0:19ba`), `Kernel_RegisterProcForTimerEvents` (`11d0:2dd8`), `SystemTimerProcess_Increment` (`11c0:00f8`) | Partial 0x4a-byte owned constructor and registered counter linked to harness and Windows diagnostic scheduler; zero initialization, 16-bit carry, uniqueness, process flags, registration gate, and strict Stand wake boundary tested | Exported `ConstructVtable3AD2/3AA6` (`11e0:14fb/1814`) sets interrupt/realtime flags and zeros the periodic tail; constructor stores period `0x3c` at `+0x36`, tail bit `2` at `+0x32`, and waiting/daemon/active-counter flags. Registration sets `Proc_GetTimerEvents` (`0x400`) and records the process ID; host delivery requires both. Increment carries from `+0x40` to `+0x42`. Original randomized reschedule, event type, active-counter globals, general timer list/dispatch, DOS interrupt source, and general timer teardown remain unported. | -| `KeyboardProcess_CreateProcess` (`11b8:02e1`), `Process_RegisterForKeyboardEvents` (`11e0:172a`), `Kernel_RegisterForKeyboardEvents` (`11d0:3b74`), `Process_SetKeyboardInterruptFlag` (`11e0:17a4`), `KeyboardProcess_HandleKeyEvent` (`11b8:03ad`) | Partial owned 0x36-byte keyboard process registered by harness and diagnostic window; layout, flags, singleton, exhaustion, teardown refusal, and accepted/rejected callback copies tested | Inherits `ConstructVtable3AD2` (`11e0:14fb`) interrupt flag `0x100`, registers `ExtProc_KeyboardEvents` (`0x80`) once, sets `Proc_Waiting|Proc_Daemon` (`0x3`) and `ExtProc_KeyboardInterrupt` (`0x100`). Live disassembly at `11b8:03c5-0418` and bytes `11b8:041a-041f` confirm filter pair `0x10,0`; a nonzero character and field `+0x08` copy 12 bytes from `g_lastKeyEvent` to the supplied event and clear tail `+0x32 & ~0x10`. Window `WM_CHAR` supplies a host-synthesized event for the diagnostic count only; original callback registry, `KeyDaemon`, event queue, modifier state, and player-input routing remain unported. | +| `KeyboardProcess_CreateProcess` (`11b8:02e1`), `Process_RegisterForKeyboardEvents` (`11e0:172a`), `Kernel_RegisterForKeyboardEvents` (`11d0:3b74`), `Process_SetKeyboardInterruptFlag` (`11e0:17a4`), `KeyboardProcess_HandleKeyEvent` (`11b8:03ad`) | Partial owned 0x36-byte keyboard process registered by harness and diagnostic window; layout, flags, singleton, exhaustion, teardown refusal, and accepted/rejected callback copies tested | Inherits `ConstructVtable3AD2` (`11e0:14fb`) interrupt flag `0x100`, registers `ExtProc_KeyboardEvents` (`0x80`) once, sets `Proc_Waiting|Proc_Daemon` (`0x3`) and `ExtProc_KeyboardInterrupt` (`0x100`). Live disassembly at `11b8:03c5-0418` and bytes `11b8:041a-041f` confirm filter pair `0x10,0`; a nonzero character and field `+0x08` copy 12 bytes from `g_lastKeyEvent` to the supplied event and clear tail `+0x32 & ~0x10`. Window `WM_CHAR` supplies a host-synthesized event for the diagnostic count only; original callback registry, key event queue, modifier state, and player-input routing remain unported. | | `KeyDaemon_CreateProcess` (`11b8:0000`) | Partial owned 0x40-byte constructor invoked after keyboard registration in harness and window; layout, singleton, and teardown refusal tested | Inherits `ConstructVtable3AD2/3AA6` (`11e0:14fb/1814`) interrupt/realtime flags `0x300`, sets `Proc_Daemon|Proc_Waiting` (`0x3`), `Proc_ImmediateTimer` (`0x2000`), timer-event bit `0x400`, derived tail `+0x32 |= 2`, and period `0x2d` at `+0x36`. The randomized schedule, timer list dispatch, held-key repeat callback, and DOS input state are not linked. | Live Ghidra MCP decompilation and disassembly have resolved local stack ABI, scheduler gates, and call order, not runtime state parity. Do not promote the Stand harness trace to gameplay behavior until its host-supplied NPC services and remaining tick services can be checked against execution. +`Kernel_InitProcessTables` (`11d0:1aae`) allocates and clears the separate `DS:3a04` presence bitmap (`0x480` bytes) and `DS:3a08` process-type bytes (`0x2400` bytes), as confirmed in the live NE decompilation. These lookup tables index item IDs through `0x23ff`, even though the item cache initialized by `ItemCache_InitAndLoadFixedDat` (`10a8:163a`) has a wider free-item range. The host kernel now rejects source/NPC item IDs above the lookup-table limit before changing process state; the Windows diagnostic reports an out-of-range candidate rather than queuing it. This is a bound for the modeled process tables, not an assertion that the whole item cache stops there. Tests cover `0x23ff` and `0x2400`. `Kernel_Init` (`11d0:000c`) calls the table initializer before registering timer and keyboard processes, but its DOS interrupt, real-segment, and mouse setup remain unported. + +The exported free-item path can issue `0x2400` from its `0x100..0x27ff` range, and a staged synthetic map reaches that ID; retail map 1 remains inside the kernel lookup limit. Exported `SetSourceType` (`11e0:01b6`) calls the presence/type-table writers without a visible range guard. This does not prove how a live run handles such an ID: preserve the host guard and investigate the original allocation/use path before allowing out-of-range process ownership. + +`FUN_11d0_31cf` (`11d0:31cf`) is a caller of the scheduler scan at `11d0:0255`. Its one-pass prefix snapshots the registered SystemTimer, scans runnable processes, then invokes an optional callback. The host now compiles and calls that ordered pass from the harness and Windows diagnostic, returning elapsed ticks after the callback; tests verify that a timer event delivered by the callback cannot wake a process in the already-started scan. The original infinite loop, interval wait, DOS interrupt delivery, and live group-transition trace remain unported. + +The first search-side dependency is compiled and tested in isolation: `ItemFind_10c0_14c9` (`10c0:14c9`) classifies a candidate as match type 1 (candidate Z equals origin top) or type 2 (candidate top equals origin Z), using TYPEFLAG-derived footprint widths and height, with type 1 taking priority. The host receives staged item fields and decoded shape metadata explicitly. This is **not** a port of `ItemFind_StartSearchAroundItem` (`10c0:0f73`) or the `10c0:1637` iterator; block-chain traversal, loop-script evaluation, and live item state are absent, so the classifier is not yet used to select a window item. + +The area-search setup now translates the rectangle around the origin (`10c0:0f73`), signed-coordinate normalization (`10c0:1099`), and `64 x 64` block order with 512-unit cells (`10c0:072e/0c50`). Tests cover a four-block crossing and a staged retail origin; the harness computes four candidate blocks for its first staged map-1 item. These are block indices only, not block heads, item-next chains, or script-filtered search results. + +Next source-port checks, in call-chain order: + +1. Check the live allocator/process pair at the `0x23ff/0x2400` item boundary before widening process lookup tables or changing the guard. +2. Compare timed scheduler snapshots, post-scan callbacks, and active-group transitions with a live runtime trace; port the interval wait only behind a host timing boundary. +3. Reconstruct block heads and `g_itemNext` chains for staged retail items, including insertion order and contained-item handling, before consuming the computed search blocks. +4. Recover the `Item_Grab` loop-script predicate and the `10c0:1637` iterator before connecting the isolated Z/footprint classifier to item search. +5. Trace and port `Item_Fall` (`1038:1334`) for search-result type 1, keeping it separate from process creation. +6. Wire `Item_Grab` (`10a0:2970`) to the recovered search and per-item status check, then compare requested process IDs against a live trace. +7. Lift `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`) and its interpreter initialization; keep release event-body lookup diagnostic until the VM executes it. + ## First Interactive Windows Game Shell `rebuild/remorse/out/build-nmake/remorse_game.exe` is the first windowed application target. It locates the game data root from its own executable path (or the current directory), defaults to map 1, and accepts an optional fixed-map index from 0 through 255. @@ -321,11 +346,23 @@ The application builds the selected retail map scene and player assets on a work The second HUD row is an observable, separate process-runtime diagnostic: the host 40 Hz step delivers a registered SystemTimer event, advances the recovered scheduler scan, and runs an owned Stand entry through its verified off-screen sleep branch. Tick, remaining sleep ticks, and wake count update while the window is active. Three base entries reserve the low process IDs; the Stand entry and NPC number are diagnostic fixtures, not map NPCs or the player process. Host tick frequency is not the original DOS timer interrupt rate. The diagnostic kernel also registers a partial KeyboardProcess and KeyDaemon at startup. Text-capable Win32 key messages exercise the recovered keyboard filter/copy callback and update the key-event count on the HUD. The daemon does not receive timer events yet. The visible WASD/keypad controls still use host polling; these processes do not yet deliver player input. -The walk/run modifier choice is the isolated branch from `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. Win32 supplies modifier bits; NPC state, weapon-dependent actions, original keyboard events, and the remainder of the controller selector are not ported. Retail ANIM.DAT regression checks retain the signed reverse steps in the decoder while testing the host-only forward movement filter across all four affected walk directions. +### First Map-Derived Item/Process Tick -On Windows, `remorse_game.exe`, `remorse_rebuild.exe`, and `remorse_map_preview.exe` configure crash reports at startup. Debug CRT assertions do not open Abort/Retry/Ignore windows; the terminate handler reports active C++ exception messages to the Visual Studio Debug output and stderr when available. Escaped/unhandled Windows exceptions log their code/address and suppress the fault popup. The GUI executable has no console stderr by default, so attach a debugger to see that output. A timeout-bounded CTest child process exercises the terminate reporter without a modal prompt. This does not replace a full crash dump or catch process termination that bypasses user-mode handlers. +The Phase 4 diagnostic now stages directly placed, nonzero-shape `FIXED.DAT` records into item-numbered state using the initial free-list head `0x100` and capacity `0x2700` from `ItemCache_InitAndLoadFixedDat` (`10a8:163a`). It skips zero-shape records, accounts for contained records consuming an ID without staging them as world items, and clears the status low bit for directly placed records as `ItemCache_10a8_00a0` does. Map 1 has 7,547 source records; the harness constructs an `ItemProcess` for the first eligible staged record (shape 16, diagnostic ID 256), advances a scheduler tick, records the `UC_Release` request, and verifies the process is removed. The window waits for `F` near a staged item before scheduling the one-shot path and showing its result on a separate diagnostic HUD row. Retail-data and two-tick regression tests check shape/record provenance, release-request count, process removal, and item-presence/group-count cleanup. -This is the first interactive gameplay slice, not yet a playable game: movement has no actor collision response, and there are no enemies, triggers, sound, saves, or USECODE execution. The rendered map is the retail static scene, not a live simulation. +This is an integration checkpoint, **not the Phase 4 exit criterion or a playable interaction**: the host starts this item process as a diagnostic fixture, not via the original `Item_Grab`/search trigger; it selects eligible USECODE bytes but does not create the original VM context, run the interpreter, mutate the item through `Item_Release`, or implement cache block chains, contained-item placement, shape-flag cache-out, or verified live item IDs. Staged X/Y reverse the preview loader's display scale to retain the original fixed-record words. NPC item IDs `1..255` are reserved separately and must not be conflated with staged map-item IDs. + +The Windows diagnostic no longer schedules the first staged item on scene load. `F` now selects a staged fixed-map record within 48 world units of the host-controlled actor (nearest in X/Y, using the fixed-record display scale), then runs the existing `ItemProcess` release callback on the next scheduler tick. The HUD reports the candidate and callback result; a synthetic proximity test and the MSVC/CTest gate cover selection and the existing process lifecycle. This is a one-shot diagnostic with no item-type filtering, vertical reach, USECODE event execution, or visible item-state change. Exported `Item_Grab` (`10a0:2970`) uses `ItemFind` search and an item-cache status guard before creating item processes; exported `Item_Release` (`10a0:2a06`) calls `Usecode_ItemCallEvent` with `UC_Release`. Neither original trigger nor the event executor is ported, so this change does not meet the playable-game milestone. + +The `Item_Grab` creation branch now applies the verified `FUN_11d0_3f95(itemNumber, -0xf)` item-cache flag-1 check to staged item flags before queuing a diagnostic process. Live disassembly at `10a0:29c5-29e3` confirms the branch; a separate search-result type 1 calls `Item_Fall` instead, which is not ported. The Ghidra export's zero-initialized `npcno` loop is a decompiler artifact, not evidence that the search never iterates. The host still uses proximity instead of original `ItemFind`, does not model live item-cache mutations or falling items, and must not treat process-presence bookkeeping as the checked item flag. + +The first Phase 6 resource slice is compiled into `remorse_core`: a bounded `EUSECODE.FLX` class/name/event-body reader follows the owner-loaded `classId + 2`, 13-byte name-table, `+0x14` six-byte row, and `codeBase + relativeOffset - 1` body rules verified in `docs/raw-000a-000d.md`. Retail tests confirm `EVENT` (`class 0x361`, slot `0x0a`, code base `0xd4`, body length `0x1fd6`) and `RECHFLNS` (`class 0x138`, release slot `9`, body length `102`, owner mask `0x200`). The harness resolves and reports the `EVENT` body (8,150 bytes). `Item_GetUsecodeClassId` selects a class from item identity and startup class bases; `Usecode_ItemCallEvent` gates on the owner row. Map-1 tests cover both its classless first staged item and at least one actual staged item with an eligible release body. The window applies both checks to the nearest staged item's release request and labels eligible bytes NOT RUN. This remains lookup, not bytecode interpretation or a live owner-loaded item system. The next original call is `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`, mode 2, selected class/slot and a four-byte parameter), which initializes an interpreter through `Inter_1418_0244` (`1418:0244`) and `Interpreter_1418_00e8` (`1418:00e8`). No context, interpreter dispatch, or item side effect is ported. Even the short `RECHFLNS` release event branches through item surface-weight logic and `FREE.slot_33`; an isolated opcode stub would not complete that call chain. + +The walk/run modifier choice is the isolated branch from `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. The same selector's Num Lock-off directional scan branch (`0x47/48/49/4b/4d/4f/50/51`) is now compiled in the controls helper, regression-tested across all eight mappings, and called by Win32 movement polling. Win32 still supplies modifiers and held-key state; NPC state, weapon-dependent actions, original keyboard events, and the remainder of the controller selector are not ported. Retail ANIM.DAT regression checks retain the signed reverse steps in the decoder while testing the host-only forward movement filter across all four affected walk directions. + +On Windows, `remorse_game.exe`, `remorse_rebuild.exe`, and `remorse_map_preview.exe` configure crash reports at startup. All CTest binaries now link a test-only startup initializer for the same diagnostics, so an assertion before `main` cannot open an Abort/Retry/Debug modal that blocks the build terminal. The timeout-bounded child probes exercise both a Debug CRT assertion and C++ termination, verifying prompt-free nonzero exits. The terminate handler reports active C++ exception messages to the Visual Studio Debug output and stderr when available. Escaped/unhandled Windows exceptions log their code/address and suppress the fault popup. The GUI executable has no console stderr by default, so attach a debugger to see that output. This does not replace a full crash dump or catch process termination that bypasses user-mode handlers. + +This is the first interactive gameplay slice, not yet a playable game: movement uses approximate host collision rather than the original actor response, and there are no live enemies, triggers, sound, saves, or USECODE execution. The rendered map is the retail static scene, not a live simulation. ## Import-Slice Tool @@ -630,14 +667,14 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat ## Near-Term Next Actions -1. Verify the live `Process` group-table allocation/initialization and the active-group writer `11d0:19b5`; compare `11e0:02a8` side effects with an execution trace (including counter ownership and error paths). +1. Verify the live `Process` group-table allocation/initialization and compare the compiled active-group writer/selector (`11d0:19b5/0445`) and `11e0:02a8` side effects with an execution trace (including counter ownership and error paths). 2. Complete `InitBase` (`11e0:0000`) and the kernel lifecycle by resolving the segment assertion, conditional kernel branch, item-linked teardown, process destructor dispatch and far-pointer storage; compare the host registry to real process snapshots. -3. Trace `Init_Everything` -> `FUN_11d0_0255` -> the player process and additional vtable `Run` targets; verify Stand's ported presence-bit lifecycle against original snapshots, then port animation-cache and nonempty-child teardown against real NPC state. +3. Trace `Init_Everything` -> `FUN_11d0_0255` -> the player process and additional vtable `Run` targets; compare the staged map-item/ItemProcess IDs and Stand's presence-bit lifecycle against original snapshots, then port animation-cache and nonempty-child teardown against real NPC state. 4. Port the real timer process and NPC service implementations, then scheduler keyboard, active-group advancement, remaining sleep-completion dispatch and table-maintenance tails; compare deterministic process-order/state traces before connecting the Windows window. 5. Replace DOS file and memory APIs encountered by the ported chain with narrow host adapters; validate far-pointer/layout conversions against live evidence. 6. Port original movement and AreaSearch/collision behavior before promoting the host actor movement from stand-in to gameplay code. -7. Feed original item/draw-list output into the existing renderer, then lift USECODE dispatch, save/load, audio, and frontend chains as required for playable mission progression. +7. Port `CreateFromSlotIndex` and the `Inter_1418_0244`/`Interpreter_1418_00e8` initialization path with checked stack, parameter, and program-counter state, then execute one selected retail event through original opcode handlers and verify its item/process side effects before connecting it to the window. Continue through original item/draw-list output, save/load, audio, and frontend chains for playable mission progression. ## Current Bottom Line -The project has a buildable diagnostic host, retail resource loaders, a tested process lifecycle for host-owned base and zero-child-state Stand entries, a partial original scheduler scan, and an owned 0x42-byte Stand entry executing recovered NPC-decision and `Run` branches against a source-backed timer counter (`StandProcess Run sleep ticks: 60`, three other host callbacks). Creation and termination update the per-item presence bit, but this is **not** a game milestone: real NPC item ownership, nonempty-child teardown, visibility/activity service implementations, timer-process construction and interrupts, the complete tick, startup, player, renderer, and interaction chains remain unported; `remorse_game.exe` is not connected to this registry. The next measure of progress is a real item-linked Stand/NPC instance running on the original call chain with state trace parity. +The project has a buildable diagnostic host, retail resource loaders, partial original scheduler scan, and owned Stand and item-process entries. The Windows diagnostic registry now runs an item process bound to a staged retail map record, selects any eligible release-script bytes, and runs a Stand entry under the host tick. This is a map-derived process integration checkpoint, **not** a complete Phase 4 or gameplay milestone: original item cache/block IDs, actual release USECODE execution, real NPC ownership/services, nonempty-child teardown, DOS timer/keyboard interrupts, full scheduler, original startup/player chain, renderer item output, and interactions remain unported. The next measures of gameplay progress are an executed retail event with a verified live item mutation and a real item-linked Stand/NPC instance on the original call chain with state trace parity. diff --git a/rebuild/remorse/CMakeLists.txt b/rebuild/remorse/CMakeLists.txt index 454d3a8..67ee6da 100644 --- a/rebuild/remorse/CMakeLists.txt +++ b/rebuild/remorse/CMakeLists.txt @@ -17,6 +17,7 @@ add_library(remorse_core src/runtime.cpp src/shape_archive.cpp src/type_flags.cpp + src/usecode_archive.cpp ) target_compile_features(remorse_core PUBLIC cxx_std_17) @@ -155,6 +156,16 @@ target_link_libraries(combat_tactics_tests PRIVATE remorse_core) add_test(NAME combat_tactics_tests COMMAND combat_tactics_tests) +add_library(remorse_test_crash_setup OBJECT tests/test_crash_setup.cpp) +target_link_libraries(remorse_test_crash_setup PRIVATE remorse_core) +foreach(test_target IN ITEMS + entity_dispatch_entry_tests file_system_tests palette_tests flex_archive_tests + fixed_map_tests glob_archive_tests type_flags_tests shape_archive_tests + map_renderer_tests map_sorter_tests isometric_controls_tests + animation_archive_tests collision_tests combat_tactics_tests) + target_sources(${test_target} PRIVATE $) +endforeach() + if(MSVC) target_compile_options(remorse_core PRIVATE /W4 /permissive-) target_compile_options(combat_tactics_tests PRIVATE /W4 /permissive-) diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index 3be351b..e43e059 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -67,8 +67,10 @@ struct NpcBehaviorServices { class ProcessKernel { public: + static constexpr u16 maxTrackedItemNumber = 0x23ff; EntityDispatchEntryBase* createProcess(u8 activeGroup, u16 (&groupCounts)[32]); StandProcessEntry* createStandProcess(u8 activeGroup, u16 npcNumber, u16 (&groupCounts)[32]); + EntityDispatchEntryBase* createItemProcess(u8 activeGroup, u16 itemNumber, u16 (&groupCounts)[32]); SystemTimerProcessEntry* createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]); @@ -76,16 +78,25 @@ public: u32 systemTimerTick() const; void setSyncContext(bool enabled, u16 currentProcessId); void setMarkNewProcesses(bool enabled); + void setActiveGroup(u8 groupId); + u8 activeGroup() const; + bool groupSelectionPending() const; + void refreshActiveGroup(const u16 (&groupCounts)[32]); void setLastAllocationSize(u16 size); u16 addProcess(EntityDispatchEntryBase& entry); void clearProcessSlot(u16 id); void terminateProcess(u16 id, u16 (&groupCounts)[32]); void clearTerminatedProcesses(); + void setProcessSourceType(EntityDispatchEntryBase& entry, u16 itemNumber); + void setProcessEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType); void scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, u32 timerTick = 0); + u32 runTimedSchedulerPass(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, + void (*afterScan)(void*) = nullptr, void* afterContext = nullptr); EntityDispatchEntryBase* processAt(u16 id) const; u16 allocationSizeAt(u16 id) const; const char* processNameAt(u16 id) const; bool itemHasProcess(u16 itemNumber) const; + u8 itemProcessTypes(u16 itemNumber) const; u16 processCount() const; u16 terminatedProcessCount() const; u16 newlyCreatedCount() const; @@ -93,6 +104,8 @@ public: private: void releaseOwnedProcess(u16 id); + void refreshItemPresence(u16 itemNumber); + void refreshItemProcessType(u16 itemNumber, u16 eventType); std::vector processes_; std::vector allocationSizes_; std::vector processNames_; @@ -103,11 +116,14 @@ private: std::unique_ptr keyDaemonProcess_; u16 systemTimerProcessId_ = 0xffff; std::vector itemProcessPresence_; + std::vector itemProcessTypes_; u16 lastAllocationSize_ = 0; u16 processCount_ = 0; u16 terminatedProcessCount_ = 0; u16 newlyCreatedCount_ = 0; u16 currentProcessId_ = 0; + u8 activeGroup_ = 1; + bool groupSelectionPending_ = false; bool syncEnabled_ = false; bool markNewProcesses_ = false; }; @@ -119,7 +135,7 @@ public: static EntityDispatchEntryBase* initBase(EntityDispatchEntryBase* entry, u8 activeGroup, u16 (&groupCounts)[32]); static void setGroupId(EntityDispatchEntryBase& entry, u8 groupId, u16 (&groupCounts)[32]); - static void incrementGroupId(EntityDispatchEntryBase& entry); + static void incrementGroupId(EntityDispatchEntryBase& entry, ProcessKernel& kernel, u16 (&groupCounts)[32]); static void setSourceType(EntityDispatchEntryBase& entry, u16 sourceType); static void setEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType); static void sleep(EntityDispatchEntryBase& entry, u32 timerTick, u32 duration); @@ -136,6 +152,15 @@ public: static void run(StandProcessEntry& entry, const NpcBehaviorServices& services, u32 timerTick); }; +class ItemProcess { +public: + static constexpr u16 runOffset = 0x0078; + static constexpr u16 vtableOffset = 0x102f; + + static void run(EntityDispatchEntryBase& entry, ProcessKernel& kernel, u16 (&groupCounts)[32], + void (*release)(u16 itemNumber, u32 eventMask, u16 eventId, void*), void* context); +}; + class SystemTimerProcess { public: static u32 tick(const SystemTimerProcessEntry& entry); diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index cb4b068..e3ae718 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -8,6 +8,8 @@ namespace remorse { +struct ShapeTypeInfo; + struct FixedMapEntry { u16 x = 0; u16 y = 0; @@ -26,6 +28,19 @@ struct FixedMap { std::vector entries; }; +struct StagedFixedMapItem { + u16 itemNumber = 0; + std::size_t recordIndex = 0; + FixedMapEntry data; +}; + +struct ItemFindArea { + u16 minX = 0; + u16 minY = 0; + u16 maxX = 0; + u16 maxY = 0; +}; + struct FixedMapArchive { u32 mapCount = 0; std::vector bytes; @@ -33,5 +48,13 @@ struct FixedMapArchive { std::optional loadFixedMapArchive(const std::filesystem::path& path); std::optional loadFixedMap(const FixedMapArchive& archive, u32 mapIndex); +std::optional> stageFixedMapItems(const FixedMap& map); +std::optional nearestStagedFixedMapItem( + const std::vector& items, s32 worldX, s32 worldY, s32 maxDistance); +bool itemGrabCanCreateProcess(const StagedFixedMapItem& item); +u8 classifyItemFindZMatch(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape, + const StagedFixedMapItem& candidate, const ShapeTypeInfo& candidateShape, u8 zMatchFlags); +ItemFindArea itemFindAreaAroundItem(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape); +std::vector itemFindBlockOrder(const ItemFindArea& area); } // namespace remorse diff --git a/rebuild/remorse/include/remorse/isometric_controls.h b/rebuild/remorse/include/remorse/isometric_controls.h index 902c14d..e0f50ae 100644 --- a/rebuild/remorse/include/remorse/isometric_controls.h +++ b/rebuild/remorse/include/remorse/isometric_controls.h @@ -17,6 +17,22 @@ inline bool controllerWalkRequested(u16 modifiers) return shiftDown == capsLockOn; } +inline std::optional controllerDirectionFromScan(u8 scanCode) +{ + // Controller_PickNextAnimByKeyevent (1130:12d6), directional keys with Num Lock off. + switch (scanCode) { + case 0x47: return u8{12}; + case 0x48: return u8{14}; + case 0x49: return u8{0}; + case 0x4b: return u8{10}; + case 0x4d: return u8{2}; + case 0x4f: return u8{8}; + case 0x50: return u8{6}; + case 0x51: return u8{4}; + default: return std::nullopt; + } +} + inline std::optional hostMovementStep( const AnimationFrameMetadata& metadata, u8 direction, bool rotateDirection) { diff --git a/rebuild/remorse/include/remorse/usecode_archive.h b/rebuild/remorse/include/remorse/usecode_archive.h new file mode 100644 index 0000000..dc50820 --- /dev/null +++ b/rebuild/remorse/include/remorse/usecode_archive.h @@ -0,0 +1,54 @@ +#pragma once + +#include "remorse/flex_archive.h" + +#include +#include +#include + +namespace remorse { + +struct UsecodeClass { + u32 classId = 0; + std::string name; + u32 codeBase = 0; + std::vector bytes; +}; + +struct UsecodeEventBody { + u16 length = 0; + u32 relativeOffset = 0; + std::vector bytes; +}; + +struct UsecodeClassBases { + u16 regularShape = 0; + u16 npc = 0; + u16 unknownEgg = 0; +}; + +struct UsecodeItemIdentity { + u16 itemNumber = 0; + u16 shape = 0; + u16 status = 0; + u16 quality = 0; + u8 family = 0; + bool isNpc = false; +}; + +struct EligibleUsecodeEvent { + u16 classId = 0; + std::string className; + UsecodeEventBody body; +}; + +u16 selectUsecodeClassId(const UsecodeItemIdentity& item, const UsecodeClassBases& bases); +std::optional> loadUsecodeOwnerRows(const FlexArchive& archive); +bool ownerRowAllowsEvent(const std::vector& ownerRows, u16 classId, u32 eventMask); +std::optional loadUsecodeClass(const FlexArchive& archive, u32 classId); +std::optional readUsecodeEventBody(const UsecodeClass& usecodeClass, u32 eventId); +std::optional selectEligibleUsecodeEvent(const FlexArchive& archive, + const std::vector& ownerRows, const UsecodeItemIdentity& item, + const UsecodeClassBases& bases, u32 eventMask, u16 eventId); + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index ed2dd79..a41b9a2 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -61,6 +61,9 @@ EntityDispatchEntryBase* ProcessKernel::createProcess(u8 activeGroup, u16 (&grou StandProcessEntry* ProcessKernel::createStandProcess(u8 activeGroup, u16 npcNumber, u16 (&groupCounts)[32]) { + if (npcNumber > maxTrackedItemNumber) { + throw std::out_of_range("NPC item number exceeds process lookup tables"); + } if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { throw std::overflow_error("process table exhausted"); } @@ -102,6 +105,28 @@ StandProcessEntry* ProcessKernel::createStandProcess(u8 activeGroup, u16 npcNumb return result; } +EntityDispatchEntryBase* ProcessKernel::createItemProcess(u8 activeGroup, u16 itemNumber, u16 (&groupCounts)[32]) +{ + if (itemNumber == 0) { + throw std::invalid_argument("item process needs an item number"); + } + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + ownedProcesses_.reserve(ownedProcesses_.size() + 1); + auto process = std::make_unique(); + EntityDispatchEntry::initBase(process.get(), activeGroup, groupCounts); + writeLe16(*process, 0x00, ItemProcess::vtableOffset); + setProcessSourceType(*process, itemNumber); + setProcessEventTypeChecked(*process, 0xf1); + setLastAllocationSize(sizeof(EntityDispatchEntryBase)); + const u16 id = addProcess(*process); + processNames_[id] = "ItemProcess"; + EntityDispatchEntryBase* result = process.get(); + ownedProcesses_.push_back(std::move(process)); + return result; +} + SystemTimerProcessEntry* ProcessKernel::createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]) { if (systemTimerProcess_ != nullptr) { @@ -195,6 +220,45 @@ void ProcessKernel::setMarkNewProcesses(bool enabled) markNewProcesses_ = enabled; } +void ProcessKernel::setActiveGroup(u8 groupId) +{ + if (groupId == 0 || groupId > 31) { + throw std::invalid_argument("active process group must be in 1..31"); + } + if (activeGroup_ != groupId) { + activeGroup_ = groupId; + groupSelectionPending_ = true; + } +} + +u8 ProcessKernel::activeGroup() const +{ + return activeGroup_; +} + +bool ProcessKernel::groupSelectionPending() const +{ + return groupSelectionPending_; +} + +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; + } + } + } + setActiveGroup(highestGroup); + groupSelectionPending_ = false; +} + void ProcessKernel::setLastAllocationSize(u16 size) { lastAllocationSize_ = size; @@ -260,6 +324,7 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) throw std::out_of_range("process ID is not addressable"); } const u16 itemNumber = readLe16(*entry, 0x04); + const u16 eventType = readLe16(*entry, 0x06); if (systemTimerProcess_ != nullptr && entry == &systemTimerProcess_->base) { throw std::logic_error("system timer teardown is not ported"); } @@ -271,7 +336,10 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) } const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(), [entry](const auto& process) { return &process->base == entry; }); - if (itemNumber != 0 && (stand == ownedStandProcesses_.end() || id < 3 || + const bool ownedItemProcess = readLe16(*entry, 0x00) == ItemProcess::vtableOffset && + std::any_of(ownedProcesses_.begin(), ownedProcesses_.end(), + [entry](const auto& process) { return process.get() == entry; }); + if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess || id < 3 || readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 || readLe16(*entry, 0x2e) != 0 || readLe16(*entry, 0x30) != 0)) { throw std::logic_error("item process child cleanup is not ported"); @@ -292,15 +360,92 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) ++terminatedProcessCount_; } --processCount_; + refreshItemPresence(itemNumber); + refreshItemProcessType(itemNumber, eventType); +} + +void ProcessKernel::refreshItemPresence(u16 itemNumber) +{ + if (itemNumber == 0) { + return; + } + const bool present = processes_.size() > 3 && std::any_of(processes_.begin() + 3, processes_.end(), + [itemNumber](const EntityDispatchEntryBase* process) { + return process != nullptr && readLe16(*process, 0x04) == itemNumber && + (readLe16(*process, 0x16) & 0x08) == 0; + }); + const std::size_t itemByte = itemNumber >> 3; + if (itemProcessPresence_.size() <= itemByte) { + itemProcessPresence_.resize(itemByte + 1, 0); + } + if (present) { + itemProcessPresence_[itemByte] |= static_cast(1u << (itemNumber & 7)); + } else { + itemProcessPresence_[itemByte] &= static_cast(~(1u << (itemNumber & 7))); + } +} + +void ProcessKernel::refreshItemProcessType(u16 itemNumber, u16 eventType) +{ + if (itemNumber == 0 || eventType < 0xf0 || eventType > 0xf7) { + return; + } + const bool present = processes_.size() > 3 && std::any_of(processes_.begin() + 3, processes_.end(), + [itemNumber, eventType](const EntityDispatchEntryBase* process) { + return process != nullptr && readLe16(*process, 0x04) == itemNumber && + readLe16(*process, 0x06) == eventType && (readLe16(*process, 0x16) & 0x08) == 0; + }); + if (itemProcessTypes_.size() <= itemNumber) { + itemProcessTypes_.resize(static_cast(itemNumber) + 1, 0); + } + const u8 bit = static_cast(1u << (eventType - 0xf0)); + if (present) { + itemProcessTypes_[itemNumber] |= bit; + } else { + itemProcessTypes_[itemNumber] &= static_cast(~bit); + } +} + +void ProcessKernel::setProcessSourceType(EntityDispatchEntryBase& entry, u16 itemNumber) +{ + if (itemNumber > maxTrackedItemNumber) { + throw std::out_of_range("item number exceeds process lookup tables"); + } + const u16 previousItem = readLe16(entry, 0x04); + const u16 eventType = readLe16(entry, 0x06); + EntityDispatchEntry::setSourceType(entry, itemNumber); if (itemNumber != 0) { - const bool stillPresent = std::any_of(processes_.begin() + 3, processes_.end(), - [itemNumber](const EntityDispatchEntryBase* process) { - return process != nullptr && readLe16(*process, 0x04) == itemNumber && - (readLe16(*process, 0x16) & 0x08) == 0; - }); - if (!stillPresent) { - itemProcessPresence_[itemNumber >> 3] &= static_cast(~(1u << (itemNumber & 7))); + const std::size_t itemByte = itemNumber >> 3; + if (itemProcessPresence_.size() <= itemByte) { + itemProcessPresence_.resize(itemByte + 1, 0); } + itemProcessPresence_[itemByte] |= static_cast(1u << (itemNumber & 7)); + if (eventType >= 0xf0 && eventType <= 0xf7) { + if (itemProcessTypes_.size() <= itemNumber) { + itemProcessTypes_.resize(static_cast(itemNumber) + 1, 0); + } + itemProcessTypes_[itemNumber] |= static_cast(1u << (eventType - 0xf0)); + } + } + if (previousItem != 0 && previousItem != itemNumber) { + refreshItemPresence(previousItem); + refreshItemProcessType(previousItem, eventType); + } +} + +void ProcessKernel::setProcessEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType) +{ + const u16 previousType = readLe16(entry, 0x06); + const u16 itemNumber = readLe16(entry, 0x04); + EntityDispatchEntry::setEventTypeChecked(entry, eventType); + if (itemNumber != 0 && eventType >= 0xf0 && eventType <= 0xf7) { + if (itemProcessTypes_.size() <= itemNumber) { + itemProcessTypes_.resize(static_cast(itemNumber) + 1, 0); + } + itemProcessTypes_[itemNumber] |= static_cast(1u << (eventType - 0xf0)); + } + if (previousType != eventType) { + refreshItemProcessType(itemNumber, previousType); } } @@ -324,6 +469,7 @@ void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDisp if (run == nullptr) { throw std::invalid_argument("process run slot is required"); } + setActiveGroup(activeGroup); const bool priorSyncEnabled = syncEnabled_; const u16 priorProcessId = currentProcessId_; syncEnabled_ = true; @@ -353,7 +499,7 @@ void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDisp 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)) { + ((flags & 2) != 0 || groupId == activeGroup_ || groupId == 30 || groupId == 31)) { currentProcessId_ = static_cast(id); run(*entry, context); currentProcessId_ = 0; @@ -371,6 +517,17 @@ void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDisp currentProcessId_ = priorProcessId; } +u32 ProcessKernel::runTimedSchedulerPass(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, + void (*afterScan)(void*), void* afterContext) +{ + const u32 startTick = systemTimerTick(); + scanRunnableProcesses(activeGroup, run, context, startTick); + if (afterScan != nullptr) { + afterScan(afterContext); + } + return systemTimerTick() - startTick; +} + EntityDispatchEntryBase* ProcessKernel::processAt(u16 id) const { return id < processes_.size() ? processes_[id] : nullptr; @@ -393,6 +550,11 @@ bool ProcessKernel::itemHasProcess(u16 itemNumber) const (itemProcessPresence_[itemByte] & (1u << (itemNumber & 7))) != 0; } +u8 ProcessKernel::itemProcessTypes(u16 itemNumber) const +{ + return itemNumber < itemProcessTypes_.size() ? itemProcessTypes_[itemNumber] : 0; +} + u16 ProcessKernel::processCount() const { return processCount_; @@ -449,9 +611,15 @@ void EntityDispatchEntry::setGroupId(EntityDispatchEntryBase& entry, u8 groupId, ++groupCounts[groupId]; } -void EntityDispatchEntry::incrementGroupId(EntityDispatchEntryBase& entry) +void EntityDispatchEntry::incrementGroupId(EntityDispatchEntryBase& entry, ProcessKernel& kernel, u16 (&groupCounts)[32]) { - ++entry.bytes[groupIdOffset]; + 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); } void EntityDispatchEntry::setSourceType(EntityDispatchEntryBase& entry, u16 sourceType) @@ -462,6 +630,9 @@ void EntityDispatchEntry::setSourceType(EntityDispatchEntryBase& entry, u16 sour void EntityDispatchEntry::setEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType) { writeLe16(entry, eventTypeOffset, eventType); + if (eventType > 0x0fff) { + throw std::invalid_argument("process event type exceeds 0x0fff"); + } } void EntityDispatchEntry::sleep(EntityDispatchEntryBase& entry, u32 timerTick, u32 duration) @@ -511,6 +682,17 @@ void StandProcess::run(StandProcessEntry& entry, const NpcBehaviorServices& serv }, &started, timerTick); } +void ItemProcess::run(EntityDispatchEntryBase& entry, ProcessKernel& kernel, u16 (&groupCounts)[32], + void (*release)(u16 itemNumber, u32 eventMask, u16 eventId, void*), void* context) +{ + if (release == nullptr) { + throw std::invalid_argument("item release boundary is required"); + } + const u16 itemNumber = readLe16(entry, 0x04); + release(itemNumber, 0x200, 9, context); + kernel.terminateProcess(readLe16(entry, 0x02), groupCounts); +} + u32 SystemTimerProcess::tick(const SystemTimerProcessEntry& entry) { return static_cast(entry.extra[0x0e] | (static_cast(entry.extra[0x0f]) << 8)) | diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index 9c981db..33222ff 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -1,6 +1,7 @@ #include "remorse/fixed_map.h" #include "remorse/file_system.h" +#include "remorse/type_flags.h" namespace remorse { namespace { @@ -116,4 +117,111 @@ std::optional loadFixedMap(const FixedMapArchive& archive, u32 mapInde return map; } +std::optional> stageFixedMapItems(const FixedMap& map) +{ + constexpr std::size_t firstFreeItemNumber = 0x100; + constexpr std::size_t freeItemCount = 0x2700; + std::vector items; + items.reserve(map.entries.size()); + std::size_t allocated = 0; + for (std::size_t index = 0; index < map.entries.size(); ++index) { + if (map.entries[index].shape == 0) { + continue; + } + if (allocated == freeItemCount) { + return std::nullopt; + } + const u16 itemNumber = static_cast(firstFreeItemNumber + allocated++); + if ((map.entries[index].flags & 8) != 0) { + continue; + } + StagedFixedMapItem item; + item.itemNumber = itemNumber; + item.recordIndex = index; + item.data = map.entries[index]; + item.data.x = static_cast(item.data.x / crusaderCoordinateScale); + item.data.y = static_cast(item.data.y / crusaderCoordinateScale); + item.data.flags &= static_cast(~1u); + items.push_back(item); + } + return items; +} + +std::optional nearestStagedFixedMapItem( + const std::vector& items, s32 worldX, s32 worldY, s32 maxDistance) +{ + if (maxDistance < 0) { + return std::nullopt; + } + const auto limit = static_cast(maxDistance) * maxDistance; + auto bestDistance = limit + 1; + const StagedFixedMapItem* best = nullptr; + for (const auto& item : items) { + const auto deltaX = static_cast(item.data.x) * crusaderCoordinateScale - worldX; + const auto deltaY = static_cast(item.data.y) * crusaderCoordinateScale - worldY; + const auto distance = deltaX * deltaX + deltaY * deltaY; + if (distance <= limit && distance < bestDistance) { + bestDistance = distance; + best = &item; + } + } + return best == nullptr ? std::nullopt : std::optional(*best); +} + +bool itemGrabCanCreateProcess(const StagedFixedMapItem& item) +{ + return (item.data.flags & 0x02) == 0; +} + +u8 classifyItemFindZMatch(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape, + const StagedFixedMapItem& candidate, const ShapeTypeInfo& candidateShape, u8 zMatchFlags) +{ + if (candidate.itemNumber == 0) { + return 0; + } + const auto height = [](const ShapeTypeInfo& shape) { + return shape.z == 0 && (shape.flags & 1) == 0 ? 1 : static_cast(shape.z) * 8; + }; + const int minimumX = static_cast(candidate.data.x) - static_cast(candidateShape.x) * 16 + 1; + const int minimumY = static_cast(candidate.data.y) - static_cast(candidateShape.y) * 16 + 1; + if (minimumX > origin.data.x || minimumY > origin.data.y) { + return 0; + } + const u8 originTop = static_cast(static_cast(origin.data.z) + height(originShape)); + if ((zMatchFlags & 1) != 0 && candidate.data.z == originTop) { + return 1; + } + if ((zMatchFlags & 2) != 0 && origin.data.z == static_cast(candidate.data.z) + height(candidateShape)) { + return 2; + } + return 0; +} + +ItemFindArea itemFindAreaAroundItem(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape) +{ + const auto normalize = [](u16 value, u16 negativeValue) { + return static_cast(value) < 0 ? negativeValue : value; + }; + const u16 minX = static_cast(static_cast(origin.data.x) - originShape.x * 16 + 1); + const u16 minY = static_cast(static_cast(origin.data.y) - originShape.y * 16 + 1); + const u16 maxX = static_cast(origin.data.x + 0x100); + const u16 maxY = static_cast(origin.data.y + 0x100); + return {normalize(minX, 0), normalize(minY, 0), + normalize(maxX, 0x7fff), normalize(maxY, 0x7fff)}; +} + +std::vector itemFindBlockOrder(const ItemFindArea& area) +{ + std::vector blocks; + if (area.minX > area.maxX || area.minY > area.maxY) { + return blocks; + } + for (u16 blockY = area.minY >> 9; blockY <= (area.maxY >> 9); ++blockY) { + for (u16 blockX = area.minX >> 9; blockX <= (area.maxX >> 9); ++blockX) { + blocks.push_back(static_cast(blockX * 0x40 + blockY)); + } + } + return blocks; +} + } // namespace remorse diff --git a/rebuild/remorse/src/main.cpp b/rebuild/remorse/src/main.cpp index b3d1ae7..a269199 100644 --- a/rebuild/remorse/src/main.cpp +++ b/rebuild/remorse/src/main.cpp @@ -7,6 +7,7 @@ #include "remorse/palette.h" #include "remorse/runtime.h" #include "remorse/type_flags.h" +#include "remorse/usecode_archive.h" #include #include @@ -27,7 +28,7 @@ int main(int argc, char** argv) remorse::printStartupReport(*manifest); remorse::ProcessKernel kernel; remorse::u16 groupCounts[32]{}; - const auto* entry = kernel.createProcess(1, groupCounts); + auto* entry = kernel.createProcess(1, groupCounts); std::cout << "Registered process ID: " << (entry ? entry->bytes[0x02] : 0) << '\n'; for (int index = 0; index < 3; ++index) { kernel.createProcess(1, groupCounts); @@ -57,20 +58,25 @@ int main(int argc, char** argv) kernel.deliverSystemTimerEvent(); } scanContext.timerTick = kernel.systemTimerTick(); - kernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) { + const remorse::u32 schedulerElapsed = kernel.runTimedSchedulerPass(1, [](remorse::EntityDispatchEntryBase& process, void* context) { auto& scan = *static_cast(context); if (process.bytes[0] == 0x0f && process.bytes[1] == 0x1f) { remorse::StandProcess::run(*scan.standing, *scan.npcServices, scan.timerTick); } else { ++scan.hostCallbacks; } - }, &scanContext, scanContext.timerTick); + }, &scanContext); + kernel.refreshActiveGroup(groupCounts); + remorse::EntityDispatchEntry::incrementGroupId(*entry, kernel, groupCounts); + std::cout << "Advanced process group: " << static_cast(kernel.activeGroup()) << '\n'; std::cout << "Scheduler scan host callbacks: " << scanContext.hostCallbacks << '\n'; + std::cout << "Scheduler pass elapsed ticks: " << schedulerElapsed << '\n'; std::cout << "StandProcess Run sleep ticks: " << static_cast(reused->base.bytes[0x0e]) << '\n'; const auto gameDataRoot = remorse::findGameDataRoot(std::filesystem::current_path()); std::cout << "Game data root: " << (gameDataRoot ? gameDataRoot->path.string() : "not found") << '\n'; if (gameDataRoot) { + std::optional firstStagedItem; const auto palettePath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("STATIC") / "GAMEPAL.PAL"); const auto paletteBytes = palettePath ? remorse::readBinaryFile(*palettePath) : std::nullopt; std::cout << "GAMEPAL.PAL bytes: " << (paletteBytes ? paletteBytes->size() : 0) << '\n'; @@ -92,6 +98,33 @@ int main(int argc, char** argv) if (map && !map->entries.empty()) { std::cout << "FIXED.DAT first non-empty map: " << index << '\n'; std::cout << "FIXED.DAT first non-empty entries: " << map->entries.size() << '\n'; + const auto items = remorse::stageFixedMapItems(*map); + if (items && !items->empty()) { + firstStagedItem = items->front(); + struct ItemScanContext { + remorse::ProcessKernel* kernel; + remorse::u16 (*groups)[32]; + remorse::u16 releaseEventItem = 0; + } itemScan{&kernel, &groupCounts}; + auto* itemProcess = kernel.createItemProcess(kernel.activeGroup(), items->front().itemNumber, groupCounts); + const remorse::u16 itemProcessId = static_cast( + itemProcess->bytes[2] | (static_cast(itemProcess->bytes[3]) << 8)); + kernel.scanRunnableProcesses(kernel.activeGroup(), [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& scan = *static_cast(context); + if (process.bytes[0] == 0x2f && process.bytes[1] == 0x10) { + remorse::ItemProcess::run(process, *scan.kernel, *scan.groups, + [](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* releaseContext) { + if (eventMask == 0x200 && eventId == 9) { + static_cast(releaseContext)->releaseEventItem = itemNumber; + } + }, &scan); + } + }, &itemScan, kernel.systemTimerTick()); + kernel.refreshActiveGroup(groupCounts); + std::cout << "Staged retail item shape: " << items->front().data.shape << '\n'; + std::cout << "ItemProcess release event boundary item: " << itemScan.releaseEventItem << '\n'; + std::cout << "ItemProcess terminated: " << (kernel.processAt(itemProcessId) == nullptr) << '\n'; + } break; } } @@ -104,6 +137,26 @@ int main(int argc, char** argv) const auto typeFlagPath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); const auto typeFlags = typeFlagPath ? remorse::loadTypeFlags(*typeFlagPath) : std::nullopt; std::cout << "TYPEFLAG.DAT shapes: " << (typeFlags ? typeFlags->size() : 0) << '\n'; + if (firstStagedItem && typeFlags && firstStagedItem->data.shape < typeFlags->size()) { + const auto area = remorse::itemFindAreaAroundItem( + *firstStagedItem, (*typeFlags)[firstStagedItem->data.shape]); + std::cout << "Staged item ItemFind blocks: " << remorse::itemFindBlockOrder(area).size() << '\n'; + } + + const auto usecodePath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("USECODE") / "EUSECODE.FLX"); + const auto usecodeArchive = usecodePath ? remorse::loadFlexArchive(*usecodePath) : std::nullopt; + const auto eventClass = usecodeArchive ? remorse::loadUsecodeClass(*usecodeArchive, 0x361) : std::nullopt; + const auto eventBody = eventClass ? remorse::readUsecodeEventBody(*eventClass, 0x0a) : std::nullopt; + std::cout << "EUSECODE EVENT slot 0x0a body bytes: " << (eventBody ? eventBody->bytes.size() : 0) << '\n'; + if (firstStagedItem && typeFlags && usecodeArchive && firstStagedItem->data.shape < typeFlags->size()) { + const auto& item = *firstStagedItem; + const remorse::UsecodeItemIdentity identity{item.itemNumber, item.data.shape, + item.data.flags, item.data.quality, (*typeFlags)[item.data.shape].family, false}; + const remorse::UsecodeClassBases bases{0, 0x800, 0x900}; + const auto itemClass = remorse::loadUsecodeClass(*usecodeArchive, + remorse::selectUsecodeClassId(identity, bases)); + std::cout << "Staged item USECODE class: " << (itemClass ? itemClass->name : "not present") << '\n'; + } } return 0; } diff --git a/rebuild/remorse/src/usecode_archive.cpp b/rebuild/remorse/src/usecode_archive.cpp new file mode 100644 index 0000000..a8fd2c2 --- /dev/null +++ b/rebuild/remorse/src/usecode_archive.cpp @@ -0,0 +1,109 @@ +#include "remorse/usecode_archive.h" + +#include + +namespace remorse { +namespace { + +u16 readWord(const std::vector& bytes, std::size_t offset) +{ + return static_cast(bytes[offset] | (static_cast(bytes[offset + 1]) << 8)); +} + +u32 readDword(const std::vector& bytes, std::size_t offset) +{ + return static_cast(bytes[offset]) | (static_cast(bytes[offset + 1]) << 8) | + (static_cast(bytes[offset + 2]) << 16) | (static_cast(bytes[offset + 3]) << 24); +} + +} // namespace + +u16 selectUsecodeClassId(const UsecodeItemIdentity& item, const UsecodeClassBases& bases) +{ + if (item.isNpc && (item.status & 2) == 0) { + return static_cast(item.itemNumber + bases.npc); + } + if (item.family == 4) { + return static_cast((item.quality & 0xff) + bases.unknownEgg); + } + return static_cast(item.shape + bases.regularShape); +} + +std::optional> loadUsecodeOwnerRows(const FlexArchive& archive) +{ + auto rows = readFlexEntry(archive, 1); + if (!rows || rows->size() % 13 != 0) { + return std::nullopt; + } + return rows; +} + +bool ownerRowAllowsEvent(const std::vector& ownerRows, u16 classId, u32 eventMask) +{ + constexpr std::size_t rowSize = 13; + const std::size_t row = static_cast(classId) * rowSize; + if (eventMask == 0 || row > ownerRows.size() || ownerRows.size() - row < rowSize) { + return false; + } + return (readDword(ownerRows, row) & eventMask) != 0; +} + +std::optional loadUsecodeClass(const FlexArchive& archive, u32 classId) +{ + if (classId >= archive.entryCount || archive.entryCount - classId <= 2) { + return std::nullopt; + } + const auto names = loadUsecodeOwnerRows(archive); + auto bytes = readFlexEntry(archive, classId + 2); + if (!names || !bytes || bytes->size() < 20 || classId >= names->size() / 13) { + return std::nullopt; + } + const std::size_t nameOffset = 4 + static_cast(classId) * 13; + const u32 codeBase = readDword(*bytes, 8); + if (codeBase < 20 || codeBase > bytes->size() || (codeBase - 20) % 6 != 0) { + return std::nullopt; + } + std::string name; + for (std::size_t index = 0; index < 9 && (*names)[nameOffset + index] != 0; ++index) { + name.push_back(static_cast((*names)[nameOffset + index])); + } + return UsecodeClass{classId, std::move(name), codeBase, std::move(*bytes)}; +} + +std::optional readUsecodeEventBody(const UsecodeClass& usecodeClass, u32 eventId) +{ + if (usecodeClass.codeBase < 20 || usecodeClass.codeBase > usecodeClass.bytes.size() || + eventId >= (usecodeClass.codeBase - 20) / 6) { + return std::nullopt; + } + const std::size_t row = 20 + static_cast(eventId) * 6; + const u16 length = readWord(usecodeClass.bytes, row); + const u32 offset = readDword(usecodeClass.bytes, row + 2); + if (length == 0 || offset == 0 || offset > usecodeClass.bytes.size() - usecodeClass.codeBase + 1) { + return std::nullopt; + } + const std::size_t start = usecodeClass.codeBase + static_cast(offset) - 1; + if (length > usecodeClass.bytes.size() - start) { + return std::nullopt; + } + return UsecodeEventBody{length, offset, + std::vector(usecodeClass.bytes.begin() + start, usecodeClass.bytes.begin() + start + length)}; +} + +std::optional selectEligibleUsecodeEvent(const FlexArchive& archive, + const std::vector& ownerRows, const UsecodeItemIdentity& item, + const UsecodeClassBases& bases, u32 eventMask, u16 eventId) +{ + const u16 classId = selectUsecodeClassId(item, bases); + if (!ownerRowAllowsEvent(ownerRows, classId, eventMask)) { + return std::nullopt; + } + const auto usecodeClass = loadUsecodeClass(archive, classId); + const auto body = usecodeClass ? readUsecodeEventBody(*usecodeClass, eventId) : std::nullopt; + if (!body) { + return std::nullopt; + } + return EligibleUsecodeEvent{classId, usecodeClass->name, *body}; +} + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index 25a232e..c3ba213 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -14,6 +14,7 @@ #include "remorse/runtime.h" #include "remorse/shape_archive.h" #include "remorse/type_flags.h" +#include "remorse/usecode_archive.h" #include #include @@ -37,6 +38,7 @@ constexpr remorse::u32 backingHeight = 1440; constexpr int initialClientWidth = 1280; constexpr int initialClientHeight = 760; constexpr double simulationTickSeconds = 0.025; +constexpr remorse::s32 diagnosticItemRange = 48; struct AppState { remorse::GameDataRoot root; @@ -45,6 +47,13 @@ struct AppState { remorse::u16 diagnosticGroupCounts[32]{}; remorse::StandProcessEntry* diagnosticStand = nullptr; remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr; + std::vector stagedItems; + std::optional diagnosticItem; + remorse::u16 diagnosticItemProcessId = 0; + remorse::u16 diagnosticReleaseEventItem = 0; + std::string diagnosticReleaseClass; + std::size_t diagnosticReleaseBodyBytes = 0; + bool diagnosticItemCompleted = false; remorse::u32 standWakeCount = 0; remorse::u32 diagnosticKeyEvents = 0; std::mutex sceneMutex; @@ -55,6 +64,9 @@ struct AppState { std::vector> playerFrames; remorse::CollisionBody playerCollisionBody{}; std::vector collisionBodies; + std::vector shapeTypes; + std::optional usecodeArchive; + std::vector usecodeOwnerRows; remorse::Palette256 playerPalette{}; std::vector dibPixels; std::vector viewPixels; @@ -139,6 +151,7 @@ void loadSceneAsync(HWND window, AppState& state) PostMessageW(window, sceneReadyMessage, 0, 0); return; } + const auto stagedItems = remorse::stageFixedMapItems(*map); const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath); const auto globObjects = remorse::loadGlobObjects(*globPath); @@ -148,6 +161,11 @@ void loadSceneAsync(HWND window, AppState& state) return; } auto collisionBodies = remorse::collectMapCollisionBodies(*map, *shapeTypes, *globObjects); + const auto usecodePath = remorse::resolveGameDataPath( + state.root, std::filesystem::path("USECODE") / "EUSECODE.FLX"); + auto usecodeArchive = usecodePath ? remorse::loadFlexArchive(*usecodePath) : std::nullopt; + const auto usecodeOwnerRows = usecodeArchive + ? remorse::loadUsecodeOwnerRows(*usecodeArchive) : std::nullopt; const auto animationPath = remorse::resolveGameDataPath( state.root, std::filesystem::path("STATIC") / "ANIM.DAT"); @@ -246,6 +264,11 @@ void loadSceneAsync(HWND window, AppState& state) state.playerWorld = spawn; state.playerCollisionBody = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]); state.collisionBodies = std::move(collisionBodies); + state.shapeTypes = *shapeTypes; + state.usecodeArchive = std::move(usecodeArchive); + if (usecodeOwnerRows) { + state.usecodeOwnerRows = *usecodeOwnerRows; + } state.minWorldX = minX; state.minWorldY = minY; state.maxWorldX = maxX; @@ -257,6 +280,9 @@ void loadSceneAsync(HWND window, AppState& state) state.runAnimation = *runAnimation; state.playerFrames = std::move(playerFrames); state.playerPalette = *palette; + if (stagedItems) { + state.stagedItems = std::move(*stagedItems); + } state.sceneLoaded = true; } } catch (const std::exception& error) { @@ -285,23 +311,23 @@ bool isKeyDown(int key) std::optional readMovementDirection() { - if (isKeyDown(VK_HOME) || isKeyDown(VK_NUMPAD7) || isKeyDown('Q')) return static_cast(12); - if (isKeyDown(VK_PRIOR) || isKeyDown(VK_NUMPAD9) || isKeyDown('E')) return static_cast(0); - if (isKeyDown(VK_END) || isKeyDown(VK_NUMPAD1) || isKeyDown('Z')) return static_cast(8); - if (isKeyDown(VK_NEXT) || isKeyDown(VK_NUMPAD3) || isKeyDown('C')) return static_cast(4); + if (isKeyDown(VK_HOME) || isKeyDown(VK_NUMPAD7) || isKeyDown('Q')) return remorse::controllerDirectionFromScan(0x47); + if (isKeyDown(VK_PRIOR) || isKeyDown(VK_NUMPAD9) || isKeyDown('E')) return remorse::controllerDirectionFromScan(0x49); + if (isKeyDown(VK_END) || isKeyDown(VK_NUMPAD1) || isKeyDown('Z')) return remorse::controllerDirectionFromScan(0x4f); + if (isKeyDown(VK_NEXT) || isKeyDown(VK_NUMPAD3) || isKeyDown('C')) return remorse::controllerDirectionFromScan(0x51); const bool up = isKeyDown(VK_UP) || isKeyDown('W') || isKeyDown(VK_NUMPAD8); const bool right = isKeyDown(VK_RIGHT) || isKeyDown('D') || isKeyDown(VK_NUMPAD6); const bool down = isKeyDown(VK_DOWN) || isKeyDown('S') || isKeyDown(VK_NUMPAD2); const bool left = isKeyDown(VK_LEFT) || isKeyDown('A') || isKeyDown(VK_NUMPAD4); - if (up && left) return static_cast(12); - if (up && right) return static_cast(0); - if (down && left) return static_cast(8); - if (down && right) return static_cast(4); - if (up) return static_cast(14); - if (right) return static_cast(2); - if (down) return static_cast(6); - if (left) return static_cast(10); + if (up && left) return remorse::controllerDirectionFromScan(0x47); + if (up && right) return remorse::controllerDirectionFromScan(0x49); + if (down && left) return remorse::controllerDirectionFromScan(0x4f); + if (down && right) return remorse::controllerDirectionFromScan(0x51); + if (up) return remorse::controllerDirectionFromScan(0x48); + if (right) return remorse::controllerDirectionFromScan(0x4d); + if (down) return remorse::controllerDirectionFromScan(0x50); + if (left) return remorse::controllerDirectionFromScan(0x4b); return std::nullopt; } @@ -488,7 +514,7 @@ void paintWindow(HWND window, AppState& state) } compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride); - RECT hud{0, 0, viewWidth, 62}; + RECT hud{0, 0, viewWidth, 80}; HBRUSH hudBrush = CreateSolidBrush(RGB(14, 24, 29)); FillRect(device, &hud, hudBrush); DeleteObject(hudBrush); @@ -510,7 +536,7 @@ void paintWindow(HWND window, AppState& state) HFONT hudFont = CreateFontW(-16, 0, 0, 0, FW_MEDIUM, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Consolas"); - RECT labelBounds{20, 0, viewWidth - 12, 36}; + RECT labelBounds{20, 0, viewWidth - 12, 30}; const int saved = SaveDC(device); SetBkMode(device, TRANSPARENT); SetTextColor(device, RGB(224, 229, 214)); @@ -528,9 +554,27 @@ void paintWindow(HWND window, AppState& state) : 0) << L" | WAKEUPS " << state.standWakeCount << L" | KEY EVENTS " << state.diagnosticKeyEvents; - RECT diagnosticsBounds{20, 36, viewWidth - 12, hud.bottom - 1}; + RECT diagnosticsBounds{20, 30, viewWidth - 12, 54}; SetTextColor(device, RGB(74, 207, 184)); DrawTextW(device, diagnostics.str().c_str(), -1, &diagnosticsBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); + const auto nearbyItem = remorse::nearestStagedFixedMapItem( + state.stagedItems, state.playerWorld.x, state.playerWorld.y, diagnosticItemRange); + if (state.diagnosticItem || nearbyItem) { + const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem; + std::wostringstream itemStatus; + itemStatus << L"MAP ITEM " << displayItem->itemNumber + << L" | SHAPE " << displayItem->data.shape + << L" | RELEASE REQUEST " << state.diagnosticReleaseEventItem + << L" | " << (state.diagnosticReleaseBodyBytes != 0 + ? widen(state.diagnosticReleaseClass) + L" SCRIPT " + std::to_wstring(state.diagnosticReleaseBodyBytes) + L" BYTES (NOT RUN)" + : L"NO RELEASE SCRIPT") + << L" | PROCESS " << (state.diagnosticItemCompleted ? L"DONE" : + state.diagnosticItemProcessId != 0 ? L"QUEUED" : + displayItem->itemNumber > remorse::ProcessKernel::maxTrackedItemNumber ? L"ITEM OUT OF RANGE" : + !remorse::itemGrabCanCreateProcess(*displayItem) ? L"ITEM FLAG BLOCKS" : L"F: TEST RELEASE"); + RECT itemBounds{20, 54, viewWidth - 12, hud.bottom - 1}; + DrawTextW(device, itemStatus.str().c_str(), -1, &itemBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); + } RestoreDC(device, saved); DeleteObject(hudFont); @@ -567,14 +611,38 @@ void updatePlayer(HWND window, AppState& state) state.diagnosticKernel.deliverSystemTimerEvent(); const bool wasSleeping = (state.diagnosticStand->base.bytes[0x19] & 0x10) != 0; const remorse::u32 previousSleepStart = standSleepStart(*state.diagnosticStand); - state.diagnosticKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& entry, void* context) { + state.diagnosticKernel.runTimedSchedulerPass(state.diagnosticKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& entry, void* context) { auto& app = *static_cast(context); if (&entry == &app.diagnosticStand->base) { remorse::StandProcess::run(entry, [](const remorse::EntityDispatchEntryBase&, void*) { return false; }, nullptr, app.diagnosticKernel.systemTimerTick()); + } else if (entry.bytes[0] == 0x2f && entry.bytes[1] == 0x10) { + remorse::ItemProcess::run(entry, app.diagnosticKernel, app.diagnosticGroupCounts, + [](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* releaseContext) { + auto& app = *static_cast(releaseContext); + app.diagnosticReleaseEventItem = itemNumber; + if (app.diagnosticItem && app.usecodeArchive && + app.diagnosticItem->data.shape < app.shapeTypes.size()) { + const auto& item = *app.diagnosticItem; + const remorse::UsecodeItemIdentity identity{item.itemNumber, item.data.shape, + item.data.flags, item.data.quality, app.shapeTypes[item.data.shape].family, false}; + const remorse::UsecodeClassBases bases{0, 0x800, 0x900}; + const auto eligible = remorse::selectEligibleUsecodeEvent(*app.usecodeArchive, + app.usecodeOwnerRows, identity, bases, eventMask, eventId); + if (eligible) { + app.diagnosticReleaseClass = eligible->className; + app.diagnosticReleaseBodyBytes = eligible->body.bytes.size(); + } + } + }, &app); } - }, &state, state.diagnosticKernel.systemTimerTick()); + }, &state); + state.diagnosticKernel.refreshActiveGroup(state.diagnosticGroupCounts); + if (state.diagnosticItemProcessId != 0 && + state.diagnosticKernel.processAt(state.diagnosticItemProcessId) == nullptr) { + state.diagnosticItemCompleted = true; + } if (wasSleeping && standSleepStart(*state.diagnosticStand) != previousSleepStart) { ++state.standWakeCount; } @@ -656,6 +724,26 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA updatePlayer(window, *state); } return 0; + case WM_KEYDOWN: + if (wParam == 'F') { + std::lock_guard lock(state->sceneMutex); + if (state->sceneLoaded && state->scene && !state->diagnosticItemCompleted && + state->diagnosticItemProcessId == 0) { + state->diagnosticItem = remorse::nearestStagedFixedMapItem( + state->stagedItems, state->playerWorld.x, state->playerWorld.y, diagnosticItemRange); + } + if (state->diagnosticItem && state->diagnosticItemProcessId == 0 && + state->diagnosticItem->itemNumber <= remorse::ProcessKernel::maxTrackedItemNumber && + remorse::itemGrabCanCreateProcess(*state->diagnosticItem)) { + auto* itemProcess = state->diagnosticKernel.createItemProcess( + state->diagnosticKernel.activeGroup(), state->diagnosticItem->itemNumber, + state->diagnosticGroupCounts); + state->diagnosticItemProcessId = static_cast( + itemProcess->bytes[2] | (static_cast(itemProcess->bytes[3]) << 8)); + InvalidateRect(window, nullptr, FALSE); + } + } + return 0; case WM_CHAR: if (wParam > 0 && wParam <= 0xff) { remorse::KeyEvent lastEvent{}; @@ -677,9 +765,10 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA case WM_PAINT: paintWindow(window, *state); return 0; - case sceneReadyMessage: + case sceneReadyMessage: { InvalidateRect(window, nullptr, FALSE); return 0; + } case WM_DESTROY: KillTimer(window, timerId); if (state->sceneThread.joinable()) { diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index d844f3c..0e24243 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -33,6 +33,15 @@ int main() remorse::EntityDispatchEntry::setEventTypeChecked(entry, 0x00f2); assert(entry.bytes[0x06] == 0xf2); assert(entry.bytes[0x07] == 0x00); + remorse::EntityDispatchEntry::setEventTypeChecked(entry, 0x0fff); + assert(entry.bytes[0x06] == 0xff && entry.bytes[0x07] == 0x0f); + bool invalidEventType = false; + try { + remorse::EntityDispatchEntry::setEventTypeChecked(entry, 0x1000); + } catch (const std::invalid_argument&) { + invalidEventType = true; + } + assert(invalidEventType && entry.bytes[0x06] == 0 && entry.bytes[0x07] == 0x10); remorse::EntityDispatchEntry::sleep(entry, 0x12345678, 0x0001003c); assert(entry.bytes[0x18] == 0x01 && entry.bytes[0x19] == 0x10); @@ -63,8 +72,34 @@ int main() assert(rejected && entry.bytes[0x08] == 4 && groupCounts[4] == 1); } - remorse::EntityDispatchEntry::incrementGroupId(entry); - assert(entry.bytes[0x08] == 5); + remorse::ProcessKernel incrementKernel; + incrementKernel.setActiveGroup(4); + remorse::EntityDispatchEntry::incrementGroupId(entry, incrementKernel, groupCounts); + assert(entry.bytes[0x08] == 5 && groupCounts[4] == 0 && groupCounts[5] == 1); + assert(incrementKernel.activeGroup() == 5 && incrementKernel.groupSelectionPending()); + bool wrongActiveGroup = false; + try { + remorse::EntityDispatchEntry::incrementGroupId(entry, incrementKernel, groupCounts); + } catch (const std::invalid_argument&) { + wrongActiveGroup = true; + } + assert(!wrongActiveGroup && entry.bytes[0x08] == 6 && incrementKernel.activeGroup() == 6); + incrementKernel.setActiveGroup(7); + try { + remorse::EntityDispatchEntry::incrementGroupId(entry, incrementKernel, groupCounts); + } catch (const std::invalid_argument&) { + wrongActiveGroup = true; + } + assert(wrongActiveGroup && entry.bytes[0x08] == 6 && groupCounts[6] == 1); + remorse::EntityDispatchEntry::setGroupId(entry, 29, groupCounts); + incrementKernel.setActiveGroup(29); + bool groupLimitReached = false; + try { + remorse::EntityDispatchEntry::incrementGroupId(entry, incrementKernel, groupCounts); + } catch (const std::invalid_argument&) { + groupLimitReached = true; + } + assert(groupLimitReached && entry.bytes[0x08] == 29 && groupCounts[29] == 1); remorse::ProcessKernel kernel; kernel.setLastAllocationSize(sizeof(entry)); @@ -171,8 +206,43 @@ int main() } assert(exhausted && fullKernel.processCount() == 1020 && fullGroups[2] == 0); + remorse::ProcessKernel groupKernel; + remorse::u16 groupTable[32]{}; + for (int index = 0; index < 3; ++index) { + groupKernel.createProcess(1, groupTable); + } + groupKernel.createProcess(2, groupTable); + groupKernel.createProcess(3, groupTable); + groupKernel.createProcess(30, groupTable); + groupKernel.createProcess(31, groupTable); + groupKernel.refreshActiveGroup(groupTable); + assert(groupKernel.activeGroup() == 1 && !groupKernel.groupSelectionPending()); + groupKernel.setActiveGroup(4); + assert(groupKernel.activeGroup() == 4 && groupKernel.groupSelectionPending()); + groupKernel.refreshActiveGroup(groupTable); + assert(groupKernel.activeGroup() == 3 && !groupKernel.groupSelectionPending()); + groupKernel.terminateProcess(4, groupTable); + groupKernel.clearTerminatedProcesses(); + groupKernel.refreshActiveGroup(groupTable); + assert(groupKernel.activeGroup() == 2 && !groupKernel.groupSelectionPending()); + for (remorse::u8 invalidGroup : {remorse::u8{0}, remorse::u8{32}}) { + bool rejected = false; + try { + groupKernel.setActiveGroup(invalidGroup); + } catch (const std::invalid_argument&) { + rejected = true; + } + assert(rejected && groupKernel.activeGroup() == 2 && !groupKernel.groupSelectionPending()); + } + groupKernel.setActiveGroup(30); + groupKernel.refreshActiveGroup(groupTable); + assert(groupKernel.activeGroup() == 30 && groupKernel.groupSelectionPending()); + remorse::ProcessKernel scheduler; remorse::u16 scheduledGroups[32]{}; + assert(scheduler.activeGroup() == 1 && !scheduler.groupSelectionPending()); + scheduler.setActiveGroup(1); + assert(!scheduler.groupSelectionPending()); auto* otherGroup = scheduler.createProcess(1, scheduledGroups); auto* matching = scheduler.createProcess(2, scheduledGroups); auto* syncingProcess = scheduler.createProcess(2, scheduledGroups); @@ -185,6 +255,7 @@ int main() }; scheduler.scanRunnableProcesses(2, recordRun, &ran); assert((ran == std::vector{1, 3})); + assert(scheduler.activeGroup() == 2 && scheduler.groupSelectionPending()); assert(syncingProcess->bytes[0x16] == 0 && otherGroup->bytes[0x16] == 0); ran.clear(); matching->bytes[0x16] = 1; @@ -246,10 +317,37 @@ int main() assert(sleeper->bytes[offset] == 0); } + remorse::ProcessKernel timedPassKernel; + remorse::u16 timedPassGroups[32]{}; + auto* timedPassSleeper = timedPassKernel.createProcess(1, timedPassGroups); + timedPassKernel.createSystemTimerProcess(1, timedPassGroups); + timedPassKernel.deliverSystemTimerEvent(); + remorse::EntityDispatchEntry::sleep(*timedPassSleeper, 1, 1); + std::vector timedPassRuns; + const auto advanceTimer = [](void* context) { + static_cast(context)->deliverSystemTimerEvent(); + }; + assert(timedPassKernel.runTimedSchedulerPass(1, recordRun, &timedPassRuns, + advanceTimer, &timedPassKernel) == 1); + assert(timedPassRuns.empty() && timedPassKernel.systemTimerTick() == 2); + assert(timedPassKernel.runTimedSchedulerPass(1, recordRun, &timedPassRuns, + advanceTimer, &timedPassKernel) == 1); + assert(timedPassRuns.empty() && timedPassKernel.systemTimerTick() == 3); + assert(timedPassKernel.runTimedSchedulerPass(1, recordRun, &timedPassRuns, + advanceTimer, &timedPassKernel) == 1); + assert((timedPassRuns == std::vector{0})); + remorse::ProcessKernel standKernel; remorse::u16 standGroups[32]{}; standKernel.createProcess(2, standGroups); assert(!standKernel.itemHasProcess(0x1234) && !standKernel.itemHasProcess(0x1235)); + bool oversizedStandRejected = false; + try { + standKernel.createStandProcess(2, 0x2400, standGroups); + } catch (const std::out_of_range&) { + oversizedStandRejected = true; + } + assert(oversizedStandRejected && standGroups[2] == 1 && standKernel.processCount() == 1); auto* standEntry = standKernel.createStandProcess(2, 0x1234, standGroups); auto* standing = &standEntry->base; assert(standKernel.processAt(1) == standing && standKernel.allocationSizeAt(1) == 0x42); @@ -260,6 +358,72 @@ int main() assert(standing->bytes[0x17] == 0x03 && standEntry->extra[0] == 0x01 && standEntry->extra[1] == 0x01); assert(standEntry->extra[0x0e] == 0x34 && standEntry->extra[0x0f] == 0x12); assert(standKernel.itemHasProcess(0x1234) && !standKernel.itemHasProcess(0x1235)); + + remorse::ProcessKernel cachedItemKernel; + remorse::u16 cachedItemGroups[32]{}; + for (int index = 0; index < 3; ++index) { + cachedItemKernel.createProcess(1, cachedItemGroups); + } + auto* itemProcess = cachedItemKernel.createItemProcess(1, 0x100, cachedItemGroups); + assert(cachedItemKernel.processAt(3) == itemProcess && cachedItemKernel.allocationSizeAt(3) == 0x32); + assert(std::strcmp(cachedItemKernel.processNameAt(3), "ItemProcess") == 0); + assert(itemProcess->bytes[0] == 0x2f && itemProcess->bytes[1] == 0x10); + assert(itemProcess->bytes[4] == 0 && itemProcess->bytes[5] == 1); + assert(itemProcess->bytes[6] == 0xf1 && itemProcess->bytes[7] == 0); + assert(cachedItemKernel.itemHasProcess(0x100) && cachedItemKernel.itemProcessTypes(0x100) == 2); + assert(cachedItemGroups[1] == 4); + auto* sharedItemProcess = cachedItemKernel.createItemProcess(1, 0x100, cachedItemGroups); + assert(cachedItemKernel.itemProcessTypes(0x100) == 2); + cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x101); + assert(cachedItemKernel.itemHasProcess(0x100) && cachedItemKernel.itemHasProcess(0x101)); + assert(cachedItemKernel.itemProcessTypes(0x100) == 2 && cachedItemKernel.itemProcessTypes(0x101) == 2); + cachedItemKernel.setProcessEventTypeChecked(*sharedItemProcess, 0xf2); + assert(cachedItemKernel.itemProcessTypes(0x101) == 4); + cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0); + assert(!cachedItemKernel.itemHasProcess(0x101) && cachedItemKernel.itemProcessTypes(0x101) == 0); + cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x102); + assert(cachedItemKernel.itemHasProcess(0x102) && cachedItemKernel.itemProcessTypes(0x102) == 4); + cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x23ff); + assert(cachedItemKernel.itemHasProcess(0x23ff) && cachedItemKernel.itemProcessTypes(0x23ff) == 4); + bool invalidItemNumber = false; + try { + cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x2400); + } catch (const std::out_of_range&) { + invalidItemNumber = true; + } + assert(invalidItemNumber && cachedItemKernel.itemHasProcess(0x23ff)); + assert(!cachedItemKernel.itemHasProcess(0x2400) && cachedItemKernel.itemProcessTypes(0x2400) == 0); + cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x102); + cachedItemKernel.terminateProcess(4, cachedItemGroups); + cachedItemKernel.clearTerminatedProcesses(); + assert(!cachedItemKernel.itemHasProcess(0x102) && cachedItemKernel.itemProcessTypes(0x102) == 0); + bool missingReleaseRejected = false; + try { + remorse::ItemProcess::run(*itemProcess, cachedItemKernel, cachedItemGroups, nullptr, nullptr); + } catch (const std::invalid_argument&) { + missingReleaseRejected = true; + } + assert(missingReleaseRejected && cachedItemKernel.itemHasProcess(0x100) && cachedItemGroups[1] == 4); + remorse::u16 releasedItem = 0; + struct ItemRunContext { + remorse::ProcessKernel* kernel; + remorse::u16 (*groups)[32]; + remorse::u16* released; + } itemRunContext{&cachedItemKernel, &cachedItemGroups, &releasedItem}; + cachedItemKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& state = *static_cast(context); + if (process.bytes[0] == 0x2f && process.bytes[1] == 0x10) { + remorse::ItemProcess::run(process, *state.kernel, *state.groups, + [](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* result) { + assert(eventMask == 0x200 && eventId == 9); + *static_cast(result) = itemNumber; + }, + state.released); + } + }, &itemRunContext); + assert(releasedItem == 0x100 && !cachedItemKernel.itemHasProcess(0x100)); + assert(cachedItemKernel.itemProcessTypes(0x100) == 0); + assert(cachedItemKernel.processAt(3) == nullptr && cachedItemGroups[1] == 3); bool itemTeardownRejected = false; try { standKernel.terminateProcess(1, standGroups); diff --git a/rebuild/remorse/tests/file_system_tests.cpp b/rebuild/remorse/tests/file_system_tests.cpp index 86d6735..0e0614e 100644 --- a/rebuild/remorse/tests/file_system_tests.cpp +++ b/rebuild/remorse/tests/file_system_tests.cpp @@ -29,6 +29,10 @@ int main(int argc, char** argv) } } #ifdef _DEBUG + if (argc == 2 && std::strcmp(argv[1], "--assert-probe") == 0) { + assert(false && "diagnostic assert probe"); + return 0; + } _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_WNDW); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW); #endif @@ -44,52 +48,63 @@ int main(int argc, char** argv) if (GetModuleFileNameW(nullptr, executable, MAX_PATH) == 0) { return 1; } - std::wstring commandLine = L"\"" + std::wstring(executable) + L"\" --crash-probe"; - SECURITY_ATTRIBUTES pipeSecurity{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE}; - HANDLE readPipe = nullptr; - HANDLE writePipe = nullptr; - if (!CreatePipe(&readPipe, &writePipe, &pipeSecurity, 0)) { - return 1; - } - if (!SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0)) { - CloseHandle(readPipe); + auto runProbe = [&](const wchar_t* option, const char* expectedOutput, bool expectExitOne) { + std::wstring commandLine = L"\"" + std::wstring(executable) + L"\" " + option; + SECURITY_ATTRIBUTES pipeSecurity{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE}; + HANDLE readPipe = nullptr; + HANDLE writePipe = nullptr; + if (!CreatePipe(&readPipe, &writePipe, &pipeSecurity, 0)) { + return false; + } + if (!SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0)) { + CloseHandle(readPipe); + CloseHandle(writePipe); + return false; + } + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + startup.dwFlags = STARTF_USESTDHANDLES; + startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + startup.hStdOutput = writePipe; + startup.hStdError = writePipe; + PROCESS_INFORMATION child{}; + if (!CreateProcessW(nullptr, commandLine.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW, + nullptr, nullptr, &startup, &child)) { + CloseHandle(readPipe); + CloseHandle(writePipe); + return false; + } CloseHandle(writePipe); - return 1; - } - STARTUPINFOW startup{}; - startup.cb = sizeof(startup); - startup.dwFlags = STARTF_USESTDHANDLES; - startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); - startup.hStdOutput = writePipe; - startup.hStdError = writePipe; - PROCESS_INFORMATION child{}; - if (!CreateProcessW(nullptr, commandLine.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW, - nullptr, nullptr, &startup, &child)) { + const DWORD waitResult = WaitForSingleObject(child.hProcess, 5000); + if (waitResult == WAIT_TIMEOUT) { + TerminateProcess(child.hProcess, 2); + WaitForSingleObject(child.hProcess, INFINITE); + } + char buffer[512]; + DWORD count = 0; + std::string crashOutput; + while (ReadFile(readPipe, buffer, sizeof(buffer), &count, nullptr) && count != 0) { + crashOutput.append(buffer, count); + } + DWORD exitCode = 0; + const BOOL gotExitCode = GetExitCodeProcess(child.hProcess, &exitCode); CloseHandle(readPipe); - CloseHandle(writePipe); - return 1; - } - CloseHandle(writePipe); - const DWORD waitResult = WaitForSingleObject(child.hProcess, 5000); - if (waitResult == WAIT_TIMEOUT) { - TerminateProcess(child.hProcess, 2); - WaitForSingleObject(child.hProcess, INFINITE); - } - char buffer[512]; - DWORD count = 0; - std::string crashOutput; - while (ReadFile(readPipe, buffer, sizeof(buffer), &count, nullptr) && count != 0) { - crashOutput.append(buffer, count); - } - DWORD exitCode = 0; - const BOOL gotExitCode = GetExitCodeProcess(child.hProcess, &exitCode); - CloseHandle(readPipe); - CloseHandle(child.hThread); - CloseHandle(child.hProcess); - if (!gotExitCode || waitResult != WAIT_OBJECT_0 || exitCode != 1 || - crashOutput.find("Unhandled C++ exception: diagnostic probe") == std::string::npos) { - std::fprintf(stderr, "Crash probe wait=%lu exit=0x%08lX output=%s\n", - waitResult, exitCode, crashOutput.c_str()); + CloseHandle(child.hThread); + CloseHandle(child.hProcess); + const bool passed = gotExitCode && waitResult == WAIT_OBJECT_0 && + (expectExitOne ? exitCode == 1 : exitCode != 0) && + crashOutput.find(expectedOutput) != std::string::npos; + if (!passed) { + std::fprintf(stderr, "Probe %ls wait=%lu exit=0x%08lX output=%s\n", + option, waitResult, exitCode, crashOutput.c_str()); + } + return passed; + }; + if (!runProbe(L"--crash-probe", "Unhandled C++ exception: diagnostic probe", true) +#ifdef _DEBUG + || !runProbe(L"--assert-probe", "diagnostic assert probe", false) +#endif + ) { return 1; } #endif diff --git a/rebuild/remorse/tests/fixed_map_tests.cpp b/rebuild/remorse/tests/fixed_map_tests.cpp index fcc14f3..37f5f37 100644 --- a/rebuild/remorse/tests/fixed_map_tests.cpp +++ b/rebuild/remorse/tests/fixed_map_tests.cpp @@ -1,8 +1,11 @@ +#include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" #include "remorse/fixed_map.h" +#include "remorse/type_flags.h" #include #include +#include int main() { @@ -31,6 +34,126 @@ int main() } assert(foundNonEmptyMap); + const auto retailMap = remorse::loadFixedMap(*archive, 1); + assert(retailMap.has_value() && !retailMap->entries.empty()); + const auto cachedItems = remorse::stageFixedMapItems(*retailMap); + assert(cachedItems.has_value() && !cachedItems->empty()); + assert(cachedItems->back().itemNumber <= remorse::ProcessKernel::maxTrackedItemNumber); + const auto typeFlagPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); + const auto typeFlags = typeFlagPath ? remorse::loadTypeFlags(*typeFlagPath) : std::nullopt; + assert(typeFlags && cachedItems->front().data.shape < typeFlags->size()); + const auto& originShape = (*typeFlags)[cachedItems->front().data.shape]; + auto origin = cachedItems->front(); + origin.data.z = 80; + auto candidate = origin; + candidate.itemNumber = static_cast(origin.itemNumber + 1); + candidate.data.z = static_cast(origin.data.z + (originShape.z == 0 && (originShape.flags & 1) == 0 ? 1 : originShape.z * 8)); + remorse::ShapeTypeInfo footprint{0, 0, 1, 1, 0, 0}; + assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 1); + assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 2) == 0); + candidate.data.z = 79; + assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 2); + remorse::ShapeTypeInfo flatShape{0, 1, 1, 1, 0, 0}; + candidate.data.z = 80; + assert(remorse::classifyItemFindZMatch(origin, flatShape, candidate, flatShape, 3) == 1); + candidate.data.x = static_cast(origin.data.x + 16); + assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 0); + const auto retailSearchArea = remorse::itemFindAreaAroundItem(cachedItems->front(), originShape); + const auto retailSearchBlocks = remorse::itemFindBlockOrder(retailSearchArea); + assert(!retailSearchBlocks.empty() && retailSearchBlocks.front() == + (retailSearchArea.minX >> 9) * 0x40 + (retailSearchArea.minY >> 9)); + origin.data.x = 511; + origin.data.y = 511; + const auto crossingArea = remorse::itemFindAreaAroundItem(origin, footprint); + assert(crossingArea.minX == 496 && crossingArea.minY == 496); + assert(crossingArea.maxX == 767 && crossingArea.maxY == 767); + assert((remorse::itemFindBlockOrder(crossingArea) == std::vector{0, 64, 1, 65})); + origin.data.x = 0; + origin.data.y = 0; + const auto edgeArea = remorse::itemFindAreaAroundItem(origin, footprint); + assert(edgeArea.minX == 0 && edgeArea.minY == 0); + assert((remorse::itemFindBlockOrder(edgeArea) == std::vector{0})); + candidate.itemNumber = 0; + assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 0); + assert(cachedItems->front().recordIndex < retailMap->entries.size()); + for (const auto& item : *cachedItems) { + const auto& record = retailMap->entries[item.recordIndex]; + assert(record.shape != 0 && (record.flags & 8) == 0); + assert(item.data.x == record.x / 2 && item.data.y == record.y / 2); + assert(item.data.shape == record.shape); + assert(item.data.npcNumber == record.npcNumber); + assert(item.data.flags == (record.flags & ~1u)); + } + remorse::ProcessKernel retailKernel; + remorse::u16 retailGroups[32]{}; + for (int index = 0; index < 3; ++index) { + retailKernel.createProcess(1, retailGroups); + } + const auto retailItemNumber = cachedItems->front().itemNumber; + auto* retailProcess = retailKernel.createItemProcess(1, retailItemNumber, retailGroups); + assert(retailProcess->bytes[4] == static_cast(retailItemNumber)); + assert(retailKernel.itemHasProcess(retailItemNumber)); + struct RetailScan { + remorse::ProcessKernel* kernel; + remorse::u16 (*groups)[32]; + remorse::u16 released = 0; + int releaseCount = 0; + } retailScan{&retailKernel, &retailGroups}; + auto runRetailItem = [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& scan = *static_cast(context); + if (process.bytes[0] == 0x2f && process.bytes[1] == 0x10) { + remorse::ItemProcess::run(process, *scan.kernel, *scan.groups, + [](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* releaseContext) { + assert(eventMask == 0x200 && eventId == 9); + auto& result = *static_cast(releaseContext); + result.released = itemNumber; + ++result.releaseCount; + }, &scan); + } + }; + retailKernel.scanRunnableProcesses(1, runRetailItem, &retailScan, 1); + retailKernel.scanRunnableProcesses(1, runRetailItem, &retailScan, 2); + assert(retailScan.released == retailItemNumber && retailScan.releaseCount == 1); + assert(retailKernel.processAt(3) == nullptr && !retailKernel.itemHasProcess(retailItemNumber)); + assert(retailGroups[1] == 3); + remorse::FixedMap stagedMap; + stagedMap.entries.resize(4); + stagedMap.entries[1].shape = 16; + stagedMap.entries[2].shape = 16; + stagedMap.entries[2].flags = 8; + stagedMap.entries[3].shape = 16; + stagedMap.entries[3].flags = 1; + auto stagedItems = remorse::stageFixedMapItems(stagedMap); + assert(stagedItems && stagedItems->size() == 2); + assert((*stagedItems)[0].recordIndex == 1 && (*stagedItems)[0].itemNumber == 0x100); + assert((*stagedItems)[1].recordIndex == 3 && (*stagedItems)[1].itemNumber == 0x102); + assert((*stagedItems)[1].data.flags == 0); + assert(remorse::itemGrabCanCreateProcess((*stagedItems)[0])); + (*stagedItems)[0].data.flags |= 0x02; + assert(!remorse::itemGrabCanCreateProcess((*stagedItems)[0])); + (*stagedItems)[0].data.x = 20; + (*stagedItems)[0].data.y = 10; + (*stagedItems)[1].data.x = 30; + (*stagedItems)[1].data.y = 10; + const auto nearby = remorse::nearestStagedFixedMapItem(*stagedItems, 59, 20, 16); + assert(nearby && nearby->itemNumber == 0x102); + assert(!remorse::nearestStagedFixedMapItem(*stagedItems, 100, 20, 16)); + assert(!remorse::nearestStagedFixedMapItem(*stagedItems, 60, 20, -1)); + remorse::FixedMap oversizedMap; + oversizedMap.entries.resize(0x2701); + for (auto& record : oversizedMap.entries) { + record.shape = 16; + } + assert(!remorse::stageFixedMapItems(oversizedMap).has_value()); + remorse::FixedMap widerCacheMap; + widerCacheMap.entries.resize(0x2301); + for (auto& record : widerCacheMap.entries) { + record.shape = 16; + } + const auto widerCacheItems = remorse::stageFixedMapItems(widerCacheMap); + assert(widerCacheItems && widerCacheItems->back().itemNumber == 0x2400); + assert(widerCacheItems->back().itemNumber > remorse::ProcessKernel::maxTrackedItemNumber); + const auto outOfRange = remorse::loadFixedMap(*archive, archive->mapCount); assert(!outOfRange.has_value()); return 0; diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index deadc46..dbb5900 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -1,5 +1,8 @@ #include "remorse/file_system.h" #include "remorse/flex_archive.h" +#include "remorse/fixed_map.h" +#include "remorse/type_flags.h" +#include "remorse/usecode_archive.h" #include #include @@ -23,5 +26,91 @@ int main() assert((*firstEntry)[1] == 'u'); assert((*firstEntry)[2] == 'm'); assert((*firstEntry)[3] == 'b'); + const auto usecodePath = remorse::resolveGameDataPath(*root, std::filesystem::path("USECODE") / "EUSECODE.FLX"); + assert(usecodePath); + const auto usecode = remorse::loadFlexArchive(*usecodePath); + assert(usecode); + const auto retailOwnerRows = remorse::loadUsecodeOwnerRows(*usecode); + assert(retailOwnerRows && retailOwnerRows->size() % 13 == 0); + const auto eventClass = remorse::loadUsecodeClass(*usecode, 0x361); + assert(eventClass && eventClass->name == "EVENT" && eventClass->codeBase == 0xd4); + const auto eventBody = remorse::readUsecodeEventBody(*eventClass, 0x0a); + assert(eventBody && eventBody->length == 0x1fd6 && eventBody->relativeOffset == 1); + assert(eventBody->bytes.size() == 0x1fd6 && eventBody->bytes.front() == eventClass->bytes[0xd4]); + assert(!remorse::readUsecodeEventBody(*eventClass, 0x20)); + assert(!remorse::loadUsecodeClass(*usecode, usecode->entryCount)); + auto truncated = *eventClass; + truncated.bytes.resize(truncated.codeBase + 1); + assert(!remorse::readUsecodeEventBody(truncated, 0x0a)); + auto invalidOffset = *eventClass; + invalidOffset.bytes[20 + 0x0a * 6 + 2] = 0; + assert(!remorse::readUsecodeEventBody(invalidOffset, 0x0a)); + const auto rechargeClass = remorse::loadUsecodeClass(*usecode, 0x138); + assert(rechargeClass && rechargeClass->name == "RECHFLNS"); + const auto releaseBody = remorse::readUsecodeEventBody(*rechargeClass, 9); + assert(releaseBody && releaseBody->length == 102 && releaseBody->relativeOffset == 0x256); + assert(remorse::ownerRowAllowsEvent(*retailOwnerRows, 0x138, 0x200)); + const remorse::UsecodeClassBases bases{0x200, 0x400, 0x600}; + remorse::UsecodeItemIdentity identity{7, 0x45, 0, 0x1278, 4, true}; + assert(remorse::selectUsecodeClassId(identity, bases) == 0x407); + identity.status = 2; + assert(remorse::selectUsecodeClassId(identity, bases) == 0x678); + identity.family = 0; + assert(remorse::selectUsecodeClassId(identity, bases) == 0x245); + identity.isNpc = false; + identity.status = 0; + assert(remorse::selectUsecodeClassId(identity, bases) == 0x245); + const auto fixedPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "FIXED.DAT"); + const auto flagsPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); + assert(fixedPath && flagsPath); + const auto fixedArchive = remorse::loadFixedMapArchive(*fixedPath); + const auto fixedMap = fixedArchive ? remorse::loadFixedMap(*fixedArchive, 1) : std::nullopt; + const auto typeFlags = remorse::loadTypeFlags(*flagsPath); + assert(fixedMap && typeFlags); + const auto stagedItems = remorse::stageFixedMapItems(*fixedMap); + assert(stagedItems && !stagedItems->empty()); + const auto& staged = stagedItems->front(); + assert(staged.data.shape < typeFlags->size()); + const remorse::UsecodeItemIdentity stagedIdentity{staged.itemNumber, staged.data.shape, + staged.data.flags, staged.data.quality, (*typeFlags)[staged.data.shape].family, false}; + const remorse::UsecodeClassBases retailBases{0, 0x800, 0x900}; + assert(remorse::selectUsecodeClassId(stagedIdentity, retailBases) == staged.data.shape); + const auto stagedClass = remorse::loadUsecodeClass(*usecode, + remorse::selectUsecodeClassId(stagedIdentity, retailBases)); + assert(!stagedClass); + assert(!remorse::ownerRowAllowsEvent(*retailOwnerRows, staged.data.shape, 0x200)); + assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + stagedIdentity, retailBases, 0x200, 9)); + bool foundStagedRelease = false; + for (const auto& item : *stagedItems) { + if (item.data.shape >= typeFlags->size()) { + continue; + } + const remorse::UsecodeItemIdentity mapItemIdentity{item.itemNumber, item.data.shape, + item.data.flags, item.data.quality, (*typeFlags)[item.data.shape].family, false}; + if (remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + mapItemIdentity, retailBases, 0x200, 9)) { + foundStagedRelease = true; + break; + } + } + assert(foundStagedRelease); + const remorse::UsecodeItemIdentity rechargeItem{0x100, 0x138, 0, 0, 0, false}; + const auto eligibleRelease = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + rechargeItem, retailBases, 0x200, 9); + assert(eligibleRelease && eligibleRelease->classId == 0x138 && + eligibleRelease->className == "RECHFLNS" && eligibleRelease->body.bytes.size() == 102); + assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + rechargeItem, retailBases, 0, 9)); + std::vector ownerRows(26); + ownerRows[13] = 0x00; + ownerRows[14] = 0x02; + ownerRows[16] = 0x01; + assert(remorse::ownerRowAllowsEvent(ownerRows, 1, 0x200)); + assert(remorse::ownerRowAllowsEvent(ownerRows, 1, 0x1000000)); + assert(!remorse::ownerRowAllowsEvent(ownerRows, 1, 0x400)); + assert(!remorse::ownerRowAllowsEvent(ownerRows, 0, 0x200)); + assert(!remorse::ownerRowAllowsEvent(ownerRows, 2, 0x200)); + assert(!remorse::ownerRowAllowsEvent(ownerRows, 1, 0)); return 0; } diff --git a/rebuild/remorse/tests/isometric_controls_tests.cpp b/rebuild/remorse/tests/isometric_controls_tests.cpp index 92f12d6..7c8032f 100644 --- a/rebuild/remorse/tests/isometric_controls_tests.cpp +++ b/rebuild/remorse/tests/isometric_controls_tests.cpp @@ -11,6 +11,12 @@ int main() assert(!remorse::controllerWalkRequested(0x40)); assert(remorse::controllerWalkRequested(0x41)); assert(remorse::controllerWalkRequested(0x42)); + constexpr remorse::u8 scans[] = {0x47, 0x48, 0x49, 0x4b, 0x4d, 0x4f, 0x50, 0x51}; + constexpr remorse::u8 directions[] = {12, 14, 0, 10, 2, 8, 6, 4}; + for (std::size_t index = 0; index < std::size(scans); ++index) { + assert(remorse::controllerDirectionFromScan(scans[index]) == directions[index]); + } + assert(!remorse::controllerDirectionFromScan(0x52)); constexpr remorse::s32 originX = 1024; constexpr remorse::s32 originY = 2048; const remorse::ScreenPoint origin = remorse::projectToScreen({originX, originY, 0}); diff --git a/rebuild/remorse/tests/test_crash_setup.cpp b/rebuild/remorse/tests/test_crash_setup.cpp new file mode 100644 index 0000000..e091eee --- /dev/null +++ b/rebuild/remorse/tests/test_crash_setup.cpp @@ -0,0 +1,11 @@ +#include "remorse/runtime.h" + +namespace { + +struct TestCrashSetup { + TestCrashSetup() { remorse::installCrashDiagnostics(); } +}; + +TestCrashSetup testCrashSetup; + +} // namespace \ No newline at end of file From b99fb59c125fe4a71867af733bf27466415e6ac7 Mon Sep 17 00:00:00 2001 From: Maddo Date: Sat, 26 Sep 2026 19:20:20 +0200 Subject: [PATCH 04/14] Enhance item handling and collision detection in remorse - Introduced new functionality for staging and managing fixed map items, including the ability to build block chains and find candidates for item interactions. - Updated the main application logic to utilize staged item block chains for improved item finding and grabbing mechanics. - Added weight attribute to shape type information, allowing for more nuanced item interactions based on weight. - Enhanced collision tests to cover new item handling scenarios, including gravity sweeps and item grabbing. - Implemented additional tests for entity dispatch entries and fixed map items to ensure robustness of item spawning and movement logic. - Improved type flags loading to validate weight against binary data, ensuring consistency in item attributes. --- docs/remorse-windows-rebuild-roadmap.md | 34 ++- rebuild/remorse/include/remorse/collision.h | 14 + .../include/remorse/entity_dispatch_entry.h | 18 ++ rebuild/remorse/include/remorse/fixed_map.h | 58 ++++ rebuild/remorse/include/remorse/type_flags.h | 1 + rebuild/remorse/src/collision.cpp | 29 ++ rebuild/remorse/src/entity_dispatch_entry.cpp | 133 ++++++++- rebuild/remorse/src/fixed_map.cpp | 263 ++++++++++++++++++ rebuild/remorse/src/main.cpp | 21 ++ rebuild/remorse/src/type_flags.cpp | 1 + rebuild/remorse/src/windowed_game_main.cpp | 12 +- rebuild/remorse/tests/collision_tests.cpp | 18 ++ .../tests/entity_dispatch_entry_tests.cpp | 172 ++++++++++++ rebuild/remorse/tests/fixed_map_tests.cpp | 200 +++++++++++++ rebuild/remorse/tests/type_flags_tests.cpp | 5 + 15 files changed, 961 insertions(+), 18 deletions(-) diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 75bc7f1..71349c9 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -316,18 +316,32 @@ The exported free-item path can issue `0x2400` from its `0x100..0x27ff` range, a `FUN_11d0_31cf` (`11d0:31cf`) is a caller of the scheduler scan at `11d0:0255`. Its one-pass prefix snapshots the registered SystemTimer, scans runnable processes, then invokes an optional callback. The host now compiles and calls that ordered pass from the harness and Windows diagnostic, returning elapsed ticks after the callback; tests verify that a timer event delivered by the callback cannot wake a process in the already-started scan. The original infinite loop, interval wait, DOS interrupt delivery, and live group-transition trace remain unported. -The first search-side dependency is compiled and tested in isolation: `ItemFind_10c0_14c9` (`10c0:14c9`) classifies a candidate as match type 1 (candidate Z equals origin top) or type 2 (candidate top equals origin Z), using TYPEFLAG-derived footprint widths and height, with type 1 taking priority. The host receives staged item fields and decoded shape metadata explicitly. This is **not** a port of `ItemFind_StartSearchAroundItem` (`10c0:0f73`) or the `10c0:1637` iterator; block-chain traversal, loop-script evaluation, and live item state are absent, so the classifier is not yet used to select a window item. +The first search-side dependency is compiled and tested in isolation: `ItemFind_10c0_14c9` (`10c0:14c9`) classifies a candidate as match type 1 (candidate Z equals origin top) or type 2 (candidate top equals origin Z), using TYPEFLAG-derived footprint widths and height, with type 1 taking priority. The host receives staged item fields and decoded shape metadata explicitly. This is **not** a complete port of `ItemFind_StartSearchAroundItem` (`10c0:0f73`) or the `10c0:1637` iterator; live item state and general loop-script evaluation remain absent, and the classifier is not used to select a window item. -The area-search setup now translates the rectangle around the origin (`10c0:0f73`), signed-coordinate normalization (`10c0:1099`), and `64 x 64` block order with 512-unit cells (`10c0:072e/0c50`). Tests cover a four-block crossing and a staged retail origin; the harness computes four candidate blocks for its first staged map-1 item. These are block indices only, not block heads, item-next chains, or script-filtered search results. +The area-search setup translates the rectangle around the origin (`10c0:0f73`), signed-coordinate normalization (`10c0:1099`), and `64 x 64` block order with 512-unit cells (`10c0:072e/0c50`). `ItemCache_10a8_00a0` (`10a8:00a0`) inserts directly placed records at the head of each block's `g_itemNext` chain, and the `10c0:1637` iterator follows that chain before advancing blocks. The staged host now reconstructs those heads/links from non-contained item records, rejects duplicate/out-of-range IDs and coordinates, and visits candidates in source block order. Synthetic tests distinguish chain order from record order; retail map 1 yields eight staged candidates in four search blocks around the first item. + +A separate diagnostic applies the exported Z/footprint classifier in chain order, yielding one script-free match for the retail origin with both Z flags enabled. Live `Item_Grab` (`10a0:2970`) pushes script pointer `DS:102d`, script length **1**, and Z flags **3**; callee `10c0:0f73` reads the flags at `[BP+0x12]`, correcting misleading export parameter names. The byte at `DS:102d` is `$`, which selects the `0x5000` fast iterator in `ItemFind_AreaSearch2` (`10c0:1099`). Live `10c8:0385` walks item-next links and X-first blocks, accepting only candidates whose X/Y coordinates lie inside the inclusive search rectangle, before the Z classifier. The host's bounded `Item_Grab` search applies these gates to staged, directly placed items; a test excludes an out-of-rectangle item whose footprint would otherwise pass. Retail map 1 yields one candidate for its first staged item. + +Contained placement has a separate source-derived diagnostic: for nonzero maps, nonempty contained records consume free IDs, encode nesting depth in the fixed-record X field, ascend the parent link when depth falls, and append children only to container/monster-egg families (`10a8:05e3`, `10a8:2533`, `10a0:0e32`). Synthetic nested/sibling and invalid-parent tests pass; retail map 1 contains no nonzero-shape contained records, so it cannot verify those links. The stage is not a live container cache or a runtime ID-order trace. The shape loader exposes TYPEFLAG row byte 7 as weight, and the `Item_Fall` (`1038:1334`) gate requires a drawable, nonzero-weight shape. The action planner preserves `Item_Grab`'s type-1 fall versus type-2 flag-checked process decision in source order; the first retail origin produces zero actions. + +The bounded staged dispatcher can now issue those actions against the host process kernel. `Process_GetProcessForItemAndType` (`11d0:13a4`) scans live slots from 3, ignores terminated entries, and supports item/type wildcards; the host mirrors those rules. `Item_Hurl` (`1038:12a6`) reuses an existing type-`0x203` gravity process and adds velocity, or creates a `0x42`-byte process (`1038:0395`) with zero velocity, gravity 2, and a 20-tick sleep for a fall request. Tests cover both branches, duplicate item-process requests, strict wake, ownership and ID-limit rejection, and teardown/reuse. Staged dispatch rejects any out-of-range action before starting; the Windows `F` key is still a separate release fixture. A host-owned `LiveFixedMapItems` copy now supports ID lookup, bounded position changes, and `Item_Grab` dispatch against current item positions; the window owns this copy for nearby-item lookup. `Item_LegalMoveToPointWithCollisionInfo` (`10a0:1841`) calls `Item_Grab` before `AreaSearch_CollideMove` on its successful path; `moveApprovedItem` preserves that ordering once a caller has approved the move, and tests distinguish old-position requests from post-move search. Synthetic move/dispatch and retail-map ownership tests pass. This is not the original item cache, does not yet provide a legal-move collision event or update rendered sprites, and does not include contained items. `runUnobstructedGravity` now moves an owned item and advances/sleeps its owned process in the nonzero-vertical-speed branch after explicit caller-supplied approval of the full pre-sweep target. A refused or missing sweep makes no mutation; tests cover both paths. This does not execute the zero-speed fall/`Item_Grab` branch, process collision responses, map fast-area gate, or an automatic scheduler tick. The original `AreaSearch_SweepTestItem` (`10e0:1151`) forwards into `AreaSearch_SweepTestPt` (`10e0:0b39`), which requires fast-area map blocks, item iteration, and resolved collision points absent from the host's boolean-only sweep. DOSBox-X is now installed at `C:\DOSBox-X`, but its interactive debugger has not produced a retail map-load or ItemFind trace; runtime IDs, parents, and first/next search behavior still lack original-execution trace parity. + +The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied, newly allocated item IDs can also be inserted at a block head with duplicate and placement guards. Focused tests verify process request order for moved and inserted items and the Z value; the host still lacks free-ID allocation, fast-area, viewport, and contained-item side effects. + +The supported horizontal `GravityProcess_Run` path now issues `Item_Grab` at the old item position when Z speed is zero and X/Y speed is nonzero, then asks the injected sweep to approve movement. As in the source order, a refused sweep can leave a newly requested item process behind while the item stays put. The earlier no-mutation guarantee for a refused sweep applies only to the nonzero-Z path, which does not issue that request. The stationary zero-speed fall search, collision response, and automatic scheduler dispatch are still unported; a caller must provide shapes, group counts, and the sweep decision for this host-only branch. + +The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. Tests cover combined and Z-only out-of-range targets. It is not yet the sweep's fast-area, item-iteration, or collision-resolution stage, and the gravity runner still requires an explicit approved sweep callback. + +Original DOS debugging and runtime verification are postponed indefinitely until requested again. The DOSBox-X debugger session has been stopped; do not treat a live trace as a prerequisite for the source-port work below. Keep unverified parity claims labeled as such. Next source-port checks, in call-chain order: -1. Check the live allocator/process pair at the `0x23ff/0x2400` item boundary before widening process lookup tables or changing the guard. -2. Compare timed scheduler snapshots, post-scan callbacks, and active-group transitions with a live runtime trace; port the interval wait only behind a host timing boundary. -3. Reconstruct block heads and `g_itemNext` chains for staged retail items, including insertion order and contained-item handling, before consuming the computed search blocks. -4. Recover the `Item_Grab` loop-script predicate and the `10c0:1637` iterator before connecting the isolated Z/footprint classifier to item search. -5. Trace and port `Item_Fall` (`1038:1334`) for search-result type 1, keeping it separate from process creation. -6. Wire `Item_Grab` (`10a0:2970`) to the recovered search and per-item status check, then compare requested process IDs against a live trace. +1. Keep the `0x23ff/0x2400` process item boundary until source-derived allocation limits support changing it; do not infer a wider live table from staged map IDs. +2. Port the remaining scheduler interval/group transitions behind host timing boundaries using static code evidence, with runtime parity explicitly deferred. +3. Port original free-ID allocation and contained-item ownership, and connect the caller-supplied live insert path to those allocation events. +4. Port the area sweep's fast-area and item-collision resolution, including failed directions and resolved points, before enabling collision-driven movement. +5. Port the `GravityProcess_Run` area sweep, collision responses, and item-cache position/status writes to make created gravity entries move real items after their sleep. +6. Connect the approved-move `Item_Grab` path to a ported `Item_LegalMoveToPointWithCollisionInfo` sweep and item-cache lifecycle, without changing the separate Windows `F` release fixture. 7. Lift `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`) and its interpreter initialization; keep release event-body lookup diagnostic until the VM executes it. ## First Interactive Windows Game Shell @@ -350,11 +364,11 @@ The diagnostic kernel also registers a partial KeyboardProcess and KeyDaemon at The Phase 4 diagnostic now stages directly placed, nonzero-shape `FIXED.DAT` records into item-numbered state using the initial free-list head `0x100` and capacity `0x2700` from `ItemCache_InitAndLoadFixedDat` (`10a8:163a`). It skips zero-shape records, accounts for contained records consuming an ID without staging them as world items, and clears the status low bit for directly placed records as `ItemCache_10a8_00a0` does. Map 1 has 7,547 source records; the harness constructs an `ItemProcess` for the first eligible staged record (shape 16, diagnostic ID 256), advances a scheduler tick, records the `UC_Release` request, and verifies the process is removed. The window waits for `F` near a staged item before scheduling the one-shot path and showing its result on a separate diagnostic HUD row. Retail-data and two-tick regression tests check shape/record provenance, release-request count, process removal, and item-presence/group-count cleanup. -This is an integration checkpoint, **not the Phase 4 exit criterion or a playable interaction**: the host starts this item process as a diagnostic fixture, not via the original `Item_Grab`/search trigger; it selects eligible USECODE bytes but does not create the original VM context, run the interpreter, mutate the item through `Item_Release`, or implement cache block chains, contained-item placement, shape-flag cache-out, or verified live item IDs. Staged X/Y reverse the preview loader's display scale to retain the original fixed-record words. NPC item IDs `1..255` are reserved separately and must not be conflated with staged map-item IDs. +This is an integration checkpoint, **not the Phase 4 exit criterion or a playable interaction**: the host starts this item process as a diagnostic fixture, not via the original `Item_Grab`/search trigger; it selects eligible USECODE bytes but does not create the original VM context, run the interpreter, mutate the item through `Item_Release`, or implement live contained-item placement, shape-flag cache-out, or verified runtime item IDs. The staged direct-placement block chains and separate contained-parent diagnostic are read-only, not a live item cache. Staged X/Y reverse the preview loader's display scale to retain the original fixed-record words. NPC item IDs `1..255` are reserved separately and must not be conflated with staged map-item IDs. The Windows diagnostic no longer schedules the first staged item on scene load. `F` now selects a staged fixed-map record within 48 world units of the host-controlled actor (nearest in X/Y, using the fixed-record display scale), then runs the existing `ItemProcess` release callback on the next scheduler tick. The HUD reports the candidate and callback result; a synthetic proximity test and the MSVC/CTest gate cover selection and the existing process lifecycle. This is a one-shot diagnostic with no item-type filtering, vertical reach, USECODE event execution, or visible item-state change. Exported `Item_Grab` (`10a0:2970`) uses `ItemFind` search and an item-cache status guard before creating item processes; exported `Item_Release` (`10a0:2a06`) calls `Usecode_ItemCallEvent` with `UC_Release`. Neither original trigger nor the event executor is ported, so this change does not meet the playable-game milestone. -The `Item_Grab` creation branch now applies the verified `FUN_11d0_3f95(itemNumber, -0xf)` item-cache flag-1 check to staged item flags before queuing a diagnostic process. Live disassembly at `10a0:29c5-29e3` confirms the branch; a separate search-result type 1 calls `Item_Fall` instead, which is not ported. The Ghidra export's zero-initialized `npcno` loop is a decompiler artifact, not evidence that the search never iterates. The host still uses proximity instead of original `ItemFind`, does not model live item-cache mutations or falling items, and must not treat process-presence bookkeeping as the checked item flag. +The `Item_Grab` creation branch applies the verified `FUN_11d0_3f95(itemNumber, -0xf)` item-cache flag-1 check to staged item flags before a type-2 process request. Live disassembly at `10a0:29c5-29e3` confirms the branch; a separate search-result type 1 calls `Item_Fall`, whose hurl request now creates or merges a sleeping gravity entry in the host. The Ghidra export's zero-initialized `npcno` loop is a decompiler artifact, not evidence that the search never iterates. The window still uses proximity instead of original `ItemFind`, does not model live item-cache mutations or gravity movement, and must not treat process-presence bookkeeping as the checked item flag. The first Phase 6 resource slice is compiled into `remorse_core`: a bounded `EUSECODE.FLX` class/name/event-body reader follows the owner-loaded `classId + 2`, 13-byte name-table, `+0x14` six-byte row, and `codeBase + relativeOffset - 1` body rules verified in `docs/raw-000a-000d.md`. Retail tests confirm `EVENT` (`class 0x361`, slot `0x0a`, code base `0xd4`, body length `0x1fd6`) and `RECHFLNS` (`class 0x138`, release slot `9`, body length `102`, owner mask `0x200`). The harness resolves and reports the `EVENT` body (8,150 bytes). `Item_GetUsecodeClassId` selects a class from item identity and startup class bases; `Usecode_ItemCallEvent` gates on the owner row. Map-1 tests cover both its classless first staged item and at least one actual staged item with an eligible release body. The window applies both checks to the nearest staged item's release request and labels eligible bytes NOT RUN. This remains lookup, not bytecode interpretation or a live owner-loaded item system. The next original call is `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`, mode 2, selected class/slot and a four-byte parameter), which initializes an interpreter through `Inter_1418_0244` (`1418:0244`) and `Interpreter_1418_00e8` (`1418:00e8`). No context, interpreter dispatch, or item side effect is ported. Even the short `RECHFLNS` release event branches through item surface-weight logic and `FREE.slot_33`; an isolated opcode stub would not complete that call chain. diff --git a/rebuild/remorse/include/remorse/collision.h b/rebuild/remorse/include/remorse/collision.h index a8abd2b..16bed27 100644 --- a/rebuild/remorse/include/remorse/collision.h +++ b/rebuild/remorse/include/remorse/collision.h @@ -16,6 +16,20 @@ struct CollisionBody { s32 extentZ = 0; }; +struct GravitySweepPlan { + WorldPoint destination{}; + s16 nextZSpeed = 0; +}; + +struct SweepBoundsResult { + WorldPoint destination{}; + u8 failedDirections = 0; + bool failed = false; +}; + +SweepBoundsResult clampAreaSweepBounds(WorldPoint from, WorldPoint destination); +GravitySweepPlan planGravitySweep(WorldPoint location, s16 xSpeed, s16 ySpeed, s16 zSpeed, + s16 gravity, u32 timeScale); CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped = false); bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right); bool canMoveCollisionBody( diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index e43e059..d4a1ef1 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -8,6 +8,10 @@ namespace remorse { +class LiveFixedMapItems; +struct ShapeTypeInfo; +struct WorldPoint; + CR_PACK_PUSH_1 struct EntityDispatchEntryBase { u8 bytes[0x32]; @@ -18,6 +22,11 @@ struct StandProcessEntry { u8 extra[0x10]; } CR_PACKED; +struct GravityProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x10]; +} CR_PACKED; + struct SystemTimerProcessEntry { EntityDispatchEntryBase base; u8 extra[0x18]; @@ -51,6 +60,7 @@ CR_PACK_POP static_assert(sizeof(EntityDispatchEntryBase) == 0x32, "EntityDispatchEntryBase size must match allocation evidence"); static_assert(sizeof(StandProcessEntry) == 0x42, "StandProcessEntry size must match allocation evidence"); +static_assert(sizeof(GravityProcessEntry) == 0x42, "GravityProcessEntry size must match allocation evidence"); static_assert(sizeof(SystemTimerProcessEntry) == 0x4a, "SystemTimerProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyDaemonProcessEntry) == 0x40, "KeyDaemonProcessEntry size must match allocation evidence"); @@ -71,6 +81,12 @@ public: EntityDispatchEntryBase* createProcess(u8 activeGroup, u16 (&groupCounts)[32]); StandProcessEntry* createStandProcess(u8 activeGroup, u16 npcNumber, u16 (&groupCounts)[32]); EntityDispatchEntryBase* createItemProcess(u8 activeGroup, u16 itemNumber, u16 (&groupCounts)[32]); + u16 hurlItem(u8 activeGroup, u16 itemNumber, s16 xs, s16 ys, s16 zs, s16 gravity, + u32 timerTick, u16 (&groupCounts)[32]); + bool runUnobstructedGravity(u16 processId, LiveFixedMapItems& items, u32 timeScale, u32 timerTick, + bool (*approveSweep)(u16 itemNumber, const WorldPoint& from, const WorldPoint& to, void* context), + void* context, const std::vector* shapes = nullptr, + u16 (*groupCounts)[32] = nullptr); SystemTimerProcessEntry* createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]); @@ -93,6 +109,7 @@ public: u32 runTimedSchedulerPass(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, void (*afterScan)(void*) = nullptr, void* afterContext = nullptr); EntityDispatchEntryBase* processAt(u16 id) const; + EntityDispatchEntryBase* findProcessForItemAndType(u16 itemNumber, u16 eventType) const; u16 allocationSizeAt(u16 id) const; const char* processNameAt(u16 id) const; bool itemHasProcess(u16 itemNumber) const; @@ -111,6 +128,7 @@ private: std::vector processNames_; std::vector> ownedProcesses_; std::vector> ownedStandProcesses_; + std::vector> ownedGravityProcesses_; std::unique_ptr systemTimerProcess_; std::unique_ptr keyboardProcess_; std::unique_ptr keyDaemonProcess_; diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index e3ae718..37ac7a7 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -9,6 +9,7 @@ namespace remorse { struct ShapeTypeInfo; +class ProcessKernel; struct FixedMapEntry { u16 x = 0; @@ -34,6 +35,12 @@ struct StagedFixedMapItem { FixedMapEntry data; }; +struct StagedContainedFixedMapItem { + u16 itemNumber = 0; + u16 parentItemNumber = 0; + std::size_t recordIndex = 0; +}; + struct ItemFindArea { u16 minX = 0; u16 minY = 0; @@ -41,6 +48,26 @@ struct ItemFindArea { u16 maxY = 0; }; +struct StagedItemBlockChains { + std::vector heads; + std::vector next; +}; + +struct ItemFindZCandidate { + u16 itemNumber = 0; + u8 matchType = 0; +}; + +enum class ItemGrabActionKind { + Hurl, + CreateProcess +}; + +struct ItemGrabAction { + u16 itemNumber = 0; + ItemGrabActionKind kind = ItemGrabActionKind::Hurl; +}; + struct FixedMapArchive { u32 mapCount = 0; std::vector bytes; @@ -49,12 +76,43 @@ struct FixedMapArchive { std::optional loadFixedMapArchive(const std::filesystem::path& path); std::optional loadFixedMap(const FixedMapArchive& archive, u32 mapIndex); std::optional> stageFixedMapItems(const FixedMap& map); +std::optional> stageContainedFixedMapItems( + const FixedMap& map, const std::vector& shapes); std::optional nearestStagedFixedMapItem( const std::vector& items, s32 worldX, s32 worldY, s32 maxDistance); bool itemGrabCanCreateProcess(const StagedFixedMapItem& item); +bool itemFallStartsHurl(const ShapeTypeInfo& shape); u8 classifyItemFindZMatch(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape, const StagedFixedMapItem& candidate, const ShapeTypeInfo& candidateShape, u8 zMatchFlags); ItemFindArea itemFindAreaAroundItem(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape); std::vector itemFindBlockOrder(const ItemFindArea& area); +std::optional buildStagedItemBlockChains(const std::vector& items); +std::vector itemFindCandidateOrder(const ItemFindArea& area, const StagedItemBlockChains& chains); +std::optional> itemFindZMatches(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, u8 zMatchFlags); +std::optional> itemGrabSearchCandidates(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes); +std::optional> planItemGrabActions(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes); +std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, + ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick); + +class LiveFixedMapItems { +public: + explicit LiveFixedMapItems(std::vector items); + const StagedFixedMapItem* findItem(u16 itemNumber) const; + std::optional nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const; + bool insertItem(StagedFixedMapItem item); + bool moveItem(u16 itemNumber, u16 x, u16 y, u8 z); + std::optional> grabItem(u16 itemNumber, const std::vector& shapes, + ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick) const; + std::optional> moveApprovedItem(u16 itemNumber, u16 x, u16 y, u8 z, + const std::vector& shapes, ProcessKernel& kernel, + u16 (&groupCounts)[32], u32 timerTick); + +private: + std::vector items_; +}; } // namespace remorse diff --git a/rebuild/remorse/include/remorse/type_flags.h b/rebuild/remorse/include/remorse/type_flags.h index 9abd84a..f73698a 100644 --- a/rebuild/remorse/include/remorse/type_flags.h +++ b/rebuild/remorse/include/remorse/type_flags.h @@ -15,6 +15,7 @@ struct ShapeTypeInfo { u8 y = 0; u8 z = 0; u8 animationType = 0; + u8 weight = 0; }; std::optional> loadTypeFlags(const std::filesystem::path& path); diff --git a/rebuild/remorse/src/collision.cpp b/rebuild/remorse/src/collision.cpp index b4cc809..68f44b4 100644 --- a/rebuild/remorse/src/collision.cpp +++ b/rebuild/remorse/src/collision.cpp @@ -77,6 +77,35 @@ void appendSolidBody(std::vector& bodies, const std::vector 0x7fff) { + result.destination.x = destination.x < from.x ? 0 : 0x7fff; + result.failedDirections |= 1; + result.failed = true; + } + if (destination.y < 0 || destination.y > 0x7fff) { + result.destination.y = destination.y < from.y ? 0 : 0x7fff; + result.failedDirections |= 2; + result.failed = true; + } + if (destination.z < 0 || destination.z > 0xfa) { + result.destination.z = std::clamp(destination.z, 0, 0xfa); + result.failedDirections |= 4; + } + return result; +} + +GravitySweepPlan planGravitySweep(WorldPoint location, s16 xSpeed, s16 ySpeed, s16 zSpeed, + s16 gravity, u32 timeScale) +{ + const s32 multiplier = static_cast(std::clamp(timeScale, 1u, 4u)); + return {{location.x + xSpeed * multiplier, location.y + ySpeed * multiplier, + static_cast(location.z + zSpeed * multiplier)}, + static_cast(zSpeed - gravity * multiplier)}; +} + CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped) { const s32 extentX = static_cast(flipped ? shapeInfo.y : shapeInfo.x) * shapeDimensionScale; diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index a41b9a2..904b439 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -1,4 +1,6 @@ #include "remorse/entity_dispatch_entry.h" +#include "remorse/collision.h" +#include "remorse/fixed_map.h" #include #include @@ -122,11 +124,115 @@ EntityDispatchEntryBase* ProcessKernel::createItemProcess(u8 activeGroup, u16 it setLastAllocationSize(sizeof(EntityDispatchEntryBase)); const u16 id = addProcess(*process); processNames_[id] = "ItemProcess"; + if (syncEnabled_) { + EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_); + if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) { + current->bytes[0x18] |= 0x04; + } + if (id > currentProcessId_) { + process->bytes[0x16] |= 0x40; + } + } EntityDispatchEntryBase* result = process.get(); ownedProcesses_.push_back(std::move(process)); return result; } +u16 ProcessKernel::hurlItem(u8 activeGroup, u16 itemNumber, s16 xs, s16 ys, s16 zs, s16 gravity, + u32 timerTick, u16 (&groupCounts)[32]) +{ + if (itemNumber == 0 || itemNumber > maxTrackedItemNumber) { + throw std::out_of_range("gravity item number exceeds process lookup tables"); + } + if (auto* existing = findProcessForItemAndType(itemNumber, 0x203)) { + const u16 processId = readLe16(*existing, 0x02); + if (allocationSizeAt(processId) != sizeof(GravityProcessEntry) || + std::none_of(ownedGravityProcesses_.begin(), ownedGravityProcesses_.end(), + [existing](const auto& process) { return &process->base == existing; })) { + throw std::logic_error("gravity process ownership is not ported"); + } + writeLe16(*existing, 0x32, static_cast(readLe16(*existing, 0x32) + xs)); + writeLe16(*existing, 0x34, static_cast(readLe16(*existing, 0x34) + ys)); + writeLe16(*existing, 0x36, static_cast(readLe16(*existing, 0x36) + zs)); + return processId; + } + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + ownedGravityProcesses_.reserve(ownedGravityProcesses_.size() + 1); + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x00, 0x0610); + setProcessSourceType(process->base, itemNumber); + setProcessEventTypeChecked(process->base, 0x203); + writeLe16(process->base, 0x32, static_cast(xs)); + writeLe16(process->base, 0x34, static_cast(ys)); + writeLe16(process->base, 0x36, static_cast(zs)); + writeLe16(process->base, 0x38, static_cast(gravity)); + writeLe16(process->base, 0x3b, 200); + process->base.bytes[0x3a] = 1; + process->base.bytes[0x3d] = 1; + setLastAllocationSize(sizeof(GravityProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "Gravity"; + if (syncEnabled_) { + EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_); + if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) { + current->bytes[0x18] |= 0x04; + } + if (id > currentProcessId_) { + process->base.bytes[0x16] |= 0x40; + } + } + EntityDispatchEntry::sleep(process->base, timerTick, 0x14); + ownedGravityProcesses_.push_back(std::move(process)); + return id; +} + +bool ProcessKernel::runUnobstructedGravity(u16 processId, LiveFixedMapItems& items, + u32 timeScale, u32 timerTick, + bool (*approveSweep)(u16, const WorldPoint&, const WorldPoint&, void*), void* context, + const std::vector* shapes, u16 (*groupCounts)[32]) +{ + const auto* process = processAt(processId); + if (process == nullptr || approveSweep == nullptr || allocationSizeAt(processId) != sizeof(GravityProcessEntry) || + (process->bytes[0x16] & 0x08) != 0 || (process->bytes[0x19] & 0x10) != 0 || + std::none_of(ownedGravityProcesses_.begin(), ownedGravityProcesses_.end(), + [process](const auto& owned) { return &owned->base == process; })) { + return false; + } + const u16 itemNumber = readLe16(*process, 0x04); + const auto* item = items.findItem(itemNumber); + const auto zSpeed = static_cast(readLe16(*process, 0x36)); + if (item == nullptr || item->data.z > 250) { + return false; + } + if (zSpeed == 0) { + if (shapes == nullptr || groupCounts == nullptr || + (readLe16(*process, 0x32) == 0 && readLe16(*process, 0x34) == 0) || + !items.grabItem(itemNumber, *shapes, *this, *groupCounts, timerTick)) { + return false; + } + } + const WorldPoint from{item->data.x, item->data.y, item->data.z}; + const auto step = planGravitySweep(from, static_cast(readLe16(*process, 0x32)), + static_cast(readLe16(*process, 0x34)), zSpeed, + static_cast(readLe16(*process, 0x38)), timeScale); + if (step.destination.x < 0 || step.destination.x > 0x7fff || + step.destination.y < 0 || step.destination.y > 0x7fff || step.destination.z > 250 || + !approveSweep(itemNumber, from, step.destination, context)) { + return false; + } + if (!items.moveItem(itemNumber, static_cast(step.destination.x), + static_cast(step.destination.y), static_cast(step.destination.z))) { + return false; + } + auto* mutableProcess = processAt(processId); + writeLe16(*mutableProcess, 0x36, static_cast(step.nextZSpeed)); + EntityDispatchEntry::sleep(*mutableProcess, timerTick, 4 * std::clamp(timeScale, 1u, 4u)); + return true; +} + SystemTimerProcessEntry* ProcessKernel::createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]) { if (systemTimerProcess_ != nullptr) { @@ -312,6 +418,12 @@ void ProcessKernel::releaseOwnedProcess(u16 id) ownedStandProcesses_.erase(stand); return; } + const auto gravity = std::find_if(ownedGravityProcesses_.begin(), ownedGravityProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (gravity != ownedGravityProcesses_.end()) { + ownedGravityProcesses_.erase(gravity); + return; + } const auto owned = std::find_if(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; }); ownedProcesses_.erase(owned); @@ -336,15 +448,19 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) } const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(), [entry](const auto& process) { return &process->base == entry; }); + const bool ownedGravityProcess = readLe16(*entry, 0x00) == 0x0610 && + std::any_of(ownedGravityProcesses_.begin(), ownedGravityProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); const bool ownedItemProcess = readLe16(*entry, 0x00) == ItemProcess::vtableOffset && std::any_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; }); - if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess || id < 3 || + if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess && !ownedGravityProcess || id < 3 || readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 || readLe16(*entry, 0x2e) != 0 || readLe16(*entry, 0x30) != 0)) { throw std::logic_error("item process child cleanup is not ported"); } - if (stand == ownedStandProcesses_.end() && std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(), + if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && + std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; })) { throw std::logic_error("external process ownership is not ported"); } @@ -533,6 +649,19 @@ EntityDispatchEntryBase* ProcessKernel::processAt(u16 id) const return id < processes_.size() ? processes_[id] : nullptr; } +EntityDispatchEntryBase* ProcessKernel::findProcessForItemAndType(u16 itemNumber, u16 eventType) const +{ + for (std::size_t id = 3; id < processes_.size(); ++id) { + EntityDispatchEntryBase* process = processes_[id]; + if (process != nullptr && (itemNumber == 0 || readLe16(*process, 0x04) == itemNumber) && + (eventType == 0x0c || readLe16(*process, 0x06) == eventType) && + (readLe16(*process, 0x16) & 0x08) == 0) { + return process; + } + } + return nullptr; +} + u16 ProcessKernel::allocationSizeAt(u16 id) const { return id < allocationSizes_.size() ? allocationSizes_[id] : 0; diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index 33222ff..140a84d 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -1,8 +1,13 @@ #include "remorse/fixed_map.h" +#include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" #include "remorse/type_flags.h" +#include +#include +#include + namespace remorse { namespace { @@ -147,6 +152,54 @@ std::optional> stageFixedMapItems(const FixedMap return items; } +std::optional> stageContainedFixedMapItems( + const FixedMap& map, const std::vector& shapes) +{ + if (map.index == 0) { + return std::nullopt; + } + std::vector contained; + std::vector parentById(0x2800); + std::vector shapeById(0x2800); + u16 previousItemNumber = 0; + u16 currentParent = 0; + u16 currentDepth = 0; + std::size_t allocated = 0; + for (std::size_t index = 0; index < map.entries.size(); ++index) { + const auto& record = map.entries[index]; + if (record.shape == 0) { + continue; + } + if (allocated == 0x2700 || record.shape >= shapes.size()) { + return std::nullopt; + } + const auto itemNumber = static_cast(0x100 + allocated++); + shapeById[itemNumber] = record.shape; + if ((record.flags & 8) != 0) { + const u16 depth = record.x / crusaderCoordinateScale; + if (depth > currentDepth) { + currentParent = previousItemNumber; + currentDepth = depth; + } + while (depth < currentDepth) { + currentParent = parentById[currentParent]; + --currentDepth; + } + if (currentParent == 0 || (shapes[shapeById[currentParent]].family != 6 && + shapes[shapeById[currentParent]].family != 7)) { + return std::nullopt; + } + parentById[itemNumber] = currentParent; + contained.push_back({itemNumber, currentParent, index}); + } else { + currentParent = 0; + currentDepth = 0; + } + previousItemNumber = itemNumber; + } + return contained; +} + std::optional nearestStagedFixedMapItem( const std::vector& items, s32 worldX, s32 worldY, s32 maxDistance) { @@ -173,6 +226,11 @@ bool itemGrabCanCreateProcess(const StagedFixedMapItem& item) return (item.data.flags & 0x02) == 0; } +bool itemFallStartsHurl(const ShapeTypeInfo& shape) +{ + return (shape.flags & 1) == 0 && shape.weight != 0; +} + u8 classifyItemFindZMatch(const StagedFixedMapItem& origin, const ShapeTypeInfo& originShape, const StagedFixedMapItem& candidate, const ShapeTypeInfo& candidateShape, u8 zMatchFlags) { @@ -224,4 +282,209 @@ std::vector itemFindBlockOrder(const ItemFindArea& area) return blocks; } +std::optional buildStagedItemBlockChains(const std::vector& items) +{ + StagedItemBlockChains chains; + chains.heads.resize(0x1000); + chains.next.resize(0x2800); + std::vector seen(chains.next.size()); + for (const auto& item : items) { + if (item.itemNumber < 0x100 || item.itemNumber >= chains.next.size() || seen[item.itemNumber] || + item.data.x > 0x7fff || item.data.y > 0x7fff) { + return std::nullopt; + } + seen[item.itemNumber] = true; + const auto block = (item.data.x >> 9) * 0x40 + (item.data.y >> 9); + chains.next[item.itemNumber] = chains.heads[block]; + chains.heads[block] = item.itemNumber; + } + return chains; +} + +std::vector itemFindCandidateOrder(const ItemFindArea& area, const StagedItemBlockChains& chains) +{ + std::vector candidates; + for (const auto block : itemFindBlockOrder(area)) { + for (u16 itemNumber = chains.heads[block]; itemNumber != 0; itemNumber = chains.next[itemNumber]) { + candidates.push_back(itemNumber); + } + } + return candidates; +} + +namespace { + +std::optional> collectZMatches(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, + u8 zMatchFlags, bool checkRectangle) +{ + if (origin.data.shape >= shapes.size()) { + return std::nullopt; + } + const auto chains = buildStagedItemBlockChains(items); + if (!chains) { + return std::nullopt; + } + std::vector byId(chains->next.size()); + for (const auto& item : items) { + if (item.data.shape >= shapes.size()) { + return std::nullopt; + } + byId[item.itemNumber] = &item; + } + std::vector matches; + const auto area = itemFindAreaAroundItem(origin, shapes[origin.data.shape]); + for (const auto itemNumber : itemFindCandidateOrder(area, *chains)) { + const auto& candidate = *byId[itemNumber]; + if (checkRectangle && (candidate.data.x < area.minX || candidate.data.x > area.maxX || + candidate.data.y < area.minY || candidate.data.y > area.maxY)) { + continue; + } + const auto matchType = classifyItemFindZMatch(origin, shapes[origin.data.shape], + candidate, shapes[candidate.data.shape], zMatchFlags); + if (matchType != 0) { + matches.push_back({itemNumber, matchType}); + } + } + return matches; +} + +} // namespace + +std::optional> itemFindZMatches(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, u8 zMatchFlags) +{ + return collectZMatches(origin, items, shapes, zMatchFlags, false); +} + +std::optional> itemGrabSearchCandidates(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes) +{ + return collectZMatches(origin, items, shapes, 3, true); +} + +std::optional> planItemGrabActions(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes) +{ + const auto candidates = itemGrabSearchCandidates(origin, items, shapes); + if (!candidates) { + return std::nullopt; + } + std::vector byId(0x2800); + for (const auto& item : items) { + byId[item.itemNumber] = &item; + } + std::vector actions; + for (const auto& candidate : *candidates) { + const auto& item = *byId[candidate.itemNumber]; + if (candidate.matchType == 1 && itemFallStartsHurl(shapes[item.data.shape])) { + actions.push_back({candidate.itemNumber, ItemGrabActionKind::Hurl}); + } else if (candidate.matchType == 2 && itemGrabCanCreateProcess(item)) { + actions.push_back({candidate.itemNumber, ItemGrabActionKind::CreateProcess}); + } + } + return actions; +} + +std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, + ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick) +{ + const auto actions = planItemGrabActions(origin, items, shapes); + if (!actions) { + return std::nullopt; + } + for (const auto& action : *actions) { + if (action.itemNumber > ProcessKernel::maxTrackedItemNumber) { + return std::nullopt; + } + } + std::vector processIds; + for (const auto& action : *actions) { + if (action.kind == ItemGrabActionKind::Hurl) { + processIds.push_back(kernel.hurlItem(kernel.activeGroup(), action.itemNumber, 0, 0, 0, 2, + timerTick, groupCounts)); + } else { + auto* process = kernel.createItemProcess(kernel.activeGroup(), action.itemNumber, groupCounts); + processIds.push_back(static_cast(process->bytes[2] | (static_cast(process->bytes[3]) << 8))); + } + } + return processIds; +} + +LiveFixedMapItems::LiveFixedMapItems(std::vector items) : items_(std::move(items)) +{ + if (!buildStagedItemBlockChains(items_)) { + throw std::invalid_argument("invalid live item IDs or coordinates"); + } +} + +const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const +{ + for (const auto& item : items_) { + if (item.itemNumber == itemNumber) { + return &item; + } + } + return nullptr; +} + +std::optional LiveFixedMapItems::nearestItem(s32 worldX, s32 worldY, + s32 maxDistance) const +{ + return nearestStagedFixedMapItem(items_, worldX, worldY, maxDistance); +} + +bool LiveFixedMapItems::insertItem(StagedFixedMapItem item) +{ + if (item.itemNumber < 0x100 || item.itemNumber >= 0x2800 || item.data.x > 0x7fff || + item.data.y > 0x7fff || findItem(item.itemNumber)) { + return false; + } + item.data.z = std::min(item.data.z, 0xfa); + items_.push_back(item); + return true; +} + +bool LiveFixedMapItems::moveItem(u16 itemNumber, u16 x, u16 y, u8 z) +{ + if (x > 0x7fff || y > 0x7fff) { + return false; + } + const auto item = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& candidate) { + return candidate.itemNumber == itemNumber; + }); + if (item == items_.end()) { + return false; + } + item->data.x = x; + item->data.y = y; + item->data.z = std::min(z, 0xfa); + std::rotate(item, item + 1, items_.end()); + return true; +} + +std::optional> LiveFixedMapItems::grabItem(u16 itemNumber, + const std::vector& shapes, ProcessKernel& kernel, + u16 (&groupCounts)[32], u32 timerTick) const +{ + const auto* origin = findItem(itemNumber); + return origin == nullptr ? std::nullopt : dispatchStagedItemGrab(*origin, items_, shapes, + kernel, groupCounts, timerTick); +} + +std::optional> LiveFixedMapItems::moveApprovedItem(u16 itemNumber, u16 x, u16 y, + u8 z, const std::vector& shapes, ProcessKernel& kernel, + u16 (&groupCounts)[32], u32 timerTick) +{ + if (x > 0x7fff || y > 0x7fff || !findItem(itemNumber)) { + return std::nullopt; + } + auto processIds = grabItem(itemNumber, shapes, kernel, groupCounts, timerTick); + if (processIds) { + moveItem(itemNumber, x, y, z); + } + return processIds; +} + } // namespace remorse diff --git a/rebuild/remorse/src/main.cpp b/rebuild/remorse/src/main.cpp index a269199..2691154 100644 --- a/rebuild/remorse/src/main.cpp +++ b/rebuild/remorse/src/main.cpp @@ -77,6 +77,8 @@ int main(int argc, char** argv) std::cout << "Game data root: " << (gameDataRoot ? gameDataRoot->path.string() : "not found") << '\n'; if (gameDataRoot) { std::optional firstStagedItem; + std::optional stagedBlockChains; + std::optional> stagedMapItems; const auto palettePath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("STATIC") / "GAMEPAL.PAL"); const auto paletteBytes = palettePath ? remorse::readBinaryFile(*palettePath) : std::nullopt; std::cout << "GAMEPAL.PAL bytes: " << (paletteBytes ? paletteBytes->size() : 0) << '\n'; @@ -101,6 +103,8 @@ int main(int argc, char** argv) const auto items = remorse::stageFixedMapItems(*map); if (items && !items->empty()) { firstStagedItem = items->front(); + stagedBlockChains = remorse::buildStagedItemBlockChains(*items); + stagedMapItems = *items; struct ItemScanContext { remorse::ProcessKernel* kernel; remorse::u16 (*groups)[32]; @@ -141,6 +145,23 @@ int main(int argc, char** argv) const auto area = remorse::itemFindAreaAroundItem( *firstStagedItem, (*typeFlags)[firstStagedItem->data.shape]); std::cout << "Staged item ItemFind blocks: " << remorse::itemFindBlockOrder(area).size() << '\n'; + if (stagedBlockChains) { + std::cout << "Staged item ItemFind candidates: " << + remorse::itemFindCandidateOrder(area, *stagedBlockChains).size() << '\n'; + } + if (stagedMapItems) { + const auto matches = remorse::itemFindZMatches(*firstStagedItem, *stagedMapItems, *typeFlags, 3); + std::cout << "Staged item ItemFind Z matches (script-free): " << + (matches ? matches->size() : 0) << '\n'; + const auto grabCandidates = remorse::itemGrabSearchCandidates( + *firstStagedItem, *stagedMapItems, *typeFlags); + const auto grabActions = remorse::planItemGrabActions( + *firstStagedItem, *stagedMapItems, *typeFlags); + std::cout << "Staged item Item_Grab candidates: " << + (grabCandidates ? grabCandidates->size() : 0) << '\n'; + std::cout << "Staged item Item_Grab planned actions: " << + (grabActions ? grabActions->size() : 0) << '\n'; + } } const auto usecodePath = remorse::resolveGameDataPath(*gameDataRoot, std::filesystem::path("USECODE") / "EUSECODE.FLX"); diff --git a/rebuild/remorse/src/type_flags.cpp b/rebuild/remorse/src/type_flags.cpp index abe64fd..853a234 100644 --- a/rebuild/remorse/src/type_flags.cpp +++ b/rebuild/remorse/src/type_flags.cpp @@ -29,6 +29,7 @@ std::optional> loadTypeFlags(const std::filesystem::p info.y = static_cast((byte3 >> 2) & 0x1f); info.z = static_cast(((byte4 << 1) | (byte3 >> 7)) & 0x1f); info.animationType = static_cast(byte4 >> 4); + info.weight = (*bytes)[offset + 7]; infos.push_back(info); } diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index c3ba213..becb72f 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -47,7 +47,7 @@ struct AppState { remorse::u16 diagnosticGroupCounts[32]{}; remorse::StandProcessEntry* diagnosticStand = nullptr; remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr; - std::vector stagedItems; + std::optional liveItems; std::optional diagnosticItem; remorse::u16 diagnosticItemProcessId = 0; remorse::u16 diagnosticReleaseEventItem = 0; @@ -281,7 +281,7 @@ void loadSceneAsync(HWND window, AppState& state) state.playerFrames = std::move(playerFrames); state.playerPalette = *palette; if (stagedItems) { - state.stagedItems = std::move(*stagedItems); + state.liveItems.emplace(std::move(*stagedItems)); } state.sceneLoaded = true; } @@ -557,8 +557,8 @@ void paintWindow(HWND window, AppState& state) RECT diagnosticsBounds{20, 30, viewWidth - 12, 54}; SetTextColor(device, RGB(74, 207, 184)); DrawTextW(device, diagnostics.str().c_str(), -1, &diagnosticsBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); - const auto nearbyItem = remorse::nearestStagedFixedMapItem( - state.stagedItems, state.playerWorld.x, state.playerWorld.y, diagnosticItemRange); + const auto nearbyItem = state.liveItems ? state.liveItems->nearestItem( + state.playerWorld.x, state.playerWorld.y, diagnosticItemRange) : std::nullopt; if (state.diagnosticItem || nearbyItem) { const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem; std::wostringstream itemStatus; @@ -729,8 +729,8 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA std::lock_guard lock(state->sceneMutex); if (state->sceneLoaded && state->scene && !state->diagnosticItemCompleted && state->diagnosticItemProcessId == 0) { - state->diagnosticItem = remorse::nearestStagedFixedMapItem( - state->stagedItems, state->playerWorld.x, state->playerWorld.y, diagnosticItemRange); + state->diagnosticItem = state->liveItems ? state->liveItems->nearestItem( + state->playerWorld.x, state->playerWorld.y, diagnosticItemRange) : std::nullopt; } if (state->diagnosticItem && state->diagnosticItemProcessId == 0 && state->diagnosticItem->itemNumber <= remorse::ProcessKernel::maxTrackedItemNumber && diff --git a/rebuild/remorse/tests/collision_tests.cpp b/rebuild/remorse/tests/collision_tests.cpp index d8fe5c7..b3b06e6 100644 --- a/rebuild/remorse/tests/collision_tests.cpp +++ b/rebuild/remorse/tests/collision_tests.cpp @@ -4,6 +4,24 @@ int main() { + const auto outsideBounds = remorse::clampAreaSweepBounds({10, 20, 10}, {-3, 0x8000, 252}); + assert(outsideBounds.destination.x == 0 && outsideBounds.destination.y == 0x7fff && + outsideBounds.destination.z == 250 && outsideBounds.failedDirections == 7 && + outsideBounds.failed); + const auto belowFloor = remorse::clampAreaSweepBounds({10, 20, 10}, {10, 20, -3}); + assert(belowFloor.destination.z == 0 && belowFloor.failedDirections == 4 && !belowFloor.failed); + const auto withinBounds = remorse::clampAreaSweepBounds({10, 20, 10}, {12, 23, 11}); + assert(withinBounds.failedDirections == 0 && !withinBounds.failed); + const auto gravityStep = remorse::planGravitySweep({100, 200, 250}, 3, -2, 4, 2, 3); + assert(gravityStep.destination.x == 109 && gravityStep.destination.y == 194); + assert(gravityStep.destination.z == 6 && gravityStep.nextZSpeed == -2); + const auto slowStep = remorse::planGravitySweep({100, 200, 0}, 3, -2, -4, 2, 0); + assert(slowStep.destination.x == 103 && slowStep.destination.y == 198); + assert(slowStep.destination.z == 252 && slowStep.nextZSpeed == -6); + const auto cappedStep = remorse::planGravitySweep({100, 200, 0}, 3, -2, 4, 2, 5); + assert(cappedStep.destination.x == 112 && cappedStep.destination.y == 192); + assert(cappedStep.destination.z == 16 && cappedStep.nextZSpeed == -4); + const remorse::CollisionBody actor{{100, 100, 0}, 96, 96, 80}; const remorse::CollisionBody wall{{300, 100, 0}, 64, 96, 128}; assert(!remorse::collisionBodiesOverlap(actor, wall)); diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index 0e24243..0978576 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -1,4 +1,7 @@ #include "remorse/entity_dispatch_entry.h" +#include "remorse/fixed_map.h" +#include "remorse/map_renderer.h" +#include "remorse/type_flags.h" #include #include @@ -285,6 +288,33 @@ int main() assert(spawnContext.runs == 1 && spawnContext.spawned == spawningKernel.processAt(2)); assert(spawningProcess->bytes[0x18] == 0x07 && spawnContext.spawned->bytes[0x16] == 0); + remorse::ProcessKernel itemSpawnKernel; + remorse::u16 itemSpawnGroups[32]{}; + for (int index = 0; index < 3; ++index) { + itemSpawnKernel.createProcess(1, itemSpawnGroups); + } + auto* itemSpawner = itemSpawnKernel.createProcess(2, itemSpawnGroups); + itemSpawner->bytes[0x18] |= 0x02; + struct ItemSpawnContext { + remorse::ProcessKernel* kernel; + remorse::u16 (*groups)[32]; + remorse::EntityDispatchEntryBase* spawned = nullptr; + int spawnedRuns = 0; + } itemSpawnContext{&itemSpawnKernel, &itemSpawnGroups}; + auto spawnItemRun = [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& state = *static_cast(context); + if (process.bytes[0] == remorse::ItemProcess::vtableOffset % 256) { + ++state.spawnedRuns; + } else if (state.spawned == nullptr && process.bytes[2] == 3) { + state.spawned = state.kernel->createItemProcess(2, 0x100, *state.groups); + } + }; + itemSpawnKernel.scanRunnableProcesses(2, spawnItemRun, &itemSpawnContext); + assert(itemSpawnContext.spawned && itemSpawnContext.spawnedRuns == 0 && + (itemSpawnContext.spawned->bytes[0x16] & 0x40) == 0); + itemSpawnKernel.scanRunnableProcesses(2, spawnItemRun, &itemSpawnContext); + assert(itemSpawnContext.spawnedRuns == 1); + remorse::ProcessKernel retiringKernel; remorse::u16 retiringGroups[32]{}; for (int index = 0; index < 3; ++index) { @@ -372,7 +402,11 @@ int main() assert(itemProcess->bytes[6] == 0xf1 && itemProcess->bytes[7] == 0); assert(cachedItemKernel.itemHasProcess(0x100) && cachedItemKernel.itemProcessTypes(0x100) == 2); assert(cachedItemGroups[1] == 4); + assert(cachedItemKernel.findProcessForItemAndType(0x100, 0xf1) == itemProcess); + assert(cachedItemKernel.findProcessForItemAndType(0, 0x0c) == itemProcess); + assert(cachedItemKernel.findProcessForItemAndType(0x101, 0xf1) == nullptr); auto* sharedItemProcess = cachedItemKernel.createItemProcess(1, 0x100, cachedItemGroups); + assert(cachedItemKernel.findProcessForItemAndType(0x100, 0xf1) == itemProcess); assert(cachedItemKernel.itemProcessTypes(0x100) == 2); cachedItemKernel.setProcessSourceType(*sharedItemProcess, 0x101); assert(cachedItemKernel.itemHasProcess(0x100) && cachedItemKernel.itemHasProcess(0x101)); @@ -422,6 +456,7 @@ int main() } }, &itemRunContext); assert(releasedItem == 0x100 && !cachedItemKernel.itemHasProcess(0x100)); + assert(cachedItemKernel.findProcessForItemAndType(0x100, 0xf1) == nullptr); assert(cachedItemKernel.itemProcessTypes(0x100) == 0); assert(cachedItemKernel.processAt(3) == nullptr && cachedItemGroups[1] == 3); bool itemTeardownRejected = false; @@ -431,6 +466,143 @@ int main() itemTeardownRejected = true; } assert(itemTeardownRejected && standGroups[2] == 2 && standKernel.processAt(1) == standing); + remorse::ProcessKernel gravityKernel; + remorse::u16 gravityGroups[32]{}; + for (int index = 0; index < 3; ++index) { + gravityKernel.createProcess(1, gravityGroups); + } + const auto gravityId = gravityKernel.hurlItem(1, 0x100, 2, -3, 4, 2, 10, gravityGroups); + auto* gravityEntry = gravityKernel.processAt(gravityId); + assert(gravityEntry && gravityKernel.allocationSizeAt(gravityId) == 0x42); + assert(std::strcmp(gravityKernel.processNameAt(gravityId), "Gravity") == 0); + assert(gravityKernel.findProcessForItemAndType(0x100, 0x203) == gravityEntry); + assert(gravityEntry->bytes[0] == 0x10 && gravityEntry->bytes[1] == 0x06); + assert(gravityEntry->bytes[0x32] == 2 && gravityEntry->bytes[0x34] == 0xfd && + gravityEntry->bytes[0x35] == 0xff && gravityEntry->bytes[0x36] == 4); + assert(gravityEntry->bytes[0x38] == 2 && gravityEntry->bytes[0x3b] == 200); + assert((gravityEntry->bytes[0x19] & 0x10) != 0 && gravityEntry->bytes[0x0a] == 10 && + gravityEntry->bytes[0x0e] == 20 && gravityGroups[1] == 4); + assert(gravityKernel.hurlItem(1, 0x100, -4, 5, -2, 99, 11, gravityGroups) == gravityId); + assert(gravityEntry->bytes[0x32] == 0xfe && gravityEntry->bytes[0x33] == 0xff && + gravityEntry->bytes[0x34] == 2 && gravityEntry->bytes[0x36] == 2 && + gravityEntry->bytes[0x38] == 2 && gravityGroups[1] == 4); + bool invalidHurlRejected = false; + try { + gravityKernel.hurlItem(1, 0x2400, 0, 0, 0, 2, 10, gravityGroups); + } catch (const std::out_of_range&) { + invalidHurlRejected = true; + } + assert(invalidHurlRejected && gravityGroups[1] == 4); + int gravityRuns = 0; + auto countGravityRun = [](remorse::EntityDispatchEntryBase& process, void* context) { + if (process.bytes[0] == 0x10 && process.bytes[1] == 0x06) { + ++*static_cast(context); + } + }; + gravityKernel.scanRunnableProcesses(1, countGravityRun, &gravityRuns, 30); + assert(gravityRuns == 0); + gravityKernel.scanRunnableProcesses(1, countGravityRun, &gravityRuns, 31); + assert(gravityRuns == 1 && gravityKernel.itemHasProcess(0x100)); + remorse::StagedFixedMapItem fallingItem{}; + fallingItem.itemNumber = 0x100; + fallingItem.data.x = 100; + fallingItem.data.y = 100; + fallingItem.data.z = 10; + remorse::LiveFixedMapItems fallingItems({fallingItem}); + auto approveGravity = [](remorse::u16 itemNumber, const remorse::WorldPoint& from, + const remorse::WorldPoint& to, void* context) { + ++*static_cast(context); + return itemNumber == 0x100 && from.x == 100 && from.y == 100 && from.z == 10 && + to.x == 98 && to.y == 102 && to.z == 12; + }; + int sweepCalls = 0; + assert(!gravityKernel.runUnobstructedGravity(gravityId, fallingItems, 1, 31, nullptr, nullptr)); + assert(sweepCalls == 0 && fallingItems.findItem(0x100)->data.x == 100); + auto rejectGravity = [](remorse::u16, const remorse::WorldPoint&, const remorse::WorldPoint&, + void* context) { + ++*static_cast(context); + return false; + }; + assert(!gravityKernel.runUnobstructedGravity(gravityId, fallingItems, 1, 31, + rejectGravity, &sweepCalls)); + assert(sweepCalls == 1 && fallingItems.findItem(0x100)->data.x == 100 && + gravityEntry->bytes[0x36] == 2 && (gravityEntry->bytes[0x19] & 0x10) == 0); + assert(gravityKernel.runUnobstructedGravity(gravityId, fallingItems, 1, 31, + approveGravity, &sweepCalls)); + assert(sweepCalls == 2 && fallingItems.findItem(0x100)->data.x == 98 && + fallingItems.findItem(0x100)->data.y == 102 && fallingItems.findItem(0x100)->data.z == 12); + assert(gravityEntry->bytes[0x36] == 0 && gravityEntry->bytes[0x37] == 0 && + (gravityEntry->bytes[0x19] & 0x10) != 0 && gravityEntry->bytes[0x0e] == 4); + assert(!gravityKernel.runUnobstructedGravity(gravityId, fallingItems, 1, 32, + approveGravity, &sweepCalls) && sweepCalls == 2); + remorse::ProcessKernel horizontalKernel; + remorse::u16 horizontalGroups[32]{}; + for (int index = 0; index < 3; ++index) { + horizontalKernel.createProcess(1, horizontalGroups); + } + const auto horizontalId = horizontalKernel.hurlItem(1, 0x100, 2, 0, 0, 2, 0, horizontalGroups); + remorse::StagedFixedMapItem supportedItem = fallingItem; + supportedItem.data.shape = 1; + supportedItem.data.z = 72; + supportedItem.itemNumber = 0x101; + fallingItem.data.shape = 1; + fallingItem.data.z = 80; + remorse::LiveFixedMapItems horizontalItems({fallingItem, supportedItem}); + std::vector horizontalShapes(2); + horizontalShapes[1].x = 1; + horizontalShapes[1].y = 1; + horizontalShapes[1].z = 1; + horizontalKernel.scanRunnableProcesses(1, countGravityRun, &gravityRuns, 21); + struct HorizontalSweep { + remorse::ProcessKernel* kernel; + int calls = 0; + } horizontalSweep{&horizontalKernel}; + auto approveHorizontal = [](remorse::u16 itemNumber, const remorse::WorldPoint& from, + const remorse::WorldPoint& to, void* context) { + auto& state = *static_cast(context); + ++state.calls; + return itemNumber == 0x100 && from.x == 100 && from.z == 80 && to.x == 102 && + to.z == 80 && state.kernel->findProcessForItemAndType(0x101, 0xf1) != nullptr; + }; + assert(!horizontalKernel.runUnobstructedGravity(horizontalId, horizontalItems, 1, 21, + approveHorizontal, &horizontalSweep)); + assert(horizontalSweep.calls == 0 && horizontalKernel.processCount() == 4); + auto rejectHorizontal = [](remorse::u16, const remorse::WorldPoint&, + const remorse::WorldPoint&, void* context) { + ++static_cast(context)->calls; + return false; + }; + assert(!horizontalKernel.runUnobstructedGravity(horizontalId, horizontalItems, 1, 21, + rejectHorizontal, &horizontalSweep, &horizontalShapes, &horizontalGroups)); + assert(horizontalSweep.calls == 1 && horizontalItems.findItem(0x100)->data.x == 100 && + horizontalKernel.findProcessForItemAndType(0x101, 0xf1) != nullptr && + horizontalKernel.processCount() == 5); + assert(horizontalKernel.runUnobstructedGravity(horizontalId, horizontalItems, 1, 21, + approveHorizontal, &horizontalSweep, &horizontalShapes, &horizontalGroups)); + assert(horizontalSweep.calls == 2 && horizontalItems.findItem(0x100)->data.x == 102 && + horizontalKernel.processCount() == 6); + assert(horizontalKernel.processAt(horizontalId)->bytes[0x36] == 0xfe && + horizontalKernel.processAt(horizontalId)->bytes[0x37] == 0xff); + gravityKernel.terminateProcess(gravityId, gravityGroups); + assert(gravityKernel.findProcessForItemAndType(0x100, 0x203) == nullptr); + gravityKernel.clearTerminatedProcesses(); + assert(gravityKernel.processAt(gravityId) == nullptr && !gravityKernel.itemHasProcess(0x100)); + assert(gravityKernel.hurlItem(1, 0x100, 0, 0, 0, 2, 31, gravityGroups) == gravityId); + remorse::ProcessKernel externalGravityKernel; + remorse::u16 externalGravityGroups[32]{}; + for (int index = 0; index < 3; ++index) { + externalGravityKernel.createProcess(1, externalGravityGroups); + } + auto* externalGravity = externalGravityKernel.createProcess(1, externalGravityGroups); + externalGravityKernel.setProcessSourceType(*externalGravity, 0x101); + externalGravityKernel.setProcessEventTypeChecked(*externalGravity, 0x203); + bool unownedGravityRejected = false; + try { + externalGravityKernel.hurlItem(1, 0x101, 1, 0, 0, 2, 0, externalGravityGroups); + } catch (const std::logic_error&) { + unownedGravityRejected = true; + } + assert(unownedGravityRejected && externalGravityGroups[1] == 4); struct StandContext { remorse::u32 tick; bool visible; diff --git a/rebuild/remorse/tests/fixed_map_tests.cpp b/rebuild/remorse/tests/fixed_map_tests.cpp index 37f5f37..5a043da 100644 --- a/rebuild/remorse/tests/fixed_map_tests.cpp +++ b/rebuild/remorse/tests/fixed_map_tests.cpp @@ -42,6 +42,8 @@ int main() const auto typeFlagPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); const auto typeFlags = typeFlagPath ? remorse::loadTypeFlags(*typeFlagPath) : std::nullopt; assert(typeFlags && cachedItems->front().data.shape < typeFlags->size()); + const auto retailContained = remorse::stageContainedFixedMapItems(*retailMap, *typeFlags); + assert(retailContained && retailContained->empty()); const auto& originShape = (*typeFlags)[cachedItems->front().data.shape]; auto origin = cachedItems->front(); origin.data.z = 80; @@ -49,6 +51,12 @@ int main() candidate.itemNumber = static_cast(origin.itemNumber + 1); candidate.data.z = static_cast(origin.data.z + (originShape.z == 0 && (originShape.flags & 1) == 0 ? 1 : originShape.z * 8)); remorse::ShapeTypeInfo footprint{0, 0, 1, 1, 0, 0}; + assert(!remorse::itemFallStartsHurl(footprint)); + footprint.weight = 2; + assert(remorse::itemFallStartsHurl(footprint)); + footprint.flags = 1; + assert(!remorse::itemFallStartsHurl(footprint)); + footprint.flags = 0; assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 1); assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 2) == 0); candidate.data.z = 79; @@ -62,6 +70,23 @@ int main() const auto retailSearchBlocks = remorse::itemFindBlockOrder(retailSearchArea); assert(!retailSearchBlocks.empty() && retailSearchBlocks.front() == (retailSearchArea.minX >> 9) * 0x40 + (retailSearchArea.minY >> 9)); + const auto retailChains = remorse::buildStagedItemBlockChains(*cachedItems); + assert(retailChains); + const auto retailCandidates = remorse::itemFindCandidateOrder(retailSearchArea, *retailChains); + std::size_t stagedItemsInAreaBlocks = 0; + for (const auto& item : *cachedItems) { + const auto block = (item.data.x >> 9) * 0x40 + (item.data.y >> 9); + for (const auto searchBlock : retailSearchBlocks) { + if (block == searchBlock) { + ++stagedItemsInAreaBlocks; + } + } + } + assert(!retailCandidates.empty() && retailCandidates.size() == stagedItemsInAreaBlocks); + const auto retailGrabCandidates = remorse::itemGrabSearchCandidates(cachedItems->front(), *cachedItems, *typeFlags); + const auto retailGrabActions = remorse::planItemGrabActions(cachedItems->front(), *cachedItems, *typeFlags); + assert(retailGrabCandidates && retailGrabCandidates->size() == 1); + assert(retailGrabActions && retailGrabActions->empty()); origin.data.x = 511; origin.data.y = 511; const auto crossingArea = remorse::itemFindAreaAroundItem(origin, footprint); @@ -73,9 +98,163 @@ int main() const auto edgeArea = remorse::itemFindAreaAroundItem(origin, footprint); assert(edgeArea.minX == 0 && edgeArea.minY == 0); assert((remorse::itemFindBlockOrder(edgeArea) == std::vector{0})); + std::vector blockItems(4); + blockItems[0].itemNumber = 0x100; + blockItems[0].data.x = 511; + blockItems[0].data.y = 511; + blockItems[1].itemNumber = 0x102; + blockItems[1].data.x = 512; + blockItems[1].data.y = 511; + blockItems[2].itemNumber = 0x103; + blockItems[2].data.x = 511; + blockItems[2].data.y = 511; + blockItems[3].itemNumber = 0x104; + blockItems[3].data.x = 512; + blockItems[3].data.y = 512; + const auto chains = remorse::buildStagedItemBlockChains(blockItems); + assert(chains && chains->heads[0] == 0x103 && chains->next[0x103] == 0x100); + assert((remorse::itemFindCandidateOrder(crossingArea, *chains) == + std::vector{0x103, 0x100, 0x102, 0x104})); + blockItems[3].itemNumber = 0x103; + assert(!remorse::buildStagedItemBlockChains(blockItems)); + blockItems[3].itemNumber = 0x104; + blockItems[3].data.x = 0x8000; + assert(!remorse::buildStagedItemBlockChains(blockItems)); + blockItems[3].data.x = 512; + std::vector searchShapes(2, footprint); + auto searchOrigin = origin; + searchOrigin.itemNumber = 0x105; + searchOrigin.data.x = 511; + searchOrigin.data.y = 511; + searchOrigin.data.z = 80; + searchOrigin.data.shape = 1; + for (auto& item : blockItems) { + item.data.shape = 1; + } + blockItems[0].data.z = 81; + blockItems[1].data.z = 0; + blockItems[2].data.z = 79; + blockItems[3].data.z = 81; + blockItems.push_back(searchOrigin); + const auto zMatches = remorse::itemFindZMatches(searchOrigin, blockItems, searchShapes, 3); + assert(zMatches && zMatches->size() == 3); + assert((*zMatches)[0].itemNumber == 0x103 && (*zMatches)[0].matchType == 2); + assert((*zMatches)[1].itemNumber == 0x100 && (*zMatches)[1].matchType == 1); + assert((*zMatches)[2].itemNumber == 0x104 && (*zMatches)[2].matchType == 1); + const auto topMatches = remorse::itemFindZMatches(searchOrigin, blockItems, searchShapes, 1); + assert(topMatches && topMatches->size() == 2); + blockItems[3].data.x = 768; + searchShapes[1].x = 17; + assert(remorse::classifyItemFindZMatch(searchOrigin, searchShapes[1], + blockItems[3], searchShapes[1], 1) == 1); + const auto grabCandidates = remorse::itemGrabSearchCandidates(searchOrigin, blockItems, searchShapes); + assert(grabCandidates && grabCandidates->size() == 2); + assert((*grabCandidates)[0].itemNumber == 0x103 && (*grabCandidates)[0].matchType == 2); + assert((*grabCandidates)[1].itemNumber == 0x100 && (*grabCandidates)[1].matchType == 1); + const auto grabActions = remorse::planItemGrabActions(searchOrigin, blockItems, searchShapes); + assert(grabActions && grabActions->size() == 2); + assert((*grabActions)[0].itemNumber == 0x103 && + (*grabActions)[0].kind == remorse::ItemGrabActionKind::CreateProcess); + assert((*grabActions)[1].itemNumber == 0x100 && + (*grabActions)[1].kind == remorse::ItemGrabActionKind::Hurl); + remorse::ProcessKernel grabKernel; + remorse::u16 grabGroups[32]{}; + for (int index = 0; index < 3; ++index) { + grabKernel.createProcess(1, grabGroups); + } + const auto dispatched = remorse::dispatchStagedItemGrab(searchOrigin, blockItems, searchShapes, + grabKernel, grabGroups, 12); + assert(dispatched && dispatched->size() == 2 && (*dispatched)[0] == 3 && (*dispatched)[1] == 4); + assert(grabKernel.findProcessForItemAndType(0x103, 0xf1) == grabKernel.processAt(3)); + assert(grabKernel.findProcessForItemAndType(0x100, 0x203) == grabKernel.processAt(4)); + const auto repeated = remorse::dispatchStagedItemGrab(searchOrigin, blockItems, searchShapes, + grabKernel, grabGroups, 13); + assert(repeated && repeated->size() == 2 && (*repeated)[0] == 5 && (*repeated)[1] == 4); + assert(grabGroups[1] == 6); + remorse::LiveFixedMapItems liveItems(blockItems); + remorse::ProcessKernel liveKernel; + remorse::u16 liveGroups[32]{}; + for (int index = 0; index < 3; ++index) { + liveKernel.createProcess(1, liveGroups); + } + assert(!liveItems.findItem(0x106) && !liveItems.moveItem(0x106, 0, 0, 0)); + assert(!liveItems.moveItem(0x100, 0x8000, 0, 0)); + assert(liveItems.moveItem(0x100, 768, 511, 81)); + assert(liveItems.findItem(0x100)->data.x == 768 && blockItems[0].data.x == 511); + assert(liveItems.nearestItem(768 * 2, 511 * 2, 0)->itemNumber == 0x100); + assert(!liveItems.nearestItem(511 * 2, 511 * 2, -1)); + assert(!liveItems.grabItem(0x106, searchShapes, liveKernel, liveGroups, 14)); + const auto liveDispatched = liveItems.grabItem(0x105, searchShapes, liveKernel, liveGroups, 14); + assert(liveDispatched && liveDispatched->size() == 1 && (*liveDispatched)[0] == 3); + assert(liveKernel.findProcessForItemAndType(0x103, 0xf1) == liveKernel.processAt(3)); + assert(liveKernel.findProcessForItemAndType(0x100, 0x203) == nullptr); + assert(liveItems.moveItem(0x100, 768, 511, 255)); + assert(liveItems.findItem(0x100)->data.z == 250); + remorse::LiveFixedMapItems reorderedItems(blockItems); + remorse::ProcessKernel reorderedKernel; + remorse::u16 reorderedGroups[32]{}; + for (int index = 0; index < 3; ++index) { + reorderedKernel.createProcess(1, reorderedGroups); + } + assert(reorderedItems.moveItem(0x100, 511, 511, 81)); + const auto reorderedGrab = reorderedItems.grabItem(0x105, searchShapes, + reorderedKernel, reorderedGroups, 14); + assert(reorderedGrab && reorderedGrab->size() == 2 && (*reorderedGrab)[0] == 3 && + (*reorderedGrab)[1] == 4); + assert(reorderedKernel.findProcessForItemAndType(0x100, 0x203) == reorderedKernel.processAt(3)); + assert(reorderedKernel.findProcessForItemAndType(0x103, 0xf1) == reorderedKernel.processAt(4)); + remorse::LiveFixedMapItems insertedItems(blockItems); + remorse::StagedFixedMapItem newItem = blockItems[2]; + newItem.itemNumber = 0x106; + assert(!insertedItems.insertItem(blockItems[2])); + newItem.data.x = 0x8000; + assert(!insertedItems.insertItem(newItem)); + newItem.data.x = 511; + assert(insertedItems.insertItem(newItem)); + assert(insertedItems.findItem(0x106)->data.x == 511); + remorse::ProcessKernel insertedKernel; + remorse::u16 insertedGroups[32]{}; + for (int index = 0; index < 3; ++index) { + insertedKernel.createProcess(1, insertedGroups); + } + const auto insertedGrab = insertedItems.grabItem(0x105, searchShapes, + insertedKernel, insertedGroups, 14); + assert(insertedGrab && insertedGrab->size() == 3 && (*insertedGrab)[0] == 3); + assert(insertedKernel.findProcessForItemAndType(0x106, 0xf1) == insertedKernel.processAt(3)); + remorse::LiveFixedMapItems movingItems(blockItems); + remorse::ProcessKernel movingKernel; + remorse::u16 movingGroups[32]{}; + for (int index = 0; index < 3; ++index) { + movingKernel.createProcess(1, movingGroups); + } + const auto rejectedMove = movingItems.moveApprovedItem(0x105, 0x8000, 0, 0, + searchShapes, movingKernel, movingGroups, 14); + assert(!rejectedMove && movingItems.findItem(0x105)->data.x == 511 && movingKernel.processCount() == 3); + const auto approvedMove = movingItems.moveApprovedItem(0x105, 768, 768, 80, + searchShapes, movingKernel, movingGroups, 14); + assert(approvedMove && approvedMove->size() == 2 && (*approvedMove)[0] == 3 && (*approvedMove)[1] == 4); + assert(movingItems.findItem(0x105)->data.x == 768 && movingItems.findItem(0x105)->data.y == 768); + const auto afterMoveGrab = movingItems.grabItem(0x105, searchShapes, movingKernel, movingGroups, 15); + assert(afterMoveGrab && afterMoveGrab->empty()); + blockItems[0].itemNumber = 0x2400; + const auto priorProcessCount = grabKernel.processCount(); + assert(!remorse::dispatchStagedItemGrab(searchOrigin, blockItems, searchShapes, + grabKernel, grabGroups, 14)); + assert(grabKernel.processCount() == priorProcessCount); + blockItems[0].itemNumber = 0x100; + blockItems[2].data.flags |= 2; + searchShapes[1].weight = 0; + const auto blockedActions = remorse::planItemGrabActions(searchOrigin, blockItems, searchShapes); + assert(blockedActions && blockedActions->empty()); + searchShapes[1].x = 1; + searchOrigin.data.shape = 2; + assert(!remorse::itemFindZMatches(searchOrigin, blockItems, searchShapes, 3)); candidate.itemNumber = 0; assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 0); assert(cachedItems->front().recordIndex < retailMap->entries.size()); + const remorse::LiveFixedMapItems retailLiveItems(*cachedItems); + assert(retailLiveItems.findItem(cachedItems->front().itemNumber)->recordIndex == + cachedItems->front().recordIndex); for (const auto& item : *cachedItems) { const auto& record = retailMap->entries[item.recordIndex]; assert(record.shape != 0 && (record.flags & 8) == 0); @@ -128,6 +307,27 @@ int main() assert((*stagedItems)[0].recordIndex == 1 && (*stagedItems)[0].itemNumber == 0x100); assert((*stagedItems)[1].recordIndex == 3 && (*stagedItems)[1].itemNumber == 0x102); assert((*stagedItems)[1].data.flags == 0); + remorse::FixedMap containedMap; + containedMap.index = 1; + containedMap.entries.resize(5); + for (auto& record : containedMap.entries) { + record.shape = 1; + } + containedMap.entries[1].flags = 8; + containedMap.entries[1].x = 2; + containedMap.entries[2].flags = 8; + containedMap.entries[2].x = 4; + containedMap.entries[3].flags = 8; + containedMap.entries[3].x = 2; + std::vector containerShapes(2); + containerShapes[1].family = 6; + const auto contained = remorse::stageContainedFixedMapItems(containedMap, containerShapes); + assert(contained && contained->size() == 3); + assert((*contained)[0].itemNumber == 0x101 && (*contained)[0].parentItemNumber == 0x100); + assert((*contained)[1].itemNumber == 0x102 && (*contained)[1].parentItemNumber == 0x101); + assert((*contained)[2].itemNumber == 0x103 && (*contained)[2].parentItemNumber == 0x100); + containerShapes[1].family = 0; + assert(!remorse::stageContainedFixedMapItems(containedMap, containerShapes)); assert(remorse::itemGrabCanCreateProcess((*stagedItems)[0])); (*stagedItems)[0].data.flags |= 0x02; assert(!remorse::itemGrabCanCreateProcess((*stagedItems)[0])); diff --git a/rebuild/remorse/tests/type_flags_tests.cpp b/rebuild/remorse/tests/type_flags_tests.cpp index 10cc562..ae30680 100644 --- a/rebuild/remorse/tests/type_flags_tests.cpp +++ b/rebuild/remorse/tests/type_flags_tests.cpp @@ -15,6 +15,11 @@ int main() const auto infos = remorse::loadTypeFlags(*typeFlagPath); assert(infos.has_value()); assert(infos->size() == 2048); + const auto bytes = remorse::readBinaryFile(*typeFlagPath); + assert(bytes && bytes->size() == infos->size() * 9); + for (std::size_t index = 0; index < infos->size(); ++index) { + assert((*infos)[index].weight == (*bytes)[index * 9 + 7]); + } bool foundGlobFamily = false; for (const remorse::ShapeTypeInfo& info : *infos) { From b3975ca41bdcaf60eee2e72507f36c7e794924ed Mon Sep 17 00:00:00 2001 From: Maddo Date: Sat, 26 Sep 2026 19:50:26 +0200 Subject: [PATCH 05/14] Refactor collision handling and item management in the Remorse project - Introduced new structures for handling sweep impacts and collision results, including SweepItemImpact, SweepCandidateImpact, and SweepCollisionResult. - Implemented functions to check if a world point or sweep footprint is within a defined fast area. - Enhanced LiveFixedMapItems to manage contained items and support item allocation with parent-child relationships. - Updated collision detection logic to handle solid item impacts and collect sweep impacts from live items. - Added tests for new collision functionalities, including sweep impact resolution and candidate selection. - Modified existing tests to validate new item management features and ensure proper integration with the collision system. --- docs/remorse-windows-rebuild-roadmap.md | 10 +- rebuild/remorse/include/remorse/collision.h | 39 +++++ rebuild/remorse/include/remorse/fixed_map.h | 10 +- rebuild/remorse/src/collision.cpp | 181 ++++++++++++++++++++ rebuild/remorse/src/fixed_map.cpp | 73 +++++++- rebuild/remorse/src/windowed_game_main.cpp | 12 +- rebuild/remorse/tests/collision_tests.cpp | 117 +++++++++++++ rebuild/remorse/tests/fixed_map_tests.cpp | 33 ++++ 8 files changed, 467 insertions(+), 8 deletions(-) diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 71349c9..f5a7f43 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -324,13 +324,13 @@ A separate diagnostic applies the exported Z/footprint classifier in chain order Contained placement has a separate source-derived diagnostic: for nonzero maps, nonempty contained records consume free IDs, encode nesting depth in the fixed-record X field, ascend the parent link when depth falls, and append children only to container/monster-egg families (`10a8:05e3`, `10a8:2533`, `10a0:0e32`). Synthetic nested/sibling and invalid-parent tests pass; retail map 1 contains no nonzero-shape contained records, so it cannot verify those links. The stage is not a live container cache or a runtime ID-order trace. The shape loader exposes TYPEFLAG row byte 7 as weight, and the `Item_Fall` (`1038:1334`) gate requires a drawable, nonzero-weight shape. The action planner preserves `Item_Grab`'s type-1 fall versus type-2 flag-checked process decision in source order; the first retail origin produces zero actions. -The bounded staged dispatcher can now issue those actions against the host process kernel. `Process_GetProcessForItemAndType` (`11d0:13a4`) scans live slots from 3, ignores terminated entries, and supports item/type wildcards; the host mirrors those rules. `Item_Hurl` (`1038:12a6`) reuses an existing type-`0x203` gravity process and adds velocity, or creates a `0x42`-byte process (`1038:0395`) with zero velocity, gravity 2, and a 20-tick sleep for a fall request. Tests cover both branches, duplicate item-process requests, strict wake, ownership and ID-limit rejection, and teardown/reuse. Staged dispatch rejects any out-of-range action before starting; the Windows `F` key is still a separate release fixture. A host-owned `LiveFixedMapItems` copy now supports ID lookup, bounded position changes, and `Item_Grab` dispatch against current item positions; the window owns this copy for nearby-item lookup. `Item_LegalMoveToPointWithCollisionInfo` (`10a0:1841`) calls `Item_Grab` before `AreaSearch_CollideMove` on its successful path; `moveApprovedItem` preserves that ordering once a caller has approved the move, and tests distinguish old-position requests from post-move search. Synthetic move/dispatch and retail-map ownership tests pass. This is not the original item cache, does not yet provide a legal-move collision event or update rendered sprites, and does not include contained items. `runUnobstructedGravity` now moves an owned item and advances/sleeps its owned process in the nonzero-vertical-speed branch after explicit caller-supplied approval of the full pre-sweep target. A refused or missing sweep makes no mutation; tests cover both paths. This does not execute the zero-speed fall/`Item_Grab` branch, process collision responses, map fast-area gate, or an automatic scheduler tick. The original `AreaSearch_SweepTestItem` (`10e0:1151`) forwards into `AreaSearch_SweepTestPt` (`10e0:0b39`), which requires fast-area map blocks, item iteration, and resolved collision points absent from the host's boolean-only sweep. DOSBox-X is now installed at `C:\DOSBox-X`, but its interactive debugger has not produced a retail map-load or ItemFind trace; runtime IDs, parents, and first/next search behavior still lack original-execution trace parity. +The bounded staged dispatcher can now issue those actions against the host process kernel. `Process_GetProcessForItemAndType` (`11d0:13a4`) scans live slots from 3, ignores terminated entries, and supports item/type wildcards; the host mirrors those rules. `Item_Hurl` (`1038:12a6`) reuses an existing type-`0x203` gravity process and adds velocity, or creates a `0x42`-byte process (`1038:0395`) with zero velocity, gravity 2, and a 20-tick sleep for a fall request. Tests cover both branches, duplicate item-process requests, strict wake, ownership and ID-limit rejection, and teardown/reuse. Staged dispatch rejects any out-of-range action before starting; the Windows `F` key is still a separate release fixture. A host-owned `LiveFixedMapItems` copy now supports ID lookup, bounded position changes, and `Item_Grab` dispatch against current item positions; the window owns this copy for nearby-item lookup. `Item_LegalMoveToPointWithCollisionInfo` (`10a0:1841`) calls `Item_Grab` before `AreaSearch_CollideMove` on its successful path; `moveApprovedItem` preserves that ordering once a caller has approved the move, and tests distinguish old-position requests from post-move search. Synthetic move/dispatch and retail-map ownership tests pass. This is not the original item cache, does not yet provide a legal-move collision event or update rendered sprites, and does not include live contained items. `runUnobstructedGravity` moves an owned item and advances/sleeps its owned process in the nonzero-vertical-speed branch after explicit caller-supplied approval of the full pre-sweep target. A refused or missing sweep makes no mutation on that path. On the zero-Z horizontal path, it requests `Item_Grab` before sweep approval, so a refused sweep may still leave a process request. The stationary zero-speed fall search, collision responses, live fast-area state, and automatic scheduler tick remain unported. The original `AreaSearch_SweepTestItem` (`10e0:1151`) forwards into `AreaSearch_SweepTestPt` (`10e0:0b39`); the host has bounded fast-area and item-iterator gates but not resolved collision points. Runtime ID and search-order parity remain unverified and are not a current gate. -The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied, newly allocated item IDs can also be inserted at a block head with duplicate and placement guards. Focused tests verify process request order for moved and inserted items and the Z value; the host still lacks free-ID allocation, fast-area, viewport, and contained-item side effects. +The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied item IDs can also be inserted at a block head. The host free-ID allocator uses the source `0x100..0x27ff` range, skips staged direct and contained records, and fails without mutation when exhausted. The window reserves staged contained IDs and retains their parent links; placing one in the world clears its parent while its children remain linked. Synthetic nested/exhaustion and retail-map tests pass. This does not yet implement returning freed IDs to the list, live inventory/container transfers, fast-area status, or viewport side effects. The supported horizontal `GravityProcess_Run` path now issues `Item_Grab` at the old item position when Z speed is zero and X/Y speed is nonzero, then asks the injected sweep to approve movement. As in the source order, a refused sweep can leave a newly requested item process behind while the item stays put. The earlier no-mutation guarantee for a refused sweep applies only to the nonzero-Z path, which does not issue that request. The stationary zero-speed fall search, collision response, and automatic scheduler dispatch are still unported; a caller must provide shapes, group counts, and the sweep decision for this host-only branch. -The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. Tests cover combined and Z-only out-of-range targets. It is not yet the sweep's fast-area, item-iteration, or collision-resolution stage, and the gravity runner still requires an explicit approved sweep callback. +The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. The source's `World_MapBlockInFastArea` (`10a8:0000`) rotated block predicate and eight-corner start/destination footprint gate are now testable with an explicit fast-area range. The sweep's item-iterator rectangle and live candidate query follow inclusive X/Y filtering and Y-then-X block order. The per-item sweep uses 16-unit X/Y extents, 8-unit Z extents with the source zero-height fallback, and six axis-face tests that report one-unit-before-contact points and failed-direction bits. A read-only live collector combines those tests with candidate order, shape solidity and flip flags, and an explicit fast-area range. The host now selects a solid hit in source order when any axis is strictly closer, retains the earlier hit on a tie, and accumulates direction bits across contacts; a live entry point returns the resulting point and first colliding item. Synthetic tests cover both directions on all axes, self-exclusion, non-solid items, chain order, flipped shapes, and candidate selection. It does not handle damaging-only or floor contacts, maintain live fast-area state, or drive gravity movement. The gravity runner still requires an explicit approved sweep callback. Original DOS debugging and runtime verification are postponed indefinitely until requested again. The DOSBox-X debugger session has been stopped; do not treat a live trace as a prerequisite for the source-port work below. Keep unverified parity claims labeled as such. @@ -338,8 +338,8 @@ Next source-port checks, in call-chain order: 1. Keep the `0x23ff/0x2400` process item boundary until source-derived allocation limits support changing it; do not infer a wider live table from staged map IDs. 2. Port the remaining scheduler interval/group transitions behind host timing boundaries using static code evidence, with runtime parity explicitly deferred. -3. Port original free-ID allocation and contained-item ownership, and connect the caller-supplied live insert path to those allocation events. -4. Port the area sweep's fast-area and item-collision resolution, including failed directions and resolved points, before enabling collision-driven movement. +3. Port free-ID return/reuse and live container transfers while preserving contained parent/child links and process ownership. +4. Add damaging-only and mode-dependent floor contacts, then combine the solid-hit result with bounds and fast-area failures before enabling collision-driven movement. 5. Port the `GravityProcess_Run` area sweep, collision responses, and item-cache position/status writes to make created gravity entries move real items after their sleep. 6. Connect the approved-move `Item_Grab` path to a ported `Item_LegalMoveToPointWithCollisionInfo` sweep and item-cache lifecycle, without changing the separate Windows `F` release fixture. 7. Lift `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`) and its interpreter initialization; keep release event-body lookup diagnostic until the VM executes it. diff --git a/rebuild/remorse/include/remorse/collision.h b/rebuild/remorse/include/remorse/collision.h index 16bed27..9fc32d9 100644 --- a/rebuild/remorse/include/remorse/collision.h +++ b/rebuild/remorse/include/remorse/collision.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include "remorse\fixed_map.h" @@ -27,10 +28,48 @@ struct SweepBoundsResult { bool failed = false; }; +struct SweepItemImpact { + WorldPoint resolved{}; + u8 failedDirections = 0; +}; + +struct SweepCandidateImpact { + u16 itemNumber = 0; + SweepItemImpact impact{}; +}; + +struct SweepCollisionResult { + WorldPoint destination{}; + u16 firstCollision = 0; + u8 failedDirections = 0; +}; + +struct FastAreaRange { + s32 minSum = 0; + s32 maxSum = 0; + s32 minDifference = 0; + s32 maxDifference = 0; +}; + +bool isWorldPointInFastArea(s32 x, s32 y, const FastAreaRange& range); +bool isSweepFootprintInFastArea(WorldPoint from, WorldPoint destination, + s32 extentX, s32 extentY, const FastAreaRange& range); +WorldRect areaSweepCandidateBounds(WorldPoint from, WorldPoint destination, s32 extentX, s32 extentY); SweepBoundsResult clampAreaSweepBounds(WorldPoint from, WorldPoint destination); GravitySweepPlan planGravitySweep(WorldPoint location, s16 xSpeed, s16 ySpeed, s16 zSpeed, s16 gravity, u32 timeScale); CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped = false); +CollisionBody makeSweepItemBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped = false); +std::optional sweepSolidItemImpact( + const CollisionBody& moving, WorldPoint destination, const CollisionBody& obstacle); +std::optional> collectSolidSweepImpacts( + const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, + const std::vector& shapes, const FastAreaRange& fastArea); +SweepCollisionResult selectSolidSweepImpact(WorldPoint from, WorldPoint destination, + const std::vector& impacts); +std::optional resolveSolidLiveSweep( + const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, + const std::vector& shapes, const FastAreaRange& fastArea); bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right); bool canMoveCollisionBody( const CollisionBody& body, diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index 37ac7a7..184964c 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -9,6 +9,7 @@ namespace remorse { struct ShapeTypeInfo; +struct WorldRect; class ProcessKernel; struct FixedMapEntry { @@ -100,9 +101,13 @@ std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& class LiveFixedMapItems { public: - explicit LiveFixedMapItems(std::vector items); + explicit LiveFixedMapItems(std::vector items, + std::vector containedItems = {}); const StagedFixedMapItem* findItem(u16 itemNumber) const; + u16 containedParent(u16 itemNumber) const; std::optional nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const; + std::optional> sweepCandidateIds(const WorldRect& area, u16 excludedItemNumber) const; + std::optional allocateItem(StagedFixedMapItem item); bool insertItem(StagedFixedMapItem item); bool moveItem(u16 itemNumber, u16 x, u16 y, u8 z); std::optional> grabItem(u16 itemNumber, const std::vector& shapes, @@ -113,6 +118,9 @@ public: private: std::vector items_; + std::vector allocatedIds_; + std::vector parentById_; + u16 nextFreeItemNumber_ = 0x100; }; } // namespace remorse diff --git a/rebuild/remorse/src/collision.cpp b/rebuild/remorse/src/collision.cpp index 68f44b4..b14a01b 100644 --- a/rebuild/remorse/src/collision.cpp +++ b/rebuild/remorse/src/collision.cpp @@ -1,6 +1,7 @@ #include "remorse/collision.h" #include +#include #include namespace remorse { @@ -77,6 +78,40 @@ void appendSolidBody(std::vector& bodies, const std::vector 0x7fff || y < 0 || y > 0x7fff) { + return false; + } + const s32 blockX = x >> 9; + const s32 blockY = y >> 9; + return range.minSum <= blockX + blockY && blockX + blockY <= range.maxSum && + range.minDifference <= blockX - blockY && blockX - blockY <= range.maxDifference; +} + +bool isSweepFootprintInFastArea(WorldPoint from, WorldPoint destination, + s32 extentX, s32 extentY, const FastAreaRange& range) +{ + for (const WorldPoint point : {from, destination}) { + for (const s32 x : {point.x - extentX + 1, point.x}) { + for (const s32 y : {point.y - extentY + 1, point.y}) { + if (!isWorldPointInFastArea(x, y, range)) { + return false; + } + } + } + } + return true; +} + +WorldRect areaSweepCandidateBounds(WorldPoint from, WorldPoint destination, s32 extentX, s32 extentY) +{ + return {std::max(0, std::min(from.x, destination.x) - extentX), + std::max(0, std::min(from.y, destination.y) - extentY), + std::min(0x7fff, std::max(from.x, destination.x) + 0x100), + std::min(0x7fff, std::max(from.y, destination.y) + 0x100)}; +} + SweepBoundsResult clampAreaSweepBounds(WorldPoint from, WorldPoint destination) { SweepBoundsResult result{destination}; @@ -117,6 +152,152 @@ CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeI static_cast(shapeInfo.z) * shapeHeightScale}; } +CollisionBody makeSweepItemBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped) +{ + const s32 extentX = static_cast(flipped ? shapeInfo.y : shapeInfo.x) * 16; + const s32 extentY = static_cast(flipped ? shapeInfo.x : shapeInfo.y) * 16; + const s32 extentZ = shapeInfo.z == 0 && (shapeInfo.flags & 1) == 0 ? 1 : + static_cast(shapeInfo.z) * shapeHeightScale; + return {location, extentX, extentY, extentZ}; +} + +std::optional sweepSolidItemImpact( + const CollisionBody& moving, WorldPoint destination, const CollisionBody& obstacle) +{ + if (moving.extentX <= 0 || moving.extentY <= 0 || moving.extentZ <= 0 || + obstacle.extentX <= 0 || obstacle.extentY <= 0 || obstacle.extentZ <= 0) { + return std::nullopt; + } + const std::array origin{moving.location.x, moving.location.y, moving.location.z}; + const std::array delta{ + static_cast(destination.x) - origin[0], + static_cast(destination.y) - origin[1], + static_cast(destination.z) - origin[2]}; + const std::array obstaclePosition{ + obstacle.location.x, obstacle.location.y, obstacle.location.z}; + const std::array movingExtent{moving.extentX, moving.extentY, moving.extentZ}; + const std::array obstacleExtent{obstacle.extentX, obstacle.extentY, obstacle.extentZ}; + std::array lower{}; + std::array upper{}; + for (std::size_t axis = 0; axis < 3; ++axis) { + lower[axis] = obstaclePosition[axis] - obstacleExtent[axis] + 1 - origin[axis]; + upper[axis] = obstaclePosition[axis] + movingExtent[axis] - 1 - origin[axis]; + } + lower[2] = obstaclePosition[2] - movingExtent[2] + 1 - origin[2]; + upper[2] = obstaclePosition[2] + obstacleExtent[2] - 1 - origin[2]; + + for (const int direction : {1, -1}) { + for (std::size_t axis = 0; axis < 3; ++axis) { + const std::int64_t distance = direction > 0 ? lower[axis] : -upper[axis]; + const std::int64_t extent = delta[axis] * direction; + if (distance <= 0 || distance > extent) { + continue; + } + bool withinOtherAxes = true; + for (std::size_t other = 0; other < 3; ++other) { + if (other == axis) { + continue; + } + const std::int64_t progress = delta[other] * distance; + if (progress < lower[other] * extent || progress > upper[other] * extent) { + withinOtherAxes = false; + break; + } + } + if (withinOtherAxes) { + const std::int64_t beforeContact = distance - 1; + std::array resolved{}; + for (std::size_t coordinate = 0; coordinate < 3; ++coordinate) { + resolved[coordinate] = static_cast(origin[coordinate] + + delta[coordinate] * beforeContact / extent); + } + return SweepItemImpact{{resolved[0], resolved[1], resolved[2]}, + static_cast(1u << axis)}; + } + } + } + return std::nullopt; +} + +std::optional> collectSolidSweepImpacts( + const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, + const std::vector& shapes, const FastAreaRange& fastArea) +{ + const auto* movingItem = items.findItem(movingItemNumber); + if (movingItem == nullptr || movingItem->data.shape >= shapes.size() || + destination.x < 0 || destination.x > 0x7fff || destination.y < 0 || + destination.y > 0x7fff || destination.z < 0 || destination.z > 0xfa) { + return std::nullopt; + } + const WorldPoint from{movingItem->data.x, movingItem->data.y, movingItem->data.z}; + const auto movingBody = makeSweepItemBody(from, shapes[movingItem->data.shape], + (movingItem->data.flags & flippedFlag) != 0); + if (!isSweepFootprintInFastArea(from, destination, movingBody.extentX, + movingBody.extentY, fastArea)) { + return std::nullopt; + } + const auto candidates = items.sweepCandidateIds(areaSweepCandidateBounds(from, destination, + movingBody.extentX, movingBody.extentY), movingItemNumber); + if (!candidates) { + return std::nullopt; + } + std::vector impacts; + for (const u16 itemNumber : *candidates) { + const auto* item = items.findItem(itemNumber); + if (item == nullptr || item->data.shape >= shapes.size()) { + return std::nullopt; + } + const auto& shape = shapes[item->data.shape]; + if ((shape.flags & solidFlag) == 0) { + continue; + } + const auto obstacle = makeSweepItemBody({item->data.x, item->data.y, item->data.z}, + shape, (item->data.flags & flippedFlag) != 0); + if (const auto impact = sweepSolidItemImpact(movingBody, destination, obstacle)) { + impacts.push_back({itemNumber, *impact}); + } + } + return impacts; +} + +SweepCollisionResult selectSolidSweepImpact(WorldPoint from, WorldPoint destination, + const std::vector& impacts) +{ + SweepCollisionResult result{destination}; + for (const auto& candidate : impacts) { + result.failedDirections |= candidate.impact.failedDirections; + const auto& point = candidate.impact.resolved; + if (candidate.itemNumber != 0 && + (std::abs(static_cast(point.x) - from.x) < + std::abs(static_cast(result.destination.x) - from.x) || + std::abs(static_cast(point.y) - from.y) < + std::abs(static_cast(result.destination.y) - from.y) || + std::abs(static_cast(point.z) - from.z) < + std::abs(static_cast(result.destination.z) - from.z))) { + result.destination = point; + result.firstCollision = candidate.itemNumber; + } + } + return result; +} + +std::optional resolveSolidLiveSweep( + const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, + const std::vector& shapes, const FastAreaRange& fastArea) +{ + const auto* movingItem = items.findItem(movingItemNumber); + if (movingItem == nullptr) { + return std::nullopt; + } + const auto impacts = collectSolidSweepImpacts(items, movingItemNumber, destination, + shapes, fastArea); + if (!impacts) { + return std::nullopt; + } + return selectSolidSweepImpact({movingItem->data.x, movingItem->data.y, movingItem->data.z}, + destination, *impacts); +} + bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right) { return overlapsAt(left, left.location, right); diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index 140a84d..79d4fa5 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -2,6 +2,7 @@ #include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" +#include "remorse/map_renderer.h" #include "remorse/type_flags.h" #include @@ -412,11 +413,30 @@ std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& return processIds; } -LiveFixedMapItems::LiveFixedMapItems(std::vector items) : items_(std::move(items)) +LiveFixedMapItems::LiveFixedMapItems(std::vector items, + std::vector containedItems) + : items_(std::move(items)), allocatedIds_(0x2800), parentById_(0x2800) { if (!buildStagedItemBlockChains(items_)) { throw std::invalid_argument("invalid live item IDs or coordinates"); } + for (const auto& item : items_) { + allocatedIds_[item.itemNumber] = true; + } + for (const auto& contained : containedItems) { + const u16 itemNumber = contained.itemNumber; + if (itemNumber < 0x100 || itemNumber >= allocatedIds_.size() || allocatedIds_[itemNumber]) { + throw std::invalid_argument("invalid contained item ID"); + } + allocatedIds_[itemNumber] = true; + } + for (const auto& contained : containedItems) { + if (contained.parentItemNumber < 0x100 || contained.parentItemNumber >= contained.itemNumber || + !allocatedIds_[contained.parentItemNumber]) { + throw std::invalid_argument("invalid contained parent ID"); + } + parentById_[contained.itemNumber] = contained.parentItemNumber; + } } const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const @@ -429,12 +449,61 @@ const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const return nullptr; } +u16 LiveFixedMapItems::containedParent(u16 itemNumber) const +{ + return itemNumber < parentById_.size() ? parentById_[itemNumber] : 0; +} + std::optional LiveFixedMapItems::nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const { return nearestStagedFixedMapItem(items_, worldX, worldY, maxDistance); } +std::optional> LiveFixedMapItems::sweepCandidateIds(const WorldRect& area, + u16 excludedItemNumber) const +{ + if (area.minX < 0 || area.minY < 0 || area.maxX > 0x7fff || area.maxY > 0x7fff || + area.minX > area.maxX || area.minY > area.maxY) { + return std::nullopt; + } + const auto chains = buildStagedItemBlockChains(items_); + if (!chains) { + return std::nullopt; + } + std::vector byId(chains->next.size()); + for (const auto& item : items_) { + byId[item.itemNumber] = &item; + } + const ItemFindArea itemArea{static_cast(area.minX), static_cast(area.minY), + static_cast(area.maxX), static_cast(area.maxY)}; + std::vector candidates; + for (const u16 itemNumber : itemFindCandidateOrder(itemArea, *chains)) { + const auto& item = *byId[itemNumber]; + if (itemNumber != excludedItemNumber && item.data.x >= area.minX && item.data.x <= area.maxX && + item.data.y >= area.minY && item.data.y <= area.maxY) { + candidates.push_back(itemNumber); + } + } + return candidates; +} + +std::optional LiveFixedMapItems::allocateItem(StagedFixedMapItem item) +{ + if (item.data.x > 0x7fff || item.data.y > 0x7fff) { + return std::nullopt; + } + while (nextFreeItemNumber_ < allocatedIds_.size() && allocatedIds_[nextFreeItemNumber_]) { + ++nextFreeItemNumber_; + } + if (nextFreeItemNumber_ == allocatedIds_.size()) { + return std::nullopt; + } + item.itemNumber = nextFreeItemNumber_; + insertItem(item); + return item.itemNumber; +} + bool LiveFixedMapItems::insertItem(StagedFixedMapItem item) { if (item.itemNumber < 0x100 || item.itemNumber >= 0x2800 || item.data.x > 0x7fff || @@ -443,6 +512,8 @@ bool LiveFixedMapItems::insertItem(StagedFixedMapItem item) } item.data.z = std::min(item.data.z, 0xfa); items_.push_back(item); + allocatedIds_[item.itemNumber] = true; + parentById_[item.itemNumber] = 0; return true; } diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index becb72f..fa3712d 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -160,6 +160,16 @@ void loadSceneAsync(HWND window, AppState& state) PostMessageW(window, sceneReadyMessage, 0, 0); return; } + std::vector containedItems; + if (map->index != 0) { + const auto contained = remorse::stageContainedFixedMapItems(*map, *shapeTypes); + if (!contained) { + setLoadFailure(state, L"Contained map items could not be staged."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + containedItems = std::move(*contained); + } auto collisionBodies = remorse::collectMapCollisionBodies(*map, *shapeTypes, *globObjects); const auto usecodePath = remorse::resolveGameDataPath( state.root, std::filesystem::path("USECODE") / "EUSECODE.FLX"); @@ -281,7 +291,7 @@ void loadSceneAsync(HWND window, AppState& state) state.playerFrames = std::move(playerFrames); state.playerPalette = *palette; if (stagedItems) { - state.liveItems.emplace(std::move(*stagedItems)); + state.liveItems.emplace(std::move(*stagedItems), std::move(containedItems)); } state.sceneLoaded = true; } diff --git a/rebuild/remorse/tests/collision_tests.cpp b/rebuild/remorse/tests/collision_tests.cpp index b3b06e6..bde848a 100644 --- a/rebuild/remorse/tests/collision_tests.cpp +++ b/rebuild/remorse/tests/collision_tests.cpp @@ -4,6 +4,24 @@ int main() { + const remorse::FastAreaRange fastArea{2, 4, 0, 2}; + assert(remorse::isWorldPointInFastArea(512, 512, fastArea)); + assert(!remorse::isWorldPointInFastArea(-1, 512, fastArea)); + assert(!remorse::isWorldPointInFastArea(0x8000, 512, fastArea)); + assert(remorse::isSweepFootprintInFastArea({1000, 1000, 0}, {2000, 1000, 0}, + 32, 32, fastArea)); + assert(!remorse::isSweepFootprintInFastArea({1000, 1000, 0}, {2000, 1000, 0}, + 32, 32, {2, 3, 0, 2})); + assert(!remorse::isSweepFootprintInFastArea({1000, 1000, 0}, {2000, 1000, 0}, + 32, 32, {2, 4, 1, 2})); + const auto sweepArea = remorse::areaSweepCandidateBounds({511, 512, 0}, {1024, 1536, 0}, 32, 64); + assert(sweepArea.minX == 479 && sweepArea.minY == 448 && + sweepArea.maxX == 1280 && sweepArea.maxY == 1792); + const auto reverseArea = remorse::areaSweepCandidateBounds({1024, 1536, 0}, {511, 512, 0}, 32, 64); + assert(reverseArea.minX == sweepArea.minX && reverseArea.maxY == sweepArea.maxY); + const auto edgeSweepArea = remorse::areaSweepCandidateBounds({10, 10, 0}, {0x7fff, 0x7fff, 0}, 32, 64); + assert(edgeSweepArea.minX == 0 && edgeSweepArea.minY == 0 && + edgeSweepArea.maxX == 0x7fff && edgeSweepArea.maxY == 0x7fff); const auto outsideBounds = remorse::clampAreaSweepBounds({10, 20, 10}, {-3, 0x8000, 252}); assert(outsideBounds.destination.x == 0 && outsideBounds.destination.y == 0x7fff && outsideBounds.destination.z == 250 && outsideBounds.failedDirections == 7 && @@ -56,6 +74,105 @@ int main() assert(flipped.extentX == 128); assert(flipped.extentY == 64); + const auto sweepItem = remorse::makeSweepItemBody({300, 300, 0}, obstacleInfo, true); + assert(sweepItem.extentX == 64 && sweepItem.extentY == 32 && sweepItem.extentZ == 64); + obstacleInfo.z = 0; + const auto zeroHeightItem = remorse::makeSweepItemBody({300, 300, 0}, obstacleInfo); + assert(zeroHeightItem.extentZ == 1); + obstacleInfo.flags = 1; + assert(remorse::makeSweepItemBody({300, 300, 0}, obstacleInfo).extentZ == 0); + obstacleInfo.z = 8; + obstacleInfo.flags = 0; + + const remorse::CollisionBody sweepActor{{100, 100, 0}, 32, 32, 16}; + const remorse::CollisionBody sweepWall{{200, 100, 0}, 32, 32, 16}; + const auto rightHit = remorse::sweepSolidItemImpact(sweepActor, {250, 100, 0}, sweepWall); + assert(rightHit && rightHit->failedDirections == 1 && rightHit->resolved.x == 168); + const auto leftHit = remorse::sweepSolidItemImpact({{300, 100, 0}, 32, 32, 16}, + {150, 100, 0}, sweepWall); + assert(leftHit && leftHit->failedDirections == 1 && leftHit->resolved.x == 232); + const auto upHit = remorse::sweepSolidItemImpact(sweepActor, {100, 250, 0}, + {{100, 200, 0}, 32, 32, 16}); + assert(upHit && upHit->failedDirections == 2 && upHit->resolved.y == 168); + const auto downHit = remorse::sweepSolidItemImpact({{100, 300, 0}, 32, 32, 16}, + {100, 150, 0}, {{100, 200, 0}, 32, 32, 16}); + assert(downHit && downHit->failedDirections == 2 && downHit->resolved.y == 232); + const auto ascendingHit = remorse::sweepSolidItemImpact(sweepActor, {100, 100, 30}, + {{100, 100, 20}, 32, 32, 16}); + assert(ascendingHit && ascendingHit->failedDirections == 4 && ascendingHit->resolved.z == 4); + const auto descendingHit = remorse::sweepSolidItemImpact({{100, 100, 40}, 32, 32, 16}, + {100, 100, 0}, {{100, 100, 20}, 32, 32, 16}); + assert(descendingHit && descendingHit->failedDirections == 4 && descendingHit->resolved.z == 36); + assert(!remorse::sweepSolidItemImpact(sweepActor, {250, 100, 0}, + {{200, 200, 0}, 32, 32, 16})); + + remorse::StagedFixedMapItem movingItem; + movingItem.itemNumber = 0x100; + movingItem.data.x = 512; + movingItem.data.y = 512; + movingItem.data.shape = 1; + auto wallItem = movingItem; + wallItem.itemNumber = 0x101; + wallItem.data.x = 640; + wallItem.data.shape = 2; + auto harmlessItem = wallItem; + harmlessItem.itemNumber = 0x102; + harmlessItem.data.x = 600; + harmlessItem.data.shape = 3; + remorse::LiveFixedMapItems liveSweepItems({movingItem, wallItem, harmlessItem}); + std::vector sweepShapes(4); + sweepShapes[1].x = sweepShapes[1].y = sweepShapes[1].z = 2; + sweepShapes[2] = sweepShapes[1]; + sweepShapes[2].flags = 2; + sweepShapes[3] = sweepShapes[1]; + const remorse::FastAreaRange allBlocks{-128, 128, -128, 128}; + const auto liveImpacts = remorse::collectSolidSweepImpacts(liveSweepItems, 0x100, + {700, 512, 0}, sweepShapes, allBlocks); + assert(liveImpacts && liveImpacts->size() == 1); + assert((*liveImpacts)[0].itemNumber == 0x101 && + (*liveImpacts)[0].impact.failedDirections == 1 && + (*liveImpacts)[0].impact.resolved.x == 608); + auto nextWall = wallItem; + nextWall.itemNumber = 0x103; + nextWall.data.x = 670; + sweepShapes[2].x = 1; + sweepShapes[2].y = 4; + wallItem.data.flags = 0x20; + remorse::LiveFixedMapItems flippedSweepItems({movingItem, wallItem, nextWall, harmlessItem}); + const auto flippedImpacts = remorse::collectSolidSweepImpacts(flippedSweepItems, 0x100, + {700, 512, 0}, sweepShapes, allBlocks); + assert(flippedImpacts && flippedImpacts->size() == 2); + assert((*flippedImpacts)[0].itemNumber == 0x103 && (*flippedImpacts)[0].impact.resolved.x == 654); + assert((*flippedImpacts)[1].itemNumber == 0x101 && (*flippedImpacts)[1].impact.resolved.x == 576); + const auto nearestImpact = remorse::selectSolidSweepImpact({512, 512, 0}, + {700, 512, 0}, *flippedImpacts); + assert(nearestImpact.firstCollision == 0x101 && nearestImpact.destination.x == 576 && + nearestImpact.failedDirections == 1); + const auto resolvedLive = remorse::resolveSolidLiveSweep(flippedSweepItems, 0x100, + {700, 512, 0}, sweepShapes, allBlocks); + assert(resolvedLive && resolvedLive->firstCollision == 0x101 && + resolvedLive->destination.x == 576 && resolvedLive->failedDirections == 1); + assert(!remorse::resolveSolidLiveSweep(flippedSweepItems, 0x100, + {700, 512, 0}, sweepShapes, {2, 2, 0, 0})); + const auto noImpact = remorse::selectSolidSweepImpact({512, 512, 0}, {700, 512, 0}, {}); + assert(noImpact.firstCollision == 0 && noImpact.destination.x == 700 && + noImpact.failedDirections == 0); + const std::vector tiedImpacts{ + {0x101, {{576, 512, 0}, 1}}, {0x103, {{576, 512, 0}, 2}}}; + const auto tiedImpact = remorse::selectSolidSweepImpact({512, 512, 0}, + {700, 512, 0}, tiedImpacts); + assert(tiedImpact.firstCollision == 0x101 && tiedImpact.failedDirections == 3); + const std::vector mixedAxisImpacts{ + {0x101, {{540, 590, 0}, 1}}, {0x103, {{550, 550, 0}, 2}}}; + const auto mixedAxis = remorse::selectSolidSweepImpact({512, 512, 0}, + {700, 700, 0}, mixedAxisImpacts); + assert(mixedAxis.firstCollision == 0x103 && mixedAxis.destination.x == 550 && + mixedAxis.destination.y == 550 && mixedAxis.failedDirections == 3); + assert(!remorse::collectSolidSweepImpacts(liveSweepItems, 0x100, + {700, 512, 0}, sweepShapes, {2, 2, 0, 0})); + assert(!remorse::collectSolidSweepImpacts(liveSweepItems, 0x105, + {700, 512, 0}, sweepShapes, allBlocks)); + remorse::FixedMap map; remorse::FixedMapEntry solid; solid.x = 500; diff --git a/rebuild/remorse/tests/fixed_map_tests.cpp b/rebuild/remorse/tests/fixed_map_tests.cpp index 5a043da..bd81532 100644 --- a/rebuild/remorse/tests/fixed_map_tests.cpp +++ b/rebuild/remorse/tests/fixed_map_tests.cpp @@ -1,6 +1,7 @@ #include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" #include "remorse/fixed_map.h" +#include "remorse/map_renderer.h" #include "remorse/type_flags.h" #include @@ -181,6 +182,9 @@ int main() assert(!liveItems.moveItem(0x100, 0x8000, 0, 0)); assert(liveItems.moveItem(0x100, 768, 511, 81)); assert(liveItems.findItem(0x100)->data.x == 768 && blockItems[0].data.x == 511); + const auto sweepBefore = liveItems.sweepCandidateIds({511, 511, 512, 512}, 0x105); + assert(sweepBefore && (*sweepBefore == std::vector{0x103, 0x102})); + assert(!liveItems.sweepCandidateIds({-1, 0, 512, 512}, 0x105)); assert(liveItems.nearestItem(768 * 2, 511 * 2, 0)->itemNumber == 0x100); assert(!liveItems.nearestItem(511 * 2, 511 * 2, -1)); assert(!liveItems.grabItem(0x106, searchShapes, liveKernel, liveGroups, 14)); @@ -197,6 +201,8 @@ int main() reorderedKernel.createProcess(1, reorderedGroups); } assert(reorderedItems.moveItem(0x100, 511, 511, 81)); + const auto sweepAfter = reorderedItems.sweepCandidateIds({511, 511, 512, 512}, 0x105); + assert(sweepAfter && (*sweepAfter == std::vector{0x100, 0x103, 0x102})); const auto reorderedGrab = reorderedItems.grabItem(0x105, searchShapes, reorderedKernel, reorderedGroups, 14); assert(reorderedGrab && reorderedGrab->size() == 2 && (*reorderedGrab)[0] == 3 && @@ -221,6 +227,14 @@ int main() insertedKernel, insertedGroups, 14); assert(insertedGrab && insertedGrab->size() == 3 && (*insertedGrab)[0] == 3); assert(insertedKernel.findProcessForItemAndType(0x106, 0xf1) == insertedKernel.processAt(3)); + remorse::LiveFixedMapItems allocatedItems(blockItems, {{0x101, 0x100, 0}}); + newItem.itemNumber = 0; + assert(!allocatedItems.findItem(0x101)); + assert(allocatedItems.allocateItem(newItem) == 0x106); + assert(allocatedItems.findItem(0x106)->data.x == 511); + assert(allocatedItems.allocateItem(newItem) == 0x107); + newItem.data.x = 0x8000; + assert(!allocatedItems.allocateItem(newItem) && !allocatedItems.findItem(0x108)); remorse::LiveFixedMapItems movingItems(blockItems); remorse::ProcessKernel movingKernel; remorse::u16 movingGroups[32]{}; @@ -326,6 +340,25 @@ int main() assert((*contained)[0].itemNumber == 0x101 && (*contained)[0].parentItemNumber == 0x100); assert((*contained)[1].itemNumber == 0x102 && (*contained)[1].parentItemNumber == 0x101); assert((*contained)[2].itemNumber == 0x103 && (*contained)[2].parentItemNumber == 0x100); + const auto directContainerItems = remorse::stageFixedMapItems(containedMap); + assert(directContainerItems && directContainerItems->size() == 2); + remorse::LiveFixedMapItems nestedItems(*directContainerItems, *contained); + assert(nestedItems.containedParent(0x101) == 0x100 && + nestedItems.containedParent(0x102) == 0x101 && nestedItems.containedParent(0x103) == 0x100); + remorse::StagedFixedMapItem nestedNewItem = directContainerItems->front(); + assert(nestedItems.allocateItem(nestedNewItem) == 0x105); + assert(!nestedItems.findItem(0x101) && !nestedItems.findItem(0x102) && + !nestedItems.findItem(0x103) && nestedItems.findItem(0x105)); + nestedNewItem.itemNumber = 0x101; + assert(nestedItems.insertItem(nestedNewItem)); + assert(nestedItems.containedParent(0x101) == 0 && nestedItems.containedParent(0x102) == 0x101); + std::vector fullItemRange; + for (remorse::u16 itemNumber = 0x101; itemNumber < 0x2800; ++itemNumber) { + fullItemRange.push_back({itemNumber, 0x100, 0}); + } + remorse::LiveFixedMapItems exhaustedItems({directContainerItems->front()}, fullItemRange); + assert(!exhaustedItems.allocateItem(nestedNewItem)); + assert(!exhaustedItems.findItem(0x101) && exhaustedItems.containedParent(0x101) == 0x100); containerShapes[1].family = 0; assert(!remorse::stageContainedFixedMapItems(containedMap, containerShapes)); assert(remorse::itemGrabCanCreateProcess((*stagedItems)[0])); From 2e16b2d524a4303d7ae24e4c7a305ec82546db64 Mon Sep 17 00:00:00 2001 From: Maddo Date: Sat, 26 Sep 2026 21:58:01 +0200 Subject: [PATCH 06/14] Implement gravity resolution and fast area calculations in collision handling --- docs/remorse-windows-rebuild-roadmap.md | 8 +- rebuild/remorse/include/remorse/collision.h | 15 +++- .../include/remorse/entity_dispatch_entry.h | 7 ++ rebuild/remorse/src/collision.cpp | 69 +++++++++++++--- rebuild/remorse/src/entity_dispatch_entry.cpp | 80 +++++++++++++++++++ rebuild/remorse/src/windowed_game_main.cpp | 9 +++ rebuild/remorse/tests/collision_tests.cpp | 70 ++++++++++++++-- .../tests/entity_dispatch_entry_tests.cpp | 69 ++++++++++++++++ 8 files changed, 301 insertions(+), 26 deletions(-) diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index f5a7f43..eccb171 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -328,9 +328,9 @@ The bounded staged dispatcher can now issue those actions against the host proce The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied item IDs can also be inserted at a block head. The host free-ID allocator uses the source `0x100..0x27ff` range, skips staged direct and contained records, and fails without mutation when exhausted. The window reserves staged contained IDs and retains their parent links; placing one in the world clears its parent while its children remain linked. Synthetic nested/exhaustion and retail-map tests pass. This does not yet implement returning freed IDs to the list, live inventory/container transfers, fast-area status, or viewport side effects. -The supported horizontal `GravityProcess_Run` path now issues `Item_Grab` at the old item position when Z speed is zero and X/Y speed is nonzero, then asks the injected sweep to approve movement. As in the source order, a refused sweep can leave a newly requested item process behind while the item stays put. The earlier no-mutation guarantee for a refused sweep applies only to the nonzero-Z path, which does not issue that request. The stationary zero-speed fall search, collision response, and automatic scheduler dispatch are still unported; a caller must provide shapes, group counts, and the sweep decision for this host-only branch. +The supported horizontal `GravityProcess_Run` path now issues `Item_Grab` at the old item position when Z speed is zero and X/Y speed is nonzero, then asks the injected sweep to approve movement. As in the source order, a refused sweep can leave a newly requested item process behind while the item stays put. The earlier no-mutation guarantee for a refused sweep applies only to the nonzero-Z path, which does not issue that request. This callback-based unobstructed runner does not handle the stationary zero-speed fall search or collision response; a caller must provide shapes, group counts, and sweep approval. -The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. The source's `World_MapBlockInFastArea` (`10a8:0000`) rotated block predicate and eight-corner start/destination footprint gate are now testable with an explicit fast-area range. The sweep's item-iterator rectangle and live candidate query follow inclusive X/Y filtering and Y-then-X block order. The per-item sweep uses 16-unit X/Y extents, 8-unit Z extents with the source zero-height fallback, and six axis-face tests that report one-unit-before-contact points and failed-direction bits. A read-only live collector combines those tests with candidate order, shape solidity and flip flags, and an explicit fast-area range. The host now selects a solid hit in source order when any axis is strictly closer, retains the earlier hit on a tie, and accumulates direction bits across contacts; a live entry point returns the resulting point and first colliding item. Synthetic tests cover both directions on all axes, self-exclusion, non-solid items, chain order, flipped shapes, and candidate selection. It does not handle damaging-only or floor contacts, maintain live fast-area state, or drive gravity movement. The gravity runner still requires an explicit approved sweep callback. +The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. The source's `World_MapBlockInFastArea` (`10a8:0000`) rotated block predicate and eight-corner start/destination footprint gate are testable with an explicit fast-area range. `World_CalcFastAreaLimits` (`10a8:0048`) now supplies the source sum ±5 / difference ±3 block window from a world center. The window refreshes a player-centered host range after movement and dispatches any owned gravity processes through its timed scheduler; it still does not create gravity entries or repaint moved map items in the static preview. The sweep's item-iterator rectangle and live candidate query follow inclusive X/Y filtering and Y-then-X block order. The per-item sweep uses 16-unit X/Y extents, 8-unit Z extents with the source zero-height fallback, and six axis-face tests that report one-unit-before-contact points and failed-direction bits. A read-only live collector combines those tests with candidate order, shape solidity and flip flags. The host selects a solid hit in source order when any axis is strictly closer, retains the earlier hit on a tie, and accumulates direction bits across contacts. Damaging-only face contacts are recorded in candidate order without blocking the resolved point. With an explicitly enabled floor-gap limit, the host also identifies the closest solid support beneath the destination footprint for source limits 0 and 9; this support metadata does not change the destination. The resolved sweep now reports fast-area failure at the original point with direction bits 1/2 and clamps out-of-range Z with bit 4; the gravity runner conservatively rejects these unsupported responses before mutation. `runResolvedGravity` moves an owned item to a solid-hit point after its strict process wake, damps and reverses horizontal speed on collision, and sleeps the process again. `scanResolvedGravity` dispatches this bounded runner through the host scheduler; tests verify a wall impact, a later move away, and no repeat within the same tick. The remaining gaps are vertical collision response, item status/cache writes, collision events, stationary fall search, and an actual window gravity producer and moving-item renderer. Original runtime parity remains unverified. Original DOS debugging and runtime verification are postponed indefinitely until requested again. The DOSBox-X debugger session has been stopped; do not treat a live trace as a prerequisite for the source-port work below. Keep unverified parity claims labeled as such. @@ -339,8 +339,8 @@ Next source-port checks, in call-chain order: 1. Keep the `0x23ff/0x2400` process item boundary until source-derived allocation limits support changing it; do not infer a wider live table from staged map IDs. 2. Port the remaining scheduler interval/group transitions behind host timing boundaries using static code evidence, with runtime parity explicitly deferred. 3. Port free-ID return/reuse and live container transfers while preserving contained parent/child links and process ownership. -4. Add damaging-only and mode-dependent floor contacts, then combine the solid-hit result with bounds and fast-area failures before enabling collision-driven movement. -5. Port the `GravityProcess_Run` area sweep, collision responses, and item-cache position/status writes to make created gravity entries move real items after their sleep. +4. Carry source sweep mode flags through callers and implement vertical collision responses for supported item/status branches; bounds and fast-area failures are now explicit but conservatively rejected by gravity. +5. Extend scheduled gravity with item status/cache writes and collision events; add a real window gravity producer and dynamic item renderer before claiming visible gameplay movement. 6. Connect the approved-move `Item_Grab` path to a ported `Item_LegalMoveToPointWithCollisionInfo` sweep and item-cache lifecycle, without changing the separate Windows `F` release fixture. 7. Lift `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`) and its interpreter initialization; keep release event-body lookup diagnostic until the VM executes it. diff --git a/rebuild/remorse/include/remorse/collision.h b/rebuild/remorse/include/remorse/collision.h index 9fc32d9..4230dd8 100644 --- a/rebuild/remorse/include/remorse/collision.h +++ b/rebuild/remorse/include/remorse/collision.h @@ -36,12 +36,18 @@ struct SweepItemImpact { struct SweepCandidateImpact { u16 itemNumber = 0; SweepItemImpact impact{}; + bool damaging = false; + std::optional floorGap; }; struct SweepCollisionResult { WorldPoint destination{}; u16 firstCollision = 0; u8 failedDirections = 0; + std::vector damagingContacts; + u16 supportItem = 0; + std::optional supportGap; + bool failed = false; }; struct FastAreaRange { @@ -51,6 +57,7 @@ struct FastAreaRange { s32 maxDifference = 0; }; +FastAreaRange calculateFastAreaRange(WorldPoint center); bool isWorldPointInFastArea(s32 x, s32 y, const FastAreaRange& range); bool isSweepFootprintInFastArea(WorldPoint from, WorldPoint destination, s32 extentX, s32 extentY, const FastAreaRange& range); @@ -62,14 +69,16 @@ CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeI CollisionBody makeSweepItemBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped = false); std::optional sweepSolidItemImpact( const CollisionBody& moving, WorldPoint destination, const CollisionBody& obstacle); -std::optional> collectSolidSweepImpacts( +std::optional> collectSweepItemImpacts( const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, - const std::vector& shapes, const FastAreaRange& fastArea); + const std::vector& shapes, const FastAreaRange& fastArea, + std::optional floorGapLimit = std::nullopt); SweepCollisionResult selectSolidSweepImpact(WorldPoint from, WorldPoint destination, const std::vector& impacts); std::optional resolveSolidLiveSweep( const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, - const std::vector& shapes, const FastAreaRange& fastArea); + const std::vector& shapes, const FastAreaRange& fastArea, + std::optional floorGapLimit = std::nullopt); bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right); bool canMoveCollisionBody( const CollisionBody& body, diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index d4a1ef1..3492924 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -11,6 +11,7 @@ namespace remorse { class LiveFixedMapItems; struct ShapeTypeInfo; struct WorldPoint; +struct FastAreaRange; CR_PACK_PUSH_1 struct EntityDispatchEntryBase { @@ -87,6 +88,12 @@ public: bool (*approveSweep)(u16 itemNumber, const WorldPoint& from, const WorldPoint& to, void* context), void* context, const std::vector* shapes = nullptr, u16 (*groupCounts)[32] = nullptr); + bool runResolvedGravity(u16 processId, LiveFixedMapItems& items, + const std::vector& shapes, const FastAreaRange& fastArea, + u32 timeScale, u32 timerTick, u16 (&groupCounts)[32]); + u32 scanResolvedGravity(u8 activeGroup, LiveFixedMapItems& items, + const std::vector& shapes, const FastAreaRange& fastArea, + u32 timeScale, u32 timerTick, u16 (&groupCounts)[32]); SystemTimerProcessEntry* createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]); diff --git a/rebuild/remorse/src/collision.cpp b/rebuild/remorse/src/collision.cpp index b14a01b..bbb7de0 100644 --- a/rebuild/remorse/src/collision.cpp +++ b/rebuild/remorse/src/collision.cpp @@ -78,6 +78,15 @@ void appendSolidBody(std::vector& bodies, const std::vector> 9; + const s32 blockY = center.y >> 9; + const s32 sum = blockX + blockY; + const s32 difference = blockX - blockY; + return {sum - 5, sum + 5, difference - 3, difference + 3}; +} + bool isWorldPointInFastArea(s32 x, s32 y, const FastAreaRange& range) { if (x < 0 || x > 0x7fff || y < 0 || y > 0x7fff) { @@ -219,9 +228,10 @@ std::optional sweepSolidItemImpact( return std::nullopt; } -std::optional> collectSolidSweepImpacts( +std::optional> collectSweepItemImpacts( const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, - const std::vector& shapes, const FastAreaRange& fastArea) + const std::vector& shapes, const FastAreaRange& fastArea, + std::optional floorGapLimit) { const auto* movingItem = items.findItem(movingItemNumber); if (movingItem == nullptr || movingItem->data.shape >= shapes.size() || @@ -248,13 +258,27 @@ std::optional> collectSolidSweepImpacts( return std::nullopt; } const auto& shape = shapes[item->data.shape]; - if ((shape.flags & solidFlag) == 0) { - continue; - } const auto obstacle = makeSweepItemBody({item->data.x, item->data.y, item->data.z}, shape, (item->data.flags & flippedFlag) != 0); + std::optional floorGap; + const s32 gap = destination.z - item->data.z - obstacle.extentZ; + if (floorGapLimit && (shape.flags & solidFlag) != 0 && gap >= 0 && + gap <= *floorGapLimit && + destination.x - movingBody.extentX + 1 <= item->data.x && + item->data.x - obstacle.extentX + 1 <= destination.x && + destination.y - movingBody.extentY + 1 <= item->data.y && + item->data.y - obstacle.extentY + 1 <= destination.y) { + floorGap = static_cast(gap); + } + if ((shape.flags & (solidFlag | 0x40)) == 0) { + continue; + } if (const auto impact = sweepSolidItemImpact(movingBody, destination, obstacle)) { - impacts.push_back({itemNumber, *impact}); + impacts.push_back({itemNumber, + {impact->resolved, (shape.flags & solidFlag) != 0 ? impact->failedDirections : u8{0}}, + (shape.flags & 0x40) != 0, floorGap}); + } else if (floorGap) { + impacts.push_back({itemNumber, {}, false, floorGap}); } } return impacts; @@ -265,9 +289,16 @@ SweepCollisionResult selectSolidSweepImpact(WorldPoint from, WorldPoint destinat { SweepCollisionResult result{destination}; for (const auto& candidate : impacts) { + if (candidate.floorGap && (!result.supportGap || *candidate.floorGap <= *result.supportGap)) { + result.supportItem = candidate.itemNumber; + result.supportGap = candidate.floorGap; + } + if (candidate.damaging) { + result.damagingContacts.push_back(candidate.itemNumber); + } result.failedDirections |= candidate.impact.failedDirections; const auto& point = candidate.impact.resolved; - if (candidate.itemNumber != 0 && + if (candidate.itemNumber != 0 && candidate.impact.failedDirections != 0 && (std::abs(static_cast(point.x) - from.x) < std::abs(static_cast(result.destination.x) - from.x) || std::abs(static_cast(point.y) - from.y) < @@ -283,19 +314,31 @@ SweepCollisionResult selectSolidSweepImpact(WorldPoint from, WorldPoint destinat std::optional resolveSolidLiveSweep( const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination, - const std::vector& shapes, const FastAreaRange& fastArea) + const std::vector& shapes, const FastAreaRange& fastArea, + std::optional floorGapLimit) { const auto* movingItem = items.findItem(movingItemNumber); - if (movingItem == nullptr) { + if (movingItem == nullptr || movingItem->data.shape >= shapes.size()) { return std::nullopt; } - const auto impacts = collectSolidSweepImpacts(items, movingItemNumber, destination, - shapes, fastArea); + const WorldPoint from{movingItem->data.x, movingItem->data.y, movingItem->data.z}; + const auto bounds = clampAreaSweepBounds(from, destination); + const auto body = makeSweepItemBody(from, shapes[movingItem->data.shape], + (movingItem->data.flags & flippedFlag) != 0); + if (!isSweepFootprintInFastArea(from, destination, body.extentX, body.extentY, fastArea)) { + SweepCollisionResult result{from}; + result.failedDirections = static_cast(bounds.failedDirections | 3); + result.failed = true; + return result; + } + const auto impacts = collectSweepItemImpacts(items, movingItemNumber, bounds.destination, + shapes, fastArea, floorGapLimit); if (!impacts) { return std::nullopt; } - return selectSolidSweepImpact({movingItem->data.x, movingItem->data.y, movingItem->data.z}, - destination, *impacts); + auto result = selectSolidSweepImpact(from, bounds.destination, *impacts); + result.failedDirections |= bounds.failedDirections; + return result; } bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right) diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index 904b439..a07b7e5 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -233,6 +233,86 @@ bool ProcessKernel::runUnobstructedGravity(u16 processId, LiveFixedMapItems& ite return true; } +bool ProcessKernel::runResolvedGravity(u16 processId, LiveFixedMapItems& items, + const std::vector& shapes, const FastAreaRange& fastArea, + u32 timeScale, u32 timerTick, u16 (&groupCounts)[32]) +{ + const auto* process = processAt(processId); + if (process == nullptr || allocationSizeAt(processId) != sizeof(GravityProcessEntry) || + (process->bytes[0x16] & 0x08) != 0 || (process->bytes[0x19] & 0x10) != 0 || + std::none_of(ownedGravityProcesses_.begin(), ownedGravityProcesses_.end(), + [process](const auto& owned) { return &owned->base == process; })) { + return false; + } + const u16 itemNumber = readLe16(*process, 0x04); + const auto* item = items.findItem(itemNumber); + const auto zSpeed = static_cast(readLe16(*process, 0x36)); + if (item == nullptr || item->data.z > 250) { + return false; + } + if (zSpeed == 0 && + ((readLe16(*process, 0x32) == 0 && readLe16(*process, 0x34) == 0) || + !items.grabItem(itemNumber, shapes, *this, groupCounts, timerTick))) { + return false; + } + const WorldPoint from{item->data.x, item->data.y, item->data.z}; + const auto step = planGravitySweep(from, static_cast(readLe16(*process, 0x32)), + static_cast(readLe16(*process, 0x34)), zSpeed, + static_cast(readLe16(*process, 0x38)), timeScale); + const auto sweep = resolveSolidLiveSweep(items, itemNumber, step.destination, shapes, fastArea); + if (!sweep || sweep->failed || (sweep->failedDirections & 4) != 0) { + return false; + } + const auto& resolved = sweep->destination; + if (!items.moveItem(itemNumber, static_cast(resolved.x), + static_cast(resolved.y), static_cast(resolved.z))) { + return false; + } + auto* mutableProcess = processAt(processId); + auto nextZSpeed = step.nextZSpeed; + if (sweep->failedDirections != 0) { + const auto damped = [](s16 speed) { + return static_cast((static_cast(speed) + (speed < 0 ? 1 : 0)) >> 2); + }; + nextZSpeed = damped(nextZSpeed); + for (const u8 axis : {u8{1}, u8{2}}) { + const u16 offset = axis == 1 ? 0x32 : 0x34; + const s16 speed = static_cast(readLe16(*mutableProcess, offset)); + const s16 response = static_cast((sweep->failedDirections & axis) != 0 ? + -damped(speed) : damped(speed)); + writeLe16(*mutableProcess, offset, static_cast(response)); + } + } + writeLe16(*mutableProcess, 0x36, static_cast(nextZSpeed)); + EntityDispatchEntry::sleep(*mutableProcess, timerTick, 4 * std::clamp(timeScale, 1u, 4u)); + return true; +} + +u32 ProcessKernel::scanResolvedGravity(u8 activeGroup, LiveFixedMapItems& items, + const std::vector& shapes, const FastAreaRange& fastArea, + u32 timeScale, u32 timerTick, u16 (&groupCounts)[32]) +{ + struct ScanContext { + ProcessKernel& kernel; + LiveFixedMapItems& items; + const std::vector& shapes; + const FastAreaRange& fastArea; + u32 timeScale; + u32 timerTick; + u16 (&groupCounts)[32]; + u32 moved = 0; + } context{*this, items, shapes, fastArea, timeScale, timerTick, groupCounts}; + scanRunnableProcesses(activeGroup, [](EntityDispatchEntryBase& process, void* state) { + auto& scan = *static_cast(state); + if (readLe16(process, 0x00) == 0x0610 && + scan.kernel.runResolvedGravity(readLe16(process, 0x02), scan.items, + scan.shapes, scan.fastArea, scan.timeScale, scan.timerTick, scan.groupCounts)) { + ++scan.moved; + } + }, &context, timerTick); + return context.moved; +} + SystemTimerProcessEntry* ProcessKernel::createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]) { if (systemTimerProcess_ != nullptr) { diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index fa3712d..345d6a7 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -72,6 +72,7 @@ struct AppState { std::vector viewPixels; remorse::WorldPoint spawn{}; remorse::WorldPoint playerWorld{}; + remorse::FastAreaRange fastArea{}; remorse::s32 minWorldX = 0; remorse::s32 minWorldY = 0; remorse::s32 maxWorldX = 0; @@ -272,6 +273,7 @@ void loadSceneAsync(HWND window, AppState& state) std::lock_guard lock(state.sceneMutex); state.spawn = spawn; state.playerWorld = spawn; + state.fastArea = remorse::calculateFastAreaRange(spawn); state.playerCollisionBody = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]); state.collisionBodies = std::move(collisionBodies); state.shapeTypes = *shapeTypes; @@ -646,6 +648,12 @@ void updatePlayer(HWND window, AppState& state) } } }, &app); + } else if (entry.bytes[0] == 0x10 && entry.bytes[1] == 0x06 && app.liveItems) { + const remorse::u16 processId = static_cast(entry.bytes[2] | + (static_cast(entry.bytes[3]) << 8)); + app.diagnosticKernel.runResolvedGravity(processId, *app.liveItems, + app.shapeTypes, app.fastArea, 1, app.diagnosticKernel.systemTimerTick(), + app.diagnosticGroupCounts); } }, &state); state.diagnosticKernel.refreshActiveGroup(state.diagnosticGroupCounts); @@ -697,6 +705,7 @@ void updatePlayer(HWND window, AppState& state) if (withinMapBounds && withinSceneBounds && remorse::canMoveCollisionBody( state.playerCollisionBody, destination, state.collisionBodies)) { state.playerWorld = destination; + state.fastArea = remorse::calculateFastAreaRange(destination); state.playerCollisionBody.location = destination; state.playerOffsetX = nextOffsetX; state.playerOffsetY = nextOffsetY; diff --git a/rebuild/remorse/tests/collision_tests.cpp b/rebuild/remorse/tests/collision_tests.cpp index bde848a..4f98e41 100644 --- a/rebuild/remorse/tests/collision_tests.cpp +++ b/rebuild/remorse/tests/collision_tests.cpp @@ -4,6 +4,14 @@ int main() { + const auto centeredArea = remorse::calculateFastAreaRange({512, 512, 0}); + assert(centeredArea.minSum == -3 && centeredArea.maxSum == 7 && + centeredArea.minDifference == -3 && centeredArea.maxDifference == 3); + assert(remorse::isWorldPointInFastArea(512, 512, centeredArea)); + assert(!remorse::isWorldPointInFastArea(4096, 512, centeredArea)); + const auto beforeBlockCrossing = remorse::calculateFastAreaRange({511, 512, 0}); + assert(beforeBlockCrossing.minSum == centeredArea.minSum - 1 && + beforeBlockCrossing.minDifference == centeredArea.minDifference - 1); const remorse::FastAreaRange fastArea{2, 4, 0, 2}; assert(remorse::isWorldPointInFastArea(512, 512, fastArea)); assert(!remorse::isWorldPointInFastArea(-1, 512, fastArea)); @@ -126,7 +134,7 @@ int main() sweepShapes[2].flags = 2; sweepShapes[3] = sweepShapes[1]; const remorse::FastAreaRange allBlocks{-128, 128, -128, 128}; - const auto liveImpacts = remorse::collectSolidSweepImpacts(liveSweepItems, 0x100, + const auto liveImpacts = remorse::collectSweepItemImpacts(liveSweepItems, 0x100, {700, 512, 0}, sweepShapes, allBlocks); assert(liveImpacts && liveImpacts->size() == 1); assert((*liveImpacts)[0].itemNumber == 0x101 && @@ -139,7 +147,7 @@ int main() sweepShapes[2].y = 4; wallItem.data.flags = 0x20; remorse::LiveFixedMapItems flippedSweepItems({movingItem, wallItem, nextWall, harmlessItem}); - const auto flippedImpacts = remorse::collectSolidSweepImpacts(flippedSweepItems, 0x100, + const auto flippedImpacts = remorse::collectSweepItemImpacts(flippedSweepItems, 0x100, {700, 512, 0}, sweepShapes, allBlocks); assert(flippedImpacts && flippedImpacts->size() == 2); assert((*flippedImpacts)[0].itemNumber == 0x103 && (*flippedImpacts)[0].impact.resolved.x == 654); @@ -152,8 +160,18 @@ int main() {700, 512, 0}, sweepShapes, allBlocks); assert(resolvedLive && resolvedLive->firstCollision == 0x101 && resolvedLive->destination.x == 576 && resolvedLive->failedDirections == 1); - assert(!remorse::resolveSolidLiveSweep(flippedSweepItems, 0x100, - {700, 512, 0}, sweepShapes, {2, 2, 0, 0})); + const auto outsideFastArea = remorse::resolveSolidLiveSweep(flippedSweepItems, 0x100, + {700, 512, 0}, sweepShapes, {2, 2, 0, 0}); + assert(outsideFastArea && outsideFastArea->failed && + outsideFastArea->destination.x == 512 && outsideFastArea->failedDirections == 3); + const auto outsideWorld = remorse::resolveSolidLiveSweep(flippedSweepItems, 0x100, + {-1, 512, 0}, sweepShapes, allBlocks); + assert(outsideWorld && outsideWorld->failed && outsideWorld->failedDirections == 3 && + outsideWorld->destination.x == 512); + const auto aboveCeiling = remorse::resolveSolidLiveSweep(flippedSweepItems, 0x100, + {512, 512, 251}, sweepShapes, allBlocks); + assert(aboveCeiling && !aboveCeiling->failed && aboveCeiling->failedDirections == 4 && + aboveCeiling->destination.z == 250); const auto noImpact = remorse::selectSolidSweepImpact({512, 512, 0}, {700, 512, 0}, {}); assert(noImpact.firstCollision == 0 && noImpact.destination.x == 700 && noImpact.failedDirections == 0); @@ -168,9 +186,49 @@ int main() {700, 700, 0}, mixedAxisImpacts); assert(mixedAxis.firstCollision == 0x103 && mixedAxis.destination.x == 550 && mixedAxis.destination.y == 550 && mixedAxis.failedDirections == 3); - assert(!remorse::collectSolidSweepImpacts(liveSweepItems, 0x100, + sweepShapes[3].flags = 0x40; + remorse::LiveFixedMapItems damagingItems({movingItem, harmlessItem}); + const auto damageOnly = remorse::resolveSolidLiveSweep(damagingItems, 0x100, + {700, 512, 0}, sweepShapes, allBlocks); + assert(damageOnly && damageOnly->firstCollision == 0 && + damageOnly->destination.x == 700 && damageOnly->failedDirections == 0 && + (damageOnly->damagingContacts == std::vector{0x102})); + movingItem.data.z = 32; + wallItem.data.x = 512; + wallItem.data.z = 16; + remorse::LiveFixedMapItems floorItems({movingItem, wallItem}); + const auto floorDisabled = remorse::resolveSolidLiveSweep(floorItems, 0x100, + {512, 512, 32}, sweepShapes, allBlocks); + assert(floorDisabled && floorDisabled->supportItem == 0); + const auto floorTouch = remorse::resolveSolidLiveSweep(floorItems, 0x100, + {512, 512, 32}, sweepShapes, allBlocks, remorse::u8{0}); + assert(floorTouch && floorTouch->supportItem == 0x101 && floorTouch->supportGap == 0 && + floorTouch->destination.z == 32 && floorTouch->firstCollision == 0); + const auto floorStep = remorse::resolveSolidLiveSweep(floorItems, 0x100, + {512, 512, 41}, sweepShapes, allBlocks, remorse::u8{9}); + assert(floorStep && floorStep->supportGap == 9 && floorStep->destination.z == 41); + const auto floorTooFar = remorse::resolveSolidLiveSweep(floorItems, 0x100, + {512, 512, 42}, sweepShapes, allBlocks, remorse::u8{9}); + assert(floorTooFar && !floorTooFar->supportGap); + auto lowerFloor = wallItem; + lowerFloor.itemNumber = 0x104; + lowerFloor.data.z = 17; + remorse::LiveFixedMapItems layeredFloorItems({movingItem, wallItem, lowerFloor}); + const auto closestFloor = remorse::resolveSolidLiveSweep(layeredFloorItems, 0x100, + {512, 512, 41}, sweepShapes, allBlocks, remorse::u8{9}); + assert(closestFloor && closestFloor->supportItem == 0x104 && closestFloor->supportGap == 8); + lowerFloor.data.x = 650; + remorse::LiveFixedMapItems distantFloorItems({movingItem, lowerFloor}); + const auto outsideFootprint = remorse::resolveSolidLiveSweep(distantFloorItems, 0x100, + {512, 512, 37}, sweepShapes, allBlocks, remorse::u8{9}); + assert(outsideFootprint && !outsideFootprint->supportGap); + sweepShapes[2].flags = 0x40; + const auto damagingFloor = remorse::resolveSolidLiveSweep(floorItems, 0x100, + {512, 512, 32}, sweepShapes, allBlocks, remorse::u8{0}); + assert(damagingFloor && !damagingFloor->supportGap); + assert(!remorse::collectSweepItemImpacts(liveSweepItems, 0x100, {700, 512, 0}, sweepShapes, {2, 2, 0, 0})); - assert(!remorse::collectSolidSweepImpacts(liveSweepItems, 0x105, + assert(!remorse::collectSweepItemImpacts(liveSweepItems, 0x105, {700, 512, 0}, sweepShapes, allBlocks)); remorse::FixedMap map; diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index 0978576..4d16f58 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -1,3 +1,4 @@ +#include "remorse/collision.h" #include "remorse/entity_dispatch_entry.h" #include "remorse/fixed_map.h" #include "remorse/map_renderer.h" @@ -583,6 +584,74 @@ int main() horizontalKernel.processCount() == 6); assert(horizontalKernel.processAt(horizontalId)->bytes[0x36] == 0xfe && horizontalKernel.processAt(horizontalId)->bytes[0x37] == 0xff); + remorse::ProcessKernel resolvedKernel; + remorse::u16 resolvedGroups[32]{}; + for (int index = 0; index < 3; ++index) { + resolvedKernel.createProcess(1, resolvedGroups); + } + remorse::StagedFixedMapItem movingGravityItem = fallingItem; + movingGravityItem.data.x = 512; + movingGravityItem.data.y = 512; + movingGravityItem.data.z = 80; + movingGravityItem.data.shape = 1; + auto gravityWall = movingGravityItem; + gravityWall.itemNumber = 0x101; + gravityWall.data.x = 600; + gravityWall.data.shape = 2; + remorse::LiveFixedMapItems resolvedItems({movingGravityItem, gravityWall}); + std::vector resolvedShapes(3); + resolvedShapes[1].x = resolvedShapes[1].y = resolvedShapes[1].z = 2; + resolvedShapes[2] = resolvedShapes[1]; + resolvedShapes[2].flags = 2; + const remorse::FastAreaRange resolvedFastArea{-128, 128, -128, 128}; + const auto resolvedId = resolvedKernel.hurlItem(1, 0x100, 100, 0, 2, 2, 0, resolvedGroups); + assert(!resolvedKernel.runResolvedGravity(resolvedId, resolvedItems, + resolvedShapes, resolvedFastArea, 1, 0, resolvedGroups)); + resolvedKernel.scanRunnableProcesses(1, countGravityRun, &gravityRuns, 21); + assert(resolvedKernel.runResolvedGravity(resolvedId, resolvedItems, + resolvedShapes, resolvedFastArea, 1, 21, resolvedGroups)); + assert(resolvedItems.findItem(0x100)->data.x == 568 && + resolvedItems.findItem(0x100)->data.z == 81); + const auto* resolvedProcess = resolvedKernel.processAt(resolvedId); + assert(resolvedProcess->bytes[0x32] == 0xe7 && resolvedProcess->bytes[0x33] == 0xff && + resolvedProcess->bytes[0x36] == 0 && (resolvedProcess->bytes[0x19] & 0x10) != 0 && + resolvedProcess->bytes[0x0e] == 4); + assert(!resolvedKernel.runResolvedGravity(resolvedId, resolvedItems, + resolvedShapes, resolvedFastArea, 1, 22, resolvedGroups)); + resolvedKernel.scanRunnableProcesses(1, countGravityRun, &gravityRuns, 26); + assert(!resolvedKernel.runResolvedGravity(resolvedId, resolvedItems, + resolvedShapes, {2, 2, 0, 0}, 1, 26, resolvedGroups)); + assert(resolvedItems.findItem(0x100)->data.x == 568 && + resolvedKernel.processAt(resolvedId)->bytes[0x32] == 0xe7); + assert(resolvedKernel.runResolvedGravity(resolvedId, resolvedItems, + resolvedShapes, resolvedFastArea, 1, 26, resolvedGroups)); + assert(resolvedItems.findItem(0x100)->data.x == 543 && + resolvedItems.findItem(0x100)->data.z == 81 && + resolvedKernel.processAt(resolvedId)->bytes[0x36] == 0xfe); + assert(resolvedKernel.scanResolvedGravity(1, resolvedItems, resolvedShapes, + resolvedFastArea, 1, 30, resolvedGroups) == 0); + assert(resolvedKernel.scanResolvedGravity(1, resolvedItems, resolvedShapes, + resolvedFastArea, 1, 31, resolvedGroups) == 1); + assert(resolvedItems.findItem(0x100)->data.x == 518 && + resolvedItems.findItem(0x100)->data.z == 79); + assert(resolvedKernel.scanResolvedGravity(1, resolvedItems, resolvedShapes, + resolvedFastArea, 1, 31, resolvedGroups) == 0); + remorse::ProcessKernel verticalKernel; + remorse::u16 verticalGroups[32]{}; + for (int index = 0; index < 3; ++index) { + verticalKernel.createProcess(1, verticalGroups); + } + movingGravityItem.data.z = 40; + gravityWall.data.x = 512; + gravityWall.data.z = 20; + remorse::LiveFixedMapItems verticalItems({movingGravityItem, gravityWall}); + const auto verticalId = verticalKernel.hurlItem(1, 0x100, 0, 0, -20, 2, 0, verticalGroups); + verticalKernel.scanRunnableProcesses(1, countGravityRun, &gravityRuns, 21); + assert(!verticalKernel.runResolvedGravity(verticalId, verticalItems, + resolvedShapes, resolvedFastArea, 1, 21, verticalGroups)); + assert(verticalItems.findItem(0x100)->data.z == 40 && + verticalKernel.processAt(verticalId)->bytes[0x36] == 0xec && + (verticalKernel.processAt(verticalId)->bytes[0x19] & 0x10) == 0); gravityKernel.terminateProcess(gravityId, gravityGroups); assert(gravityKernel.findProcessForItemAndType(0x100, 0x203) == nullptr); gravityKernel.clearTerminatedProcesses(); From e757bb33d0fd9b877eee3ca92d6d12f4d3044b3d Mon Sep 17 00:00:00 2001 From: Maddo Date: Sun, 27 Sep 2026 11:48:14 +0200 Subject: [PATCH 07/14] Add extensive tests for animation, input handling, and map rendering - Enhanced animation archive tests to validate frame metadata and start frame selection logic. - Introduced new tests for entity dispatch entry handling, including key event queuing and processing. - Added tests for fixed map item interactions, including glob egg hatching and item movement. - Expanded flex archive tests to cover teleport egg spawning and usecode event selection. - Implemented isometric controls tests to verify directional key handling and animation state changes. - Improved map renderer tests to ensure correct rendering of map previews and collision detection. --- docs/remorse-windows-rebuild-roadmap.md | 23 +- rebuild/remorse/CMakeLists.txt | 1 + .../include/remorse/animation_archive.h | 7 + .../include/remorse/entity_dispatch_entry.h | 36 ++ rebuild/remorse/include/remorse/fixed_map.h | 20 + .../include/remorse/isometric_controls.h | 43 ++ .../remorse/include/remorse/map_renderer.h | 23 ++ rebuild/remorse/include/remorse/usecode_vm.h | 30 ++ rebuild/remorse/src/animation_archive.cpp | 23 ++ rebuild/remorse/src/entity_dispatch_entry.cpp | 205 +++++++++- rebuild/remorse/src/fixed_map.cpp | 114 +++++- rebuild/remorse/src/map_renderer.cpp | 106 +++-- rebuild/remorse/src/usecode_vm.cpp | 29 ++ rebuild/remorse/src/windowed_game_main.cpp | 383 +++++++++++++----- .../remorse/tests/animation_archive_tests.cpp | 23 ++ .../tests/entity_dispatch_entry_tests.cpp | 133 ++++++ rebuild/remorse/tests/fixed_map_tests.cpp | 32 +- rebuild/remorse/tests/flex_archive_tests.cpp | 47 +++ .../tests/isometric_controls_tests.cpp | 16 + rebuild/remorse/tests/map_renderer_tests.cpp | 99 +++++ 20 files changed, 1249 insertions(+), 144 deletions(-) create mode 100644 rebuild/remorse/include/remorse/usecode_vm.h create mode 100644 rebuild/remorse/src/usecode_vm.cpp diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index eccb171..aa7898e 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -16,6 +16,25 @@ The exported files are evidence, not directly compilable game source. Keep them - At each milestone, count original functions translated and exercised in the Windows build, platform calls replaced, and parity checks passed. A rendered scene or a controllable stand-in actor alone does not pass a game-code milestone. - Do not claim whole-game recompilation until startup, game ticks, interactions, mission flow, save/load, and presentation are driven by ported game code and playable on modern Windows using the original data. +## Source-Backed In-Game Vertical Slice + +The immediate target is a fresh game on retail map 1 at the original starting teleporter, with an avatar owned by the ported item/NPC runtime, a tick and input path that actually drive that avatar, a changing world image, and at least one original-script-backed interaction. The current host-controlled sprite over a frozen map does **not** count. Keep the diagnostic traversal view separate while replacing its behavior; no DOSBox parity gate is required for this Windows milestone. + +1. **Startup and spawn:** port the fresh-game branch of `Game_Start` (`1020:0000`) through `Teleporter_CreateProcessDirect(1, 0x1e, 1)` and its placement callee. Resolve egg `0x1e` from original map data, not from the map bounds, and prove its coordinates and the spawned avatar/item ID in a retail-data test. Do not implement intro movies, main menu, save loading, or warp overrides for this slice. +2. **Live world ownership:** initialize the original item cache and NPC/avatar state for that map. The displayed avatar must be the same numbered, mutable item advanced by the process runtime; reject a separately drawn or separately positioned stand-in. +3. **Tick and input:** port the minimal recovered cycle/scheduler and keyboard queue/control chain that moves that avatar. Route Win32 key/timer events through the host boundary into those routines; test deterministic state changes with recorded inputs, including idle and blocked movement. +4. **Gameplay presentation:** render the live item/sprite state in source draw order each tick and follow the recovered camera state. Verify that movement, facing, and at least one changed world item appear on screen, without relying on a single prepainted fixed-map image. +5. **Real interaction:** implement one reachable map-1 usecode event through the original item find/grab, VM dispatch, and resulting world-state mutation. Demonstrate a repeatable before/input/after trace and visible effect; a script lookup or release-request counter is not an interaction. +6. **Acceptance:** launch the normal Windows executable with retail data, start map 1 at egg `0x1e`, move and interact without a diagnostic shortcut, and verify on-screen state plus a deterministic integration test. Keep absent combat, audio, menus, persistence, and broader missions listed as limitations, not silently simulated features. + +Progress: the map-1 fixed-map test identifies one family-8/frame-1 item with low quality byte `0x1e` (the teleporter's item-search predicate); startup centers on that egg instead of the map-bounds midpoint. The live item owner reserves avatar item `1` with defaults from `NPC_Init` (`10e8:000c`) and applies the coordinate/map write from `NPC_Teleport` (`10e8:29f2`). Win32 directional events now pass through the kernel keyboard queue to a registered controller entry; an owned `AnimPrimitiveProcess` advances the avatar item on 40 Hz host ticks. A cached map renderer redraws snapshots of mutable map items in source sorter order on a worker thread, while the avatar pose is still drawn in a separate screen overlay. Fast-area GLOB eggs now hatch into numbered live children using the `1098:039c` placement/status rules; the renderer replaces a hatched egg's preview expansion with those items. The interpreter's initial stack and 31-entry code-address stack are compiled and tested against exported `1418:00e8/0244/0000`; opcode execution is not implemented. These are partial translations of steps 1-4, **not completed steps**: `Game_Start` (`1020:0000`), teleporter scheduling, complete item cache, controller actions beyond directional movement, original camera/draw-list integration, and USECODE execution remain open. Collision is approximate; no visible scripted world mutation or deterministic end-to-end interaction acceptance exists. Steps 5-6 remain open. + +Retail map-1 probing at the starting egg found four children after fast-area GLOB hatching and no eligible `use` script on those children; no direct fixed-map item within 1,024 staged units has an eligible event body. The nearest direct `use` items are panel/card objects roughly 8,800 staged units away. Their event bodies delegate to `TRIGGER.slot_20` or `SWITCH.slot_21`, which require additional VM, timer, selector, and world-state services. A renderer regression confirms that moving hatched children changes live scene pixels, but this is not script execution or proof that those distant interactions are reachable through the current collision path. + +Control-path evidence for step 3: live `CRUSADER.EXE` disassembly at `1130:224b-226a` compares event selectors against the five words at `1130:273b` (`1, 2, 4, 0x10, 0x100`); the matching CS jump-table words at `1130:274f` target `226e, 2276, 22b6, 22bd, 22b6`. The gameplay-key case at `1130:22bd` copies all 12 bytes of the incoming key event. The exported `Controller_HandleKeyEvent` pseudo-C contains an invalid branch after this table and must not be compiled verbatim. The 32-slot, 12-byte pending-key ring (`11d0:3533/3ad4/3a74/3aad`) and a registered-subscriber dispatch (`11d0:3c4d`) are ported in `ProcessKernel`; tests cover order, full/overflow, wrap, and delivery to a controller entry rather than the excluded keyboard process. The 0x40-byte controller entry mirrors the keyboard registration and daemon/update flags of `ControllerProcess_CreateProcess` (`1130:00e3`), **but the window does not create it or feed its queue**. `Controller_PickNextAnimByKeyevent` (`1130:12d6`) reads two keyboard state arrays through `Keyboard_GetKeyState` (`11d0:39b9`, DS offsets `3652` and `3352`) and selects animation through NPC state and services. `Kernel_11d0_39fb` installs the DOS interrupt-9 keyboard path through `FUN_1218_059b`; exported C exposes the arrays' reads/resets but not their hardware writer. Recover the key-state update semantics from the interrupt path and port the controller's reachable movement branches before replacing host polling; do not guess their edge/held meaning. + +Animation dependency for step 3: live disassembly at `1130:1eda-1ef0` supplies `NPC_DoAnim` (`10e8:0252`) with the controlled NPC item pointer, animation number, direction, and two zero arguments that the exported controller pseudo-C omits. The unarmed walk/run cases allocate `AnimPrimitiveProcess` (`1150:0000`, size `0x5b`); live disassembly at `1150:0033-009c` confirms its normal vtable offset `0x2a57`, event type `0xf0`, and linear-capable setup. A kernel-owned constructor with this layout, item/type registration, direction, and clip metadata now has a byte-level test. `AnimPrimitive_SetStartFrame` (`1150:17b2`) is ported and tested for two-step/looping and controlled-avatar frame-skip branches. Its tick (`1150:1906`) still needs NPC animation-frame state, fast-area/collision behavior, item updates, transitions, and teardown. The Windows host frame counter is not this process. Finish the tick and collision result before swapping the default control path. + ## Current Inputs - `exports/src_remorse/export_manifest.json` reports `CRUSADER.EXE`, 2,984 exported function files, 9 fallback function files, 57 global buckets, and 15,403 global definitions. @@ -348,6 +367,8 @@ Next source-port checks, in call-chain order: `rebuild/remorse/out/build-nmake/remorse_game.exe` is the first windowed application target. It locates the game data root from its own executable path (or the current directory), defaults to map 1, and accepts an optional fixed-map index from 0 through 255. +The default window now opens directly onto the retail-map traversal test with no diagnostic HUD, synthetic Stand/keyboard processes, or `F` release shortcut. Pass `--diagnostics` (before or after the map number) to restore the diagnostic harness and its HUD. The map-1 startup midpoint is checked against the same collision bodies as the window, with at least one legal neighboring move. This is a **retail-data movement test**, not yet the real game: the player is host-created, rendering uses a static map preview, movement uses host polling/step policy, and neither the original startup/game loop nor item USECODE/mission interactions are running. Do not use this mode split as the roadmap's playable-game exit criterion. + From the repository root: ```powershell @@ -355,7 +376,7 @@ rebuild\remorse\build_msvc.cmd Debug .\rebuild\remorse\out\build-nmake\remorse_game.exe 1 ``` -The application builds the selected retail map scene and player assets on a worker thread, then displays a resizable Win32 window with the game palette and dependency-sorted map art. Shape 1 uses `ANIM.DAT` actions 0 (stand), 1 (walk), and 3 (unarmed run); frame metadata selects the `SHAPES.FLX` pose, horizontal flip, and movement delta. The original keypad direction mapping is supported alongside WASD/arrows and diagonal combinations. Shift and Caps Lock select walk/run using the controller's same-state rule. A 40 Hz host simulation tick advances frame steps against fixed-map and expanded-glob solid volumes; it now catches up after long paints instead of discarding all elapsed time beyond 50 ms. The retail signed displacement decoder is unchanged. The prototype's forward-only host movement step skips the small backward stride on walk frames 4 and 12 of directions 6/7/10/11, which had made both actor and following camera reverse mid-stride. This comfort policy and host tick rate are not recovered controller behavior. The persistent GDI back buffer avoids painting each moving frame directly to the window. The HUD shows map, world position, facing, and locomotion state. Collision is an axis-aligned TYPEFLAG approximation; it does not reproduce original AreaSearch shape sweeps or step-up behavior, and the fixed-map record bounds remain the outer movement limit. +The application builds the selected retail map scene and player assets on a worker thread, then displays a resizable Win32 window with the game palette and dependency-sorted map art. Shape 1 uses `ANIM.DAT` actions 0 (stand), 1 (walk), and 3 (unarmed run); frame metadata selects the `SHAPES.FLX` pose, horizontal flip, and movement delta. The original keypad direction mapping is supported alongside WASD/arrows and diagonal combinations. Shift and Caps Lock select walk/run using the controller's same-state rule. A 40 Hz host simulation tick advances frame steps against fixed-map and expanded-glob solid volumes; it now catches up after long paints instead of discarding all elapsed time beyond 50 ms. The retail signed displacement decoder is unchanged. The prototype's forward-only host movement step skips the small backward stride on walk frames 4 and 12 of directions 6/7/10/11, which had made both actor and following camera reverse mid-stride. This comfort policy and host tick rate are not recovered controller behavior. The persistent GDI back buffer avoids painting each moving frame directly to the window. The opt-in diagnostic HUD shows map, world position, facing, and locomotion state. Collision is an axis-aligned TYPEFLAG approximation; it does not reproduce original AreaSearch shape sweeps or step-up behavior, and the fixed-map record bounds remain the outer movement limit. The second HUD row is an observable, separate process-runtime diagnostic: the host 40 Hz step delivers a registered SystemTimer event, advances the recovered scheduler scan, and runs an owned Stand entry through its verified off-screen sleep branch. Tick, remaining sleep ticks, and wake count update while the window is active. Three base entries reserve the low process IDs; the Stand entry and NPC number are diagnostic fixtures, not map NPCs or the player process. Host tick frequency is not the original DOS timer interrupt rate. The diagnostic kernel also registers a partial KeyboardProcess and KeyDaemon at startup. Text-capable Win32 key messages exercise the recovered keyboard filter/copy callback and update the key-event count on the HUD. The daemon does not receive timer events yet. The visible WASD/keypad controls still use host polling; these processes do not yet deliver player input. diff --git a/rebuild/remorse/CMakeLists.txt b/rebuild/remorse/CMakeLists.txt index 67ee6da..9a37b5c 100644 --- a/rebuild/remorse/CMakeLists.txt +++ b/rebuild/remorse/CMakeLists.txt @@ -18,6 +18,7 @@ add_library(remorse_core src/shape_archive.cpp src/type_flags.cpp src/usecode_archive.cpp + src/usecode_vm.cpp ) target_compile_features(remorse_core PUBLIC cxx_std_17) diff --git a/rebuild/remorse/include/remorse/animation_archive.h b/rebuild/remorse/include/remorse/animation_archive.h index 3af202f..2b08e30 100644 --- a/rebuild/remorse/include/remorse/animation_archive.h +++ b/rebuild/remorse/include/remorse/animation_archive.h @@ -39,6 +39,13 @@ std::optional getAnimationFrame( u8 frameIndex); u16 getAnimationShapeFrame(const AnimationFrameMetadata& metadata) noexcept; bool isAnimationFrameFlipped(const AnimationFrameMetadata& metadata) noexcept; +u8 selectAnimationStartFrame( + const AnimationClip& clip, + bool returningFromTwoStep, + bool sameAsLastAnimation, + bool controlledAvatar, + bool entirelyOnScreen, + u8 frameSkip) noexcept; std::optional decodeAnimationDisplacement( const AnimationFrameMetadata& metadata, u8 direction, diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index 3492924..b993856 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -2,13 +2,16 @@ #include "remorse/compat.h" +#include #include #include +#include #include namespace remorse { class LiveFixedMapItems; +struct AnimationClip; struct ShapeTypeInfo; struct WorldPoint; struct FastAreaRange; @@ -43,6 +46,16 @@ struct KeyDaemonProcessEntry { u8 extra[0x0e]; } CR_PACKED; +struct ControllerProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x0e]; +} CR_PACKED; + +struct AnimPrimitiveProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x29]; +} CR_PACKED; + struct KeyEvent { u8 character; u8 scanCode; @@ -65,6 +78,8 @@ static_assert(sizeof(GravityProcessEntry) == 0x42, "GravityProcessEntry size mus static_assert(sizeof(SystemTimerProcessEntry) == 0x4a, "SystemTimerProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyDaemonProcessEntry) == 0x40, "KeyDaemonProcessEntry size must match allocation evidence"); +static_assert(sizeof(ControllerProcessEntry) == 0x40, "ControllerProcessEntry size must match allocation evidence"); +static_assert(sizeof(AnimPrimitiveProcessEntry) == 0x5b, "AnimPrimitiveProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyEvent) == 0x0c, "KeyEvent size must match keyboard event copy"); struct NpcBehaviorServices { @@ -97,6 +112,20 @@ public: SystemTimerProcessEntry* createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]); + ControllerProcessEntry* createControllerProcess(u8 activeGroup, u16 (&groupCounts)[32]); + AnimPrimitiveProcessEntry* createAnimPrimitiveProcess(u8 activeGroup, u16 itemNumber, + u16 animationNumber, u8 direction, const AnimationClip& clip, u16 (&groupCounts)[32]); + bool startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items, + const AnimationClip& clip, u8 frameSkip = 0); + std::optional advanceGroundedAnimPrimitive(u16 processId, LiveFixedMapItems& items, + const AnimationClip& clip, const std::vector& shapes, + const FastAreaRange& fastArea); + bool queuePendingKeyEvent(const KeyEvent& event); + std::optional popPendingKeyEvent(); + u8 pendingKeyEventCount() const; + bool pendingKeyEventOverflowed() const; + void dispatchPendingKeyEvents( + void (*deliver)(EntityDispatchEntryBase&, u16, u16, KeyEvent&, void*), void* context); void deliverSystemTimerEvent(); u32 systemTimerTick() const; void setSyncContext(bool enabled, u16 currentProcessId); @@ -136,9 +165,16 @@ private: std::vector> ownedProcesses_; std::vector> ownedStandProcesses_; std::vector> ownedGravityProcesses_; + std::vector> ownedAnimPrimitiveProcesses_; std::unique_ptr systemTimerProcess_; std::unique_ptr keyboardProcess_; std::unique_ptr keyDaemonProcess_; + std::unique_ptr controllerProcess_; + std::vector keyboardSubscriberIds_; + std::array pendingKeyEvents_{}; + u8 nextKeyEventOffset_ = 0; + u8 keyEventOffset_ = 0; + bool pendingKeyEventOverflowed_ = false; u16 systemTimerProcessId_ = 0xffff; std::vector itemProcessPresence_; std::vector itemProcessTypes_; diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index 184964c..3b7bd42 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -10,6 +10,7 @@ namespace remorse { struct ShapeTypeInfo; struct WorldRect; +struct GlobObject; class ProcessKernel; struct FixedMapEntry { @@ -77,6 +78,8 @@ struct FixedMapArchive { std::optional loadFixedMapArchive(const std::filesystem::path& path); std::optional loadFixedMap(const FixedMapArchive& archive, u32 mapIndex); std::optional> stageFixedMapItems(const FixedMap& map); +std::optional findTeleportEgg( + const std::vector& items, const std::vector& shapes, u8 eggId); std::optional> stageContainedFixedMapItems( const FixedMap& map, const std::vector& shapes); std::optional nearestStagedFixedMapItem( @@ -99,16 +102,30 @@ std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& const std::vector& items, const std::vector& shapes, ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick); +struct NpcAnimationState { + u16 lastAnimation = 0xffff; + u8 frame = 0; + u8 moreFlags = 0; +}; + class LiveFixedMapItems { public: explicit LiveFixedMapItems(std::vector items, std::vector containedItems = {}); + bool initializeAvatar(); + bool teleportAvatar(const StagedFixedMapItem& egg, u8 mapNumber); const StagedFixedMapItem* findItem(u16 itemNumber) const; + const std::vector& mapItems() const noexcept { return items_; } + const NpcAnimationState* findNpcAnimation(u16 itemNumber) const; + NpcAnimationState* editNpcAnimation(u16 itemNumber); u16 containedParent(u16 itemNumber) const; std::optional nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const; std::optional> sweepCandidateIds(const WorldRect& area, u16 excludedItemNumber) const; std::optional allocateItem(StagedFixedMapItem item); bool insertItem(StagedFixedMapItem item); + std::optional> hatchGlobEgg(u16 eggItemNumber, const GlobObject& glob, + const std::vector& shapes); + bool isGlobHatched(u16 eggItemNumber) const; bool moveItem(u16 itemNumber, u16 x, u16 y, u8 z); std::optional> grabItem(u16 itemNumber, const std::vector& shapes, ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick) const; @@ -118,7 +135,10 @@ public: private: std::vector items_; + std::optional avatar_; + std::vector npcAnimations_; std::vector allocatedIds_; + std::vector hatchedGlobIds_; std::vector parentById_; u16 nextFreeItemNumber_ = 0x100; }; diff --git a/rebuild/remorse/include/remorse/isometric_controls.h b/rebuild/remorse/include/remorse/isometric_controls.h index e0f50ae..3120aad 100644 --- a/rebuild/remorse/include/remorse/isometric_controls.h +++ b/rebuild/remorse/include/remorse/isometric_controls.h @@ -3,6 +3,9 @@ #include "remorse/animation_archive.h" #include "remorse/compat.h" +#include +#include + namespace remorse { struct WorldPositionD { @@ -33,6 +36,46 @@ inline std::optional controllerDirectionFromScan(u8 scanCode) } } +struct ControllerMovementRequest { + u8 animation = 0; + u8 direction = 14; +}; + +class ControllerMovementState { +public: + void handleDirectionalKey(u8 scanCode, u16 modifiers, bool pressed) + { + modifiers_ = modifiers; + const auto direction = controllerDirectionFromScan(scanCode); + if (!direction) { + return; + } + const auto held = std::find(heldScans_.begin(), heldScans_.end(), scanCode); + if (held != heldScans_.end()) { + heldScans_.erase(held); + } + if (pressed && (modifiers & 0x20) == 0) { + heldScans_.push_back(scanCode); + } + } + + ControllerMovementRequest request() const + { + if (heldScans_.empty()) { + return {0, lastDirection_}; + } + lastDirection_ = *controllerDirectionFromScan(heldScans_.back()); + return {static_cast(controllerWalkRequested(modifiers_) ? 1 : 3), lastDirection_}; + } + + void clear() { heldScans_.clear(); } + +private: + std::vector heldScans_; + u16 modifiers_ = 0; + mutable u8 lastDirection_ = 14; +}; + inline std::optional hostMovementStep( const AnimationFrameMetadata& metadata, u8 direction, bool rotateDirection) { diff --git a/rebuild/remorse/include/remorse/map_renderer.h b/rebuild/remorse/include/remorse/map_renderer.h index 90510b3..28425dc 100644 --- a/rebuild/remorse/include/remorse/map_renderer.h +++ b/rebuild/remorse/include/remorse/map_renderer.h @@ -6,7 +6,13 @@ #include "remorse/compat.h" #include "remorse/file_system.h" +#include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" #include "remorse/palette.h" +#include "remorse/shape_archive.h" +#include "remorse/type_flags.h" + +#include namespace remorse { @@ -17,6 +23,8 @@ struct WorldRect { s32 maxY = 0; }; +class LiveFixedMapItems; + struct WorldPoint { s32 x = 0; s32 y = 0; @@ -53,7 +61,22 @@ struct RenderedMapImage { std::vector pixels; }; +struct MapSceneRenderer { + FixedMap map; + std::vector globs; + ShapeArchive shapes; + Palette256 palette; + std::vector typeFlags; + std::map, DecodedShapeFrame> decodedFrames; + + std::optional render(const MapRenderOptions& options, + const LiveFixedMapItems* liveItems = nullptr); +}; + +std::optional loadMapSceneRenderer(const GameDataRoot& root, u32 mapIndex); std::optional renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options); +std::optional renderLiveMapPreview(const GameDataRoot& root, + const MapRenderOptions& options, const LiveFixedMapItems& items); ScreenPoint projectToScreen(const WorldPoint& point); bool writeBmp24(const std::filesystem::path& path, const RenderedMapImage& image); diff --git a/rebuild/remorse/include/remorse/usecode_vm.h b/rebuild/remorse/include/remorse/usecode_vm.h new file mode 100644 index 0000000..1d59e25 --- /dev/null +++ b/rebuild/remorse/include/remorse/usecode_vm.h @@ -0,0 +1,30 @@ +#pragma once + +#include +#include +#include +#include + +#include "remorse/compat.h" + +namespace remorse { + +struct UsecodeCallFrame { + u16 offset = 0; + u16 segment = 0; +}; + +class UsecodeInterpreterState { +public: + static std::optional initialize( + const std::vector& itemParameter); + bool pushCodeAddress(u16 offset, u16 segment); + + std::array valueStack{}; + std::size_t stackTop = 0xcc; + std::array callFrames{}; + u16 callFrameCount = 0; + u16 stackLimit = 199; +}; + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/animation_archive.cpp b/rebuild/remorse/src/animation_archive.cpp index f898135..401ee9e 100644 --- a/rebuild/remorse/src/animation_archive.cpp +++ b/rebuild/remorse/src/animation_archive.cpp @@ -104,6 +104,29 @@ bool isAnimationFrameFlipped(const AnimationFrameMetadata& metadata) noexcept return (metadata.bytes[1] & 0x80) != 0; } +u8 selectAnimationStartFrame( + const AnimationClip& clip, + bool returningFromTwoStep, + bool sameAsLastAnimation, + bool controlledAvatar, + bool entirelyOnScreen, + u8 frameSkip) noexcept +{ + const u8 flags = clip.header[1]; + if ((flags & 1) != 0) { + if (!returningFromTwoStep) { + return static_cast(clip.frameCount / 2); + } + return (flags & 4) != 0 ? static_cast(clip.frameCount - 1) : 0; + } + if ((flags & 4) == 0 || !sameAsLastAnimation) { + return 0; + } + const bool skipFrame = controlledAvatar ? frameSkip == 3 : + frameSkip >= 2 || !entirelyOnScreen; + return skipFrame ? 2 : 1; +} + std::optional decodeAnimationDisplacement( const AnimationFrameMetadata& metadata, u8 direction, diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index a07b7e5..829e83a 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -1,4 +1,5 @@ #include "remorse/entity_dispatch_entry.h" +#include "remorse/animation_archive.h" #include "remorse/collision.h" #include "remorse/fixed_map.h" @@ -138,6 +139,115 @@ EntityDispatchEntryBase* ProcessKernel::createItemProcess(u8 activeGroup, u16 it return result; } +AnimPrimitiveProcessEntry* ProcessKernel::createAnimPrimitiveProcess(u8 activeGroup, u16 itemNumber, + u16 animationNumber, u8 direction, const AnimationClip& clip, u16 (&groupCounts)[32]) +{ + if (itemNumber == 0 || itemNumber > maxTrackedItemNumber || animationNumber > 0x3f || + direction > 15 || clip.frameCount == 0) { + throw std::out_of_range("invalid animation process request"); + } + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x00, 0x2a57); + setProcessSourceType(process->base, itemNumber); + setProcessEventTypeChecked(process->base, 0xf0); + writeLe16(process->base, 0x16, static_cast(readLe16(process->base, 0x16) | 0x800)); + writeLe16(process->base, 0x22, 0xf0); + process->extra[0] = 1; + process->extra[4] = static_cast(animationNumber); + process->extra[5] = static_cast(animationNumber >> 8); + process->extra[6] = direction; + process->extra[7] = clip.frameCount; + std::copy(clip.header.begin(), clip.header.end(), process->extra + 0x18); + setLastAllocationSize(sizeof(AnimPrimitiveProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "AnimPrimitive"; + AnimPrimitiveProcessEntry* result = process.get(); + ownedAnimPrimitiveProcesses_.push_back(std::move(process)); + return result; +} + +bool ProcessKernel::startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items, + const AnimationClip& clip, u8 frameSkip) +{ + auto* process = processAt(processId); + if (process == nullptr || allocationSizeAt(processId) != sizeof(AnimPrimitiveProcessEntry) || + (readLe16(*process, 0x16) & 0x08) != 0 || process->bytes[0x3a] != 0 || + std::none_of(ownedAnimPrimitiveProcesses_.begin(), ownedAnimPrimitiveProcesses_.end(), + [process](const auto& owned) { return &owned->base == process; }) || + clip.frameCount != process->bytes[0x39] || + !std::equal(clip.header.begin(), clip.header.end(), process->bytes + 0x4a)) { + return false; + } + auto* npc = items.editNpcAnimation(readLe16(*process, 0x04)); + if (npc == nullptr) { + return false; + } + const u16 animation = readLe16(*process, 0x36); + npc->frame = selectAnimationStartFrame(clip, (npc->moreFlags & 4) != 0, + npc->lastAnimation == animation, readLe16(*process, 0x04) == 1, true, frameSkip); + npc->lastAnimation = animation; + process->bytes[0x3a] = 1; + return true; +} + +std::optional ProcessKernel::advanceGroundedAnimPrimitive(u16 processId, + LiveFixedMapItems& items, const AnimationClip& clip, + const std::vector& shapes, const FastAreaRange& fastArea) +{ + auto* process = processAt(processId); + if (process == nullptr || allocationSizeAt(processId) != sizeof(AnimPrimitiveProcessEntry) || + (readLe16(*process, 0x16) & 0x08) != 0 || process->bytes[0x3a] == 0 || + std::none_of(ownedAnimPrimitiveProcesses_.begin(), ownedAnimPrimitiveProcesses_.end(), + [process](const auto& owned) { return &owned->base == process; }) || + clip.frameCount != process->bytes[0x39] || + !std::equal(clip.header.begin(), clip.header.end(), process->bytes + 0x4a)) { + return std::nullopt; + } + const u16 itemNumber = readLe16(*process, 0x04); + auto* npc = items.editNpcAnimation(itemNumber); + const auto* item = items.findItem(itemNumber); + if (npc == nullptr || item == nullptr || item->data.shape >= shapes.size() || + npc->lastAnimation != readLe16(*process, 0x36)) { + return std::nullopt; + } + u8 nextFrame = static_cast(npc->frame + 1); + if ((clip.header[1] & 1) != 0 && (npc->moreFlags & 4) != 0 && + nextFrame == clip.frameCount / 2) { + return std::nullopt; + } + if (nextFrame >= clip.frameCount && (clip.header[1] & 5) == 5) { + nextFrame = 1; + } + if (nextFrame >= clip.frameCount) { + return std::nullopt; + } + const u8 direction = process->bytes[0x38]; + const auto metadata = getAnimationFrame(clip, direction, nextFrame); + if (!metadata || (metadata->bytes[5] & 2) == 0) { + return std::nullopt; + } + const auto step = decodeAnimationDisplacement(*metadata, direction, (clip.header[2] & 0x10) != 0); + if (!step) { + return std::nullopt; + } + const WorldPoint destination{static_cast(item->data.x) + step->x, + static_cast(item->data.y) + step->y, + static_cast(item->data.z) + step->z}; + const auto sweep = resolveSolidLiveSweep(items, itemNumber, destination, shapes, fastArea); + if (!sweep || sweep->failed || sweep->failedDirections != 0 || + !items.moveItem(itemNumber, static_cast(sweep->destination.x), + static_cast(sweep->destination.y), static_cast(sweep->destination.z))) { + process->bytes[0x3c] = 1; + return false; + } + npc->frame = nextFrame; + return true; +} + u16 ProcessKernel::hurlItem(u8 activeGroup, u16 itemNumber, s16 xs, s16 ys, s16 zs, s16 gravity, u32 timerTick, u16 (&groupCounts)[32]) { @@ -350,6 +460,7 @@ KeyboardProcessEntry* ProcessKernel::createKeyboardProcess(u8 activeGroup, u16 ( const u16 id = addProcess(process->base); processNames_[id] = "KeyboardProcess"; writeLe16(process->base, 0x18, static_cast(readLe16(process->base, 0x18) | 0x180)); + keyboardSubscriberIds_.push_back(id); keyboardProcess_ = std::move(process); return keyboardProcess_.get(); } @@ -375,6 +486,30 @@ KeyDaemonProcessEntry* ProcessKernel::createKeyDaemonProcess(u8 activeGroup, u16 return keyDaemonProcess_.get(); } +ControllerProcessEntry* ProcessKernel::createControllerProcess(u8 activeGroup, u16 (&groupCounts)[32]) +{ + if (controllerProcess_ != nullptr) { + throw std::logic_error("controller process already exists"); + } + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x00, 0x3aa6); + writeLe16(process->base, 0x16, static_cast(readLe16(process->base, 0x16) | 0x300)); + writeLe16(process->base, 0x18, static_cast(readLe16(process->base, 0x18) | 0x80)); + process->extra[0] = 0x15; + process->extra[1] = 0x01; + process->extra[4] = 0x3c; + setLastAllocationSize(sizeof(ControllerProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "Controller"; + keyboardSubscriberIds_.push_back(id); + controllerProcess_ = std::move(process); + return controllerProcess_.get(); +} + void ProcessKernel::deliverSystemTimerEvent() { if (systemTimerProcess_ == nullptr) { @@ -504,6 +639,12 @@ void ProcessKernel::releaseOwnedProcess(u16 id) ownedGravityProcesses_.erase(gravity); return; } + const auto animation = std::find_if(ownedAnimPrimitiveProcesses_.begin(), ownedAnimPrimitiveProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (animation != ownedAnimPrimitiveProcesses_.end()) { + ownedAnimPrimitiveProcesses_.erase(animation); + return; + } const auto owned = std::find_if(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; }); ownedProcesses_.erase(owned); @@ -526,6 +667,12 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) if (keyDaemonProcess_ != nullptr && entry == &keyDaemonProcess_->base) { throw std::logic_error("key daemon process teardown is not ported"); } + if (controllerProcess_ != nullptr && entry == &controllerProcess_->base) { + throw std::logic_error("controller process teardown is not ported"); + } + const bool ownedAnimationProcess = std::any_of(ownedAnimPrimitiveProcesses_.begin(), + ownedAnimPrimitiveProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(), [entry](const auto& process) { return &process->base == entry; }); const bool ownedGravityProcess = readLe16(*entry, 0x00) == 0x0610 && @@ -534,12 +681,13 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) const bool ownedItemProcess = readLe16(*entry, 0x00) == ItemProcess::vtableOffset && std::any_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; }); - if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess && !ownedGravityProcess || id < 3 || + if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess && + !ownedGravityProcess && !ownedAnimationProcess || id < 3 || readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 || readLe16(*entry, 0x2e) != 0 || readLe16(*entry, 0x30) != 0)) { throw std::logic_error("item process child cleanup is not ported"); } - if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && + if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && !ownedAnimationProcess && std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; })) { throw std::logic_error("external process ownership is not ported"); @@ -928,4 +1076,57 @@ bool KeyboardProcess::handleKeyEvent(KeyboardProcessEntry& process, u16 selector return true; } +bool ProcessKernel::queuePendingKeyEvent(const KeyEvent& event) +{ + if ((nextKeyEventOffset_ + 1) % pendingKeyEvents_.size() == keyEventOffset_) { + pendingKeyEventOverflowed_ = true; + return false; + } + pendingKeyEvents_[nextKeyEventOffset_] = event; + nextKeyEventOffset_ = static_cast((nextKeyEventOffset_ + 1) % pendingKeyEvents_.size()); + return true; +} + +std::optional ProcessKernel::popPendingKeyEvent() +{ + if (keyEventOffset_ == nextKeyEventOffset_) { + return std::nullopt; + } + const KeyEvent event = pendingKeyEvents_[keyEventOffset_]; + keyEventOffset_ = static_cast((keyEventOffset_ + 1) % pendingKeyEvents_.size()); + pendingKeyEventOverflowed_ = false; + return event; +} + +u8 ProcessKernel::pendingKeyEventCount() const +{ + return static_cast((nextKeyEventOffset_ + pendingKeyEvents_.size() - keyEventOffset_) % + pendingKeyEvents_.size()); +} + +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 79d4fa5..c13b6fa 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/glob_archive.h" #include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" @@ -153,6 +154,23 @@ std::optional> stageFixedMapItems(const FixedMap return items; } +std::optional findTeleportEgg( + const std::vector& items, const std::vector& shapes, u8 eggId) +{ + std::optional match; + for (const auto& item : items) { + if (item.data.shape >= shapes.size() || shapes[item.data.shape].family != 8 || + item.data.frame != 1 || (item.data.quality & 0xff) != eggId) { + continue; + } + if (match) { + return std::nullopt; + } + match = item; + } + return match; +} + std::optional> stageContainedFixedMapItems( const FixedMap& map, const std::vector& shapes) { @@ -415,7 +433,7 @@ std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& LiveFixedMapItems::LiveFixedMapItems(std::vector items, std::vector containedItems) - : items_(std::move(items)), allocatedIds_(0x2800), parentById_(0x2800) + : items_(std::move(items)), allocatedIds_(0x2800), hatchedGlobIds_(0x2800), parentById_(0x2800) { if (!buildStagedItemBlockChains(items_)) { throw std::invalid_argument("invalid live item IDs or coordinates"); @@ -439,8 +457,36 @@ LiveFixedMapItems::LiveFixedMapItems(std::vector items, } } +bool LiveFixedMapItems::initializeAvatar() +{ + if (avatar_) { + return false; + } + avatar_.emplace(); + avatar_->itemNumber = 1; + avatar_->data.shape = 1; + avatar_->data.npcNumber = 1; + npcAnimations_.resize(2); + return true; +} + +bool LiveFixedMapItems::teleportAvatar(const StagedFixedMapItem& egg, u8 mapNumber) +{ + if (!avatar_) { + return false; + } + avatar_->data.x = egg.data.x; + avatar_->data.y = egg.data.y; + avatar_->data.z = egg.data.z; + avatar_->data.mapNumber = mapNumber; + return true; +} + const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const { + if (itemNumber == 1) { + return avatar_ ? &*avatar_ : nullptr; + } for (const auto& item : items_) { if (item.itemNumber == itemNumber) { return &item; @@ -449,6 +495,19 @@ const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const return nullptr; } +const NpcAnimationState* LiveFixedMapItems::findNpcAnimation(u16 itemNumber) const +{ + const auto* item = findItem(itemNumber); + return itemNumber < npcAnimations_.size() && item != nullptr && item->data.npcNumber != 0 + ? &npcAnimations_[itemNumber] : nullptr; +} + +NpcAnimationState* LiveFixedMapItems::editNpcAnimation(u16 itemNumber) +{ + return const_cast( + static_cast(this)->findNpcAnimation(itemNumber)); +} + u16 LiveFixedMapItems::containedParent(u16 itemNumber) const { return itemNumber < parentById_.size() ? parentById_[itemNumber] : 0; @@ -517,11 +576,64 @@ bool LiveFixedMapItems::insertItem(StagedFixedMapItem item) return true; } +std::optional> LiveFixedMapItems::hatchGlobEgg(u16 eggItemNumber, + const GlobObject& glob, const std::vector& shapes) +{ + const auto* egg = findItem(eggItemNumber); + if (!egg || egg->data.shape >= shapes.size() || shapes[egg->data.shape].family != 3 || + egg->data.quality == 0 || egg->data.quality != glob.index || + isGlobHatched(eggItemNumber)) { + return std::nullopt; + } + std::vector children; + children.reserve(glob.entries.size()); + for (const auto& entry : glob.entries) { + StagedFixedMapItem child; + child.recordIndex = static_cast(-1); + child.data.x = static_cast((egg->data.x & ~0x1ff) + entry.x * 2 + 1); + child.data.y = static_cast((egg->data.y & ~0x1ff) + entry.y * 2 + 1); + child.data.z = static_cast(egg->data.z + entry.z); + child.data.shape = entry.shape; + child.data.frame = entry.frame; + child.data.flags = 0x82; + if (entry.shape == 0 || child.data.x > 0x7fff || child.data.y > 0x7fff) { + return std::nullopt; + } + children.push_back(child); + } + const std::size_t freeCount = static_cast(std::count( + allocatedIds_.begin() + nextFreeItemNumber_, allocatedIds_.end(), false)); + if (freeCount < children.size()) { + return std::nullopt; + } + std::vector childIds; + childIds.reserve(children.size()); + for (auto& child : children) { + childIds.push_back(*allocateItem(child)); + } + hatchedGlobIds_[eggItemNumber] = true; + return childIds; +} + +bool LiveFixedMapItems::isGlobHatched(u16 eggItemNumber) const +{ + return eggItemNumber < hatchedGlobIds_.size() && hatchedGlobIds_[eggItemNumber]; +} + bool LiveFixedMapItems::moveItem(u16 itemNumber, u16 x, u16 y, u8 z) { if (x > 0x7fff || y > 0x7fff) { return false; } + if (itemNumber == 1) { + if (!avatar_) { + return false; + } + avatar_->data.x = x; + avatar_->data.y = y; + avatar_->data.z = std::min(z, 0xfa); + return true; + } const auto item = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& candidate) { return candidate.itemNumber == itemNumber; }); diff --git a/rebuild/remorse/src/map_renderer.cpp b/rebuild/remorse/src/map_renderer.cpp index 8f2a84b..568131d 100644 --- a/rebuild/remorse/src/map_renderer.cpp +++ b/rebuild/remorse/src/map_renderer.cpp @@ -39,7 +39,7 @@ struct SceneItem { struct RenderNode { SceneItem item; - DecodedShapeFrame decoded; + const DecodedShapeFrame* decoded = nullptr; s32 left = 0; s32 top = 0; s32 right = 0; @@ -82,14 +82,27 @@ std::vector collectSceneItems( const FixedMap& fixedMap, const std::vector& typeFlags, const std::vector& globs, - const MapRenderOptions& options) + const MapRenderOptions& options, + const LiveFixedMapItems* liveItems) { std::vector pending; pending.reserve(fixedMap.entries.size()); - for (const FixedMapEntry& entry : fixedMap.entries) { + std::vector liveByRecord; + if (liveItems != nullptr) { + liveByRecord.resize(fixedMap.entries.size(), nullptr); + for (const auto& item : liveItems->mapItems()) { + if (item.recordIndex < liveByRecord.size()) { + liveByRecord[item.recordIndex] = &item; + } + } + } + for (std::size_t recordIndex = 0; recordIndex < fixedMap.entries.size(); ++recordIndex) { + const FixedMapEntry& entry = liveByRecord.empty() || liveByRecord[recordIndex] == nullptr + ? fixedMap.entries[recordIndex] : liveByRecord[recordIndex]->data; + const s32 scale = liveByRecord.empty() || liveByRecord[recordIndex] == nullptr ? 1 : 2; pending.push_back(SceneItem{ - static_cast(entry.x), - static_cast(entry.y), + static_cast(entry.x) * scale, + static_cast(entry.y) * scale, static_cast(entry.z), entry.shape, entry.frame, @@ -98,6 +111,16 @@ std::vector collectSceneItems( entry.mapNumber, true}); } + if (liveItems != nullptr) { + for (const auto& item : liveItems->mapItems()) { + if (item.recordIndex == static_cast(-1)) { + pending.push_back(SceneItem{static_cast(item.data.x) * 2, + static_cast(item.data.y) * 2, item.data.z, item.data.shape, + item.data.frame, item.data.flags, item.data.quality, item.data.mapNumber, + false}); + } + } + } std::vector items; for (std::size_t index = 0; index < pending.size(); ++index) { @@ -116,7 +139,10 @@ std::vector collectSceneItems( continue; } if (options.expandGlobs && info.family == 3 && item.fromFixed) { - const auto glob = findGlobObject(globs, item.quality); + const auto* stagedEgg = liveByRecord.empty() || index >= liveByRecord.size() + ? nullptr : liveByRecord[index]; + const auto glob = stagedEgg && liveItems->isGlobHatched(stagedEgg->itemNumber) + ? std::nullopt : findGlobObject(globs, item.quality); if (glob) { for (const GlobObjectEntry& entry : glob->entries) { pending.push_back(SceneItem{ @@ -153,7 +179,7 @@ s32 screenY(const SceneItem& item) return projectToScreen(WorldPoint{item.x, item.y, item.z}).y; } -std::optional cachedDecode( +const DecodedShapeFrame* cachedDecode( const ShapeArchive& archive, std::map, DecodedShapeFrame>& cache, u32 shape, @@ -162,28 +188,27 @@ std::optional cachedDecode( const auto key = std::make_pair(shape, frame); const auto found = cache.find(key); if (found != cache.end()) { - return found->second; + return &found->second; } const auto decoded = decodeShapeFrame(archive, shape, frame); if (!decoded) { - return std::nullopt; + return nullptr; } - cache.emplace(key, *decoded); - return decoded; + return &cache.emplace(key, std::move(*decoded)).first->second; } std::vector prepareRenderNodes( const std::vector& items, const ShapeArchive& shapeArchive, - const std::vector& typeFlags) + const std::vector& typeFlags, + std::map, DecodedShapeFrame>& cache) { - std::map, DecodedShapeFrame> cache; std::vector nodes; std::vector sortItems; nodes.reserve(items.size()); sortItems.reserve(items.size()); for (const SceneItem& item : items) { - const auto decoded = cachedDecode(shapeArchive, cache, item.shape, item.frame); + const auto* decoded = cachedDecode(shapeArchive, cache, item.shape, item.frame); if (!decoded) { continue; } @@ -193,13 +218,13 @@ std::vector prepareRenderNodes( const bool flipped = (item.flags & flagFlipped) != 0; RenderNode node; node.item = item; - node.decoded = *decoded; + node.decoded = decoded; node.left = flipped - ? bottomX + node.decoded.frame.xOffset - static_cast(node.decoded.frame.width) - : bottomX - node.decoded.frame.xOffset; - node.top = bottomY - node.decoded.frame.yOffset; - node.right = node.left + static_cast(node.decoded.frame.width); - node.bottom = node.top + static_cast(node.decoded.frame.height); + ? bottomX + decoded->frame.xOffset - static_cast(decoded->frame.width) + : bottomX - decoded->frame.xOffset; + node.top = bottomY - decoded->frame.yOffset; + node.right = node.left + static_cast(decoded->frame.width); + node.bottom = node.top + static_cast(decoded->frame.height); const ShapeTypeInfo& info = typeFlags[item.shape]; const s32 xDimension = static_cast(flipped ? info.y : info.x) * 32; @@ -251,15 +276,15 @@ std::vector prepareRenderNodes( void paintNode(RenderedMapImage& image, const RenderNode& node, const Palette256& palette) { const bool flipped = (node.item.flags & flagFlipped) != 0; - for (u32 sourceY = 0; sourceY < node.decoded.frame.height; ++sourceY) { + for (u32 sourceY = 0; sourceY < node.decoded->frame.height; ++sourceY) { const s32 destY = node.top - image.sourceTop + static_cast(sourceY); if (destY < 0 || destY >= static_cast(image.height)) { continue; } - const std::size_t sourceRow = static_cast(sourceY) * node.decoded.frame.width; - for (u32 sourceX = 0; sourceX < node.decoded.frame.width; ++sourceX) { - const u32 actualSourceX = flipped ? node.decoded.frame.width - 1 - sourceX : sourceX; - const s16 colorIndex = node.decoded.pixels[sourceRow + actualSourceX]; + const std::size_t sourceRow = static_cast(sourceY) * node.decoded->frame.width; + for (u32 sourceX = 0; sourceX < node.decoded->frame.width; ++sourceX) { + const u32 actualSourceX = flipped ? node.decoded->frame.width - 1 - sourceX : sourceX; + const s16 colorIndex = node.decoded->pixels[sourceRow + actualSourceX]; if (colorIndex < 0 || colorIndex >= 256) { continue; } @@ -293,7 +318,7 @@ ScreenPoint projectToScreen(const WorldPoint& point) return ScreenPoint{(point.x - point.y) / 4, (point.x + point.y) / 8 - point.z}; } -std::optional renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options) +std::optional loadMapSceneRenderer(const GameDataRoot& root, u32 mapIndex) { const auto fixedPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "FIXED.DAT"); const auto globPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "GLOB.FLX"); @@ -305,7 +330,7 @@ std::optional renderMapPreview(const GameDataRoot& root, const } const auto fixedArchive = loadFixedMapArchive(*fixedPath); - const auto fixedMap = fixedArchive ? loadFixedMap(*fixedArchive, options.mapIndex) : std::nullopt; + const auto fixedMap = fixedArchive ? loadFixedMap(*fixedArchive, mapIndex) : std::nullopt; const auto globs = loadGlobObjects(*globPath); const auto shapeArchive = loadShapeArchive(*shapePath); const auto palette = loadPalette256(*palettePath); @@ -313,9 +338,15 @@ std::optional renderMapPreview(const GameDataRoot& root, const if (!fixedMap || !globs || !shapeArchive || !palette || !typeFlags) { return std::nullopt; } + return MapSceneRenderer{std::move(*fixedMap), std::move(*globs), std::move(*shapeArchive), + *palette, std::move(*typeFlags), {}}; +} - const auto items = collectSceneItems(*fixedMap, *typeFlags, *globs, options); - auto nodes = prepareRenderNodes(items, *shapeArchive, *typeFlags); +std::optional MapSceneRenderer::render(const MapRenderOptions& options, + const LiveFixedMapItems* liveItems) +{ + const auto items = collectSceneItems(map, typeFlags, globs, options, liveItems); + auto nodes = prepareRenderNodes(items, shapes, typeFlags, decodedFrames); if (nodes.empty()) { return std::nullopt; } @@ -332,7 +363,7 @@ std::optional renderMapPreview(const GameDataRoot& root, const } RenderedMapImage image; - image.rawItemCount = static_cast(fixedMap->entries.size()); + image.rawItemCount = static_cast(map.entries.size()); image.renderItemCount = static_cast(items.size()); image.decodedItemCount = static_cast(nodes.size()); image.fullWidth = maxRight - minLeft; @@ -361,12 +392,25 @@ std::optional renderMapPreview(const GameDataRoot& root, const node.top >= image.sourceTop + static_cast(image.height)) { continue; } - paintNode(image, node, *palette); + paintNode(image, node, palette); ++image.paintedItemCount; } return image; } +std::optional renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options) +{ + auto renderer = loadMapSceneRenderer(root, options.mapIndex); + return renderer ? renderer->render(options) : std::nullopt; +} + +std::optional renderLiveMapPreview(const GameDataRoot& root, + const MapRenderOptions& options, const LiveFixedMapItems& items) +{ + auto renderer = loadMapSceneRenderer(root, options.mapIndex); + return renderer ? renderer->render(options, &items) : std::nullopt; +} + bool writeBmp24(const std::filesystem::path& path, const RenderedMapImage& image) { if (image.width == 0 || image.height == 0 || image.pixels.size() != static_cast(image.width) * image.height) { diff --git a/rebuild/remorse/src/usecode_vm.cpp b/rebuild/remorse/src/usecode_vm.cpp new file mode 100644 index 0000000..86d6d81 --- /dev/null +++ b/rebuild/remorse/src/usecode_vm.cpp @@ -0,0 +1,29 @@ +#include "remorse/usecode_vm.h" + +#include + +namespace remorse { + +std::optional UsecodeInterpreterState::initialize( + const std::vector& itemParameter) +{ + if (itemParameter.size() > 0xcc) { + return std::nullopt; + } + UsecodeInterpreterState state; + state.stackTop -= itemParameter.size(); + std::copy(itemParameter.begin(), itemParameter.end(), + state.valueStack.begin() + state.stackTop); + return state; +} + +bool UsecodeInterpreterState::pushCodeAddress(u16 offset, u16 segment) +{ + if (callFrameCount >= 0x1f) { + return false; + } + callFrames[callFrameCount++] = UsecodeCallFrame{offset, segment}; + return true; +} + +} // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index 345d6a7..6027077 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -43,10 +44,13 @@ constexpr remorse::s32 diagnosticItemRange = 48; struct AppState { remorse::GameDataRoot root; remorse::u32 mapIndex = 1; + bool diagnostics = false; remorse::ProcessKernel diagnosticKernel; remorse::u16 diagnosticGroupCounts[32]{}; remorse::StandProcessEntry* diagnosticStand = nullptr; remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr; + remorse::ControllerMovementState controllerMovement; + remorse::u16 animationProcessId = 0; std::optional liveItems; std::optional diagnosticItem; remorse::u16 diagnosticItemProcessId = 0; @@ -57,7 +61,11 @@ struct AppState { remorse::u32 standWakeCount = 0; remorse::u32 diagnosticKeyEvents = 0; std::mutex sceneMutex; + std::condition_variable renderWake; + bool renderRequested = false; + bool renderStop = false; std::optional scene; + std::optional renderer; std::optional standAnimation; std::optional walkAnimation; std::optional runAnimation; @@ -71,7 +79,6 @@ struct AppState { std::vector dibPixels; std::vector viewPixels; remorse::WorldPoint spawn{}; - remorse::WorldPoint playerWorld{}; remorse::FastAreaRange fastArea{}; remorse::s32 minWorldX = 0; remorse::s32 minWorldY = 0; @@ -86,6 +93,7 @@ struct AppState { std::wstring loadError; bool sceneLoaded = false; std::thread sceneThread; + std::thread renderThread; HDC backBufferDc = nullptr; HBITMAP backBufferBitmap = nullptr; HBITMAP previousBackBufferBitmap = nullptr; @@ -124,6 +132,16 @@ void setLoadFailure(AppState& state, const std::wstring& message) state.sceneLoaded = true; } +remorse::WorldPoint avatarWorld(const AppState& state) +{ + const auto* avatar = state.liveItems ? state.liveItems->findItem(1) : nullptr; + return avatar ? remorse::WorldPoint{avatar->data.x * 2, avatar->data.y * 2, avatar->data.z} + : state.spawn; +} + +bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, + const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range); + void loadSceneAsync(HWND window, AppState& state) { state.sceneThread = std::thread([window, &state]() { @@ -153,6 +171,11 @@ void loadSceneAsync(HWND window, AppState& state) return; } const auto stagedItems = remorse::stageFixedMapItems(*map); + if (!stagedItems) { + setLoadFailure(state, L"The fixed-map item cache could not be initialized."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath); const auto globObjects = remorse::loadGlobObjects(*globPath); @@ -249,13 +272,38 @@ void loadSceneAsync(HWND window, AppState& state) maxY = std::max(maxY, static_cast(entry.y)); } - const remorse::WorldPoint spawn{(minX + maxX) / 2, (minY + maxY) / 2, 0}; + const auto startingEgg = remorse::findTeleportEgg(*stagedItems, *shapeTypes, 0x1e); + if (state.mapIndex == 1 && !startingEgg) { + setLoadFailure(state, L"The original map 1 starting teleporter could not be found uniquely."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + if (state.mapIndex != 1 && !state.diagnostics) { + setLoadFailure(state, L"Only map 1 has a source-backed start. Use --diagnostics for other maps."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + const remorse::WorldPoint spawn = startingEgg + ? remorse::WorldPoint{startingEgg->data.x * 2, startingEgg->data.y * 2, startingEgg->data.z} + : remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0}; remorse::MapRenderOptions options; options.mapIndex = state.mapIndex; options.maxWidth = backingWidth; options.maxHeight = backingHeight; options.viewCenter = spawn; - auto scene = remorse::renderMapPreview(state.root, options); + remorse::LiveFixedMapItems liveItems(std::move(*stagedItems), std::move(containedItems)); + liveItems.initializeAvatar(); + remorse::StagedFixedMapItem diagnosticStart; + diagnosticStart.data.x = static_cast(spawn.x / 2); + diagnosticStart.data.y = static_cast(spawn.y / 2); + diagnosticStart.data.z = static_cast(spawn.z); + liveItems.teleportAvatar(startingEgg ? *startingEgg : diagnosticStart, + static_cast(state.mapIndex)); + auto renderer = remorse::loadMapSceneRenderer(state.root, state.mapIndex); + if (renderer) { + hatchGlobsInFastArea(liveItems, *renderer, remorse::calculateFastAreaRange(spawn)); + } + auto scene = renderer ? renderer->render(options, &liveItems) : std::nullopt; if (!scene) { setLoadFailure(state, L"Map graphics or palette data could not be loaded."); PostMessageW(window, sceneReadyMessage, 0, 0); @@ -272,7 +320,6 @@ void loadSceneAsync(HWND window, AppState& state) { std::lock_guard lock(state.sceneMutex); state.spawn = spawn; - state.playerWorld = spawn; state.fastArea = remorse::calculateFastAreaRange(spawn); state.playerCollisionBody = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]); state.collisionBodies = std::move(collisionBodies); @@ -286,15 +333,14 @@ void loadSceneAsync(HWND window, AppState& state) state.maxWorldX = maxX; state.maxWorldY = maxY; state.scene = std::move(scene); + state.renderer = std::move(renderer); state.dibPixels = std::move(dibPixels); state.standAnimation = *standAnimation; state.walkAnimation = *walkAnimation; state.runAnimation = *runAnimation; state.playerFrames = std::move(playerFrames); state.playerPalette = *palette; - if (stagedItems) { - state.liveItems.emplace(std::move(*stagedItems), std::move(containedItems)); - } + state.liveItems.emplace(std::move(liveItems)); state.sceneLoaded = true; } } catch (const std::exception& error) { @@ -306,6 +352,78 @@ void loadSceneAsync(HWND window, AppState& state) }); } +bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, + const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range) +{ + std::vector eggIds; + for (const auto& item : items.mapItems()) { + if (item.data.shape < renderer.typeFlags.size() && + renderer.typeFlags[item.data.shape].family == 3 && + !items.isGlobHatched(item.itemNumber) && remorse::isWorldPointInFastArea( + item.data.x * 2, item.data.y * 2, range)) { + eggIds.push_back(item.itemNumber); + } + } + bool changed = false; + for (const remorse::u16 eggId : eggIds) { + const auto* egg = items.findItem(eggId); + const auto glob = std::find_if(renderer.globs.begin(), renderer.globs.end(), + [egg](const auto& object) { return object.index == egg->data.quality; }); + if (glob != renderer.globs.end()) { + changed = items.hatchGlobEgg(eggId, *glob, renderer.typeFlags).has_value() || changed; + } + } + return changed; +} + +void startLiveRenderer(HWND window, AppState& state) +{ + state.renderThread = std::thread([window, &state]() { + for (;;) { + std::optional snapshot; + remorse::WorldPoint center{}; + { + std::unique_lock lock(state.sceneMutex); + state.renderWake.wait(lock, [&state]() { return state.renderStop || state.renderRequested; }); + if (state.renderStop) { + return; + } + state.renderRequested = false; + snapshot.emplace(*state.liveItems); + center = avatarWorld(state); + } + remorse::MapRenderOptions options; + options.mapIndex = state.mapIndex; + options.maxWidth = backingWidth; + options.maxHeight = backingHeight; + options.viewCenter = center; + const remorse::s32 radius = static_cast( + backingWidth + backingHeight * 2 + 512); + options.worldRect = remorse::WorldRect{ + center.x - radius, center.y - radius, center.x + radius, center.y + radius}; + auto scene = state.renderer->render(options, &*snapshot); + if (!scene) { + continue; + } + std::vector pixels(scene->pixels.size() * 3); + for (std::size_t index = 0; index < scene->pixels.size(); ++index) { + pixels[index * 3] = scene->pixels[index].blue; + pixels[index * 3 + 1] = scene->pixels[index].green; + pixels[index * 3 + 2] = scene->pixels[index].red; + } + { + std::lock_guard lock(state.sceneMutex); + if (state.renderStop) { + return; + } + state.scene = std::move(scene); + state.dibPixels = std::move(pixels); + } + PostMessageW(window, sceneReadyMessage, 0, 0); + } + }); +} + void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLORREF color, HFONT font) { const int saved = SaveDC(device); @@ -316,41 +434,6 @@ void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLOR RestoreDC(device, saved); } -bool isKeyDown(int key) -{ - return (GetAsyncKeyState(key) & 0x8000) != 0; -} - -std::optional readMovementDirection() -{ - if (isKeyDown(VK_HOME) || isKeyDown(VK_NUMPAD7) || isKeyDown('Q')) return remorse::controllerDirectionFromScan(0x47); - if (isKeyDown(VK_PRIOR) || isKeyDown(VK_NUMPAD9) || isKeyDown('E')) return remorse::controllerDirectionFromScan(0x49); - if (isKeyDown(VK_END) || isKeyDown(VK_NUMPAD1) || isKeyDown('Z')) return remorse::controllerDirectionFromScan(0x4f); - if (isKeyDown(VK_NEXT) || isKeyDown(VK_NUMPAD3) || isKeyDown('C')) return remorse::controllerDirectionFromScan(0x51); - - const bool up = isKeyDown(VK_UP) || isKeyDown('W') || isKeyDown(VK_NUMPAD8); - const bool right = isKeyDown(VK_RIGHT) || isKeyDown('D') || isKeyDown(VK_NUMPAD6); - const bool down = isKeyDown(VK_DOWN) || isKeyDown('S') || isKeyDown(VK_NUMPAD2); - const bool left = isKeyDown(VK_LEFT) || isKeyDown('A') || isKeyDown(VK_NUMPAD4); - if (up && left) return remorse::controllerDirectionFromScan(0x47); - if (up && right) return remorse::controllerDirectionFromScan(0x49); - if (down && left) return remorse::controllerDirectionFromScan(0x4f); - if (down && right) return remorse::controllerDirectionFromScan(0x51); - if (up) return remorse::controllerDirectionFromScan(0x48); - if (right) return remorse::controllerDirectionFromScan(0x4d); - if (down) return remorse::controllerDirectionFromScan(0x50); - if (left) return remorse::controllerDirectionFromScan(0x4b); - return std::nullopt; -} - -bool isWalkRequested() -{ - remorse::u16 modifiers = (GetKeyState(VK_CAPITAL) & 1) != 0 ? 0x40 : 0; - if (isKeyDown(VK_LSHIFT)) modifiers |= 0x01; - if (isKeyDown(VK_RSHIFT)) modifiers |= 0x02; - return remorse::controllerWalkRequested(modifiers); -} - void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight, int sourceLeft, int sourceTop, std::size_t viewStride) { @@ -377,10 +460,9 @@ void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight, } const remorse::DecodedShapeFrame& sprite = *state.playerFrames[shapeFrame]; - const int actorX = static_cast(state.scene->width / 2) + - static_cast(std::lround(state.playerOffsetX)) - sourceLeft; - const int actorY = static_cast(state.scene->height / 2) + - static_cast(std::lround(state.playerOffsetY)) - sourceTop; + const auto avatarScreen = remorse::projectToScreen(avatarWorld(state)); + const int actorX = avatarScreen.x - state.scene->sourceLeft - sourceLeft; + const int actorY = avatarScreen.y - state.scene->sourceTop - sourceTop; const int spriteLeft = actorX + sprite.frame.xOffset; const int spriteTop = actorY + sprite.frame.yOffset; const bool flipped = remorse::isAnimationFrameFlipped(*metadata); @@ -507,10 +589,9 @@ void paintWindow(HWND window, AppState& state) const int viewWidth = std::min(clientWidth, static_cast(state.scene->width)); const int viewHeight = std::min(clientHeight, static_cast(state.scene->height)); - const int centeredLeft = static_cast(state.scene->width / 2) + - static_cast(std::lround(state.playerOffsetX)) - viewWidth / 2; - const int centeredTop = static_cast(state.scene->height / 2) + - static_cast(std::lround(state.playerOffsetY)) - viewHeight / 2; + const auto avatarScreen = remorse::projectToScreen(avatarWorld(state)); + const int centeredLeft = avatarScreen.x - state.scene->sourceLeft - viewWidth / 2; + const int centeredTop = avatarScreen.y - state.scene->sourceTop - viewHeight / 2; const int sourceLeft = std::clamp(centeredLeft, 0, static_cast(state.scene->width) - viewWidth); const int sourceTop = std::clamp(centeredTop, 0, static_cast(state.scene->height) - viewHeight); @@ -525,6 +606,10 @@ void paintWindow(HWND window, AppState& state) static_cast(viewWidth) * 3); } compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride); + if (!state.diagnostics) { + finishPaint(); + return; + } RECT hud{0, 0, viewWidth, 80}; HBRUSH hudBrush = CreateSolidBrush(RGB(14, 24, 29)); @@ -538,10 +623,11 @@ void paintWindow(HWND window, AppState& state) DeleteObject(hudLine); std::wostringstream label; + const remorse::WorldPoint playerWorld = avatarWorld(state); label << L"MAP " << std::setw(3) << std::setfill(L'0') << state.mapIndex - << L" X " << state.playerWorld.x - << L" Y " << state.playerWorld.y - << L" Z " << static_cast(state.playerWorld.z) + << L" X " << playerWorld.x + << L" Y " << playerWorld.y + << L" Z " << static_cast(playerWorld.z) << L" DIR " << std::setw(2) << static_cast(state.playerDirection) << L" " << (state.playerAnimation == 3 ? L"RUN" : state.playerAnimation == 1 ? L"WALK" : L"IDLE") << L" WASD / KEYPAD SHIFT RUN"; @@ -570,7 +656,7 @@ void paintWindow(HWND window, AppState& state) SetTextColor(device, RGB(74, 207, 184)); DrawTextW(device, diagnostics.str().c_str(), -1, &diagnosticsBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS); const auto nearbyItem = state.liveItems ? state.liveItems->nearestItem( - state.playerWorld.x, state.playerWorld.y, diagnosticItemRange) : std::nullopt; + playerWorld.x, playerWorld.y, diagnosticItemRange) : std::nullopt; if (state.diagnosticItem || nearbyItem) { const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem; std::wostringstream itemStatus; @@ -603,10 +689,6 @@ void updatePlayer(HWND window, AppState& state) 0.0, 0.25); state.lastTick = now; - if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) { - DestroyWindow(window); - return; - } if (GetForegroundWindow() != window) { return; } @@ -616,11 +698,19 @@ void updatePlayer(HWND window, AppState& state) } state.simulationAccumulator += elapsed; - const auto direction = readMovementDirection(); bool changed = false; while (state.simulationAccumulator >= simulationTickSeconds) { state.simulationAccumulator -= simulationTickSeconds; + state.diagnosticKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& entry, + remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { + auto& app = *static_cast(context); + if (entry.bytes[0] == 0xa6 && entry.bytes[1] == 0x3a && selector == 0x10 && filter == 0) { + app.controllerMovement.handleDirectionalKey(event.scanCode, event.modifiers, event.field8 != 0); + } + }, &state); + const auto movement = state.controllerMovement.request(); state.diagnosticKernel.deliverSystemTimerEvent(); + if (state.diagnostics) { const bool wasSleeping = (state.diagnosticStand->base.bytes[0x19] & 0x10) != 0; const remorse::u32 previousSleepStart = standSleepStart(*state.diagnosticStand); state.diagnosticKernel.runTimedSchedulerPass(state.diagnosticKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& entry, void* context) { @@ -664,53 +754,69 @@ void updatePlayer(HWND window, AppState& state) if (wasSleeping && standSleepStart(*state.diagnosticStand) != previousSleepStart) { ++state.standWakeCount; } - changed = true; - if (!direction) { + } + changed = changed || state.diagnostics; + if (movement.animation == 0) { + if (state.animationProcessId != 0) { + auto* process = state.diagnosticKernel.processAt(state.animationProcessId); + process->bytes[0x18] |= 4; + state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts); + state.animationProcessId = 0; + } changed = changed || state.playerAnimation != 0 || state.playerFrame != 0; state.playerAnimation = 0; state.playerFrame = 0; continue; } - const remorse::u8 requestedAnimation = isWalkRequested() ? 1 : 3; + const remorse::u8 requestedAnimation = movement.animation; const remorse::AnimationClip& clip = requestedAnimation == 1 ? *state.walkAnimation : *state.runAnimation; - if (state.playerAnimation != requestedAnimation) { - state.playerAnimation = requestedAnimation; - state.playerFrame = 0; - } else { - state.playerFrame = static_cast( - (state.playerFrame + 1) % clip.frameCount); - } - state.playerDirection = *direction; - - const auto metadata = remorse::getAnimationFrame(clip, state.playerDirection, state.playerFrame); - if (metadata) { - const auto step = remorse::hostMovementStep( - *metadata, state.playerDirection, (clip.header[2] & 0x10) != 0); - if (step) { - const remorse::WorldPoint destination{ - state.playerWorld.x + step->x, - state.playerWorld.y + step->y, - state.playerWorld.z + step->z}; - const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(destination); - const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn); - const double nextOffsetX = destinationScreen.x - spawnScreen.x; - const double nextOffsetY = destinationScreen.y - spawnScreen.y; - const bool withinMapBounds = destination.x >= state.minWorldX && - destination.x <= state.maxWorldX && destination.y >= state.minWorldY && - destination.y <= state.maxWorldY; - const bool withinSceneBounds = std::abs(nextOffsetX) <= backingWidth / 2 - 16 && - std::abs(nextOffsetY) <= backingHeight / 2 - 16; - if (withinMapBounds && withinSceneBounds && remorse::canMoveCollisionBody( - state.playerCollisionBody, destination, state.collisionBodies)) { - state.playerWorld = destination; - state.fastArea = remorse::calculateFastAreaRange(destination); - state.playerCollisionBody.location = destination; - state.playerOffsetX = nextOffsetX; - state.playerOffsetY = nextOffsetY; - } + if (state.animationProcessId == 0 || state.playerAnimation != requestedAnimation || + state.playerDirection != movement.direction) { + if (state.animationProcessId != 0) { + auto* process = state.diagnosticKernel.processAt(state.animationProcessId); + process->bytes[0x18] |= 4; + state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts); } + auto* process = state.diagnosticKernel.createAnimPrimitiveProcess( + state.diagnosticKernel.activeGroup(), 1, requestedAnimation, movement.direction, + clip, state.diagnosticGroupCounts); + state.animationProcessId = static_cast(process->base.bytes[2] | + (static_cast(process->base.bytes[3]) << 8)); + state.diagnosticKernel.startAnimPrimitiveProcess(state.animationProcessId, *state.liveItems, clip); + state.playerAnimation = requestedAnimation; + } + state.playerDirection = movement.direction; + const auto* avatar = state.liveItems->findItem(1); + const remorse::WorldPoint beforeMove{avatar->data.x, avatar->data.y, avatar->data.z}; + const auto fastArea = remorse::calculateFastAreaRange( + {avatar->data.x, avatar->data.y, avatar->data.z}); + state.diagnosticKernel.runTimedSchedulerPass(state.diagnosticKernel.activeGroup(), + [](remorse::EntityDispatchEntryBase& entry, void* context) { + auto& app = *static_cast(context); + if (&entry == app.diagnosticKernel.processAt(app.animationProcessId)) { + const remorse::AnimationClip& activeClip = app.playerAnimation == 1 + ? *app.walkAnimation : *app.runAnimation; + const auto* item = app.liveItems->findItem(1); + app.diagnosticKernel.advanceGroundedAnimPrimitive(app.animationProcessId, + *app.liveItems, activeClip, app.shapeTypes, + remorse::calculateFastAreaRange({item->data.x, item->data.y, item->data.z})); + } + }, &state); + state.fastArea = fastArea; + state.playerFrame = state.liveItems->findNpcAnimation(1)->frame; + const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(avatarWorld(state)); + const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn); + state.playerOffsetX = destinationScreen.x - spawnScreen.x; + state.playerOffsetY = destinationScreen.y - spawnScreen.y; + const bool moved = avatar->data.x != beforeMove.x || avatar->data.y != beforeMove.y || + avatar->data.z != beforeMove.z; + const bool hatched = moved && hatchGlobsInFastArea( + *state.liveItems, *state.renderer, remorse::calculateFastAreaRange(avatarWorld(state))); + if (state.renderThread.joinable() && (moved || hatched)) { + state.renderRequested = true; + state.renderWake.notify_one(); } changed = true; } @@ -743,13 +849,47 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA updatePlayer(window, *state); } return 0; + case WM_KILLFOCUS: + state->controllerMovement.clear(); + while (state->diagnosticKernel.popPendingKeyEvent()) {} + return 0; case WM_KEYDOWN: - if (wParam == 'F') { + case WM_KEYUP: + if (wParam == VK_ESCAPE && message == WM_KEYDOWN) { + DestroyWindow(window); + return 0; + } + { + remorse::KeyEvent event{}; + event.scanCode = static_cast((lParam >> 16) & 0xff); + switch (wParam) { + case 'W': event.scanCode = 0x48; break; + case 'A': event.scanCode = 0x4b; break; + case 'S': event.scanCode = 0x50; break; + case 'D': event.scanCode = 0x4d; break; + case 'Q': event.scanCode = 0x47; break; + case 'E': event.scanCode = 0x49; break; + case 'Z': event.scanCode = 0x4f; break; + case 'C': event.scanCode = 0x51; break; + } + event.modifiers = (GetKeyState(VK_CAPITAL) & 1) != 0 ? 0x40 : 0; + if (GetKeyState(VK_NUMLOCK) & 1) event.modifiers |= 0x20; + if ((lParam & (1L << 24)) != 0 || wParam == 'W' || wParam == 'A' || + wParam == 'S' || wParam == 'D' || wParam == 'Q' || wParam == 'E' || + wParam == 'Z' || wParam == 'C') event.modifiers &= ~0x20; + if (GetKeyState(VK_LSHIFT) & 0x8000) event.modifiers |= 1; + if (GetKeyState(VK_RSHIFT) & 0x8000) event.modifiers |= 2; + event.field8 = message == WM_KEYDOWN ? 1 : 0; + state->diagnosticKernel.queuePendingKeyEvent(event); + } + if (message == WM_KEYUP) return 0; + if (state->diagnostics && wParam == 'F') { std::lock_guard lock(state->sceneMutex); if (state->sceneLoaded && state->scene && !state->diagnosticItemCompleted && state->diagnosticItemProcessId == 0) { + const remorse::WorldPoint playerWorld = avatarWorld(*state); state->diagnosticItem = state->liveItems ? state->liveItems->nearestItem( - state->playerWorld.x, state->playerWorld.y, diagnosticItemRange) : std::nullopt; + playerWorld.x, playerWorld.y, diagnosticItemRange) : std::nullopt; } if (state->diagnosticItem && state->diagnosticItemProcessId == 0 && state->diagnosticItem->itemNumber <= remorse::ProcessKernel::maxTrackedItemNumber && @@ -764,7 +904,7 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA } return 0; case WM_CHAR: - if (wParam > 0 && wParam <= 0xff) { + if (state->diagnostics && wParam > 0 && wParam <= 0xff) { remorse::KeyEvent lastEvent{}; lastEvent.character = static_cast(wParam); lastEvent.scanCode = static_cast((lParam >> 16) & 0xff); @@ -785,6 +925,12 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA paintWindow(window, *state); return 0; case sceneReadyMessage: { + { + std::lock_guard lock(state->sceneMutex); + if (state->sceneLoaded && state->renderer && !state->renderThread.joinable()) { + startLiveRenderer(window, *state); + } + } InvalidateRect(window, nullptr, FALSE); return 0; } @@ -793,6 +939,14 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA if (state->sceneThread.joinable()) { state->sceneThread.join(); } + { + std::lock_guard lock(state->sceneMutex); + state->renderStop = true; + } + state->renderWake.notify_one(); + if (state->renderThread.joinable()) { + state->renderThread.join(); + } if (state->backBufferDc) { SelectObject(state->backBufferDc, state->previousBackBufferBitmap); DeleteObject(state->backBufferBitmap); @@ -811,11 +965,18 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo { remorse::installCrashDiagnostics(); remorse::u32 mapIndex = 1; - if (commandLine && *commandLine) { - wchar_t* end = nullptr; - const unsigned long parsed = std::wcstoul(commandLine, &end, 0); - if (end != commandLine && parsed <= 255) { - mapIndex = static_cast(parsed); + bool diagnostics = false; + std::wistringstream arguments(commandLine ? commandLine : L""); + std::wstring argument; + while (arguments >> argument) { + if (argument == L"--diagnostics") { + diagnostics = true; + } else { + wchar_t* end = nullptr; + const unsigned long parsed = std::wcstoul(argument.c_str(), &end, 0); + if (end != argument.c_str() && *end == L'\0' && parsed <= 255) { + mapIndex = static_cast(parsed); + } } } @@ -835,13 +996,17 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo AppState state; state.root = *root; state.mapIndex = mapIndex; + state.diagnostics = diagnostics; for (int index = 0; index < 3; ++index) { state.diagnosticKernel.createProcess(1, state.diagnosticGroupCounts); } state.diagnosticKernel.createSystemTimerProcess(1, state.diagnosticGroupCounts); state.diagnosticKeyboard = state.diagnosticKernel.createKeyboardProcess(1, state.diagnosticGroupCounts); - state.diagnosticKernel.createKeyDaemonProcess(1, state.diagnosticGroupCounts); - state.diagnosticStand = state.diagnosticKernel.createStandProcess(1, 1, state.diagnosticGroupCounts); + state.diagnosticKernel.createControllerProcess(1, state.diagnosticGroupCounts); + if (diagnostics) { + state.diagnosticKernel.createKeyDaemonProcess(1, state.diagnosticGroupCounts); + state.diagnosticStand = state.diagnosticKernel.createStandProcess(1, 1, state.diagnosticGroupCounts); + } WNDCLASSEXW windowClass{}; windowClass.cbSize = sizeof(windowClass); @@ -859,7 +1024,9 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo RECT bounds{0, 0, initialClientWidth, initialClientHeight}; AdjustWindowRect(&bounds, WS_OVERLAPPEDWINDOW, FALSE); - HWND window = CreateWindowExW(0, windowClassName, L"Crusader: No Remorse | Rebuild", WS_OVERLAPPEDWINDOW, + HWND window = CreateWindowExW(0, windowClassName, + diagnostics ? L"Crusader: No Remorse | Diagnostics" : L"Crusader: No Remorse | Traversal Test", + WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, bounds.right - bounds.left, bounds.bottom - bounds.top, nullptr, nullptr, instance, &state); if (!window) { diff --git a/rebuild/remorse/tests/animation_archive_tests.cpp b/rebuild/remorse/tests/animation_archive_tests.cpp index 6795822..b88fae4 100644 --- a/rebuild/remorse/tests/animation_archive_tests.cpp +++ b/rebuild/remorse/tests/animation_archive_tests.cpp @@ -100,6 +100,29 @@ int main() assert(stand.has_value() && stand->frameCount > 0); assert(walk.has_value() && walk->frameCount == 17); assert(run.has_value() && run->frameCount == 12); + for (const remorse::AnimationClip* clip : {&*walk, &*run}) { + assert(clip->header[1] == 5); + for (remorse::u8 direction = 0; direction < 16; ++direction) { + for (remorse::u8 frame = 1; frame < clip->frameCount; ++frame) { + const auto metadata = remorse::getAnimationFrame(*clip, direction, frame); + assert(metadata && (metadata->bytes[5] & 2) != 0); + } + } + } + auto startClip = *walk; + startClip.header[1] = 1; + assert(remorse::selectAnimationStartFrame(startClip, false, false, true, true, 0) == 8); + assert(remorse::selectAnimationStartFrame(startClip, true, false, true, true, 0) == 0); + startClip.header[1] = 5; + assert(remorse::selectAnimationStartFrame(startClip, true, false, true, true, 0) == 16); + startClip.header[1] = 4; + assert(remorse::selectAnimationStartFrame(startClip, false, false, true, true, 0) == 0); + assert(remorse::selectAnimationStartFrame(startClip, false, true, true, true, 0) == 1); + assert(remorse::selectAnimationStartFrame(startClip, false, true, true, true, 3) == 2); + assert(remorse::selectAnimationStartFrame(startClip, false, true, false, false, 0) == 2); + assert(remorse::selectAnimationStartFrame(startClip, false, true, false, true, 2) == 2); + startClip.header[1] = 0; + assert(remorse::selectAnimationStartFrame(startClip, false, true, true, true, 0) == 0); assert(remorse::getAnimationFrame(*walk, 0, 0).has_value()); assert(remorse::getAnimationFrame(*run, 15, 11).has_value()); for (remorse::u8 direction : {remorse::u8{6}, remorse::u8{7}, remorse::u8{10}, remorse::u8{11}}) { diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index 4d16f58..177f96f 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -1,6 +1,8 @@ +#include "remorse/animation_archive.h" #include "remorse/collision.h" #include "remorse/entity_dispatch_entry.h" #include "remorse/fixed_map.h" +#include "remorse/isometric_controls.h" #include "remorse/map_renderer.h" #include "remorse/type_flags.h" @@ -877,8 +879,139 @@ int main() assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent)); keyboardEvent.character = 0x41; assert(remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent)); + remorse::ProcessKernel inputKernel; + assert(!inputKernel.popPendingKeyEvent()); + for (remorse::u8 index = 0; index < 31; ++index) { + remorse::KeyEvent queued{}; + queued.scanCode = index; + assert(inputKernel.queuePendingKeyEvent(queued)); + } + assert(inputKernel.pendingKeyEventCount() == 31); + assert(!inputKernel.queuePendingKeyEvent({})); + assert(inputKernel.pendingKeyEventOverflowed()); + for (remorse::u8 index = 0; index < 31; ++index) { + const auto queued = inputKernel.popPendingKeyEvent(); + assert(queued && queued->scanCode == index); + } + assert(inputKernel.pendingKeyEventCount() == 0 && !inputKernel.pendingKeyEventOverflowed()); + remorse::KeyEvent wrapped{}; + wrapped.scanCode = 0x47; + assert(inputKernel.queuePendingKeyEvent(wrapped)); + assert(inputKernel.popPendingKeyEvent()->scanCode == 0x47); + remorse::u16 inputGroups[32]{}; + auto* inputKeyboard = inputKernel.createKeyboardProcess(1, inputGroups); + auto* inputController = inputKernel.createControllerProcess(1, inputGroups); + assert(inputController && inputController->base.bytes[0x00] == 0xa6 && + inputController->base.bytes[0x01] == 0x3a); + assert(inputController->base.bytes[0x17] == 0x03 && inputController->extra[4] == 0x3c); + assert(!inputKeyboard->extra[0]); + assert(inputKernel.queuePendingKeyEvent(wrapped)); + wrapped.scanCode = 0x48; + assert(inputKernel.queuePendingKeyEvent(wrapped)); + std::vector deliveredScans; + inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process, + remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { + assert(selector == 0x10 && filter == 0); + assert(process.bytes[0x00] == 0xa6); + static_cast*>(context)->push_back(event.scanCode); + }, &deliveredScans); + assert((deliveredScans == std::vector{0x47, 0x48})); + assert(inputKernel.pendingKeyEventCount() == 0); + remorse::ControllerMovementState deliveredMovement; + wrapped.scanCode = 0x48; + wrapped.field8 = 1; + assert(inputKernel.queuePendingKeyEvent(wrapped)); + inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process, + remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { + assert(process.bytes[0] == 0xa6 && selector == 0x10 && filter == 0); + static_cast(context)->handleDirectionalKey( + event.scanCode, event.modifiers, event.field8 != 0); + }, &deliveredMovement); + assert(deliveredMovement.request().animation == 1 && deliveredMovement.request().direction == 14); + wrapped.field8 = 0; + assert(inputKernel.queuePendingKeyEvent(wrapped)); + inputKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase&, + remorse::u16, remorse::u16, remorse::KeyEvent& event, void* context) { + static_cast(context)->handleDirectionalKey( + event.scanCode, event.modifiers, event.field8 != 0); + }, &deliveredMovement); + assert(deliveredMovement.request().animation == 0); assert(std::memcmp(&keyboardEvent, &lastEvent, sizeof(keyboardEvent)) == 0); assert(keyboard->extra[0] == 0x21); + remorse::ProcessKernel animationKernel; + remorse::u16 animationGroups[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + animationKernel.createProcess(1, animationGroups); + } + remorse::AnimationClip walking{}; + walking.header = {17, 4, 0, 0}; + walking.frameCount = 17; + auto* animation = animationKernel.createAnimPrimitiveProcess(1, 1, 1, 6, walking, animationGroups); + assert(animationKernel.processAt(3) == &animation->base); + assert(animationKernel.allocationSizeAt(3) == 0x5b && animationGroups[1] == 4); + assert(animationKernel.findProcessForItemAndType(1, 0xf0) == &animation->base); + assert(animation->base.bytes[0] == 0x57 && animation->base.bytes[1] == 0x2a); + assert(animation->base.bytes[0x16] == 0 && animation->base.bytes[0x17] == 0x08); + assert(animation->extra[0] == 1 && animation->extra[4] == 1 && animation->extra[6] == 6); + assert(animation->extra[7] == 17 && animation->extra[0x18] == 17 && animation->extra[0x19] == 4); + remorse::LiveFixedMapItems animationItems({}); + assert(animationItems.initializeAvatar()); + assert(animationKernel.startAnimPrimitiveProcess(3, animationItems, walking)); + const auto* npcAnimation = animationItems.findNpcAnimation(1); + assert(npcAnimation && npcAnimation->lastAnimation == 1 && npcAnimation->frame == 0); + assert(!animationKernel.startAnimPrimitiveProcess(3, animationItems, walking)); + auto* repeatedWalk = animationKernel.createAnimPrimitiveProcess(1, 1, 1, 6, walking, animationGroups); + assert(animationKernel.startAnimPrimitiveProcess(4, animationItems, walking)); + assert(repeatedWalk->base.bytes[0x3a] == 1 && animationItems.findNpcAnimation(1)->frame == 1); + auto* turning = animationKernel.createAnimPrimitiveProcess(1, 1, 0, 6, walking, animationGroups); + assert(animationKernel.startAnimPrimitiveProcess(5, animationItems, walking)); + assert(turning->base.bytes[0x3a] == 1 && animationItems.findNpcAnimation(1)->frame == 0); + remorse::StagedFixedMapItem animationSpawn{}; + animationSpawn.data.x = 512; + animationSpawn.data.y = 512; + assert(animationItems.teleportAvatar(animationSpawn, 1)); + walking.frames.resize(17 * 8); + auto& nextWalkFrame = walking.frames[3 * 17 + 1]; + nextWalkFrame.bytes[4] = 1; + nextWalkFrame.bytes[5] = 2; + std::vector animationShapes(2); + animationShapes[1].x = animationShapes[1].y = animationShapes[1].z = 2; + auto& movingNpc = *animationItems.editNpcAnimation(1); + movingNpc.lastAnimation = 1; + movingNpc.frame = 0; + const auto animationArea = remorse::calculateFastAreaRange({512, 512, 0}); + assert(animationKernel.advanceGroundedAnimPrimitive(3, animationItems, + walking, animationShapes, animationArea) == true); + assert(animationItems.findItem(1)->data.x == 514 && animationItems.findItem(1)->data.y == 514); + assert(movingNpc.frame == 1); + nextWalkFrame.bytes[4] = 100; + movingNpc.frame = 0; + remorse::StagedFixedMapItem animationWall{}; + animationWall.itemNumber = 0x100; + animationWall.data.shape = 2; + animationWall.data.x = 650; + animationWall.data.y = 650; + animationShapes.push_back(animationShapes[1]); + animationShapes[2].flags = 2; + assert(animationItems.insertItem(animationWall)); + assert(animationKernel.advanceGroundedAnimPrimitive(3, animationItems, + walking, animationShapes, animationArea) == false); + assert(animationItems.findItem(1)->data.x == 514 && movingNpc.frame == 0); + assert(animation->extra[0x0a] == 1); + walking.header[1] = 5; + nextWalkFrame.bytes[4] = 1; + auto* twoStepWalk = animationKernel.createAnimPrimitiveProcess(1, 1, 1, 6, walking, animationGroups); + assert(animationKernel.startAnimPrimitiveProcess(6, animationItems, walking)); + assert(movingNpc.frame == 8 && twoStepWalk->extra[7] == 17); + movingNpc.frame = 16; + assert(animationKernel.advanceGroundedAnimPrimitive(6, animationItems, + walking, animationShapes, animationArea) == true); + assert(movingNpc.frame == 1 && animationItems.findItem(1)->data.x == 516); + twoStepWalk->base.bytes[0x18] |= 4; + animationKernel.terminateProcess(6, animationGroups); + assert(animationKernel.processAt(6) == nullptr && animationKernel.allocationSizeAt(6) == 0); + assert(animationGroups[1] == 6 && animationKernel.itemHasProcess(1)); + return 0; } diff --git a/rebuild/remorse/tests/fixed_map_tests.cpp b/rebuild/remorse/tests/fixed_map_tests.cpp index bd81532..9be0fa8 100644 --- a/rebuild/remorse/tests/fixed_map_tests.cpp +++ b/rebuild/remorse/tests/fixed_map_tests.cpp @@ -1,6 +1,7 @@ #include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" #include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" #include "remorse/map_renderer.h" #include "remorse/type_flags.h" @@ -235,6 +236,24 @@ int main() assert(allocatedItems.allocateItem(newItem) == 0x107); newItem.data.x = 0x8000; assert(!allocatedItems.allocateItem(newItem) && !allocatedItems.findItem(0x108)); + remorse::StagedFixedMapItem globEgg; + globEgg.itemNumber = 0x100; + globEgg.data.x = 0x403; + globEgg.data.y = 0x601; + globEgg.data.z = 12; + globEgg.data.shape = 3; + globEgg.data.quality = 7; + remorse::LiveFixedMapItems hatchedItems({globEgg}); + std::vector globShapes(4); + globShapes[3].family = 3; + remorse::GlobObject glob{7, {{2, 5, 3, 1, 2}}}; + const auto childIds = hatchedItems.hatchGlobEgg(0x100, glob, globShapes); + assert(childIds && *childIds == std::vector{0x101}); + const auto* child = hatchedItems.findItem(0x101); + assert(child && child->recordIndex == static_cast(-1)); + assert(child->data.x == 0x405 && child->data.y == 0x60b && child->data.z == 15); + assert(child->data.flags == 0x82 && child->data.frame == 2); + assert(hatchedItems.isGlobHatched(0x100) && !hatchedItems.hatchGlobEgg(0x100, glob, globShapes)); remorse::LiveFixedMapItems movingItems(blockItems); remorse::ProcessKernel movingKernel; remorse::u16 movingGroups[32]{}; @@ -266,7 +285,18 @@ int main() candidate.itemNumber = 0; assert(remorse::classifyItemFindZMatch(origin, originShape, candidate, footprint, 3) == 0); assert(cachedItems->front().recordIndex < retailMap->entries.size()); - const remorse::LiveFixedMapItems retailLiveItems(*cachedItems); + remorse::LiveFixedMapItems retailLiveItems(*cachedItems); + assert(!retailLiveItems.findItem(1)); + assert(retailLiveItems.initializeAvatar()); + assert(!retailLiveItems.initializeAvatar()); + assert(retailLiveItems.findItem(1)->data.shape == 1); + assert(retailLiveItems.findItem(1)->data.frame == 0); + assert(retailLiveItems.findItem(1)->data.npcNumber == 1); + assert(retailLiveItems.teleportAvatar(cachedItems->front(), 1)); + assert(retailLiveItems.findItem(1)->data.x == cachedItems->front().data.x); + assert(retailLiveItems.findItem(1)->data.mapNumber == 1); + assert(retailLiveItems.moveItem(1, 100, 200, 5)); + assert(retailLiveItems.findItem(1)->data.x == 100 && retailLiveItems.findItem(1)->data.y == 200); assert(retailLiveItems.findItem(cachedItems->front().itemNumber)->recordIndex == cachedItems->front().recordIndex); for (const auto& item : *cachedItems) { diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index dbb5900..a828602 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -1,8 +1,11 @@ +#include "remorse/collision.h" #include "remorse/file_system.h" #include "remorse/flex_archive.h" #include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" #include "remorse/type_flags.h" #include "remorse/usecode_archive.h" +#include "remorse/usecode_vm.h" #include #include @@ -69,6 +72,38 @@ int main() assert(fixedMap && typeFlags); const auto stagedItems = remorse::stageFixedMapItems(*fixedMap); assert(stagedItems && !stagedItems->empty()); + const auto spawnEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x1e); + assert(spawnEgg); + const auto globPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GLOB.FLX"); + const auto globs = globPath ? remorse::loadGlobObjects(*globPath) : std::nullopt; + assert(globs); + remorse::LiveFixedMapItems spawnedItems(*stagedItems); + const auto fastArea = remorse::calculateFastAreaRange({ + spawnEgg->data.x * 2, spawnEgg->data.y * 2, spawnEgg->data.z}); + unsigned hatched = 0; + for (const auto& egg : *stagedItems) { + if (egg.data.shape >= typeFlags->size() || (*typeFlags)[egg.data.shape].family != 3 || + !remorse::isWorldPointInFastArea(egg.data.x * 2, egg.data.y * 2, fastArea)) continue; + for (const auto& glob : *globs) { + if (glob.index == egg.data.quality) { + const auto children = spawnedItems.hatchGlobEgg(egg.itemNumber, glob, *typeFlags); + if (children) hatched += static_cast(children->size()); + break; + } + } + } + unsigned scriptChildren = 0; + for (const auto& item : spawnedItems.mapItems()) { + if (item.recordIndex != static_cast(-1) || item.data.shape >= typeFlags->size()) continue; + const remorse::UsecodeItemIdentity childIdentity{item.itemNumber, item.data.shape, + item.data.flags, item.data.quality, (*typeFlags)[item.data.shape].family, false}; + const auto use = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, childIdentity, + remorse::UsecodeClassBases{0, 0x800, 0x900}, 2, 1); + if (use) { + ++scriptChildren; + } + } + assert(hatched == 4 && scriptChildren == 0); const auto& staged = stagedItems->front(); assert(staged.data.shape < typeFlags->size()); const remorse::UsecodeItemIdentity stagedIdentity{staged.itemNumber, staged.data.shape, @@ -100,6 +135,18 @@ int main() rechargeItem, retailBases, 0x200, 9); assert(eligibleRelease && eligibleRelease->classId == 0x138 && eligibleRelease->className == "RECHFLNS" && eligibleRelease->body.bytes.size() == 102); + auto interpreter = remorse::UsecodeInterpreterState::initialize({0x00, 0x01}); + assert(interpreter && interpreter->stackTop == 0xca && interpreter->stackLimit == 199); + assert(interpreter->valueStack[0xca] == 0x00 && interpreter->valueStack[0xcb] == 0x01); + assert(interpreter->pushCodeAddress(eligibleRelease->classId, 9)); + assert(interpreter->callFrameCount == 1 && interpreter->callFrames[0].offset == 0x138 && + interpreter->callFrames[0].segment == 9); + for (unsigned index = 1; index < 0x1f; ++index) { + assert(interpreter->pushCodeAddress(static_cast(index), 0)); + } + assert(!interpreter->pushCodeAddress(0xffff, 0)); + assert(interpreter->callFrameCount == 0x1f && interpreter->callFrames[31].offset == 0); + assert(!remorse::UsecodeInterpreterState::initialize(std::vector(0xcd))); assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, rechargeItem, retailBases, 0, 9)); std::vector ownerRows(26); diff --git a/rebuild/remorse/tests/isometric_controls_tests.cpp b/rebuild/remorse/tests/isometric_controls_tests.cpp index 7c8032f..a9bd432 100644 --- a/rebuild/remorse/tests/isometric_controls_tests.cpp +++ b/rebuild/remorse/tests/isometric_controls_tests.cpp @@ -5,6 +5,22 @@ int main() { + remorse::ControllerMovementState controller; + assert(controller.request().animation == 0); + controller.handleDirectionalKey(0x48, 0, true); + assert(controller.request().animation == 1 && controller.request().direction == 14); + controller.handleDirectionalKey(0x4d, 1, true); + assert(controller.request().animation == 3 && controller.request().direction == 2); + controller.handleDirectionalKey(0x4d, 1, false); + assert(controller.request().animation == 3 && controller.request().direction == 14); + controller.handleDirectionalKey(0x48, 0, false); + assert(controller.request().animation == 0 && controller.request().direction == 14); + controller.handleDirectionalKey(0x49, 0x20, true); + assert(controller.request().animation == 0); + controller.handleDirectionalKey(0x47, 0x40, true); + assert(controller.request().animation == 3 && controller.request().direction == 12); + controller.clear(); + assert(controller.request().animation == 0); assert(remorse::controllerWalkRequested(0)); assert(!remorse::controllerWalkRequested(0x01)); assert(!remorse::controllerWalkRequested(0x02)); diff --git a/rebuild/remorse/tests/map_renderer_tests.cpp b/rebuild/remorse/tests/map_renderer_tests.cpp index 987e88d..d4197da 100644 --- a/rebuild/remorse/tests/map_renderer_tests.cpp +++ b/rebuild/remorse/tests/map_renderer_tests.cpp @@ -1,10 +1,14 @@ +#include "remorse/collision.h" #include "remorse/file_system.h" #include "remorse/fixed_map.h" +#include "remorse/glob_archive.h" #include "remorse/map_renderer.h" +#include "remorse/type_flags.h" #include #include #include +#include int main() { @@ -51,5 +55,100 @@ int main() const remorse::ScreenPoint center = remorse::projectToScreen(*options.viewCenter); assert(centeredImage->sourceLeft == center.x - static_cast(options.maxWidth / 2)); assert(centeredImage->sourceTop == center.y - static_cast(options.maxHeight / 2)); + + const auto typesPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT"); + const auto globPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GLOB.FLX"); + assert(typesPath && globPath); + const auto shapeTypes = remorse::loadTypeFlags(*typesPath); + const auto globs = remorse::loadGlobObjects(*globPath); + assert(shapeTypes && shapeTypes->size() > 1 && globs); + const auto stagedItems = remorse::stageFixedMapItems(*fixedMap); + assert(stagedItems); + const auto startingEgg = remorse::findTeleportEgg(*stagedItems, *shapeTypes, 0x1e); + assert(startingEgg && startingEgg->itemNumber >= 0x100); + assert((startingEgg->data.quality & 0xff) == 0x1e && startingEgg->data.frame == 1); + assert(startingEgg->data.x > 0 && startingEgg->data.y > 0); + assert(startingEgg->data.x * 2 == fixedMap->entries[startingEgg->recordIndex].x); + assert(startingEgg->data.y * 2 == fixedMap->entries[startingEgg->recordIndex].y); + const auto obstacles = remorse::collectMapCollisionBodies(*fixedMap, *shapeTypes, *globs); + const remorse::WorldPoint spawn{startingEgg->data.x * 2, startingEgg->data.y * 2, startingEgg->data.z}; + options.maxWidth = 320; + options.maxHeight = 200; + options.viewCenter = spawn; + const auto startingScene = remorse::renderMapPreview(*root, options); + assert(startingScene && startingScene->paintedItemCount > 0); + remorse::LiveFixedMapItems liveSceneItems(*stagedItems); + auto cachedRenderer = remorse::loadMapSceneRenderer(*root, 1); + assert(cachedRenderer); + const auto liveBefore = cachedRenderer->render(options, &liveSceneItems); + const auto samePixels = [](const auto& left, const auto& right) { + return left.size() == right.size() && std::equal(left.begin(), left.end(), right.begin(), + [](const auto& lhs, const auto& rhs) { + return lhs.red == rhs.red && lhs.green == rhs.green && lhs.blue == rhs.blue; + }); + }; + assert(liveBefore && samePixels(liveBefore->pixels, startingScene->pixels)); + const remorse::s32 redrawRadius = static_cast( + options.maxWidth + options.maxHeight * 2 + 512); + options.worldRect = remorse::WorldRect{spawn.x - redrawRadius, spawn.y - redrawRadius, + spawn.x + redrawRadius, spawn.y + redrawRadius}; + const auto boundedScene = cachedRenderer->render(options, &liveSceneItems); + assert(boundedScene && samePixels(boundedScene->pixels, liveBefore->pixels)); + options.worldRect.reset(); + const auto nearEgg = std::find_if(stagedItems->begin(), stagedItems->end(), [&](const auto& item) { + return item.data.shape < shapeTypes->size() && + (*shapeTypes)[item.data.shape].family == 3 && item.data.quality != 0 && + std::any_of(globs->begin(), globs->end(), [&](const auto& object) { + return object.index == item.data.quality; + }); + }); + assert(nearEgg != stagedItems->end()); + { + options.viewCenter = remorse::WorldPoint{ + nearEgg->data.x * 2, nearEgg->data.y * 2, nearEgg->data.z}; + const auto unhatchedScene = cachedRenderer->render(options, &liveSceneItems); + assert(unhatchedScene); + const auto glob = std::find_if(globs->begin(), globs->end(), [&](const auto& object) { + return object.index == nearEgg->data.quality; + }); + assert(glob != globs->end()); + const auto childIds = liveSceneItems.hatchGlobEgg(nearEgg->itemNumber, *glob, *shapeTypes); + assert(childIds && childIds->size() == glob->entries.size()); + const auto hatchedScene = cachedRenderer->render(options, &liveSceneItems); + assert(hatchedScene && samePixels(hatchedScene->pixels, unhatchedScene->pixels)); + for (const remorse::u16 childId : *childIds) { + const auto* child = liveSceneItems.findItem(childId); + assert(child && liveSceneItems.moveItem(childId, + static_cast(child->data.x + 512), + static_cast(child->data.y + 512), child->data.z)); + } + const auto movedScene = cachedRenderer->render(options, &liveSceneItems); + assert(movedScene && !samePixels(movedScene->pixels, hatchedScene->pixels)); + } + options.viewCenter = spawn; + auto visibleItem = std::find_if(stagedItems->begin(), stagedItems->end(), [&](const auto& item) { + if (item.data.shape >= shapeTypes->size() || (item.data.flags & 0x10) != 0 || + ((*shapeTypes)[item.data.shape].flags & 0x400) != 0) { + return false; + } + const auto family = (*shapeTypes)[item.data.shape].family; + if (family == 3 || family == 4 || family == 7 || family == 8) { + return false; + } + return true; + }); + assert(visibleItem != stagedItems->end()); + assert(liveSceneItems.moveItem(visibleItem->itemNumber, startingEgg->data.x, + startingEgg->data.y, 16)); + const auto liveAfter = cachedRenderer->render(options, &liveSceneItems); + assert(liveAfter && !samePixels(liveAfter->pixels, liveBefore->pixels)); + assert(!cachedRenderer->decodedFrames.empty()); + const auto actor = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]); + bool canLeaveSpawn = false; + for (const auto [deltaX, deltaY] : {std::pair{32, 0}, {0, 32}, {-32, 0}, {0, -32}}) { + canLeaveSpawn |= remorse::canMoveCollisionBody(actor, + {spawn.x + deltaX, spawn.y + deltaY, spawn.z}, obstacles); + } + assert(canLeaveSpawn); return 0; } From 08a907f322afb1d5a63148f30d04d43feefef80c Mon Sep 17 00:00:00 2001 From: Maddo Date: Sun, 4 Oct 2026 18:11:16 +0200 Subject: [PATCH 08/14] Add comprehensive tests for ProcessKernel and Usecode VM functionality - Implemented tests for ProcessKernel in entity_dispatch_entry_tests.cpp, covering process creation, termination, and scanning of runnable processes. - Enhanced fixed_map_tests.cpp with tests for item allocation and release, including recycling of items and process ownership. - Expanded flex_archive_tests.cpp to validate the interaction between usecode events and item processes, ensuring correct behavior of spawned tasks and rendering. - Introduced usecode_vm_tests.cpp to thoroughly test the UsecodeInterpreterState and UsecodeProcessTask functionalities, including stack operations and opcode services. --- ...entity-vm-runtime-owner-resource-layout.md | 10 + docs/remorse-windows-rebuild-roadmap.md | 32 +- rebuild/remorse/CMakeLists.txt | 12 +- .../include/remorse/entity_dispatch_entry.h | 9 + rebuild/remorse/include/remorse/fixed_map.h | 15 + rebuild/remorse/include/remorse/usecode_vm.h | 99 +++- rebuild/remorse/src/entity_dispatch_entry.cpp | 62 ++- rebuild/remorse/src/fixed_map.cpp | 254 ++++++++- rebuild/remorse/src/usecode_vm.cpp | 503 +++++++++++++++++- rebuild/remorse/src/windowed_game_main.cpp | 242 ++++++++- .../tests/entity_dispatch_entry_tests.cpp | 37 ++ rebuild/remorse/tests/fixed_map_tests.cpp | 60 +++ rebuild/remorse/tests/flex_archive_tests.cpp | 349 ++++++++++++ rebuild/remorse/tests/usecode_vm_tests.cpp | 134 +++++ 14 files changed, 1784 insertions(+), 34 deletions(-) create mode 100644 rebuild/remorse/tests/usecode_vm_tests.cpp diff --git a/docs/entity-vm-runtime-owner-resource-layout.md b/docs/entity-vm-runtime-owner-resource-layout.md index aa1927c..7f3b30c 100644 --- a/docs/entity-vm-runtime-owner-resource-layout.md +++ b/docs/entity-vm-runtime-owner-resource-layout.md @@ -52,7 +52,9 @@ Live runtime-helper classification added during the 2026-04-05 MCP-upgrade pass: - seeds the sentinel-filled chunk-state array used by later lazy chunk loads - `1420:19fd Remorse::EntityVmRuntime::EnsureSlotChunkLoaded` - lazily materializes one indexed owner chunk for a slot into runtime memory + - obtains the chunk through `UProcess_1420_0000` using the owner-row offset/size, materializes it through the owner-resource helper, and caches the returned far pointer in the slot entry - marks the chunk present through the slot-local state arrays and updates the runtime-wide budget counters + - `GetSlotChunkPtrAtOffset` (`1420:1d72`) returns that allocator-produced pointer plus the caller's intra-chunk offset; it does not expose a stable file/archive address - `1420:1f24 entity_vm_runtime_apply_to_matching_owner_rows` - runtime-owned iterator over the owner list, used both for broad cleanup and for filtered slot/category work - `1420:2040 entity_vm_slot_entry_create_or_clear` @@ -123,10 +125,18 @@ Current layout claims that matter for class lifting: - `+0x36` embeds the mini-VM/state object - `+0xd6/+0xd8` hold the seeded source/control stream lane - `+0x102` is the backward-growing local payload/buffer lane +- `+0x11f` stores the context-relative offset of the saved parameter-stack pointer when `ucparam` is non-null and mode flags are nonzero +- `+0x121` stores the low mode-flags byte, and `+0x122` is initialized to zero by `CreateFromSlotIndex` - `+0x10c/+0x10e` store a derived low/high pair reused by save/load - `+0x117/+0x119` cache the owner-linked source pair - `+0x123` behaves as a busy or active flag in the sync/dispatch path +`CreateFromSlotIndex` initializes the embedded interpreter, copies the item parameter only when mode flags are nonzero, copies optional `ucparam` bytes into the backward-growing stack, then reserves four bytes for the prior stack pointer when both are present. The host VM models this order and the `+0x11f` relative offset, but does not synthesize the original segment:offset pointer or map the runtime-owned code and owner buffers yet. + +The embedded interpreter initializes its stack limit to 199 bytes; the host bootstrap rejects a combined initial item/context payload and saved-pointer slot above that limit. + +The host opcode service currently maps segment `0` to the task's item-memory buffer through `UsecodeProcessTask::readMappedItemWord`; all other segments are rejected. This centralizes the existing fixture behavior but is not a general segmented address space. + Current caution: - context dispatch semantics are still active work, so this object should be modeled around lifecycle and data ownership first, not around final method names for every opcode-facing helper. diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index aa7898e..499ec8b 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -27,7 +27,7 @@ The immediate target is a fresh game on retail map 1 at the original starting te 5. **Real interaction:** implement one reachable map-1 usecode event through the original item find/grab, VM dispatch, and resulting world-state mutation. Demonstrate a repeatable before/input/after trace and visible effect; a script lookup or release-request counter is not an interaction. 6. **Acceptance:** launch the normal Windows executable with retail data, start map 1 at egg `0x1e`, move and interact without a diagnostic shortcut, and verify on-screen state plus a deterministic integration test. Keep absent combat, audio, menus, persistence, and broader missions listed as limitations, not silently simulated features. -Progress: the map-1 fixed-map test identifies one family-8/frame-1 item with low quality byte `0x1e` (the teleporter's item-search predicate); startup centers on that egg instead of the map-bounds midpoint. The live item owner reserves avatar item `1` with defaults from `NPC_Init` (`10e8:000c`) and applies the coordinate/map write from `NPC_Teleport` (`10e8:29f2`). Win32 directional events now pass through the kernel keyboard queue to a registered controller entry; an owned `AnimPrimitiveProcess` advances the avatar item on 40 Hz host ticks. A cached map renderer redraws snapshots of mutable map items in source sorter order on a worker thread, while the avatar pose is still drawn in a separate screen overlay. Fast-area GLOB eggs now hatch into numbered live children using the `1098:039c` placement/status rules; the renderer replaces a hatched egg's preview expansion with those items. The interpreter's initial stack and 31-entry code-address stack are compiled and tested against exported `1418:00e8/0244/0000`; opcode execution is not implemented. These are partial translations of steps 1-4, **not completed steps**: `Game_Start` (`1020:0000`), teleporter scheduling, complete item cache, controller actions beyond directional movement, original camera/draw-list integration, and USECODE execution remain open. Collision is approximate; no visible scripted world mutation or deterministic end-to-end interaction acceptance exists. Steps 5-6 remain open. +Progress: the map-1 fixed-map test identifies one family-8/frame-1 item with low quality byte `0x1e` (the teleporter's item-search predicate); startup centers on that egg instead of the map-bounds midpoint. The live item owner reserves avatar item `1` with defaults from `NPC_Init` (`10e8:000c`) and applies the coordinate/map write from `NPC_Teleport` (`10e8:29f2`). Win32 directional events now pass through the kernel keyboard queue to a registered controller entry; an owned `AnimPrimitiveProcess` advances the avatar item on 40 Hz host ticks. A cached map renderer redraws snapshots of mutable map items in source sorter order on a worker thread, while the avatar pose is still drawn in a separate screen overlay. Fast-area GLOB eggs now hatch into numbered live children using the `1098:039c` placement/status rules; the renderer replaces a hatched egg's preview expansion with those items. The interpreter's initial stack and 31-entry code-address stack are compiled and tested against exported `1418:00e8/0244/0000`; the host VM executes a tested opcode subset and task lifecycle. Retail-data tests execute `CARD_NS` spawning `SWITCH` and the `BOX_NS` timer chain through a changed live item frame and rendered scene. The Windows host queues a selected retail release-event body from the item-process callback and reports its task state, but this remains diagnostic: `F` host-selects the nearby item, the original `Item_Grab`/`Usecode_ItemCallEvent` dispatch is not ported, and `E` starts a nearest eligible use event through host selection. The task bytecode offset is now named `usecodeEventBytecodeOffset` (`0x0e`) and verified against raw `CARD_NS`, `BOX_NS`, and `RECHFLNS` bodies: each has a 14-byte prefix followed by opcode `0x0b`; Ghidra shows the selected event chunk pointer is passed with intra-chunk offset zero. The prefix field meanings remain untyped. These are partial translations of steps 1-5, **not completed milestones**: `Game_Start` (`1020:0000`), teleporter scheduling, complete item cache, controller actions beyond directional movement, original camera/draw-list integration, and original USECODE event dispatch remain open. Collision is approximate; no normal-input, end-to-end interaction acceptance exists. Steps 5-6 remain open. Retail map-1 probing at the starting egg found four children after fast-area GLOB hatching and no eligible `use` script on those children; no direct fixed-map item within 1,024 staged units has an eligible event body. The nearest direct `use` items are panel/card objects roughly 8,800 staged units away. Their event bodies delegate to `TRIGGER.slot_20` or `SWITCH.slot_21`, which require additional VM, timer, selector, and world-state services. A renderer regression confirms that moving hatched children changes live scene pixels, but this is not script execution or proof that those distant interactions are reachable through the current collision path. @@ -69,7 +69,7 @@ Current scaffold files: - `rebuild/remorse/include/remorse/type_flags.h`: typed `TYPEFLAG.DAT` shape-family and flag decoder. - `rebuild/remorse/src/combat_tactics.cpp`: parses tactic names, four block offsets, and bytecode payloads from `COMBAT.DAT` entries. - `rebuild/remorse/src/collision.cpp`: builds conservative solid volumes from fixed-map records and expanded glob children, then sweeps the player footpad against them. -- `rebuild/remorse/src/entity_dispatch_entry.cpp`: partial source translation of process lifecycle, the `11d0:0255` scan, `Process_Sleep`/`Unlink`, the 0x42-byte Stand constructor fields, `StandProcess::Run` (`1100:0359`), a kernel-owned SystemTimer constructor/counter (`11c0:0000/00f8`), and partial Keyboard/KeyDaemon registration. The harness executes the NPC decision tree through host services and delivers timer events explicitly; real NPC data, timer interrupts/rescheduling, original keyboard queue/player input, and complete game tick remain unported. +- `rebuild/remorse/src/entity_dispatch_entry.cpp`: partial source translation of process lifecycle, the `11d0:0255` scan and `11d0:0445/19b5` post-scan group selection, `Process_Sleep`/`Unlink`, the 0x42-byte Stand constructor fields, `StandProcess::Run` (`1100:0359`), a kernel-owned SystemTimer constructor/counter (`11c0:0000/00f8`), and partial Keyboard/KeyDaemon registration. The harness executes the NPC decision tree through host services and delivers timer events explicitly; real NPC data, timer interrupts/rescheduling, original keyboard queue/player input, and complete game tick remain unported. - `rebuild/remorse/src/file_system.cpp`: repository/retail data-root discovery using modern `std::filesystem`. - `rebuild/remorse/src/flex_archive.cpp`: loader for count-at-`0x54`, table-at-`0x80` FLEX archives. - `rebuild/remorse/src/fixed_map.cpp`: loader for `FIXED.DAT` map tables and scaled fixed-map item coordinates. @@ -97,7 +97,7 @@ Current scaffold files: - `rebuild/remorse/tests/type_flags_tests.cpp`: checks `STATIC/TYPEFLAG.DAT` parses 2,048 shape records and includes glob-family records. - `rebuild/remorse/tools/import_export_slice.py`: stages one exported function folder into `rebuild/remorse/imported/` for manual cleanup review. -This is not the game yet. It is a buildable diagnostic host with a source-backed itemless process lifecycle, partial scheduler scan/group selection, owned Stand process layout, and recovered Stand `Run`/NPC decision and timer-counter branches. It does not have the original NPC service data, DOS timer delivery, keyboard event queue, or game loop. +This is not the game yet. It is a buildable diagnostic host with a source-backed itemless process lifecycle, one-pass scheduler scan and post-scan active-group selection, owned Stand process layout, and recovered Stand `Run`/NPC decision and timer-counter branches. It does not have the original NPC service data, DOS timer delivery, keyboard event queue, or game loop. ## Why The Export Does Not Compile Yet @@ -318,8 +318,8 @@ First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a | `Kernel_ClearProcessSomethingAndName` (`11d0:1972`), `Kernel_11d0_1dcc` | Slot pointer/size/name clear and deferred cleanup for IDs >= 3 translated; ID reuse exercised | Live cleanup scans from ID 3, requires `+0x1a == 0`, clears the slot, frees the entry, and decrements terminated count. The clear helper itself does not decrement live process count. Other scheduler cleanup paths and process destructor dispatch remain unported. | | `FUN_11d0_0255` (`11d0:0255`) | Normal-process scan and timer wake translated; harness callback invokes compiled Stand `Run`, tests cover sleep/wake and scheduler gates | Live `11d0:02b4-03ac`: skip terminated, process sleep via `11e0:0379`, clear `Proc_Syncing` for one pass, skip nonzero `+0x24/+0x26`, `Proc_Waiting`, and off-group entries unless daemon or group 30/31; set current ID around vtable run call. Host receives an explicit timer tick, uses the original strict `start+duration < tick` wake comparison, and recognizes Stand's verified no-op completion slot (`1100:0fe3`); other completion targets remain unsupported. Immediate timer/keyboard interrupts, early-stop/group advance/table-maintenance tails, and general vtable dispatch remain unported. | | `Kernel_11d0_19b5` (`11d0:19b5`), `Kernel_11d0_0445` (`11d0:0445`) | Active-group writer and empty-group highest-ordinary-group selection translated; invoked after diagnostic scans in harness/window, CTest checks change flag and groups 30/31 exclusion | Exported globals initialize active group `DS:39c9` to 1 and pending byte `DS:39a2` to 0. Writer marks pending only when group changes; selector scans all occupied process slots (including terminated entries until cleanup), ignores groups 30/31 for the maximum, then clears pending. Host rejects invalid group IDs and uses explicit group counters; original group-table allocation, mid-scan early stop, and runtime traces remain unported. | -| `Item_CreateProcess` (`10a0:0020`), `ItemProcess_Run` (`10a0:0078`), `Item_Release` (`10a0:2a06`) | Owned 0x32-byte item process constructed and advanced by the scheduler from a staged retail map record; release-request/termination/presence cleanup checked over two ticks, harness/window invoke the same path | Live disassembly confirms function-table root `0x102f`, item number at `+0x04`, event type `0xf1` at `+0x06`, then `Item_Release` followed unconditionally by the vtable terminate slot. The compiled release boundary now passes mask `0x200` and `UC_Release` ordinal `9` to the host callback, both asserted by CTest. It still does not execute the USECODE event. Instance is a diagnostic, not an original `Item_Grab` trigger; original item process child teardown and general vtable dispatch remain unported. | -| `Item_GetUsecodeClassId` (`1420:0dc5`), `Usecode_ItemCallEvent` (`1420:0e3a`) | Class selection and owner-row event-mask gate translated into `remorse_core`; retail and synthetic CTest checks, harness and window release-request lookup | The item selector chooses regular shape, NPC number plus startup NPC base `0x800` (unless status bit 1), or unknown-egg quality plus startup base `0x900`. FLEX entry 1 supplies 13-byte owner rows (size callback `1220:01bb`, materialization callback `1240:02a8`). The window retains TYPEFLAG families and EUSECODE data to check release eligibility and report body availability, without creating a VM context or executing the body. Classless map items are normal; the first staged map-1 item (shape 16) has no matching class. | +| `Item_CreateProcess` (`10a0:0020`), `ItemProcess_Run` (`10a0:0078`), `Item_Release` (`10a0:2a06`) | Owned 0x32-byte item process constructed and advanced by the scheduler from a staged retail map record; release request, event-body queueing, task state, termination, and presence cleanup are exercised by the diagnostic host | Live disassembly confirms function-table root `0x102f`, item number at `+0x04`, event type `0xf1` at `+0x06`, then `Item_Release` followed unconditionally by the vtable terminate slot. The host callback receives mask `0x200` and `UC_Release` ordinal `9`, resolves an eligible retail body, and queues it in the host VM task registry. Only supported opcodes/services execute; unsupported paths halt the task. This remains a diagnostic trigger, not the original `Item_Grab` path; child teardown and general vtable dispatch remain unported. | +| `Item_GetUsecodeClassId` (`1420:0dc5`), `Usecode_ItemCallEvent` (`1420:0e3a`) | Class selection and owner-row event-mask gate translated into `remorse_core`; retail and synthetic CTest checks, harness/window release selection, and host task execution | The item selector chooses regular shape, NPC number plus startup NPC base `0x800` (unless status bit 1), or unknown-egg quality plus startup base `0x900`. FLEX entry 1 supplies 13-byte owner rows (size callback `1220:01bb`, materialization callback `1240:02a8`). The diagnostic host resolves the selected release body and runs it through the subset VM. This is not the original `Usecode_ItemCallEvent`/`CreateFromSlotIndex` dispatcher or `EntityVmContext`; classless map items remain valid, and the first staged map-1 item (shape 16) has no matching class. | | `Process_Sleep` (`11e0:0320`), `EntityDispatchEntry::Unlink` (`11e0:0353`) | Flag and 32-bit timer writes/clear translated; exact byte offsets and wake deadline tested | Live sleep ORs `0x1000` at `+0x18`, snapshots timer into `+0x0a/+0x0c`, writes duration to `+0x0e/+0x10`; unlink clears the flag and those four words. Host receives a tick instead of reading the original timer-process pointer. | | `NPCActionProcess::Create` (`1100:0000`), `StandProcess::CreateProcess` (`1100:02ed`) | Owned 0x42-byte Stand entry registered and run in harness; constructor fields, item number, and presence-bit transitions tested | Live chain stamps `+0x16 |= 0x300`, clears derived words `+0x32..0x3e`, stores NPC number at `+0x40`, ORs `0x101` at `+0x32`, sets Stand vtable `0x1f0f`, process name `Stand`, and event `0x258`. Host marks the item bit on registration and refreshes it after terminating a zero-child-state Stand, following `Item_MarkProcessPresent`/`Item_RefreshProcessPresenceFlag` (`11d0:3e0b/3e7f`). Item animation/cache reset, nonempty child-list destruction, and real NPC item ownership remain unported. | | `NPC_StartBehaviorInField0x8IfCanSeeControlledNPC` (`1100:026e`), `StandProcess::Run` (`1100:0359`) | Compiled NPC decision/Stand run branches; tests cover off-screen sleep, visible behavior start, already-current sleep, and strict wake | Live `1100:0274-02e9` reads NPC number from `+0x40`, tests entirely-on-screen, nonzero field-8 activity, not-current activity `0x71`, can-see-controlled-NPC, and starts the next behavior; `1100:035c-0382` sleeps 60 on false. `1478:1f0f` starts with far `Run` pointer `1100:0359`. Host services supply visibility/activity/item effects and timer tick; no real NPC item, general vtable resolver, or binary trace parity. | @@ -333,7 +333,7 @@ Live Ghidra MCP decompilation and disassembly have resolved local stack ABI, sch The exported free-item path can issue `0x2400` from its `0x100..0x27ff` range, and a staged synthetic map reaches that ID; retail map 1 remains inside the kernel lookup limit. Exported `SetSourceType` (`11e0:01b6`) calls the presence/type-table writers without a visible range guard. This does not prove how a live run handles such an ID: preserve the host guard and investigate the original allocation/use path before allowing out-of-range process ownership. -`FUN_11d0_31cf` (`11d0:31cf`) is a caller of the scheduler scan at `11d0:0255`. Its one-pass prefix snapshots the registered SystemTimer, scans runnable processes, then invokes an optional callback. The host now compiles and calls that ordered pass from the harness and Windows diagnostic, returning elapsed ticks after the callback; tests verify that a timer event delivered by the callback cannot wake a process in the already-started scan. The original infinite loop, interval wait, DOS interrupt delivery, and live group-transition trace remain unported. +`FUN_11d0_31cf` (`11d0:31cf`) is a caller of the scheduler scan at `11d0:0255`. Its one-pass prefix snapshots the registered SystemTimer, scans runnable processes, then invokes an optional callback. The host compiles and calls that ordered pass from the harness and Windows diagnostic, returning elapsed ticks after the callback; tests verify that a timer event delivered by the callback cannot wake a process in the already-started scan. At the end of the scan, the host now reproduces the source group transition: if the active group has no live processes, select the highest occupied group except 30/31, set the pending flag only on change, then clear it as `Kernel_11d0_0445` (`11d0:0445`) does. The original infinite loop, interval wait, DOS interrupt delivery, `11d0:04cd` resize maintenance, and runtime group-transition parity remain unported or unverified. The first search-side dependency is compiled and tested in isolation: `ItemFind_10c0_14c9` (`10c0:14c9`) classifies a candidate as match type 1 (candidate Z equals origin top) or type 2 (candidate top equals origin Z), using TYPEFLAG-derived footprint widths and height, with type 1 taking priority. The host receives staged item fields and decoded shape metadata explicitly. This is **not** a complete port of `ItemFind_StartSearchAroundItem` (`10c0:0f73`) or the `10c0:1637` iterator; live item state and general loop-script evaluation remain absent, and the classifier is not used to select a window item. @@ -345,10 +345,14 @@ Contained placement has a separate source-derived diagnostic: for nonzero maps, The bounded staged dispatcher can now issue those actions against the host process kernel. `Process_GetProcessForItemAndType` (`11d0:13a4`) scans live slots from 3, ignores terminated entries, and supports item/type wildcards; the host mirrors those rules. `Item_Hurl` (`1038:12a6`) reuses an existing type-`0x203` gravity process and adds velocity, or creates a `0x42`-byte process (`1038:0395`) with zero velocity, gravity 2, and a 20-tick sleep for a fall request. Tests cover both branches, duplicate item-process requests, strict wake, ownership and ID-limit rejection, and teardown/reuse. Staged dispatch rejects any out-of-range action before starting; the Windows `F` key is still a separate release fixture. A host-owned `LiveFixedMapItems` copy now supports ID lookup, bounded position changes, and `Item_Grab` dispatch against current item positions; the window owns this copy for nearby-item lookup. `Item_LegalMoveToPointWithCollisionInfo` (`10a0:1841`) calls `Item_Grab` before `AreaSearch_CollideMove` on its successful path; `moveApprovedItem` preserves that ordering once a caller has approved the move, and tests distinguish old-position requests from post-move search. Synthetic move/dispatch and retail-map ownership tests pass. This is not the original item cache, does not yet provide a legal-move collision event or update rendered sprites, and does not include live contained items. `runUnobstructedGravity` moves an owned item and advances/sleeps its owned process in the nonzero-vertical-speed branch after explicit caller-supplied approval of the full pre-sweep target. A refused or missing sweep makes no mutation on that path. On the zero-Z horizontal path, it requests `Item_Grab` before sweep approval, so a refused sweep may still leave a process request. The stationary zero-speed fall search, collision responses, live fast-area state, and automatic scheduler tick remain unported. The original `AreaSearch_SweepTestItem` (`10e0:1151`) forwards into `AreaSearch_SweepTestPt` (`10e0:0b39`); the host has bounded fast-area and item-iterator gates but not resolved collision points. Runtime ID and search-order parity remain unverified and are not a current gate. -The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied item IDs can also be inserted at a block head. The host free-ID allocator uses the source `0x100..0x27ff` range, skips staged direct and contained records, and fails without mutation when exhausted. The window reserves staged contained IDs and retains their parent links; placing one in the world clears its parent while its children remain linked. Synthetic nested/exhaustion and retail-map tests pass. This does not yet implement returning freed IDs to the list, live inventory/container transfers, fast-area status, or viewport side effects. +The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied item IDs can also be inserted at a block head. The host free-ID allocator uses the source `0x100..0x27ff` range, skips staged direct and contained records, and fails without mutation when exhausted. The window reserves staged contained IDs and retains their parent links; placing one in the world clears its parent while its children remain linked. Synthetic nested/exhaustion and retail-map tests pass. A follow-up item-cache slice now models returned IDs as a LIFO free list (`ItemCache_10a8_1aef`, `10a8:1aef`), initial contained sibling order (`ItemCache_PopToEnd`, `10a8:2533`), family-6 head insertion (`ItemCache_PopToContainer`, `10a8:2369`), and transfers that preserve nested children. Release refuses active-process ownership, nonempty items, hatched glob eggs, and IDs above the `0x23ff` process-table boundary. Synthetic tests cover sibling ordering, cycle rejection, process ownership, and free-ID reuse. Runtime parity, cache-status/fast-area effects, family-7 transfer, and viewport writes remain unverified. The supported horizontal `GravityProcess_Run` path now issues `Item_Grab` at the old item position when Z speed is zero and X/Y speed is nonzero, then asks the injected sweep to approve movement. As in the source order, a refused sweep can leave a newly requested item process behind while the item stays put. The earlier no-mutation guarantee for a refused sweep applies only to the nonzero-Z path, which does not issue that request. This callback-based unobstructed runner does not handle the stationary zero-speed fall search or collision response; a caller must provide shapes, group counts, and sweep approval. +Live `Item_SetQIfContainerType` (`10a0:0f78`) writes a family-6/7 parent quality field to its first contained child, and `ItemCache_10a8_1949` (`10a8:1949`) advances that field when unlinking the head. The host now mirrors the head ID during initial contained staging and runtime head insertion/removal, including nested parents; family-6 and family-7 staging and the quality transitions have focused regressions. This does not port the `Item_PopToEnd` free-item-to-tail path or the separate item-status/fast-area effects. + +Live Ghidra decompilation shows that vertical `GravityProcess_Run` impacts use sweep mode 4, then `AreaSearch_CollideMove`, and branch on `Item_IsCurrentControlledNPC` plus masks from the separate `g_itemStatus` table. Those branches include callback/termination paths and controlled-item rebound behavior using `RandomVal`; collision movement can also create hit/got-hit storage processes. `FixedMapEntry::flags` is not a verified substitute for `g_itemStatus` and already carries modeled fixed-item flags such as flip. Keep vertical response, status/cache writes, and collision-event creation deferred until those runtime states and side effects are represented. + The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. The source's `World_MapBlockInFastArea` (`10a8:0000`) rotated block predicate and eight-corner start/destination footprint gate are testable with an explicit fast-area range. `World_CalcFastAreaLimits` (`10a8:0048`) now supplies the source sum ±5 / difference ±3 block window from a world center. The window refreshes a player-centered host range after movement and dispatches any owned gravity processes through its timed scheduler; it still does not create gravity entries or repaint moved map items in the static preview. The sweep's item-iterator rectangle and live candidate query follow inclusive X/Y filtering and Y-then-X block order. The per-item sweep uses 16-unit X/Y extents, 8-unit Z extents with the source zero-height fallback, and six axis-face tests that report one-unit-before-contact points and failed-direction bits. A read-only live collector combines those tests with candidate order, shape solidity and flip flags. The host selects a solid hit in source order when any axis is strictly closer, retains the earlier hit on a tie, and accumulates direction bits across contacts. Damaging-only face contacts are recorded in candidate order without blocking the resolved point. With an explicitly enabled floor-gap limit, the host also identifies the closest solid support beneath the destination footprint for source limits 0 and 9; this support metadata does not change the destination. The resolved sweep now reports fast-area failure at the original point with direction bits 1/2 and clamps out-of-range Z with bit 4; the gravity runner conservatively rejects these unsupported responses before mutation. `runResolvedGravity` moves an owned item to a solid-hit point after its strict process wake, damps and reverses horizontal speed on collision, and sleeps the process again. `scanResolvedGravity` dispatches this bounded runner through the host scheduler; tests verify a wall impact, a later move away, and no repeat within the same tick. The remaining gaps are vertical collision response, item status/cache writes, collision events, stationary fall search, and an actual window gravity producer and moving-item renderer. Original runtime parity remains unverified. Original DOS debugging and runtime verification are postponed indefinitely until requested again. The DOSBox-X debugger session has been stopped; do not treat a live trace as a prerequisite for the source-port work below. Keep unverified parity claims labeled as such. @@ -356,12 +360,12 @@ Original DOS debugging and runtime verification are postponed indefinitely until Next source-port checks, in call-chain order: 1. Keep the `0x23ff/0x2400` process item boundary until source-derived allocation limits support changing it; do not infer a wider live table from staged map IDs. -2. Port the remaining scheduler interval/group transitions behind host timing boundaries using static code evidence, with runtime parity explicitly deferred. -3. Port free-ID return/reuse and live container transfers while preserving contained parent/child links and process ownership. -4. Carry source sweep mode flags through callers and implement vertical collision responses for supported item/status branches; bounds and fast-area failures are now explicit but conservatively rejected by gravity. +2. Keep the original scheduler wait behind a host timing boundary. `11d0:04cd/0575` reallocates and copies three segmented process tables; defer a direct port until the host's vector-backed slot/capacity semantics are explicitly modeled. Post-scan active-group selection is now statically translated, with runtime parity explicitly deferred. +3. Verify and extend the host free-ID/container slice against live runtime traces; synthetic tests now cover family-7 contained-record staging and family-6 runtime insertion, but item-cache status/fast-area effects and the `Item_PopToEnd` runtime append path remain unverified. +4. Port an explicit item-status model before implementing vertical gravity responses; bounds and fast-area failures are explicit but conservatively rejected, and live gravity branches also require controlled-NPC identity and random-response behavior. 5. Extend scheduled gravity with item status/cache writes and collision events; add a real window gravity producer and dynamic item renderer before claiming visible gameplay movement. 6. Connect the approved-move `Item_Grab` path to a ported `Item_LegalMoveToPointWithCollisionInfo` sweep and item-cache lifecycle, without changing the separate Windows `F` release fixture. -7. Lift `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`) and its interpreter initialization; keep release event-body lookup diagnostic until the VM executes it. +7. Lift `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`) and the `Inter_1418_0244` interpreter/context layout, replacing host task setup with the original event-frame and parameter semantics; extend opcode/intrinsic coverage before claiming event parity. ## First Interactive Windows Game Shell @@ -391,7 +395,7 @@ The Windows diagnostic no longer schedules the first staged item on scene load. The `Item_Grab` creation branch applies the verified `FUN_11d0_3f95(itemNumber, -0xf)` item-cache flag-1 check to staged item flags before a type-2 process request. Live disassembly at `10a0:29c5-29e3` confirms the branch; a separate search-result type 1 calls `Item_Fall`, whose hurl request now creates or merges a sleeping gravity entry in the host. The Ghidra export's zero-initialized `npcno` loop is a decompiler artifact, not evidence that the search never iterates. The window still uses proximity instead of original `ItemFind`, does not model live item-cache mutations or gravity movement, and must not treat process-presence bookkeeping as the checked item flag. -The first Phase 6 resource slice is compiled into `remorse_core`: a bounded `EUSECODE.FLX` class/name/event-body reader follows the owner-loaded `classId + 2`, 13-byte name-table, `+0x14` six-byte row, and `codeBase + relativeOffset - 1` body rules verified in `docs/raw-000a-000d.md`. Retail tests confirm `EVENT` (`class 0x361`, slot `0x0a`, code base `0xd4`, body length `0x1fd6`) and `RECHFLNS` (`class 0x138`, release slot `9`, body length `102`, owner mask `0x200`). The harness resolves and reports the `EVENT` body (8,150 bytes). `Item_GetUsecodeClassId` selects a class from item identity and startup class bases; `Usecode_ItemCallEvent` gates on the owner row. Map-1 tests cover both its classless first staged item and at least one actual staged item with an eligible release body. The window applies both checks to the nearest staged item's release request and labels eligible bytes NOT RUN. This remains lookup, not bytecode interpretation or a live owner-loaded item system. The next original call is `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`, mode 2, selected class/slot and a four-byte parameter), which initializes an interpreter through `Inter_1418_0244` (`1418:0244`) and `Interpreter_1418_00e8` (`1418:00e8`). No context, interpreter dispatch, or item side effect is ported. Even the short `RECHFLNS` release event branches through item surface-weight logic and `FREE.slot_33`; an isolated opcode stub would not complete that call chain. +The first Phase 6 resource slice is compiled into `remorse_core`: a bounded `EUSECODE.FLX` class/name/event-body reader follows the owner-loaded `classId + 2`, 13-byte name-table, `+0x14` six-byte row, and `codeBase + relativeOffset - 1` body rules verified in `docs/raw-000a-000d.md`. Retail tests confirm `EVENT` (`class 0x361`, slot `0x0a`, code base `0xd4`, body length `0x1fd6`) and `RECHFLNS` (`class 0x138`, release slot `9`, body length `102`, owner mask `0x200`). Raw extracted `CARD_NS`, `BOX_NS`, and `RECHFLNS` bodies confirm a 14-byte metadata prefix followed by the first opcode at offset `0x0e`; its exact field meanings remain unknown. The named offset is shared by the host task runner and tested against these retail bodies. Retail integration tests execute `CARD_NS` spawning `SWITCH` and `BOX_NS` through timer yields to a changed item frame and rendered scene. The Windows diagnostic release callback also resolves and queues an eligible body, but this is host-side dispatch and task initialization, not `Usecode_ItemCallEvent` or `EntityVmContext::CreateFromSlotIndex`. The interpreter covers only a subset of opcodes/services, and unsupported operations halt tasks; original context memory, far-pointer execution, general event dispatch, and runtime parity remain open. The recovered `CreateFromSlotIndex` call selects a class/slot and passes a four-byte parameter into `Inter_1418_0244` (`1418:0244`) and `Interpreter_1418_00e8` (`1418:00e8`). Even the short `RECHFLNS` release event branches through item surface-weight logic and `FREE.slot_33`; the current host service table does not complete that path. The walk/run modifier choice is the isolated branch from `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. The same selector's Num Lock-off directional scan branch (`0x47/48/49/4b/4d/4f/50/51`) is now compiled in the controls helper, regression-tested across all eight mappings, and called by Win32 movement polling. Win32 still supplies modifiers and held-key state; NPC state, weapon-dependent actions, original keyboard events, and the remainder of the controller selector are not ported. Retail ANIM.DAT regression checks retain the signed reverse steps in the decoder while testing the host-only forward movement filter across all four affected walk directions. @@ -708,8 +712,8 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat 4. Port the real timer process and NPC service implementations, then scheduler keyboard, active-group advancement, remaining sleep-completion dispatch and table-maintenance tails; compare deterministic process-order/state traces before connecting the Windows window. 5. Replace DOS file and memory APIs encountered by the ported chain with narrow host adapters; validate far-pointer/layout conversions against live evidence. 6. Port original movement and AreaSearch/collision behavior before promoting the host actor movement from stand-in to gameplay code. -7. Port `CreateFromSlotIndex` and the `Inter_1418_0244`/`Interpreter_1418_00e8` initialization path with checked stack, parameter, and program-counter state, then execute one selected retail event through original opcode handlers and verify its item/process side effects before connecting it to the window. Continue through original item/draw-list output, save/load, audio, and frontend chains for playable mission progression. +7. Port `EnsureSlotChunkLoaded` (`1420:19fd`), its `UProcess_1420_0000` allocation and owner-helper materialization path, and the slot cache's far-pointer ownership. Then extend the host's segment-0 item-memory mapping to that runtime-owned code region, finish `CreateFromSlotIndex`/`Inter_1418_0244` context wiring, and execute one selected retail event with verified item/process side effects before connecting it to the window. Continue through original item/draw-list output, save/load, audio, and frontend chains for playable mission progression. ## Current Bottom Line -The project has a buildable diagnostic host, retail resource loaders, partial original scheduler scan, and owned Stand and item-process entries. The Windows diagnostic registry now runs an item process bound to a staged retail map record, selects any eligible release-script bytes, and runs a Stand entry under the host tick. This is a map-derived process integration checkpoint, **not** a complete Phase 4 or gameplay milestone: original item cache/block IDs, actual release USECODE execution, real NPC ownership/services, nonempty-child teardown, DOS timer/keyboard interrupts, full scheduler, original startup/player chain, renderer item output, and interactions remain unported. The next measures of gameplay progress are an executed retail event with a verified live item mutation and a real item-linked Stand/NPC instance on the original call chain with state trace parity. +The project has a buildable diagnostic host, retail resource loaders, partial original scheduler scan, and owned Stand and item-process entries. The Windows diagnostic registry runs an item process bound to a staged retail map record, queues an eligible release body into the subset VM, and runs a Stand entry under the host tick. Retail tests demonstrate script-driven item-frame mutation. The `E` selector now iterates bounded, source-order candidates from `itemGrabSearchCandidates` (the modeled `Item_Grab` query) and queues the first candidate with an eligible `use` body, replacing its earlier nearest-distance choice. This is source-derived candidate selection, not original interaction dispatch: the window still constructs the item identity and queues the event body directly, and no visible before/input/after interaction is proven. The partial `CreateFromSlotIndex` slice writes the verified slot index (`+0x32`), value offset (`+0x34`), owner-source far pointer (`+0x11b`), mode byte (`+0x121`), and cleared parameter/active fields (`+0x11f/+0x122`) into the allocated 0x124-byte context. The VM bootstrap now copies the item parameter only for nonzero mode flags, then optional context bytes, reserves the four-byte saved-stack-pointer slot, and records the context-relative parameter offset; focused tests cover the ordering and zero-mode case. Real segment:offset pointer mapping, runtime code/owner-resource addresses, and embedded interpreter-context execution remain unported. `F` remains a separate release diagnostic. The original item cache/block IDs, full `Item_Grab`/`Usecode_ItemCallEvent`/`CreateFromSlotIndex` chain, real NPC ownership/services, nonempty-child teardown, DOS timer/keyboard interrupts, full scheduler, original startup/player chain, and renderer integration remain open. This is not a playable-game milestone; the next measure is mapping far addresses into the host VM and using them to execute one selected retail event through original context dispatch. diff --git a/rebuild/remorse/CMakeLists.txt b/rebuild/remorse/CMakeLists.txt index 9a37b5c..119a7d5 100644 --- a/rebuild/remorse/CMakeLists.txt +++ b/rebuild/remorse/CMakeLists.txt @@ -157,13 +157,21 @@ target_link_libraries(combat_tactics_tests PRIVATE remorse_core) add_test(NAME combat_tactics_tests COMMAND combat_tactics_tests) +add_executable(usecode_vm_tests + tests/usecode_vm_tests.cpp +) + +target_link_libraries(usecode_vm_tests PRIVATE remorse_core) + +add_test(NAME usecode_vm_tests COMMAND usecode_vm_tests) + add_library(remorse_test_crash_setup OBJECT tests/test_crash_setup.cpp) target_link_libraries(remorse_test_crash_setup PRIVATE remorse_core) foreach(test_target IN ITEMS entity_dispatch_entry_tests file_system_tests palette_tests flex_archive_tests fixed_map_tests glob_archive_tests type_flags_tests shape_archive_tests map_renderer_tests map_sorter_tests isometric_controls_tests - animation_archive_tests collision_tests combat_tactics_tests) + animation_archive_tests collision_tests combat_tactics_tests usecode_vm_tests) target_sources(${test_target} PRIVATE $) endforeach() @@ -175,6 +183,7 @@ if(MSVC) target_compile_options(isometric_controls_tests PRIVATE /W4 /permissive-) target_compile_options(animation_archive_tests PRIVATE /W4 /permissive-) target_compile_options(collision_tests PRIVATE /W4 /permissive-) + target_compile_options(usecode_vm_tests PRIVATE /W4 /permissive-) target_compile_options(remorse_map_preview PRIVATE /W4 /permissive-) if(WIN32) target_compile_options(remorse_game PRIVATE /W4 /permissive-) @@ -196,6 +205,7 @@ else() target_compile_options(isometric_controls_tests PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(animation_archive_tests PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(collision_tests PRIVATE -Wall -Wextra -Wpedantic) + target_compile_options(usecode_vm_tests PRIVATE -Wall -Wextra -Wpedantic) target_compile_options(remorse_map_preview PRIVATE -Wall -Wextra -Wpedantic) if(WIN32) target_compile_options(remorse_game PRIVATE -Wall -Wextra -Wpedantic) diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index b993856..7e06929 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -56,6 +56,11 @@ struct AnimPrimitiveProcessEntry { u8 extra[0x29]; } CR_PACKED; +struct EntityVmContextProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0xf2]; +} CR_PACKED; + struct KeyEvent { u8 character; u8 scanCode; @@ -80,6 +85,7 @@ static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size m static_assert(sizeof(KeyDaemonProcessEntry) == 0x40, "KeyDaemonProcessEntry size must match allocation evidence"); static_assert(sizeof(ControllerProcessEntry) == 0x40, "ControllerProcessEntry size must match allocation evidence"); static_assert(sizeof(AnimPrimitiveProcessEntry) == 0x5b, "AnimPrimitiveProcessEntry size must match allocation evidence"); +static_assert(sizeof(EntityVmContextProcessEntry) == 0x124, "EntityVmContext process size must match allocation evidence"); static_assert(sizeof(KeyEvent) == 0x0c, "KeyEvent size must match keyboard event copy"); struct NpcBehaviorServices { @@ -115,6 +121,7 @@ public: ControllerProcessEntry* createControllerProcess(u8 activeGroup, u16 (&groupCounts)[32]); AnimPrimitiveProcessEntry* createAnimPrimitiveProcess(u8 activeGroup, u16 itemNumber, u16 animationNumber, u8 direction, const AnimationClip& clip, u16 (&groupCounts)[32]); + EntityVmContextProcessEntry* createUsecodeProcess(u8 activeGroup, u16 (&groupCounts)[32]); bool startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items, const AnimationClip& clip, u8 frameSkip = 0); std::optional advanceGroundedAnimPrimitive(u16 processId, LiveFixedMapItems& items, @@ -141,6 +148,7 @@ public: void clearTerminatedProcesses(); void setProcessSourceType(EntityDispatchEntryBase& entry, u16 itemNumber); void setProcessEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType); + bool setProcessInfo(u16 processId, u16 eventType, u16 sourceItem); void scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, u32 timerTick = 0); u32 runTimedSchedulerPass(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, void (*afterScan)(void*) = nullptr, void* afterContext = nullptr); @@ -166,6 +174,7 @@ private: std::vector> ownedStandProcesses_; std::vector> ownedGravityProcesses_; std::vector> ownedAnimPrimitiveProcesses_; + std::vector> ownedUsecodeProcesses_; std::unique_ptr systemTimerProcess_; std::unique_ptr keyboardProcess_; std::unique_ptr keyDaemonProcess_; diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index 3b7bd42..ca1ecc7 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -41,6 +41,7 @@ struct StagedContainedFixedMapItem { u16 itemNumber = 0; u16 parentItemNumber = 0; std::size_t recordIndex = 0; + FixedMapEntry data; }; struct ItemFindArea { @@ -119,13 +120,19 @@ public: const NpcAnimationState* findNpcAnimation(u16 itemNumber) const; NpcAnimationState* editNpcAnimation(u16 itemNumber); u16 containedParent(u16 itemNumber) const; + std::vector containedChildren(u16 parentItemNumber) const; std::optional nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const; std::optional> sweepCandidateIds(const WorldRect& area, u16 excludedItemNumber) const; std::optional allocateItem(StagedFixedMapItem item); bool insertItem(StagedFixedMapItem item); + bool moveItemIntoContainer(u16 itemNumber, u16 containerItemNumber, + const std::vector& shapes); + bool moveContainedItemToWorld(u16 itemNumber, u16 x, u16 y, u8 z); + bool releaseItem(u16 itemNumber, const ProcessKernel& kernel); std::optional> hatchGlobEgg(u16 eggItemNumber, const GlobObject& glob, const std::vector& shapes); bool isGlobHatched(u16 eggItemNumber) const; + bool setItemFrame(u16 itemNumber, u8 frame); bool moveItem(u16 itemNumber, u16 x, u16 y, u8 z); std::optional> grabItem(u16 itemNumber, const std::vector& shapes, ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick) const; @@ -134,12 +141,20 @@ public: u16 (&groupCounts)[32], u32 timerTick); private: + bool unlinkContainedItem(u16 itemNumber); + void refreshContainerQuality(u16 parentItemNumber); + bool insertContainedItemAtHead(u16 parentItemNumber, u16 itemNumber); std::vector items_; std::optional avatar_; std::vector npcAnimations_; std::vector allocatedIds_; std::vector hatchedGlobIds_; std::vector parentById_; + std::vector> containedItemData_; + std::vector containedNextById_; + std::vector containedHeadById_; + std::vector containedTailById_; + std::vector freeItemIds_; u16 nextFreeItemNumber_ = 0x100; }; diff --git a/rebuild/remorse/include/remorse/usecode_vm.h b/rebuild/remorse/include/remorse/usecode_vm.h index 1d59e25..7dbdd45 100644 --- a/rebuild/remorse/include/remorse/usecode_vm.h +++ b/rebuild/remorse/include/remorse/usecode_vm.h @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include @@ -9,22 +11,115 @@ namespace remorse { +constexpr std::size_t usecodeEventBytecodeOffset = 14; +constexpr std::size_t usecodeFrameBaseOffset = 0x40; +constexpr std::size_t usecodeInterpreterStackLimit = 199; +constexpr std::size_t usecodeContextProcessSize = 0x124; +constexpr std::size_t usecodeContextSlotIndexOffset = 0x32; +constexpr std::size_t usecodeContextValueAddOffset = 0x34; +constexpr std::size_t usecodeContextOwnerSourceOffset = 0x11b; +constexpr std::size_t usecodeContextParameterOffset = 0x11f; +constexpr std::size_t usecodeContextModeFlagsOffset = 0x121; +constexpr std::size_t usecodeContextActiveFlagOffset = 0x122; + struct UsecodeCallFrame { u16 offset = 0; u16 segment = 0; }; +enum class UsecodeStepResult { + Advanced, + Returned, + SetInfo, + Spawned, + Yielded, + UnsupportedOpcode, + InvalidInstruction, + StackFault, + ServiceRejected +}; + +struct UsecodeOpcodeServices { + std::function(u16 offset, u16 segment)> readFarWord; + std::function setInfo; + std::function processCount; + std::function(u16 classId, u16 eventSlot, u8 extraArgumentBytes, + u8 itemArgumentSize, u16 itemArgument, const u8* extraArguments)> spawn; + std::function(u16 ordinal, u8 argumentBytes, const u8* arguments)> callIntrinsic; + std::function currentProcessId; +}; + class UsecodeInterpreterState { public: static std::optional initialize( - const std::vector& itemParameter); + const std::vector& itemParameter, const std::vector& contextParameter = {}, + u16 modeFlags = 0); bool pushCodeAddress(u16 offset, u16 segment); + bool pushWord(u16 value); + bool pushDword(u32 value); + std::optional popWord(); + std::optional popDword(); + UsecodeStepResult step(const std::vector& code, std::size_t& programCounter, + std::vector& frame, const UsecodeOpcodeServices& services); + std::optional> lastSetInfoOperands; std::array valueStack{}; std::size_t stackTop = 0xcc; + std::size_t stackHighWatermark = 0xcc; std::array callFrames{}; u16 callFrameCount = 0; - u16 stackLimit = 199; + u16 stackLimit = usecodeInterpreterStackLimit; + u16 temporaryWord = 0; + std::optional contextParameterOffset; + bool processExcluded = false; + u16 currentProcessId = 0; + u16 impliedProcessId = 0; +}; + +struct UsecodeProcessTask { + static std::optional create(u16 processId, u16 classId, + u16 eventSlot, u16 sourceItem, std::vector code, + u8 itemArgumentSize = 2, std::vector extraArguments = {}, + std::vector contextParameter = {}); + UsecodeStepResult step(const UsecodeOpcodeServices& services); + + u16 processId = 0; + u16 classId = 0; + u16 eventSlot = 0; + u16 sourceItem = 0; + std::vector code; + std::vector frame; + std::vector itemMemory; + UsecodeInterpreterState interpreter; + std::size_t programCounter = usecodeEventBytecodeOffset; + bool halted = false; + bool timerDelayProcess = false; + u32 wakeTick = 0; + + std::optional readMappedItemWord(FarPtr16 address) const; +}; + +struct UsecodeContextFactoryFields { + FarPtr16 ownerSource{}; + u16 modeFlags = 0; + u16 slotIndex = 0; + u16 valueAddOffset = 0; + u16 parameterOffset = 0; +}; + +bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize, + const UsecodeContextFactoryFields& fields); + +class UsecodeTaskRegistry { +public: + bool add(UsecodeProcessTask task); + UsecodeProcessTask* find(u16 processId); + const UsecodeProcessTask* find(u16 processId) const; + bool remove(u16 processId); + std::size_t size() const noexcept { return tasks_.size(); } + +private: + std::map tasks_; }; } // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index 829e83a..e5724ea 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -170,6 +170,37 @@ AnimPrimitiveProcessEntry* ProcessKernel::createAnimPrimitiveProcess(u8 activeGr return result; } +EntityVmContextProcessEntry* ProcessKernel::createUsecodeProcess(u8 activeGroup, + u16 (&groupCounts)[32]) +{ + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + if (std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + processes_.reserve(processes_.size() + 30); + allocationSizes_.reserve(allocationSizes_.size() + 30); + processNames_.reserve(processNames_.size() + 30); + } + ownedUsecodeProcesses_.reserve(ownedUsecodeProcesses_.size() + 1); + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + setLastAllocationSize(sizeof(EntityVmContextProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "Usecode"; + if (syncEnabled_) { + EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_); + if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) { + current->bytes[0x18] |= 0x04; + } + if (id > currentProcessId_) { + process->base.bytes[0x16] |= 0x40; + } + } + EntityVmContextProcessEntry* result = process.get(); + ownedUsecodeProcesses_.push_back(std::move(process)); + return result; +} + bool ProcessKernel::startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items, const AnimationClip& clip, u8 frameSkip) { @@ -645,6 +676,12 @@ void ProcessKernel::releaseOwnedProcess(u16 id) ownedAnimPrimitiveProcesses_.erase(animation); return; } + const auto usecode = std::find_if(ownedUsecodeProcesses_.begin(), ownedUsecodeProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (usecode != ownedUsecodeProcesses_.end()) { + ownedUsecodeProcesses_.erase(usecode); + return; + } const auto owned = std::find_if(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; }); ownedProcesses_.erase(owned); @@ -681,13 +718,17 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) const bool ownedItemProcess = readLe16(*entry, 0x00) == ItemProcess::vtableOffset && std::any_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; }); + const bool ownedUsecodeProcess = std::any_of(ownedUsecodeProcesses_.begin(), + ownedUsecodeProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess && - !ownedGravityProcess && !ownedAnimationProcess || id < 3 || + !ownedGravityProcess && !ownedAnimationProcess && !ownedUsecodeProcess || id < 3 || readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 || readLe16(*entry, 0x2e) != 0 || readLe16(*entry, 0x30) != 0)) { throw std::logic_error("item process child cleanup is not ported"); } if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && !ownedAnimationProcess && + !ownedUsecodeProcess && std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; })) { throw std::logic_error("external process ownership is not ported"); @@ -793,6 +834,18 @@ void ProcessKernel::setProcessEventTypeChecked(EntityDispatchEntryBase& entry, u } } +bool ProcessKernel::setProcessInfo(u16 processId, u16 eventType, u16 sourceItem) +{ + EntityDispatchEntryBase* entry = processAt(processId); + if (entry == nullptr || processId < 3 || (entry->bytes[0x16] & 0x08) != 0 || + eventType > 0x0fff || sourceItem > maxTrackedItemNumber) { + return false; + } + setProcessEventTypeChecked(*entry, eventType); + setProcessSourceType(*entry, sourceItem); + return true; +} + void ProcessKernel::clearTerminatedProcesses() { for (std::size_t id = 3; id < processes_.size() && terminatedProcessCount_ != 0; ++id) { @@ -852,6 +905,13 @@ void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDisp } clearTerminatedProcesses(); } + u16 activeGroupCounts[32]{}; + for (const EntityDispatchEntryBase* entry : processes_) { + if (entry != nullptr && (readLe16(*entry, 0x16) & 0x08) == 0) { + ++activeGroupCounts[entry->bytes[0x08] & 0x1f]; + } + } + refreshActiveGroup(activeGroupCounts); } catch (...) { syncEnabled_ = priorSyncEnabled; currentProcessId_ = priorProcessId; diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index c13b6fa..e419081 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -209,7 +209,7 @@ std::optional> stageContainedFixedMapIt return std::nullopt; } parentById[itemNumber] = currentParent; - contained.push_back({itemNumber, currentParent, index}); + contained.push_back({itemNumber, currentParent, index, record}); } else { currentParent = 0; currentDepth = 0; @@ -433,8 +433,11 @@ std::optional> dispatchStagedItemGrab(const StagedFixedMapItem& LiveFixedMapItems::LiveFixedMapItems(std::vector items, std::vector containedItems) - : items_(std::move(items)), allocatedIds_(0x2800), hatchedGlobIds_(0x2800), parentById_(0x2800) + : items_(std::move(items)), allocatedIds_(0x2800), hatchedGlobIds_(0x2800), parentById_(0x2800), + containedItemData_(0x2800), containedNextById_(0x2800), containedHeadById_(0x2800), + containedTailById_(0x2800) { + freeItemIds_.reserve(allocatedIds_.size()); if (!buildStagedItemBlockChains(items_)) { throw std::invalid_argument("invalid live item IDs or coordinates"); } @@ -454,6 +457,15 @@ LiveFixedMapItems::LiveFixedMapItems(std::vector items, throw std::invalid_argument("invalid contained parent ID"); } parentById_[contained.itemNumber] = contained.parentItemNumber; + containedItemData_[contained.itemNumber] = contained.data; + const u16 previousTail = containedTailById_[contained.parentItemNumber]; + if (previousTail == 0) { + containedHeadById_[contained.parentItemNumber] = contained.itemNumber; + } else { + containedNextById_[previousTail] = contained.itemNumber; + } + containedTailById_[contained.parentItemNumber] = contained.itemNumber; + refreshContainerQuality(contained.parentItemNumber); } } @@ -513,6 +525,97 @@ u16 LiveFixedMapItems::containedParent(u16 itemNumber) const return itemNumber < parentById_.size() ? parentById_[itemNumber] : 0; } +std::vector LiveFixedMapItems::containedChildren(u16 parentItemNumber) const +{ + std::vector children; + if (parentItemNumber >= containedHeadById_.size()) { + return children; + } + for (u16 itemNumber = containedHeadById_[parentItemNumber]; itemNumber != 0; + itemNumber = containedNextById_[itemNumber]) { + if (itemNumber >= containedNextById_.size() || + parentById_[itemNumber] != parentItemNumber || children.size() >= containedNextById_.size()) { + children.clear(); + return children; + } + children.push_back(itemNumber); + } + return children; +} + +bool LiveFixedMapItems::unlinkContainedItem(u16 itemNumber) +{ + if (itemNumber >= parentById_.size()) { + return false; + } + const u16 parentItemNumber = parentById_[itemNumber]; + if (parentItemNumber == 0 || parentItemNumber >= containedHeadById_.size()) { + return false; + } + u16 previousItemNumber = 0; + u16 currentItemNumber = containedHeadById_[parentItemNumber]; + while (currentItemNumber != 0 && currentItemNumber != itemNumber) { + if (currentItemNumber >= containedNextById_.size()) { + return false; + } + previousItemNumber = currentItemNumber; + currentItemNumber = containedNextById_[currentItemNumber]; + } + if (currentItemNumber != itemNumber) { + return false; + } + const u16 nextItemNumber = containedNextById_[itemNumber]; + if (previousItemNumber == 0) { + containedHeadById_[parentItemNumber] = nextItemNumber; + } else { + containedNextById_[previousItemNumber] = nextItemNumber; + } + if (containedTailById_[parentItemNumber] == itemNumber) { + containedTailById_[parentItemNumber] = previousItemNumber; + } + if (containedHeadById_[parentItemNumber] == 0) { + containedTailById_[parentItemNumber] = 0; + } + parentById_[itemNumber] = 0; + containedNextById_[itemNumber] = 0; + refreshContainerQuality(parentItemNumber); + return true; +} + +void LiveFixedMapItems::refreshContainerQuality(u16 parentItemNumber) +{ + if (parentItemNumber >= containedHeadById_.size()) { + return; + } + const u16 firstChild = containedHeadById_[parentItemNumber]; + const auto worldParent = std::find_if(items_.begin(), items_.end(), [parentItemNumber](const auto& item) { + return item.itemNumber == parentItemNumber; + }); + if (worldParent != items_.end()) { + worldParent->data.quality = firstChild; + } else if (containedItemData_[parentItemNumber]) { + containedItemData_[parentItemNumber]->quality = firstChild; + } +} + +bool LiveFixedMapItems::insertContainedItemAtHead(u16 parentItemNumber, u16 itemNumber) +{ + if (parentItemNumber >= allocatedIds_.size() || itemNumber >= allocatedIds_.size() || + parentItemNumber == itemNumber || !allocatedIds_[parentItemNumber] || !allocatedIds_[itemNumber] || + parentById_[itemNumber] != 0 || containedNextById_[itemNumber] != 0) { + return false; + } + const u16 previousHead = containedHeadById_[parentItemNumber]; + containedNextById_[itemNumber] = previousHead; + containedHeadById_[parentItemNumber] = itemNumber; + if (previousHead == 0) { + containedTailById_[parentItemNumber] = itemNumber; + } + parentById_[itemNumber] = parentItemNumber; + refreshContainerQuality(parentItemNumber); + return true; +} + std::optional LiveFixedMapItems::nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const { @@ -552,6 +655,19 @@ std::optional LiveFixedMapItems::allocateItem(StagedFixedMapItem item) if (item.data.x > 0x7fff || item.data.y > 0x7fff) { return std::nullopt; } + while (!freeItemIds_.empty()) { + const u16 itemNumber = freeItemIds_.back(); + freeItemIds_.pop_back(); + if (itemNumber >= allocatedIds_.size() || allocatedIds_[itemNumber]) { + continue; + } + item.itemNumber = itemNumber; + if (insertItem(item)) { + return itemNumber; + } + freeItemIds_.push_back(itemNumber); + return std::nullopt; + } while (nextFreeItemNumber_ < allocatedIds_.size() && allocatedIds_[nextFreeItemNumber_]) { ++nextFreeItemNumber_; } @@ -565,14 +681,132 @@ std::optional LiveFixedMapItems::allocateItem(StagedFixedMapItem item) bool LiveFixedMapItems::insertItem(StagedFixedMapItem item) { - if (item.itemNumber < 0x100 || item.itemNumber >= 0x2800 || item.data.x > 0x7fff || + if (item.itemNumber < 0x100 || item.itemNumber >= allocatedIds_.size() || item.data.x > 0x7fff || item.data.y > 0x7fff || findItem(item.itemNumber)) { return false; } + const bool wasContained = parentById_[item.itemNumber] != 0 && + containedItemData_[item.itemNumber].has_value(); + if (parentById_[item.itemNumber] != 0 && !wasContained) { + return false; + } + if (allocatedIds_[item.itemNumber] != wasContained) { + return false; + } + if (wasContained) { + item.data.flags &= static_cast(~8u); + } item.data.z = std::min(item.data.z, 0xfa); items_.push_back(item); + if (wasContained && !unlinkContainedItem(item.itemNumber)) { + items_.pop_back(); + return false; + } + containedItemData_[item.itemNumber].reset(); + const auto freeItem = std::find(freeItemIds_.begin(), freeItemIds_.end(), item.itemNumber); + if (freeItem != freeItemIds_.end()) { + freeItemIds_.erase(freeItem); + } allocatedIds_[item.itemNumber] = true; - parentById_[item.itemNumber] = 0; + return true; +} + +bool LiveFixedMapItems::moveItemIntoContainer(u16 itemNumber, u16 containerItemNumber, + const std::vector& shapes) +{ + if (itemNumber < 0x100 || containerItemNumber < 0x100 || itemNumber == containerItemNumber || + itemNumber >= allocatedIds_.size() || containerItemNumber >= allocatedIds_.size() || + !allocatedIds_[itemNumber] || !allocatedIds_[containerItemNumber]) { + return false; + } + const auto worldContainer = std::find_if(items_.begin(), items_.end(), [containerItemNumber](const auto& item) { + return item.itemNumber == containerItemNumber; + }); + const FixedMapEntry* containerData = worldContainer == items_.end() + ? (containedItemData_[containerItemNumber] ? &*containedItemData_[containerItemNumber] : nullptr) + : &worldContainer->data; + if (containerData == nullptr || containerData->shape >= shapes.size() || + shapes[containerData->shape].family != 6) { + return false; + } + if (parentById_[itemNumber] == containerItemNumber) { + return true; + } + for (u16 ancestor = containerItemNumber; ancestor != 0; ancestor = parentById_[ancestor]) { + if (ancestor == itemNumber || ancestor >= parentById_.size()) { + return false; + } + } + + const auto worldItem = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& item) { + return item.itemNumber == itemNumber; + }); + const bool wasContained = worldItem == items_.end() && parentById_[itemNumber] != 0 && + containedItemData_[itemNumber].has_value(); + if (worldItem == items_.end() && !wasContained) { + return false; + } + FixedMapEntry itemData = worldItem == items_.end() ? *containedItemData_[itemNumber] : worldItem->data; + if (wasContained && !unlinkContainedItem(itemNumber)) { + return false; + } + if (worldItem != items_.end()) { + items_.erase(worldItem); + } + itemData.flags |= 8; + containedItemData_[itemNumber] = itemData; + return insertContainedItemAtHead(containerItemNumber, itemNumber); +} + +bool LiveFixedMapItems::moveContainedItemToWorld(u16 itemNumber, u16 x, u16 y, u8 z) +{ + if (itemNumber < 0x100 || itemNumber >= allocatedIds_.size() || !allocatedIds_[itemNumber] || + parentById_[itemNumber] == 0 || !containedItemData_[itemNumber] || x > 0x7fff || y > 0x7fff) { + return false; + } + FixedMapEntry itemData = *containedItemData_[itemNumber]; + itemData.x = x; + itemData.y = y; + itemData.z = std::min(z, 0xfa); + itemData.flags &= static_cast(~9u); + items_.push_back({itemNumber, static_cast(-1), itemData}); + if (!unlinkContainedItem(itemNumber)) { + items_.pop_back(); + return false; + } + containedItemData_[itemNumber].reset(); + return true; +} + +bool LiveFixedMapItems::releaseItem(u16 itemNumber, const ProcessKernel& kernel) +{ + if (itemNumber < 0x100 || itemNumber > ProcessKernel::maxTrackedItemNumber || + itemNumber >= allocatedIds_.size() || !allocatedIds_[itemNumber] || + kernel.itemHasProcess(itemNumber) || containedHeadById_[itemNumber] != 0 || + hatchedGlobIds_[itemNumber]) { + return false; + } + const auto worldItem = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& item) { + return item.itemNumber == itemNumber; + }); + const bool wasContained = worldItem == items_.end() && parentById_[itemNumber] != 0 && + containedItemData_[itemNumber].has_value(); + if (worldItem == items_.end() && !wasContained) { + return false; + } + if (wasContained && !unlinkContainedItem(itemNumber)) { + return false; + } + if (worldItem != items_.end()) { + items_.erase(worldItem); + } + containedItemData_[itemNumber].reset(); + containedNextById_[itemNumber] = 0; + containedHeadById_[itemNumber] = 0; + containedTailById_[itemNumber] = 0; + parentById_[itemNumber] = 0; + allocatedIds_[itemNumber] = false; + freeItemIds_.push_back(itemNumber); return true; } @@ -620,6 +854,18 @@ bool LiveFixedMapItems::isGlobHatched(u16 eggItemNumber) const return eggItemNumber < hatchedGlobIds_.size() && hatchedGlobIds_[eggItemNumber]; } +bool LiveFixedMapItems::setItemFrame(u16 itemNumber, u8 frame) +{ + const auto item = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& candidate) { + return candidate.itemNumber == itemNumber; + }); + if (item == items_.end()) { + return false; + } + item->data.frame = frame; + return true; +} + bool LiveFixedMapItems::moveItem(u16 itemNumber, u16 x, u16 y, u8 z) { if (x > 0x7fff || y > 0x7fff) { diff --git a/rebuild/remorse/src/usecode_vm.cpp b/rebuild/remorse/src/usecode_vm.cpp index 86d6d81..3abfc65 100644 --- a/rebuild/remorse/src/usecode_vm.cpp +++ b/rebuild/remorse/src/usecode_vm.cpp @@ -5,15 +5,28 @@ namespace remorse { std::optional UsecodeInterpreterState::initialize( - const std::vector& itemParameter) + const std::vector& itemParameter, const std::vector& contextParameter, + u16 modeFlags) { - if (itemParameter.size() > 0xcc) { + const bool saveStackPointer = !contextParameter.empty() && modeFlags != 0; + const std::size_t savedPointerBytes = saveStackPointer ? sizeof(FarPtr16) : 0; + if (itemParameter.size() > usecodeInterpreterStackLimit || + contextParameter.size() > usecodeInterpreterStackLimit - itemParameter.size() || + savedPointerBytes > usecodeInterpreterStackLimit - itemParameter.size() - contextParameter.size()) { return std::nullopt; } UsecodeInterpreterState state; - state.stackTop -= itemParameter.size(); - std::copy(itemParameter.begin(), itemParameter.end(), - state.valueStack.begin() + state.stackTop); + state.stackHighWatermark = state.valueStack.size(); + const auto pushBytes = [&state](const std::vector& bytes) { + state.stackTop -= bytes.size(); + std::copy(bytes.begin(), bytes.end(), state.valueStack.begin() + state.stackTop); + }; + pushBytes(itemParameter); + pushBytes(contextParameter); + if (saveStackPointer) { + state.stackTop -= savedPointerBytes; + state.contextParameterOffset = static_cast(state.stackTop - sizeof(u16) * 2); + } return state; } @@ -26,4 +39,484 @@ bool UsecodeInterpreterState::pushCodeAddress(u16 offset, u16 segment) return true; } +bool UsecodeInterpreterState::pushWord(u16 value) +{ + if (stackTop < sizeof(value)) { + return false; + } + stackTop -= sizeof(value); + valueStack[stackTop] = static_cast(value); + valueStack[stackTop + 1] = static_cast(value >> 8); + return true; +} + +bool UsecodeInterpreterState::pushDword(u32 value) +{ + if (stackTop < sizeof(value)) { + return false; + } + stackTop -= sizeof(value); + for (std::size_t index = 0; index < sizeof(value); ++index) { + valueStack[stackTop + index] = static_cast(value >> (index * 8)); + } + return true; +} + +std::optional UsecodeInterpreterState::popWord() +{ + if (stackTop > stackHighWatermark || stackHighWatermark > valueStack.size() || + stackHighWatermark - stackTop < sizeof(u16)) { + return std::nullopt; + } + const u16 value = static_cast(valueStack[stackTop] | + (static_cast(valueStack[stackTop + 1]) << 8)); + stackTop += sizeof(u16); + return value; +} + +std::optional UsecodeInterpreterState::popDword() +{ + if (stackTop > stackHighWatermark || stackHighWatermark > valueStack.size() || + stackHighWatermark - stackTop < sizeof(u32)) { + return std::nullopt; + } + u32 value = 0; + for (std::size_t index = 0; index < sizeof(value); ++index) { + value |= static_cast(valueStack[stackTop + index]) << (index * 8); + } + stackTop += sizeof(value); + return value; +} + +UsecodeStepResult UsecodeInterpreterState::step(const std::vector& code, + std::size_t& programCounter, std::vector& frame, + const UsecodeOpcodeServices& services) +{ + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const u8 opcode = code[programCounter++]; + if (opcode == 0x00 || opcode == 0x01 || opcode == 0x3e || opcode == 0x3f) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const auto rawOffset = static_cast(code[programCounter]); + const auto localIndex = static_cast(usecodeFrameBaseOffset) + rawOffset; + const bool byteOperation = opcode == 0x00 || opcode == 0x3e; + const std::size_t valueSize = byteOperation ? sizeof(u8) : sizeof(u16); + if (localIndex < 0 || static_cast(localIndex) > frame.size() || + frame.size() - static_cast(localIndex) < valueSize) { + return UsecodeStepResult::InvalidInstruction; + } + const std::size_t localOffset = static_cast(localIndex); + if (opcode == 0x3e) { + ++programCounter; + return pushWord(frame[localOffset]) + ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x3f) { + ++programCounter; + const u16 value = static_cast(frame[localOffset] | + (static_cast(frame[localOffset + 1]) << 8)); + return pushWord(value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (stackTop > valueStack.size() - sizeof(u16)) { + return UsecodeStepResult::StackFault; + } + ++programCounter; + if (opcode == 0x00) { + frame[localOffset] = valueStack[stackTop]; + } else { + frame[localOffset] = valueStack[stackTop]; + frame[localOffset + 1] = valueStack[stackTop + 1]; + } + return popWord() ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x0a) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const auto value = static_cast(static_cast(code[programCounter++])); + return pushWord(static_cast(value)) + ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x0c) { + if (code.size() - programCounter < sizeof(u32)) { + return UsecodeStepResult::InvalidInstruction; + } + u32 value = 0; + for (std::size_t index = 0; index < sizeof(value); ++index) { + value |= static_cast(code[programCounter + index]) << (index * 8); + } + programCounter += sizeof(value); + return pushDword(value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x0f) { + const std::size_t instructionStart = programCounter - 1; + if (code.size() - programCounter < 3) { + return UsecodeStepResult::InvalidInstruction; + } + const u8 argumentBytes = code[programCounter]; + const u16 ordinal = static_cast(code[programCounter + 1] | + (static_cast(code[programCounter + 2]) << 8)); + if (!services.callIntrinsic) { + programCounter = instructionStart; + return UsecodeStepResult::UnsupportedOpcode; + } + if (argumentBytes > valueStack.size() - stackTop) { + return UsecodeStepResult::StackFault; + } + const auto result = services.callIntrinsic(ordinal, argumentBytes, + valueStack.data() + stackTop); + if (!result) { + programCounter = instructionStart; + return UsecodeStepResult::ServiceRejected; + } + programCounter += 3; + temporaryWord = *result; + return UsecodeStepResult::Advanced; + } + if (opcode == 0x14 || opcode == 0x1c || opcode == 0x24 || opcode == 0x2a || + opcode == 0x2c || opcode == 0x36) { + const auto right = popWord(); + const auto left = right ? popWord() : std::nullopt; + if (!left || !right) { + if (right) pushWord(*right); + return UsecodeStepResult::StackFault; + } + u16 result = 0; + if (opcode == 0x14) result = static_cast(*left + *right); + else if (opcode == 0x1c) result = static_cast(*left - *right); + else if (opcode == 0x24) result = static_cast(*left == *right); + else if (opcode == 0x2a) result = static_cast(*left <= *right); + else if (opcode == 0x2c) result = static_cast(static_cast(*left) > static_cast(*right)); + else result = static_cast(*left != *right); + return pushWord(result) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x51 || opcode == 0x52) { + if (code.size() - programCounter < sizeof(u16)) { + return UsecodeStepResult::InvalidInstruction; + } + const s16 relativeOffset = static_cast(code[programCounter] | + (static_cast(code[programCounter + 1]) << 8)); + programCounter += sizeof(u16); + bool shouldJump = opcode == 0x52; + if (opcode == 0x51) { + const auto condition = popWord(); + if (!condition) { + return UsecodeStepResult::StackFault; + } + shouldJump = *condition == 0; + } + if (shouldJump) { + const auto target = static_cast(programCounter) + relativeOffset; + if (target < 0 || static_cast(target) >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + programCounter = static_cast(target); + } + return UsecodeStepResult::Advanced; + } + if (opcode == 0x53) { + return UsecodeStepResult::Yielded; + } + if (opcode == 0x54) { + if (code.size() - programCounter < 2) { + return UsecodeStepResult::InvalidInstruction; + } + programCounter += 2; + if (!popWord()) { + return UsecodeStepResult::StackFault; + } + if (temporaryWord >= 3) { + impliedProcessId = temporaryWord; + } + return UsecodeStepResult::Advanced; + } + if (opcode == 0x59) { + if (!services.currentProcessId) { + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; + } + currentProcessId = services.currentProcessId(); + return pushWord(currentProcessId) + ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x5d) { + return pushWord(static_cast(temporaryWord)) + ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x6e) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const auto adjustment = static_cast(code[programCounter++]); + const auto newTop = static_cast(stackTop) - adjustment; + if (newTop < 0 || newTop > static_cast(valueStack.size())) { + return UsecodeStepResult::StackFault; + } + stackTop = static_cast(newTop); + stackHighWatermark = std::max(stackHighWatermark, stackTop); + return UsecodeStepResult::Advanced; + } + if (opcode == 0x12) { + const auto value = popWord(); + if (!value) { + return UsecodeStepResult::StackFault; + } + temporaryWord = *value; + return UsecodeStepResult::Advanced; + } + if (opcode == 0x0b) { + if (code.size() - programCounter < 2) { + return UsecodeStepResult::InvalidInstruction; + } + const u16 value = static_cast(code[programCounter] | + (static_cast(code[programCounter + 1]) << 8)); + programCounter += 2; + return pushWord(value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x40) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const std::size_t localOffset = code[programCounter++]; + const std::size_t localIndex = usecodeFrameBaseOffset + localOffset; + if (localIndex > frame.size() || frame.size() - localIndex < sizeof(u32)) { + return UsecodeStepResult::InvalidInstruction; + } + const u32 value = static_cast(frame[localIndex]) | + (static_cast(frame[localIndex + 1]) << 8) | + (static_cast(frame[localIndex + 2]) << 16) | + (static_cast(frame[localIndex + 3]) << 24); + return pushDword(value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x4c) { + if (programCounter >= code.size()) { + return UsecodeStepResult::InvalidInstruction; + } + const std::size_t valueSize = code[programCounter++]; + if (valueSize != sizeof(u16)) { + return UsecodeStepResult::UnsupportedOpcode; + } + const auto address = popDword(); + if (!address) { + return UsecodeStepResult::StackFault; + } + if (!services.readFarWord) { + pushDword(*address); + return UsecodeStepResult::ServiceRejected; + } + const auto value = services.readFarWord(static_cast(*address), + static_cast(*address >> 16)); + if (!value) { + pushDword(*address); + return UsecodeStepResult::InvalidInstruction; + } + return pushWord(*value) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x77) { + if (!services.setInfo) { + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; + } + const auto first = popWord(); + const auto second = first ? popWord() : std::nullopt; + if (!first || !second) { + if (first) pushWord(*first); + return UsecodeStepResult::StackFault; + } + lastSetInfoOperands = std::array{*first, *second}; + if (!services.setInfo(*second, *first)) { + pushWord(*second); + pushWord(*first); + return UsecodeStepResult::ServiceRejected; + } + return UsecodeStepResult::SetInfo; + } + if (opcode == 0x50) { + return UsecodeStepResult::Returned; + } + if (opcode == 0x57) { + const std::size_t instructionStart = programCounter - 1; + if (code.size() - programCounter < 6) { + return UsecodeStepResult::InvalidInstruction; + } + const u8 extraArgumentBytes = code[programCounter]; + const u8 itemArgumentSize = code[programCounter + 1]; + const u16 classId = static_cast(code[programCounter + 2] | + (static_cast(code[programCounter + 3]) << 8)); + const u16 eventSlot = static_cast(code[programCounter + 4] | + (static_cast(code[programCounter + 5]) << 8)); + if ((itemArgumentSize != 0 && itemArgumentSize != sizeof(u16)) || + stackTop > valueStack.size() - sizeof(u32) || + extraArgumentBytes > valueStack.size() - stackTop - sizeof(u32)) { + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; + } + if (!services.spawn || (itemArgumentSize != 0 && !services.readFarWord)) { + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; + } + const auto itemPointer = popDword(); + if (!itemPointer) { + return UsecodeStepResult::StackFault; + } + u16 itemArgument = 0; + if (itemArgumentSize == sizeof(u16)) { + const auto value = services.readFarWord(static_cast(*itemPointer), + static_cast(*itemPointer >> 16)); + if (!value) { + pushDword(*itemPointer); + programCounter = instructionStart; + return UsecodeStepResult::InvalidInstruction; + } + itemArgument = *value; + } + const u8* extraArguments = valueStack.data() + stackTop; + programCounter += 6; + const auto processId = services.spawn(classId, eventSlot, extraArgumentBytes, + itemArgumentSize, itemArgument, extraArguments); + if (!processId) { + pushDword(*itemPointer); + programCounter = instructionStart; + return UsecodeStepResult::ServiceRejected; + } + temporaryWord = *processId; + return UsecodeStepResult::Spawned; + } + if (opcode == 0x5b) { + if (code.size() - programCounter < 2) { + return UsecodeStepResult::InvalidInstruction; + } + programCounter += 2; + return UsecodeStepResult::Advanced; + } + if (opcode == 0x5c) { + constexpr std::size_t symbolInfoBytes = 11; + if (code.size() - programCounter < symbolInfoBytes) { + return UsecodeStepResult::InvalidInstruction; + } + programCounter += symbolInfoBytes; + return UsecodeStepResult::Advanced; + } + if (opcode == 0x5e) { + return pushWord(temporaryWord) ? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault; + } + if (opcode == 0x78) { + if (!services.processCount) { + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; + } + processExcluded = services.processCount() > 1; + return UsecodeStepResult::Advanced; + } + --programCounter; + return UsecodeStepResult::UnsupportedOpcode; +} + +std::optional UsecodeProcessTask::create(u16 processId, u16 classId, + u16 eventSlot, u16 sourceItem, std::vector code, u8 itemArgumentSize, + std::vector extraArguments, std::vector contextParameter) +{ + if (processId < 3 || code.size() <= usecodeEventBytecodeOffset || + (itemArgumentSize != 0 && itemArgumentSize != sizeof(u16))) { + return std::nullopt; + } + const std::vector itemParameter = itemArgumentSize == 0 ? std::vector{} + : std::vector{static_cast(sourceItem), static_cast(sourceItem >> 8)}; + auto interpreter = UsecodeInterpreterState::initialize(itemParameter, contextParameter, + itemArgumentSize); + if (!interpreter) { + return std::nullopt; + } + UsecodeProcessTask task; + task.processId = processId; + task.classId = classId; + task.eventSlot = eventSlot; + task.sourceItem = sourceItem; + task.code = std::move(code); + task.frame.resize(0x80); + task.itemMemory.resize(0x102); + task.itemMemory[0x100] = static_cast(sourceItem); + task.itemMemory[0x101] = static_cast(sourceItem >> 8); + std::size_t argumentOffset = usecodeFrameBaseOffset + 6; + if (itemArgumentSize == sizeof(u16)) { + task.frame[argumentOffset] = 0x00; + task.frame[argumentOffset + 1] = 0x01; + argumentOffset += sizeof(u32); + } + if (extraArguments.size() > task.frame.size() - argumentOffset) { + return std::nullopt; + } + std::copy(extraArguments.begin(), extraArguments.end(), task.frame.begin() + argumentOffset); + task.interpreter = std::move(*interpreter); + return task; +} + +std::optional UsecodeProcessTask::readMappedItemWord(FarPtr16 address) const +{ + if (address.segment != 0 || address.offset > itemMemory.size() || + itemMemory.size() - address.offset < sizeof(u16)) { + return std::nullopt; + } + return static_cast(itemMemory[address.offset] | + (static_cast(itemMemory[address.offset + 1]) << 8)); +} + +bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize, + const UsecodeContextFactoryFields& fields) +{ + if (processBytes == nullptr || processSize < usecodeContextProcessSize) { + return false; + } + const auto writeWord = [processBytes](std::size_t offset, u16 value) { + processBytes[offset] = static_cast(value); + processBytes[offset + 1] = static_cast(value >> 8); + }; + writeWord(usecodeContextSlotIndexOffset, fields.slotIndex); + writeWord(usecodeContextValueAddOffset, fields.valueAddOffset); + writeWord(usecodeContextOwnerSourceOffset, fields.ownerSource.offset); + writeWord(usecodeContextOwnerSourceOffset + sizeof(u16), fields.ownerSource.segment); + writeWord(usecodeContextParameterOffset, fields.parameterOffset); + processBytes[usecodeContextModeFlagsOffset] = static_cast(fields.modeFlags); + processBytes[usecodeContextActiveFlagOffset] = 0; + return true; +} + +UsecodeStepResult UsecodeProcessTask::step(const UsecodeOpcodeServices& services) +{ + if (halted) { + return UsecodeStepResult::Returned; + } + const auto result = interpreter.step(code, programCounter, frame, services); + halted = result == UsecodeStepResult::Returned; + return result; +} + +bool UsecodeTaskRegistry::add(UsecodeProcessTask task) +{ + if (task.processId < 3) { + return false; + } + return tasks_.emplace(task.processId, std::move(task)).second; +} + +UsecodeProcessTask* UsecodeTaskRegistry::find(u16 processId) +{ + const auto found = tasks_.find(processId); + return found == tasks_.end() ? nullptr : &found->second; +} + +const UsecodeProcessTask* UsecodeTaskRegistry::find(u16 processId) const +{ + const auto found = tasks_.find(processId); + return found == tasks_.end() ? nullptr : &found->second; +} + +bool UsecodeTaskRegistry::remove(u16 processId) +{ + return tasks_.erase(processId) != 0; +} + } // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index 6027077..acf676f 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -15,6 +15,7 @@ #include "remorse/shape_archive.h" #include "remorse/type_flags.h" #include "remorse/usecode_archive.h" +#include "remorse/usecode_vm.h" #include #include @@ -47,6 +48,10 @@ struct AppState { bool diagnostics = false; remorse::ProcessKernel diagnosticKernel; remorse::u16 diagnosticGroupCounts[32]{}; + remorse::UsecodeTaskRegistry usecodeTasks; + bool useRequested = false; + bool usecodeWorldMutationPending = false; + std::uint64_t heldKeycards = 0; remorse::StandProcessEntry* diagnosticStand = nullptr; remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr; remorse::ControllerMovementState controllerMovement; @@ -55,6 +60,7 @@ struct AppState { std::optional diagnosticItem; remorse::u16 diagnosticItemProcessId = 0; remorse::u16 diagnosticReleaseEventItem = 0; + remorse::u16 diagnosticReleaseProcessId = 0; std::string diagnosticReleaseClass; std::size_t diagnosticReleaseBodyBytes = 0; bool diagnosticItemCompleted = false; @@ -142,6 +148,208 @@ remorse::WorldPoint avatarWorld(const AppState& state) bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range); +std::optional queueUsecodeTask(AppState& state, remorse::u16 classId, + remorse::u16 eventSlot, remorse::u16 sourceItem, std::vector code, + remorse::u8 itemArgumentSize = 2, std::vector extraArguments = {}) +{ + auto* process = state.diagnosticKernel.createUsecodeProcess( + state.diagnosticKernel.activeGroup(), state.diagnosticGroupCounts); + const remorse::u16 processId = static_cast(process->base.bytes[2] | + (static_cast(process->base.bytes[3]) << 8)); + auto task = remorse::UsecodeProcessTask::create(processId, classId, eventSlot, + sourceItem, std::move(code), itemArgumentSize, std::move(extraArguments)); + if (!task) { + state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts); + state.diagnosticKernel.clearTerminatedProcesses(); + return std::nullopt; + } + const remorse::UsecodeContextFactoryFields factoryFields{{0, 0}, itemArgumentSize, + classId, eventSlot, task->interpreter.contextParameterOffset.value_or(0)}; + if (!remorse::writeUsecodeContextFactoryFields(reinterpret_cast(process), + sizeof(*process), factoryFields) || !state.usecodeTasks.add(std::move(*task))) { + state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts); + state.diagnosticKernel.clearTerminatedProcesses(); + return std::nullopt; + } + return processId; +} + +bool startNearbyUsecode(AppState& state) +{ + if (!state.liveItems || !state.usecodeArchive || state.usecodeOwnerRows.empty()) { + return false; + } + const auto* origin = state.liveItems->findItem(1); + if (origin == nullptr || origin->data.shape >= state.shapeTypes.size()) { + return false; + } + const auto candidates = remorse::itemGrabSearchCandidates(*origin, + state.liveItems->mapItems(), state.shapeTypes); + if (!candidates) { + return false; + } + for (const auto& candidate : *candidates) { + const auto* item = state.liveItems->findItem(candidate.itemNumber); + if (item == nullptr || item->data.shape >= state.shapeTypes.size()) { + continue; + } + const auto& shape = state.shapeTypes[item->data.shape]; + const remorse::UsecodeItemIdentity identity{item->itemNumber, item->data.shape, + item->data.flags, item->data.quality, shape.family, false}; + const auto eligible = remorse::selectEligibleUsecodeEvent(*state.usecodeArchive, + state.usecodeOwnerRows, identity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); + if (eligible) { + return queueUsecodeTask(state, eligible->classId, 1, item->itemNumber, + eligible->body.bytes).has_value(); + } + } + return false; +} + +void runUsecodeTasks(AppState& state) +{ + state.diagnosticKernel.scanRunnableProcesses(state.diagnosticKernel.activeGroup(), + [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& app = *static_cast(context); + const remorse::u16 processId = static_cast(process.bytes[2] | + (static_cast(process.bytes[3]) << 8)); + auto* task = app.usecodeTasks.find(processId); + if (!task || task->halted) { + return; + } + if (task->timerDelayProcess) { + if (app.diagnosticKernel.systemTimerTick() >= task->wakeTick) { + app.diagnosticKernel.terminateProcess(processId, app.diagnosticGroupCounts); + } + return; + } + if (task->interpreter.impliedProcessId != 0) { + if (app.diagnosticKernel.processAt(task->interpreter.impliedProcessId) != nullptr) { + return; + } + task->interpreter.impliedProcessId = 0; + } + remorse::UsecodeOpcodeServices services; + services.readFarWord = [task](remorse::u16 offset, remorse::u16 segment) + -> std::optional { + return task->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + services.setInfo = [&app, processId](remorse::u16 eventType, remorse::u16 sourceItem) { + return app.diagnosticKernel.setProcessInfo(processId, eventType, sourceItem); + }; + services.processCount = [&app]() { return app.diagnosticKernel.processCount(); }; + services.currentProcessId = [processId]() { return processId; }; + services.callIntrinsic = [&app, task](remorse::u16 ordinal, remorse::u8 argumentBytes, + const remorse::u8* arguments) -> std::optional { + if (ordinal == 0x00 && argumentBytes == 0) { + return remorse::u16{0}; + } + if (ordinal == 0xfd && argumentBytes == 2) { + const remorse::u16 keycard = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + return static_cast(keycard < 64 && + (app.heldKeycards & (std::uint64_t{1} << keycard)) != 0); + } + if (ordinal == 0x15 && argumentBytes == 6) { + return remorse::u16{0}; + } + if (ordinal == 0x3a && argumentBytes == 6) { + return remorse::u16{0}; + } + if (argumentBytes < 4) { + return std::nullopt; + } + const remorse::u16 offset = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + const remorse::u16 segment = static_cast(arguments[2] | + (static_cast(arguments[3]) << 8)); + const auto itemNumber = task->readMappedItemWord(remorse::FarPtr16{offset, segment}); + if (!itemNumber) { + return std::nullopt; + } + if (ordinal == 0xea && argumentBytes == 4) { + const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; + return item ? std::optional{static_cast(item->data.quality & 0xff)} + : std::nullopt; + } + if (ordinal == 0x01 && argumentBytes == 4) { + const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; + return item ? std::optional{item->data.frame} : std::nullopt; + } + if (ordinal == 0x03 && argumentBytes == 4) { + const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; + return item ? std::optional{item->data.mapNumber} : std::nullopt; + } + if (ordinal == 0x59 && argumentBytes == 6) { + std::lock_guard lock(app.sceneMutex); + const remorse::u8 frame = static_cast(arguments[4] | + (static_cast(arguments[5]) << 8)); + if (!app.liveItems || !app.liveItems->setItemFrame(*itemNumber, frame)) { + return std::nullopt; + } + app.usecodeWorldMutationPending = true; + return remorse::u16{0}; + } + return std::nullopt; + }; + services.spawn = [&app](remorse::u16 classId, remorse::u16 eventSlot, + remorse::u8 extraArgumentBytes, remorse::u8 itemArgumentSize, + remorse::u16 itemArgument, const remorse::u8* extraArguments) + -> std::optional { + if (!app.usecodeArchive) { + return std::nullopt; + } + const auto usecodeClass = remorse::loadUsecodeClass(*app.usecodeArchive, classId); + const auto body = usecodeClass + ? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt; + if (!body) { + return std::nullopt; + } + std::vector arguments; + if (extraArgumentBytes != 0) { + arguments.assign(extraArguments, extraArguments + extraArgumentBytes); + } + const auto childId = queueUsecodeTask(app, classId, eventSlot, + itemArgument, body->bytes, itemArgumentSize, std::move(arguments)); + if (!childId) { + return std::nullopt; + } + auto* registeredChild = app.usecodeTasks.find(*childId); + if (registeredChild && classId == 0x0a0c && eventSlot == 0x32 && + itemArgumentSize == 0 && extraArgumentBytes == 2) { + const remorse::u16 delay = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + registeredChild->timerDelayProcess = true; + registeredChild->wakeTick = app.diagnosticKernel.systemTimerTick() + delay; + } + return childId; + }; + for (std::size_t instructionCount = 0; instructionCount < 256; ++instructionCount) { + const auto result = task->step(services); + if (result == remorse::UsecodeStepResult::Returned) { + app.diagnosticKernel.terminateProcess(processId, app.diagnosticGroupCounts); + break; + } + if (result == remorse::UsecodeStepResult::Yielded) { + break; + } + if (result != remorse::UsecodeStepResult::Advanced && + result != remorse::UsecodeStepResult::SetInfo && + result != remorse::UsecodeStepResult::Spawned) { + task->halted = true; + break; + } + } + }, &state, state.diagnosticKernel.systemTimerTick()); + state.diagnosticKernel.clearTerminatedProcesses(); + for (std::size_t processId = 3; processId < 1020; ++processId) { + const auto id = static_cast(processId); + if (state.usecodeTasks.find(id) && state.diagnosticKernel.processAt(id) == nullptr) { + state.usecodeTasks.remove(id); + } + } +} + void loadSceneAsync(HWND window, AppState& state) { state.sceneThread = std::thread([window, &state]() { @@ -659,12 +867,18 @@ void paintWindow(HWND window, AppState& state) playerWorld.x, playerWorld.y, diagnosticItemRange) : std::nullopt; if (state.diagnosticItem || nearbyItem) { const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem; + const auto* releaseTask = state.diagnosticReleaseProcessId != 0 + ? state.usecodeTasks.find(state.diagnosticReleaseProcessId) : nullptr; + const std::wstring releaseStatus = state.diagnosticReleaseProcessId == 0 ? L"NOT QUEUED" : + releaseTask == nullptr ? L"COMPLETE" : releaseTask->halted ? L"HALTED" : + releaseTask->programCounter == remorse::usecodeEventBytecodeOffset ? L"QUEUED" : L"RUNNING"; std::wostringstream itemStatus; itemStatus << L"MAP ITEM " << displayItem->itemNumber << L" | SHAPE " << displayItem->data.shape << L" | RELEASE REQUEST " << state.diagnosticReleaseEventItem << L" | " << (state.diagnosticReleaseBodyBytes != 0 - ? widen(state.diagnosticReleaseClass) + L" SCRIPT " + std::to_wstring(state.diagnosticReleaseBodyBytes) + L" BYTES (NOT RUN)" + ? widen(state.diagnosticReleaseClass) + L" SCRIPT " + std::to_wstring(state.diagnosticReleaseBodyBytes) + + L" BYTES (" + releaseStatus + L")" : L"NO RELEASE SCRIPT") << L" | PROCESS " << (state.diagnosticItemCompleted ? L"DONE" : state.diagnosticItemProcessId != 0 ? L"QUEUED" : @@ -708,6 +922,11 @@ void updatePlayer(HWND window, AppState& state) app.controllerMovement.handleDirectionalKey(event.scanCode, event.modifiers, event.field8 != 0); } }, &state); + if (state.useRequested) { + state.useRequested = false; + changed = startNearbyUsecode(state) || changed; + } + runUsecodeTasks(state); const auto movement = state.controllerMovement.request(); state.diagnosticKernel.deliverSystemTimerEvent(); if (state.diagnostics) { @@ -724,17 +943,21 @@ void updatePlayer(HWND window, AppState& state) [](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* releaseContext) { auto& app = *static_cast(releaseContext); app.diagnosticReleaseEventItem = itemNumber; - if (app.diagnosticItem && app.usecodeArchive && - app.diagnosticItem->data.shape < app.shapeTypes.size()) { - const auto& item = *app.diagnosticItem; - const remorse::UsecodeItemIdentity identity{item.itemNumber, item.data.shape, - item.data.flags, item.data.quality, app.shapeTypes[item.data.shape].family, false}; + app.diagnosticReleaseProcessId = 0; + app.diagnosticReleaseClass.clear(); + app.diagnosticReleaseBodyBytes = 0; + const auto* item = app.liveItems ? app.liveItems->findItem(itemNumber) : nullptr; + if (item && app.usecodeArchive && item->data.shape < app.shapeTypes.size()) { + const remorse::UsecodeItemIdentity identity{item->itemNumber, item->data.shape, + item->data.flags, item->data.quality, app.shapeTypes[item->data.shape].family, false}; const remorse::UsecodeClassBases bases{0, 0x800, 0x900}; const auto eligible = remorse::selectEligibleUsecodeEvent(*app.usecodeArchive, app.usecodeOwnerRows, identity, bases, eventMask, eventId); if (eligible) { app.diagnosticReleaseClass = eligible->className; app.diagnosticReleaseBodyBytes = eligible->body.bytes.size(); + app.diagnosticReleaseProcessId = queueUsecodeTask(app, + eligible->classId, eventId, itemNumber, eligible->body.bytes).value_or(0); } } }, &app); @@ -814,7 +1037,9 @@ void updatePlayer(HWND window, AppState& state) avatar->data.z != beforeMove.z; const bool hatched = moved && hatchGlobsInFastArea( *state.liveItems, *state.renderer, remorse::calculateFastAreaRange(avatarWorld(state))); - if (state.renderThread.joinable() && (moved || hatched)) { + const bool usecodeMutation = state.usecodeWorldMutationPending; + state.usecodeWorldMutationPending = false; + if (state.renderThread.joinable() && (moved || hatched || usecodeMutation)) { state.renderRequested = true; state.renderWake.notify_one(); } @@ -859,6 +1084,9 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA DestroyWindow(window); return 0; } + if (wParam == 'E' && message == WM_KEYDOWN) { + state->useRequested = true; + } { remorse::KeyEvent event{}; event.scanCode = static_cast((lParam >> 16) & 0xff); diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index 177f96f..9a4ee99 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -151,6 +151,33 @@ int main() assert(createdKernel.processAt(2) == syncing && createdGroups[2] == 3); assert(syncing->bytes[0x16] == 0x40 && syncing->bytes[0x17] == 0); + remorse::ProcessKernel usecodeKernel; + remorse::u16 usecodeGroups[32]{}; + for (int index = 0; index < 3; ++index) { + usecodeKernel.createProcess(1, usecodeGroups); + } + auto* usecodeContext = usecodeKernel.createUsecodeProcess(1, usecodeGroups); + const remorse::u16 usecodeProcessId = static_cast( + usecodeContext->base.bytes[2] | (static_cast(usecodeContext->base.bytes[3]) << 8)); + assert(usecodeKernel.allocationSizeAt(usecodeProcessId) == 0x124 && + std::strcmp(usecodeKernel.processNameAt(usecodeProcessId), "Usecode") == 0); + assert(usecodeKernel.setProcessInfo(usecodeProcessId, 0x0207, 0x1234)); + int usecodeRuns = 0; + usecodeKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& scan = *static_cast(context); + if (process.bytes[2] == 3 && process.bytes[3] == 0) { + ++scan; + } + }, &usecodeRuns); + assert(usecodeRuns == 1 && usecodeKernel.processAt(usecodeProcessId) == &usecodeContext->base); + usecodeKernel.terminateProcess(usecodeProcessId, usecodeGroups); + assert(usecodeKernel.processAt(usecodeProcessId) == &usecodeContext->base && + (usecodeContext->base.bytes[0x16] & 0x08) != 0 && + usecodeKernel.processCount() == 3 && usecodeGroups[1] == 3); + usecodeKernel.clearTerminatedProcesses(); + assert(usecodeKernel.processAt(usecodeProcessId) == nullptr && + usecodeKernel.terminatedProcessCount() == 0); + createdKernel.setSyncContext(true, 1); next->bytes[0x18] |= 0x02; auto* retiring = createdKernel.createProcess(2, createdGroups); @@ -269,6 +296,16 @@ int main() assert((ran == std::vector{2, 3})); assert(specialGroup->bytes[0x08] == 30); + remorse::ProcessKernel automaticGroupKernel; + remorse::u16 automaticGroupCounts[32]{}; + automaticGroupKernel.createProcess(3, automaticGroupCounts); + std::vector automaticGroupRuns; + automaticGroupKernel.scanRunnableProcesses(2, recordRun, &automaticGroupRuns); + assert(automaticGroupRuns.empty() && automaticGroupKernel.activeGroup() == 3 && + !automaticGroupKernel.groupSelectionPending()); + automaticGroupKernel.scanRunnableProcesses(3, recordRun, &automaticGroupRuns); + assert((automaticGroupRuns == std::vector{0})); + remorse::ProcessKernel spawningKernel; remorse::u16 spawningGroups[32]{}; spawningKernel.createProcess(1, spawningGroups); diff --git a/rebuild/remorse/tests/fixed_map_tests.cpp b/rebuild/remorse/tests/fixed_map_tests.cpp index 9be0fa8..f4b84a2 100644 --- a/rebuild/remorse/tests/fixed_map_tests.cpp +++ b/rebuild/remorse/tests/fixed_map_tests.cpp @@ -236,6 +236,13 @@ int main() assert(allocatedItems.allocateItem(newItem) == 0x107); newItem.data.x = 0x8000; assert(!allocatedItems.allocateItem(newItem) && !allocatedItems.findItem(0x108)); + newItem.data.x = 511; + remorse::ProcessKernel recyclingKernel; + assert(allocatedItems.releaseItem(0x106, recyclingKernel)); + assert(allocatedItems.releaseItem(0x107, recyclingKernel)); + assert(allocatedItems.allocateItem(newItem) == 0x107); + assert(allocatedItems.allocateItem(newItem) == 0x106); + remorse::StagedFixedMapItem globEgg; globEgg.itemNumber = 0x100; globEgg.data.x = 0x403; @@ -254,6 +261,24 @@ int main() assert(child->data.x == 0x405 && child->data.y == 0x60b && child->data.z == 15); assert(child->data.flags == 0x82 && child->data.frame == 2); assert(hatchedItems.isGlobHatched(0x100) && !hatchedItems.hatchGlobEgg(0x100, glob, globShapes)); + + remorse::LiveFixedMapItems processOwnedItems({globEgg}); + remorse::ProcessKernel itemOwnerKernel; + remorse::u16 itemOwnerGroups[32]{}; + for (int index = 0; index < 3; ++index) { + itemOwnerKernel.createProcess(1, itemOwnerGroups); + } + auto* itemOwner = itemOwnerKernel.createItemProcess(1, 0x100, itemOwnerGroups); + assert(itemOwnerKernel.itemHasProcess(0x100)); + assert(!processOwnedItems.releaseItem(0x100, itemOwnerKernel)); + const remorse::u16 itemOwnerProcessId = static_cast( + itemOwner->bytes[0x02] | (static_cast(itemOwner->bytes[0x03]) << 8)); + itemOwnerKernel.terminateProcess(itemOwnerProcessId, itemOwnerGroups); + itemOwnerKernel.clearTerminatedProcesses(); + assert(!itemOwnerKernel.itemHasProcess(0x100)); + assert(processOwnedItems.releaseItem(0x100, itemOwnerKernel)); + assert(processOwnedItems.allocateItem(globEgg) == 0x100); + remorse::LiveFixedMapItems movingItems(blockItems); remorse::ProcessKernel movingKernel; remorse::u16 movingGroups[32]{}; @@ -372,16 +397,51 @@ int main() assert((*contained)[2].itemNumber == 0x103 && (*contained)[2].parentItemNumber == 0x100); const auto directContainerItems = remorse::stageFixedMapItems(containedMap); assert(directContainerItems && directContainerItems->size() == 2); + auto monsterEggShapes = containerShapes; + monsterEggShapes[1].family = 7; + const auto monsterEggContents = remorse::stageContainedFixedMapItems(containedMap, monsterEggShapes); + assert(monsterEggContents && monsterEggContents->size() == 3 && + (*monsterEggContents)[0].parentItemNumber == 0x100 && + (*monsterEggContents)[1].parentItemNumber == 0x101 && + (*monsterEggContents)[2].parentItemNumber == 0x100); + remorse::LiveFixedMapItems monsterEggItems(*directContainerItems, *monsterEggContents); + assert((monsterEggItems.containedChildren(0x100) == std::vector{0x101, 0x103})); + assert(monsterEggItems.findItem(0x100)->data.quality == 0x101); + assert(!monsterEggItems.moveItemIntoContainer(0x104, 0x100, monsterEggShapes)); + assert(monsterEggItems.moveContainedItemToWorld(0x101, 600, 700, 12)); + assert(monsterEggItems.findItem(0x101)->data.quality == 0x102 && + monsterEggItems.findItem(0x100)->data.quality == 0x103); remorse::LiveFixedMapItems nestedItems(*directContainerItems, *contained); assert(nestedItems.containedParent(0x101) == 0x100 && nestedItems.containedParent(0x102) == 0x101 && nestedItems.containedParent(0x103) == 0x100); + assert((nestedItems.containedChildren(0x100) == std::vector{0x101, 0x103})); + assert((nestedItems.containedChildren(0x101) == std::vector{0x102})); + assert(nestedItems.findItem(0x100)->data.quality == 0x101); + assert(!nestedItems.moveItemIntoContainer(0x100, 0x102, containerShapes)); + assert(nestedItems.moveItemIntoContainer(0x104, 0x100, containerShapes)); + assert((nestedItems.containedChildren(0x100) == std::vector{0x104, 0x101, 0x103})); + assert(nestedItems.findItem(0x100)->data.quality == 0x104); + assert(!nestedItems.findItem(0x104) && nestedItems.containedParent(0x104) == 0x100); + assert(nestedItems.moveContainedItemToWorld(0x104, 700, 800, 12)); + assert((nestedItems.containedChildren(0x100) == std::vector{0x101, 0x103})); + assert(nestedItems.findItem(0x100)->data.quality == 0x101); + assert(nestedItems.findItem(0x104)->data.x == 700 && nestedItems.findItem(0x104)->data.y == 800); + assert(nestedItems.containedParent(0x102) == 0x101); remorse::StagedFixedMapItem nestedNewItem = directContainerItems->front(); assert(nestedItems.allocateItem(nestedNewItem) == 0x105); + remorse::ProcessKernel noItemProcesses; + assert(nestedItems.releaseItem(0x105, noItemProcesses)); + assert(!nestedItems.findItem(0x105)); + assert(nestedItems.allocateItem(nestedNewItem) == 0x105); assert(!nestedItems.findItem(0x101) && !nestedItems.findItem(0x102) && !nestedItems.findItem(0x103) && nestedItems.findItem(0x105)); nestedNewItem.itemNumber = 0x101; assert(nestedItems.insertItem(nestedNewItem)); + assert(nestedItems.findItem(0x100)->data.quality == 0x103); assert(nestedItems.containedParent(0x101) == 0 && nestedItems.containedParent(0x102) == 0x101); + assert((nestedItems.containedChildren(0x100) == std::vector{0x103})); + assert((nestedItems.containedChildren(0x101) == std::vector{0x102})); + assert(!nestedItems.releaseItem(0x101, noItemProcesses)); std::vector fullItemRange; for (remorse::u16 itemNumber = 0x101; itemNumber < 0x2800; ++itemNumber) { fullItemRange.push_back({itemNumber, 0x100, 0}); diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index a828602..0d04ad6 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -1,17 +1,28 @@ #include "remorse/collision.h" +#include "remorse/entity_dispatch_entry.h" #include "remorse/file_system.h" #include "remorse/flex_archive.h" #include "remorse/fixed_map.h" #include "remorse/glob_archive.h" +#include "remorse/map_renderer.h" #include "remorse/type_flags.h" #include "remorse/usecode_archive.h" #include "remorse/usecode_vm.h" +#include +#include #include +#include #include int main() { + const auto hasRetailEventEntry = [](const std::vector& body, + const std::array& prefix) { + return body.size() > remorse::usecodeEventBytecodeOffset && + std::equal(prefix.begin(), prefix.end(), body.begin()) && + body[remorse::usecodeEventBytecodeOffset] == 0x0b; + }; const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); assert(root.has_value()); @@ -52,6 +63,9 @@ int main() assert(rechargeClass && rechargeClass->name == "RECHFLNS"); const auto releaseBody = remorse::readUsecodeEventBody(*rechargeClass, 9); assert(releaseBody && releaseBody->length == 102 && releaseBody->relativeOffset == 0x256); + const std::array releasePrefix{ + 0x5a, 0x02, 0x5c, 0x49, 0x00, 'R', 'E', 'C', 'H', 'F', 'L', 'N', 'S', 0x00}; + assert(hasRetailEventEntry(releaseBody->bytes, releasePrefix)); assert(remorse::ownerRowAllowsEvent(*retailOwnerRows, 0x138, 0x200)); const remorse::UsecodeClassBases bases{0x200, 0x400, 0x600}; remorse::UsecodeItemIdentity identity{7, 0x45, 0, 0x1278, 4, true}; @@ -74,6 +88,27 @@ int main() assert(stagedItems && !stagedItems->empty()); const auto spawnEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x1e); assert(spawnEgg); + unsigned eligibleMapUseItems = 0; + unsigned keycardUseItems = 0; + std::optional boxItem; + for (const auto& item : *stagedItems) { + if (item.data.shape >= typeFlags->size()) continue; + const auto& shape = (*typeFlags)[item.data.shape]; + const remorse::UsecodeItemIdentity mapItemIdentity{item.itemNumber, item.data.shape, + item.data.flags, item.data.quality, shape.family, false}; + const auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + mapItemIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); + if (eligible) { + ++eligibleMapUseItems; + if (eligible->classId == 0x031d || eligible->classId == 0x031e) { + ++keycardUseItems; + } + if (eligible->className == "BOX_NS" && item.data.frame == 0 && !boxItem) { + boxItem = item; + } + } + } + assert(eligibleMapUseItems == 218 && keycardUseItems == 10 && boxItem); const auto globPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GLOB.FLX"); const auto globs = globPath ? remorse::loadGlobObjects(*globPath) : std::nullopt; assert(globs); @@ -147,6 +182,320 @@ int main() assert(!interpreter->pushCodeAddress(0xffff, 0)); assert(interpreter->callFrameCount == 0x1f && interpreter->callFrames[31].offset == 0); assert(!remorse::UsecodeInterpreterState::initialize(std::vector(0xcd))); + const auto cardClass = remorse::loadUsecodeClass(*usecode, 0x31d); + const auto cardUse = cardClass ? remorse::readUsecodeEventBody(*cardClass, 1) : std::nullopt; + assert(cardClass && cardClass->name == "CARD_NS" && cardUse && cardUse->bytes.size() == 56); + const std::array cardPrefix{ + 0x5a, 0x00, 0x5c, 0x24, 0x00, 'C', 'A', 'R', 'D', '_', 'N', 'S', 0x00, 0x00}; + assert(hasRetailEventEntry(cardUse->bytes, cardPrefix)); + std::vector frame(0x80); + frame[remorse::usecodeFrameBaseOffset + 6] = 0x00; + frame[remorse::usecodeFrameBaseOffset + 7] = 0x01; + std::vector itemMemory(0x102); + itemMemory[0x100] = 0x34; + itemMemory[0x101] = 0x12; + remorse::ProcessKernel vmKernel; + remorse::u16 vmGroupCounts[32]{}; + for (int index = 0; index < 3; ++index) { + vmKernel.createProcess(1, vmGroupCounts); + } + auto* vmProcess = vmKernel.createUsecodeProcess(1, vmGroupCounts); + const remorse::u16 vmProcessId = static_cast( + vmProcess->base.bytes[2] | (static_cast(vmProcess->base.bytes[3]) << 8)); + auto cardTask = remorse::UsecodeProcessTask::create(vmProcessId, 0x31d, 1, 0x1234, + cardUse->bytes); + assert(cardTask && cardTask->programCounter == remorse::usecodeEventBytecodeOffset && + cardTask->frame.size() == 0x80 && + cardTask->frame[remorse::usecodeFrameBaseOffset + 7] == 1 && + cardTask->itemMemory[0x100] == 0x34 && + cardTask->itemMemory[0x101] == 0x12); + remorse::UsecodeTaskRegistry taskRegistry; + assert(taskRegistry.add(std::move(*cardTask)) && taskRegistry.size() == 1); + cardTask.reset(); + auto* registeredCardTask = taskRegistry.find(vmProcessId); + assert(registeredCardTask && registeredCardTask->classId == 0x31d && + registeredCardTask->eventSlot == 1 && registeredCardTask->sourceItem == 0x1234); + assert(!taskRegistry.add(*registeredCardTask)); + const auto switchClass = remorse::loadUsecodeClass(*usecode, 0x0a16); + const auto switchUse = switchClass ? remorse::readUsecodeEventBody(*switchClass, 0x21) : std::nullopt; + assert(switchClass && switchClass->name == "SWITCH" && switchUse); + remorse::UsecodeOpcodeServices opcodeServices; + opcodeServices.readFarWord = [registeredCardTask](remorse::u16 offset, remorse::u16 segment) + -> std::optional { + return registeredCardTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + opcodeServices.setInfo = [&vmKernel, vmProcessId](remorse::u16 eventType, + remorse::u16 sourceItem) { + return vmKernel.setProcessInfo(vmProcessId, eventType, sourceItem); + }; + std::optional> spawnedUsecode; + remorse::u16 spawnedProcessId = 0; + opcodeServices.processCount = [&vmKernel]() { return vmKernel.processCount(); }; + opcodeServices.spawn = [&spawnedUsecode, &spawnedProcessId, &vmKernel, &vmGroupCounts, + &taskRegistry, &switchUse](remorse::u16 classId, remorse::u16 eventSlot, + remorse::u8 extraArgumentBytes, remorse::u8 itemArgumentSize, + remorse::u16 itemArgument, const remorse::u8*) -> std::optional { + assert(extraArgumentBytes == 0 && itemArgumentSize == 2); + spawnedUsecode = std::array{classId, eventSlot, itemArgument}; + auto* child = vmKernel.createUsecodeProcess(1, vmGroupCounts); + spawnedProcessId = static_cast( + child->base.bytes[2] | (static_cast(child->base.bytes[3]) << 8)); + auto childTask = remorse::UsecodeProcessTask::create(spawnedProcessId, classId, + eventSlot, itemArgument, switchUse->bytes); + if (!childTask || !taskRegistry.add(std::move(*childTask))) { + vmKernel.terminateProcess(spawnedProcessId, vmGroupCounts); + vmKernel.clearTerminatedProcesses(); + return std::nullopt; + } + return spawnedProcessId; + }; + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 17); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 19); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 21); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::SetInfo && + registeredCardTask->programCounter == 22); + assert(registeredCardTask->interpreter.lastSetInfoOperands && + (*registeredCardTask->interpreter.lastSetInfoOperands)[0] == 0x1234 && + (*registeredCardTask->interpreter.lastSetInfoOperands)[1] == 0x0207); + assert(vmKernel.processAt(vmProcessId)->bytes[0x04] == 0x34 && + vmKernel.processAt(vmProcessId)->bytes[0x05] == 0x12 && + vmKernel.processAt(vmProcessId)->bytes[0x06] == 0x07 && + vmKernel.processAt(vmProcessId)->bytes[0x07] == 0x02); + opcodeServices.setInfo = [](remorse::u16, remorse::u16) { return false; }; + const auto stackTopBeforeRejectedInfo = registeredCardTask->interpreter.stackTop; + assert(registeredCardTask->interpreter.pushWord(0x1234) && + registeredCardTask->interpreter.pushWord(0x0207)); + const auto stackTopWithRejectedInfo = registeredCardTask->interpreter.stackTop; + registeredCardTask->programCounter = 21; + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::ServiceRejected && + registeredCardTask->programCounter == 22); + assert(registeredCardTask->interpreter.stackTop == stackTopWithRejectedInfo && + registeredCardTask->interpreter.popWord() == 0x0207 && + registeredCardTask->interpreter.popWord() == 0x1234); + registeredCardTask->interpreter.stackTop = stackTopBeforeRejectedInfo; + registeredCardTask->programCounter = 22; + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 23 && registeredCardTask->interpreter.processExcluded); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 26); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 28); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Spawned && + registeredCardTask->programCounter == 35); + assert(spawnedUsecode && (*spawnedUsecode)[0] == 0x0a16 && + (*spawnedUsecode)[1] == 0x21 && (*spawnedUsecode)[2] == 0x1234); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 36); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 37 && + registeredCardTask->interpreter.temporaryWord == spawnedProcessId); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Advanced && + registeredCardTask->programCounter == 40); + assert(registeredCardTask->step(opcodeServices) == remorse::UsecodeStepResult::Returned && + registeredCardTask->programCounter == 41); + auto* registeredSwitchTask = taskRegistry.find(spawnedProcessId); + assert(registeredSwitchTask && registeredSwitchTask->classId == 0x0a16 && + registeredSwitchTask->eventSlot == 0x21 && registeredSwitchTask->sourceItem == 0x1234 && + vmKernel.processAt(spawnedProcessId) != nullptr); + vmKernel.terminateProcess(vmProcessId, vmGroupCounts); + vmKernel.clearTerminatedProcesses(); + assert(taskRegistry.remove(vmProcessId) && taskRegistry.size() == 1 && + !taskRegistry.find(vmProcessId) && taskRegistry.find(spawnedProcessId) == registeredSwitchTask); + struct SwitchScheduleContext { + remorse::ProcessKernel* kernel; + remorse::UsecodeTaskRegistry* tasks; + remorse::u16 processId; + unsigned runs = 0; + } switchSchedule{&vmKernel, &taskRegistry, spawnedProcessId}; + vmKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& schedule = *static_cast(context); + const remorse::u16 processId = static_cast( + process.bytes[2] | (static_cast(process.bytes[3]) << 8)); + if (processId != schedule.processId) { + return; + } + ++schedule.runs; + auto* task = schedule.tasks->find(processId); + assert(task); + remorse::UsecodeOpcodeServices services; + services.readFarWord = [task](remorse::u16 offset, remorse::u16 segment) + -> std::optional { + return task->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + services.setInfo = [schedule, processId](remorse::u16 eventType, remorse::u16 sourceItem) { + return schedule.kernel->setProcessInfo(processId, eventType, sourceItem); + }; + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->step(services) == remorse::UsecodeStepResult::SetInfo); + }, &switchSchedule); + assert(switchSchedule.runs == 1 && registeredSwitchTask->programCounter == 22 && + vmKernel.processAt(spawnedProcessId)->bytes[0x04] == 0x34 && + vmKernel.processAt(spawnedProcessId)->bytes[0x06] == 0x07); + remorse::StagedFixedMapItem switchItem; + switchItem.itemNumber = 0x1234; + switchItem.data.shape = 0x216; + switchItem.data.quality = 3; + remorse::LiveFixedMapItems switchWorld({switchItem}); + auto switchTask = remorse::UsecodeProcessTask::create(spawnedProcessId, 0x0a16, 0x21, + switchItem.itemNumber, switchUse->bytes); + assert(switchTask); + const std::uint64_t heldKeycards = std::uint64_t{1} << switchItem.data.quality; + remorse::UsecodeOpcodeServices switchServices; + switchServices.readFarWord = [&switchTask](remorse::u16 offset, remorse::u16 segment) + -> std::optional { + return switchTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + switchServices.setInfo = [&vmKernel, spawnedProcessId](remorse::u16 eventType, + remorse::u16 sourceItem) { + return vmKernel.setProcessInfo(spawnedProcessId, eventType, sourceItem); + }; + switchServices.callIntrinsic = [&switchTask, &switchWorld, heldKeycards](remorse::u16 ordinal, + remorse::u8 argumentBytes, const remorse::u8* arguments) -> std::optional { + const auto itemNumber = [&]() -> std::optional { + if (argumentBytes < 4) return std::nullopt; + const remorse::u16 offset = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + const remorse::u16 segment = static_cast(arguments[2] | + (static_cast(arguments[3]) << 8)); + return switchTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + if (ordinal == 0x00 && argumentBytes == 0) return remorse::u16{0}; + if (ordinal == 0xfd && argumentBytes == 2) { + const remorse::u16 keycard = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + return static_cast((heldKeycards & (std::uint64_t{1} << (keycard & 0x1f))) != 0); + } + if (ordinal == 0x18 && argumentBytes == 4) return remorse::u16{0}; + if (ordinal == 0x15 && argumentBytes == 6) return remorse::u16{0}; + const auto source = itemNumber(); + if (!source) return std::nullopt; + const auto* item = switchWorld.findItem(*source); + if (ordinal == 0xea && argumentBytes == 4 && item) { + return static_cast(item->data.quality & 0xff); + } + if (ordinal == 0x01 && argumentBytes == 4 && item) { + return static_cast(item->data.frame); + } + if (ordinal == 0x59 && argumentBytes == 6 && arguments[4] == 4 && item) { + return switchWorld.setItemFrame(*source, arguments[4]) + ? std::optional{remorse::u16{0}} : std::nullopt; + } + return std::nullopt; + }; + bool switchFrameChanged = false; + for (unsigned instruction = 0; instruction < 100 && !switchFrameChanged; ++instruction) { + const auto result = switchTask->step(switchServices); + const auto* item = switchWorld.findItem(switchItem.itemNumber); + switchFrameChanged = item && item->data.frame == 4; + assert(result == remorse::UsecodeStepResult::Advanced || + result == remorse::UsecodeStepResult::SetInfo); + } + assert(switchFrameChanged && switchTask->programCounter < switchUse->bytes.size() && + switchTask->sourceItem == switchItem.itemNumber); + const auto boxClass = remorse::loadUsecodeClass(*usecode, 0x0081); + const auto boxUse = boxClass ? remorse::readUsecodeEventBody(*boxClass, 1) : std::nullopt; + assert(boxClass && boxClass->name == "BOX_NS" && boxUse && boxItem); + const std::array boxPrefix{ + 0x5a, 0x02, 0x5c, 0xd6, 0x01, 'B', 'O', 'X', '_', 'N', 'S', 0x00, 0x00, 0x00}; + assert(hasRetailEventEntry(boxUse->bytes, boxPrefix)); + remorse::LiveFixedMapItems boxWorld(*stagedItems); + auto boxTask = remorse::UsecodeProcessTask::create(0x0340, 0x0081, 1, + boxItem->itemNumber, boxUse->bytes); + assert(boxTask); + const auto freeClass = remorse::loadUsecodeClass(*usecode, 0x0a0c); + const auto freeTimerBody = freeClass ? remorse::readUsecodeEventBody(*freeClass, 0x32) : std::nullopt; + auto boxRenderer = remorse::loadMapSceneRenderer(*root, 1); + assert(freeClass && freeTimerBody && boxRenderer); + remorse::MapRenderOptions boxRenderOptions; + boxRenderOptions.mapIndex = 1; + boxRenderOptions.maxWidth = 320; + boxRenderOptions.maxHeight = 200; + boxRenderOptions.viewCenter = remorse::WorldPoint{ + boxItem->data.x * 2, boxItem->data.y * 2, boxItem->data.z}; + const auto boxBefore = boxRenderer->render(boxRenderOptions, &boxWorld); + assert(boxBefore); + remorse::UsecodeOpcodeServices boxServices; + boxServices.readFarWord = [&boxTask](remorse::u16 offset, remorse::u16 segment) + -> std::optional { + return boxTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); + }; + boxServices.setInfo = [](remorse::u16, remorse::u16) { return true; }; + boxServices.processCount = []() { return remorse::u16{2}; }; + boxServices.currentProcessId = []() { return remorse::u16{0x0340}; }; + boxServices.callIntrinsic = [&boxTask, &boxWorld](remorse::u16 ordinal, + remorse::u8 argumentBytes, const remorse::u8* arguments) -> std::optional { + if ((ordinal == 0x15 || ordinal == 0x3a) && argumentBytes == 6) return remorse::u16{0}; + if (argumentBytes < 4) return std::nullopt; + const remorse::u16 offset = static_cast(arguments[0] | + (static_cast(arguments[1]) << 8)); + const remorse::u16 segment = static_cast(arguments[2] | + (static_cast(arguments[3]) << 8)); + const auto itemNumber = boxTask->readMappedItemWord(remorse::FarPtr16{offset, segment}); + if (!itemNumber) return std::nullopt; + const auto* item = boxWorld.findItem(*itemNumber); + if (ordinal == 0x01 && argumentBytes == 4 && item) return item->data.frame; + if (ordinal == 0x02 && argumentBytes == 6 && item) { + const remorse::u8 frame = static_cast(arguments[4] | + (static_cast(arguments[5]) << 8)); + return boxWorld.setItemFrame(*itemNumber, frame) + ? std::optional{remorse::u16{0}} : std::nullopt; + } + if (ordinal == 0x03 && argumentBytes == 4 && item) return item->data.mapNumber; + return std::nullopt; + }; + remorse::u16 nextTimerProcessId = 0x0350; + remorse::u32 timerTick = 100; + remorse::u16 lastTimerDelay = 0; + std::optional timerTask; + boxServices.spawn = [&nextTimerProcessId, &timerTick, &lastTimerDelay, &timerTask, + &freeTimerBody](remorse::u16 classId, + remorse::u16 eventSlot, remorse::u8 extraArgumentBytes, remorse::u8 itemArgumentSize, + remorse::u16 itemArgument, const remorse::u8* extraArguments) -> std::optional { + if (classId != 0x0a0c || eventSlot != 0x32 || extraArgumentBytes != 2 || + itemArgumentSize != 0 || itemArgument != 0) return std::nullopt; + lastTimerDelay = static_cast(extraArguments[0] | + (static_cast(extraArguments[1]) << 8)); + std::vector timerArguments(extraArguments, extraArguments + extraArgumentBytes); + const remorse::u16 processId = nextTimerProcessId++; + timerTask = remorse::UsecodeProcessTask::create(processId, classId, eventSlot, + itemArgument, freeTimerBody->bytes, itemArgumentSize, std::move(timerArguments)); + if (!timerTask) return std::nullopt; + timerTask->timerDelayProcess = true; + timerTask->wakeTick = timerTick + lastTimerDelay; + return processId; + }; + for (remorse::u8 expectedFrame = 0; expectedFrame < 6; ++expectedFrame) { + bool yielded = false; + for (unsigned instruction = 0; instruction < 500 && !yielded; ++instruction) { + const auto result = boxTask->step(boxServices); + if (result == remorse::UsecodeStepResult::Yielded) { + yielded = true; + break; + } + assert(result == remorse::UsecodeStepResult::Advanced || + result == remorse::UsecodeStepResult::SetInfo || + result == remorse::UsecodeStepResult::Spawned); + } + assert(yielded && lastTimerDelay == 5 && timerTask && + boxTask->interpreter.impliedProcessId == timerTask->processId); + assert(boxWorld.findItem(boxItem->itemNumber)->data.frame == expectedFrame); + assert(timerTask->frame[remorse::usecodeFrameBaseOffset + 6] == 5 && + timerTask->timerDelayProcess && timerTask->wakeTick == timerTick + 5); + timerTick = timerTask->wakeTick; + timerTask.reset(); + boxTask->interpreter.impliedProcessId = 0; + } + const auto boxAfter = boxRenderer->render(boxRenderOptions, &boxWorld); + assert(boxAfter && boxBefore->pixels.size() == boxAfter->pixels.size()); + assert(!std::equal(boxBefore->pixels.begin(), boxBefore->pixels.end(), boxAfter->pixels.begin(), + [](const auto& left, const auto& right) { + return left.red == right.red && left.green == right.green && left.blue == right.blue; + })); assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, rechargeItem, retailBases, 0, 9)); std::vector ownerRows(26); diff --git a/rebuild/remorse/tests/usecode_vm_tests.cpp b/rebuild/remorse/tests/usecode_vm_tests.cpp new file mode 100644 index 0000000..bd8d993 --- /dev/null +++ b/rebuild/remorse/tests/usecode_vm_tests.cpp @@ -0,0 +1,134 @@ +#include "remorse/usecode_vm.h" + +#include +#include + +int main() +{ + auto emptyStack = remorse::UsecodeInterpreterState::initialize({}); + assert(emptyStack.has_value()); + assert(!emptyStack->popWord().has_value()); + assert(!emptyStack->popDword().has_value()); + assert(emptyStack->pushDword(0x12345678)); + const auto pushedDword = emptyStack->popDword(); + assert(pushedDword.has_value() && *pushedDword == static_cast(0x12345678)); + assert(!emptyStack->popWord().has_value()); + + const std::vector itemParameter{0x34, 0x12}; + const std::vector contextParameter{0xa1, 0xb2, 0xc3, 0xd4}; + auto factoryStack = remorse::UsecodeInterpreterState::initialize( + itemParameter, contextParameter, 2); + assert(factoryStack && factoryStack->stackTop == 194 && + factoryStack->contextParameterOffset == 190); + assert(factoryStack->valueStack[194] == 0 && factoryStack->valueStack[197] == 0 && + factoryStack->valueStack[198] == 0xa1 && factoryStack->valueStack[201] == 0xd4 && + factoryStack->valueStack[202] == 0x34 && factoryStack->valueStack[203] == 0x12); + auto noPointerStack = remorse::UsecodeInterpreterState::initialize( + itemParameter, contextParameter, 0); + assert(noPointerStack && noPointerStack->stackTop == 198 && + !noPointerStack->contextParameterOffset && + noPointerStack->valueStack[198] == 0xa1 && noPointerStack->valueStack[201] == 0xd4); + assert(!remorse::UsecodeInterpreterState::initialize( + itemParameter, std::vector(0xcb), 2)); + auto stackLimitState = remorse::UsecodeInterpreterState::initialize( + {}, std::vector(remorse::usecodeInterpreterStackLimit - 4), 2); + assert(stackLimitState && stackLimitState->stackTop == 5 && + stackLimitState->contextParameterOffset == 1); + assert(!remorse::UsecodeInterpreterState::initialize( + {}, std::vector(remorse::usecodeInterpreterStackLimit - 3), 2)); + + auto frameState = remorse::UsecodeInterpreterState::initialize({}); + assert(frameState.has_value()); + for (int frameIndex = 0; frameIndex < 31; ++frameIndex) { + assert(frameState->pushCodeAddress(static_cast(frameIndex), 0x1418)); + } + assert(!frameState->pushCodeAddress(31, 0x1418)); + + std::array processContext{}; + processContext[0x123] = 0xa5; + const remorse::UsecodeContextFactoryFields factoryFields{ + remorse::FarPtr16{0x5678, 0x1234}, 0x0102, 0x0361, 0x000a, 190}; + assert(remorse::writeUsecodeContextFactoryFields(processContext.data(), processContext.size(), + factoryFields)); + assert(processContext[remorse::usecodeContextSlotIndexOffset] == 0x61 && + processContext[remorse::usecodeContextSlotIndexOffset + 1] == 0x03); + assert(processContext[remorse::usecodeContextValueAddOffset] == 0x0a && + processContext[remorse::usecodeContextValueAddOffset + 1] == 0x00); + assert(processContext[remorse::usecodeContextOwnerSourceOffset] == 0x78 && + processContext[remorse::usecodeContextOwnerSourceOffset + 1] == 0x56 && + processContext[remorse::usecodeContextOwnerSourceOffset + 2] == 0x34 && + processContext[remorse::usecodeContextOwnerSourceOffset + 3] == 0x12); + assert(processContext[remorse::usecodeContextParameterOffset] == 190 && + processContext[remorse::usecodeContextParameterOffset + 1] == 0 && + processContext[remorse::usecodeContextModeFlagsOffset] == 0x02 && + processContext[remorse::usecodeContextActiveFlagOffset] == 0 && + processContext[0x123] == 0xa5); + assert(!remorse::writeUsecodeContextFactoryFields(processContext.data(), + processContext.size() - 1, factoryFields)); + + std::vector code(remorse::usecodeEventBytecodeOffset, 0); + code.insert(code.end(), { + 0x0a, 0x07, + 0x0f, 0x02, 0x34, 0x12, + 0x5e, + 0x77, + 0x50 + }); + auto factoryTask = remorse::UsecodeProcessTask::create(4, 0x361, 0x0a, 0x1234, + std::vector(15, 0), 2, {}, contextParameter); + assert(factoryTask && factoryTask->interpreter.contextParameterOffset == 190 && + factoryTask->interpreter.valueStack[198] == 0xa1 && + factoryTask->interpreter.valueStack[202] == 0x34); + assert(factoryTask->readMappedItemWord(remorse::FarPtr16{0x0100, 0}) == 0x1234 && + !factoryTask->readMappedItemWord(remorse::FarPtr16{0x0100, 1}) && + !factoryTask->readMappedItemWord(remorse::FarPtr16{0x0101, 0})); + auto noItemTask = remorse::UsecodeProcessTask::create(5, 0x361, 0x0a, 0x1234, + std::vector(15, 0), 0); + assert(noItemTask && noItemTask->interpreter.stackTop == 0xcc && + !noItemTask->interpreter.contextParameterOffset); + auto task = remorse::UsecodeProcessTask::create(3, 0x361, 0x0a, 0x1234, + std::move(code)); + assert(task.has_value()); + assert(task->programCounter == remorse::usecodeEventBytecodeOffset); + const auto seededItem = task->interpreter.popWord(); + assert(seededItem.has_value() && *seededItem == static_cast(0x1234)); + assert(!task->interpreter.popWord().has_value()); + assert(task->interpreter.pushWord(0x1234)); + + remorse::UsecodeOpcodeServices services; + services.callIntrinsic = [](remorse::u16 ordinal, remorse::u8 argumentBytes, + const remorse::u8* arguments) -> std::optional { + assert(ordinal == 0x1234); + assert(argumentBytes == 2); + assert(arguments[0] == 7 && arguments[1] == 0); + return static_cast(0x5678); + }; + services.setInfo = [](remorse::u16 eventType, remorse::u16 sourceItem) { + return eventType == 7 && sourceItem == 0x5678; + }; + + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->interpreter.temporaryWord == 0x5678); + assert(task->step(services) == remorse::UsecodeStepResult::Advanced); + assert(task->step(services) == remorse::UsecodeStepResult::SetInfo); + const std::array expectedSetInfoOperands{0x5678, 7}; + assert(task->interpreter.lastSetInfoOperands == expectedSetInfoOperands); + assert(task->step(services) == remorse::UsecodeStepResult::Returned); + assert(task->halted); + const auto returnProgramCounter = task->programCounter; + assert(task->step(services) == remorse::UsecodeStepResult::Returned); + assert(task->programCounter == returnProgramCounter); + + remorse::UsecodeTaskRegistry registry; + assert(registry.add(std::move(*task))); + assert(registry.find(3) != nullptr); + assert(!registry.add(remorse::UsecodeProcessTask{})); + auto duplicateTask = remorse::UsecodeProcessTask::create(3, 0x361, 0x0a, 0x1234, + std::vector(15, 0)); + assert(duplicateTask.has_value()); + assert(!registry.add(std::move(*duplicateTask))); + assert(registry.remove(3)); + assert(registry.find(3) == nullptr); + return 0; +} \ No newline at end of file From 8c23bb02c9a4987dd3e7d99a1ff238cb876c7bc1 Mon Sep 17 00:00:00 2001 From: Maddo Date: Sun, 4 Oct 2026 18:29:58 +0200 Subject: [PATCH 09/14] Enhance Usecode handling with new structures and caching mechanisms - Introduced UsecodeSlotOwnerBuffers for managing descriptors and chunk states. - Added UsecodeSlotChunkCache class for efficient loading and unloading of event bodies. - Updated UsecodeClass to include extraSlotCount and adjusted related functions. - Implemented tests for new functionality, ensuring correct behavior of slot management and event loading. --- ...entity-vm-runtime-owner-resource-layout.md | 4 + docs/remorse-windows-rebuild-roadmap.md | 4 +- .../remorse/include/remorse/usecode_archive.h | 23 ++++ rebuild/remorse/src/usecode_archive.cpp | 128 ++++++++++++++++-- rebuild/remorse/tests/flex_archive_tests.cpp | 44 ++++++ 5 files changed, 188 insertions(+), 15 deletions(-) diff --git a/docs/entity-vm-runtime-owner-resource-layout.md b/docs/entity-vm-runtime-owner-resource-layout.md index 7f3b30c..07ce5ef 100644 --- a/docs/entity-vm-runtime-owner-resource-layout.md +++ b/docs/entity-vm-runtime-owner-resource-layout.md @@ -55,6 +55,8 @@ Live runtime-helper classification added during the 2026-04-05 MCP-upgrade pass: - obtains the chunk through `UProcess_1420_0000` using the owner-row offset/size, materializes it through the owner-resource helper, and caches the returned far pointer in the slot entry - marks the chunk present through the slot-local state arrays and updates the runtime-wide budget counters - `GetSlotChunkPtrAtOffset` (`1420:1d72`) returns that allocator-produced pointer plus the caller's intra-chunk offset; it does not expose a stable file/archive address +- `ReleaseSlotChunkRef` (`1420:1d8d`) decrements a positive chunk-state reference count and asserts on an unretained chunk +- `TryUnloadSlotChunk` (`1420:1e17`) unloads only a zero-count chunk, restores its saved source pointer, resets the state to `0xffff`, and removes its loaded-list record - `1420:1f24 entity_vm_runtime_apply_to_matching_owner_rows` - runtime-owned iterator over the owner list, used both for broad cleanup and for filtered slot/category work - `1420:2040 entity_vm_slot_entry_create_or_clear` @@ -137,6 +139,8 @@ The embedded interpreter initializes its stack limit to 199 bytes; the host boot The host opcode service currently maps segment `0` to the task's item-memory buffer through `UsecodeProcessTask::readMappedItemWord`; all other segments are rejected. This centralizes the existing fixture behavior but is not a general segmented address space. +`UsecodeClass` now reads the first header dword as the extra-slot count. `initializeUsecodeSlotOwnerBuffers` copies the six-byte descriptors from class `+0x14` into a host buffer of `0xc0 + 6 * extraSlotCount` bytes and creates `32 + extraSlotCount` state words initialized to `0xffff`, matching `InitSlotOwnerBuffers`; retail `EVENT` and `NPCTRIG` cover the base and one-extra-slot cases. `UsecodeSlotChunkCache` reads descriptors through this buffer, tracks ensure/release counts, and unloads only at count zero, restoring the state sentinel so a later ensure reloads the body. This remains an archive-backed host model: the 0x16-byte `UProcess_1420_0000` object, owner-helper materialization, runtime loaded-list record, and far-pointer allocation/restoration are not implemented. + Current caution: - context dispatch semantics are still active work, so this object should be modeled around lifecycle and data ownership first, not around final method names for every opcode-facing helper. diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 499ec8b..9be7b12 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -17,6 +17,7 @@ The exported files are evidence, not directly compilable game source. Keep them - Do not claim whole-game recompilation until startup, game ticks, interactions, mission flow, save/load, and presentation are driven by ported game code and playable on modern Windows using the original data. ## Source-Backed In-Game Vertical Slice +Current progress correction: the long progress paragraph below predates the latest selector change. `E` now walks `itemGrabSearchCandidates` in source order and queues the first candidate with an eligible `use` event; it does not select the nearest eligible item. This remains host-side selection, not the original `Item_Grab`/`Usecode_ItemCallEvent` dispatch. The immediate target is a fresh game on retail map 1 at the original starting teleporter, with an avatar owned by the ported item/NPC runtime, a tick and input path that actually drive that avatar, a changing world image, and at least one original-script-backed interaction. The current host-controlled sprite over a frozen map does **not** count. Keep the diagnostic traversal view separate while replacing its behavior; no DOSBox parity gate is required for this Windows milestone. @@ -712,8 +713,9 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat 4. Port the real timer process and NPC service implementations, then scheduler keyboard, active-group advancement, remaining sleep-completion dispatch and table-maintenance tails; compare deterministic process-order/state traces before connecting the Windows window. 5. Replace DOS file and memory APIs encountered by the ported chain with narrow host adapters; validate far-pointer/layout conversions against live evidence. 6. Port original movement and AreaSearch/collision behavior before promoting the host actor movement from stand-in to gameplay code. -7. Port `EnsureSlotChunkLoaded` (`1420:19fd`), its `UProcess_1420_0000` allocation and owner-helper materialization path, and the slot cache's far-pointer ownership. Then extend the host's segment-0 item-memory mapping to that runtime-owned code region, finish `CreateFromSlotIndex`/`Inter_1418_0244` context wiring, and execute one selected retail event with verified item/process side effects before connecting it to the window. Continue through original item/draw-list output, save/load, audio, and frontend chains for playable mission progression. +7. Complete runtime chunk materialization before context dispatch: extend the tested archive-backed `UsecodeSlotChunkCache` through `InitSlotOwnerBuffers`/`EnsureSlotChunkLoaded` (`1420:1866/19fd`), port the `0x16`-byte `UProcess_1420_0000` allocation and owner-helper materialization, then model loaded-list ownership, far-pointer restoration, release, and eviction. After that, map runtime-owned code into host VM memory, lift `CreateFromSlotIndex`/`Inter_1418_0244`, and execute a selected retail event with verified item/process side effects before connecting it to the window. Continue through original item/draw-list output, save/load, audio, and frontend chains for playable mission progression. ## Current Bottom Line +Runtime-cache progress correction: the host now models the extra-slot header, descriptor/state buffers, ensure/release counts, and archive-backed zero-count unload/reload. It still lacks `UProcess_1420_0000` allocation, owner-helper materialization, loaded-list ownership, and runtime far-pointer restoration; complete those prerequisites before far-address integration and the numbered context-dispatch action above. The project has a buildable diagnostic host, retail resource loaders, partial original scheduler scan, and owned Stand and item-process entries. The Windows diagnostic registry runs an item process bound to a staged retail map record, queues an eligible release body into the subset VM, and runs a Stand entry under the host tick. Retail tests demonstrate script-driven item-frame mutation. The `E` selector now iterates bounded, source-order candidates from `itemGrabSearchCandidates` (the modeled `Item_Grab` query) and queues the first candidate with an eligible `use` body, replacing its earlier nearest-distance choice. This is source-derived candidate selection, not original interaction dispatch: the window still constructs the item identity and queues the event body directly, and no visible before/input/after interaction is proven. The partial `CreateFromSlotIndex` slice writes the verified slot index (`+0x32`), value offset (`+0x34`), owner-source far pointer (`+0x11b`), mode byte (`+0x121`), and cleared parameter/active fields (`+0x11f/+0x122`) into the allocated 0x124-byte context. The VM bootstrap now copies the item parameter only for nonzero mode flags, then optional context bytes, reserves the four-byte saved-stack-pointer slot, and records the context-relative parameter offset; focused tests cover the ordering and zero-mode case. Real segment:offset pointer mapping, runtime code/owner-resource addresses, and embedded interpreter-context execution remain unported. `F` remains a separate release diagnostic. The original item cache/block IDs, full `Item_Grab`/`Usecode_ItemCallEvent`/`CreateFromSlotIndex` chain, real NPC ownership/services, nonempty-child teardown, DOS timer/keyboard interrupts, full scheduler, original startup/player chain, and renderer integration remain open. This is not a playable-game milestone; the next measure is mapping far addresses into the host VM and using them to execute one selected retail event through original context dispatch. diff --git a/rebuild/remorse/include/remorse/usecode_archive.h b/rebuild/remorse/include/remorse/usecode_archive.h index dc50820..4d7b136 100644 --- a/rebuild/remorse/include/remorse/usecode_archive.h +++ b/rebuild/remorse/include/remorse/usecode_archive.h @@ -11,16 +11,38 @@ namespace remorse { struct UsecodeClass { u32 classId = 0; std::string name; + u32 extraSlotCount = 0; u32 codeBase = 0; std::vector bytes; }; +struct UsecodeSlotOwnerBuffers { + std::vector descriptors; + std::vector chunkStates; +}; + struct UsecodeEventBody { u16 length = 0; u32 relativeOffset = 0; std::vector bytes; }; +class UsecodeSlotChunkCache { +public: + explicit UsecodeSlotChunkCache(UsecodeClass usecodeClass); + const UsecodeEventBody* ensureLoaded(u16 chunkIndex); + bool release(u16 chunkIndex) noexcept; + bool tryUnload(u16 chunkIndex) noexcept; + u16 inUseCount(u16 chunkIndex) const noexcept; + std::size_t chunkCount() const noexcept { return chunks_.size(); } + const UsecodeSlotOwnerBuffers& ownerBuffers() const noexcept { return ownerBuffers_; } + +private: + UsecodeClass usecodeClass_; + UsecodeSlotOwnerBuffers ownerBuffers_; + std::vector> chunks_; +}; + struct UsecodeClassBases { u16 regularShape = 0; u16 npc = 0; @@ -46,6 +68,7 @@ u16 selectUsecodeClassId(const UsecodeItemIdentity& item, const UsecodeClassBase std::optional> loadUsecodeOwnerRows(const FlexArchive& archive); bool ownerRowAllowsEvent(const std::vector& ownerRows, u16 classId, u32 eventMask); std::optional loadUsecodeClass(const FlexArchive& archive, u32 classId); +std::optional initializeUsecodeSlotOwnerBuffers(const UsecodeClass& usecodeClass); std::optional readUsecodeEventBody(const UsecodeClass& usecodeClass, u32 eventId); std::optional selectEligibleUsecodeEvent(const FlexArchive& archive, const std::vector& ownerRows, const UsecodeItemIdentity& item, diff --git a/rebuild/remorse/src/usecode_archive.cpp b/rebuild/remorse/src/usecode_archive.cpp index a8fd2c2..dfbdb3c 100644 --- a/rebuild/remorse/src/usecode_archive.cpp +++ b/rebuild/remorse/src/usecode_archive.cpp @@ -16,6 +16,29 @@ u32 readDword(const std::vector& bytes, std::size_t offset) (static_cast(bytes[offset + 2]) << 16) | (static_cast(bytes[offset + 3]) << 24); } +std::optional readEventBodyFromDescriptors(const UsecodeClass& usecodeClass, + const std::vector& descriptors, std::size_t descriptorOffset, u32 eventId) +{ + if (usecodeClass.codeBase < 20 || usecodeClass.codeBase > usecodeClass.bytes.size() || + eventId >= (usecodeClass.codeBase - 20) / 6 || + descriptorOffset > descriptors.size() || descriptors.size() - descriptorOffset < + static_cast(eventId) * 6 + 6) { + return std::nullopt; + } + const std::size_t row = descriptorOffset + static_cast(eventId) * 6; + const u16 length = readWord(descriptors, row); + const u32 offset = readDword(descriptors, row + 2); + if (length == 0 || offset == 0 || offset > usecodeClass.bytes.size() - usecodeClass.codeBase + 1) { + return std::nullopt; + } + const std::size_t start = usecodeClass.codeBase + static_cast(offset) - 1; + if (length > usecodeClass.bytes.size() - start) { + return std::nullopt; + } + return UsecodeEventBody{length, offset, + std::vector(usecodeClass.bytes.begin() + start, usecodeClass.bytes.begin() + start + length)}; +} + } // namespace u16 selectUsecodeClassId(const UsecodeItemIdentity& item, const UsecodeClassBases& bases) @@ -59,6 +82,7 @@ std::optional loadUsecodeClass(const FlexArchive& archive, u32 cla return std::nullopt; } const std::size_t nameOffset = 4 + static_cast(classId) * 13; + const u32 extraSlotCount = readDword(*bytes, 0); const u32 codeBase = readDword(*bytes, 8); if (codeBase < 20 || codeBase > bytes->size() || (codeBase - 20) % 6 != 0) { return std::nullopt; @@ -67,27 +91,103 @@ std::optional loadUsecodeClass(const FlexArchive& archive, u32 cla for (std::size_t index = 0; index < 9 && (*names)[nameOffset + index] != 0; ++index) { name.push_back(static_cast((*names)[nameOffset + index])); } - return UsecodeClass{classId, std::move(name), codeBase, std::move(*bytes)}; + return UsecodeClass{classId, std::move(name), extraSlotCount, codeBase, std::move(*bytes)}; +} + +std::optional initializeUsecodeSlotOwnerBuffers(const UsecodeClass& usecodeClass) +{ + constexpr std::size_t baseChunkCount = 0x20; + constexpr std::size_t baseDescriptorBytes = 0xc0; + constexpr std::size_t baseStateBytes = 0x40; + if (usecodeClass.codeBase < 20 || usecodeClass.codeBase > usecodeClass.bytes.size()) { + return std::nullopt; + } + + const std::size_t chunkCount = baseChunkCount + usecodeClass.extraSlotCount; + const std::size_t descriptorBytes = baseDescriptorBytes + + static_cast(usecodeClass.extraSlotCount) * 6; + const std::size_t stateBytes = baseStateBytes + + static_cast(usecodeClass.extraSlotCount) * 2; + if (chunkCount != (usecodeClass.codeBase - 20) / 6 || + descriptorBytes != chunkCount * 6 || stateBytes != chunkCount * 2 || + descriptorBytes > usecodeClass.bytes.size() - 20) { + return std::nullopt; + } + + UsecodeSlotOwnerBuffers buffers; + buffers.descriptors.assign(usecodeClass.bytes.begin() + 20, + usecodeClass.bytes.begin() + 20 + descriptorBytes); + buffers.chunkStates.assign(stateBytes / 2, 0xffff); + return buffers; } std::optional readUsecodeEventBody(const UsecodeClass& usecodeClass, u32 eventId) { - if (usecodeClass.codeBase < 20 || usecodeClass.codeBase > usecodeClass.bytes.size() || - eventId >= (usecodeClass.codeBase - 20) / 6) { - return std::nullopt; + return readEventBodyFromDescriptors(usecodeClass, usecodeClass.bytes, 20, eventId); +} + +UsecodeSlotChunkCache::UsecodeSlotChunkCache(UsecodeClass usecodeClass) + : usecodeClass_(std::move(usecodeClass)) +{ + auto buffers = initializeUsecodeSlotOwnerBuffers(usecodeClass_); + if (buffers) { + ownerBuffers_ = std::move(*buffers); + chunks_.resize(ownerBuffers_.chunkStates.size()); } - const std::size_t row = 20 + static_cast(eventId) * 6; - const u16 length = readWord(usecodeClass.bytes, row); - const u32 offset = readDword(usecodeClass.bytes, row + 2); - if (length == 0 || offset == 0 || offset > usecodeClass.bytes.size() - usecodeClass.codeBase + 1) { - return std::nullopt; +} + +const UsecodeEventBody* UsecodeSlotChunkCache::ensureLoaded(u16 chunkIndex) +{ + if (chunkIndex >= chunks_.size()) { + return nullptr; } - const std::size_t start = usecodeClass.codeBase + static_cast(offset) - 1; - if (length > usecodeClass.bytes.size() - start) { - return std::nullopt; + auto& body = chunks_[chunkIndex]; + auto& state = ownerBuffers_.chunkStates[chunkIndex]; + if (!body) { + if (state != 0xffff) { + return nullptr; + } + auto loadedBody = readEventBodyFromDescriptors(usecodeClass_, ownerBuffers_.descriptors, 0, chunkIndex); + if (!loadedBody) { + return nullptr; + } + chunks_[chunkIndex] = std::move(*loadedBody); + state = 1; + } else { + if (state >= 29999) { + return nullptr; + } + ++state; } - return UsecodeEventBody{length, offset, - std::vector(usecodeClass.bytes.begin() + start, usecodeClass.bytes.begin() + start + length)}; + return &*chunks_[chunkIndex]; +} + +bool UsecodeSlotChunkCache::release(u16 chunkIndex) noexcept +{ + if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] == 0xffff || + ownerBuffers_.chunkStates[chunkIndex] == 0) { + return false; + } + --ownerBuffers_.chunkStates[chunkIndex]; + return true; +} + +bool UsecodeSlotChunkCache::tryUnload(u16 chunkIndex) noexcept +{ + if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] != 0) { + return false; + } + chunks_[chunkIndex].reset(); + ownerBuffers_.chunkStates[chunkIndex] = 0xffff; + return true; +} + +u16 UsecodeSlotChunkCache::inUseCount(u16 chunkIndex) const noexcept +{ + if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] == 0xffff) { + return 0; + } + return ownerBuffers_.chunkStates[chunkIndex]; } std::optional selectEligibleUsecodeEvent(const FlexArchive& archive, diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index 0d04ad6..b020a0f 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -48,9 +48,53 @@ int main() assert(retailOwnerRows && retailOwnerRows->size() % 13 == 0); const auto eventClass = remorse::loadUsecodeClass(*usecode, 0x361); assert(eventClass && eventClass->name == "EVENT" && eventClass->codeBase == 0xd4); + assert(eventClass->extraSlotCount == 0); + const auto eventOwnerBuffers = remorse::initializeUsecodeSlotOwnerBuffers(*eventClass); + assert(eventOwnerBuffers && eventOwnerBuffers->descriptors.size() == 0xc0 && + eventOwnerBuffers->chunkStates.size() == 32); + assert(std::all_of(eventOwnerBuffers->chunkStates.begin(), eventOwnerBuffers->chunkStates.end(), + [](remorse::u16 state) { return state == 0xffff; })); + assert(std::equal(eventOwnerBuffers->descriptors.begin(), eventOwnerBuffers->descriptors.end(), + eventClass->bytes.begin() + 20)); + const auto npcTriggerClass = remorse::loadUsecodeClass(*usecode, 0x363); + assert(npcTriggerClass && npcTriggerClass->name == "NPCTRIG" && + npcTriggerClass->extraSlotCount == 1 && npcTriggerClass->codeBase == 0xda); + const auto npcTriggerOwnerBuffers = remorse::initializeUsecodeSlotOwnerBuffers(*npcTriggerClass); + assert(npcTriggerOwnerBuffers && npcTriggerOwnerBuffers->descriptors.size() == 0xc6 && + npcTriggerOwnerBuffers->chunkStates.size() == 33); + assert(std::all_of(npcTriggerOwnerBuffers->chunkStates.begin(), npcTriggerOwnerBuffers->chunkStates.end(), + [](remorse::u16 state) { return state == 0xffff; })); + assert(std::equal(npcTriggerOwnerBuffers->descriptors.begin(), npcTriggerOwnerBuffers->descriptors.end(), + npcTriggerClass->bytes.begin() + 20)); + auto inconsistentOwnerHeader = *eventClass; + inconsistentOwnerHeader.extraSlotCount = 1; + assert(!remorse::initializeUsecodeSlotOwnerBuffers(inconsistentOwnerHeader)); const auto eventBody = remorse::readUsecodeEventBody(*eventClass, 0x0a); assert(eventBody && eventBody->length == 0x1fd6 && eventBody->relativeOffset == 1); assert(eventBody->bytes.size() == 0x1fd6 && eventBody->bytes.front() == eventClass->bytes[0xd4]); + remorse::UsecodeSlotChunkCache eventChunkCache(*eventClass); + assert(eventChunkCache.chunkCount() == 32); + const auto* loadedEventChunk = eventChunkCache.ensureLoaded(0x0a); + assert(loadedEventChunk && loadedEventChunk->bytes == eventBody->bytes && + eventChunkCache.inUseCount(0x0a) == 1); + const auto* reusedEventChunk = eventChunkCache.ensureLoaded(0x0a); + assert(reusedEventChunk == loadedEventChunk && eventChunkCache.inUseCount(0x0a) == 2); + assert(eventChunkCache.release(0x0a) && eventChunkCache.inUseCount(0x0a) == 1); + assert(!eventChunkCache.tryUnload(0x0a)); + assert(eventChunkCache.release(0x0a) && eventChunkCache.inUseCount(0x0a) == 0); + assert(!eventChunkCache.release(0x0a)); + assert(eventChunkCache.tryUnload(0x0a)); + assert(eventChunkCache.ownerBuffers().chunkStates[0x0a] == 0xffff); + const auto* reloadedEventChunk = eventChunkCache.ensureLoaded(0x0a); + assert(reloadedEventChunk && reloadedEventChunk->bytes == eventBody->bytes && + eventChunkCache.inUseCount(0x0a) == 1); + assert(eventChunkCache.release(0x0a) && eventChunkCache.inUseCount(0x0a) == 0); + for (remorse::u32 acquiredReferences = 0; acquiredReferences < 29999; ++acquiredReferences) { + assert(eventChunkCache.ensureLoaded(0x0a) == reloadedEventChunk); + } + assert(eventChunkCache.inUseCount(0x0a) == 29999); + assert(eventChunkCache.ensureLoaded(0x0a) == nullptr && eventChunkCache.inUseCount(0x0a) == 29999); + assert(eventChunkCache.ensureLoaded(0x20) == nullptr && eventChunkCache.inUseCount(0x20) == 0); assert(!remorse::readUsecodeEventBody(*eventClass, 0x20)); assert(!remorse::loadUsecodeClass(*usecode, usecode->entryCount)); auto truncated = *eventClass; From 0771c86043dcda05fa407f927d4c70e52d2e8a8f Mon Sep 17 00:00:00 2001 From: Maddo Date: Mon, 5 Oct 2026 21:50:41 +0200 Subject: [PATCH 10/14] Refactor usecode task management and enhance teleportation logic - Improved the queueUsecodeTask function to streamline process termination and context management. - Added robust error handling for event context creation and memory writing. - Enhanced the loadSceneAsync function to better handle avatar teleportation, including a new teleporter process. - Expanded entity dispatch tests to cover movement and teleporter processes, ensuring correct behavior under various conditions. - Introduced new tests for usecode runtime memory allocation and context creation, validating edge cases and error handling. - Updated flex archive tests to ensure proper loading and unloading of usecode slot chunk caches. --- ...entity-vm-runtime-owner-resource-layout.md | 12 +- docs/remorse-windows-rebuild-roadmap.md | 232 ++--------------- .../include/remorse/entity_dispatch_entry.h | 18 ++ .../remorse/include/remorse/usecode_archive.h | 55 +++- rebuild/remorse/include/remorse/usecode_vm.h | 50 +++- rebuild/remorse/src/entity_dispatch_entry.cpp | 52 +++- rebuild/remorse/src/usecode_archive.cpp | 224 ++++++++++++++++- rebuild/remorse/src/usecode_vm.cpp | 237 +++++++++++++++++- rebuild/remorse/src/windowed_game_main.cpp | 69 +++-- .../tests/entity_dispatch_entry_tests.cpp | 96 +++++++ rebuild/remorse/tests/flex_archive_tests.cpp | 202 ++++++++++++++- rebuild/remorse/tests/usecode_vm_tests.cpp | 91 +++++++ 12 files changed, 1088 insertions(+), 250 deletions(-) diff --git a/docs/entity-vm-runtime-owner-resource-layout.md b/docs/entity-vm-runtime-owner-resource-layout.md index 07ce5ef..94a4a5e 100644 --- a/docs/entity-vm-runtime-owner-resource-layout.md +++ b/docs/entity-vm-runtime-owner-resource-layout.md @@ -133,13 +133,21 @@ Current layout claims that matter for class lifting: - `+0x117/+0x119` cache the owner-linked source pair - `+0x123` behaves as a busy or active flag in the sync/dispatch path -`CreateFromSlotIndex` initializes the embedded interpreter, copies the item parameter only when mode flags are nonzero, copies optional `ucparam` bytes into the backward-growing stack, then reserves four bytes for the prior stack pointer when both are present. The host VM models this order and the `+0x11f` relative offset, but does not synthesize the original segment:offset pointer or map the runtime-owned code and owner buffers yet. +`CreateFromSlotIndex` initializes the embedded interpreter, copies the item parameter only when mode flags are nonzero, copies optional `ucparam` bytes into the backward-growing stack, then reserves four bytes for the prior stack pointer when both are present. `createUsecodeContext` now builds a bounded host context from caller-supplied runtime pointers: it allocates the `0x124` process body and `0x82` call-stack buffer, maps code/owner pointers through `UsecodeRuntimeMemory`, writes the interpreter's stack/base/limit fields, copies only the active stack window, stores the saved pointer at the recovered relative location, and seeds the initial far-call pair. Invalid source ranges and stack overflow fail before leaving partial allocations. `usecode_vm_tests` checks the process bytes, pointer ranges, parameter ordering, call-stack bytes, and cleanup. + +`createUsecodeEventContext` adds the retail owner-row and event-slot inputs. `UsecodeTaskRegistry::addWithContext` owns the resulting context allocations for the task lifetime. The window use-request path now searches nearby item candidates, selects an eligible event through the owner rows, creates the context-backed task, writes its process ID output word, and copies the context bytes into the owned process entry. The retail BOX_NS test exercises candidate-driven selection and VM execution through injected item/timer services; it verifies frame/render changes and releases all context allocations on task removal. + +This is still host-side selection and execution, not the original `Usecode_ItemCallEvent` dispatcher or proven `CreateFromSlotIndex` call chain. The exact runtime meaning of the initial slot/value-add call-frame pair remains unverified, as do original owner-resource callback parity and general far-pointer dispatch. The embedded interpreter initializes its stack limit to 199 bytes; the host bootstrap rejects a combined initial item/context payload and saved-pointer slot above that limit. The host opcode service currently maps segment `0` to the task's item-memory buffer through `UsecodeProcessTask::readMappedItemWord`; all other segments are rejected. This centralizes the existing fixture behavior but is not a general segmented address space. -`UsecodeClass` now reads the first header dword as the extra-slot count. `initializeUsecodeSlotOwnerBuffers` copies the six-byte descriptors from class `+0x14` into a host buffer of `0xc0 + 6 * extraSlotCount` bytes and creates `32 + extraSlotCount` state words initialized to `0xffff`, matching `InitSlotOwnerBuffers`; retail `EVENT` and `NPCTRIG` cover the base and one-extra-slot cases. `UsecodeSlotChunkCache` reads descriptors through this buffer, tracks ensure/release counts, and unloads only at count zero, restoring the state sentinel so a later ensure reloads the body. This remains an archive-backed host model: the 0x16-byte `UProcess_1420_0000` object, owner-helper materialization, runtime loaded-list record, and far-pointer allocation/restoration are not implemented. +`UsecodeClass` now reads the first header dword as the extra-slot count. `initializeUsecodeSlotOwnerBuffers` copies the six-byte descriptors from class `+0x14` into a host buffer of `0xc0 + 6 * extraSlotCount` bytes and creates `32 + extraSlotCount` state words initialized to `0xffff`, matching `InitSlotOwnerBuffers`; retail `EVENT` and `NPCTRIG` cover the base and one-extra-slot cases. + +`UsecodeSlotChunkCache` now models the verified `UProcess_1420_0000` layout as a 0x16-byte record: a 16-bit vtable offset, previous/next far links at `+0x02/+0x06`, chunk-buffer far pointer at `+0x0a`, saved source pair at `+0x0e`, and slot/chunk indices at `+0x12/+0x14`. The host allocates a bounded segment for each process and chunk buffer, initializes the chunk buffer to `0xff`, copies the archive-backed body, replaces the descriptor's source pair with the buffer pointer, and links the process at the loaded-list head. On zero-count eviction it restores the saved source pair, resets state to `0xffff`, unlinks both neighbors, and releases both allocations. Retail `EVENT`/`NPCTRIG` tests and a synthetic two-node list cover reuse, eviction, pointer restoration, and list unlinking. + +`UsecodeRuntimeMemory` currently assigns one bounded region per nonzero segment, with at most 64 KiB per allocation and range-checked reads/writes. This is host address-space scaffolding, not a recovered DOS allocator. Materialization reads from the loaded `UsecodeClass` byte buffer; the original `EntityVmOwnerResource` callback and live runtime allocation/address parity remain unverified. Current caution: diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 9be7b12..548fb34 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -17,9 +17,7 @@ The exported files are evidence, not directly compilable game source. Keep them - Do not claim whole-game recompilation until startup, game ticks, interactions, mission flow, save/load, and presentation are driven by ported game code and playable on modern Windows using the original data. ## Source-Backed In-Game Vertical Slice -Current progress correction: the long progress paragraph below predates the latest selector change. `E` now walks `itemGrabSearchCandidates` in source order and queues the first candidate with an eligible `use` event; it does not select the nearest eligible item. This remains host-side selection, not the original `Item_Grab`/`Usecode_ItemCallEvent` dispatch. - -The immediate target is a fresh game on retail map 1 at the original starting teleporter, with an avatar owned by the ported item/NPC runtime, a tick and input path that actually drive that avatar, a changing world image, and at least one original-script-backed interaction. The current host-controlled sprite over a frozen map does **not** count. Keep the diagnostic traversal view separate while replacing its behavior; no DOSBox parity gate is required for this Windows milestone. +The immediate target is a fresh game on retail map 1 at the original starting teleporter, with an avatar owned by the ported item/NPC runtime, a tick and input path that actually drive that avatar, a changing world image, and at least one original-script-backed interaction. The current host item/process movement and live-item rendering are useful verified steps, but do **not** count as the original loop or interaction. Keep the diagnostic traversal view separate while replacing its behavior; no DOSBox parity gate is required for this Windows milestone. 1. **Startup and spawn:** port the fresh-game branch of `Game_Start` (`1020:0000`) through `Teleporter_CreateProcessDirect(1, 0x1e, 1)` and its placement callee. Resolve egg `0x1e` from original map data, not from the map bounds, and prove its coordinates and the spawned avatar/item ID in a retail-data test. Do not implement intro movies, main menu, save loading, or warp overrides for this slice. 2. **Live world ownership:** initialize the original item cache and NPC/avatar state for that map. The displayed avatar must be the same numbered, mutable item advanced by the process runtime; reject a separately drawn or separately positioned stand-in. @@ -28,13 +26,7 @@ The immediate target is a fresh game on retail map 1 at the original starting te 5. **Real interaction:** implement one reachable map-1 usecode event through the original item find/grab, VM dispatch, and resulting world-state mutation. Demonstrate a repeatable before/input/after trace and visible effect; a script lookup or release-request counter is not an interaction. 6. **Acceptance:** launch the normal Windows executable with retail data, start map 1 at egg `0x1e`, move and interact without a diagnostic shortcut, and verify on-screen state plus a deterministic integration test. Keep absent combat, audio, menus, persistence, and broader missions listed as limitations, not silently simulated features. -Progress: the map-1 fixed-map test identifies one family-8/frame-1 item with low quality byte `0x1e` (the teleporter's item-search predicate); startup centers on that egg instead of the map-bounds midpoint. The live item owner reserves avatar item `1` with defaults from `NPC_Init` (`10e8:000c`) and applies the coordinate/map write from `NPC_Teleport` (`10e8:29f2`). Win32 directional events now pass through the kernel keyboard queue to a registered controller entry; an owned `AnimPrimitiveProcess` advances the avatar item on 40 Hz host ticks. A cached map renderer redraws snapshots of mutable map items in source sorter order on a worker thread, while the avatar pose is still drawn in a separate screen overlay. Fast-area GLOB eggs now hatch into numbered live children using the `1098:039c` placement/status rules; the renderer replaces a hatched egg's preview expansion with those items. The interpreter's initial stack and 31-entry code-address stack are compiled and tested against exported `1418:00e8/0244/0000`; the host VM executes a tested opcode subset and task lifecycle. Retail-data tests execute `CARD_NS` spawning `SWITCH` and the `BOX_NS` timer chain through a changed live item frame and rendered scene. The Windows host queues a selected retail release-event body from the item-process callback and reports its task state, but this remains diagnostic: `F` host-selects the nearby item, the original `Item_Grab`/`Usecode_ItemCallEvent` dispatch is not ported, and `E` starts a nearest eligible use event through host selection. The task bytecode offset is now named `usecodeEventBytecodeOffset` (`0x0e`) and verified against raw `CARD_NS`, `BOX_NS`, and `RECHFLNS` bodies: each has a 14-byte prefix followed by opcode `0x0b`; Ghidra shows the selected event chunk pointer is passed with intra-chunk offset zero. The prefix field meanings remain untyped. These are partial translations of steps 1-5, **not completed milestones**: `Game_Start` (`1020:0000`), teleporter scheduling, complete item cache, controller actions beyond directional movement, original camera/draw-list integration, and original USECODE event dispatch remain open. Collision is approximate; no normal-input, end-to-end interaction acceptance exists. Steps 5-6 remain open. - -Retail map-1 probing at the starting egg found four children after fast-area GLOB hatching and no eligible `use` script on those children; no direct fixed-map item within 1,024 staged units has an eligible event body. The nearest direct `use` items are panel/card objects roughly 8,800 staged units away. Their event bodies delegate to `TRIGGER.slot_20` or `SWITCH.slot_21`, which require additional VM, timer, selector, and world-state services. A renderer regression confirms that moving hatched children changes live scene pixels, but this is not script execution or proof that those distant interactions are reachable through the current collision path. - -Control-path evidence for step 3: live `CRUSADER.EXE` disassembly at `1130:224b-226a` compares event selectors against the five words at `1130:273b` (`1, 2, 4, 0x10, 0x100`); the matching CS jump-table words at `1130:274f` target `226e, 2276, 22b6, 22bd, 22b6`. The gameplay-key case at `1130:22bd` copies all 12 bytes of the incoming key event. The exported `Controller_HandleKeyEvent` pseudo-C contains an invalid branch after this table and must not be compiled verbatim. The 32-slot, 12-byte pending-key ring (`11d0:3533/3ad4/3a74/3aad`) and a registered-subscriber dispatch (`11d0:3c4d`) are ported in `ProcessKernel`; tests cover order, full/overflow, wrap, and delivery to a controller entry rather than the excluded keyboard process. The 0x40-byte controller entry mirrors the keyboard registration and daemon/update flags of `ControllerProcess_CreateProcess` (`1130:00e3`), **but the window does not create it or feed its queue**. `Controller_PickNextAnimByKeyevent` (`1130:12d6`) reads two keyboard state arrays through `Keyboard_GetKeyState` (`11d0:39b9`, DS offsets `3652` and `3352`) and selects animation through NPC state and services. `Kernel_11d0_39fb` installs the DOS interrupt-9 keyboard path through `FUN_1218_059b`; exported C exposes the arrays' reads/resets but not their hardware writer. Recover the key-state update semantics from the interrupt path and port the controller's reachable movement branches before replacing host polling; do not guess their edge/held meaning. - -Animation dependency for step 3: live disassembly at `1130:1eda-1ef0` supplies `NPC_DoAnim` (`10e8:0252`) with the controlled NPC item pointer, animation number, direction, and two zero arguments that the exported controller pseudo-C omits. The unarmed walk/run cases allocate `AnimPrimitiveProcess` (`1150:0000`, size `0x5b`); live disassembly at `1150:0033-009c` confirms its normal vtable offset `0x2a57`, event type `0xf0`, and linear-capable setup. A kernel-owned constructor with this layout, item/type registration, direction, and clip metadata now has a byte-level test. `AnimPrimitive_SetStartFrame` (`1150:17b2`) is ported and tested for two-step/looping and controlled-avatar frame-skip branches. Its tick (`1150:1906`) still needs NPC animation-frame state, fast-area/collision behavior, item updates, transitions, and teardown. The Windows host frame counter is not this process. Finish the tick and collision result before swapping the default control path. +Current blocker: the normal host window resolves egg `0x1e` from map 1 and places host item 1 at that retail record, then routes queued input through host controller and animation processes that mutate the same live item. These are tested host models, not calls through `Game_Start`, `Teleporter_CreateProcessDirect`, or the original kernel loop. A test using the production-equivalent item search at the egg spawn found one candidate and no eligible `use` event. The BOX_NS effect test therefore still uses a fixture origin; a reachable target and original item/event dispatch remain open. Nearby panel/card scripts also require additional VM, timer, selector, and world-state services. ## Current Inputs @@ -43,62 +35,9 @@ Animation dependency for step 3: live disassembly at `1130:1eda-1ef0` supplies ` - `exports/src_remorse/functions/` contains split function bodies, including class-like folders such as `Remorse/EntityDispatchEntry`, `Remorse/SpriteNode`, `Remorse/EntityVmRuntime`, and related process families. - Existing rebuild planning is in `docs/remorse-cpp-decompilation-plan.md`, `docs/remorse-rebuild-abi-notes.md`, and `docs/remorse-cpp-compatibility-header-draft.md`. -## First Concrete Scaffold +## Rebuild Scaffold -The first host rebuild scaffold is now under `rebuild/remorse/`. - -It is deliberately separate from `exports/src_remorse/` because the export is generated, ignored by git, and still contains syntax and ABI artifacts that modern compilers cannot accept wholesale. - -Current scaffold files: - -- `rebuild/remorse/CMakeLists.txt`: CMake target for a Windows-friendly C++17 executable named `remorse_rebuild`. -- `rebuild/remorse/build_msvc.cmd`: repeatable MSVC/CMake build, test, and harness-run command. -- `rebuild/remorse/include/remorse/combat_tactics.h`: typed reader for `COMBAT.DAT` tactic records. -- `rebuild/remorse/include/remorse/compat.h`: exact-width aliases, far-pointer placeholders, packing macros, and calling-convention marker macros. -- `rebuild/remorse/include/remorse/export_prelude.h`: temporary bridge types for staged Ghidra-export imports. -- `rebuild/remorse/include/remorse/entity_dispatch_entry.h`: first hand-maintained class-family skeleton, anchored to the `11e0:0000` / older `0008:ba00` allocation evidence. -- `rebuild/remorse/include/remorse/file_system.h`: first host file/path discovery shim for replacing DOS install-path assumptions. -- `rebuild/remorse/include/remorse/flex_archive.h`: standard FLEX archive directory parser. -- `rebuild/remorse/include/remorse/fixed_map.h`: typed `FIXED.DAT` map table and 16-byte item-record reader. -- `rebuild/remorse/include/remorse/glob_archive.h`: typed `GLOB.FLX` object-entry reader. -- `rebuild/remorse/include/remorse/map_renderer.h`: first dependency-free map preview renderer and BMP writer. -- `rebuild/remorse/include/remorse/palette.h`: first game-data parser for 256-color RGB palette files. -- `rebuild/remorse/include/remorse/runtime.h`: minimal runtime/export-manifest surface. -- `rebuild/remorse/include/remorse/shape_archive.h`: typed `SHAPES.FLX` shape-frame parser and row-RLE decoder. -- `rebuild/remorse/include/remorse/animation_archive.h`: bounds-checked raw `ANIM.DAT` lookup, direction/frame metadata, sprite-frame and flip extraction, and authored movement-step decoding. -- `rebuild/remorse/include/remorse/collision.h`: TYPEFLAG-sized collision volumes, swept movement query, and fixed-map/GLOB solid-volume extraction. -- `rebuild/remorse/include/remorse/type_flags.h`: typed `TYPEFLAG.DAT` shape-family and flag decoder. -- `rebuild/remorse/src/combat_tactics.cpp`: parses tactic names, four block offsets, and bytecode payloads from `COMBAT.DAT` entries. -- `rebuild/remorse/src/collision.cpp`: builds conservative solid volumes from fixed-map records and expanded glob children, then sweeps the player footpad against them. -- `rebuild/remorse/src/entity_dispatch_entry.cpp`: partial source translation of process lifecycle, the `11d0:0255` scan and `11d0:0445/19b5` post-scan group selection, `Process_Sleep`/`Unlink`, the 0x42-byte Stand constructor fields, `StandProcess::Run` (`1100:0359`), a kernel-owned SystemTimer constructor/counter (`11c0:0000/00f8`), and partial Keyboard/KeyDaemon registration. The harness executes the NPC decision tree through host services and delivers timer events explicitly; real NPC data, timer interrupts/rescheduling, original keyboard queue/player input, and complete game tick remain unported. -- `rebuild/remorse/src/file_system.cpp`: repository/retail data-root discovery using modern `std::filesystem`. -- `rebuild/remorse/src/flex_archive.cpp`: loader for count-at-`0x54`, table-at-`0x80` FLEX archives. -- `rebuild/remorse/src/fixed_map.cpp`: loader for `FIXED.DAT` map tables and scaled fixed-map item coordinates. -- `rebuild/remorse/src/glob_archive.cpp`: parser for glob object entry lists inside `GLOB.FLX`. -- `rebuild/remorse/src/map_preview_main.cpp`: command-line preview executable for writing a viewable BMP image. -- `rebuild/remorse/src/windowed_game_main.cpp`: native Windows game shell, with async retail map/player/collision loading, shape-1 stand/walk/run sprites, metadata-driven 8-way movement, a following camera, and a position HUD. -- `rebuild/remorse/src/map_renderer.cpp`: combines fixed maps, glob expansion, typeflags, shape frames, and palette data into a painted preview image. -- `rebuild/remorse/src/palette.cpp`: `GAMEPAL.PAL`-style 768-byte palette parser. -- `rebuild/remorse/src/runtime.cpp`: loads a summary from the Ghidra export manifest. -- `rebuild/remorse/src/shape_archive.cpp`: ports the documented Crusader frame-table and row-RLE decode rules. -- `rebuild/remorse/src/animation_archive.cpp`: parses shape-indexed animation tables and direction-major frame metadata from raw `ANIM.DAT`. -- `rebuild/remorse/src/type_flags.cpp`: ports the verified 9-byte Crusader typeflag decode from the map-rendering tool. -- `rebuild/remorse/src/main.cpp`: starts the host harness and prints the export status. -- `rebuild/remorse/tests/combat_tactics_tests.cpp`: checks `COMBAT.DAT` parses to 14 tactics and entry 0 is `Dumb`. -- `rebuild/remorse/tests/entity_dispatch_entry_tests.cpp`: checks entry offsets, group counters, ID assignment, 30-slot growth, lifecycle, scheduler gates/spawn/cleanup, sleep writes, strict wake deadline, the owned Stand layout, NPC-gated `Run` branches, and timer-counter carry. -- `rebuild/remorse/tests/file_system_tests.cpp`: first host-side check that the current repository root can be recognized as a game-data root. -- `rebuild/remorse/tests/flex_archive_tests.cpp`: checks `STATIC/COMBAT.DAT` as a small FLEX archive with 14 populated records. -- `rebuild/remorse/tests/fixed_map_tests.cpp`: checks `STATIC/FIXED.DAT` map count and map 0 item-record loading. -- `rebuild/remorse/tests/glob_archive_tests.cpp`: checks `STATIC/GLOB.FLX` parses into at least one populated glob object. -- `rebuild/remorse/tests/map_renderer_tests.cpp`: checks map 1 can produce a non-empty preview image. -- `rebuild/remorse/tests/palette_tests.cpp`: checks that `STATIC/GAMEPAL.PAL` parses into 256 colors. -- `rebuild/remorse/tests/shape_archive_tests.cpp`: checks `STATIC/SHAPES.FLX` can decode at least one visible frame. -- `rebuild/remorse/tests/animation_archive_tests.cpp`: checks ANIM.DAT parsing, signed displacement and direction rotation, sprite-frame/flip decoding, and retail shape-1 stand/walk/run references. -- `rebuild/remorse/tests/collision_tests.cpp`: checks TYPEFLAG extents, swept obstruction, vertical clearance, flipped footprints, and fixed-map/GLOB placement extraction. -- `rebuild/remorse/tests/type_flags_tests.cpp`: checks `STATIC/TYPEFLAG.DAT` parses 2,048 shape records and includes glob-family records. -- `rebuild/remorse/tools/import_export_slice.py`: stages one exported function folder into `rebuild/remorse/imported/` for manual cleanup review. - -This is not the game yet. It is a buildable diagnostic host with a source-backed itemless process lifecycle, one-pass scheduler scan and post-scan active-group selection, owned Stand process layout, and recovered Stand `Run`/NPC decision and timer-counter branches. It does not have the original NPC service data, DOS timer delivery, keyboard event queue, or game loop. +`rebuild/remorse/` contains the MSVC/CMake build, retail-data readers, diagnostic map/window, partial process/item/USECODE runtime, and focused tests. These are host infrastructure and partial source ports, not a playable game; subsystem documents retain detailed implementation evidence. ## Why The Export Does Not Compile Yet @@ -130,63 +69,6 @@ It can replace DOS extender, VGA, sound, input, timing, file, and memory service For the stated goal of running on modern Windows, Track B is the practical primary track. Track A should still guide early type cleanup so the port does not accidentally erase evidence. -## Conversion Strategy - -1. Keep `exports/src_remorse/` as generated evidence; keep a function-address ledger of what was translated, what is still a stand-in, and which callers actually execute the translation. -2. Move one original call chain at a time into `rebuild/remorse/` as minimally corrected C/C++ with a documented address mapping and tests for the observed side effects. -3. Compile every moved slice immediately, even before it is runnable game logic. -4. Replace Ghidra pseudo-types with `remorse::u8`, `remorse::u16`, `remorse::u32`, `remorse::FarPtr16`, and explicit packed structs. -5. Convert Ghidra calling-convention tokens into marker macros from `compat.h` until the final host calling surface is chosen. -6. Keep raw address provenance in comments or mapping tables for every imported function. -7. Implement host runtime shims at the DOS/hardware call boundaries encountered by the ported chain; avoid duplicating game logic in the shim. -8. Validate recovered behavior with binary evidence, retail resources, and deterministic trace/state comparisons; connect each port to its caller in the Windows runtime. - -## Full Rebuild Plan - -The practical target is Track B: recompile recovered game logic for Windows and replace the DOS platform boundary. Track A remains an evidence constraint for layout, calling convention, far-pointer provenance, and validation. The phases below describe supporting capabilities, not permission to implement an independent game first: prioritize ported startup -> tick -> player/item process -> renderer/interaction call chains over further standalone host features. - -### Phase 0: Build And Evidence Discipline - -Goal: every step builds, runs tests, and keeps provenance visible. - -Exit criteria: - -- `rebuild\remorse\build_msvc.cmd Debug` passes from the repository root -- every imported subsystem has address/source provenance in code or docs -- generated Ghidra exports remain input evidence, not hand-edited source -- at least one corrected exported function is compiled, tested against its documented side effects, and invoked by a host caller; list remaining placeholder behavior explicitly - -### Phase 1: Host Runtime Foundation - -Goal: replace DOS installation assumptions with modern host services. - -Work: - -- game-data root discovery -- case-insensitive path resolution -- binary reads -- DOS-style file-handle facade -- writable config/save/user-data root -- command-line and config parsing -- logging and fatal-error reporting - -Exit criteria: the harness can find data, open/read assets through the same facade future game code will use, and write test save/config output outside the read-only retail data root. - -### Phase 2: Core Resource Loaders - -Goal: typed loaders for the files needed before gameplay can start. - -Work: - -- palettes: `GAMEPAL.PAL`, misc palettes, palette transforms -- FLEX archives: `COMBAT.DAT`, `GLOB.FLX`, `SHAPES.FLX`, `EUSECODE.FLX`, fonts/gumps/icons -- maps: `FIXED.DAT`, glob expansion, type flags -- shapes: Crusader frame directory and RLE decode -- usecode archive chunk discovery - -Exit criteria: a smoke test can load one map, expand globs, decode referenced shapes, and produce an in-memory scene without executing gameplay. - -### Phase 3: Minimal Renderer Goal: put a real Crusader world image on screen on Windows. @@ -298,25 +180,12 @@ Work: Exit criteria: a clean checkout/build can run against a retail data directory with documented setup steps. -## Current Execution Focus +## Historical Implementation Evidence -The current active work must shift from Phase 3 host presentation to decompiled source conversion and call-chain integration (Phases 0 and 4). Core Phase 2 loaders, the footpad-aware overlap sorter, and the Windows map window are diagnostic infrastructure. The actor uses retail stand/walk/run metadata, authored XYZ displacements, and the original 16-way direction table, but its 20 Hz host tick, conservative TYPEFLAG collision, and fixed-map boundary are not the recovered player process or original AreaSearch. Floor support, step-up/ledge handling, moving items, interactions, and USECODE remain unported. Keep the window as a test host, not as the implementation template for game logic. - -First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a8` (older `0008:bca8`) validates 1..31, updates the group byte at `+0x08`, and adjusts 16-bit counters through the far table pointer at `DS:39c5`. Live disassembly confirms the entry far pointer at `[BP+6]`, group byte at `[BP+0xa]`, and word-sized counter operations; the decompiler's `_group_id` alias is not a real implicit argument. The host receives the entry and table explicitly. `InitBase` at `11e0:0000` stamps the function-table words `0x3b06` (`+0x00`), `0x2d10` (`+0x1e`), `0x3afe` (`+0x28`), initializes the observed scalars, and seeds the group through `SetGroupId`. The seed comes from `DS:39c9` (written by `Kernel_11d0_19b5`); the host receives it as explicit runtime state. The unknown `+0x09` is not deliberately written. The host-owned path performs allocate -> initialize -> register, records default name/new-process metadata, executes the conditional current-process extflag branch, and applies the post-registration sync predicate. Itemless termination and slot reclamation are present. The scheduler scan applies normal-process group/flag gates and timer wake logic at `11d0:0255`, and its callback invokes the compiled `StandProcess::Run` branch for the 0x42-byte host-owned Stand entry. The `1100:026e` NPC decision gates are compiled, with their item/visibility/activity operations passed through host services. Owned Stand entries now maintain the per-item presence bit; the kernel-owned timer and keyboard constructors register their diagnostic processes. This is **not** a complete constructor or process system: stack-segment assertion, nonempty item child teardown, NPC service implementations, DOS timer/keyboard event delivery, end-of-pass work, other process `Run` functions, and far-memory behavior remain absent. Kernel-owned source/type transitions and active-group increment now have focused coverage, but the static source/type setters still lack item-cache context; runtime binary parity is not established. - -### Process Source-Port Ledger +Partial process and item ports below are retained as technical evidence, not as the active work order. Follow **Near-Term Next Actions** for current priorities. | Exported function | Compiled status | Evidence and remaining boundary | |---|---|---| -| `SetGroupId@11e0_02a8.c` (`0008:bca8`) | Partial translation; invoked from host `InitBase`, CTest transitions and invalid IDs | Live `11e0:02ae-031b`: group byte parameter at `[BP+0xa]`, far entry pointer at `[BP+6]`, 2-byte counter stride via `DS:39c5`, overwrite entire `+0x08` byte when changing group. Host exception replaces `AssertError`; counter-table ownership and runtime trace still need verification. | -| `IncrementGroupId@11e0_0405.c` | Group increment, current-active-group assertion, and 29-to-30 rejection translated; harness and CTest invoke it | Live `11e0:040b-0466` masks the group byte to five bits, checks next group `< 30` and `DS:39c9 == old group`, then calls `SetGroupId` and `Kernel_11d0_19b5`. The host passes the owning kernel and group counts explicitly; assertions become exceptions, without a DOS runtime trace. | -| `SetSourceType@11e0_01b6.c`, `SetEventTypeChecked@11e0_0227.c` | Kernel-owned item source and event-type transitions compiled and exercised by the item-process constructor, CTest reassignment/teardown | Source change stamps `+0x04`, marks the new item's presence bit, refreshes the old bit by searching unterminated processes from slot 3, and moves the type bit when `+0x06` is `0xf0..0xf7`. Type change stamps `+0x06`, sets the new type bit and refreshes the old type; values above `0x0fff` assert after the write. Per-item presence bits (`DS:3a04`) and per-item process-type bytes (`DS:3a08`) are separate host-owned tables. Static setters without kernel context remain partial; other item-cache mutations and binary parity are unverified. | -| `InitBase@11e0_0000.c` (`0008:ba00`) | Function-table/scalar/group-seed subset plus host-owned allocate/register path; harness-invoked, CTest offsets, counters, IDs | Live `11e0:0006-014e`: optional alloc `11e0:014f`, table words `0x3b06/0x2d10/0x3afe`, group from `DS:39c9`, then `SetGroupId`, `Kernel_AddProcess` (`11d0:0aff`), conditional `Kernel_GetSomeProcId_11d0_177c` branch, `Process_11d0_19cd`. Host updates extflags `+0x18 |= 4` on an addressable, unterminated current process with bit `2` set; it still omits stack-segment assertion and segmented-pointer relocation. | -| `Kernel_GetNextFreeProcId` (`11d0:0a97`), `Kernel_11d0_0716` | First-free slot and 30-slot growth translated; registered in host harness and CTest | Live decompile scans far process-pointer slots, grows parallel pointer/size/name arrays by 30 up to 1020 entries. Host stores native pointers, sizes, and default names; the original far-address mapping is not implemented. `Process_GetProcById` (`11d0:0bf3`) treats ID 0 as null even though the raw slot allocator may choose it. | -| `Kernel_AddProcess` (`11d0:0aff`) | Process pointer, ID, allocation-size, count, optional new-process flag/counter, default-name subset translated | Live disassembly stamps `procid` at `+0x02`, consumes `g_kernelLastProcessAllocSize`, increments count, optionally sets `ExtProc_NewlyCreated` (`0x200`), and names the slot `Default`. Host omits initialized-state assertion, far-pointer representation, and runtime parity. | -| `Process_11d0_19cd` / `Process_11d0_19ec` | Sync-flag predicate translated on the host creation path | Live `11d0:19ef-1a07` tests kernel flag and `procid > current ID`; `11d0:19e2-19e5` ORs `0x40` into process flags at `+0x16`. The conditional `InitBase` current-process extflag branch is also translated, without runtime parity. | -| `Kernel_TerminteProcessByPid` (`11d0:18a3`), `Process_SetTerminatedState` | Immediate and deferred termination translated for host-owned base and zero-child-state Stand entries | Live `11d0:18e5-1939`: decrement group count; if extflags `+0x18 & 4`, clear slot and free immediately; otherwise set flags `+0x16 & 8`, increment terminated count; decrement live process count in either case. Host refreshes the per-item bit after termination; child lists, special event callbacks, and teardown for non-owned entries remain unported. | -| `Kernel_ClearProcessSomethingAndName` (`11d0:1972`), `Kernel_11d0_1dcc` | Slot pointer/size/name clear and deferred cleanup for IDs >= 3 translated; ID reuse exercised | Live cleanup scans from ID 3, requires `+0x1a == 0`, clears the slot, frees the entry, and decrements terminated count. The clear helper itself does not decrement live process count. Other scheduler cleanup paths and process destructor dispatch remain unported. | | `FUN_11d0_0255` (`11d0:0255`) | Normal-process scan and timer wake translated; harness callback invokes compiled Stand `Run`, tests cover sleep/wake and scheduler gates | Live `11d0:02b4-03ac`: skip terminated, process sleep via `11e0:0379`, clear `Proc_Syncing` for one pass, skip nonzero `+0x24/+0x26`, `Proc_Waiting`, and off-group entries unless daemon or group 30/31; set current ID around vtable run call. Host receives an explicit timer tick, uses the original strict `start+duration < tick` wake comparison, and recognizes Stand's verified no-op completion slot (`1100:0fe3`); other completion targets remain unsupported. Immediate timer/keyboard interrupts, early-stop/group advance/table-maintenance tails, and general vtable dispatch remain unported. | | `Kernel_11d0_19b5` (`11d0:19b5`), `Kernel_11d0_0445` (`11d0:0445`) | Active-group writer and empty-group highest-ordinary-group selection translated; invoked after diagnostic scans in harness/window, CTest checks change flag and groups 30/31 exclusion | Exported globals initialize active group `DS:39c9` to 1 and pending byte `DS:39a2` to 0. Writer marks pending only when group changes; selector scans all occupied process slots (including terminated entries until cleanup), ignores groups 30/31 for the maximum, then clears pending. Host rejects invalid group IDs and uses explicit group counters; original group-table allocation, mid-scan early stop, and runtime traces remain unported. | | `Item_CreateProcess` (`10a0:0020`), `ItemProcess_Run` (`10a0:0078`), `Item_Release` (`10a0:2a06`) | Owned 0x32-byte item process constructed and advanced by the scheduler from a staged retail map record; release request, event-body queueing, task state, termination, and presence cleanup are exercised by the diagnostic host | Live disassembly confirms function-table root `0x102f`, item number at `+0x04`, event type `0xf1` at `+0x06`, then `Item_Release` followed unconditionally by the vtable terminate slot. The host callback receives mask `0x200` and `UC_Release` ordinal `9`, resolves an eligible retail body, and queues it in the host VM task registry. Only supported opcodes/services execute; unsupported paths halt the task. This remains a diagnostic trigger, not the original `Item_Grab` path; child teardown and general vtable dispatch remain unported. | @@ -356,18 +225,6 @@ Live Ghidra decompilation shows that vertical `GravityProcess_Run` impacts use s The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. The source's `World_MapBlockInFastArea` (`10a8:0000`) rotated block predicate and eight-corner start/destination footprint gate are testable with an explicit fast-area range. `World_CalcFastAreaLimits` (`10a8:0048`) now supplies the source sum ±5 / difference ±3 block window from a world center. The window refreshes a player-centered host range after movement and dispatches any owned gravity processes through its timed scheduler; it still does not create gravity entries or repaint moved map items in the static preview. The sweep's item-iterator rectangle and live candidate query follow inclusive X/Y filtering and Y-then-X block order. The per-item sweep uses 16-unit X/Y extents, 8-unit Z extents with the source zero-height fallback, and six axis-face tests that report one-unit-before-contact points and failed-direction bits. A read-only live collector combines those tests with candidate order, shape solidity and flip flags. The host selects a solid hit in source order when any axis is strictly closer, retains the earlier hit on a tie, and accumulates direction bits across contacts. Damaging-only face contacts are recorded in candidate order without blocking the resolved point. With an explicitly enabled floor-gap limit, the host also identifies the closest solid support beneath the destination footprint for source limits 0 and 9; this support metadata does not change the destination. The resolved sweep now reports fast-area failure at the original point with direction bits 1/2 and clamps out-of-range Z with bit 4; the gravity runner conservatively rejects these unsupported responses before mutation. `runResolvedGravity` moves an owned item to a solid-hit point after its strict process wake, damps and reverses horizontal speed on collision, and sleeps the process again. `scanResolvedGravity` dispatches this bounded runner through the host scheduler; tests verify a wall impact, a later move away, and no repeat within the same tick. The remaining gaps are vertical collision response, item status/cache writes, collision events, stationary fall search, and an actual window gravity producer and moving-item renderer. Original runtime parity remains unverified. -Original DOS debugging and runtime verification are postponed indefinitely until requested again. The DOSBox-X debugger session has been stopped; do not treat a live trace as a prerequisite for the source-port work below. Keep unverified parity claims labeled as such. - -Next source-port checks, in call-chain order: - -1. Keep the `0x23ff/0x2400` process item boundary until source-derived allocation limits support changing it; do not infer a wider live table from staged map IDs. -2. Keep the original scheduler wait behind a host timing boundary. `11d0:04cd/0575` reallocates and copies three segmented process tables; defer a direct port until the host's vector-backed slot/capacity semantics are explicitly modeled. Post-scan active-group selection is now statically translated, with runtime parity explicitly deferred. -3. Verify and extend the host free-ID/container slice against live runtime traces; synthetic tests now cover family-7 contained-record staging and family-6 runtime insertion, but item-cache status/fast-area effects and the `Item_PopToEnd` runtime append path remain unverified. -4. Port an explicit item-status model before implementing vertical gravity responses; bounds and fast-area failures are explicit but conservatively rejected, and live gravity branches also require controlled-NPC identity and random-response behavior. -5. Extend scheduled gravity with item status/cache writes and collision events; add a real window gravity producer and dynamic item renderer before claiming visible gameplay movement. -6. Connect the approved-move `Item_Grab` path to a ported `Item_LegalMoveToPointWithCollisionInfo` sweep and item-cache lifecycle, without changing the separate Windows `F` release fixture. -7. Lift `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`) and the `Inter_1418_0244` interpreter/context layout, replacing host task setup with the original event-frame and parameter semantics; extend opcode/intrinsic coverage before claiming event parity. - ## First Interactive Windows Game Shell `rebuild/remorse/out/build-nmake/remorse_game.exe` is the first windowed application target. It locates the game data root from its own executable path (or the current directory), defaults to map 1, and accepts an optional fixed-map index from 0 through 255. @@ -645,77 +502,22 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat ## What Is Done -- Established a separate rebuild tree under `rebuild/remorse/`. -- Added a CMake-based C++17 executable target. -- Added an initial compatibility header matching the earlier ABI draft categories. -- Added a temporary export prelude for staged decompiler-source imports. -- Added a minimal runtime harness that reads the exported decompilation manifest and reports the current export scope. -- Added an import-slice tool for staging individual exported function folders without linking them yet. -- Ran the importer on `classes/Remorse/EntityDispatchEntry`; it staged 24 files, replaced 62 calling-convention tokens, and reported `CONCAT22`, `unaff_CS`, and `unaff_SS` as cleanup signals. -- Added the first hand-maintained `EntityDispatchEntry` source skeleton and wired it into the CMake target. -- Translated `11e0:02a8` group-ID validation, counter transitions, and no-op on an unchanged group into the compiled skeleton; other methods still have incomplete or placeholder behavior. -- Replaced `InitBase`'s blanket clear with live-confirmed `11e0:0000` function-table stamps, scalar assignments, and the active-group `SetGroupId` call; seeded-byte tests protect unknown bytes while the rest of the constructor remains unported. -- Added an owned host allocate/init/register call path, porting the first-free ID, 30-slot growth, process-ID/size/count bookkeeping, and `Process_11d0_19cd` syncing predicate. The harness now registers a process (ID 0); this does not run the original scheduler. -- Added default process-name storage, optional `ExtProc_NewlyCreated` flag/counter, immediate and deferred itemless termination, and slot cleanup/ID reuse. The harness also terminates ID 3, cleans its slot, and registers another process at ID 3; normal ID 0 lookup is a special case. -- Ported the conditional `InitBase` current-process extflag branch and the normal-process scan gates of `11d0:0255`. Tests cover group selection, one-pass sync, creation from a run callback, and cleanup during the scan. -- Ported the original `Process_Sleep`/`Unlink` timer writes and wake check, then executed `StandProcess::Run` under the scheduler in the diagnostic harness. It now uses an owned 0x42-byte Stand entry, compiled `1100:026e` NPC decision gates with host-supplied services, and a timer value produced by `SystemTimerProcess_Increment`. CTest checks off-screen sleep, the strict 60-tick deadline, visible behavior start, already-current activity, Stand's no-op completion slot, and timer carry. Host-owned Stand termination now refreshes the per-item bit; tests cover two processes for one item, deferred reclamation, and final immediate removal. Live Ghidra names `Item_MarkProcessPresent`/`Item_ClearProcessPresent`/`Item_RefreshProcessPresenceFlag` at `11d0:3e0b/3e44/3e7f` anchor the port. -- Configured the Windows GUI and console executables to emit CRT and unexpected-exception details to debugger output/stderr instead of modal crash prompts. CTest resets the CRT assert mode to window mode and verifies the installer removes it, then captures a deliberately terminating child process without a popup. -- Split the scaffold into a `remorse_core` library, host executable, and first CTest target for `EntityDispatchEntry` setters. -- Added the first host file-system shim and CTest target for game-data root discovery. -- Extended the host file-system shim with case-insensitive data-path resolution, parent-traversal blocking, and binary file reads. -- Added the first typed game-data parser for 256-color palette files and verified `STATIC/GAMEPAL.PAL` parses to 256 colors. -- Added a standard FLEX archive parser and verified `STATIC/COMBAT.DAT` exposes 14 populated records. -- Added a typed `COMBAT.DAT` tactic parser and verified entry 0 metadata against the existing combat note. -- Added a full staged rebuild plan from current harness through a playable and packaged modern Windows source port. -- Added a typed `FIXED.DAT` map loader for map table and 16-byte fixed-item records. -- Added a typed `GLOB.FLX` object parser for the fixed-map glob-expansion path. -- Added a typed `TYPEFLAG.DAT` parser for shape family, flags, dimensions, and animation metadata. -- Added a typed `SHAPES.FLX` parser and row-RLE decoder for renderable frame pixels. -- Added the first visual map preview renderer and BMP output command. -- Added `remorse_game.exe`, a native Win32 window that asynchronously loads a retail map, displays the graph-sorted scene, and supports bounded WASD/arrow movement with a following camera. -- Added a persistent GDI back buffer and disabled background erase for the window's movement redraw path. -- Mapped keyboard movement to screen-cardinal directions through the inverse isometric transform and added a four-direction projection regression. -- Added a camera-centered render origin and a renderer test covering fixed-size viewport output. -- Documented the windowed app command and clearly scoped its current debug-marker/no-collision limitations. -- Replaced the host preview's scalar paint key with a footpad-aware dependency graph based on the local Ultima 8/Crusader sorter, including pairwise overlap, `below()` rules, and occlusion handling. -- Added a synthetic regression proving vertical separation can override the old `x+y` order, and retained the retail-data map-render smoke test. -- Validated `remorse_map_preview` by rendering map 1 to `rebuild/remorse/out/preview/map1-preview.bmp` from original retail data. -- Verified the scaffold with Visual Studio Community 2026: CMake configure succeeded, MSVC build succeeded, `ctest -C Debug` passed 2/2 tests, and `remorse_rebuild.exe` ran against `exports/src_remorse/export_manifest.json`. -- Added `build_msvc.cmd` so the MSVC build/test/harness loop is repeatable from the repository root; it uses an isolated NMake build tree to avoid the local CMake Visual Studio-instance resolution failure. -- Revalidated the wrapper with MSVC `19.51.36246.0`: all C++ targets built, all 11 CTest tests passed, and the host harness loaded the export manifest and retail resource summaries. -- Documented the current blockers between the Ghidra export and compiler-ready source. -- Split the goal into historical reconstruction and Windows source-port tracks. -- Chose Visual Studio Build Tools plus CMake as the first intended Windows host toolchain. +- **Build foundation:** `remorse_core`, the Windows game, MSVC/CMake build entry point, and focused CTest targets are in place. +- **Retail data:** loaders cover the resources used by the current map, rendering, item, and USECODE slices. The preview renderer and Win32 window remain diagnostic infrastructure. +- **Process and world state:** partial scheduler/process behavior, staged item placement/search, and selected item-cache operations are compiled and tested. The host does not yet run the original game loop or item runtime. +- **Teleporter startup slice:** live Ghidra evidence confirms `TeleporterProcess` is `0x36` bytes, with vtable `0x0f3a`, target map at `+0x32`, and egg ID at `+0x34`. The host kernel owns this typed process and models its same-map run by resolving a family-8/frame-1 destination whose quality low byte matches the requested ID, then moving item 1. Map loading now creates, runs, and retires this process using a local kernel. It does not port `Game_Start`, temporary-stasis wait, cross-map camera/NPC setup, collision/fall, sound, or original scheduler dispatch. +- **USECODE:** class/event parsing, a tested opcode subset, task lifecycle, and bounded `CreateFromSlotIndex` context construction are implemented. The window's use request now searches nearby item candidates, applies owner-row event selection, creates a context-backed task, and mirrors the context bytes into the process entry. A retail `BOX_NS` regression follows candidate search through context ownership and VM execution, checks six frame transitions and a rendered pixel change, then verifies output-pointer and allocation cleanup. This remains host-side dispatch with fixture-provided VM services, not original dispatcher parity or a verified interaction from the map-1 spawn. +- **Runtime chunks:** the host now models the 0x16-byte `UProcess_1420_0000` record, bounded far-memory allocations for chunk/process buffers, the doubly linked loaded-process list, descriptor-pointer replacement/restoration, and zero-count eviction. Retail `EVENT` and `NPCTRIG` plus a two-node fixture cover load, reuse, release, reload, and unlink behavior. The host materializer reads archive-backed class bytes; parity with the original owner-resource callback and allocator remains unverified. -## What Is Left To Do +## Later Scope -- Keep the host scaffold building as new source slices are added. -- Lift the confirmed `EntityDispatchEntry` byte offsets into named packed fields once the surrounding `Process` layout is stable. -- Convert the compatibility header from placeholders into enforced layout macros with static assertions. -- Extend the translated `SetGroupId` slice to its original initializer/callers and record the ported function addresses and parity checks. -- Expand the host file-system shim into DOS file-handle replacements and writable save/config locations. -- Model far pointers and segmented memory in a way that can support both trace comparison and Windows execution. -- Normalize Ghidra exported types into valid C++ names without losing address provenance. -- Replace raw global-byte exports with typed data definitions or resource loaders. -- Define resource fixture tests for palette, shape, map, and usecode data. -- Add explicit crop/navigation controls and tests for bounded map previews. -- Validate roof/hidden-object rendering policy against selected retail scenes. -- Keep the current Win32/GDI window as a diagnostic host while lifting the original player/process loop; choose other platform layers only as original DOS/hardware boundaries require them. -- Replace the windowed prototype movement/collision with ported player and AreaSearch behavior, using retail art and the existing renderer for presentation. -- Connect triggers and object interaction to the USECODE runtime after its value/context model is lifted. -- Add CI-style smoke tests once the host toolchain and first resource loader compile reliably. +After the first source-backed interaction, complete the original player/item loop, save/load, combat, mission flow, audio, frontend, and retail-map coverage. Keep the current preview and window as test hosts until recovered runtime behavior replaces their stand-ins. ## Near-Term Next Actions -1. Verify the live `Process` group-table allocation/initialization and compare the compiled active-group writer/selector (`11d0:19b5/0445`) and `11e0:02a8` side effects with an execution trace (including counter ownership and error paths). -2. Complete `InitBase` (`11e0:0000`) and the kernel lifecycle by resolving the segment assertion, conditional kernel branch, item-linked teardown, process destructor dispatch and far-pointer storage; compare the host registry to real process snapshots. -3. Trace `Init_Everything` -> `FUN_11d0_0255` -> the player process and additional vtable `Run` targets; compare the staged map-item/ItemProcess IDs and Stand's presence-bit lifecycle against original snapshots, then port animation-cache and nonempty-child teardown against real NPC state. -4. Port the real timer process and NPC service implementations, then scheduler keyboard, active-group advancement, remaining sleep-completion dispatch and table-maintenance tails; compare deterministic process-order/state traces before connecting the Windows window. -5. Replace DOS file and memory APIs encountered by the ported chain with narrow host adapters; validate far-pointer/layout conversions against live evidence. -6. Port original movement and AreaSearch/collision behavior before promoting the host actor movement from stand-in to gameplay code. -7. Complete runtime chunk materialization before context dispatch: extend the tested archive-backed `UsecodeSlotChunkCache` through `InitSlotOwnerBuffers`/`EnsureSlotChunkLoaded` (`1420:1866/19fd`), port the `0x16`-byte `UProcess_1420_0000` allocation and owner-helper materialization, then model loaded-list ownership, far-pointer restoration, release, and eviction. After that, map runtime-owned code into host VM memory, lift `CreateFromSlotIndex`/`Inter_1418_0244`, and execute a selected retail event with verified item/process side effects before connecting it to the window. Continue through original item/draw-list output, save/load, audio, and frontend chains for playable mission progression. +1. **Close the event path:** identify an eligible retail `use` target reachable from the original map-1 spawn. The exact production-equivalent search at egg `0x1e` currently returns one candidate and no eligible event. Then exercise movement to a real target, owner selection, context creation, and VM execution through supported runtime services, verifying a process/world-state effect. The BOX_NS regression verifies candidate-driven selection and visible frame output from a fixture origin only; it does not close this action or establish `Usecode_ItemCallEvent` parity. +2. **Integrate the map-1 loop:** port `Game_Start` (`1020:0000`) and the teleporter constructor/run lifecycle rather than host initialization; add the stasis wait, original target-map transition and item search, collision/fall, then move input and animation onto the recovered kernel loop. The current tests cover same-map egg resolution, shared item-1 mutation, and host input/scheduler behavior, not those binary lifecycle semantics or source draw-order/camera parity. Keep the normal window on the original path before calling the vertical slice accepted. ## Current Bottom Line -Runtime-cache progress correction: the host now models the extra-slot header, descriptor/state buffers, ensure/release counts, and archive-backed zero-count unload/reload. It still lacks `UProcess_1420_0000` allocation, owner-helper materialization, loaded-list ownership, and runtime far-pointer restoration; complete those prerequisites before far-address integration and the numbered context-dispatch action above. -The project has a buildable diagnostic host, retail resource loaders, partial original scheduler scan, and owned Stand and item-process entries. The Windows diagnostic registry runs an item process bound to a staged retail map record, queues an eligible release body into the subset VM, and runs a Stand entry under the host tick. Retail tests demonstrate script-driven item-frame mutation. The `E` selector now iterates bounded, source-order candidates from `itemGrabSearchCandidates` (the modeled `Item_Grab` query) and queues the first candidate with an eligible `use` body, replacing its earlier nearest-distance choice. This is source-derived candidate selection, not original interaction dispatch: the window still constructs the item identity and queues the event body directly, and no visible before/input/after interaction is proven. The partial `CreateFromSlotIndex` slice writes the verified slot index (`+0x32`), value offset (`+0x34`), owner-source far pointer (`+0x11b`), mode byte (`+0x121`), and cleared parameter/active fields (`+0x11f/+0x122`) into the allocated 0x124-byte context. The VM bootstrap now copies the item parameter only for nonzero mode flags, then optional context bytes, reserves the four-byte saved-stack-pointer slot, and records the context-relative parameter offset; focused tests cover the ordering and zero-mode case. Real segment:offset pointer mapping, runtime code/owner-resource addresses, and embedded interpreter-context execution remain unported. `F` remains a separate release diagnostic. The original item cache/block IDs, full `Item_Grab`/`Usecode_ItemCallEvent`/`CreateFromSlotIndex` chain, real NPC ownership/services, nonempty-child teardown, DOS timer/keyboard interrupts, full scheduler, original startup/player chain, and renderer integration remain open. This is not a playable-game milestone; the next measure is mapping far addresses into the host VM and using them to execute one selected retail event through original context dispatch. +The host now materializes archive-backed USECODE chunks and builds tested 0x124-byte contexts with bounded source pointers and an initialized 0x82-byte call stack. Its window routes use-request candidates through owner-row selection into a context-backed task; the BOX_NS regression verifies VM-driven frame changes, rendered output, and cleanup, while a separate retail test confirms no eligible event at the original spawn. Retail egg selection and placement of item 1 are covered, the typed `TeleporterProcess` performs its tested same-map egg move, and a deterministic host input/tick test verifies that the item-owned animation process moves item 1. Original `Game_Start`, the full teleporter lifecycle, `Usecode_ItemCallEvent`/context-dispatch, owner-resource callback parity, a reachable retail interaction, and original loop/render parity remain incomplete. Whole-game and playable-game acceptance remain unmet. diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index 7e06929..7a3eadc 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -51,6 +51,11 @@ struct ControllerProcessEntry { u8 extra[0x0e]; } CR_PACKED; +struct TeleporterProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x04]; +} CR_PACKED; + struct AnimPrimitiveProcessEntry { EntityDispatchEntryBase base; u8 extra[0x29]; @@ -84,6 +89,7 @@ static_assert(sizeof(SystemTimerProcessEntry) == 0x4a, "SystemTimerProcessEntry static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size must match allocation evidence"); static_assert(sizeof(KeyDaemonProcessEntry) == 0x40, "KeyDaemonProcessEntry size must match allocation evidence"); static_assert(sizeof(ControllerProcessEntry) == 0x40, "ControllerProcessEntry size must match allocation evidence"); +static_assert(sizeof(TeleporterProcessEntry) == 0x36, "TeleporterProcessEntry size must match allocation evidence"); static_assert(sizeof(AnimPrimitiveProcessEntry) == 0x5b, "AnimPrimitiveProcessEntry size must match allocation evidence"); static_assert(sizeof(EntityVmContextProcessEntry) == 0x124, "EntityVmContext process size must match allocation evidence"); static_assert(sizeof(KeyEvent) == 0x0c, "KeyEvent size must match keyboard event copy"); @@ -119,6 +125,8 @@ public: KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]); KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]); ControllerProcessEntry* createControllerProcess(u8 activeGroup, u16 (&groupCounts)[32]); + TeleporterProcessEntry* createTeleporterProcess(u8 activeGroup, u16 mapNumber, u16 teleportId, + u16 (&groupCounts)[32]); AnimPrimitiveProcessEntry* createAnimPrimitiveProcess(u8 activeGroup, u16 itemNumber, u16 animationNumber, u8 direction, const AnimationClip& clip, u16 (&groupCounts)[32]); EntityVmContextProcessEntry* createUsecodeProcess(u8 activeGroup, u16 (&groupCounts)[32]); @@ -174,6 +182,7 @@ private: std::vector> ownedStandProcesses_; std::vector> ownedGravityProcesses_; std::vector> ownedAnimPrimitiveProcesses_; + std::vector> ownedTeleporterProcesses_; std::vector> ownedUsecodeProcesses_; std::unique_ptr systemTimerProcess_; std::unique_ptr keyboardProcess_; @@ -237,6 +246,15 @@ public: static void increment(SystemTimerProcessEntry& entry); }; +class TeleporterProcess { +public: + static constexpr u16 vtableOffset = 0x0f3a; + static constexpr u16 mapNumberOffset = 0x32; + static constexpr u16 teleportIdOffset = 0x34; + static bool run(const TeleporterProcessEntry& process, LiveFixedMapItems& items, + u16 currentMapNumber, const std::vector& shapes); +}; + class KeyboardProcess { public: static bool handleKeyEvent(KeyboardProcessEntry& process, u16 selector, u16 filter, diff --git a/rebuild/remorse/include/remorse/usecode_archive.h b/rebuild/remorse/include/remorse/usecode_archive.h index 4d7b136..0e9aa7b 100644 --- a/rebuild/remorse/include/remorse/usecode_archive.h +++ b/rebuild/remorse/include/remorse/usecode_archive.h @@ -2,6 +2,8 @@ #include "remorse/flex_archive.h" +#include +#include #include #include #include @@ -27,20 +29,69 @@ struct UsecodeEventBody { std::vector bytes; }; +struct UsecodeLoadedChunkProcessLayout { + u16 vtableOffset = 0; + FarPtr16 previous{0, 0}; + FarPtr16 next{0, 0}; + FarPtr16 chunkBuffer{0, 0}; + FarPtr16 savedSource{0, 0}; + u16 slotIndex = 0; + u16 chunkIndex = 0; +}; + +static_assert(sizeof(UsecodeLoadedChunkProcessLayout) == 0x16); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, previous) == 0x02); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, next) == 0x06); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, chunkBuffer) == 0x0a); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, savedSource) == 0x0e); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, slotIndex) == 0x12); +static_assert(offsetof(UsecodeLoadedChunkProcessLayout, chunkIndex) == 0x14); + +struct UsecodeLoadedChunkProcess { + FarPtr16 processAddress{0, 0}; + UsecodeLoadedChunkProcessLayout layout; + UsecodeEventBody body; +}; + +class UsecodeRuntimeMemory { +public: + std::optional allocate(std::size_t byteCount, u8 initialValue = 0); + bool release(FarPtr16 address) noexcept; + bool contains(FarPtr16 address, std::size_t byteCount) const noexcept; + std::optional> read(FarPtr16 address, std::size_t byteCount) const; + bool write(FarPtr16 address, const std::vector& bytes); + std::size_t allocationCount() const noexcept { return allocations_.size(); } + +private: + u32 nextSegment_ = 1; + std::map> allocations_; +}; + class UsecodeSlotChunkCache { public: explicit UsecodeSlotChunkCache(UsecodeClass usecodeClass); const UsecodeEventBody* ensureLoaded(u16 chunkIndex); bool release(u16 chunkIndex) noexcept; - bool tryUnload(u16 chunkIndex) noexcept; + bool tryUnload(u16 chunkIndex); u16 inUseCount(u16 chunkIndex) const noexcept; + const UsecodeLoadedChunkProcess* loadedProcess(u16 chunkIndex) const noexcept; + std::size_t loadedProcessCount() const noexcept; + FarPtr16 loadedListHead() const noexcept { return loadedListHead_; } std::size_t chunkCount() const noexcept { return chunks_.size(); } const UsecodeSlotOwnerBuffers& ownerBuffers() const noexcept { return ownerBuffers_; } + UsecodeRuntimeMemory& runtimeMemory() noexcept { return runtimeMemory_; } + const UsecodeRuntimeMemory& runtimeMemory() const noexcept { return runtimeMemory_; } private: + UsecodeLoadedChunkProcess* findLoadedProcess(FarPtr16 processAddress) noexcept; + bool unlinkLoadedProcess(FarPtr16 processAddress); + UsecodeClass usecodeClass_; UsecodeSlotOwnerBuffers ownerBuffers_; - std::vector> chunks_; + std::vector> chunks_; + UsecodeRuntimeMemory runtimeMemory_; + FarPtr16 loadedListHead_{0, 0}; + FarPtr16 loadedListTail_{0, 0}; }; struct UsecodeClassBases { diff --git a/rebuild/remorse/include/remorse/usecode_vm.h b/rebuild/remorse/include/remorse/usecode_vm.h index 7dbdd45..4c4063f 100644 --- a/rebuild/remorse/include/remorse/usecode_vm.h +++ b/rebuild/remorse/include/remorse/usecode_vm.h @@ -8,6 +8,7 @@ #include #include "remorse/compat.h" +#include "remorse/usecode_archive.h" namespace remorse { @@ -15,12 +16,20 @@ constexpr std::size_t usecodeEventBytecodeOffset = 14; constexpr std::size_t usecodeFrameBaseOffset = 0x40; constexpr std::size_t usecodeInterpreterStackLimit = 199; constexpr std::size_t usecodeContextProcessSize = 0x124; +constexpr std::size_t usecodeContextInterpreterOffset = 0x36; constexpr std::size_t usecodeContextSlotIndexOffset = 0x32; constexpr std::size_t usecodeContextValueAddOffset = 0x34; +constexpr std::size_t usecodeContextStackPointerOffset = 0x102; +constexpr std::size_t usecodeContextStackBaseOffset = 0x106; +constexpr std::size_t usecodeContextStackLimitOffset = 0x10a; +constexpr std::size_t usecodeContextCodeSourceOffset = 0x10c; +constexpr std::size_t usecodeContextSelfPointerOffset = 0x110; +constexpr std::size_t usecodeContextOwnerRowsOffset = 0x117; constexpr std::size_t usecodeContextOwnerSourceOffset = 0x11b; constexpr std::size_t usecodeContextParameterOffset = 0x11f; constexpr std::size_t usecodeContextModeFlagsOffset = 0x121; constexpr std::size_t usecodeContextActiveFlagOffset = 0x122; +constexpr std::size_t usecodeInterpreterCallStackSize = 0x82; struct UsecodeCallFrame { u16 offset = 0; @@ -53,7 +62,7 @@ class UsecodeInterpreterState { public: static std::optional initialize( const std::vector& itemParameter, const std::vector& contextParameter = {}, - u16 modeFlags = 0); + u16 modeFlags = 0, bool contextParameterPresent = false); bool pushCodeAddress(u16 offset, u16 segment); bool pushWord(u16 value); bool pushDword(u32 value); @@ -71,6 +80,7 @@ public: u16 stackLimit = usecodeInterpreterStackLimit; u16 temporaryWord = 0; std::optional contextParameterOffset; + std::optional contextParameterStackTop; bool processExcluded = false; u16 currentProcessId = 0; u16 impliedProcessId = 0; @@ -107,19 +117,57 @@ struct UsecodeContextFactoryFields { u16 parameterOffset = 0; }; +struct UsecodeContextCreateRequest { + FarPtr16 ownerSource{}; + FarPtr16 codeSource{}; + FarPtr16 ownerRows{}; + std::optional> itemParameter; + std::optional> contextParameter; + u16 modeFlags = 0; + u16 slotIndex = 0; + u16 valueAddOffset = 0; +}; + +struct UsecodeContextInstance { + FarPtr16 processAddress{0, 0}; + FarPtr16 callStackAddress{0, 0}; + std::array processBytes{}; + UsecodeInterpreterState interpreter; +}; + +struct UsecodeEventContext { + UsecodeContextInstance context; + FarPtr16 processIdOutput{0, 0}; + std::vector ownedRegions; +}; + bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize, const UsecodeContextFactoryFields& fields); +std::optional createUsecodeContext(UsecodeRuntimeMemory& memory, + const UsecodeContextCreateRequest& request); +bool destroyUsecodeContext(UsecodeRuntimeMemory& memory, + const UsecodeContextInstance& context) noexcept; +std::optional createUsecodeEventContext(UsecodeRuntimeMemory& memory, + const std::vector& ownerRows, u16 classId, u16 eventSlot, u16 sourceItem, + const std::vector& code, u8 itemArgumentSize); +bool destroyUsecodeEventContext(UsecodeRuntimeMemory& memory, + const UsecodeEventContext& eventContext) noexcept; class UsecodeTaskRegistry { public: + UsecodeRuntimeMemory& runtimeMemory() noexcept { return runtimeMemory_; } bool add(UsecodeProcessTask task); + bool addWithContext(UsecodeProcessTask task, UsecodeEventContext context); UsecodeProcessTask* find(u16 processId); const UsecodeProcessTask* find(u16 processId) const; + const UsecodeEventContext* context(u16 processId) const noexcept; bool remove(u16 processId); std::size_t size() const noexcept { return tasks_.size(); } private: std::map tasks_; + std::map contexts_; + UsecodeRuntimeMemory runtimeMemory_; }; } // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index e5724ea..c813b00 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -170,6 +170,47 @@ AnimPrimitiveProcessEntry* ProcessKernel::createAnimPrimitiveProcess(u8 activeGr return result; } +TeleporterProcessEntry* ProcessKernel::createTeleporterProcess(u8 activeGroup, u16 mapNumber, + u16 teleportId, u16 (&groupCounts)[32]) +{ + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + if (std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + processes_.reserve(processes_.size() + 30); + allocationSizes_.reserve(allocationSizes_.size() + 30); + processNames_.reserve(processNames_.size() + 30); + } + ownedTeleporterProcesses_.reserve(ownedTeleporterProcesses_.size() + 1); + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x00, TeleporterProcess::vtableOffset); + writeLe16(process->base, TeleporterProcess::mapNumberOffset, mapNumber); + writeLe16(process->base, TeleporterProcess::teleportIdOffset, teleportId); + setLastAllocationSize(sizeof(TeleporterProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "Teleporter"; + TeleporterProcessEntry* result = process.get(); + ownedTeleporterProcesses_.push_back(std::move(process)); + return result; +} + +bool TeleporterProcess::run(const TeleporterProcessEntry& process, LiveFixedMapItems& items, + u16 currentMapNumber, const std::vector& shapes) +{ + const auto readWord = [&process](u16 offset) { + return static_cast(process.base.bytes[offset] | + (static_cast(process.base.bytes[offset + 1]) << 8)); + }; + const u16 targetMap = readWord(mapNumberOffset); + if (targetMap != currentMapNumber) { + return false; + } + const auto destination = findTeleportEgg(items.mapItems(), shapes, + static_cast(readWord(teleportIdOffset))); + return destination && items.teleportAvatar(*destination, static_cast(targetMap)); +} + EntityVmContextProcessEntry* ProcessKernel::createUsecodeProcess(u8 activeGroup, u16 (&groupCounts)[32]) { @@ -676,6 +717,12 @@ void ProcessKernel::releaseOwnedProcess(u16 id) ownedAnimPrimitiveProcesses_.erase(animation); return; } + const auto teleporter = std::find_if(ownedTeleporterProcesses_.begin(), ownedTeleporterProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (teleporter != ownedTeleporterProcesses_.end()) { + ownedTeleporterProcesses_.erase(teleporter); + return; + } const auto usecode = std::find_if(ownedUsecodeProcesses_.begin(), ownedUsecodeProcesses_.end(), [entry](const auto& process) { return &process->base == entry; }); if (usecode != ownedUsecodeProcesses_.end()) { @@ -721,6 +768,9 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) const bool ownedUsecodeProcess = std::any_of(ownedUsecodeProcesses_.begin(), ownedUsecodeProcesses_.end(), [entry](const auto& process) { return &process->base == entry; }); + const bool ownedTeleporterProcess = std::any_of(ownedTeleporterProcesses_.begin(), + ownedTeleporterProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess && !ownedGravityProcess && !ownedAnimationProcess && !ownedUsecodeProcess || id < 3 || readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 || @@ -728,7 +778,7 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) throw std::logic_error("item process child cleanup is not ported"); } if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && !ownedAnimationProcess && - !ownedUsecodeProcess && + !ownedUsecodeProcess && !ownedTeleporterProcess && std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; })) { throw std::logic_error("external process ownership is not ported"); diff --git a/rebuild/remorse/src/usecode_archive.cpp b/rebuild/remorse/src/usecode_archive.cpp index dfbdb3c..98e4cfc 100644 --- a/rebuild/remorse/src/usecode_archive.cpp +++ b/rebuild/remorse/src/usecode_archive.cpp @@ -1,5 +1,7 @@ #include "remorse/usecode_archive.h" +#include +#include #include namespace remorse { @@ -16,6 +18,34 @@ u32 readDword(const std::vector& bytes, std::size_t offset) (static_cast(bytes[offset + 2]) << 16) | (static_cast(bytes[offset + 3]) << 24); } +void writeWord(std::vector& bytes, std::size_t offset, u16 value) +{ + bytes[offset] = static_cast(value); + bytes[offset + 1] = static_cast(value >> 8); +} + +void writeDword(std::vector& bytes, std::size_t offset, u32 value) +{ + writeWord(bytes, offset, static_cast(value)); + writeWord(bytes, offset + 2, static_cast(value >> 16)); +} + +bool isNull(FarPtr16 address) noexcept +{ + return address.offset == 0 && address.segment == 0; +} + +bool sameAddress(FarPtr16 left, FarPtr16 right) noexcept +{ + return left.offset == right.offset && left.segment == right.segment; +} + +std::vector serialize(const UsecodeLoadedChunkProcessLayout& layout) +{ + const auto* first = reinterpret_cast(&layout); + return std::vector(first, first + sizeof(layout)); +} + std::optional readEventBodyFromDescriptors(const UsecodeClass& usecodeClass, const std::vector& descriptors, std::size_t descriptorOffset, u32 eventId) { @@ -41,6 +71,54 @@ std::optional readEventBodyFromDescriptors(const UsecodeClass& } // namespace +std::optional UsecodeRuntimeMemory::allocate(std::size_t byteCount, u8 initialValue) +{ + constexpr std::size_t maxSegmentBytes = static_cast(std::numeric_limits::max()) + 1; + if (byteCount == 0 || byteCount > maxSegmentBytes || nextSegment_ > std::numeric_limits::max()) { + return std::nullopt; + } + const auto segment = static_cast(nextSegment_++); + allocations_.emplace(segment, std::vector(byteCount, initialValue)); + return FarPtr16{0, segment}; +} + +bool UsecodeRuntimeMemory::release(FarPtr16 address) noexcept +{ + return address.offset == 0 && address.segment != 0 && allocations_.erase(address.segment) != 0; +} + +bool UsecodeRuntimeMemory::contains(FarPtr16 address, std::size_t byteCount) const noexcept +{ + const auto allocation = allocations_.find(address.segment); + return address.segment != 0 && allocation != allocations_.end() && + address.offset <= allocation->second.size() && + byteCount <= allocation->second.size() - address.offset; +} + +std::optional> UsecodeRuntimeMemory::read(FarPtr16 address, std::size_t byteCount) const +{ + const auto allocation = allocations_.find(address.segment); + if (address.segment == 0 || allocation == allocations_.end() || + address.offset > allocation->second.size() || + byteCount > allocation->second.size() - address.offset) { + return std::nullopt; + } + return std::vector(allocation->second.begin() + address.offset, + allocation->second.begin() + address.offset + byteCount); +} + +bool UsecodeRuntimeMemory::write(FarPtr16 address, const std::vector& bytes) +{ + const auto allocation = allocations_.find(address.segment); + if (address.segment == 0 || allocation == allocations_.end() || + address.offset > allocation->second.size() || + bytes.size() > allocation->second.size() - address.offset) { + return false; + } + std::copy(bytes.begin(), bytes.end(), allocation->second.begin() + address.offset); + return true; +} + u16 selectUsecodeClassId(const UsecodeItemIdentity& item, const UsecodeClassBases& bases) { if (item.isNpc && (item.status & 2) == 0) { @@ -141,17 +219,73 @@ const UsecodeEventBody* UsecodeSlotChunkCache::ensureLoaded(u16 chunkIndex) if (chunkIndex >= chunks_.size()) { return nullptr; } - auto& body = chunks_[chunkIndex]; + auto& process = chunks_[chunkIndex]; auto& state = ownerBuffers_.chunkStates[chunkIndex]; - if (!body) { - if (state != 0xffff) { + if (!process) { + if (state != 0xffff || usecodeClass_.classId > std::numeric_limits::max()) { return nullptr; } auto loadedBody = readEventBodyFromDescriptors(usecodeClass_, ownerBuffers_.descriptors, 0, chunkIndex); if (!loadedBody) { return nullptr; } - chunks_[chunkIndex] = std::move(*loadedBody); + + auto processAddress = runtimeMemory_.allocate(sizeof(UsecodeLoadedChunkProcessLayout)); + if (!processAddress) { + return nullptr; + } + auto chunkBuffer = runtimeMemory_.allocate(loadedBody->bytes.size(), 0xff); + if (!chunkBuffer) { + runtimeMemory_.release(*processAddress); + return nullptr; + } + + UsecodeLoadedChunkProcess loadedProcess; + loadedProcess.processAddress = *processAddress; + loadedProcess.layout.vtableOffset = 0x673c; + loadedProcess.layout.previous = loadedListHead_; + loadedProcess.layout.chunkBuffer = *chunkBuffer; + const std::size_t descriptorOffset = static_cast(chunkIndex) * 6; + const u32 sourceOffset = readDword(ownerBuffers_.descriptors, descriptorOffset + 2); + loadedProcess.layout.savedSource = FarPtr16{ + static_cast(sourceOffset), static_cast(sourceOffset >> 16)}; + loadedProcess.layout.slotIndex = static_cast(usecodeClass_.classId); + loadedProcess.layout.chunkIndex = chunkIndex; + loadedProcess.body = std::move(*loadedBody); + + if (!runtimeMemory_.write(loadedProcess.layout.chunkBuffer, loadedProcess.body.bytes) || + !runtimeMemory_.write(loadedProcess.processAddress, serialize(loadedProcess.layout))) { + runtimeMemory_.release(loadedProcess.layout.chunkBuffer); + runtimeMemory_.release(loadedProcess.processAddress); + return nullptr; + } + + chunks_[chunkIndex] = std::move(loadedProcess); + if (isNull(loadedListHead_)) { + loadedListTail_ = *processAddress; + } else { + auto* oldHead = findLoadedProcess(loadedListHead_); + if (oldHead == nullptr) { + runtimeMemory_.release(chunks_[chunkIndex]->layout.chunkBuffer); + runtimeMemory_.release(chunks_[chunkIndex]->processAddress); + chunks_[chunkIndex].reset(); + return nullptr; + } + oldHead->layout.next = *processAddress; + if (!runtimeMemory_.write(oldHead->processAddress, serialize(oldHead->layout))) { + oldHead->layout.next = FarPtr16{0, 0}; + runtimeMemory_.write(oldHead->processAddress, serialize(oldHead->layout)); + runtimeMemory_.release(chunks_[chunkIndex]->layout.chunkBuffer); + runtimeMemory_.release(chunks_[chunkIndex]->processAddress); + chunks_[chunkIndex].reset(); + return nullptr; + } + } + loadedListHead_ = *processAddress; + const auto& loadedProcessState = *chunks_[chunkIndex]; + writeDword(ownerBuffers_.descriptors, descriptorOffset + 2, + static_cast(loadedProcessState.layout.chunkBuffer.offset) | + (static_cast(loadedProcessState.layout.chunkBuffer.segment) << 16)); state = 1; } else { if (state >= 29999) { @@ -159,7 +293,7 @@ const UsecodeEventBody* UsecodeSlotChunkCache::ensureLoaded(u16 chunkIndex) } ++state; } - return &*chunks_[chunkIndex]; + return &chunks_[chunkIndex]->body; } bool UsecodeSlotChunkCache::release(u16 chunkIndex) noexcept @@ -172,13 +306,28 @@ bool UsecodeSlotChunkCache::release(u16 chunkIndex) noexcept return true; } -bool UsecodeSlotChunkCache::tryUnload(u16 chunkIndex) noexcept +bool UsecodeSlotChunkCache::tryUnload(u16 chunkIndex) { - if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] != 0) { + if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] != 0 || !chunks_[chunkIndex]) { return false; } - chunks_[chunkIndex].reset(); + + auto& process = *chunks_[chunkIndex]; + const std::size_t descriptorOffset = static_cast(chunkIndex) * 6; + writeDword(ownerBuffers_.descriptors, descriptorOffset + 2, + static_cast(process.layout.savedSource.offset) | + (static_cast(process.layout.savedSource.segment) << 16)); ownerBuffers_.chunkStates[chunkIndex] = 0xffff; + if (!unlinkLoadedProcess(process.processAddress)) { + writeDword(ownerBuffers_.descriptors, descriptorOffset + 2, + static_cast(process.layout.chunkBuffer.offset) | + (static_cast(process.layout.chunkBuffer.segment) << 16)); + ownerBuffers_.chunkStates[chunkIndex] = 0; + return false; + } + runtimeMemory_.release(process.layout.chunkBuffer); + runtimeMemory_.release(process.processAddress); + chunks_[chunkIndex].reset(); return true; } @@ -190,6 +339,65 @@ u16 UsecodeSlotChunkCache::inUseCount(u16 chunkIndex) const noexcept return ownerBuffers_.chunkStates[chunkIndex]; } +const UsecodeLoadedChunkProcess* UsecodeSlotChunkCache::loadedProcess(u16 chunkIndex) const noexcept +{ + if (chunkIndex >= chunks_.size() || !chunks_[chunkIndex]) { + return nullptr; + } + return &*chunks_[chunkIndex]; +} + +std::size_t UsecodeSlotChunkCache::loadedProcessCount() const noexcept +{ + std::size_t count = 0; + for (const auto& process : chunks_) { + count += process.has_value() ? 1 : 0; + } + return count; +} + +UsecodeLoadedChunkProcess* UsecodeSlotChunkCache::findLoadedProcess(FarPtr16 processAddress) noexcept +{ + for (auto& process : chunks_) { + if (process && sameAddress(process->processAddress, processAddress)) { + return &*process; + } + } + return nullptr; +} + +bool UsecodeSlotChunkCache::unlinkLoadedProcess(FarPtr16 processAddress) +{ + auto* process = findLoadedProcess(processAddress); + if (process == nullptr) { + return false; + } + auto* older = isNull(process->layout.previous) ? nullptr : findLoadedProcess(process->layout.previous); + auto* newer = isNull(process->layout.next) ? nullptr : findLoadedProcess(process->layout.next); + if ((!isNull(process->layout.previous) && older == nullptr) || + (!isNull(process->layout.next) && newer == nullptr)) { + return false; + } + + if (older != nullptr) { + older->layout.next = process->layout.next; + if (!runtimeMemory_.write(older->processAddress, serialize(older->layout))) { + return false; + } + } else { + loadedListTail_ = process->layout.next; + } + if (newer != nullptr) { + newer->layout.previous = process->layout.previous; + if (!runtimeMemory_.write(newer->processAddress, serialize(newer->layout))) { + return false; + } + } else { + loadedListHead_ = process->layout.previous; + } + return true; +} + std::optional selectEligibleUsecodeEvent(const FlexArchive& archive, const std::vector& ownerRows, const UsecodeItemIdentity& item, const UsecodeClassBases& bases, u32 eventMask, u16 eventId) diff --git a/rebuild/remorse/src/usecode_vm.cpp b/rebuild/remorse/src/usecode_vm.cpp index 3abfc65..23f02f0 100644 --- a/rebuild/remorse/src/usecode_vm.cpp +++ b/rebuild/remorse/src/usecode_vm.cpp @@ -1,14 +1,30 @@ #include "remorse/usecode_vm.h" +#include "remorse/usecode_archive.h" #include namespace remorse { +namespace { + +void writeWord(u8* bytes, std::size_t offset, u16 value) +{ + bytes[offset] = static_cast(value); + bytes[offset + 1] = static_cast(value >> 8); +} + +void writeFarPointer(u8* bytes, std::size_t offset, FarPtr16 pointer) +{ + writeWord(bytes, offset, pointer.offset); + writeWord(bytes, offset + sizeof(u16), pointer.segment); +} + +} // namespace std::optional UsecodeInterpreterState::initialize( const std::vector& itemParameter, const std::vector& contextParameter, - u16 modeFlags) + u16 modeFlags, bool contextParameterPresent) { - const bool saveStackPointer = !contextParameter.empty() && modeFlags != 0; + const bool saveStackPointer = (!contextParameter.empty() || contextParameterPresent) && modeFlags != 0; const std::size_t savedPointerBytes = saveStackPointer ? sizeof(FarPtr16) : 0; if (itemParameter.size() > usecodeInterpreterStackLimit || contextParameter.size() > usecodeInterpreterStackLimit - itemParameter.size() || @@ -22,10 +38,12 @@ std::optional UsecodeInterpreterState::initialize( std::copy(bytes.begin(), bytes.end(), state.valueStack.begin() + state.stackTop); }; pushBytes(itemParameter); + const std::size_t stackTopBeforeContextParameter = state.stackTop; pushBytes(contextParameter); if (saveStackPointer) { state.stackTop -= savedPointerBytes; state.contextParameterOffset = static_cast(state.stackTop - sizeof(u16) * 2); + state.contextParameterStackTop = static_cast(stackTopBeforeContextParameter); } return state; } @@ -484,6 +502,190 @@ bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize, return true; } +std::optional createUsecodeContext(UsecodeRuntimeMemory& memory, + const UsecodeContextCreateRequest& request) +{ + const bool hasOwnerSource = request.ownerSource.offset != 0 || request.ownerSource.segment != 0; + if (!memory.contains(request.codeSource, 1) || !memory.contains(request.ownerRows, 9) || + (hasOwnerSource && !memory.contains(request.ownerSource, 1))) { + return std::nullopt; + } + + std::vector itemParameter; + if (request.modeFlags != 0 && request.itemParameter) { + if (request.itemParameter->size() != request.modeFlags) { + return std::nullopt; + } + itemParameter = *request.itemParameter; + } + const std::vector contextParameter = request.contextParameter.value_or(std::vector{}); + auto interpreter = UsecodeInterpreterState::initialize(itemParameter, contextParameter, + request.modeFlags, request.contextParameter.has_value()); + if (!interpreter || !interpreter->pushCodeAddress(request.slotIndex, request.valueAddOffset)) { + return std::nullopt; + } + + const auto processAddress = memory.allocate(usecodeContextProcessSize); + if (!processAddress) { + return std::nullopt; + } + const auto callStackAddress = memory.allocate(usecodeInterpreterCallStackSize); + if (!callStackAddress) { + memory.release(*processAddress); + return std::nullopt; + } + + UsecodeContextInstance context; + context.processAddress = *processAddress; + context.callStackAddress = *callStackAddress; + writeFarPointer(context.processBytes.data(), usecodeContextInterpreterOffset, *callStackAddress); + std::copy(interpreter->valueStack.begin() + interpreter->stackTop, interpreter->valueStack.end(), + context.processBytes.begin() + usecodeContextInterpreterOffset + interpreter->stackTop); + + const auto stackTopOffset = static_cast(processAddress->offset) + + usecodeContextInterpreterOffset + static_cast(interpreter->stackTop); + const auto stackBaseOffset = static_cast(processAddress->offset) + usecodeContextStackPointerOffset; + if (stackTopOffset > 0xffff || stackBaseOffset > 0xffff) { + memory.release(*callStackAddress); + memory.release(*processAddress); + return std::nullopt; + } + writeFarPointer(context.processBytes.data(), usecodeContextStackPointerOffset, + FarPtr16{static_cast(stackTopOffset), processAddress->segment}); + writeFarPointer(context.processBytes.data(), usecodeContextStackBaseOffset, + FarPtr16{static_cast(stackBaseOffset), processAddress->segment}); + writeWord(context.processBytes.data(), usecodeContextStackLimitOffset, interpreter->stackLimit); + writeFarPointer(context.processBytes.data(), usecodeContextCodeSourceOffset, request.codeSource); + writeFarPointer(context.processBytes.data(), usecodeContextSelfPointerOffset, *processAddress); + writeFarPointer(context.processBytes.data(), usecodeContextOwnerRowsOffset, request.ownerRows); + + const UsecodeContextFactoryFields fields{request.ownerSource, request.modeFlags, + request.slotIndex, request.valueAddOffset, interpreter->contextParameterOffset.value_or(0)}; + if (!writeUsecodeContextFactoryFields(context.processBytes.data(), context.processBytes.size(), fields)) { + memory.release(*callStackAddress); + memory.release(*processAddress); + return std::nullopt; + } + if (interpreter->contextParameterStackTop) { + const std::size_t savedPointerOffset = usecodeContextInterpreterOffset + interpreter->stackTop; + const u32 savedStackOffset = static_cast(processAddress->offset) + + usecodeContextInterpreterOffset + *interpreter->contextParameterStackTop; + if (savedPointerOffset > context.processBytes.size() - sizeof(FarPtr16) || savedStackOffset > 0xffff) { + memory.release(*callStackAddress); + memory.release(*processAddress); + return std::nullopt; + } + writeFarPointer(context.processBytes.data(), savedPointerOffset, + FarPtr16{static_cast(savedStackOffset), processAddress->segment}); + } + + std::vector callStackBytes(usecodeInterpreterCallStackSize, 0); + for (u16 index = 0; index < interpreter->callFrameCount; ++index) { + const std::size_t frameOffset = static_cast(index) * 2 * sizeof(u16); + writeWord(callStackBytes.data(), frameOffset, interpreter->callFrames[index].offset); + writeWord(callStackBytes.data(), frameOffset + sizeof(u16), interpreter->callFrames[index].segment); + } + writeWord(callStackBytes.data(), 0x80, interpreter->callFrameCount); + + const std::vector processBytes(context.processBytes.begin(), context.processBytes.end()); + if (!memory.write(*processAddress, processBytes) || !memory.write(*callStackAddress, callStackBytes)) { + memory.release(*callStackAddress); + memory.release(*processAddress); + return std::nullopt; + } + context.interpreter = std::move(*interpreter); + return context; +} + +bool destroyUsecodeContext(UsecodeRuntimeMemory& memory, const UsecodeContextInstance& context) noexcept +{ + const bool callStackReleased = memory.release(context.callStackAddress); + const bool processReleased = memory.release(context.processAddress); + return callStackReleased && processReleased; +} + +std::optional createUsecodeEventContext(UsecodeRuntimeMemory& memory, + const std::vector& ownerRows, u16 classId, u16 eventSlot, u16 sourceItem, + const std::vector& code, u8 itemArgumentSize) +{ + constexpr std::size_t ownerRowSize = 13; + const std::size_t ownerRowOffset = static_cast(classId) * ownerRowSize; + if (code.size() <= usecodeEventBytecodeOffset || + (itemArgumentSize != 0 && itemArgumentSize != sizeof(u16)) || + ownerRowOffset > ownerRows.size() || ownerRows.size() - ownerRowOffset < ownerRowSize) { + return std::nullopt; + } + + UsecodeEventContext eventContext; + const auto allocateRegion = [&memory, &eventContext](const std::vector& bytes) + -> std::optional { + auto region = memory.allocate(bytes.size()); + if (!region) { + return std::nullopt; + } + if (!memory.write(*region, bytes)) { + memory.release(*region); + return std::nullopt; + } + eventContext.ownedRegions.push_back(*region); + return region; + }; + + const auto codeRegion = allocateRegion(code); + const std::vector ownerRow(ownerRows.begin() + ownerRowOffset, + ownerRows.begin() + ownerRowOffset + ownerRowSize); + const auto ownerRowRegion = codeRegion ? allocateRegion(ownerRow) : std::nullopt; + const auto outputRegion = ownerRowRegion ? memory.allocate(sizeof(u16)) : std::nullopt; + if (!codeRegion || !ownerRowRegion || !outputRegion) { + if (outputRegion) { + memory.release(*outputRegion); + } + for (const auto region : eventContext.ownedRegions) { + memory.release(region); + } + return std::nullopt; + } + eventContext.processIdOutput = *outputRegion; + eventContext.ownedRegions.push_back(*outputRegion); + + std::vector contextParameter{ + static_cast(outputRegion->offset), + static_cast(outputRegion->offset >> 8), + static_cast(outputRegion->segment), + static_cast(outputRegion->segment >> 8) + }; + UsecodeContextCreateRequest request; + request.codeSource = *codeRegion; + request.ownerRows = FarPtr16{4, ownerRowRegion->segment}; + if (itemArgumentSize == sizeof(u16)) { + request.itemParameter = std::vector{static_cast(sourceItem), + static_cast(sourceItem >> 8)}; + } + request.contextParameter = std::move(contextParameter); + request.modeFlags = itemArgumentSize; + request.slotIndex = classId; + request.valueAddOffset = eventSlot; + auto context = createUsecodeContext(memory, request); + if (!context) { + for (const auto region : eventContext.ownedRegions) { + memory.release(region); + } + return std::nullopt; + } + eventContext.context = std::move(*context); + return eventContext; +} + +bool destroyUsecodeEventContext(UsecodeRuntimeMemory& memory, + const UsecodeEventContext& eventContext) noexcept +{ + bool released = destroyUsecodeContext(memory, eventContext.context); + for (const auto region : eventContext.ownedRegions) { + released = memory.release(region) && released; + } + return released; +} + UsecodeStepResult UsecodeProcessTask::step(const UsecodeOpcodeServices& services) { if (halted) { @@ -502,6 +704,19 @@ bool UsecodeTaskRegistry::add(UsecodeProcessTask task) return tasks_.emplace(task.processId, std::move(task)).second; } +bool UsecodeTaskRegistry::addWithContext(UsecodeProcessTask task, UsecodeEventContext context) +{ + const u16 processId = task.processId; + if (processId < 3 || tasks_.find(processId) != tasks_.end() || contexts_.find(processId) != contexts_.end()) { + destroyUsecodeEventContext(runtimeMemory_, context); + return false; + } + task.interpreter = context.context.interpreter; + tasks_.emplace(processId, std::move(task)); + contexts_.emplace(processId, std::move(context)); + return true; +} + UsecodeProcessTask* UsecodeTaskRegistry::find(u16 processId) { const auto found = tasks_.find(processId); @@ -514,9 +729,25 @@ const UsecodeProcessTask* UsecodeTaskRegistry::find(u16 processId) const return found == tasks_.end() ? nullptr : &found->second; } +const UsecodeEventContext* UsecodeTaskRegistry::context(u16 processId) const noexcept +{ + const auto found = contexts_.find(processId); + return found == contexts_.end() ? nullptr : &found->second; +} + bool UsecodeTaskRegistry::remove(u16 processId) { - return tasks_.erase(processId) != 0; + const auto task = tasks_.find(processId); + if (task == tasks_.end()) { + return false; + } + const auto context = contexts_.find(processId); + if (context != contexts_.end()) { + destroyUsecodeEventContext(runtimeMemory_, context->second); + contexts_.erase(context); + } + tasks_.erase(task); + return true; } } // namespace remorse \ No newline at end of file diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index acf676f..10f9be6 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -156,21 +156,40 @@ std::optional queueUsecodeTask(AppState& state, remorse::u16 class state.diagnosticKernel.activeGroup(), state.diagnosticGroupCounts); const remorse::u16 processId = static_cast(process->base.bytes[2] | (static_cast(process->base.bytes[3]) << 8)); + + const auto terminateProcess = [&state, processId]() { + state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts); + state.diagnosticKernel.clearTerminatedProcesses(); + }; + auto eventContext = remorse::createUsecodeEventContext(state.usecodeTasks.runtimeMemory(), + state.usecodeOwnerRows, classId, eventSlot, sourceItem, code, itemArgumentSize); + if (!eventContext) { + terminateProcess(); + return std::nullopt; + } + const std::vector processIdBytes{ + static_cast(processId), static_cast(processId >> 8)}; + if (!state.usecodeTasks.runtimeMemory().write(eventContext->processIdOutput, processIdBytes)) { + remorse::destroyUsecodeEventContext(state.usecodeTasks.runtimeMemory(), *eventContext); + terminateProcess(); + return std::nullopt; + } + auto task = remorse::UsecodeProcessTask::create(processId, classId, eventSlot, sourceItem, std::move(code), itemArgumentSize, std::move(extraArguments)); - if (!task) { - state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts); - state.diagnosticKernel.clearTerminatedProcesses(); + if (!task || !state.usecodeTasks.addWithContext(std::move(*task), std::move(*eventContext))) { + terminateProcess(); return std::nullopt; } - const remorse::UsecodeContextFactoryFields factoryFields{{0, 0}, itemArgumentSize, - classId, eventSlot, task->interpreter.contextParameterOffset.value_or(0)}; - if (!remorse::writeUsecodeContextFactoryFields(reinterpret_cast(process), - sizeof(*process), factoryFields) || !state.usecodeTasks.add(std::move(*task))) { - state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts); - state.diagnosticKernel.clearTerminatedProcesses(); + const auto* registeredContext = state.usecodeTasks.context(processId); + if (registeredContext == nullptr) { + state.usecodeTasks.remove(processId); + terminateProcess(); return std::nullopt; } + std::copy(registeredContext->context.processBytes.begin() + remorse::usecodeContextSlotIndexOffset, + registeredContext->context.processBytes.end(), + reinterpret_cast(process) + remorse::usecodeContextSlotIndexOffset); return processId; } @@ -501,12 +520,32 @@ void loadSceneAsync(HWND window, AppState& state) options.viewCenter = spawn; remorse::LiveFixedMapItems liveItems(std::move(*stagedItems), std::move(containedItems)); liveItems.initializeAvatar(); - remorse::StagedFixedMapItem diagnosticStart; - diagnosticStart.data.x = static_cast(spawn.x / 2); - diagnosticStart.data.y = static_cast(spawn.y / 2); - diagnosticStart.data.z = static_cast(spawn.z); - liveItems.teleportAvatar(startingEgg ? *startingEgg : diagnosticStart, - static_cast(state.mapIndex)); + if (startingEgg) { + remorse::ProcessKernel teleporterKernel; + remorse::u16 teleporterGroupCounts[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + teleporterKernel.createProcess(1, teleporterGroupCounts); + } + auto* teleporter = teleporterKernel.createTeleporterProcess(1, + static_cast(state.mapIndex), 0x1e, teleporterGroupCounts); + const remorse::u16 processId = static_cast(teleporter->base.bytes[2] | + (static_cast(teleporter->base.bytes[3]) << 8)); + const bool teleported = remorse::TeleporterProcess::run(*teleporter, liveItems, + static_cast(state.mapIndex), *shapeTypes); + teleporter->base.bytes[0x18] |= 4; + teleporterKernel.terminateProcess(processId, teleporterGroupCounts); + if (!teleported) { + setLoadFailure(state, L"The teleporter process could not resolve its map and egg destination."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + } else { + remorse::StagedFixedMapItem diagnosticStart; + diagnosticStart.data.x = static_cast(spawn.x / 2); + diagnosticStart.data.y = static_cast(spawn.y / 2); + diagnosticStart.data.z = static_cast(spawn.z); + liveItems.teleportAvatar(diagnosticStart, static_cast(state.mapIndex)); + } auto renderer = remorse::loadMapSceneRenderer(state.root, state.mapIndex); if (renderer) { hatchGlobsInFastArea(liveItems, *renderer, remorse::calculateFastAreaRange(spawn)); diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index 9a4ee99..38ce7aa 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -1050,5 +1050,101 @@ int main() assert(animationKernel.processAt(6) == nullptr && animationKernel.allocationSizeAt(6) == 0); assert(animationGroups[1] == 6 && animationKernel.itemHasProcess(1)); + remorse::ProcessKernel movementKernel; + remorse::u16 movementGroups[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + movementKernel.createProcess(1, movementGroups); + } + assert(movementKernel.createSystemTimerProcess(1, movementGroups)); + assert(movementKernel.createKeyboardProcess(1, movementGroups)); + assert(movementKernel.createControllerProcess(1, movementGroups)); + remorse::KeyEvent movementKey{}; + movementKey.scanCode = 0x48; + movementKey.field8 = 1; + assert(movementKernel.queuePendingKeyEvent(movementKey)); + remorse::ControllerMovementState movementController; + movementKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process, + remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { + if (process.bytes[0] == 0xa6 && process.bytes[1] == 0x3a) { + assert(selector == 0x10 && filter == 0); + static_cast(context)->handleDirectionalKey( + event.scanCode, event.modifiers, event.field8 != 0); + } + }, &movementController); + const auto movementRequest = movementController.request(); + assert(movementRequest.animation == 1 && movementRequest.direction == 14); + + remorse::AnimationClip controllerWalk{}; + controllerWalk.header = {17, 4, 0, 0}; + controllerWalk.frameCount = 17; + controllerWalk.frames.resize(17 * 8); + auto& controllerStep = controllerWalk.frames[7 * 17 + 1]; + controllerStep.bytes[4] = 1; + controllerStep.bytes[5] = 2; + remorse::LiveFixedMapItems movementItems({}); + assert(movementItems.initializeAvatar()); + remorse::StagedFixedMapItem movementSpawn{}; + movementSpawn.data.x = 512; + movementSpawn.data.y = 512; + assert(movementItems.teleportAvatar(movementSpawn, 1)); + std::vector movementShapes(2); + movementShapes[1].x = movementShapes[1].y = movementShapes[1].z = 2; + auto* controllerAnimation = movementKernel.createAnimPrimitiveProcess(1, 1, + movementRequest.animation, movementRequest.direction, controllerWalk, movementGroups); + assert(controllerAnimation); + const remorse::u16 controllerAnimationId = static_cast( + controllerAnimation->base.bytes[2] | (static_cast(controllerAnimation->base.bytes[3]) << 8)); + assert(movementKernel.startAnimPrimitiveProcess(controllerAnimationId, movementItems, controllerWalk)); + struct ControllerTickContext { + remorse::ProcessKernel* kernel; + remorse::LiveFixedMapItems* items; + const remorse::AnimationClip* clip; + const std::vector* shapes; + remorse::FastAreaRange fastArea; + remorse::u16 processId; + std::optional advanced; + } controllerTick{&movementKernel, &movementItems, &controllerWalk, &movementShapes, + remorse::calculateFastAreaRange({512, 512, 0}), controllerAnimationId}; + movementKernel.runTimedSchedulerPass(1, [](remorse::EntityDispatchEntryBase& process, void* context) { + auto& tick = *static_cast(context); + if (&process == tick.kernel->processAt(tick.processId)) { + tick.advanced = tick.kernel->advanceGroundedAnimPrimitive(tick.processId, + *tick.items, *tick.clip, *tick.shapes, tick.fastArea); + } + }, &controllerTick); + assert(controllerTick.advanced == true && movementKernel.itemHasProcess(1)); + assert(movementItems.findItem(1)->data.x == 510 && movementItems.findItem(1)->data.y == 510 && + movementItems.findNpcAnimation(1)->frame == 1); + movementKey.field8 = 0; + assert(movementKernel.queuePendingKeyEvent(movementKey)); + movementKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process, + remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { + if (process.bytes[0] == 0xa6 && process.bytes[1] == 0x3a) { + assert(selector == 0x10 && filter == 0); + static_cast(context)->handleDirectionalKey( + event.scanCode, event.modifiers, event.field8 != 0); + } + }, &movementController); + assert(movementController.request().animation == 0 && movementController.request().direction == 14); + + remorse::ProcessKernel teleporterKernel; + remorse::u16 teleporterGroups[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + teleporterKernel.createProcess(1, teleporterGroups); + } + auto* teleporter = teleporterKernel.createTeleporterProcess(1, 1, 0x1e, teleporterGroups); + const remorse::u16 teleporterProcessId = static_cast( + teleporter->base.bytes[2] | (static_cast(teleporter->base.bytes[3]) << 8)); + assert(teleporterKernel.processAt(teleporterProcessId) == &teleporter->base && + teleporterKernel.allocationSizeAt(teleporterProcessId) == 0x36 && + std::strcmp(teleporterKernel.processNameAt(teleporterProcessId), "Teleporter") == 0); + assert(teleporter->base.bytes[0] == 0x3a && teleporter->base.bytes[1] == 0x0f && + teleporter->base.bytes[0x32] == 1 && teleporter->base.bytes[0x33] == 0 && + teleporter->base.bytes[0x34] == 0x1e && teleporter->base.bytes[0x35] == 0); + teleporter->base.bytes[0x18] |= 4; + teleporterKernel.terminateProcess(teleporterProcessId, teleporterGroups); + assert(teleporterKernel.processAt(teleporterProcessId) == nullptr && + teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 3); + return 0; } diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index b020a0f..64a41ff 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -23,6 +23,26 @@ int main() std::equal(prefix.begin(), prefix.end(), body.begin()) && body[remorse::usecodeEventBytecodeOffset] == 0x0b; }; + const auto readDescriptorPointer = [](const std::vector& descriptors, + std::size_t chunkIndex) { + const std::size_t offset = chunkIndex * 6 + 2; + return static_cast(descriptors[offset]) | + (static_cast(descriptors[offset + 1]) << 8) | + (static_cast(descriptors[offset + 2]) << 16) | + (static_cast(descriptors[offset + 3]) << 24); + }; + + remorse::UsecodeRuntimeMemory boundedMemory; + assert(!boundedMemory.allocate(0)); + assert(!boundedMemory.allocate(0x10001)); + const auto fullSegment = boundedMemory.allocate(0x10000, 0x5a); + assert(fullSegment); + const auto finalSegmentByte = boundedMemory.read({0xffff, fullSegment->segment}, 1); + assert(finalSegmentByte && finalSegmentByte->size() == 1 && finalSegmentByte->front() == 0x5a); + assert(!boundedMemory.read({0xffff, fullSegment->segment}, 2)); + assert(!boundedMemory.read({0, 0xffff}, 1)); + assert(boundedMemory.release(*fullSegment) && boundedMemory.allocationCount() == 0); + const auto root = remorse::findGameDataRoot(std::filesystem::current_path()); assert(root.has_value()); @@ -66,6 +86,36 @@ int main() [](remorse::u16 state) { return state == 0xffff; })); assert(std::equal(npcTriggerOwnerBuffers->descriptors.begin(), npcTriggerOwnerBuffers->descriptors.end(), npcTriggerClass->bytes.begin() + 20)); + remorse::UsecodeSlotChunkCache npcTriggerChunkCache(*npcTriggerClass); + const auto originalNpcTriggerDescriptors = npcTriggerChunkCache.ownerBuffers().descriptors; + std::optional npcTriggerChunkIndex; + for (remorse::u16 chunkIndex = 0; chunkIndex < npcTriggerChunkCache.chunkCount(); ++chunkIndex) { + if (npcTriggerChunkCache.ensureLoaded(chunkIndex)) { + npcTriggerChunkIndex = chunkIndex; + break; + } + } + assert(npcTriggerChunkIndex); + const auto npcTriggerSourcePointer = readDescriptorPointer( + originalNpcTriggerDescriptors, *npcTriggerChunkIndex); + const auto* loadedNpcTriggerProcess = npcTriggerChunkCache.loadedProcess(*npcTriggerChunkIndex); + assert(loadedNpcTriggerProcess && loadedNpcTriggerProcess->layout.slotIndex == 0x363 && + loadedNpcTriggerProcess->layout.chunkIndex == *npcTriggerChunkIndex && + loadedNpcTriggerProcess->layout.savedSource.offset == static_cast(npcTriggerSourcePointer) && + loadedNpcTriggerProcess->layout.savedSource.segment == static_cast(npcTriggerSourcePointer >> 16)); + const auto loadedNpcTriggerBytes = npcTriggerChunkCache.runtimeMemory().read( + loadedNpcTriggerProcess->layout.chunkBuffer, loadedNpcTriggerProcess->body.length); + assert(loadedNpcTriggerBytes && *loadedNpcTriggerBytes == loadedNpcTriggerProcess->body.bytes && + readDescriptorPointer(npcTriggerChunkCache.ownerBuffers().descriptors, *npcTriggerChunkIndex) == + (static_cast(loadedNpcTriggerProcess->layout.chunkBuffer.offset) | + (static_cast(loadedNpcTriggerProcess->layout.chunkBuffer.segment) << 16))); + assert(npcTriggerChunkCache.release(*npcTriggerChunkIndex)); + assert(npcTriggerChunkCache.tryUnload(*npcTriggerChunkIndex)); + assert(npcTriggerChunkCache.loadedProcessCount() == 0 && + npcTriggerChunkCache.runtimeMemory().allocationCount() == 0 && + readDescriptorPointer(npcTriggerChunkCache.ownerBuffers().descriptors, *npcTriggerChunkIndex) == + npcTriggerSourcePointer); + auto inconsistentOwnerHeader = *eventClass; inconsistentOwnerHeader.extraSlotCount = 1; assert(!remorse::initializeUsecodeSlotOwnerBuffers(inconsistentOwnerHeader)); @@ -74,9 +124,24 @@ int main() assert(eventBody->bytes.size() == 0x1fd6 && eventBody->bytes.front() == eventClass->bytes[0xd4]); remorse::UsecodeSlotChunkCache eventChunkCache(*eventClass); assert(eventChunkCache.chunkCount() == 32); + const auto sourceEventPointer = readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a); const auto* loadedEventChunk = eventChunkCache.ensureLoaded(0x0a); assert(loadedEventChunk && loadedEventChunk->bytes == eventBody->bytes && eventChunkCache.inUseCount(0x0a) == 1); + const auto* loadedEventProcess = eventChunkCache.loadedProcess(0x0a); + assert(loadedEventProcess && loadedEventProcess->layout.vtableOffset == 0x673c && + loadedEventProcess->layout.slotIndex == 0x361 && loadedEventProcess->layout.chunkIndex == 0x0a && + loadedEventProcess->layout.savedSource.offset == static_cast(sourceEventPointer) && + loadedEventProcess->layout.savedSource.segment == static_cast(sourceEventPointer >> 16)); + const auto loadedEventBytes = eventChunkCache.runtimeMemory().read( + loadedEventProcess->layout.chunkBuffer, loadedEventProcess->body.length); + assert(loadedEventBytes && *loadedEventBytes == loadedEventProcess->body.bytes && + eventChunkCache.loadedListHead().offset == loadedEventProcess->processAddress.offset && + eventChunkCache.loadedListHead().segment == loadedEventProcess->processAddress.segment && + eventChunkCache.loadedProcessCount() == 1 && eventChunkCache.runtimeMemory().allocationCount() == 2); + assert(readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a) == + (static_cast(loadedEventProcess->layout.chunkBuffer.offset) | + (static_cast(loadedEventProcess->layout.chunkBuffer.segment) << 16))); const auto* reusedEventChunk = eventChunkCache.ensureLoaded(0x0a); assert(reusedEventChunk == loadedEventChunk && eventChunkCache.inUseCount(0x0a) == 2); assert(eventChunkCache.release(0x0a) && eventChunkCache.inUseCount(0x0a) == 1); @@ -85,6 +150,9 @@ int main() assert(!eventChunkCache.release(0x0a)); assert(eventChunkCache.tryUnload(0x0a)); assert(eventChunkCache.ownerBuffers().chunkStates[0x0a] == 0xffff); + assert(eventChunkCache.loadedProcessCount() == 0 && eventChunkCache.runtimeMemory().allocationCount() == 0 && + eventChunkCache.loadedListHead().offset == 0 && eventChunkCache.loadedListHead().segment == 0 && + readDescriptorPointer(eventChunkCache.ownerBuffers().descriptors, 0x0a) == sourceEventPointer); const auto* reloadedEventChunk = eventChunkCache.ensureLoaded(0x0a); assert(reloadedEventChunk && reloadedEventChunk->bytes == eventBody->bytes && eventChunkCache.inUseCount(0x0a) == 1); @@ -95,6 +163,49 @@ int main() assert(eventChunkCache.inUseCount(0x0a) == 29999); assert(eventChunkCache.ensureLoaded(0x0a) == nullptr && eventChunkCache.inUseCount(0x0a) == 29999); assert(eventChunkCache.ensureLoaded(0x20) == nullptr && eventChunkCache.inUseCount(0x20) == 0); + + remorse::UsecodeClass syntheticOwnerClass; + syntheticOwnerClass.classId = 0x123; + syntheticOwnerClass.name = "SYNTHETIC"; + syntheticOwnerClass.codeBase = 0xd4; + syntheticOwnerClass.bytes.resize(syntheticOwnerClass.codeBase + 2); + syntheticOwnerClass.bytes[20] = 1; + syntheticOwnerClass.bytes[22] = 1; + syntheticOwnerClass.bytes[26] = 1; + syntheticOwnerClass.bytes[28] = 2; + syntheticOwnerClass.bytes[syntheticOwnerClass.codeBase] = 0xaa; + syntheticOwnerClass.bytes[syntheticOwnerClass.codeBase + 1] = 0xbb; + remorse::UsecodeSlotChunkCache syntheticChunkCache(std::move(syntheticOwnerClass)); + const auto syntheticSourceDescriptors = syntheticChunkCache.ownerBuffers().descriptors; + const auto* firstSyntheticBody = syntheticChunkCache.ensureLoaded(0); + const auto* secondSyntheticBody = syntheticChunkCache.ensureLoaded(1); + assert(firstSyntheticBody && firstSyntheticBody->bytes == std::vector{0xaa} && + secondSyntheticBody && secondSyntheticBody->bytes == std::vector{0xbb}); + const auto* firstSyntheticProcess = syntheticChunkCache.loadedProcess(0); + const auto* secondSyntheticProcess = syntheticChunkCache.loadedProcess(1); + assert(firstSyntheticProcess && secondSyntheticProcess && + secondSyntheticProcess->layout.previous.offset == firstSyntheticProcess->processAddress.offset && + secondSyntheticProcess->layout.previous.segment == firstSyntheticProcess->processAddress.segment && + firstSyntheticProcess->layout.next.offset == secondSyntheticProcess->processAddress.offset && + firstSyntheticProcess->layout.next.segment == secondSyntheticProcess->processAddress.segment && + syntheticChunkCache.loadedListHead().offset == secondSyntheticProcess->processAddress.offset && + syntheticChunkCache.loadedListHead().segment == secondSyntheticProcess->processAddress.segment); + const auto firstSyntheticSourcePointer = readDescriptorPointer( + syntheticSourceDescriptors, 0); + const auto secondSyntheticSourcePointer = readDescriptorPointer( + syntheticSourceDescriptors, 1); + assert(syntheticChunkCache.release(0) && syntheticChunkCache.tryUnload(0)); + assert(syntheticChunkCache.loadedProcessCount() == 1 && + syntheticChunkCache.loadedListHead().offset == secondSyntheticProcess->processAddress.offset && + syntheticChunkCache.loadedListHead().segment == secondSyntheticProcess->processAddress.segment && + syntheticChunkCache.loadedProcess(1)->layout.previous.offset == 0 && + syntheticChunkCache.loadedProcess(1)->layout.previous.segment == 0 && + readDescriptorPointer(syntheticChunkCache.ownerBuffers().descriptors, 0) == firstSyntheticSourcePointer); + assert(syntheticChunkCache.release(1) && syntheticChunkCache.tryUnload(1)); + assert(syntheticChunkCache.loadedProcessCount() == 0 && syntheticChunkCache.runtimeMemory().allocationCount() == 0 && + syntheticChunkCache.loadedListHead().offset == 0 && syntheticChunkCache.loadedListHead().segment == 0 && + readDescriptorPointer(syntheticChunkCache.ownerBuffers().descriptors, 1) == secondSyntheticSourcePointer); + assert(!remorse::readUsecodeEventBody(*eventClass, 0x20)); assert(!remorse::loadUsecodeClass(*usecode, usecode->entryCount)); auto truncated = *eventClass; @@ -132,6 +243,48 @@ int main() assert(stagedItems && !stagedItems->empty()); const auto spawnEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x1e); assert(spawnEgg); + remorse::LiveFixedMapItems spawnSearchWorld(*stagedItems); + assert(spawnSearchWorld.initializeAvatar()); + remorse::ProcessKernel teleporterKernel; + remorse::u16 teleporterGroups[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + teleporterKernel.createProcess(1, teleporterGroups); + } + auto* teleporterProcess = teleporterKernel.createTeleporterProcess(1, 1, 0x1e, teleporterGroups); + const remorse::u16 teleporterProcessId = static_cast( + teleporterProcess->base.bytes[2] | (static_cast(teleporterProcess->base.bytes[3]) << 8)); + assert(!remorse::TeleporterProcess::run(*teleporterProcess, spawnSearchWorld, 2, *typeFlags)); + assert(spawnSearchWorld.findItem(1)->data.x == 0 && spawnSearchWorld.findItem(1)->data.y == 0); + assert(remorse::TeleporterProcess::run(*teleporterProcess, spawnSearchWorld, 1, *typeFlags)); + teleporterProcess->base.bytes[0x18] |= 4; + teleporterKernel.terminateProcess(teleporterProcessId, teleporterGroups); + assert(teleporterKernel.processAt(teleporterProcessId) == nullptr && + teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 3); + assert(spawnEgg->recordIndex < fixedMap->entries.size()); + const auto& startingEggRecord = fixedMap->entries[spawnEgg->recordIndex]; + const auto* spawnedAvatar = spawnSearchWorld.findItem(1); + assert(spawnEgg->data.x == startingEggRecord.x / 2 && + spawnEgg->data.y == startingEggRecord.y / 2 && spawnEgg->data.z == startingEggRecord.z); + assert(spawnedAvatar && spawnedAvatar->itemNumber == 1 && + spawnedAvatar->data.x == spawnEgg->data.x && spawnedAvatar->data.y == spawnEgg->data.y && + spawnedAvatar->data.z == spawnEgg->data.z && spawnedAvatar->data.mapNumber == 1); + const auto spawnUseCandidates = remorse::itemGrabSearchCandidates( + *spawnedAvatar, spawnSearchWorld.mapItems(), *typeFlags); + assert(spawnUseCandidates); + unsigned eligibleSpawnUses = 0; + for (const auto& candidate : *spawnUseCandidates) { + const auto* item = spawnSearchWorld.findItem(candidate.itemNumber); + if (!item || item->data.shape >= typeFlags->size()) continue; + const auto& shape = (*typeFlags)[item->data.shape]; + const remorse::UsecodeItemIdentity spawnIdentity{item->itemNumber, item->data.shape, + item->data.flags, item->data.quality, shape.family, false}; + const auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + spawnIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); + if (eligible) { + ++eligibleSpawnUses; + } + } + assert(eligibleSpawnUses == 0); unsigned eligibleMapUseItems = 0; unsigned keycardUseItems = 0; std::optional boxItem; @@ -448,9 +601,46 @@ int main() 0x5a, 0x02, 0x5c, 0xd6, 0x01, 'B', 'O', 'X', '_', 'N', 'S', 0x00, 0x00, 0x00}; assert(hasRetailEventEntry(boxUse->bytes, boxPrefix)); remorse::LiveFixedMapItems boxWorld(*stagedItems); - auto boxTask = remorse::UsecodeProcessTask::create(0x0340, 0x0081, 1, - boxItem->itemNumber, boxUse->bytes); - assert(boxTask); + const auto& boxShape = (*typeFlags)[boxItem->data.shape]; + const remorse::u8 boxHeight = boxShape.z == 0 && (boxShape.flags & 1) == 0 + ? 1 : static_cast(boxShape.z * 8); + assert(static_cast(boxItem->data.z) + boxHeight <= 0xff); + remorse::StagedFixedMapItem boxSearchOrigin; + boxSearchOrigin.itemNumber = 1; + boxSearchOrigin.data.shape = 1; + boxSearchOrigin.data.x = boxItem->data.x; + boxSearchOrigin.data.y = boxItem->data.y; + boxSearchOrigin.data.z = static_cast(boxItem->data.z + boxHeight); + const auto boxCandidates = remorse::itemGrabSearchCandidates(boxSearchOrigin, + boxWorld.mapItems(), *typeFlags); + assert(boxCandidates); + const auto boxCandidate = std::find_if(boxCandidates->begin(), boxCandidates->end(), + [boxItem](const auto& candidate) { return candidate.itemNumber == boxItem->itemNumber; }); + assert(boxCandidate != boxCandidates->end()); + const auto* selectedBoxItem = boxWorld.findItem(boxCandidate->itemNumber); + assert(selectedBoxItem && selectedBoxItem->data.shape < typeFlags->size()); + const remorse::UsecodeItemIdentity boxIdentity{selectedBoxItem->itemNumber, selectedBoxItem->data.shape, + selectedBoxItem->data.flags, selectedBoxItem->data.quality, + (*typeFlags)[selectedBoxItem->data.shape].family, false}; + const auto selectedBoxEvent = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, + boxIdentity, retailBases, 0x02, 1); + assert(selectedBoxEvent && selectedBoxEvent->classId == 0x0081 && + selectedBoxEvent->className == "BOX_NS" && selectedBoxEvent->body.bytes == boxUse->bytes); + remorse::UsecodeTaskRegistry boxTasks; + auto boxContext = remorse::createUsecodeEventContext(boxTasks.runtimeMemory(), *retailOwnerRows, + selectedBoxEvent->classId, 1, boxItem->itemNumber, selectedBoxEvent->body.bytes, 2); + assert(boxContext && boxContext->context.interpreter.callFrameCount == 1 && + boxContext->ownedRegions.size() == 3 && boxTasks.runtimeMemory().allocationCount() == 5); + const std::vector boxProcessIdBytes{0x40, 0x03}; + assert(boxTasks.runtimeMemory().write(boxContext->processIdOutput, boxProcessIdBytes)); + auto boxTaskValue = remorse::UsecodeProcessTask::create(0x0340, selectedBoxEvent->classId, 1, + boxItem->itemNumber, selectedBoxEvent->body.bytes, 2); + assert(boxTaskValue && boxTasks.addWithContext(std::move(*boxTaskValue), std::move(*boxContext))); + auto* boxTask = boxTasks.find(0x0340); + const auto* registeredBoxContext = boxTasks.context(0x0340); + assert(boxTask && registeredBoxContext && boxTask->sourceItem == boxItem->itemNumber && + boxTask->interpreter.callFrameCount == 1 && registeredBoxContext->context.processBytes[ + remorse::usecodeContextSlotIndexOffset] == 0x81); const auto freeClass = remorse::loadUsecodeClass(*usecode, 0x0a0c); const auto freeTimerBody = freeClass ? remorse::readUsecodeEventBody(*freeClass, 0x32) : std::nullopt; auto boxRenderer = remorse::loadMapSceneRenderer(*root, 1); @@ -540,6 +730,12 @@ int main() [](const auto& left, const auto& right) { return left.red == right.red && left.green == right.green && left.blue == right.blue; })); + const auto boxProcessIdOutput = boxTasks.runtimeMemory().read(registeredBoxContext->processIdOutput, + sizeof(remorse::u16)); + assert(boxProcessIdOutput && (*boxProcessIdOutput)[0] == 0x40 && + (*boxProcessIdOutput)[1] == 0x03 && boxTasks.runtimeMemory().allocationCount() == 5); + assert(boxTasks.remove(0x0340) && boxTasks.size() == 0 && boxTasks.context(0x0340) == nullptr && + boxTasks.runtimeMemory().allocationCount() == 0); assert(!remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows, rechargeItem, retailBases, 0, 9)); std::vector ownerRows(26); diff --git a/rebuild/remorse/tests/usecode_vm_tests.cpp b/rebuild/remorse/tests/usecode_vm_tests.cpp index bd8d993..7126950 100644 --- a/rebuild/remorse/tests/usecode_vm_tests.cpp +++ b/rebuild/remorse/tests/usecode_vm_tests.cpp @@ -1,4 +1,5 @@ #include "remorse/usecode_vm.h" +#include "remorse/usecode_archive.h" #include #include @@ -66,6 +67,96 @@ int main() assert(!remorse::writeUsecodeContextFactoryFields(processContext.data(), processContext.size() - 1, factoryFields)); + remorse::UsecodeRuntimeMemory contextMemory; + const auto contextOwnerSource = contextMemory.allocate(8, 0x11); + const auto contextCodeBytes = contextMemory.allocate(16, 0x22); + const auto contextOwnerRows = contextMemory.allocate(13, 0x33); + assert(contextOwnerSource && contextCodeBytes && contextOwnerRows && + contextMemory.contains({1, contextOwnerSource->segment}, 1) && + !contextMemory.contains({8, contextOwnerSource->segment}, 1)); + remorse::UsecodeContextCreateRequest contextRequest; + contextRequest.ownerSource = remorse::FarPtr16{1, contextOwnerSource->segment}; + contextRequest.codeSource = remorse::FarPtr16{2, contextCodeBytes->segment}; + contextRequest.ownerRows = remorse::FarPtr16{4, contextOwnerRows->segment}; + contextRequest.itemParameter = std::vector{0x34, 0x12}; + contextRequest.contextParameter = contextParameter; + contextRequest.modeFlags = 2; + contextRequest.slotIndex = 0x000a; + contextRequest.valueAddOffset = 0x0020; + const auto contextInstance = remorse::createUsecodeContext(contextMemory, contextRequest); + assert(contextInstance && contextMemory.allocationCount() == 5 && + contextInstance->interpreter.callFrameCount == 1 && + contextInstance->interpreter.callFrames[0].offset == 0x000a && + contextInstance->interpreter.callFrames[0].segment == 0x0020); + const auto contextMemoryBytes = contextMemory.read(contextInstance->processAddress, + remorse::usecodeContextProcessSize); + assert(contextMemoryBytes && std::equal(contextMemoryBytes->begin(), contextMemoryBytes->end(), + contextInstance->processBytes.begin())); + const auto contextCallStack = contextMemory.read(contextInstance->callStackAddress, + remorse::usecodeInterpreterCallStackSize); + assert(contextCallStack && (*contextCallStack)[0] == 0x0a && (*contextCallStack)[1] == 0 && + (*contextCallStack)[2] == 0x20 && (*contextCallStack)[3] == 0 && + (*contextCallStack)[0x80] == 1 && (*contextCallStack)[0x81] == 0); + assert(contextInstance->processBytes[remorse::usecodeContextInterpreterOffset] == + static_cast(contextInstance->callStackAddress.offset) && + contextInstance->processBytes[remorse::usecodeContextInterpreterOffset + 2] == + static_cast(contextInstance->callStackAddress.segment)); + assert(contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset] == 2 && + contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 1] == 0 && + contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 2] == + static_cast(contextCodeBytes->segment) && + contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 3] == 0); + assert(contextInstance->processBytes[remorse::usecodeContextSelfPointerOffset] == + static_cast(contextInstance->processAddress.offset) && + contextInstance->processBytes[remorse::usecodeContextSelfPointerOffset + 2] == + static_cast(contextInstance->processAddress.segment)); + assert(contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset] == 4 && + contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 1] == 0 && + contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 2] == + static_cast(contextOwnerRows->segment) && + contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 3] == 0); + assert(contextInstance->processBytes[remorse::usecodeContextOwnerSourceOffset] == 1 && + contextInstance->processBytes[remorse::usecodeContextOwnerSourceOffset + 2] == + static_cast(contextOwnerSource->segment) && + contextInstance->processBytes[remorse::usecodeContextParameterOffset] == 190 && + contextInstance->processBytes[remorse::usecodeContextModeFlagsOffset] == 2 && + contextInstance->processBytes[remorse::usecodeContextActiveFlagOffset] == 0); + const std::size_t savedPointerLocation = remorse::usecodeContextInterpreterOffset + + contextInstance->interpreter.stackTop; + assert(contextInstance->processBytes[savedPointerLocation] == 0x00 && + contextInstance->processBytes[savedPointerLocation + 1] == 0x01 && + contextInstance->processBytes[savedPointerLocation + 2] == + static_cast(contextInstance->processAddress.segment) && + contextInstance->processBytes[savedPointerLocation + 3] == 0 && + contextInstance->processBytes[0x100] == 0x34 && contextInstance->processBytes[0x101] == 0x12 && + contextInstance->processBytes[0xfc] == 0xa1 && contextInstance->processBytes[0xfd] == 0xb2 && + contextInstance->processBytes[0xfe] == 0xc3 && contextInstance->processBytes[0xff] == 0xd4); + assert(contextInstance->processBytes[remorse::usecodeContextStackPointerOffset] == 0xf8 && + contextInstance->processBytes[remorse::usecodeContextStackPointerOffset + 2] == + static_cast(contextInstance->processAddress.segment) && + contextInstance->processBytes[remorse::usecodeContextStackBaseOffset] == 0x02 && + contextInstance->processBytes[remorse::usecodeContextStackBaseOffset + 1] == 0x01 && + contextInstance->processBytes[remorse::usecodeContextStackLimitOffset] == 199); + assert(remorse::destroyUsecodeContext(contextMemory, *contextInstance) && + contextMemory.allocationCount() == 3); + + remorse::UsecodeContextCreateRequest emptyContextRequest = contextRequest; + emptyContextRequest.contextParameter = std::vector{}; + const auto emptyContextInstance = remorse::createUsecodeContext(contextMemory, emptyContextRequest); + assert(emptyContextInstance && emptyContextInstance->interpreter.contextParameterOffset == 194 && + emptyContextInstance->processBytes[remorse::usecodeContextParameterOffset] == 194); + assert(remorse::destroyUsecodeContext(contextMemory, *emptyContextInstance)); + remorse::UsecodeContextCreateRequest invalidContextRequest = contextRequest; + invalidContextRequest.itemParameter = std::vector{0x34}; + assert(!remorse::createUsecodeContext(contextMemory, invalidContextRequest) && + contextMemory.allocationCount() == 3); + invalidContextRequest = contextRequest; + invalidContextRequest.codeSource = remorse::FarPtr16{0xffff, 0xfffe}; + assert(!remorse::createUsecodeContext(contextMemory, invalidContextRequest) && + contextMemory.allocationCount() == 3); + assert(contextMemory.release(*contextOwnerSource) && contextMemory.release(*contextCodeBytes) && + contextMemory.release(*contextOwnerRows) && contextMemory.allocationCount() == 0); + std::vector code(remorse::usecodeEventBytecodeOffset, 0); code.insert(code.end(), { 0x0a, 0x07, From 6d4972933fb883c1ddaf6c6f8f1939a037608229 Mon Sep 17 00:00:00 2001 From: Maddo Date: Tue, 6 Oct 2026 00:01:20 +0200 Subject: [PATCH 11/14] 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. --- docs/remorse-windows-rebuild-roadmap.md | 10 +- ...e-event-avatar-stole-something-analysis.md | 51 ++ docs/usecode-event-slots-catalog.md | 183 ++++ ...code-event-slots-combine-cast-fast-area.md | 20 +- docs/usecode-format-specification.md | 838 ++++++++++++++++++ docs/usecode-intrinsics-catalog.md | 396 +++++++++ docs/usecode-pentagram-ghidra-path.md | 12 +- docs/usecode-roundtrip-ir.md | 117 ++- docs/usecode-tool-improvement-plan.md | 73 +- docs/usecode-tooling-comparison.md | 35 +- .../include/remorse/entity_dispatch_entry.h | 22 + rebuild/remorse/include/remorse/fixed_map.h | 1 + rebuild/remorse/src/entity_dispatch_entry.cpp | 90 +- rebuild/remorse/src/fixed_map.cpp | 12 + rebuild/remorse/src/windowed_game_main.cpp | 75 +- rebuild/remorse/tests/fixed_map_tests.cpp | 5 + rebuild/remorse/tests/flex_archive_tests.cpp | 42 +- 17 files changed, 1868 insertions(+), 114 deletions(-) create mode 100644 docs/usecode-event-avatar-stole-something-analysis.md create mode 100644 docs/usecode-event-slots-catalog.md create mode 100644 docs/usecode-format-specification.md create mode 100644 docs/usecode-intrinsics-catalog.md diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 548fb34..998383f 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -26,7 +26,7 @@ The immediate target is a fresh game on retail map 1 at the original starting te 5. **Real interaction:** implement one reachable map-1 usecode event through the original item find/grab, VM dispatch, and resulting world-state mutation. Demonstrate a repeatable before/input/after trace and visible effect; a script lookup or release-request counter is not an interaction. 6. **Acceptance:** launch the normal Windows executable with retail data, start map 1 at egg `0x1e`, move and interact without a diagnostic shortcut, and verify on-screen state plus a deterministic integration test. Keep absent combat, audio, menus, persistence, and broader missions listed as limitations, not silently simulated features. -Current blocker: the normal host window resolves egg `0x1e` from map 1 and places host item 1 at that retail record, then routes queued input through host controller and animation processes that mutate the same live item. These are tested host models, not calls through `Game_Start`, `Teleporter_CreateProcessDirect`, or the original kernel loop. A test using the production-equivalent item search at the egg spawn found one candidate and no eligible `use` event. The BOX_NS effect test therefore still uses a fixture origin; a reachable target and original item/event dispatch remain open. Nearby panel/card scripts also require additional VM, timer, selector, and world-state services. +Current blocker: the normal host window resolves egg `0x1e` from map 1 and places host item 1 at that retail record, then routes queued input through host controller and animation processes that mutate the same live item. Startup now models the constructor's clear-stasis waiter and schedules the same-map teleporter over two kernel scans, but these remain host models, not calls through `Game_Start`, `Teleporter_CreateProcessDirect`, or the original scheduler. The ordinary host tick now also scans ready `Gravity` processes through the live-item collision sweep and requests a redraw when a falling item moves, including while the avatar is idle; this is not original scheduler parity. Idle ticks also consume pending usecode frame mutations and wake the renderer, rather than waiting for another movement input. The production-equivalent item search at the egg spawn still finds one candidate and no eligible `use` event. A retail scan finds 218 map-1 use-eligible items; the nearest is `PANELNS` item 288 at `(2919, 1061, 48)`, frame 0, quality 6, map-array 134, at horizontal Manhattan distance 8,818 staged-coordinate units from spawn `(6399, 6399, 0)`. Its recovered handler exits on frame 0 and nonzero map-array. A nearby `CARD_NS` at staged `(2783, 1055, 40)` has frame 0 and `QLo=6`; its `SWITCH::ordinal21` path needs keycard 6 to authorize the visible frame-4 state, and the fresh-game host keycard set is empty. The nearest chest candidate is `CHEST_EW` map-source record 151 at staged `(1087, 2559, 0)`, frame 0, `QLo=5`, 9,152 horizontal units from spawn. Its handler calls `FREE.slot_2d` to test a same-family legal swap to shape `0x054b`, then animates frames 0 through 4 and dispatches `TRIGGER` if the swap succeeds. The host currently lacks that shape-swap service, and no collision route from spawn to this chest has been verified. The nearest frame-0 `BOX_NS` is 18,048 staged-coordinate units away. The BOX_NS effect test remains fixture-origin coverage; no reachable retail interaction or original item/event dispatch is established. ## Current Inputs @@ -505,7 +505,7 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat - **Build foundation:** `remorse_core`, the Windows game, MSVC/CMake build entry point, and focused CTest targets are in place. - **Retail data:** loaders cover the resources used by the current map, rendering, item, and USECODE slices. The preview renderer and Win32 window remain diagnostic infrastructure. - **Process and world state:** partial scheduler/process behavior, staged item placement/search, and selected item-cache operations are compiled and tested. The host does not yet run the original game loop or item runtime. -- **Teleporter startup slice:** live Ghidra evidence confirms `TeleporterProcess` is `0x36` bytes, with vtable `0x0f3a`, target map at `+0x32`, and egg ID at `+0x34`. The host kernel owns this typed process and models its same-map run by resolving a family-8/frame-1 destination whose quality low byte matches the requested ID, then moving item 1. Map loading now creates, runs, and retires this process using a local kernel. It does not port `Game_Start`, temporary-stasis wait, cross-map camera/NPC setup, collision/fall, sound, or original scheduler dispatch. +- **Teleporter startup slice:** live Ghidra evidence confirms `TeleporterProcess` is `0x36` bytes, with vtable `0x0f3a`, target map at `+0x32`, and egg ID at `+0x34`. The host kernel owns this typed process and models its same-map run by resolving a family-8/frame-1 destination whose quality low byte matches the requested ID, then moving item 1. It also models the `0x33`-byte clear-avatar-stasis process and one wait dependency: the first scheduler scan clears prior stasis, and the next runs and retires the teleporter. A retail regression verifies item 1 stays at the origin until the wait completes, then reaches egg `0x1e`. This is not the original `Process_WaitFor` linked-list implementation or `Game_Start`; cross-map camera/NPC setup, collision/fall, sound, and original scheduler dispatch remain unported. - **USECODE:** class/event parsing, a tested opcode subset, task lifecycle, and bounded `CreateFromSlotIndex` context construction are implemented. The window's use request now searches nearby item candidates, applies owner-row event selection, creates a context-backed task, and mirrors the context bytes into the process entry. A retail `BOX_NS` regression follows candidate search through context ownership and VM execution, checks six frame transitions and a rendered pixel change, then verifies output-pointer and allocation cleanup. This remains host-side dispatch with fixture-provided VM services, not original dispatcher parity or a verified interaction from the map-1 spawn. - **Runtime chunks:** the host now models the 0x16-byte `UProcess_1420_0000` record, bounded far-memory allocations for chunk/process buffers, the doubly linked loaded-process list, descriptor-pointer replacement/restoration, and zero-count eviction. Retail `EVENT` and `NPCTRIG` plus a two-node fixture cover load, reuse, release, reload, and unlink behavior. The host materializer reads archive-backed class bytes; parity with the original owner-resource callback and allocator remains unverified. @@ -515,9 +515,9 @@ After the first source-backed interaction, complete the original player/item loo ## Near-Term Next Actions -1. **Close the event path:** identify an eligible retail `use` target reachable from the original map-1 spawn. The exact production-equivalent search at egg `0x1e` currently returns one candidate and no eligible event. Then exercise movement to a real target, owner selection, context creation, and VM execution through supported runtime services, verifying a process/world-state effect. The BOX_NS regression verifies candidate-driven selection and visible frame output from a fixture origin only; it does not close this action or establish `Usecode_ItemCallEvent` parity. -2. **Integrate the map-1 loop:** port `Game_Start` (`1020:0000`) and the teleporter constructor/run lifecycle rather than host initialization; add the stasis wait, original target-map transition and item search, collision/fall, then move input and animation onto the recovered kernel loop. The current tests cover same-map egg resolution, shared item-1 mutation, and host input/scheduler behavior, not those binary lifecycle semantics or source draw-order/camera parity. Keep the normal window on the original path before calling the vertical slice accepted. +1. **Close the event path:** identify and reach an eligible retail `use` target from the original map-1 spawn. The exact production-equivalent search at egg `0x1e` still returns one candidate and no eligible event. 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 prove reachability and implement only the required recovered services, then 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 same-map teleporter over two scheduler scans, 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 same-map egg resolution and the 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. ## Current Bottom Line -The host now materializes archive-backed USECODE chunks and builds tested 0x124-byte contexts with bounded source pointers and an initialized 0x82-byte call stack. Its window routes use-request candidates through owner-row selection into a context-backed task; the BOX_NS regression verifies VM-driven frame changes, rendered output, and cleanup, while a separate retail test confirms no eligible event at the original spawn. Retail egg selection and placement of item 1 are covered, the typed `TeleporterProcess` performs its tested same-map egg move, and a deterministic host input/tick test verifies that the item-owned animation process moves item 1. Original `Game_Start`, the full teleporter lifecycle, `Usecode_ItemCallEvent`/context-dispatch, owner-resource callback parity, a reachable retail interaction, and original loop/render parity remain incomplete. Whole-game and playable-game acceptance remain unmet. +The host now materializes archive-backed USECODE chunks and builds tested 0x124-byte contexts with bounded source pointers and an initialized 0x82-byte call stack. Its window routes use-request candidates through owner-row selection into a context-backed task; the BOX_NS regression verifies VM-driven frame changes, rendered output, and cleanup, while a separate retail test confirms no eligible event at the original spawn and identifies only guarded/far map-wide candidates so far. Retail egg selection and placement of item 1 are covered, and the typed `TeleporterProcess` now runs after the host-modelled clear-stasis wait in a scheduler-driven two-pass test. A deterministic host input/tick test still 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. diff --git a/docs/usecode-event-avatar-stole-something-analysis.md b/docs/usecode-event-avatar-stole-something-analysis.md new file mode 100644 index 0000000..0763077 --- /dev/null +++ b/docs/usecode-event-avatar-stole-something-analysis.md @@ -0,0 +1,51 @@ +# `avatarStoleSomething` (`slot 0x13`) in Crusader + +## Conclusion + +The event name is inherited from Ultima's theft vocabulary, but Crusader's shipped usecode uses the slot mostly as an item-movement notification for environmental objects. The common handler records the passed item id in the running process's metadata under event type `0x022E`, then excludes the process. The inspected handlers do not accuse the avatar, raise an alarm, start combat, or otherwise implement a crime response. + +There are 23 non-empty slot-`0x13` bodies in the inspected Remorse corpus and 18 in Regret. They belong mainly to electrical walls, shock objects, lights, sliding walls, doors, and a sliding floor, rather than dialogue-oriented NPC classes. Two Remorse `MDOOR` handlers launch a door-component cleanup path; `SLIDEFLR` waits for a frame transition and a specific sound state. This makes `avatarStoleSomething` a useful repurposed hook for world-object bookkeeping and synchronization, despite its theft-oriented name. + +## Native dispatch contract + +Ghidra identifies `Item_AvatarStoleSomething` at `10a0:2fda` as intrinsic `0x0B1`. It checks whether the receiving item is an NPC; if so, it suppresses the event when that NPC is dead. Otherwise it calls `Usecode_ItemCallEvent` with mask `0x80000`, slot `UC_AvatarStoleSomething` (`0x13`), and the supplied word argument. The native wrapper therefore establishes the receiver, liveness filter, and payload, but does not itself test ownership or decide whether a move is a theft. + +The event signature is one word, and the Crusader handlers consistently treat it as an item reference. The corresponding ScummVM implementation describes the legacy outer trigger in `Item::movedByPlayer`: avatar-owned items are not stolen; otherwise, nearby living actors are notified with the moved item's id. That source helps explain the inherited label and dispatch convention, but it is cross-implementation evidence, not proof of every original NE movement call site. + +ScummVM's `item.h` has a stale comment calling this event 14; its implementation and converter table use `0x13`, matching the Remorse native dispatcher and the Crusader event table. Use `0x13` as the ordinal. + +## Corpus-wide pattern + +Every one of the 41 inspected Remorse and Regret handlers executes `set_info(0x022E, *(arg_06))` followed by `process_exclude()`. In the local VM model, opcode `0x77` routes those operands to process metadata as `(eventType, sourceItem)`, and `ProcessKernel::setProcessInfo` stores those fields on the running process. The strongest supported reading is therefore that each callback tags its process with event type `0x022E` and the item id that prompted the callback. + +No `get_info(0x022E)` reads were found in the inspected usecode exports. Treat `0x022E` as an opaque process-event tag; its higher-level consumer or meaning has not been established. In particular, the handlers do not show that this is a global theft flag or alarm state. + +The broad classes and variant structure are consistent across both games: + +- Remorse has 23 handlers: two WSHOCK, two EWALL, two ETWALL, eight L_* lights, two MDOOR, six SL_* sliding walls, and one SLIDEFLR. +- Regret has 18 handlers: two WSHOCK, two EWALL, eight L_* lights, and six SL_* sliding walls. +- Apart from MDOOR and SLIDEFLR, the handlers only set the process info and exclude the process; no speech, alarm, attack, or stolen-item punishment appears in their bodies. + +## Specialized handlers + +### MDOOR + +`MDOOR_E::avatarStoleSomething` and `MDOOR_N::avatarStoleSomething` both store the moved-item id under `0x022E`, exclude the current process, spawn `DOOR.slot_22` with that item id, and suspend while the child process runs. The east variant also creates two helper items, shapes `0x02F1` and `0x04CE`, at coordinates derived from the moved item before launching the door process; the north variant goes directly to the child process. + +There is an extraction discrepancy worth preserving: the simplified [Crusader_Decomp MDOOR_E pseudocode](../USECODE/EUSECODE_extracted/pseudocode/MDOOR_E/slot_13_avatarStoleSomething.txt) lists the helper locals but omits their create/position calls. Those calls are present in the [Remorse site-data export](../../crusader_map_viewer/map_renderer/site/data/usecode/remorse/EUSECODE/pseudocode/MDOOR_E/slot_13_avatarStoleSomething.txt) and the raw [Crusader usecode disassembly](../../crusader-disasm/crusader_disasm.txt) under `MDOOR_E::AvatarStoleSomething`. The helper-item detail above relies on those corroborating representations. + +`DOOR::ordinal22` (`0A06:0022`) records the passed item as process info type `0x0001`, reads its QLo and QHi values, scans door/roof-related shape sets, and iterates shape `0x04F8` candidates. It destroys candidates whose QLo matches both values from the passed item. The class's loop metadata is only partly reconstructed, so the exact roles of every scanned shape remain uncertain; the verified behavior is a quality-keyed search and removal of matching door-associated pieces. This is a concrete environmental cleanup path, not a social theft reaction. + +### SLIDEFLR + +`SLIDEFLR::avatarStoleSomething` first performs the common `0x022E` process-info write. If the passed item is at frame `9`, it polls every four ticks until the frame changes. It then polls every two ticks until sound effect `81` is playing for that item. The handler does not start the sound itself. Its visible role is to synchronize with an existing floor animation/audio transition. + +## Interpretation and limits + +The most defensible Crusader-specific description is **item-movement notification and environmental state coordination**. The payload identifies the moved item; ordinary handlers record that identity, while the MDOOR and SLIDEFLR variants use it to coordinate related world pieces. The event name describes its inherited origin better than its present scripted effects. + +This conclusion is about the authored handlers and the native per-receiver dispatcher. The exact condition that calls the dispatcher in the original executable is not established by this function alone. The ScummVM movement routine is useful corroboration for the legacy trigger, but should not be silently treated as a byte-for-byte native call-site proof. + +## Simplified explanation + +Think of slot `0x13` as: “An item just moved; here is its id.” Most Crusader objects simply record that id. A few doors and floors use it to clean up or synchronize related pieces. In practice, it behaves more like an environmental update hook than a theft alarm. \ No newline at end of file diff --git a/docs/usecode-event-slots-catalog.md b/docs/usecode-event-slots-catalog.md new file mode 100644 index 0000000..1b04337 --- /dev/null +++ b/docs/usecode-event-slots-catalog.md @@ -0,0 +1,183 @@ +# Crusader USECODE Event Slot Catalog + +**Status:** Evidence-backed working catalog; event names and signatures remain hints unless corroborated below. +**Scope:** Main local Remorse and Regret owner-loaded `EUSECODE.FLX` corpora. Demo, Japanese, and 1.01 variants are excluded from the counts. +**Last consolidated:** 2026-10-05 + +This companion expands the event-slot summary in the [USECODE format specification](./usecode-format-specification.md). It records the common event names, local body coverage, known native callers and source-port behavior, class-local higher slots, and targeted open questions. It complements the per-ordinal [intrinsic catalog](./usecode-intrinsics-catalog.md): an event slot selects a class callback; an intrinsic ordinal selects a native function from bytecode. + +## Reading the Evidence + +- **Body count** is the number of non-empty, derived class/slot body windows in the named local corpus. It is not a count of runtime executions, reachable objects, or call sites. +- **Zero bodies** means the scanned corpus has no non-empty body at that slot. It does not mean the executable cannot dispatch that slot. +- **Source label** means a converter/disassembler name. It is a navigation hint, not proof of one universal behavior. +- **Native route** means a direct caller of `Usecode_ItemCallEvent` was identified in the live Remorse `CRUSADER.EXE` Ghidra session. This is direct evidence for Remorse only; Regret's per-slot values below are corpus evidence, not a separate native-binary audit. +- **Class-local** means the same numeric slot can do different work in different classes. This is especially important above `0x1F`. +- Body byte ranges are inclusive sizes from `derived_body_length` in the extracted event index. They are useful for prioritization, not semantic evidence. + +## Dispatch Model + +The event ordinal is resolved in the selected class's event table. Bytecode class/event calls (`0x11`) and spawned class/event processes (`0x57`, `0x58`) carry a class id and slot; they do not call a globally named event function. A body can therefore be reached by a script even when there is no engine-native wrapper with that name. + +In the Remorse executable, `Usecode_ItemCallEvent` (`1420:0e3a`) checks a per-class event capability mask and passes the class id and `UC_*` event ordinal into the runtime context-creation path. The common native wrappers use bit masks corresponding to the low event ordinals (`1 << slot`). For example, the verified masks for `equip`, `unequip`, `combine`, `cast`, and `unhatch` are `0x0400`, `0x0800`, `0x1000`, `0x20000`, and `0x200000`. The dispatcher is shared machinery; an event-specific native caller and a non-empty class body are separate facts. + +The local extractor derives body windows from owner-loaded class records; its event-count/base-offset disagreement with ScummVM and Pentagram remains open. See [the format specification](./usecode-format-specification.md#33-event-countbase-offset-disagreement) and [round-trip IR notes](./usecode-roundtrip-ir.md). + +## Corpus Coverage + +| Variant | Non-empty bodies | Common slots with bodies | Higher populated slots | Highest observed body slot | +|---|---:|---:|---|---:| +| Remorse | 977 | 15 of 32 | Every slot `0x20..0x4B` (44 slots) | `0x4B` | +| Regret | 1,152 | 14 of 32 | Every slot `0x20..0x51` (50 slots) | `0x51` | + +The common-slot counts below come from the extracted `class_event_index.tsv` files under `USECODE/EUSECODE_extracted/` and `USECODE/REGRET/REGRET_USECODE_extracted/`. The higher-slot table adds per-slot body counts and byte-length ranges. Every common slot `0x00..0x1F` is listed, including zero-body slots; higher rows cover every slot with at least one body in either main corpus. + +## Common Slots `0x00..0x1F` + +The labels in the second column follow ScummVM's Crusader converter table where available. Pentagram's older Crusader converter retains `func*` placeholders for some names that can be corroborated by the native binary. Source-level argument lists are not assumed to be the exact USECODE body ABI. + +| Slot | Converter label / variant note | Remorse / Regret bodies | Evidence, current interpretation, and next investigation | +|---:|---|---:|---| +| `0x00` | `look()` | 1 / 0 | Remorse has one body; Regret has none. The native `Item_Look` route and ScummVM item-selection path identify this as inspection/looking. Inspect the sole body and its selected-item context; do not infer that all `look` interactions are script-backed. | +| `0x01` | `use()` | 66 / 80 | Main item-use/activation callback. Native `Item_Use` has two dispatcher call sites; ScummVM also invokes it from item selection and actor-use paths. This is the best-covered public interaction slot, but class behavior is intentionally heterogeneous. Trace selected examples from input through class selection and note any caller-supplied state. | +| `0x02` | `anim()` | 0 / 0 | Native `DList_AnimateShapes` calls `Item_Anim` for animation type 5; that branch invokes the event and performs no separate frame step. Both corpora lack bodies, so no script animation behavior is available there. ScummVM shares this path; Pentagram disables non-`use` Crusader callbacks. Find type-5 authored objects and check omitted builds. | +| `0x03` | `setActivity()` | 0 / 0 | Native `NPC_SetActivity` offers `UC_SetActivity` before `NPC_StartNextNPCActivityBehaviorProcess`; if dispatch is not handled, ordinary NPC activity behavior is started. The original Crusader route is real despite zero bodies. The name is inherited from the U8 event table, but no U8 event-`0x03` producer was found in the inspected source ports. Recover its argument layout and check the original U8 caller before claiming runtime inheritance. | +| `0x04` | `cachein()` | 22 / 35 | Native `Item_Cachein` dispatches only when a current map array exists. ScummVM's map-load path calls cache-in on items and actors. Best current meaning is map/cache-in initialization. Determine exact ordering relative to item registration and whether nested loads can re-enter it. | +| `0x05` | `hit(uword, word)` | 13 / 12 | Outgoing hit/attack callback. Collision handling calls `hit` on the mover/attacker with the other item id and hit-force value; `Item_Hit` is the native wrapper. Compare this with slot `0x06` to settle directionality and the hit-force calculation for each collision path. | +| `0x06` | `gotHit(uword, word)` | 197 / 248 | Incoming damage/collision reaction; it is the most widespread common handler. `Item_GetDamaged` is the native route, and ScummVM also calls it from collision and damage code. Separate collision notification from actual health damage; inspect callers that pass zero or packed damage-type values. | +| `0x07` | `hatch()` | 28 / 26 | Egg/spawn appearance callback. ScummVM's `Egg::hatch` is one-shot and returns the callback process id; native `Item_CallHatchEvent` is a direct route. Identify which class families are hatchable eggs versus other spawn initialization and record whether the event is synchronous or process-backed. | +| `0x08` | `schedule()` | 0 / 0 | Native `NPC_Schedule` checks liveness, may clear combat state outside the fast area, and dispatches `UC_Schedule` with a 32-bit time value (mask `0x0100`). The converter label omits that payload. With no body, the wrapper returns no usecode process. Resolve time units and determine whether other builds contain schedule scripts. | +| `0x09` | `release()` | 9 / 10 | Native `Item_Release` dispatches with no explicit event payload. ScummVM also calls release during movement/collision cleanup. The broad read is release/removal cleanup; trace all retail call sites to distinguish uncache, collision exit, and ownership transitions. | +| `0x0A` | `equip()`; Pentagram Crusader table says `func0A(sint16)` | 77 / 125 | Native `Item_Equip` dispatch is verified with mask `0x0400`. In Crusader it is generalized into mode application, arming, setup, and actor initialization, not just wearable equipment. See [the equipment-system analysis](./usecode-equipment-system.md). Next, classify parameterized versus no-parameter call sites and avoid translating every use as literal equipment. | +| `0x0B` | `unequip()`; Pentagram Crusader table says `func0B(sint16)` | 50 / 47 | Native `Item_Unequip` dispatch is verified with mask `0x0800`; scripts commonly disable, disarm, or reverse slot-`0x0A` behavior. See [the equipment-system analysis](./usecode-equipment-system.md). Compare matching class pairs and determine which native callers pass a related object id or mode. | +| `0x0C` | `combine()` | 0 / 0 | Native `Item_Combine` dispatch exists, but neither corpus has a slot body or direct `.combine()` class-event call. Remorse intrinsic `0x00CF` (`Item::I_setQAndCombine`) is used twice in `MISS1EGG::cachein`: it writes item quality, then attempts this event. The callback process id is discarded, so the event cannot gate that write. This is a notification hook, not the merge algorithm. See [the combine/cast/fast-area analysis](./usecode-event-slots-combine-cast-fast-area.md). | +| `0x0D` | `func0D` | 0 / 0 | No semantics or direct native dispatcher caller have been established. Preserve the raw slot. Search alternate corpora and native callsites, then inspect any class row before assigning a name. | +| `0x0E` | `calledFromAnim()` | 27 / 43 | ScummVM's animation tracker invokes this callback; it is an animation-originated event lane, not the same thing as `anim` (`0x02`). Determine the animation condition and payload at the original native call site and compare representative class bodies. | +| `0x0F` | `enterFastArea()` | 108 / 107 | Native item movement enters this path when crossing into a fast area. Corpus evidence points to authored proximity/activation regions for spawners, timers, and controllers, not a movement-speed modifier. See [the fast-area analysis](./usecode-event-slots-combine-cast-fast-area.md). Future work: establish exact boundary/flag behavior and per-class state transitions. | +| `0x10` | `leaveFastArea()` | 52 / 52 | Exit counterpart to `enterFastArea`; used by timers and controller classes to disarm or advance phase logic. It can be bypassed for camera-followed items, so do not assume every geometric exit fires the callback. Compare enter/leave pairs class by class. | +| `0x11` | `cast(uword)`; Pentagram Crusader table says `func11(sint16)` | 1 / 8 | Native `Item_Cast` dispatch is verified with mask `0x20000`. Crusader usecode uses this for scripted activation/dispatch, not a general spell system: Remorse's sole body is an avatar map/music hook; Regret has controller/keypad examples. See [the combine/cast/fast-area analysis](./usecode-event-slots-combine-cast-fast-area.md). Resolve the apparent argument-width/name difference against real callers. | +| `0x12` | `justMoved()` | 0 / 0 | Native `Item_JustMoved` dispatch exists. ScummVM calls it after an item is moved in the world or moved into a container. No local body is present, so the known paths have no authored callback in these corpora. Check whether this is a retained compatibility hook or used in omitted builds. | +| `0x13` | `avatarStoleSomething(uword)` | 23 / 18 | In Crusader, a moved-item notification used mainly by environmental classes: handlers tag process metadata with `0x022E` and the item id; MDOOR starts door-piece cleanup and SLIDEFLR synchronizes animation/audio. The native wrapper skips dead NPC receivers before dispatch. See [the detailed analysis](./usecode-event-avatar-stole-something-analysis.md). | +| `0x14` | `animGetHit()` | 0 / 0 | Native `Item_AnimGetHit` exists and accepts a word-sized native parameter, while the converter label shows no argument. Distinct from the general incoming-hit slot `0x06`; neither corpus has a body. Recover callers and determine whether the word identifies a hit animation, attacker, or mode. | +| `0x15` | Crusader `unhatch(word)`; U8 `guardianBark(word)`; Pentagram Crusader table says `func15` | 5 / 6 | Native `Item_CallUnhatchEvent` dispatch exists; ScummVM invokes it from Crusader egg unhatching. The local name `unhatch` is supported for Crusader, but the converter's `word` argument conflicts with the wrapper path that exposes no explicit event argument. Keep the U8 `guardianBark` label separate and recover the exact payload before documenting a signature. | +| `0x16` | `func16` | 0 / 0 | Unknown placeholder. No direct native dispatcher caller identified in the Remorse caller scan. Search the complete class tables and alternate builds; retain the numeric id unless a body or call path supplies evidence. | +| `0x17` | `func17` | 0 / 0 | Unknown placeholder. No direct native dispatcher caller identified in the Remorse caller scan. Search the complete class tables and alternate builds; retain the numeric id unless a body or call path supplies evidence. | +| `0x18` | `func18` | 0 / 0 | Unknown placeholder. No direct native dispatcher caller identified in the Remorse caller scan. Search the complete class tables and alternate builds; retain the numeric id unless a body or call path supplies evidence. | +| `0x19` | `func19` | 0 / 0 | Unknown placeholder. No direct native dispatcher caller identified in the Remorse caller scan. Search the complete class tables and alternate builds; retain the numeric id unless a body or call path supplies evidence. | +| `0x1A` | `func1A` | 0 / 0 | Unknown placeholder. No direct native dispatcher caller identified in the Remorse caller scan. Search the complete class tables and alternate builds; retain the numeric id unless a body or call path supplies evidence. | +| `0x1B` | `func1B` | 0 / 0 | Unknown placeholder. No direct native dispatcher caller identified in the Remorse caller scan. Search the complete class tables and alternate builds; retain the numeric id unless a body or call path supplies evidence. | +| `0x1C` | `func1C` | 0 / 0 | Unknown placeholder. No direct native dispatcher caller identified in the Remorse caller scan. Search the complete class tables and alternate builds; retain the numeric id unless a body or call path supplies evidence. | +| `0x1D` | `func1D` | 0 / 0 | Unknown placeholder. No direct native dispatcher caller identified in the Remorse caller scan. Search the complete class tables and alternate builds; retain the numeric id unless a body or call path supplies evidence. | +| `0x1E` | `func1E` | 0 / 0 | Unknown placeholder. No direct native dispatcher caller identified in the Remorse caller scan. Search the complete class tables and alternate builds; retain the numeric id unless a body or call path supplies evidence. | +| `0x1F` | `func1F` | 0 / 0 | Unknown placeholder. No direct native dispatcher caller identified in the Remorse caller scan. Search the complete class tables and alternate builds; retain the numeric id unless a body or call path supplies evidence. | + +### Native Event Routes Confirmed in Remorse + +The live Ghidra caller scan found direct `Usecode_ItemCallEvent` callers for every named common event except `0x0D` and `0x16..0x1F`. These are the direct dispatcher callsite addresses, not necessarily the containing function entry addresses: + +| Slot | Native caller | Dispatcher callsite(s) | +|---:|---|---| +| `0x00` | `Item_Look` | `10a0:25bb` | +| `0x01` | `Item_Use` | `10a0:26d9`, `10a0:26ff` | +| `0x02` | `Item_Anim` | `10a0:28f9` | +| `0x03` | `NPC_SetActivity` | `10e8:2bbc` | +| `0x04` | `Item_Cachein` | `10a0:2abd` | +| `0x05` | `Item_Hit` | `10a0:274a` | +| `0x06` | `Item_GetDamaged` | `10a0:287f` | +| `0x07` | `Item_CallHatchEvent` | `1090:0647` | +| `0x08` | `NPC_Schedule` | `10e8:30e7` | +| `0x09` | `Item_Release` | `10a0:2a20` | +| `0x0A` | `Item_Equip` | `10a0:2a53` | +| `0x0B` | `Item_Unequip` | `10a0:2a86` | +| `0x0C` | `Item_Combine` | `10a0:2aec` | +| `0x0E` | `Item_CalledFromAnim` | `10a0:2b1b` | +| `0x0F` | `Item_EnterFastArea` | `10a0:2d96` | +| `0x10` | `Item_LeaveFastArea` | `10a0:2f29` | +| `0x11` | `Item_Cast` | `10a0:2f5c` | +| `0x12` | `Item_JustMoved` | `10a0:2f8b` | +| `0x13` | `Item_AvatarStoleSomething` | `10a0:302d` | +| `0x14` | `Item_AnimGetHit` | `10a0:2fbe` | +| `0x15` | `Item_CallUnhatchEvent` | `1090:0676` | + +Absence from this direct caller scan is not proof of impossibility: scripts can dispatch class/slot pairs through bytecode, and generic VM paths may not have event-specific native wrapper names. The native caller scan was performed against Remorse only. + +## Higher Class-Local Slots + +No common event-name table provides stable semantics for these ordinals. The examples below are deliberately local to the named class; they do not name the slot globally. For rows without a specific example, the next step is to enumerate owning classes, trace bytecode call/spawn edges, then compare representative bodies within and across variants. + +| Slot | Remorse bodies (byte range) | Regret bodies (byte range) | Known class-local evidence / next investigation | +|---:|---:|---:|---| +| `0x20` | 67 (44-9919) | 70 (19-8200) | `TRIGGER.slot_20` is a widely reused controller fan-out entry; `TIMER`, `SPECIAL`, and other classes also use high slots as workers. `TRIGGER.slot_20` still has unresolved branches. Do not equate every slot-`0x20` body. | +| `0x21` | 38 (49-9901) | 35 (11-4943) | `SPECIAL.slot_21` is a phase/delay worker; environmental families also use it. Compare owner class and caller arguments before describing other bodies. | +| `0x22` | 18 (49-2581) | 18 (17-1134) | `SURCAMNS` / `SURCAMEW` slot `0x22` bodies are a repeated callback-family near-template. Compare exact bodies and x/y variants; do not promote the template label to a shared event meaning. | +| `0x23` | 14 (45-8823) | 15 (26-12307) | `DOOR.slot_23` is used in a destroyable-door helper path; `TRIGGER.slot_23` also has class-local phase cases. Separate same-ordinal bodies by class and callsite. | +| `0x24` | 12 (61-1626) | 12 (14-1136) | `TRIGGER.slot_24` appears in the movable-wall trigger family; its case-2 branch is currently a match scan. Inspect other owners independently. | +| `0x25` | 11 (55-1439) | 10 (15-995) | Class-local only in current evidence. Enumerate owners and caller tuples; preserve raw ids. | +| `0x26` | 9 (106-1743) | 8 (34-1141) | `TRIGGER.slot_26` has a documented match-scan branch. Other class bodies remain unclassified. | +| `0x27` | 8 (223-1560) | 7 (193-1088) | Class-local only in current evidence. Compare body families and caller arguments before assigning a name. | +| `0x28` | 8 (44-4328) | 7 (12-947) | Class-local only in current evidence. The broad body-size spread makes a single shared interpretation especially unsafe. | +| `0x29` | 8 (83-1716) | 7 (23-1199) | `TRIGGER.slot_29` participates in actor-key updates, including writes to mutable actor field `0x63`. Trace each subcommand and its matched-actor filters. | +| `0x2A` | 8 (96-1425) | 7 (49-997) | Class-local only in current evidence. Enumerate owners and distinguish direct calls from spawned worker processes. | +| `0x2B` | 8 (73-1785) | 7 (46-1292) | `TRIGGER.slot_2B` also participates in actor-key updates. Compare against slot `0x29` and identify exactly which branch mutates field `0x63`. | +| `0x2C` | 5 (79-278) | 6 (112-875) | Class-local only in current evidence; inspect the small owner set and caller payloads. | +| `0x2D` | 5 (264-764) | 6 (217-537) | `ITEM.slot_2D` checks nearby shape `0x04D0` objects and compares `QLo`; `MONSTER` also uses a high-slot worker. These are separate class semantics. | +| `0x2E` | 5 (106-392) | 6 (30-302) | Class-local only in current evidence; inspect owners and call chains. | +| `0x2F` | 3 (285-314) | 6 (168-818) | Class-local only in current evidence; inspect owners and call chains. | +| `0x30` | 3 (142-553) | 6 (53-303) | Class-local only in current evidence; inspect owners and call chains. | +| `0x31` | 3 (398-1048) | 4 (205-508) | Class-local only in current evidence; inspect owners and call chains. | +| `0x32` | 3 (181-767) | 4 (31-421) | Class-local only in current evidence; inspect owners and call chains. | +| `0x33` | 3 (49-1097) | 4 (98-424) | Class-local only in current evidence; inspect owners and call chains. | +| `0x34` | 3 (136-588) | 4 (29-325) | Class-local only in current evidence; inspect owners and call chains. | +| `0x35` | 3 (97-741) | 4 (32-328) | Class-local only in current evidence; inspect owners and call chains. | +| `0x36` | 3 (91-703) | 4 (150-386) | Class-local only in current evidence; inspect owners and call chains. | +| `0x37` | 3 (89-731) | 4 (174-389) | Class-local only in current evidence; inspect owners and call chains. | +| `0x38` | 3 (78-728) | 4 (168-397) | Class-local only in current evidence; inspect owners and call chains. | +| `0x39` | 3 (106-728) | 4 (144-397) | Class-local only in current evidence; inspect owners and call chains. | +| `0x3A` | 3 (96-804) | 4 (215-443) | Class-local only in current evidence; inspect owners and call chains. | +| `0x3B` | 3 (221-1087) | 4 (75-449) | Class-local only in current evidence; inspect owners and call chains. | +| `0x3C` | 3 (426-695) | 4 (14-389) | Class-local only in current evidence; inspect owners and call chains. | +| `0x3D` | 3 (67-333) | 4 (93-267) | Class-local only in current evidence; inspect owners and call chains. | +| `0x3E` | 3 (77-2359) | 4 (36-2204) | Class-local only in current evidence; inspect owners and call chains. | +| `0x3F` | 3 (61-2379) | 4 (36-2070) | Class-local only in current evidence; inspect owners and call chains. | +| `0x40` | 3 (174-430) | 4 (33-340) | Class-local only in current evidence; inspect owners and call chains. | +| `0x41` | 3 (89-386) | 4 (35-542) | Class-local only in current evidence; inspect owners and call chains. | +| `0x42` | 2 (231-386) | 4 (47-553) | Class-local only in current evidence; inspect owners and call chains. | +| `0x43` | 2 (87-244) | 4 (35-275) | Class-local only in current evidence; inspect owners and call chains. | +| `0x44` | 2 (109-231) | 4 (190-814) | Class-local only in current evidence; inspect owners and call chains. | +| `0x45` | 2 (301-1557) | 3 (205-1025) | Class-local only in current evidence; inspect owners and call chains. | +| `0x46` | 2 (280-1553) | 3 (31-1015) | Class-local only in current evidence; inspect owners and call chains. | +| `0x47` | 2 (301-426) | 3 (55-474) | Class-local only in current evidence; inspect owners and call chains. | +| `0x48` | 2 (280-534) | 2 (27-178) | Class-local only in current evidence; inspect owners and call chains. | +| `0x49` | 1 (1953-1953) | 2 (158-164) | Only one Remorse body and two short Regret bodies. Identify owners before comparing; a long Remorse body is not evidence of shared meaning. | +| `0x4A` | 1 (1553-1553) | 2 (49-274) | Only one Remorse body and two Regret bodies. Inspect the single-owner scripts and whether they are called from another high-slot worker. | +| `0x4B` | 1 (426-426) | 1 (450-450) | One body in each corpus; no shared semantic label. Compare exact class identity and callsites. | +| `0x4C` | 0 | 1 (274-274) | Regret-only body in the scanned corpora. Determine whether this is title-specific logic or a build/content difference. | +| `0x4D` | 0 | 1 (450-450) | Regret-only body in the scanned corpora. Determine whether this is title-specific logic or a build/content difference. | +| `0x4E` | 0 | 1 (296-296) | Regret-only body in the scanned corpora. Determine whether this is title-specific logic or a build/content difference. | +| `0x4F` | 0 | 1 (300-300) | Regret-only body in the scanned corpora. Determine whether this is title-specific logic or a build/content difference. | +| `0x50` | 0 | 1 (313-313) | Regret-only body in the scanned corpora. Determine whether this is title-specific logic or a build/content difference. | +| `0x51` | 0 | 1 (300-300) | Highest observed non-empty slot in Regret. Determine whether this is title-specific logic or a build/content difference. | + +The higher-slot examples above are backed by the generated pseudocode and event indexes, not by globally meaningful event names. Useful starting points include [map-viewer trigger links](./map_renderer/trigger-usecode-links.md), [the movable-wall investigation](./movable-wall-trigger-investigation.md), [the map spawner investigation](./map_1_spawners_targeted_investigation.md), and [the FLICTEST investigation](./usecode/flictest-investigation.md). `TRIGGER.slot_20`, for example, is a class-specific worker reached by scripts; it is not a universal VM event callback. + +## Investigation Queue + +1. Audit the omitted demo, Japanese, and 1.01 archives for zero-body common slots, especially `0x02`, `0x03`, `0x08`, `0x0C`, `0x12`, and `0x14`. +2. Recover original native callers and parameter layouts for `setActivity`, `schedule`, `animGetHit`, and `unhatch`; keep converter prototypes separate from observed stack arguments. +3. Search the Remorse binary and available Regret builds for direct native routes to `0x0D` and `0x16..0x1F`; lack of a current xref is not proof that generic bytecode dispatch rejects them. +4. Run the same native event-wrapper/caller audit against a live Regret executable. Current Ghidra caller evidence in this catalog is Remorse-only. +5. Generate a class-owner and bytecode call/spawn index for every high slot. Prioritize `0x20..0x2B`, where existing notes already show controller, timer, camera, door, and actor-key families. +6. For each high slot with only one or two bodies, inspect the complete body and its callers before deciding whether the slot is private helper code, a title-specific callback, or dead content. +7. Resolve the event-table count/base-offset conflict independently of event semantics; preserve raw rows and offsets while it remains open. + +## Source and Related Notes + +- [Central format specification](./usecode-format-specification.md) +- [Detailed intrinsic catalog](./usecode-intrinsics-catalog.md) +- [Equipment events](./usecode-equipment-system.md) +- [Combine, cast, and fast-area events](./usecode-event-slots-combine-cast-fast-area.md) +- [ScummVM Crusader converter event labels](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/convert/crusader/convert_usecode_crusader.h) +- [ScummVM item event dispatch and callers](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/world/item.cpp) +- [ScummVM egg callbacks](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/world/egg.cpp) +- [ScummVM scheduler callback](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/world/actors/scheduler_process.cpp) +- Pentagram comparison sources: `misc/pentagram/convert/crusader/ConvertUsecodeCrusader.h`, `misc/pentagram/convert/u8/ConvertUsecodeU8.h`, and `misc/pentagram/world/Item.cpp`. Pentagram's `Item::callUsecodeEvent` explicitly suppresses Crusader event execution except for `use`; treat that as a port limitation, not as original executable evidence. \ No newline at end of file diff --git a/docs/usecode-event-slots-combine-cast-fast-area.md b/docs/usecode-event-slots-combine-cast-fast-area.md index 2c72e99..1fb118b 100644 --- a/docs/usecode-event-slots-combine-cast-fast-area.md +++ b/docs/usecode-event-slots-combine-cast-fast-area.md @@ -4,7 +4,7 @@ This note checks whether the suspicious inherited event labels `combine` (`slot ## Summary -- `combine` survives in the inherited event vocabulary, but current shipped Crusader exports do **not** show any recovered `slot_0C` handler bodies. +- `combine` survives in the event vocabulary and has a live Remorse native dispatch path, but current shipped Crusader exports do **not** show any recovered `slot_0C` handler bodies. - `cast` is used in Crusader, but the live behaviors look like explicit scripted activation/dispatch lanes, not a classic RPG spell system. - `fast area` in Crusader is best read as an authored proximity/trigger region around an object or controller. Entering or leaving that region fires usecode callbacks. @@ -14,6 +14,10 @@ Primary evidence for this note comes from the generated pseudocode exports in `C ## `combine` (`slot 0x0C`) +### In simple terms + +Think of `combine` as an optional reaction hook, not a command to merge items: native code updates an item's Q (used here as its quantity) and may then ask the item's class script to handle slot `0x0C`. The native stack routine does the actual merging. The inspected Remorse scripts have no handler for this slot, so there is no extra usecode reaction and the native quantity or stack operation continues. + ### What is actually present - The inherited Crusader/U8 event table still names event `C` as `combine`. @@ -22,7 +26,17 @@ Primary evidence for this note comes from the generated pseudocode exports in `C - `remorse-101` - `remorse-demo` - `regret` -- The same exported pseudocode search also found **zero** `.combine(` callsites. +- The exported pseudocode search found **zero direct class-event `.combine(...)` callsites**. This does not mean the native event is never attempted: Remorse usecode calls the separate `Item::I_setQAndCombine` intrinsic twice in `MISS1EGG::cachein`. + +### What the Remorse executable does + +Ghidra identifies `10a0:0dd1` as the native handler for Remorse intrinsic `0x00CF`, `Item::I_setQAndCombine(Item *, int16 q)`. The body writes `q` into the item's quality field, calls `Item_Combine`, and returns; the intrinsic catalog counts two calls in one Remorse event body. In `MISS1EGG::cachein` (`class_id 0x090D`, slot `0x04`), both release and non-release branches create a `BA_41_CLIP`, set its quantity to `25` through this intrinsic, then continue moving the item into the avatar's inventory. + +`Item_Combine` (`10a0:2ad2`) is only a callback wrapper. It invokes `Usecode_ItemCallEvent` with mask `0x1000` and `UC_Combine` (slot `0x0C`), returning the created process id if the event is handled, otherwise `0`. Its only direct native caller in the Remorse xref scan is `Item_SetQAndCallCombineEvent` (`10a0:0dd1`). That helper ignores the returned process id and returns `void`; it neither waits for the callback nor uses it to approve or reject the quantity change. + +The actual item merge is performed by its caller. For example, `Item_TryStackItems` checks equal shape and quantity/reagent family (and equal frame for reagents), sums the quantities, then either updates one stack and destroys the other or caps one at `0x29A` and leaves the remainder on the second. It calls the quality-and-event helper during those updates. `Item_Create`, `NPC_UseOneShot`, and `NPC_CheckForEmptyAmmo` also use the helper for initial or changing weapon/ammo quantities. So slot `0x0C` is a post-quality-change notification hook in these paths, not the item-merging algorithm. + +The usecode intrinsic `0x00CF` is Remorse-specific: the Regret intrinsic catalog maps ordinal `0x00CF` to `Item::isOn`, not `Item::I_setQAndCombine`. Do not transfer this intrinsic number across games. ### What related behavior still exists @@ -32,7 +46,7 @@ Primary evidence for this note comes from the generated pseudocode exports in `C ### Best current read -`combine` should stay treated as a historical or compatibility label in the decompiler, not as a confirmed active Crusader event family. The name likely came forward from the inherited Ultima-style event vocabulary, while the shipped Crusader usecode corpus no longer exposes recovered slot-`0x0C` handlers. +`combine` is a confirmed native callback slot, but it has no recovered handler body in the inspected corpora. In Remorse, a real usecode intrinsic call sets an item's quantity and attempts the callback; because no class has a slot-`0x0C` body, there is no authored callback behavior in those archives. The intrinsic's quantity write and its caller's inventory/stack logic still proceed. A direct bytecode class/event call to slot `0x0C` would use ordinary class/slot dispatch; it would not implicitly combine two items. ## `cast` (`slot 0x11`) diff --git a/docs/usecode-format-specification.md b/docs/usecode-format-specification.md new file mode 100644 index 0000000..840df05 --- /dev/null +++ b/docs/usecode-format-specification.md @@ -0,0 +1,838 @@ +# Crusader USECODE Format and Runtime Specification + +**Status:** Evidence-backed working specification +**Scope:** Crusader: No Remorse and Crusader: No Regret USECODE archives, class records, event dispatch, bytecode, and runtime services +**Last consolidated:** 2026-10-05 + +This document is the central format reference for Crusader USECODE in this repository. It combines local retail-binary observations with the ScummVM and Pentagram implementations. It is deliberately explicit about confidence: a shared name or parser convention is not treated as proof of retail behavior when the local binary evidence disagrees. + +“Definitive” here means the current, auditable statement of what is known and what remains unsettled. It does **not** mean every opcode, intrinsic, or event has been semantically recovered. In particular, intrinsic numbers are game/build-specific, some opcode names conflict with observed parser behavior, and parts of class-event records remain unknown. + +## 1. What USECODE is + +USECODE is Crusader's object-oriented, event-driven bytecode system. A class has a set of numbered event slots. When the engine or another script dispatches an event, the runtime resolves the class and event slot to bytecode, constructs an interpreter/process context, and runs the event body. Scripts use VM operations for local/member/global data, arithmetic, branching, strings and lists, and process control. They access most game-world and presentation behavior through **intrinsics**: native functions supplied by the particular game executable. + +The complete behavior of a USECODE program is therefore the combination of: + +1. the archive and class/event records; +2. the bytecode and its VM semantics; +3. the executable's event-dispatch rules and intrinsic table; +4. the game data and current world/process state. + +Bytecode alone does not define the semantics of an intrinsic ordinal. Remorse and Regret must not be assumed to share the same intrinsic numbering or signatures. + +## 2. Evidence and terminology + +Use these terms when reading this specification and related analysis: + +- **Observed** — directly checked in local Crusader data, bytecode, or executable/runtime evidence. +- **Cross-implementation** — present in both ScummVM and Pentagram; strong evidence for intended format design, but not conclusive where it conflicts with local samples. +- **Name hint** — a label supplied by a converter, disassembler, or inferred table. It helps navigation but is not itself proof of behavior. +- **Unresolved** — competing interpretations or insufficient direct evidence. Preserve the raw value and do not silently choose one interpretation. +- **Intrinsic** — a native executable routine called by bytecode, selected by a numeric ordinal. +- **Event** — a class-local numbered callback. An event slot is not a globally unique function address. + +The strongest local format evidence is the owner-loaded `EUSECODE.FLX` extractor and sampled class records. The detailed evidence and outstanding count/base disagreement are in [usecode-roundtrip-ir.md](./usecode-roundtrip-ir.md). Tool implementation differences are compared in [usecode-tooling-comparison.md](./usecode-tooling-comparison.md). + +## 3. Archive and class organization + +### 3.1 `EUSECODE.FLX` + +The locally validated FLEX directory interpretation is: + +| Field | Current interpretation | +|---|---| +| Header area | `0x80` bytes | +| Entry count | Little-endian `u32` at file offset `0x54` | +| Entry directory | Begins at `0x80` | +| Directory row | 8 bytes: little-endian `u32 data_offset`, then little-endian `u32 declared_size` | +| Object index | Directory row index | +| Non-class objects | Object 0 and object 1 are not class records in the observed layout; object 1 supplies names | +| Class object | Object index `class_id + 2` | +| Class name | A 13-byte slot in object 1 at `4 + 13 * class_id`; name text ends at NUL or the slot boundary | + +These are structural interpretations of the Crusader file as used by the local extractor, not a claim that every FLEX file in other games has the same layout. The extractor validates table bounds and retains original records: [extract_eusecode_flx.py](../tools/extract_eusecode_flx.py). + +### 3.2 Class record and event table + +For owner-loaded Crusader class records sampled locally: + +- The class header is at least 20 bytes. +- Bytes `8..11` contain a little-endian `u32` used in deriving the event-table extent and code addressing. +- A 6-byte-per-slot event table begins at class-relative offset `+20`. +- Each row has the observed shape: + +| Row-relative bytes | Interpretation | +|---|---| +| `+0..+1` | Unknown little-endian word; retain as raw data | +| `+2..+5` | Little-endian `u32` event-code offset field | + +- A zero code-offset field is treated by local tooling as an absent event. +- Nonzero offsets are resolved to body windows using the class code-base anchor and the next greater nonzero event offset. The end of the final body is bounded by the class-record size. +- Event names are not stored as authoritative semantic names in the row; the slot number is the stable identifier. + +The exact meaning of the row's leading word has not been established. Do not discard or rewrite it when round-tripping data. + +### 3.3 Event-count/base-offset disagreement + +ScummVM and Pentagram both implement a Crusader class-base calculation that decrements the dword at bytes `8..11`, and an event-count formula equivalent to `(base_offset + 19) / 6`. They resolve an event's offset from `class + 20 + 6 * slot + 2`. + +That shared implementation is valuable evidence, but its event-count arithmetic does **not** fit the sampled owner-loaded records used by this repository. Locally observed dwords such as `0x00d4`, `0x00da`, and `0x00e6` yield clean event-table sizes when interpreted as the first code-byte offset: `(raw_dword - 20) / 6` gives 32, 33, and 35 rows, respectively. The decremented value then acts as a `code_base_minus_one` anchor, and the event offsets behave as 1-based displacements from that anchor. + +**Current local rule:** use bounds-checked event-table parsing derived from the raw owner-loaded class record; preserve both the raw bytes-8..11 dword and the derived anchor. Do not apply the shared ScummVM/Pentagram event-count formula blindly to these samples. The discrepancy and evidence are documented in [usecode-roundtrip-ir.md](./usecode-roundtrip-ir.md). + +**Ghidra cross-check (Remorse):** In the active `CRUSADER.EXE`, `Usecode_ItemCallEvent` (`1420:0e3a`) passes the class id and event ordinal into `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`). The downstream `EntityVmRuntime` path materializes indexed owner/chunk records, including 6-byte runtime entries in `EnsureSlotChunkLoaded` (`1420:19fd`). This confirms class/event ordinal dispatch, but the inspected path consumes an already-indexed owner buffer and does not read the original `EUSECODE.FLX` bytes-8..11 field. It therefore does not decide between the competing archive event-count formulas; the local raw-record arithmetic remains the best fit for the sampled archives, and the formula disagreement remains open. + +### 3.4 Event body and byte order + +Integer operands in the observed Crusader bytecode are little-endian. The bytecode is a variable-length instruction stream; the opcode determines operand widths. Branch displacements are signed 16-bit relative offsets in the local decoders. Strings and body trailers require format-aware handling and must not be normalized through a lossy text conversion. + +The rebuild interpreter model in this repository starts executing at body offset `14` (`usecodeEventBytecodeOffset` in [usecode_vm.h](../rebuild/remorse/include/remorse/usecode_vm.h)). That is an implementation/runtime observation, not a substitute for parsing the event body framing. Analysis and round-trip tooling should preserve the complete body window, including prologue, debug metadata, and unknown trailing bytes. + +## 4. Event slots + +The event number is a class-local ordinal. The common event-name tables cover `0x00..0x1f`, but local class records also contain higher ordinals. The census below covers the main local `USECODE/EUSECODE.FLX` and `USECODE/REGRET/EUSECODE.FLX` corpora, not the demo, Japanese, or 1.01 variants. A count is the number of non-empty derived class/slot body windows, not dynamic executions; `0` means no body was found in that corpus, not that the engine lacks a dispatch route. + +For per-slot source labels, native callers, corpus coverage, class-local high-slot examples, and follow-up work, see the detailed [USECODE event slot catalog](./usecode-event-slots-catalog.md). + +| Slot | Common label | Remorse bodies | Regret bodies | Current Crusader interpretation | +|---:|---|---:|---:|---| +| `00` | `look` | 1 | 0 | Inspection/look callback. | +| `01` | `use` | 66 | 80 | Main object-use or activation callback. | +| `02` | `anim` | 0 | 0 | Native `Item_Anim` dispatch exists, but neither corpus has a body. | +| `03` | `setActivity` | 0 | 0 | Native `NPC_SetActivity` dispatch exists, but neither corpus has a body. | +| `04` | `cachein` | 22 | 35 | Object cache/load-in initialization callback. | +| `05` | `hit` | 13 | 12 | Outgoing hit/attack callback. Exact caller and parameter contract are class/runtime dependent. | +| `06` | `gotHit` | 197 | 248 | Incoming hit/damage reaction callback. | +| `07` | `hatch` | 28 | 26 | Spawn/appearance initialization callback. | +| `08` | `schedule` | 0 | 0 | Scheduled or periodic callback. | +| `09` | `release` | 9 | 10 | Release/cleanup callback. | +| `0A` | `equip` | 77 | 125 | Ghidra confirms the native `Item_Equip` route; scripts reuse it for applying modes, arming, setup, and actor initialization, not only wearable equipment. | +| `0B` | `unequip` | 50 | 47 | Ghidra confirms the native `Item_Unequip` route; scripts reuse it for disabling, disarming, or reversing state, not only removing wearable equipment. | +| `0C` | `combine` | 0 | 0 | Ghidra confirms an `Item_Combine` engine route, but neither inspected archive has a non-empty slot-`0C` body. | +| `0D` | `func0D` | 0 | 0 | Unknown. Preserve as an unnamed slot. | +| `0E` | `calledFromAnim` | 27 | 43 | Callback lane called from animation behavior. | +| `0F` | `enterFastArea` | 108 | 107 | Proximity/activation-region entry hook; local evidence supports trigger, spawner, and controller uses, not a movement-speed zone. | +| `10` | `leaveFastArea` | 52 | 52 | Proximity/activation-region exit hook. | +| `11` | `cast` | 1 | 8 | Ghidra confirms the native `Item_Cast` route; Crusader scripts use it for activation/dispatch, not a general spell system. | +| `12` | `justMoved` | 0 | 0 | Post-movement callback. | +| `13` | `avatarStoleSomething` | 23 | 18 | Player/avatar theft reaction hook. | +| `14` | `animGetHit` | 0 | 0 | Animation-specific hit-reaction callback. | +| `15` | `unhatch` | 5 | 6 | Ghidra has an `Item_CallUnhatchEvent` route; ScummVM's label is supported, while Pentagram's `func15` is a placeholder. | +| `16` | `func16` | 0 | 0 | Unknown. | +| `17` | `func17` | 0 | 0 | Unknown. | +| `18` | `func18` | 0 | 0 | Unknown. | +| `19` | `func19` | 0 | 0 | Unknown. | +| `1A` | `func1A` | 0 | 0 | Unknown. | +| `1B` | `func1B` | 0 | 0 | Unknown. | +| `1C` | `func1C` | 0 | 0 | Unknown. | +| `1D` | `func1D` | 0 | 0 | Unknown. | +| `1E` | `func1E` | 0 | 0 | Unknown. | +| `1F` | `func1F` | 0 | 0 | Unknown. | + +In Ghidra's Remorse `CRUSADER.EXE`, `Item_Equip`, `Item_Unequip`, `Item_Combine`, `Item_Cast`, and `Item_CallUnhatchEvent` dispatch `UC_Equip`, `UC_Unequip`, `UC_Combine`, `UC_Cast`, and `UC_Unhatch` through `Usecode_ItemCallEvent`. Their event masks (`0x400`, `0x800`, `0x1000`, `0x20000`, and `0x200000`) confirm ordinals `0x0A`, `0x0B`, `0x0C`, `0x11`, and `0x15`. This resolves Pentagram converter placeholders `func0A`, `func0B`, `func11`, and `func15` for those event names; raw ordinals remain the stable identifiers. + +**Zero-body slots with native routes (Remorse):** A zero census count means no callback body was found, not that the native engine lacks a caller. `DList_AnimateShapes` (`1190:183d`) calls `Item_Anim` (`10a0:28e2`) for animation type 5; `Item_Anim` passes `UC_Anim` with mask `0x4` to `Usecode_ItemCallEvent`. This animation-type branch only invokes the event and does not advance the frame itself, so with no slot-`0x02` body the branch has no usecode animation behavior to run. `NPC_SetActivity` (`10e8:2ba4`) similarly offers `UC_SetActivity` with mask `0x8`; if the dispatcher does not handle it, the function calls `NPC_StartNextNPCActivityBehaviorProcess` to start the ordinary activity behavior. Thus the empty slot-`0x03` rows leave that built-in fallback in control. + +The `anim()` and `setActivity()` names and ordinals are already present in Pentagram's and ScummVM's Ultima 8 event-name tables, and ScummVM's shared `Item` animation path also calls event `0x02`. That supports `anim` as inherited event machinery retained by Crusader. For `setActivity`, the name is inherited, and the original Crusader executable demonstrably dispatches it, but the inspected Ultima 8 runtime sources do not show a corresponding event-`0x03` producer; Pentagram's `Actor::I_cSetActivity` is a separate intrinsic, not that event. Whether the callback itself was live in the original Ultima 8 engine therefore remains unverified. Also, Pentagram's `Item::callUsecodeEvent` explicitly disables Crusader usecode events other than `use`; that is a limitation of that port and does not contradict the native Crusader call sites. Relevant source paths: `misc/scummvm/engines/ultima/ultima8/world/item.cpp`, `misc/scummvm/engines/ultima/ultima8/convert/u8/convert_usecode_u8.h`, `misc/pentagram/world/Item.cpp`, `misc/pentagram/world/actors/Actor.cpp`, and `misc/pentagram/convert/u8/ConvertUsecodeU8.h`. + +Outside the common table, the extracted Remorse corpus has non-empty body windows at every slot `0x20..0x4B` (44 ordinals), and Regret at every slot `0x20..0x51` (50 ordinals). These higher slots remain unnamed and class-specific; do not infer a common semantic label from the ordinal alone. + +### Event dispatch forms + +The observed bytecode includes class/event calls (`0x11`) and spawned class/event processes (`0x57`, `0x58`). The target is a class id plus event ordinal; the VM resolves the ordinal through that class's event table. Thus the same event ordinal can mean different behavior in different classes, and a decompiler's label does not prove the target row is present. + +The opcode called `FAR_ROUTINE_CALL` in the historical opcode-name list is decoded locally as this class/event dispatch. In Crusader, this is an event-number-based dispatch, not a call using a raw bytecode address. + +## 5. Bytecode instruction set + +The following inventory combines the historical opcode-name table copied from the Japanese No Remorse disassembly corpus with the local decoder's operand interpretations. It is the broadest recovered opcode vocabulary currently in this workspace, **not** a claim that all instructions have fully verified execution semantics in every build. + +Legend: + +- **Decoded locally** means the map-viewer/research parser recognizes the opcode and its current operand shape. +- **Name only / unresolved** means an opcode name exists in the historical table, but local decoding or semantics are absent, conflicting, or incomplete. +- The word “stack” below refers to the VM evaluation/temporary data model; exact ownership/lifetime rules for managed strings and list variants are not fully specified here. + +| Opcode | Historical name | Current behavior / status | +|---:|---|---| +| `00` | `ASSIGN_LOCAL_CHAR` | Pop/store byte-sized value to a BP-relative local. Decoded locally as `pop_local_byte`. | +| `01` | `ASSIGN_LOCAL_INT` | Pop/store word-sized value to a BP-relative local. | +| `02` | `ASSIGN_LOCAL_LONG` | Pop/store dword-sized value to a BP-relative local. | +| `03` | `ASSIGN_LOCAL_HUGE` | Pop/store an opaque-sized value to a BP-relative local; size is an operand. | +| `04` | `ASSIGN_MEMBER_CHAR` | Pop/store byte-sized value to a BP-relative member slot. | +| `05` | `ASSIGN_MEMBER_INT` | Pop/store word-sized value to a BP-relative member slot. | +| `06` | `ASSIGN_MEMBER_LONG` | Pop/store dword-sized value to a BP-relative member slot. | +| `07` | `ASSIGN_MEMBER_HUGE` | Pop/store an opaque-sized value to a BP-relative member slot; size is an operand. | +| `08` | `ASSIGN_RESULT` | Assign/pop the current result value. | +| `09` | `ASSIGN_ELEMENT` | Assign a list/aggregate element; operands include local offset, element size, and list-kind flag. | +| `0A` | `CHAR_CONSTANT` | Push byte immediate. | +| `0B` | `INT_CONSTANT` | Push little-endian 16-bit immediate. | +| `0C` | `LONG_CONSTANT` | Push little-endian 32-bit immediate. | +| `0D` | `STRING_CONSTANT` | Push length-prefixed/NUL-terminated string data; exact encoded-length convention should be preserved from raw bytes. | +| `0E` | `LIST_CONST` | Construct a list from element-size and count operands. | +| `0F` | `C_ROUTINE_CALL` | Call intrinsic/native routine. Operand shape locally: argument-byte count (`u8`), intrinsic ordinal (`u16`). | +| `10` | `NEAR_ROUTINE_CALL` | Call near routine at a `u16` body-relative offset. Full use and return convention not fully recovered. | +| `11` | `FAR_ROUTINE_CALL` | In Crusader, locally decoded as class id (`u16`) plus event slot (`u16`); performs class/event dispatch. | +| `12` | `TEMP_POP_INT` | Pop/store word result in VM temporary. | +| `13` | `TEMP_POP_LONG` | Pop/store dword result in VM temporary. | +| `14` | `ADD_INT` | Word/integer addition. | +| `15` | `ADD_LONG` | Dword/long addition. | +| `16` | `ADD_STRING` | String concatenation. | +| `17` | `ADD_LIST` | List concatenation/append operation. | +| `18` | `EXCLUSIVE_ADD_LIST` | Add list element(s) with uniqueness semantics; element size is an operand. | +| `19` | `EXCLUSIVE_ADD_STRING_LIST` | String-list variant of unique append. | +| `1A` | `SUB_STRING_LIST` | Remove matching string/list element(s); element size is an operand. | +| `1B` | `SUB_LIST` | Remove matching list element(s); element size is an operand. | +| `1C` | `SUBTRACT_INT` | Word/integer subtraction. | +| `1D` | `SUBTRACT_LONG` | Dword/long subtraction. | +| `1E` | `MULTIPLY_INT` | Word/integer multiplication. | +| `1F` | `MULTIPLY_LONG` | Dword/long multiplication. | +| `20` | `DIVIDE_INT` | Word/integer division. | +| `21` | `DIVIDE_LONG` | Dword/long division. | +| `22` | `MODULO_INT` | Word/integer modulo. | +| `23` | `MODULO_LONG` | Dword/long modulo. | +| `24` | `EQUALS_INT` | Word/integer equality comparison. | +| `25` | `EQUALS_LONG` | Dword/long equality comparison. | +| `26` | `EQUALS_STRING` | String equality comparison. | +| `27` | `EQUALS_HUGE` | Opaque/aggregate equality comparison; representation is not fully documented. | +| `28` | `LT_INT` | Integer less-than comparison. | +| `29` | `LT_LONG` | Dword less-than comparison. | +| `2A` | `LE_INT` | Integer less-than-or-equal comparison. | +| `2B` | `LE_LONG` | Dword less-than-or-equal comparison. | +| `2C` | `GT_INT` | Integer greater-than comparison. | +| `2D` | `GT_LONG` | Dword greater-than comparison. | +| `2E` | `GE_INT` | Integer greater-than-or-equal comparison. | +| `2F` | `GE_LONG` | Dword greater-than-or-equal comparison. | +| `30` | `NOT_INT` | Integer logical NOT. | +| `31` | `NOT_LONG` | Dword logical NOT. | +| `32` | `AND_INT` | Integer logical AND. | +| `33` | `AND_LONG` | Dword logical AND. | +| `34` | `OR_INT` | Integer logical OR. | +| `35` | `OR_LONG` | Dword logical OR. | +| `36` | `NE_INT` | Integer not-equal comparison. | +| `37` | `NE_LONG` | Dword not-equal comparison. | +| `38` | `IN_LIST` | Test list membership; local decoder reads element-size and list-kind operands. | +| `39` | `BIT_AND_INT` | Bitwise AND. | +| `3A` | `BIT_OR_INT` | Bitwise OR. | +| `3B` | `BIT_NOT_INT` | Bitwise NOT. | +| `3C` | `SHIFT_LEFT` | Left shift. | +| `3D` | `SHIFT_RIGHT` | Right shift. | +| `3E` | `BYTE_LOCAL_REFERENCE` | Push byte-sized BP-relative local. | +| `3F` | `INT_LOCAL_REFERENCE` | Push word-sized BP-relative local. | +| `40` | `LONG_LOCAL_REFERENCE` | Push dword-sized BP-relative local. | +| `41` | `STRING_LOCAL_REFERENCE` | Push local string reference. | +| `42` | `LIST_LOCAL_REFERENCE` | Push local list reference; element size is an operand. | +| `43` | `S_L_LOCAL_REFERENCE` | Push local special/string-list reference. | +| `44` | `LIST_ELEMENT_REF` | Push list element; local decoder reads element-size and list-kind operands. | +| `45` | `HUGE_LOCAL_REFERENCE` | Push opaque/aggregate local; two operand bytes are retained. | +| `46` | `BYTE_MEMBER_REFERENCE` | Push byte-sized BP-relative member. | +| `47` | `INT_MEMBER_REFERENCE` | Push word-sized BP-relative member. | +| `48` | `LONG_MEMBER_REFERENCE` | Push dword-sized BP-relative member. | +| `49` | `HUGE_MEMBER_REFERENCE` | Push opaque/aggregate BP-relative member. | +| `4A` | `THIS_REFERENCE` | Current “this” reference. Not fully modeled by the local decoder. | +| `4B` | `ADDRESS_OF` | Push address of a BP-relative local. | +| `4C` | `INDIRECT_REFERENCE` | Dereference pointer/reference for the specified byte size. | +| `4D` | `INDIRECT_ASSIGN` | Store indirectly through a pointer/reference for the specified byte size. | +| `4E` | `GLOBAL_DATA_REFERENCE` | Push global value by global id and size. | +| `4F` | `GLOBAL_DATA_ASSIGN` | Store global value by global id and size. | +| `50` | `RETURN` | Return from current routine/event. | +| `51` | `IF` | Conditional branch; local decoder represents it as `jne` with signed relative displacement. | +| `52` | `JUMP` | Unconditional relative branch. | +| `53` | `SUSPEND` | Yield/suspend the current process. | +| `54` | `IMPLIES` | Historical name; operand and runtime semantics unresolved. | +| `55` | `AND_IMPLIES` | Name present in historical table; not currently decoded locally. | +| `56` | `OR_IMPLIES` | Name present in historical table; not currently decoded locally. | +| `57` | `SPAWN` | Spawn a class/event process; operands include argument bytes, `this` size, class id, and slot. | +| `58` | `SPAWN_INLINE` | Spawn a class/event process using inline argument data; exact use of all operands remains partly unresolved. | +| `59` | `THIS_PID` | Push/current-process identifier. | +| `5A` | `INIT_ROUTINE` | Routine setup; local decoder reads local-byte count. | +| `5B` | `LINE_NUMBER` | Debug/source line marker (`u16`). | +| `5C` | `SYMBOL_INFO` | Debug/symbol metadata reference; includes a relative offset and fixed-width symbol text. Not ordinary executable flow in observed examples. | +| `5D` | `PUSH_RETURN_BYTE` | Push byte-sized return value. | +| `5E` | `PUSH_RETURN_INT` | Push word-sized return value. | +| `5F` | `PUSH_RETURN_LONG` | Push dword-sized return value. | +| `60` | `INT_TO_LONG` | Convert word to dword. | +| `61` | `LONG_TO_INT` | Convert dword to word. | +| `62` | `LOCAL_STRING_DELETE` | Release/delete BP-relative local string. | +| `63` | `LOCAL_STRING_LIST_DELETE` | Release/delete BP-relative local string-list. | +| `64` | `LOCAL_LIST_DELETE` | Release/delete BP-relative local list. | +| `65` | `STRING_REL_DELETE` | Release stack-relative string; local decoder reads an SP-relative displacement. | +| `66` | `LIST_REL_DELETE` | Release stack-relative list. | +| `67` | `STRING_LIST_REL_DELETE` | Release stack-relative string-list. | +| `68` | `COPY_STRING` | Copy/duplicate string value. | +| `69` | `STRING_ADDRESS` | Push address/reference for a BP-relative string. | +| `6A` | `CVT_POINTER_TO_STRING` | Convert pointer/reference to string. | +| `6B` | `CVT_STRING_TO_POINTER` | Convert string to pointer/reference. | +| `6C` | `PARAM_PID_CHANGE` | Change a process parameter; local operands include BP-relative location and copy-type byte. | +| `6D` | `RESULT` | Push process/routine result. | +| `6E` | `MOVE_SP` | Adjust stack pointer by an operand byte. | +| `6F` | `REL_ADDRESS_OF` | Push stack-relative address/reference. | +| `70` | `SEARCH` | Historical name conflicts with the local decoder's `loop` interpretation; unresolved. | +| `71` | `SEARCH_RECURSIVE` | Name present in historical table; not currently decoded locally. | +| `72` | `SEARCH_SURFACE` | Name present in historical table; not currently decoded locally. | +| `73` | `SEARCH_NEXT` | Historical name conflicts with local `loopnext`; unresolved. | +| `74` | `REAL_CHAR_CONSTANT` | Historical name conflicts with local `loopscr`; unresolved. | +| `75` | `FOREACH` | Iterate a list; local decoder reads BP-relative variable, element size, and relative branch. | +| `76` | `FOREACH_STRING` | Iterate a string-list variant; same broad local operand shape as `0x75`. | +| `77` | `SET_PROCESS` | Local decoder identifies this as `set_info`, a process/world notification operation. Exact native-side contract is engine-specific. | +| `78` | `PROCESS_EXCLUDE` | Exclude current process from a subsequent process operation/selection; exact lifecycle effects depend on runtime. | +| `79` | `GLOBAL_ADDRESS_OF` | Push address/reference of global id. | +| `7A` | `END` | End of event/body marker in local parser; bytes after it may be non-code trailing data and must be preserved. | +| `7B` | `REGRESS` | Historical name only; not currently decoded locally. | + +### Decoder coverage is not VM coverage + +The table records the combined opcode vocabulary, not a claim that every byte is executable in every Crusader version. Current parsers stop and preserve unknown/unsupported instruction bytes rather than guessing their lengths. The local C++ interpreter is explicitly partial; its enum/results and handlers should not be mistaken for a complete retail VM implementation. + +There are important known vocabulary mismatches: + +- The historical No Remorse opcode-name list calls `0x70..0x74` `SEARCH`, `SEARCH_RECURSIVE`, `SEARCH_SURFACE`, `SEARCH_NEXT`, and `REAL_CHAR_CONSTANT`. +- The current local decoder calls `0x70` `loop`, `0x73` `loopnext`, and `0x74` `loopscr`; it does not decode `0x71` or `0x72`. +- `0x55`, `0x56`, and `0x7B` have historical names but are not currently decoded by the local parser. + +Until direct runtime/disassembly evidence reconciles these, raw opcodes and operands are authoritative. Do not rewrite or compile these operations based only on a mnemonic. + +## 6. Intrinsics and native capabilities + +### 6.1 Call contract + +Opcode `0x0F` calls an intrinsic by ordinal. The local decoder reads: + +```text +u8 argument_byte_count +u16 intrinsic_ordinal +``` + +The argument-byte count is important evidence for call-site shape, but does not by itself recover parameter types, ownership, or return type. Intrinsic names/signatures shown by tools are metadata hints. The native implementation selected by the running executable is authoritative. + +### 6.2 Variant-specific tables + +Remorse and Regret have separate intrinsic tables. Do not copy a Regret ordinal name/signature into Remorse or vice versa without matching evidence. Development builds/versions may also differ. ScummVM's source separates the runtime tables (`remorse_intrinsics.h`, `regret_intrinsics.h`) from converter naming/signature hints (`convert_usecode_crusader.h`, `convert_usecode_regret.h`). Pentagram also has a Remorse runtime table, but local notes identify it as sparse/older. + +Current related artifacts: + +- [ScummVM Crusader converter names](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/convert/crusader/convert_usecode_crusader.h) +- [ScummVM Regret converter names](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/convert/crusader/convert_usecode_regret.h) +- [ScummVM Remorse runtime table](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/usecode/remorse_intrinsics.h) +- [ScummVM Regret runtime table](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/usecode/regret_intrinsics.h) +- [Detailed Remorse/Regret intrinsic catalog](./usecode-intrinsics-catalog.md) +- [Map-viewer generated intrinsic hint tables](../../crusader_map_viewer/map_renderer/src/lib/usecode-intrinsic-hints.generated.js) +- Local comparison and caveats: [usecode-tooling-comparison.md](./usecode-tooling-comparison.md) and [pentagram-crusader-reference.md](./pentagram-crusader-reference.md) + +The hint tables and converter names are useful for navigation, but they are not a complete substitute for validating the live executable's dispatch table and a representative call site. An intrinsic id with no current name hint remains a valid raw call, not necessarily an invalid opcode. +The hint tables and converter names are useful for navigation, but they are not a complete substitute for validating the live executable's dispatch table and a representative call site. An intrinsic id with no current name hint remains a valid raw call, not necessarily an invalid opcode. + +### Corpus census + +The raw `0x0F` call operands were counted from all non-empty derived event-body windows using the local parser and the variant-specific Remorse/Regret hint sets. The scan parsed 977 Remorse bodies and 1,152 Regret bodies with zero parser exceptions. + +| Variant | Non-empty bodies parsed | `0x0F` call sites | Distinct ordinals present | +|---|---:|---:|---| +| Remorse | 977 | 8,389 | 310 | +| Regret | 1,152 | 10,625 | 349 | + +| Intrinsic ordinal interval | Remorse bytecode | Regret bytecode | +|---|---|---| +| `0x0000..0x0135` | Used; all 310 ordinals observed | Used; all 310 ordinals observed | +| `0x0136..0x015C` | Not observed | Used; all 39 ordinals observed | + +Here, **used** means the raw ordinal occurs in a decoded intrinsic-call instruction; it does not assert runtime reachability or execution frequency. Ghidra's Remorse `Item_Equip` annotation identifies intrinsic ordinals `0x006`/`0x0B5`, and its `Item_Cast` annotation identifies `0x0E8`; their decompilations dispatch `UC_Equip` and `UC_Cast`, agreeing with ScummVM's Remorse runtime table. The local Remorse corpus also calls `0x134` and `0x135`, beyond Pentagram's 308-entry `RemorseIntrinsics` array configured in `GUIApp.cpp`. Treat that older sparse table's omissions as incomplete coverage, not proof that those calls are absent. Pentagram's converter intrinsic names are explicitly for Regret 1.21 and must not be used as Remorse mappings. Keep the raw ordinal authoritative and the selected variant's engine table as a naming hint; this Ghidra pass does not validate every intrinsic's semantics or Regret's native dispatch table. + +### Corpus ordinal name hints + +The inventory below lists each ordinal observed in either main corpus, using the ScummVM Remorse and Regret converter-name arrays linked above. Parenthesized argument lists are omitted for compactness. These are name hints, not verified native signatures or semantics; repeated labels at different ordinals remain distinct entries. `not scanned` means the ordinal is outside the Remorse corpus range counted above, not that Remorse's runtime rejects it. + +| Ordinal | Remorse name hint | Regret name hint | +|---|---|---| +| 0x0000 | byte World::I_getAlertActive | World::I_getAlertActive | +| 0x0001 | int16 Item::I_getFrame | Item::getFrame | +| 0x0002 | void Item::I_setFrame | Item::setFrame | +| 0x0003 | int16 Item::I_getMapArray | Item::getMapNum | +| 0x0004 | int16 Item::I_getStatus | Item::getStatus | +| 0x0005 | void Item::I_orStatus | Item::orStatus | +| 0x0006 | int16 Item::I_equip | Item::equip | +| 0x0007 | byte Item::I_isOnScreen | Item::isEntirelyOnScreen | +| 0x0008 | byte Actor::I_isNPC | Item::isNpc | +| 0x0009 | byte Item::I_getZ | Item::getZ | +| 0x000A | void Item::I_destroy | World::I_gameDifficulty | +| 0x000B | int16 Actor::I_GetNPCDataField0x63_00B | Item::getQLo | +| 0x000C | void Ultima8Engine::I_setAvatarInStasis | Item::destroy | +| 0x000D | byte Item::I_getDirToItem | Actor::I_getUnkByte | +| 0x000E | int16 Actor::I_turnToward | Item::getX | +| 0x000F | void I_playFlic | Item::getY | +| 0x0010 | int16 Item::I_getQLo | Item::playSfxCru | +| 0x0011 | int16 Actor::I_getMap | Item::getShape | +| 0x0012 | void MusicProcess:I_playMusic | Item::I_explode | +| 0x0013 | int16 Item::I_getX | UCMachine::I_rndRange | +| 0x0014 | int16 Item::I_getY | Item::legalCreateAtCoords | +| 0x0015 | void AudioProcess::I_playSFXCru | Item::andStatus | +| 0x0016 | int16 Item::I_getShape | World::I_getControlledNPCNum | +| 0x0017 | void Item::I_explode | Actor::I_getDir | +| 0x0018 | int16 UCMachine::I_rndRange | Actor::I_getLastAnimSet | +| 0x0019 | byte Item::I_legalCreateAtCoords | Item::I_fireWeapon | +| 0x001A | void Item::I_andStatus | Item::create | +| 0x001B | int16 World::I_getControlledNPCNum | Item::popToCoords | +| 0x001C | byte Actor::I_getDir | Actor::I_setDead | +| 0x001D | int16 Actor::I_getLastAnimSet | Item::push | +| 0x001E | int16 Item::I_fireWeapon | Item::I_getEtherealTop | +| 0x001F | byte Item::I_create | Item::getQLo | +| 0x0020 | void Item::I_popToCoords | Item::setQLo | +| 0x0021 | void Actor::I_setDead | Item::getQHi | +| 0x0022 | void Item::I_push | Item::setQHi | +| 0x0023 | int16 Item::I_getEtherealTop | Item::I_getClosestDirectionInRange | +| 0x0024 | void Item::I_setShape | Item::hurl | +| 0x0025 | void Item::I_touch | Item::getCY | +| 0x0026 | int16 Item::I_getQHi | Item::getCX | +| 0x0027 | int16 I_getClosestDirectionInRange | SpriteProcess::I_createSprite | +| 0x0028 | int16 Item::I_hurl | Item::setNpcNum | +| 0x0029 | int16 World::I_gameDifficulty | AudioProcess::I_playSFXCru | +| 0x002A | void AudioProcess::I_playAmbientSFXCru | Item::setShape | +| 0x002B | int16 Item::I_getQLo | Item::pop | +| 0x002C | byte Item::I_inFastArea | AudioProcess::I_stopSFXCru | +| 0x002D | void Item::I_setQHi | Item::isCompletelyOn | +| 0x002E | byte Item::I_legalMoveToPoint | Item::popToContainer | +| 0x002F | byte CurrentMap::I_canExistAtPoint | Actor::I_getHp | +| 0x0030 | void Item::I_pop | Actor::I_getMana | +| 0x0031 | void Item::I_andStatus | Item::getFamily | +| 0x0032 | void Item::I_receiveHit | Actor::destroyContents | +| 0x0033 | byte Actor::I_isBusy | AudioProcess::I_setVolumeForItemSFX | +| 0x0034 | int16 Item::I_getDirFromTo16 | Item::getDirToItem | +| 0x0035 | byte Actor::I_isKneeling | AudioProcess::I_isSfxPlayingForObject | +| 0x0036 | int16 Actor::I_doAnim | Item::I_getRangeIfVisible | +| 0x0037 | byte MainActor::I_addItemCru | AudioProcess::I_playSFXCru | +| 0x0038 | void AudioProcess::I_stopSFXCru | Item::andStatus | +| 0x0039 | byte Actor::I_isDead | Kernel::resetRef | +| 0x003A | byte AudioProcess::I_isSFXPlayingForObject | Item::touch | +| 0x003B | void Item::I_setQLo | Egg::getEggId | +| 0x003C | int16 Item::I_getItemFamily | MainActor::I_addItemCru | +| 0x003D | void Container::I_destroyContents | Actor::I_getMap | +| 0x003E | void Item::I_fallProbably_03E | Item::callEvent11 | +| 0x003F | int16 Egg::I_getEggId | CameraProcess::I_somethingAboutCameraUpdate | +| 0x0040 | void CameraProcess::I_moveTo | AudioProcess::I_stopSFXCru | +| 0x0041 | void CameraProcess::I_setCenterOn | Item::isOn | +| 0x0042 | byte Item::I_getRangeIfVisible | Item::getQHi | +| 0x0043 | void AudioProcess::I_playSFXCru | Item::isOn | +| 0x0044 | byte Item::I_IsOn | Item::getQHi | +| 0x0045 | int16 Item::I_getQHi | Item::isOn | +| 0x0046 | byte Item::I_IsOn | Item::getQHi | +| 0x0047 | int16 Item::I_getQHi | Item::isOn | +| 0x0048 | byte Item::I_IsOn | Item::getQHi | +| 0x0049 | int16 Item::I_getQHi | Item::isOn | +| 0x004A | byte Item::I_IsOn | Item::getQHi | +| 0x004B | int16 Item::I_getQHi | Item::isOn | +| 0x004C | byte Item::I_IsOn | Item::getQHi | +| 0x004D | int16 Item::I_getQHi | Actor::I_getCurrentActivityNo | +| 0x004E | byte Item::I_IsOn | Actor::isDead | +| 0x004F | int16 Item::I_getQHi | Actor::I_clrInCombat | +| 0x0050 | int16 Actor::I_getCurrentActivityNo | Actor::I_setDefaultActivity0 | +| 0x0051 | void Actor::I_clrInCombat | Actor::I_setDefaultActivity1 | +| 0x0052 | void Actor::I_setDefaultActivity0 | Actor::I_setDefaultActivity2 | +| 0x0053 | void Actor::I_setDefaultActivity1 | Actor::I_setActivity | +| 0x0054 | void Actor::I_setDefaultActivity2 | World::I_setControlledNPCNum | +| 0x0055 | void Actor::I_setActivity | Item::I_receiveHit | +| 0x0056 | void World::I_setControlledNPCNum | Game::I_isReleaseBuild | +| 0x0057 | int16 Item::I_getSurfaceWeight | MainActor::I_setMana | +| 0x0058 | byte Item::I_isCentreOn | Item::use | +| 0x0059 | void Item::I_setFrame | Item::setUnkEggType | +| 0x005A | int16 Actor::I_getLastAnimSet | MusicProcess::I_playMusic | +| 0x005B | byte Item::I_legalCreateAtPoint | Item::getSurfaceWeight | +| 0x005C | void Item::I_getPoint | Item::I_isCentreOn | +| 0x005D | void StatusGump::I_hideStatusGump | Item::setFrame | +| 0x005E | int16 MovieGump::I_playMovieOverlay | Actor::I_getLastAnimSet | +| 0x005F | void StatusGump::I_showStatusGump | Ultima8Engine::I_setAvatarInStasis | +| 0x0060 | void Actor::I_setDead | Actor::I_isBusy | +| 0x0061 | void Actor::I_create | Actor::I_getField0x13Flag2 | +| 0x0062 | void CameraProcess::I_somethingAboutCameraUpdate | Actor::I_doAnim | +| 0x0063 | void Actor::I_teleport | Item::legalCreateAtPoint | +| 0x0064 | void Item::I_getFootpad | Item::getPoint | +| 0x0065 | byte Item::I_isInNPC | Item::legalMoveToPoint | +| 0x0066 | int16 Item::I_getQLo | Item::fall | +| 0x0067 | int16 Item::I_getNPCNum | Item::hurl | +| 0x0068 | void Item::I_setNpcNum | Kernel::getNumProcesses | +| 0x0069 | void Item::I_andStatus | Item::getCY | +| 0x006A | void Item::I_move | U8Engine::I_isCfgAnimationOff | +| 0x006B | int16 Game::I_isViolenceEnabled | ResetKeyboardState | +| 0x006C | void Kernel::I_resetRef | MusicProcess::I_pauseMusic | +| 0x006D | int16 Item::I_getNPCNum | MovieGump::I_playMovieCutsceneRegret | +| 0x006E | void Item::I_andStatus | MusicProcess::I_unpauseMusic | +| 0x006F | byte Item::I_isCompletelyOn | Item::isInNpc | +| 0x0070 | byte Ultima8Engine::I_getCrusaderTeleporting | Ultima8Engine::I_setCruStasis | +| 0x0071 | void Ultima8Engine::I_setCrusaderTeleporting | Ultima8Engine::I_clrCruStasis | +| 0x0072 | void Ultima8Engine::I_setCruStasis | PaletteFaderProcess::I_jumpToColor | +| 0x0073 | void Actor::I_setDead | PaletteFaderProcess::I_fadeToGamePal | +| 0x0074 | void Ultima8Engine::I_clrCrusaderTeleporting | Actor::isDead | +| 0x0075 | void Ultima8Engine::I_clrCruStasis | Item::getNpcNum | +| 0x0076 | void AudioProcess::I_stopSFX | IntrinsicReturn0 | +| 0x0077 | int16 PaletteFaderProcess::I_fadeToBlack | Game::I_isViolenceEnabled | +| 0x0078 | void MainActor::I_clrKeycards | Item::unequip | +| 0x0079 | int16 MainActor::I_teleportToEgg | Item::andStatus | +| 0x007A | int16 PaletteFaderProcess::I_fadeToGamePal | Item::move | +| 0x007B | void Actor::I_clrImmortal | Ultima8Engine::I_getCrusaderTeleporting | +| 0x007C | int16 Actor::I_getHp | Ultima8Engine::I_setCrusaderTeleporting | +| 0x007D | void Actor::I_setActivity | Ultima8Engine::I_clrCrusaderTeleporting | +| 0x007E | int16 Item::I_getQuality | Actor::I_turnToward | +| 0x007F | void Item::I_setQuality | PaletteFaderProcess::I_fadeToBlack | +| 0x0080 | int16 Item::I_use | MainActor::I_clrKeycards | +| 0x0081 | int16 MainActor::I_getMaxEnergy | MusicProcess::I_stopMusic | +| 0x0082 | int16 Actor::I_getMana | PaletteFaderProcess::I_jumpToAllBlack | +| 0x0083 | void Actor::I_setMana | I_setUnkFlagA4 | +| 0x0084 | int16 Item::I_getQLo | I_clearUnkFlagA4 | +| 0x0085 | void Actor::I_setImmortal | MainActor::I_switchMap | +| 0x0086 | int16 CameraProcess::I_getCameraX | teleportToEgg | +| 0x0087 | int16 CameraProcess::I_getCameraY | PaletteFaderProcess::I_fadeToGamePal | +| 0x0088 | void Item::I_setMapArray | Actor::I_clrImmortal | +| 0x0089 | int16 Item::I_getNpcNum | Actor::I_setActivity | +| 0x008A | void Item::I_shoot | Item::getQuality | +| 0x008B | int16 Item::I_enterFastArea | Item::setQuality | +| 0x008C | void Item::I_setIsBroken | MainActor::I_getMaxEnergy | +| 0x008D | int16 Item::I_hurl | CameraProcess::I_moveTo | +| 0x008E | int16 Item::I_getNPCNum | Actor::I_setImmortal | +| 0x008F | void PaletteFaderProcess::I_jumpToAllBlack | Camera::getX | +| 0x0090 | void MusicProcess::I_stopMusic | Camera::getY | +| 0x0091 | void I_setSomeMovieGlobal | Item::setMapNum | +| 0x0092 | void I_playMovieCutsceneFullscreen | Item::getNpcNum | +| 0x0093 | void I_clearSomeMovieGlobal | Item::shoot | +| 0x0094 | void Game::I_playCredits | CameraProcess::I_setCenterOn | +| 0x0095 | byte Kernel::I_getCurrentKeyDown | Item::enterFastArea | +| 0x0096 | int16 MainActor::I_teleportToEgg | Item::setBroken | +| 0x0097 | void PaletteFaderProcess:I_jumpToGreyScale | Item::hurl | +| 0x0098 | void I_resetVargasShieldTo500 | Item::getNpcNum | +| 0x0099 | void Item::I_andStatus | Ultima8Engine::I_moveKeyDownRecently | +| 0x009A | void PaletteFaderProcess::I_jumpToNormalPalette | teleportToEgg | +| 0x009B | int16 PaletteFaderProcess::I_fadeToGamePal | Actor::I_createActor | +| 0x009C | int16 PaletteFaderProcess::I_fadeToGamePalWithParam | Actor::I_clrInCombat | +| 0x009D | int16 PaletteFaderProcess::I_fadeToBlack | PaletteFaderProcess::I_jumpToGreyScale | +| 0x009E | int16 PaletteFaderProcess::I_fadeToBlackWithParam | PaletteFaderProcess::I_jumpToNormalPalette | +| 0x009F | int16 PaletteFaderProcess::I_fadeToColor | CruStatusGump::I_showStatusGump | +| 0x00A0 | void Actor::I_setDead | Item::andStatus | +| 0x00A1 | int16 Item::I_getQLo | Item::getUnkEggType | +| 0x00A2 | int16 Item::I_getUnkEggType | Egg::setEggXRange | +| 0x00A3 | void Egg::I_setEggXRange | Item::setFrame | +| 0x00A4 | byte Item::I_overlaps | Item::overlaps | +| 0x00A5 | byte Item::I_isOn | Item::isOn | +| 0x00A6 | int16 I_getAnimationsEnabled | Item::getQHi | +| 0x00A7 | int16 Egg::I_getEggXRange | Actor::I_getLastAnimSet | +| 0x00A8 | void Actor::I_setDead | Item::getCY | +| 0x00A9 | void I_playMovieCutsceneFullscreen | CurrentMap::I_canExistAt | +| 0x00AA | void AudioProcess::I_playSFX | Item::isOn | +| 0x00AB | byte Actor::I_isFalling | Actor::isDead | +| 0x00AC | int16 Item::I_getFamilyOfType | Item::hurl | +| 0x00AD | int16 Item::I_getNPCNum | Item::I_inFastArea | +| 0x00AE | int16 Item::I_getQLo | Item::getQHi | +| 0x00AF | int16 Item::I_getQHi | Item::andStatus | +| 0x00B0 | int16 Item::I_unequip | Item::hurl | +| 0x00B1 | int16 Item::I_spawnUsecodeEvent0x13 | Item::andStatus | +| 0x00B2 | void Item::I_andStatus | Item::hurl | +| 0x00B3 | int32 I_getCurrentTimerTick | Item::andStatus | +| 0x00B4 | void Ultima8Engine::I_setAlertActive | Item::getDirToCoords | +| 0x00B5 | int16 Item::I_equip | MainActor::I_removeItem | +| 0x00B6 | void Ultima8Engine::I_clrAlertActive | I_updateInventoryUI | +| 0x00B7 | int16 Ultima8Engine::I_getAvatarInStasis | Item::getNpcNum | +| 0x00B8 | byte MainActor::I_addItemCru | Item::getCY | +| 0x00B9 | int16 Actor::I_getLastAnimSet | Item::isOn | +| 0x00BA | void Item::I_setQuality | Item::getFootpad | +| 0x00BB | byte CurrentMap::I_canExistAt | Actor::isDead | +| 0x00BC | byte Item::I_isOn | Actor::I_createActorCru | +| 0x00BD | int16 Item::I_hurl | Actor::I_setActivity | +| 0x00BE | int16 Item::I_getQHi | KeypadGump::I_showKeypad | +| 0x00BF | void Item::I_andStatus | Item::andStatus | +| 0x00C0 | int16 Item::I_hurl | ComputerGump::I_readComputer | +| 0x00C1 | void Item::I_andStatus | UCMachine::I_numToStr | +| 0x00C2 | int16 Item::I_hurl | IntrinsicReturn0 | +| 0x00C3 | void Item::I_andStatus | Actor::I_getDir | +| 0x00C4 | int16 KeypadGump::I_showKeypad | Item::getQHi | +| 0x00C5 | byte Item::I_isOn | Item::setQuality | +| 0x00C6 | void SpriteProcess::I_createSprite | Item::hurl | +| 0x00C7 | byte Item::I_getDirFromItem | Actor::I_addHp | +| 0x00C8 | int16 Item::I_hurl | CruHealerProcess::I_create | +| 0x00C9 | int16 Item::I_getQHi | Item::callEvent0A | +| 0x00CA | byte Actor::I_addHp | Item::setBroken | +| 0x00CB | void MainActor::I_switchMap | Item::isOn | +| 0x00CC | byte Actor::I_getInCombat | Actor::I_teleport | +| 0x00CD | void Actor::I_setActivity | Item::I_getDirFromTo16 | +| 0x00CE | int16 Game::I_isReleaseBuild | Item::getQHi | +| 0x00CF | void Item::I_setQAndCombine | Item::isOn | +| 0x00D0 | int16 Item::I_use | Actor::I_isInCombat | +| 0x00D1 | void AudioProcess:I_stopAllSFX | Actor::I_getNPCDataField0x4 | +| 0x00D2 | void I_playMovieCutscene | Actor::I_setCombatTactic | +| 0x00D3 | void I_clearKeyboardState | Actor::I_setDead | +| 0x00D4 | void I_playSFX | CameraProcess::I_getCameraY | +| 0x00D5 | int16 Item::I_use | Actor::I_getEquip | +| 0x00D6 | byte CameraProcess::I_getCameraZ | Actor::I_setEquip | +| 0x00D7 | int16 Actor::I_getLastAnimSet | Actor::I_getDefaultActivity0 | +| 0x00D8 | void Actor::I_setDead | Actor::I_getDefaultActivity1 | +| 0x00D9 | int16 Item::I_getQLo | Actor::I_getDefaultActivity2 | +| 0x00DA | void PaletteFaderProcess::I_setPalToAllGrey | Actor::I_getLastAnimSet | +| 0x00DB | void Actor::I_setActivity | Actor::I_isFalling | +| 0x00DC | byte Item::I_isOn | Item::getQLo | +| 0x00DD | int16 Actor::I_getLastActivityNo | Item::getQHi | +| 0x00DE | void Actor::I_setCombatTactic | Item::getNpcNum | +| 0x00DF | int16 Actor::I_getEquip | Item::I_setField0x81 | +| 0x00E0 | void Actor::I_setEquip | Item::hurl | +| 0x00E1 | int16 Actor::I_getDefaultActivity0 | Actor::I_setDead | +| 0x00E2 | int16 Actor::I_getDefaultActivity1 | Item::getQLo | +| 0x00E3 | int16 Actor::I_getDefaultActivity2 | Item::getCY | +| 0x00E4 | int16 Actor::I_getLastAnimSet | Item::getNpcNum | +| 0x00E5 | void Actor::I_setTarget | Item::hurl | +| 0x00E6 | void Actor::I_SetNPCDataField0x63_0E6 | Item::getNpcNum | +| 0x00E7 | void Actor::I_setDead | Item::hurl | +| 0x00E8 | int16 Item::I_cast | Item::getNpcNum | +| 0x00E9 | void Item::I_andStatus | Item::hurl | +| 0x00EA | int16 Item::I_getQLo | Item::getNpcNum | +| 0x00EB | int16 I_GetQOfAvatarInventoryItem0x4ed_0EB | Item::hurl | +| 0x00EC | void Item::I_popToEnd | Item::getNpcNum | +| 0x00ED | void Item::I_popToContainer | Item::hurl | +| 0x00EE | void BatteryChargerProcess::I_create | Item::getNpcNum | +| 0x00EF | int16 Kernel::I_getNumProcesses | Item::hurl | +| 0x00F0 | int16 Item::I_getQHi | Item::getNpcNum | +| 0x00F1 | byte Item::I_isOn | Item::hurl | +| 0x00F2 | void Actor::I_setActivity | Item::getNpcNum | +| 0x00F3 | int16 Item::I_getQHi | Item::hurl | +| 0x00F4 | int16 Item::I_getQ | Item::getNpcNum | +| 0x00F5 | void Item::I_setQ | Item::hurl | +| 0x00F6 | void CruHealer::I_create_0F6 | Item::getNpcNum | +| 0x00F7 | int16 Item::I_hurl | Item::andStatus | +| 0x00F8 | int16 Item::I_getNPCNum | Actor::I_setDead | +| 0x00F9 | int16 Item::I_hurl | Item::getQLo | +| 0x00FA | byte Item::I_isOn | Actor::I_setDead | +| 0x00FB | int16 Item::I_getQHi | Dtable::I_getMaxHPForNPC | +| 0x00FC | void Item::I_andStatus | Actor::I_setHP | +| 0x00FD | byte MainActor::I_hasKeycard | Item::getQLo | +| 0x00FE | void ComputerGump::I_readComputer | BatteryChargerProcess::I_create | +| 0x00FF | int16 UCMachine::I_numToStr | Item::hurl | +| 0x0100 | int16 Item::I_getNPCNum | Item::andStatus | +| 0x0101 | void Item::I_andStatus | Item::isOn | +| 0x0102 | int16 Item::I_getNPCNum | Actor::isDead | +| 0x0103 | byte Item::I_isCrusTypeNPC | Actor::I_setActivity | +| 0x0104 | void Item::I_andStatus | Item::getQHi | +| 0x0105 | int16 Item::I_getNPCNum | Actor::I_getLastAnimSet | +| 0x0106 | void Item::I_andStatus | Actor::I_setDead | +| 0x0107 | int16 Item::I_getNPCNum | Item::getQLo | +| 0x0108 | void Item::I_andStatus | Item::isOn | +| 0x0109 | int16 Item::I_getNPCNum | Item::getQHi | +| 0x010A | void Item::I_andStatus | Item::isOn | +| 0x010B | int16 Item::I_getNPCNum | Item::getQHi | +| 0x010C | void Item::I_andStatus | Item::hurl | +| 0x010D | int16 Item::I_getNPCNum | Item::getNpcNum | +| 0x010E | void Item::I_andStatus | Item::getCY | +| 0x010F | int16 Item::I_getNPCNum | Item::hurl | +| 0x0110 | void Item::I_andStatus | Item::isOn | +| 0x0111 | int16 Item::I_getNPCNum | MainActor::I_hasKeycard | +| 0x0112 | byte Actor::I_getDir | IntrinsicReturn0 | +| 0x0113 | int16 UCMachine::I_numToStr | Actor::isDead | +| 0x0114 | void Item::I_andStatus | Actor::I_clrImmortal | +| 0x0115 | int16 Item::I_getNPCNum | UCMachine::I_numToStr | +| 0x0116 | byte Item::I_fireDistance | Item::getQHi | +| 0x0117 | void Item::I_andStatus | Actor::I_setActivity | +| 0x0118 | int16 Item::I_hurl | Item::andStatus | +| 0x0119 | void Item::I_setIsBroken | Item::getNpcNum | +| 0x011A | void Item::I_andStatus | Item::andStatus | +| 0x011B | byte Item::I_getTypeFlag | Item::getNpcNum | +| 0x011C | int16 Item::I_getNPCNum | Item::I_isCrusTypeNPC | +| 0x011D | int16 Item::I_hurl | Item::andStatus | +| 0x011E | int16 Item::I_getCY | Item::getNpcNum | +| 0x011F | byte Item::I_getCZ | Item::AvatarStoleSomehting | +| 0x0120 | int16 Item::I_getCX | Item::andStatus | +| 0x0121 | byte Actor::I_getDir | Item::getNpcNum | +| 0x0122 | byte Actor::I_isDead | Item::getQ | +| 0x0123 | int16 Item::I_getNPCNum | Item::setQ | +| 0x0124 | int16 Actor::I_getLastAnimSet | Item::andStatus | +| 0x0125 | void Item::I_setQuality | Item::getNpcNum | +| 0x0126 | int16 UCMachine::I_numToStr | Item::andStatus | +| 0x0127 | byte Item::I_getDirToCoords | Item::getNpcNum | +| 0x0128 | void Item::I_andStatus | Item::andStatus | +| 0x0129 | int16 Item::I_getNPCNum | Item::getNpcNum | +| 0x012A | void Item::I_setIsBroken | Item::andStatus | +| 0x012B | int16 IItem::I_getCY | Item::getNpcNum | +| 0x012C | byte Item::I_isOn | Item::andStatus | +| 0x012D | void Item::I_getFootpadData | Item::getNpcNum | +| 0x012E | byte Actor::I_isDead | Actor::I_getDir | +| 0x012F | int16 Actor::I_createActorCru | Item::andStatus | +| 0x0130 | void Actor::I_clrImmortal | Item::getNpcNum | +| 0x0131 | void Actor::I_setActivity | Intrinsic0131 | +| 0x0132 | void Item::I_andStatus | Item::andStatus | +| 0x0133 | int16 Item::I_getQHi | Item::hurl | +| 0x0134 | void WeaselGump::I_showGump | Item::andStatus | +| 0x0135 | void Actor::I_setDead | Camera::getY | +| 0x0136 | not scanned | Camera::getZ | +| 0x0137 | not scanned | CruStatusGump::I_hideStatusGump | +| 0x0138 | not scanned | Actor::I_clrInCombat | +| 0x0139 | not scanned | Item::getTypeFlagCrusader | +| 0x013A | not scanned | Item::getNpcNum | +| 0x013B | not scanned | Item::hurl | +| 0x013C | not scanned | Item::getCY | +| 0x013D | not scanned | Item::getCZ | +| 0x013E | not scanned | Item::setFrame | +| 0x013F | not scanned | AudioProcess::I_playAmbientSFX | +| 0x0140 | not scanned | AudioProcess::I_isSFXPlaying | +| 0x0141 | not scanned | World::I_clrAlertActiveRegret | +| 0x0142 | not scanned | PaletteFaderProcess::I_fadeToGivenColor | +| 0x0143 | not scanned | Actor::isDead | +| 0x0144 | not scanned | Actor::I_setDead | +| 0x0145 | not scanned | Game::I_playCredits | +| 0x0146 | not scanned | PaletteFaderProcess::I_jumpToAllGrey | +| 0x0147 | not scanned | Item::I_getFamilyOfType | +| 0x0148 | not scanned | Item::getNpcNum | +| 0x0149 | not scanned | Item::getQLo | +| 0x014A | not scanned | Item::andStatus | +| 0x014B | not scanned | Ultima8Engine::getCurrentTimerTick | +| 0x014C | not scanned | World::I_setAlertActiveRegret | +| 0x014D | not scanned | Ultima8Engine::I_getAvatarInStasis | +| 0x014E | not scanned | MainActor::I_addItemCru | +| 0x014F | not scanned | Egg::getEggXRange | +| 0x0150 | not scanned | Actor::I_clrInCombat | +| 0x0151 | not scanned | PaletteFaderProcess::I_jumpToColor | +| 0x0152 | not scanned | Item::setFrame | +| 0x0153 | not scanned | UCMachine::I_numToStr | +| 0x0154 | not scanned | Actor::I_getDir | +| 0x0155 | not scanned | UCMachine::I_numToStr | +| 0x0156 | not scanned | Item::isOn | +| 0x0157 | not scanned | Actor::I_getDir | +| 0x0158 | not scanned | Actor::I_setDead | +| 0x0159 | not scanned | Item::getQHi | +| 0x015A | not scanned | Item::getQLo | +| 0x015B | not scanned | UCMachine::I_numToStr | +| 0x015C | not scanned | Actor::I_getDir | + +### 6.3 Capability families exposed through native calls + +Across the Crusader runtime tables and observed scripts, intrinsic calls expose or mediate capabilities in these broad families: + +- **Items and world objects:** read/write item properties; create, destroy, move, push/pop, grab, drop, and transfer objects; query shape/family/type, frame, status/quality/quantity, coordinates, map placement, overlap/reach, and containment. +- **Actors and combat:** query or set actor state and statistics, targets, direction, movement/activity, animation, hit/damage behavior, and combat state; create or teleport actors where the variant table provides the operation. +- **Processes and scheduling:** inspect process identifiers/results, spawn or coordinate work, suspend/yield, exclude processes, and schedule delayed/tick-driven behavior. +- **Map and trigger systems:** query/update eggs, trigger/controller state, map and coordinate relationships, enter/leave activation regions, and spawn or dispatch event-driven effects. +- **User interface and text:** interact with game UI, gumps, readable objects, prompts, or other presentation services where supported by that build's intrinsic table. +- **Graphics and camera:** camera movement/centering, sprite effects, palette transitions, fades, screen effects, and related presentation operations. +- **Audio and music:** play/stop sound effects and music, query sound state, or alter audio parameters where provided. +- **Time, randomness, and game state:** query or update selected game-time state, obtain random values, and access variant-specific flags or globals. +- **Global storage and VM-managed values:** read/write globals and use the VM's pointer/string/list support. A script-visible pointer is a VM/runtime reference, not an unrestricted host pointer. + +These are capabilities of the **bytecode plus the installed native table**, not all built-in bytecode instructions. A particular game version may leave an ordinal unused, map it differently, or implement it only in one variant. The table is not an operating-system API. + +### 6.4 Events versus intrinsics + +Event slots are script entry points. Intrinsics are native callable services. For example, an event handler can be invoked by the engine for `use`, and that handler can then call item or audio intrinsics. Do not conflate: + +- `equip` event slot `0x0A` with any specific intrinsic ordinal; +- event `cast` slot `0x11` with spellcasting; +- `spawn` opcode `0x57` with a native intrinsic; +- class/event dispatch opcode `0x11` with intrinsic call opcode `0x0F`. + +## 7. What scripts can do + +Subject to the event and intrinsic tables of the active game build, Crusader USECODE can: + +- implement class-specific callbacks and call other class/event handlers; +- branch, loop, compare, perform integer/dword arithmetic and bit operations; +- use local/member/global storage, references, indirect access, and result values; +- manipulate strings, lists, string-lists, and aggregate/“huge” values; +- create and control asynchronous processes, yield/suspend, and coordinate process results; +- use native game services to inspect and mutate items, actors, world state, UI, graphics, audio, timing, and trigger behavior; +- attach behavior to engine lifecycle, interaction, movement, hit, schedule, spawn, and proximity callbacks. + +This is an event/process scripting system integrated into the game engine. It can perform substantial gameplay logic because its intrinsic layer gives scripts access to native services. + +## 8. What the format alone cannot establish + +These are limits on what can safely be concluded from the file/bytecode representation, not absolute claims that a native executable could never provide the behavior: + +- **No intrinsic implementation from an ordinal alone.** The number, argument bytes, and optional converter name do not define the native routine's full behavior or guarantee the ordinal exists in another build. +- **No class behavior from a slot label alone.** A slot can be absent, empty, repurposed, or class-specific. Event-name tables are vocabulary hints. +- **No lossless source recovery from pseudocode alone.** Decompilation can omit exact operand encodings, opaque values, padding, symbol records, and trailers. Original bytes and offsets must be retained for exact round trips. +- **No settled meaning for every header/row field.** The leading word in each 6-byte event row and the count/base mismatch remain unresolved. +- **No settled semantics for all instructions.** The opcode-name list and local decoder disagree in places; unsupported/unknown opcodes cannot safely be skipped without a proven length rule. +- **No proof of arbitrary host/OS access.** The known model calls game-provided intrinsics. No general-purpose file/network/process/OS syscall interface is established by the bytecode specification. +- **No claim that each game feature is script-owned.** Engine code performs event selection, VM process management, native operations, and state transitions. A script can request native actions but does not necessarily implement those systems itself. +- **No inheritance or virtual-method guarantee.** The established call form names a class and event ordinal. Any higher-level inheritance/dispatch claim needs separate evidence. +- **No guarantee that all listed object-oriented concepts are source-language constructs.** Names such as “class,” “member,” and “routine” describe the compiled runtime representation; a complete original source language/compiler specification has not been recovered. + +## 9. Runtime execution model + +The most defensible high-level model is: + +1. The engine or another script selects a class and event slot. +2. Runtime class/event data resolves that slot to a code offset/body. +3. A usecode process/context is created with item and optional event/context parameters. +4. The interpreter executes variable-length bytecode against local/member/global state and a VM evaluation stack. +5. Bytecode may call another event, spawn a process, call an intrinsic, suspend/yield, or return/end. +6. The engine's process scheduler resumes suspended work and applies native/world side effects. + +The local `rebuild/remorse` model records process/context layout and partial opcode semantics in [usecode_vm.h](../rebuild/remorse/include/remorse/usecode_vm.h), [usecode_vm.cpp](../rebuild/remorse/src/usecode_vm.cpp), and [usecode_vm_tests.cpp](../rebuild/remorse/tests/usecode_vm_tests.cpp). Those are explicitly partial models; passing their tests proves the model's tested behavior, not full equivalence to every retail interpreter path. + +## 10. Remorse, Regret, and other version boundaries + +| Area | Shared evidence | Must remain variant-specific | +|---|---|---| +| Archive/class indexing | FLEX object indexing, class object at `class_id + 2`, 6-byte event rows, event ordinals | Exact class inventory and data bytes | +| Event vocabulary | Shared Crusader event-name table `0x00..0x1f` | Presence and behavior of each class/slot | +| Bytecode | Broad shared opcode vocabulary | Actual use, edge semantics, version-specific opcodes and compiler artifacts | +| Intrinsics | Same general native-call architecture | Ordinal-to-function map, signature, availability, return semantics | +| Debug/symbol data | Symbol and line records occur in bodies | Exact trailer layout and compiler/version details | +| Runtime | Process-based interpreter model | Context fields, startup globals, scheduler details, and implementation differences | + +**Remorse global-index conflict:** ScummVM's runtime source initializes global `0x003C` to avatar number `1`, while Pentagram's scratch dump for Remorse 1.01 starts at `0x003D`. The current Ghidra pass traced event dispatch and slot materialization, not a version-matched global initializer, so this remains unresolved and version-qualified. See [Pentagram's Crusader reference note](./pentagram-crusader-reference.md) for the competing evidence. + +Do not infer retail Remorse behavior solely from Regret samples, or vice versa. Demo, regional, and patched executables must likewise be recorded as separate evidence targets where their tables differ. + +## 11. Safe parsing and round-trip requirements + +Any parser, editor, or writer claiming to preserve Crusader USECODE should: + +1. preserve the original archive, entry order, sparse entries, class bytes, and unknown objects; +2. bounds-check FLEX offsets/sizes and class/event tables before reading; +3. preserve raw event-row bytes, including the unresolved leading word; +4. store raw event/body byte slices and the exact offsets used to derive them; +5. distinguish absent rows, valid zero-offset values, malformed rows, and unresolved layouts; +6. retain unsupported instruction bytes rather than discarding or guessing their lengths; +7. preserve debug/symbol data and bytes after `END`; +8. use the correct Remorse/Regret intrinsic hint table and retain the raw ordinal and argument-byte count regardless of naming; +9. require unchanged inputs to round-trip byte-for-byte before claiming a lossless format edit path; +10. write modified archives to a separate output and validate with an independent parser/runtime. + +The current product/editor path and remaining round-trip milestones are in [usecode-roundtrip-ir.md](./usecode-roundtrip-ir.md). The local proof-of-concept parser is [poc_crusader_usecode_parser.py](../tools/poc_crusader_usecode_parser.py); the user-facing map-viewer implementation is [usecode-decompiler.js](../../crusader_map_viewer/map_renderer/src/lib/usecode-decompiler.js). + +## 12. Primary references + +### Local evidence + +- [USECODE extractor](../tools/extract_eusecode_flx.py) +- [USECODE bytecode parser](../tools/poc_crusader_usecode_parser.py) +- [USECODE VM model](../rebuild/remorse/src/usecode_vm.cpp) +- [Round-trip and format evidence](./usecode-roundtrip-ir.md) +- [Pentagram/ScummVM comparison and local caveats](./usecode-tooling-comparison.md) +- [Pentagram reference investigation](./pentagram-crusader-reference.md) +- [Event-slot behavior notes](./usecode-event-slots-combine-cast-fast-area.md) +- [Equip/unequip event behavior](./usecode-equipment-system.md) + +### External implementation references + +- [ScummVM USECODE class/event interface](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/usecode/usecode.h) +- [ScummVM Crusader FLEX/class reader](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/usecode/usecode_flex.cpp) +- [ScummVM Crusader event-offset resolver](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/usecode/usecode.cpp) +- [ScummVM Crusader opcode/event/intrinsic converter tables](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/convert/crusader/convert_usecode_crusader.h) +- [Pentagram Crusader converter table](https://github.com/pentagram-u8/pentagram/blob/master/convert/crusader/ConvertUsecodeCrusader.h) +- [Pentagram Crusader FLEX/class reader](https://github.com/pentagram-u8/pentagram/blob/master/usecode/UsecodeFlex.cpp) +- [Pentagram Crusader FLEX/class reader](https://github.com/pentagram-u8/pentagram/blob/master/usecode/UsecodeFlex.cpp) +- [Pentagram Remorse runtime table](https://github.com/pentagram-u8/pentagram/blob/master/usecode/remorseintrinsics.h) +- [Pentagram Remorse table setup and entry count](https://github.com/pentagram-u8/pentagram/blob/master/kernel/GUIApp.cpp) + +External implementation links describe those projects' code and conventions. For local owner-loaded Crusader data, the raw samples and locally validated extraction rules in this repository take precedence wherever the implementations conflict. + +## 13. Open Mysteries for Investigation + +These questions have plausible, testable evidence paths. Keep results qualified by game, executable version, and archive; do not promote a shared-implementation convention to a Crusader fact without local confirmation. + +- [ ] **Class header and event-table extent:** Determine why ScummVM/Pentagram's event-count formula disagrees with sampled owner-loaded records. Compare bytes `8..11`, table boundaries, and code anchors across Remorse, Regret, demo, regional, and patched archives; verify any proposed formula against every class record. +- [ ] **Leading event-row word:** Establish what the unknown `u16` at the start of each six-byte row encodes. Correlate values with event presence, slot, class, and build, then trace any runtime or loader use before assigning meaning. +- [ ] **Event code-offset convention:** Confirm the `code_base_minus_one` and 1-based displacement interpretation, including zero offsets, duplicate or out-of-order offsets, and how the final body boundary is chosen. Check edge cases against raw class bytes and the runtime's indexed records. +- [ ] **Event-body framing:** Recover the fields and purpose of the 14-byte execution prefix, debug/symbol records, `END`, and trailing bytes. Compare bodies from multiple compiler/build variants and verify that parsing preserves all bytes while locating executable instructions correctly. +- [ ] **Unresolved call/process opcodes:** Determine the target and calling/return conventions of `0x10` (`NEAR_ROUTINE_CALL`), and the exact operand and inline-data layout of `0x58` (`SPAWN_INLINE`). Use representative bytecode call sites and the matching executable's interpreter paths. +- [ ] **Conflicting or undecoded opcodes:** Reconcile historical names and local decoder interpretations for `0x54..0x56`, `0x70..0x74`, and `0x7B`. Trace dispatch in each relevant retail interpreter and validate candidate instruction boundaries against real bodies; do not infer operand lengths from names. +- [ ] **VM value and stack semantics:** Specify ownership, lifetime, and representation for strings, lists, string-lists, references, and “huge” values; verify stack effects, result propagation, and cleanup behavior using interpreter code plus representative scripts, especially around suspend/return. +- [ ] **Intrinsic contracts by build:** Validate ordinal-to-native dispatch, argument types/order, return convention, and side effects independently for Remorse and Regret. Prioritize frequently used or ambiguously named ordinals, Remorse `0x134`/`0x135`, and Regret's native table, which is not validated here. +- [ ] **High event-slot meanings:** Identify behavior for class-local slots above `0x1F` (`0x20..0x4B` in Remorse and `0x20..0x51` in Regret). Cluster bodies by bytecode and class, then trace native callers and observed effects before proposing labels. +- [ ] **Event dispatch edge cases:** Determine how absent, empty, or unsupported event slots affect native fallbacks, and whether higher-level inheritance or virtual dispatch exists beyond the observed class-id/slot lookup. Trace callers and dispatcher behavior for representative slots, including `setActivity`. +- [ ] **Remorse global-index discrepancy:** Resolve whether global `0x003C` or `0x003D` holds the avatar number in each Remorse release. Inspect version-matched executable initialization and compare with the corresponding data/archive rather than relying on cross-version ScummVM/Pentagram notes. +- [ ] **Compiler and source-language model:** Establish which source-level constructs are actually supported by evidence, including class/member layout, routine calls, and any inheritance. Seek compiler-produced samples, symbol/debug metadata, or controlled runtime tests; keep representation terminology distinct from proven source-language features. diff --git a/docs/usecode-intrinsics-catalog.md b/docs/usecode-intrinsics-catalog.md new file mode 100644 index 0000000..06f6987 --- /dev/null +++ b/docs/usecode-intrinsics-catalog.md @@ -0,0 +1,396 @@ +# Crusader USECODE Intrinsic Catalog + +**Status:** Evidence-backed reference catalog; names/signatures remain implementation hints unless separately verified. +**Scope:** Main local Remorse and Regret owner-loaded bytecode corpora; demo, Japanese, and 1.01 corpora are excluded from usage counts. +**Last consolidated:** 2026-10-05 + +This companion holds the per-ordinal detail that would make the main [USECODE format specification](./usecode-format-specification.md) unwieldy: full converter prototypes, variant-specific mappings, and measured bytecode call shapes. It complements rather than replaces the main specification's aggregate census. + +## How to read the catalog + +Bytecode opcode `0x0F` stores an argument-byte count (`u8`) followed by an intrinsic ordinal (`u16`). The usage cells below report `call sites / event bodies / arg_bytes histogram`; histogram values are hexadecimal byte counts followed by their call-site frequencies. They describe decoded static call sites, not runtime reachability or execution frequency. + +`not scanned` means an ordinal lies outside that variant's measured corpus range; it is not equivalent to zero calls or a missing runtime function. A `0 / 0 / -` cell means the ordinal was inside the scanned range but no decoded calls were found. Each event body is counted at most once per ordinal, even if it calls that ordinal repeatedly. + +Converter prototypes are copied from the ScummVM converter-name arrays. Parameter lists are retained as published there, but remain hints: `arg_bytes` alone cannot establish parameter types, return values, ownership, or calling convention. `IntrinsicXXXX`, `IntrinsicReturn0`, and `UNUSEDIntXXX` are intentionally retained where the source has no better name. + +## Corpus and source evidence + +| Variant | Non-empty bodies parsed | Intrinsic calls | Distinct ordinals | Measured ordinal range | Converter-name entries | Unsupported/unknown stops | Parser exceptions | +|---|---:|---:|---:|---|---:|---:|---:| +| Remorse | 977 | 8,389 | 310 | 0x0000..0x0135 | 311 | 0 | 0 | +| Regret | 1,152 | 10,625 | 349 | 0x0000..0x015C | 350 | 0 | 0 | + +The corpus scan uses the local parser's decoded event-body windows and the map-viewer bytecode decoder. It agrees with the main specification's body/call/distinct-ordinal totals. The converter arrays include entries beyond one or both measured corpora; those extra source entries are listed below but receive `not scanned` usage cells when outside the relevant corpus range. + +Primary source arrays: [ScummVM Remorse converter names](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/convert/crusader/convert_usecode_crusader.h) and [ScummVM Regret converter names](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/convert/crusader/convert_usecode_regret.h). Runtime implementations are separate: [Remorse runtime table](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/usecode/remorse_intrinsics.h) and [Regret runtime table](https://github.com/scummvm/scummvm/blob/master/engines/ultima/ultima8/usecode/regret_intrinsics.h). + +Pentagram's Remorse table is sparse/older and is configured with 308 entries; that count is not a cap on local Remorse bytecode, which calls ordinals `0x0134` and `0x0135`. See [the local Pentagram comparison](./pentagram-crusader-reference.md). + +## Ordinal catalog + +Each row is one source ordinal. Repeated prototype labels are not deduplicated because the numeric ordinal is part of the callable identity. Converter-only tail entries are retained with `not scanned` usage. + +| Ordinal | Remorse converter prototype | Remorse calls / bodies / arg_bytes | Regret converter prototype | Regret calls / bodies / arg_bytes | +|---|---|---|---|---| +| 0x0000 | `byte World::I_getAlertActive(void)` | 17 / 14 / `0x00:17` | `World::I_getAlertActive()` | 25 / 20 / `0x00:25` | +| 0x0001 | `int16 Item::I_getFrame(Item *)` | 466 / 248 / `0x04:466` | `Item::getFrame(void)` | 566 / 378 / `0x04:566` | +| 0x0002 | `void Item::I_setFrame(Item *, frame)` | 98 / 41 / `0x06:98` | `Item::setFrame(uint16)` | 53 / 32 / `0x06:53` | +| 0x0003 | `int16 Item::I_getMapArray(Item *)` | 63 / 51 / `0x04:63` | `Item::getMapNum(void)` | 84 / 72 / `0x04:84` | +| 0x0004 | `int16 Item::I_getStatus(Item *)` | 149 / 134 / `0x04:149` | `Item::getStatus(void)` | 150 / 136 / `0x04:150` | +| 0x0005 | `void Item::I_orStatus(Item *, uint16 flags)` | 75 / 65 / `0x06:75` | `Item::orStatus(sint16)` | 84 / 72 / `0x06:84` | +| 0x0006 | `int16 Item::I_equip(6 bytes)` | 2 / 1 / `0x06:2` | `Item::equip(sint16)` | 10 / 2 / `0x06:10` | +| 0x0007 | `byte Item::I_isOnScreen(Item *)` | 23 / 14 / `0x04:23` | `Item::isEntirelyOnScreen()` | 50 / 36 / `0x04:50` | +| 0x0008 | `byte Actor::I_isNPC(Item *)` | 40 / 35 / `0x04:40` | `Item::isNpc(void)` | 48 / 36 / `0x04:48` | +| 0x0009 | `byte Item::I_getZ(Item *)` | 420 / 183 / `0x04:420` | `Item::getZ(void)` | 572 / 313 / `0x04:572` | +| 0x000A | `void Item::I_destroy(Item *)` | 206 / 128 / `0x04:206` | `World::I_gameDifficulty()` | 64 / 45 / `0x00:64` | +| 0x000B | `int16 Actor::I_GetNPCDataField0x63_00B(Actor *)` | 54 / 37 / `0x04:54` | `Item::getQLo(void)` | 8 / 3 / `0x04:8` | +| 0x000C | `void Ultima8Engine::I_setAvatarInStasis(int)` | 115 / 47 / `0x02:115` | `Item::destroy(void)` | 252 / 193 / `0x04:252` | +| 0x000D | `byte Item::I_getDirToItem(Item *, itemno)` | 38 / 21 / `0x06:38` | `Actor::I_getUnkByte()` | 77 / 60 / `0x04:77` | +| 0x000E | `int16 Actor::I_turnToward(Actor *, direction, dir_16)` | 74 / 38 / `0x08:74` | `Item::getX(void)` | 561 / 313 / `0x04:561` | +| 0x000F | `void I_playFlic(void), int16 I_playFlic(Item *, char *name, int16 sizex, int16 sizey)` | 407 / 31 / `0x0C:407` | `Item::getY(void)` | 561 / 313 / `0x04:561` | +| 0x0010 | `int16 Item::I_getQLo(Item *)` | 5 / 2 / `0x04:5` | `Item::playSfxCru()` | 710 / 327 / `0x06:710` | +| 0x0011 | `int16 Actor::I_getMap(4 bytes)` | 137 / 41 / `0x04:137` | `Item::getShape(void)` | 341 / 94 / `0x04:341` | +| 0x0012 | `void MusicProcess:I_playMusic(int trackno)` | 20 / 2 / `0x02:20` | `Item::I_explode()` | 81 / 54 / `0x08:81` | +| 0x0013 | `int16 Item::I_getX(Item *)` | 448 / 193 / `0x04:448` | `UCMachine::I_rndRange()` | 185 / 72 / `0x04:185` | +| 0x0014 | `int16 Item::I_getY(Item *)` | 446 / 193 / `0x04:446` | `Item::legalCreateAtCoords(uint16,uint16,uint16,uint16,uint16)` | 53 / 43 / `0x0E:53` | +| 0x0015 | `void AudioProcess::I_playSFXCru(Item *, uint16 sfxnum)` | 342 / 206 / `0x06:342` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x0016 | `int16 Item::I_getShape(Item *)` | 289 / 94 / `0x04:289` | `World::I_getControlledNPCNum()` | 107 / 72 / `0x00:107` | +| 0x0017 | `void Item::I_explode(Item *, exptype, destroy_item)` | 74 / 45 / `0x08:74` | `Actor::I_getDir()` | 120 / 12 / `0x04:120` | +| 0x0018 | `int16 UCMachine::I_rndRange(uint16 x, uint16 y)` | 148 / 61 / `0x04:148` | `Actor::I_getLastAnimSet()` | 1 / 1 / `0x04:1` | +| 0x0019 | `byte Item::I_legalCreateAtCoords(Item *, int16 shapeno, int16 frame, int16 x, int16 y, int16 z)` | 12 / 7 / `0x0E:12` | `Item::I_fireWeapon()` | 93 / 21 / `0x10:93` | +| 0x001A | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Item::create(uint16,uint16)` | 312 / 118 / `0x08:312` | +| 0x001B | `int16 World::I_getControlledNPCNum()` | 67 / 42 / `0x00:67` | `Item::popToCoords(uint16,uint16,uint8)` | 405 / 210 / `0x0A:405` | +| 0x001C | `byte Actor::I_getDir(4 bytes)` | 136 / 22 / `0x04:136` | `Actor::I_setDead()` | 1 / 1 / `0x04:1` | +| 0x001D | `int16 Actor::I_getLastAnimSet(4 bytes)` | 2 / 2 / `0x04:2` | `Item::push(void)` | 199 / 137 / `0x04:199` | +| 0x001E | `int16 Item::I_fireWeapon(Item *, x, y, z, byte, int, byte)` | 18 / 6 / `0x10:18` | `Item::I_getEtherealTop()` | 29 / 9 / `0x00:29` | +| 0x001F | `byte Item::I_create(Item *, uint16 shapenum, uint16 framenum)` | 226 / 90 / `0x08:226` | `Item::getQLo(void)` | 192 / 103 / `0x04:192` | +| 0x0020 | `void Item::I_popToCoords(Item *, uint16 x, uint16 y, uint16 z)` | 310 / 144 / `0x0A:310` | `Item::setQLo(sint16)` | 147 / 101 / `0x06:147` | +| 0x0021 | `void Actor::I_setDead(4 bytes)` | 1 / 1 / `0x04:1` | `Item::getQHi(void)` | 4 / 4 / `0x04:4` | +| 0x0022 | `void Item::I_push(Item *)` | 131 / 74 / `0x04:131` | `Item::setQHi(sint16)` | 115 / 51 / `0x06:115` | +| 0x0023 | `int16 Item::I_getEtherealTop(void)` | 33 / 9 / `0x00:33` | `Item::I_getClosestDirectionInRange()` | 5 / 5 / `0x0E:5` | +| 0x0024 | `void Item::I_setShape(Item *, int16 shapeno)` | 147 / 87 / `0x06:147` | `Item::hurl(sint16,sint16,sint16,sint16)` | 2 / 2 / `0x0C:2` | +| 0x0025 | `void Item::I_touch(Item *)` | 64 / 34 / `0x04:64` | `Item::getCY(void)` | 2 / 1 / `0x04:2` | +| 0x0026 | `int16 Item::I_getQHi(Item *)` | 26 / 13 / `0x04:26` | `Item::getCX(void)` | 27 / 17 / `0x04:27` | +| 0x0027 | `int16 I_getClosestDirectionInRange(x1, y1, x2, y2, numdirs, mindir, maxdir)` | 5 / 5 / `0x0E:5` | `SpriteProcess::I_createSprite()` | 85 / 49 / `0x0E:85` | +| 0x0028 | `int16 Item::I_hurl(Item *,8 bytes)` | 2 / 2 / `0x0C:2` | `Item::setNpcNum(sint16)` | 45 / 29 / `0x06:45` | +| 0x0029 | `int16 World::I_gameDifficulty(void)` | 27 / 21 / `0x00:27` | `AudioProcess::I_playSFXCru()` | 75 / 70 / `0x06:75` | +| 0x002A | `void AudioProcess::I_playAmbientSFXCru(Item *, sndno)` | 74 / 70 / `0x06:74` | `Item::setShape()` | 176 / 140 / `0x06:176` | +| 0x002B | `int16 Item::I_getQLo(Item *)` | 39 / 17 / `0x04:39` | `Item::pop(void)` | 85 / 54 / `0x04:85` | +| 0x002C | `byte Item::I_inFastArea(Item *)` | 19 / 11 / `0x04:19` | `AudioProcess::I_stopSFXCru()` | 10 / 4 / `0x04:10` | +| 0x002D | `void Item::I_setQHi(Item *, uint16 qhi)` | 84 / 40 / `0x06:84` | `Item::isCompletelyOn(uint16)` | 7 / 7 / `0x06:7` | +| 0x002E | `byte Item::I_legalMoveToPoint(Item *, Point *, int16 force)` | 52 / 15 / `0x0C:52` | `Item::popToContainer(uint16)` | 58 / 4 / `0x06:58` | +| 0x002F | `byte CurrentMap::I_canExistAtPoint(int, int, shapeno, Point *)` | 2 / 1 / `0x0A:2` | `Actor::I_getHp()` | 29 / 23 / `0x04:29` | +| 0x0030 | `void Item::I_pop(Item *)` | 27 / 18 / `0x04:27` | `Actor::I_getMana()` | 18 / 6 / `0x04:18` | +| 0x0031 | `void Item::I_andStatus(Item *, uint16 status)` | 14 / 14 / `0x06:14` | `Item::getFamily(void)` | 35 / 13 / `0x04:35` | +| 0x0032 | `void Item::I_receiveHit(Item *, other, dir, damage, damagetype)` | 20 / 16 / `0x0C:20` | `Actor::destroyContents(void)` | 16 / 7 / `0x04:16` | +| 0x0033 | `byte Actor::I_isBusy(Actor *)` | 31 / 25 / `0x04:31` | `AudioProcess::I_setVolumeForItemSFX(uint16,uint16,byte)` | 3 / 3 / `0x08:3` | +| 0x0034 | `int16 Item::I_getDirFromTo16(x1, y1, x2, y2)` | 8 / 6 / `0x08:8` | `Item::getDirToItem(uint16)` | 3 / 3 / `0x06:3` | +| 0x0035 | `byte Actor::I_isKneeling(Actor *)` | 9 / 9 / `0x04:9` | `AudioProcess::I_isSfxPlayingForObject(Item *,uint sfxno)` | 24 / 13 / `0x06:24` | +| 0x0036 | `int16 Actor::I_doAnim(12 bytes)` | 110 / 33 / `0x0C:110` | `Item::I_getRangeIfVisible()` | 10 / 8 / `0x06:10` | +| 0x0037 | `byte MainActor::I_addItemCru(4 bytes)` | 8 / 6 / `0x04:8` | `AudioProcess::I_playSFXCru()` | 31 / 20 / `0x06:31` | +| 0x0038 | `void AudioProcess::I_stopSFXCru(Item *, int16 sndno)` | 57 / 47 / `0x06:57` | `Item::andStatus(void)` | 8 / 8 / `0x06:8` | +| 0x0039 | `byte Actor::I_isDead(Item *)` | 42 / 21 / `0x04:42` | `Kernel::resetRef(uint16,ProcessType)` | 31 / 31 / `0x04:31` | +| 0x003A | `byte AudioProcess::I_isSFXPlayingForObject(Item *, int16 unk)` | 31 / 22 / `0x06:31` | `Item::touch(void)` | 29 / 21 / `0x04:29` | +| 0x003B | `void Item::I_setQLo(Item *, int16 qlo)` | 86 / 59 / `0x06:86` | `Egg::getEggId(void)` | 45 / 31 / `0x04:45` | +| 0x003C | `int16 Item::I_getItemFamily(Item *)` | 24 / 11 / `0x04:24` | `MainActor::I_addItemCru()` | 62 / 25 / `0x04:62` | +| 0x003D | `void Container::I_destroyContents(Item *)` | 15 / 10 / `0x04:15` | `Actor::I_getMap()` | 102 / 42 / `0x04:102` | +| 0x003E | `void Item::I_fallProbably_03E(Item *)` | 22 / 15 / `0x04:22` | `Item::callEvent11(sint16)` | 17 / 16 / `0x06:17` | +| 0x003F | `int16 Egg::I_getEggId(Item *)` | 56 / 32 / `0x04:56` | `CameraProcess::I_somethingAboutCameraUpdate()` | 41 / 39 / `0x00:41` | +| 0x0040 | `void CameraProcess::I_moveTo(x, y, z)` | 42 / 16 / `0x08:42` | `AudioProcess::I_stopSFXCru()` | 61 / 47 / `0x06:61` | +| 0x0041 | `void CameraProcess::I_setCenterOn(objid)` | 7 / 6 / `0x02:7` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x0042 | `byte Item::I_getRangeIfVisible(Item *, otheritem)` | 4 / 4 / `0x06:4` | `Item::getQHi(void)` | 2 / 2 / `0x04:2` | +| 0x0043 | `void AudioProcess::I_playSFXCru(Item *, soundno)` | 33 / 18 / `0x06:33` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x0044 | `byte Item::I_IsOn(Item *, uint16 itemno)` | 2 / 1 / `0x06:2` | `Item::getQHi(void)` | 2 / 2 / `0x04:2` | +| 0x0045 | `int16 Item::I_getQHi(Item *)` | 1 / 1 / `0x04:1` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x0046 | `byte Item::I_IsOn(Item *, uint16 itemno))` | 1 / 1 / `0x06:1` | `Item::getQHi(void)` | 2 / 2 / `0x04:2` | +| 0x0047 | `int16 Item::I_getQHi(Item *)` | 2 / 2 / `0x04:2` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x0048 | `byte Item::I_IsOn(Item *, uint16 itemno)` | 1 / 1 / `0x06:1` | `Item::getQHi(void)` | 2 / 2 / `0x04:2` | +| 0x0049 | `int16 Item::I_getQHi(Item *)` | 2 / 2 / `0x04:2` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x004A | `byte Item::I_IsOn(Item *, uint16 itemno)` | 1 / 1 / `0x06:1` | `Item::getQHi(void)` | 2 / 2 / `0x04:2` | +| 0x004B | `int16 Item::I_getQHi(Item *)` | 2 / 2 / `0x04:2` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x004C | `byte Item::I_IsOn(Item *, uint16 itemno)` | 1 / 1 / `0x06:1` | `Item::getQHi(void)` | 43 / 15 / `0x04:43` | +| 0x004D | `int16 Item::I_getQHi(Item *)` | 2 / 2 / `0x04:2` | `Actor::I_getCurrentActivityNo()` | 14 / 8 / `0x04:14` | +| 0x004E | `byte Item::I_IsOn(Item *, uint16 itemno)` | 1 / 1 / `0x06:1` | `Actor::isDead(void)` | 5 / 3 / `0x04:5` | +| 0x004F | `int16 Item::I_getQHi(Item *)` | 31 / 11 / `0x04:31` | `Actor::I_clrInCombat()` | 2 / 1 / `0x04:2` | +| 0x0050 | `int16 Actor::I_getCurrentActivityNo(Actor *)` | 9 / 4 / `0x04:9` | `Actor::I_setDefaultActivity0()` | 14 / 14 / `0x06:14` | +| 0x0051 | `void Actor::I_clrInCombat(Actor *)` | 2 / 1 / `0x04:2` | `Actor::I_setDefaultActivity1()` | 16 / 16 / `0x06:16` | +| 0x0052 | `void Actor::I_setDefaultActivity0(Actor *, int)` | 8 / 7 / `0x06:8` | `Actor::I_setDefaultActivity2()` | 21 / 19 / `0x06:21` | +| 0x0053 | `void Actor::I_setDefaultActivity1(Actor *, int)` | 10 / 9 / `0x06:10` | `Actor::I_setActivity()` | 1 / 1 / `0x06:1` | +| 0x0054 | `void Actor::I_setDefaultActivity2(Actor *, int)` | 13 / 10 / `0x06:13` | `World::I_setControlledNPCNum()` | 9 / 5 / `0x02:9` | +| 0x0055 | `void Actor::I_setActivity(Actor *, int)` | 1 / 1 / `0x06:1` | `Item::I_receiveHit()` | 41 / 29 / `0x0C:41` | +| 0x0056 | `void World::I_setControlledNPCNum(int itemno)` | 6 / 6 / `0x02:6` | `Game::I_isReleaseBuild()` | 1 / 1 / `0x00:1` | +| 0x0057 | `int16 Item::I_getSurfaceWeight(Item *)` | 17 / 10 / `0x04:17` | `MainActor::I_setMana()` | 13 / 8 / `0x06:13` | +| 0x0058 | `byte Item::I_isCentreOn(Item *, uint16 other)` | 13 / 12 / `0x06:13` | `Item::use(void)` | 7 / 5 / `0x04:7` | +| 0x0059 | `void Item::I_setFrame(Item *, frame)` | 555 / 208 / `0x06:555` | `Item::setUnkEggType(sint16)` | 5 / 1 / `0x06:5` | +| 0x005A | `int16 Actor::I_getLastAnimSet(4 bytes)` | 1 / 1 / `0x04:1` | `MusicProcess::I_playMusic()` | 2 / 2 / `0x02:2` | +| 0x005B | `byte Item::I_legalCreateAtPoint(Item *, int16 shape, int16 frame, Point *)` | 6 / 4 / `0x0C:6` | `Item::getSurfaceWeight(void)` | 25 / 13 / `0x04:25` | +| 0x005C | `void Item::I_getPoint(Item *, Point *)` | 1 / 1 / `0x08:1` | `Item::I_isCentreOn()` | 18 / 14 / `0x06:18` | +| 0x005D | `void StatusGump::I_hideStatusGump(void)` | 11 / 3 / `0x00:11` | `Item::setFrame(uint16)` | 261 / 135 / `0x06:261` | +| 0x005E | `int16 MovieGump::I_playMovieOverlay(uint32, char *, int16 a, int16 b)` | 40 / 6 / `0x0C:40` | `Actor::I_getLastAnimSet()` | 3 / 3 / `0x04:3` | +| 0x005F | `void StatusGump::I_showStatusGump(void)` | 9 / 5 / `0x00:9` | `Ultima8Engine::I_setAvatarInStasis()` | 74 / 40 / `0x02:74` | +| 0x0060 | `void Actor::I_setDead(4 bytes)` | 5 / 1 / `0x04:5` | `Actor::I_isBusy()` | 22 / 19 / `0x04:22` | +| 0x0061 | `void Actor::I_create(8 bytes)` | 12 / 7 / `0x08:12` | `Actor::I_getField0x13Flag2()` | 18 / 17 / `0x04:18` | +| 0x0062 | `void CameraProcess::I_somethingAboutCameraUpdate(void)` | 38 / 25 / `0x00:38` | `Actor::I_doAnim()` | 163 / 44 / `0x0C:163` | +| 0x0063 | `void Actor::I_teleport(12 bytes)` | 12 / 8 / `0x0C:12` | `Item::legalCreateAtPoint(uint16,uint16,WorldPoint&)` | 11 / 9 / `0x0C:11` | +| 0x0064 | `void Item::I_getFootpad(Item *, uint *, uint *, uint *)` | 1 / 1 / `0x10:1` | `Item::getPoint(WorldPoint&)` | 3 / 3 / `0x08:3` | +| 0x0065 | `byte Item::I_isInNPC(Item *)` | 1 / 1 / `0x04:1` | `Item::legalMoveToPoint(WorldPoint&,uint16,uint16)` | 55 / 16 / `0x0C:55` | +| 0x0066 | `int16 Item::I_getQLo(Item *)` | 21 / 12 / `0x04:21` | `Item::fall(void)` | 32 / 23 / `0x04:32` | +| 0x0067 | `int16 Item::I_getNPCNum(Item *)` | 1 / 1 / `0x04:1` | `Item::hurl(sint16,sint16,sint16,sint16)` | 1 / 1 / `0x0C:1` | +| 0x0068 | `void Item::I_setNpcNum(Item *, uint16 npcnum)` | 19 / 14 / `0x06:19` | `Kernel::getNumProcesses(uint16,ProcessType)` | 27 / 26 / `0x04:27` | +| 0x0069 | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Item::getCY(void)` | 1 / 1 / `0x04:1` | +| 0x006A | `void Item::I_move(Item *, int16 x, int16 y, uint16 z)` | 10 / 7 / `0x0A:10` | `U8Engine::I_isCfgAnimationOff()` | 21 / 9 / `0x00:21` | +| 0x006B | `int16 Game::I_isViolenceEnabled(void)` | 13 / 13 / `0x00:13` | `ResetKeyboardState()` | 13 / 13 / `0x00:13` | +| 0x006C | `void Kernel::I_resetRef(int16, int16)` | 21 / 21 / `0x04:21` | `MusicProcess::I_pauseMusic()` | 7 / 6 / `0x00:7` | +| 0x006D | `int16 Item::I_getNPCNum(Item *)` | 2 / 2 / `0x04:2` | `MovieGump::I_playMovieCutsceneRegret()` | 169 / 19 / `0x06:169` | +| 0x006E | `void Item::I_andStatus(Item *, uint16 status)` | 4 / 4 / `0x06:4` | `MusicProcess::I_unpauseMusic()` | 6 / 6 / `0x00:6` | +| 0x006F | `byte Item::I_isCompletelyOn(Item *, uint16 other)` | 6 / 6 / `0x06:6` | `Item::isInNpc(void)` | 2 / 2 / `0x04:2` | +| 0x0070 | `byte Ultima8Engine::I_getCrusaderTeleporting(void)` | 8 / 8 / `0x00:8` | `Ultima8Engine::I_setCruStasis()` | 8 / 8 / `0x00:8` | +| 0x0071 | `void Ultima8Engine::I_setCrusaderTeleporting(void)` | 2 / 2 / `0x00:2` | `Ultima8Engine::I_clrCruStasis()` | 17 / 14 / `0x00:17` | +| 0x0072 | `void Ultima8Engine::I_setCruStasis(void)` | 5 / 5 / `0x00:5` | `PaletteFaderProcess::I_jumpToColor()` | 5 / 5 / `0x06:5` | +| 0x0073 | `void Actor::I_setDead(4 bytes)` | 1 / 1 / `0x04:1` | `PaletteFaderProcess::I_fadeToGamePal()` | 19 / 19 / `0x02:19` | +| 0x0074 | `void Ultima8Engine::I_clrCrusaderTeleporting(void)` | 13 / 9 / `0x00:13` | `Actor::isDead(void)` | 14 / 11 / `0x04:14` | +| 0x0075 | `void Ultima8Engine::I_clrCruStasis(void)` | 5 / 5 / `0x00:5` | `Item::getNpcNum(void)` | 3 / 3 / `0x04:3` | +| 0x0076 | `void AudioProcess::I_stopSFX(Item *)` | 6 / 3 / `0x04:6` | `IntrinsicReturn0` | 3 / 3 / `0x08:3` | +| 0x0077 | `int16 PaletteFaderProcess::I_fadeToBlack(void)` | 9 / 6 / `0x00:9` | `Game::I_isViolenceEnabled()` | 18 / 18 / `0x00:18` | +| 0x0078 | `void MainActor::I_clrKeycards(void)` | 2 / 2 / `0x00:2` | `Item::unequip(sint16)` | 23 / 17 / `0x06:23` | +| 0x0079 | `int16 MainActor::I_teleportToEgg(int, int, int)` | 6 / 5 / `0x06:6` | `Item::andStatus(void)` | 4 / 4 / `0x06:4` | +| 0x007A | `int16 PaletteFaderProcess::I_fadeToGamePal(void)` | 10 / 6 / `0x00:10` | `Item::move(uint16,uint16,uint8)` | 7 / 5 / `0x0A:7` | +| 0x007B | `void Actor::I_clrImmortal(Actor *)` | 3 / 3 / `0x04:3` | `Ultima8Engine::I_getCrusaderTeleporting()` | 13 / 10 / `0x00:13` | +| 0x007C | `int16 Actor::I_getHp(Actor *)` | 11 / 11 / `0x04:11` | `Ultima8Engine::I_setCrusaderTeleporting()` | 12 / 12 / `0x00:12` | +| 0x007D | `void Actor::I_setActivity(Actor *, int)` | 2 / 2 / `0x06:2` | `Ultima8Engine::I_clrCrusaderTeleporting()` | 17 / 16 / `0x00:17` | +| 0x007E | `int16 Item::I_getQuality(Item *)` | 10 / 7 / `0x04:10` | `Actor::I_turnToward()` | 53 / 30 / `0x08:53` | +| 0x007F | `void Item::I_setQuality(Item *, int)` | 1 / 1 / `0x06:1` | `PaletteFaderProcess::I_fadeToBlack()` | 10 / 5 / `0x00:10` | +| 0x0080 | `int16 Item::I_use(Item *)` | 1 / 1 / `0x04:1` | `MainActor::I_clrKeycards()` | 3 / 3 / `0x00:3` | +| 0x0081 | `int16 MainActor::I_getMaxEnergy(Actor *)` | 6 / 1 / `0x04:6` | `MusicProcess::I_stopMusic()` | 9 / 8 / `0x00:9` | +| 0x0082 | `int16 Actor::I_getMana(Actor *)` | 5 / 2 / `0x04:5` | `PaletteFaderProcess::I_jumpToAllBlack()` | 35 / 25 / `0x00:35` | +| 0x0083 | `void Actor::I_setMana(Actor *, int)` | 5 / 3 / `0x06:5` | `I_setUnkFlagA4()` | 21 / 16 / `0x00:21` | +| 0x0084 | `int16 Item::I_getQLo(Item *)` | 16 / 3 / `0x04:16` | `I_clearUnkFlagA4()` | 20 / 15 / `0x00:20` | +| 0x0085 | `void Actor::I_setImmortal(Actor *)` | 6 / 5 / `0x04:6` | `MainActor::I_switchMap(int16)` | 4 / 3 / `0x02:4` | +| 0x0086 | `int16 CameraProcess::I_getCameraX(void)` | 3 / 2 / `0x00:3` | `teleportToEgg(sint16,int,uint8)` | 6 / 5 / `0x06:6` | +| 0x0087 | `int16 CameraProcess::I_getCameraY(void)` | 3 / 2 / `0x00:3` | `PaletteFaderProcess::I_fadeToGamePal()` | 6 / 5 / `0x00:6` | +| 0x0088 | `void Item::I_setMapArray(Item *, uint16 maparray)` | 10 / 10 / `0x06:10` | `Actor::I_clrImmortal()` | 5 / 5 / `0x04:5` | +| 0x0089 | `int16 Item::I_getNpcNum(Item *)` | 8 / 1 / `0x04:8` | `Actor::I_setActivity()` | 3 / 2 / `0x06:3` | +| 0x008A | `void Item::I_shoot(Item *, Point3 *, int speed, int gravity)` | 2 / 2 / `0x0C:2` | `Item::getQuality(void)` | 9 / 6 / `0x04:9` | +| 0x008B | `int16 Item::I_enterFastArea(Item *)` | 9 / 3 / `0x04:9` | `Item::setQuality(sint16)` | 1 / 1 / `0x06:1` | +| 0x008C | `void Item::I_setIsBroken(Item *)` | 3 / 2 / `0x04:3` | `MainActor::I_getMaxEnergy()` | 7 / 2 / `0x04:7` | +| 0x008D | `int16 Item::I_hurl(Item *,8 bytes)` | 1 / 1 / `0x0C:1` | `CameraProcess::I_moveTo(x,y,z)` | 29 / 15 / `0x08:29` | +| 0x008E | `int16 Item::I_getNPCNum(Item *)` | 1 / 1 / `0x04:1` | `Actor::I_setImmortal()` | 6 / 6 / `0x04:6` | +| 0x008F | `void PaletteFaderProcess::I_jumpToAllBlack(void)` | 26 / 14 / `0x00:26` | `Camera::getX(void)` | 4 / 4 / `0x00:4` | +| 0x0090 | `void MusicProcess::I_stopMusic(void)` | 4 / 4 / `0x00:4` | `Camera::getY(void)` | 1 / 1 / `0x00:1` | +| 0x0091 | `void I_setSomeMovieGlobal(void)` | 12 / 8 / `0x00:12` | `Item::setMapNum(sint16)` | 20 / 20 / `0x06:20` | +| 0x0092 | `void I_playMovieCutsceneFullscreen(char *)` | 1 / 1 / `0x0C:1` | `Item::getNpcNum(void)` | 7 / 1 / `0x04:7` | +| 0x0093 | `void I_clearSomeMovieGlobal(void)` | 11 / 7 / `0x00:11` | `Item::shoot(WorldPoint&,sint16,sint16)` | 2 / 2 / `0x0C:2` | +| 0x0094 | `void Game::I_playCredits(void)` | 3 / 3 / `0x00:3` | `CameraProcess::I_setCenterOn()` | 2 / 1 / `0x02:2` | +| 0x0095 | `byte Kernel::I_getCurrentKeyDown(void)` | 5 / 3 / `0x00:5` | `Item::enterFastArea(void)` | 8 / 2 / `0x04:8` | +| 0x0096 | `int16 MainActor::I_teleportToEgg(int, int)` | 2 / 2 / `0x04:2` | `Item::setBroken()` | 5 / 4 / `0x04:5` | +| 0x0097 | `void PaletteFaderProcess:I_jumpToGreyScale(void)` | 8 / 6 / `0x00:8` | `Item::hurl(sint16,sint16,sint16,sint16)` | 1 / 1 / `0x0C:1` | +| 0x0098 | `void I_resetVargasShieldTo500(void)` | 1 / 1 / `0x00:1` | `Item::getNpcNum(void)` | 5 / 1 / `0x04:5` | +| 0x0099 | `void Item::I_andStatus(Item *, uint16 status)` | 5 / 5 / `0x06:5` | `Ultima8Engine::I_moveKeyDownRecently()` | 3 / 3 / `0x00:3` | +| 0x009A | `void PaletteFaderProcess::I_jumpToNormalPalette(void)` | 12 / 7 / `0x00:12` | `teleportToEgg(sint16,uint8)` | 3 / 2 / `0x04:3` | +| 0x009B | `int16 PaletteFaderProcess::I_fadeToGamePal(nsteps)` | 4 / 4 / `0x02:4` | `Actor::I_createActor()` | 9 / 9 / `0x08:9` | +| 0x009C | `int16 PaletteFaderProcess::I_fadeToGamePalWithParam(nsteps, unk)` | 1 / 1 / `0x04:1` | `Actor::I_clrInCombat()` | 2 / 1 / `0x04:2` | +| 0x009D | `int16 PaletteFaderProcess::I_fadeToBlack(nsteps)` | 1 / 1 / `0x02:1` | `PaletteFaderProcess::I_jumpToGreyScale()` | 5 / 5 / `0x00:5` | +| 0x009E | `int16 PaletteFaderProcess::I_fadeToBlackWithParam(nsteps, unk)` | 1 / 1 / `0x04:1` | `PaletteFaderProcess::I_jumpToNormalPalette()` | 5 / 4 / `0x00:5` | +| 0x009F | `int16 PaletteFaderProcess::I_fadeToColor(r, g, b, nsteps, unk)` | 2 / 2 / `0x0A:2` | `CruStatusGump::I_showStatusGump()` | 8 / 8 / `0x00:8` | +| 0x00A0 | `void Actor::I_setDead(Actor *)` | 1 / 1 / `0x04:1` | `Item::andStatus(void)` | 9 / 9 / `0x06:9` | +| 0x00A1 | `int16 Item::I_getQLo(Item *)` | 10 / 5 / `0x04:10` | `Item::getUnkEggType(void)` | 8 / 2 / `0x04:8` | +| 0x00A2 | `int16 Item::I_getUnkEggType(Item *)` | 8 / 2 / `0x04:8` | `Egg::setEggXRange(uint16)` | 8 / 2 / `0x06:8` | +| 0x00A3 | `void Egg::I_setEggXRange(Egg *, int)` | 8 / 2 / `0x06:8` | `Item::setFrame(uint16)` | 462 / 206 / `0x06:462` | +| 0x00A4 | `byte Item::I_overlaps(Item *, uint16 unk)` | 14 / 13 / `0x06:14` | `Item::overlaps(uint16)` | 17 / 16 / `0x06:17` | +| 0x00A5 | `byte Item::I_isOn(Item *, itemno)` | 3 / 3 / `0x06:3` | `Item::isOn(uint16)` | 3 / 3 / `0x06:3` | +| 0x00A6 | `int16 I_getAnimationsEnabled(void)` | 16 / 7 / `0x00:16` | `Item::getQHi(void)` | 4 / 4 / `0x04:4` | +| 0x00A7 | `int16 Egg::I_getEggXRange(Egg *)` | 1 / 1 / `0x04:1` | `Actor::I_getLastAnimSet()` | 1 / 1 / `0x04:1` | +| 0x00A8 | `void Actor::I_setDead(Actor *)` | 2 / 2 / `0x04:2` | `Item::getCY(void)` | 4 / 2 / `0x04:4` | +| 0x00A9 | `void I_playMovieCutsceneFullscreen(char *)` | 17 / 6 / `0x0C:17` | `CurrentMap::I_canExistAt()` | 23 / 6 / `0x08:23` | +| 0x00AA | `void AudioProcess::I_playSFX(2 bytes)` | 7 / 4 / `0x02:7` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x00AB | `byte Actor::I_isFalling(Actor *)` | 2 / 2 / `0x04:2` | `Actor::isDead(void)` | 3 / 1 / `0x04:3` | +| 0x00AC | `int16 Item::I_getFamilyOfType(Item *)` | 1 / 1 / `0x02:1` | `Item::hurl(sint16,sint16,sint16,sint16)` | 1 / 1 / `0x0C:1` | +| 0x00AD | `int16 Item::I_getNPCNum(Item *)` | 2 / 2 / `0x04:2` | `Item::I_inFastArea()` | 16 / 8 / `0x04:16` | +| 0x00AE | `int16 Item::I_getQLo(Item *)` | 40 / 21 / `0x04:40` | `Item::getQHi(void)` | 10 / 6 / `0x04:10` | +| 0x00AF | `int16 Item::I_getQHi(Item *)` | 4 / 4 / `0x04:4` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x00B0 | `int16 Item::I_unequip(6 bytes)` | 11 / 11 / `0x06:11` | `Item::hurl(sint16,sint16,sint16,sint16)` | 1 / 1 / `0x0C:1` | +| 0x00B1 | `int16 Item::I_spawnUsecodeEvent0x13(Item *, 2 bytes)` | 13 / 7 / `0x06:13` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x00B2 | `void Item::I_andStatus(Item *, uint16 status)` | 5 / 5 / `0x06:5` | `Item::hurl(sint16,sint16,sint16,sint16)` | 1 / 1 / `0x0C:1` | +| 0x00B3 | `int32 I_getCurrentTimerTick(void)` | 3 / 1 / `0x00:3` | `Item::andStatus(void)` | 9 / 6 / `0x06:9` | +| 0x00B4 | `void Ultima8Engine::I_setAlertActive(void)` | 1 / 1 / `0x00:1` | `Item::getDirToCoords(uint16,uint16)` | 1 / 1 / `0x08:1` | +| 0x00B5 | `int16 Item::I_equip(6 bytes)` | 18 / 12 / `0x06:18` | `MainActor::I_removeItem(uint16)` | 4 / 4 / `0x02:4` | +| 0x00B6 | `void Ultima8Engine::I_clrAlertActive(void)` | 7 / 2 / `0x00:7` | `I_updateInventoryUI()` | 9 / 8 / `0x00:9` | +| 0x00B7 | `int16 Ultima8Engine::I_getAvatarInStasis(void)` | 1 / 1 / `0x00:1` | `Item::getNpcNum(void)` | 2 / 2 / `0x04:2` | +| 0x00B8 | `byte MainActor::I_addItemCru(4 bytes)` | 25 / 13 / `0x04:25` | `Item::getCY(void)` | 8 / 1 / `0x04:8` | +| 0x00B9 | `int16 Actor::I_getLastAnimSet(4 bytes)` | 5 / 2 / `0x04:5` | `Item::isOn(uint16)` | 2 / 2 / `0x06:2` | +| 0x00BA | `void Item::I_setQuality(Item *, int)` | 4 / 3 / `0x06:4` | `Item::getFootpad(sint16&,sint16&,sint16&)` | 2 / 2 / `0x10:2` | +| 0x00BB | `byte CurrentMap::I_canExistAt(int shapeno, word x, word y, byte z)` | 17 / 5 / `0x08:17` | `Actor::isDead(void)` | 23 / 16 / `0x04:23` | +| 0x00BC | `byte Item::I_isOn(Item *, itemno)` | 1 / 1 / `0x06:1` | `Actor::I_createActorCru()` | 2 / 1 / `0x06:2` | +| 0x00BD | `int16 Item::I_hurl(Item *,8 bytes)` | 1 / 1 / `0x0C:1` | `Actor::I_setActivity()` | 48 / 17 / `0x06:48` | +| 0x00BE | `int16 Item::I_getQHi(Item *)` | 14 / 10 / `0x04:14` | `KeypadGump::I_showKeypad()` | 3 / 2 / `0x02:3` | +| 0x00BF | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Item::andStatus(void)` | 4 / 3 / `0x06:4` | +| 0x00C0 | `int16 Item::I_hurl(Item *,8 bytes)` | 1 / 1 / `0x0C:1` | `ComputerGump::I_readComputer()` | 25 / 3 / `0x04:25` | +| 0x00C1 | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `UCMachine::I_numToStr()` | 1 / 1 / `0x02:1` | +| 0x00C2 | `int16 Item::I_hurl(Item *,8 bytes)` | 1 / 1 / `0x0C:1` | `IntrinsicReturn0` | 1 / 1 / `0x08:1` | +| 0x00C3 | `void Item::I_andStatus(Item *, uint16 status)` | 11 / 7 / `0x06:11` | `Actor::I_getDir()` | 56 / 15 / `0x04:56` | +| 0x00C4 | `int16 KeypadGump::I_showKeypad(int targetCode)` | 2 / 2 / `0x02:2` | `Item::getQHi(void)` | 12 / 12 / `0x04:12` | +| 0x00C5 | `byte Item::I_isOn(Item *, itemno)` | 1 / 1 / `0x06:1` | `Item::setQuality(sint16)` | 4 / 3 / `0x06:4` | +| 0x00C6 | `void SpriteProcess::I_createSprite(word, word, word, word, uword, uword, ubyte)` | 22 / 8 / `0x0E:22` | `Item::hurl(sint16,sint16,sint16,sint16)` | 4 / 3 / `0x0C:4` | +| 0x00C7 | `byte Item::I_getDirFromItem(Item *, itemno)` | 1 / 1 / `0x06:1` | `Actor::I_addHp()` | 1 / 1 / `0x06:1` | +| 0x00C8 | `int16 Item::I_hurl(Item *,8 bytes)` | 6 / 4 / `0x0C:6` | `CruHealerProcess::I_create()` | 1 / 1 / `0x00:1` | +| 0x00C9 | `int16 Item::I_getQHi(Item *)` | 9 / 7 / `0x04:9` | `Item::callEvent0A(sint16)` | 18 / 12 / `0x06:18` | +| 0x00CA | `byte Actor::I_addHp(Actor *, int)` | 1 / 1 / `0x06:1` | `Item::setBroken()` | 7 / 5 / `0x04:7` | +| 0x00CB | `void MainActor::I_switchMap(int16 mapnum)` | 3 / 2 / `0x02:3` | `Item::isOn(uint16)` | 2 / 2 / `0x06:2` | +| 0x00CC | `byte Actor::I_getInCombat(Actor *)` | 8 / 3 / `0x04:8` | `Actor::I_teleport()` | 3 / 3 / `0x0C:3` | +| 0x00CD | `void Actor::I_setActivity(Actor *, int)` | 2 / 2 / `0x06:2` | `Item::I_getDirFromTo16()` | 4 / 3 / `0x08:4` | +| 0x00CE | `int16 Game::I_isReleaseBuild(void)` | 3 / 3 / `0x00:3` | `Item::getQHi(void)` | 12 / 10 / `0x04:12` | +| 0x00CF | `void Item::I_setQAndCombine(Item *, int16 q)` | 2 / 1 / `0x06:2` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x00D0 | `int16 Item::I_use(Item *)` | 1 / 1 / `0x04:1` | `Actor::I_isInCombat()` | 4 / 2 / `0x04:4` | +| 0x00D1 | `void AudioProcess:I_stopAllSFX(void)` | 1 / 1 / `0x00:1` | `Actor::I_getNPCDataField0x4()` | 16 / 5 / `0x04:16` | +| 0x00D2 | `void I_playMovieCutscene(int *item,char *flicname,word sizex,word sizey)` | 1 / 1 / `0x0E:1` | `Actor::I_setCombatTactic()` | 3 / 1 / `0x06:3` | +| 0x00D3 | `void I_clearKeyboardState(void)` | 4 / 4 / `0x00:4` | `Actor::I_setDead())` | 1 / 1 / `0x04:1` | +| 0x00D4 | `void I_playSFX(2 bytes)` | 1 / 1 / `0x02:1` | `CameraProcess::I_getCameraY()` | 1 / 1 / `0x00:1` | +| 0x00D5 | `int16 Item::I_use(Item *)` | 2 / 1 / `0x04:2` | `Actor::I_getEquip()` | 3 / 1 / `0x06:3` | +| 0x00D6 | `byte CameraProcess::I_getCameraZ(void)` | 2 / 1 / `0x00:2` | `Actor::I_setEquip()` | 2 / 1 / `0x08:2` | +| 0x00D7 | `int16 Actor::I_getLastAnimSet(4 bytes)` | 1 / 1 / `0x04:1` | `Actor::I_getDefaultActivity0()` | 1 / 1 / `0x04:1` | +| 0x00D8 | `void Actor::I_setDead(4 bytes)` | 1 / 1 / `0x04:1` | `Actor::I_getDefaultActivity1()` | 1 / 1 / `0x04:1` | +| 0x00D9 | `int16 Item::I_getQLo(Item *)` | 26 / 12 / `0x04:26` | `Actor::I_getDefaultActivity2()` | 1 / 1 / `0x04:1` | +| 0x00DA | `void PaletteFaderProcess::I_setPalToAllGrey(void)` | 3 / 2 / `0x00:3` | `Actor::I_getLastAnimSet()` | 12 / 4 / `0x04:12` | +| 0x00DB | `void Actor::I_setActivity(Actor *, int)` | 13 / 5 / `0x06:13` | `Actor::I_isFalling()` | 2 / 2 / `0x04:2` | +| 0x00DC | `byte Item::I_isOn(Item *, itemno)` | 1 / 1 / `0x06:1` | `Item::getQLo(void)` | 5 / 4 / `0x04:5` | +| 0x00DD | `int16 Actor::I_getLastActivityNo(Actor *)` | 16 / 5 / `0x04:16` | `Item::getQHi(void)` | 33 / 23 / `0x04:33` | +| 0x00DE | `void Actor::I_setCombatTactic(Actor *, int)` | 3 / 1 / `0x06:3` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x00DF | `int16 Actor::I_getEquip(6 bytes)` | 3 / 1 / `0x06:3` | `Item::I_setField0x81()` | 4 / 4 / `0x06:4` | +| 0x00E0 | `void Actor::I_setEquip(8 bytes)` | 2 / 1 / `0x08:2` | `Item::hurl(sint16,sint16,sint16,sint16)` | 10 / 4 / `0x0C:10` | +| 0x00E1 | `int16 Actor::I_getDefaultActivity0(Actor *)` | 1 / 1 / `0x04:1` | `Actor::I_setDead()` | 3 / 1 / `0x04:3` | +| 0x00E2 | `int16 Actor::I_getDefaultActivity1(Actor *)` | 1 / 1 / `0x04:1` | `Item::getQLo(void)` | 15 / 13 / `0x04:15` | +| 0x00E3 | `int16 Actor::I_getDefaultActivity2(Actor *)` | 1 / 1 / `0x04:1` | `Item::getCY(void)` | 10 / 10 / `0x04:10` | +| 0x00E4 | `int16 Actor::I_getLastAnimSet(4 bytes)` | 1 / 1 / `0x04:1` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x00E5 | `void Actor::I_setTarget(Actor *, uint16 target)` | 2 / 1 / `0x06:2` | `Item::hurl(sint16,sint16,sint16,sint16)` | 2 / 1 / `0x0C:2` | +| 0x00E6 | `void Actor::I_SetNPCDataField0x63_0E6(Actor *, int)` | 4 / 4 / `0x06:4` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x00E7 | `void Actor::I_setDead(4 bytes)` | 2 / 1 / `0x04:2` | `Item::hurl(sint16,sint16,sint16,sint16)` | 2 / 1 / `0x0C:2` | +| 0x00E8 | `int16 Item::I_cast(6 bytes)` | 2 / 2 / `0x06:2` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x00E9 | `void Item::I_andStatus(Item *, uint16 status)` | 11 / 11 / `0x06:11` | `Item::hurl(sint16,sint16,sint16,sint16)` | 2 / 1 / `0x0C:2` | +| 0x00EA | `int16 Item::I_getQLo(Item *)` | 145 / 51 / `0x04:145` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x00EB | `int16 I_GetQOfAvatarInventoryItem0x4ed_0EB(void)` | 2 / 2 / `0x00:2` | `Item::hurl(sint16,sint16,sint16,sint16)` | 2 / 1 / `0x0C:2` | +| 0x00EC | `void Item::I_popToEnd(Item*, int)` | 1 / 1 / `0x06:1` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x00ED | `void Item::I_popToContainer(Item*, int)` | 40 / 5 / `0x06:40` | `Item::hurl(sint16,sint16,sint16,sint16)` | 2 / 1 / `0x0C:2` | +| 0x00EE | `void BatteryChargerProcess::I_create(void)` | 2 / 2 / `0x00:2` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x00EF | `int16 Kernel::I_getNumProcesses(int, int)` | 4 / 4 / `0x04:4` | `Item::hurl(sint16,sint16,sint16,sint16)` | 2 / 1 / `0x0C:2` | +| 0x00F0 | `int16 Item::I_getQHi(Item *)` | 8 / 8 / `0x04:8` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x00F1 | `byte Item::I_isOn(Item *, itemno)` | 1 / 1 / `0x06:1` | `Item::hurl(sint16,sint16,sint16,sint16)` | 2 / 1 / `0x0C:2` | +| 0x00F2 | `void Actor::I_setActivity(Actor *, int)` | 41 / 6 / `0x06:41` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x00F3 | `int16 Item::I_getQHi(Item *)` | 7 / 5 / `0x04:7` | `Item::hurl(sint16,sint16,sint16,sint16)` | 2 / 1 / `0x0C:2` | +| 0x00F4 | `int16 Item::I_getQ(Item *)` | 7 / 7 / `0x04:7` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x00F5 | `void Item::I_setQ(Item *, uint16 q)` | 8 / 8 / `0x06:8` | `Item::hurl(sint16,sint16,sint16,sint16)` | 2 / 1 / `0x0C:2` | +| 0x00F6 | `void CruHealer::I_create_0F6(void)` | 1 / 1 / `0x00:1` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x00F7 | `int16 Item::I_hurl(Item *,8 bytes)` | 1 / 1 / `0x0C:1` | `Item::andStatus(void)` | 8 / 8 / `0x06:8` | +| 0x00F8 | `int16 Item::I_getNPCNum(Item *)` | 3 / 3 / `0x04:3` | `Actor::I_setDead()` | 1 / 1 / `0x04:1` | +| 0x00F9 | `int16 Item::I_hurl(Item *,8 bytes)` | 2 / 1 / `0x0C:2` | `Item::getQLo(void)` | 1 / 1 / `0x04:1` | +| 0x00FA | `byte Item::I_isOn(Item *, itemno)` | 1 / 1 / `0x06:1` | `Actor::I_setDead()` | 1 / 1 / `0x04:1` | +| 0x00FB | `int16 Item::I_getQHi(Item *)` | 17 / 12 / `0x04:17` | `Dtable::I_getMaxHPForNPC()` | 1 / 1 / `0x04:1` | +| 0x00FC | `void Item::I_andStatus(Item *, uint16 status)` | 3 / 3 / `0x06:3` | `Actor::I_setHP()` | 1 / 1 / `0x06:1` | +| 0x00FD | `byte MainActor::I_hasKeycard(int)` | 1 / 1 / `0x02:1` | `Item::getQLo(void)` | 36 / 19 / `0x04:36` | +| 0x00FE | `void ComputerGump::I_readComputer(char *)` | 2 / 2 / `0x04:2` | `BatteryChargerProcess::I_create()` | 1 / 1 / `0x00:1` | +| 0x00FF | `int16 UCMachine::I_numToStr(int16 num)` | 12 / 1 / `0x02:12` | `Item::hurl(sint16,sint16,sint16,sint16)` | 1 / 1 / `0x0C:1` | +| 0x0100 | `int16 Item::I_getNPCNum(Item *)` | 1 / 1 / `0x04:1` | `Item::andStatus(void)` | 5 / 5 / `0x06:5` | +| 0x0101 | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x0102 | `int16 Item::I_getNPCNum(Item *)` | 4 / 3 / `0x04:4` | `Actor::isDead(void)` | 2 / 2 / `0x04:2` | +| 0x0103 | `byte Item::I_isCrusTypeNPC(uint16 shapenum)` | 11 / 3 / `0x02:11` | `Actor::I_setActivity()` | 1 / 1 / `0x06:1` | +| 0x0104 | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Item::getQHi(void)` | 9 / 8 / `0x04:9` | +| 0x0105 | `int16 Item::I_getNPCNum(Item *)` | 1 / 1 / `0x04:1` | `Actor::I_getLastAnimSet()` | 1 / 1 / `0x04:1` | +| 0x0106 | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Actor::I_setDead()` | 1 / 1 / `0x04:1` | +| 0x0107 | `int16 Item::I_getNPCNum(Item *)` | 2 / 2 / `0x04:2` | `Item::getQLo(void)` | 113 / 35 / `0x04:113` | +| 0x0108 | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x0109 | `int16 Item::I_getNPCNum(Item *)` | 2 / 2 / `0x04:2` | `Item::getQHi(void)` | 2 / 2 / `0x04:2` | +| 0x010A | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x010B | `int16 Item::I_getNPCNum(Item *)` | 2 / 2 / `0x04:2` | `Item::getQHi(void)` | 6 / 5 / `0x04:6` | +| 0x010C | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Item::hurl(sint16,sint16,sint16,sint16)` | 1 / 1 / `0x0C:1` | +| 0x010D | `int16 Item::I_getNPCNum(Item *)` | 2 / 2 / `0x04:2` | `Item::getNpcNum(void)` | 3 / 3 / `0x04:3` | +| 0x010E | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Item::getCY(void)` | 1 / 1 / `0x04:1` | +| 0x010F | `int16 Item::I_getNPCNum(Item *)` | 2 / 2 / `0x04:2` | `Item::hurl(sint16,sint16,sint16,sint16)` | 2 / 1 / `0x0C:2` | +| 0x0110 | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Item::isOn(uint16)` | 1 / 1 / `0x06:1` | +| 0x0111 | `int16 Item::I_getNPCNum(Item *)` | 2 / 2 / `0x04:2` | `MainActor::I_hasKeycard()` | 1 / 1 / `0x02:1` | +| 0x0112 | `byte Actor::I_getDir(Actor *)` | 3 / 3 / `0x04:3` | `IntrinsicReturn0` | 1 / 1 / `0x08:1` | +| 0x0113 | `int16 UCMachine::I_numToStr(int16 num)` | 9 / 1 / `0x02:9` | `Actor::isDead(void)` | 9 / 5 / `0x04:9` | +| 0x0114 | `void Item::I_andStatus(Item *, uint16 status)` | 2 / 2 / `0x06:2` | `Actor::I_clrImmortal()` | 4 / 4 / `0x04:4` | +| 0x0115 | `int16 Item::I_getNPCNum(Item *)` | 3 / 2 / `0x04:3` | `UCMachine::I_numToStr()` | 13 / 1 / `0x02:13` | +| 0x0116 | `byte Item::I_fireDistance(14 bytes)` | 2 / 1 / `0x0E:2` | `Item::getQHi(void)` | 41 / 27 / `0x04:41` | +| 0x0117 | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Actor::I_setActivity()` | 46 / 8 / `0x06:46` | +| 0x0118 | `int16 Item::I_hurl(Item *,8 bytes)` | 8 / 1 / `0x0C:8` | `Item::andStatus(void)` | 2 / 2 / `0x06:2` | +| 0x0119 | `void Item::I_setIsBroken(Item *)` | 1 / 1 / `0x04:1` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x011A | `void Item::I_andStatus(Item *, uint16 status)` | 1 / 1 / `0x06:1` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x011B | `byte Item::I_getTypeFlag(Item *, uint16 shift)` | 1 / 1 / `0x06:1` | `Item::getNpcNum(void)` | 4 / 3 / `0x04:4` | +| 0x011C | `int16 Item::I_getNPCNum(Item *)` | 1 / 1 / `0x04:1` | `Item::I_isCrusTypeNPC()` | 11 / 3 / `0x02:11` | +| 0x011D | `int16 Item::I_hurl(Item *,8 bytes)` | 1 / 1 / `0x0C:1` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x011E | `int16 Item::I_getCY(Item *)` | 1 / 1 / `0x04:1` | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x011F | `byte Item::I_getCZ(Item *)` | 2 / 2 / `0x04:2` | `Item::AvatarStoleSomehting(uint16)` | 13 / 7 / `0x06:13` | +| 0x0120 | `int16 Item::I_getCX(Item *)` | 9 / 2 / `0x04:9` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x0121 | `byte Actor::I_getDir(4 bytes)` | 2 / 2 / `0x04:2` | `Item::getNpcNum(void)` | 2 / 2 / `0x04:2` | +| 0x0122 | `byte Actor::I_isDead(Item *)` | 2 / 1 / `0x04:2` | `Item::getQ(void)` | 6 / 6 / `0x04:6` | +| 0x0123 | `int16 Item::I_getNPCNum(Item *)` | 1 / 1 / `0x04:1` | `Item::setQ(uint)` | 6 / 6 / `0x06:6` | +| 0x0124 | `int16 Actor::I_getLastAnimSet(4 bytes)` | 8 / 1 / `0x04:8` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x0125 | `void Item::I_setQuality(Item *, int)` | 4 / 1 / `0x06:4` | `Item::getNpcNum(void)` | 2 / 2 / `0x04:2` | +| 0x0126 | `int16 UCMachine::I_numToStr(int16 num)` | 32 / 2 / `0x02:32` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x0127 | `byte Item::I_getDirToCoords(Item *, uin16 x, uint16 y)` | 1 / 1 / `0x08:1` | `Item::getNpcNum(void)` | 2 / 2 / `0x04:2` | +| 0x0128 | `void Item::I_andStatus(Item *, uint16 status)` | 2 / 2 / `0x06:2` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x0129 | `int16 Item::I_getNPCNum(Item *)` | 2 / 2 / `0x04:2` | `Item::getNpcNum(void)` | 2 / 2 / `0x04:2` | +| 0x012A | `void Item::I_setIsBroken(Item *)` | 1 / 1 / `0x04:1` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x012B | `int16 IItem::I_getCY(Item *)` | 8 / 1 / `0x04:8` | `Item::getNpcNum(void)` | 2 / 2 / `0x04:2` | +| 0x012C | `byte Item::I_isOn(Item *, itemno)` | 1 / 1 / `0x06:1` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x012D | `void Item::I_getFootpadData(Item *, uint *, uint *, uint *)` | 2 / 2 / `0x10:2` | `Item::getNpcNum(void)` | 2 / 2 / `0x04:2` | +| 0x012E | `byte Actor::I_isDead(Item *)` | 2 / 2 / `0x04:2` | `Actor::I_getDir()` | 3 / 3 / `0x04:3` | +| 0x012F | `int16 Actor::I_createActorCru(Item *, uint16 other_itemno)` | 2 / 1 / `0x06:2` | `Item::andStatus(void)` | 2 / 2 / `0x06:2` | +| 0x0130 | `void Actor::I_clrImmortal(Actor *)` | 2 / 2 / `0x04:2` | `Item::getNpcNum(void)` | 2 / 1 / `0x04:2` | +| 0x0131 | `void Actor::I_setActivity(Actor *, int)` | 3 / 2 / `0x06:3` | `Intrinsic0131()` | 2 / 1 / `0x0E:2` | +| 0x0132 | `void Item::I_andStatus(Item *, int16 status)` | 2 / 2 / `0x06:2` | `Item::andStatus(void)` | 1 / 1 / `0x06:1` | +| 0x0133 | `int16 Item::I_getQHi(Item *)` | 5 / 1 / `0x04:5` | `Item::hurl(sint16,sint16,sint16,sint16)` | 8 / 1 / `0x0C:8` | +| 0x0134 | `void WeaselGump::I_showGump(uint16 param)` | 2 / 1 / `0x02:2` | `Item::andStatus(void)` | 2 / 2 / `0x06:2` | +| 0x0135 | `void Actor::I_setDead(Actor *)` | 3 / 3 / `0x04:3` | `Camera::getY(void)` | 2 / 2 / `0x00:2` | +| 0x0136 | `void UNUSEDInt136()` | not scanned | `Camera::getZ(void)` | 2 / 2 / `0x00:2` | +| 0x0137 | not in converter table | not scanned | `CruStatusGump::I_hideStatusGump()` | 5 / 5 / `0x00:5` | +| 0x0138 | not in converter table | not scanned | `Actor::I_clrInCombat()` | 2 / 1 / `0x04:2` | +| 0x0139 | not in converter table | not scanned | `Item::getTypeFlagCrusader(sint16)` | 1 / 1 / `0x06:1` | +| 0x013A | not in converter table | not scanned | `Item::getNpcNum(void)` | 1 / 1 / `0x04:1` | +| 0x013B | not in converter table | not scanned | `Item::hurl(sint16,sint16,sint16,sint16)` | 1 / 1 / `0x0C:1` | +| 0x013C | not in converter table | not scanned | `Item::getCY(void)` | 1 / 1 / `0x04:1` | +| 0x013D | not in converter table | not scanned | `Item::getCZ(void)` | 2 / 2 / `0x04:2` | +| 0x013E | not in converter table | not scanned | `Item::setFrame(uint16)` | 41 / 11 / `0x06:41` | +| 0x013F | not in converter table | not scanned | `AudioProcess::I_playAmbientSFX()` | 11 / 8 / `0x02:11` | +| 0x0140 | not in converter table | not scanned | `AudioProcess::I_isSFXPlaying()` | 2 / 2 / `0x02:2` | +| 0x0141 | not in converter table | not scanned | `World::I_clrAlertActiveRegret()` | 2 / 2 / `0x00:2` | +| 0x0142 | not in converter table | not scanned | `PaletteFaderProcess::I_fadeToGivenColor()` | 2 / 2 / `0x0A:2` | +| 0x0143 | not in converter table | not scanned | `Actor::isDead(void)` | 8 / 8 / `0x04:8` | +| 0x0144 | not in converter table | not scanned | `Actor::I_setDead()` | 3 / 3 / `0x04:3` | +| 0x0145 | not in converter table | not scanned | `Game::I_playCredits()` | 6 / 6 / `0x00:6` | +| 0x0146 | not in converter table | not scanned | `PaletteFaderProcess::I_jumpToAllGrey()` | 2 / 2 / `0x00:2` | +| 0x0147 | not in converter table | not scanned | `Item::I_getFamilyOfType()` | 1 / 1 / `0x02:1` | +| 0x0148 | not in converter table | not scanned | `Item::getNpcNum(void)` | 2 / 2 / `0x04:2` | +| 0x0149 | not in converter table | not scanned | `Item::getQLo(void)` | 33 / 13 / `0x04:33` | +| 0x014A | not in converter table | not scanned | `Item::andStatus(void)` | 2 / 2 / `0x06:2` | +| 0x014B | not in converter table | not scanned | `Ultima8Engine::getCurrentTimerTick()` | 3 / 1 / `0x00:3` | +| 0x014C | not in converter table | not scanned | `World::I_setAlertActiveRegret()` | 1 / 1 / `0x00:1` | +| 0x014D | not in converter table | not scanned | `Ultima8Engine::I_getAvatarInStasis()` | 1 / 1 / `0x00:1` | +| 0x014E | not in converter table | not scanned | `MainActor::I_addItemCru()` | 1 / 1 / `0x04:1` | +| 0x014F | not in converter table | not scanned | `Egg::getEggXRange(void)` | 1 / 1 / `0x04:1` | +| 0x0150 | not in converter table | not scanned | `Actor::I_clrInCombat()` | 2 / 1 / `0x04:2` | +| 0x0151 | not in converter table | not scanned | `PaletteFaderProcess::I_jumpToColor()` | 2 / 2 / `0x06:2` | +| 0x0152 | not in converter table | not scanned | `Item::setFrame(uint16)` | 9 / 8 / `0x06:9` | +| 0x0153 | not in converter table | not scanned | `UCMachine::I_numToStr()` | 9 / 1 / `0x02:9` | +| 0x0154 | not in converter table | not scanned | `Actor::I_getDir()` | 3 / 2 / `0x04:3` | +| 0x0155 | not in converter table | not scanned | `UCMachine::I_numToStr()` | 9 / 1 / `0x02:9` | +| 0x0156 | not in converter table | not scanned | `Item::isOn(uint16)` | 2 / 1 / `0x06:2` | +| 0x0157 | not in converter table | not scanned | `Actor::I_getDir()` | 6 / 2 / `0x04:6` | +| 0x0158 | not in converter table | not scanned | `Actor::I_setDead()` | 1 / 1 / `0x04:1` | +| 0x0159 | not in converter table | not scanned | `Item::getQHi(void)` | 2 / 2 / `0x04:2` | +| 0x015A | not in converter table | not scanned | `Item::getQLo(void)` | 1 / 1 / `0x04:1` | +| 0x015B | not in converter table | not scanned | `UCMachine::I_numToStr()` | 12 / 1 / `0x02:12` | +| 0x015C | not in converter table | not scanned | `Actor::I_getDir()` | 3 / 1 / `0x04:3` | +| 0x015D | not in converter table | not scanned | `Intrinsic015D()` | not scanned | + +## Evidence and limits + +- The bytecode scan establishes that a raw ordinal and argument-byte count occur at a static call site. It does not prove that a path executes in a retail playthrough. +- Converter prototypes can be imprecise, stale, or inconsistent across variants. Similar labels in both columns do not prove matching native behavior or ABI. +- Ghidra's Remorse `Item_Equip` annotations identify ordinals `0x0006` and `0x00B5`; `Item_Cast` identifies `0x00E8`. The native wrappers route these through `Usecode_ItemCallEvent` as `UC_Equip` and `UC_Cast`, corroborating those Remorse runtime mappings. +- Regret's native dispatch table was not independently verified in the referenced Ghidra pass. Treat Regret converter entries as naming/signature hints pending runtime cross-checks. +- The local Remorse bytecode includes `0x0134` and `0x0135`, beyond Pentagram's configured 308-entry sparse runtime table. This is a version/source coverage difference, not evidence that those bytecode calls are invalid. +- The current census is limited to the main local corpora. Variant/version-specific re-scans should be added as separately labeled columns or sections, not blended into these counts. + +For archive parsing, opcode details, event dispatch, and broad capability families, see the [main format specification](./usecode-format-specification.md). diff --git a/docs/usecode-pentagram-ghidra-path.md b/docs/usecode-pentagram-ghidra-path.md index 0d0a53c..d91f3c6 100644 --- a/docs/usecode-pentagram-ghidra-path.md +++ b/docs/usecode-pentagram-ghidra-path.md @@ -10,6 +10,12 @@ The goal is not to make Ghidra decompile Crusader USECODE as if it were x86 imme - replace Pentagram's older Crusader container/header assumptions with the owner-loaded class and slot model already verified in the binary and extractor - emit a lossless IR that can drive both human-readable USECODE output and future Ghidra annotations +## Product Development Direction + +The user-facing USECODE editor/decompiler/recompiler should be developed in the newer map-viewer decompiler at [usecode-decompiler.js](../../crusader_map_viewer/map_renderer/src/lib/usecode-decompiler.js), not by growing the Python proof of concept into a separate authoring tool. The map-viewer decompiler already has the newer structured rendering work and is the implementation to improve toward editable source, compilation, archive rebuilding, and in-game validation. + +The `tools/poc_crusader_usecode_parser.py` workflow below remains useful for reproducing byte-level analysis, generating comparison artifacts, and feeding verified evidence into the map-viewer implementation. It is not the intended end-user editing or recompilation workflow. + ## What To Reuse From Pentagram Useful directly: @@ -92,7 +98,7 @@ The first Ghidra-side use should be comments, bookmarks, and cross-reference not Do not try to map the bytecode into a full processor module first. -## Proof-Of-Concept Parser +## Proof-Of-Concept Parser And Evidence Workflow Tool path: @@ -109,10 +115,10 @@ Current deliberate limits: - no full intrinsic name table yet - no synthetic control-flow graph yet -- no recompilation path yet +- no recompilation path in this proof-of-concept tool - no Ghidra importer yet -That keeps the parser useful without pretending the VM is fully solved. +That keeps the parser useful without pretending the VM is fully solved. Continue the product-facing decompiler/editor/compiler work in the map viewer; keep this parser as an evidence source and independent cross-check. ## Canonical Ghidra Annotation Import Path diff --git a/docs/usecode-roundtrip-ir.md b/docs/usecode-roundtrip-ir.md index 3050ca4..46753da 100644 --- a/docs/usecode-roundtrip-ir.md +++ b/docs/usecode-roundtrip-ir.md @@ -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)** diff --git a/docs/usecode-tool-improvement-plan.md b/docs/usecode-tool-improvement-plan.md index 8911ccd..2f438cf 100644 --- a/docs/usecode-tool-improvement-plan.md +++ b/docs/usecode-tool-improvement-plan.md @@ -1,42 +1,40 @@ -# USECODE Tool Improvement Plan +# USECODE Map-Viewer Decompiler/Editor Plan ## Purpose -This note turns the earlier tooling comparison into a concrete improvement plan for the local parser/decompiler. +This note turns the tooling comparison into an implementation plan for the map-viewer USECODE decompiler/editor. -The intent is not to copy Pentagram or `crusader-disasm` wholesale. The intent is to extract the parts that are genuinely useful for the current workspace toolchain: +The primary development target is the newer map-viewer implementation at [usecode-decompiler.js](../../crusader_map_viewer/map_renderer/src/lib/usecode-decompiler.js), with regressions in `map_renderer/scripts/test-usecode-structuring.mjs`. It should grow into the actual user-facing tool for decompiling, editing, and recompiling USECODE. -- `tools/poc_crusader_usecode_parser.py` -- `tools/export_usecode_pseudocode.py` -- the extracted owner-loaded corpus under `USECODE/EUSECODE_extracted/` +The local Python parser/exporter and `USECODE/EUSECODE_extracted/` corpus are supporting research infrastructure: use them for byte-level evidence, fixtures, and independent output comparisons. Do not build a competing end-user editor/compiler in those tools. + +The intent is not to copy Pentagram or `crusader-disasm` wholesale. Extract their useful opcode, operand, and metadata evidence and apply it to the map-viewer implementation. ## Short version -The most useful next upgrades are: +The most useful next upgrades in the map-viewer implementation are: -1. make the decoder tables more authoritative -2. decode loop/selector idioms into real structured searches -3. improve intrinsic naming and signatures -4. distinguish code from trailers more rigorously -5. add corpus-level pattern clustering and family annotations -6. keep strengthening the runtime bridge back into the retail binary +1. keep strengthening opcode/operand and control-flow coverage +2. preserve a lossless, editable IR alongside readable pseudocode +3. add a source/IR editing workflow +4. build an assembler and deterministic class/FLEX archive writer +5. validate untouched and modified output, including in-game behavior ## Current status -Implemented in the current local parser/exporter batch: +Existing work to build on: -- first evidence-backed class/slot aliasing for spawned or called helpers, so common wrappers now render with class names and known slot names such as `FREE.waitNTimerTicks(...)` instead of raw `class_0A0C_slot_32(...)` -- first real loop-selector decoding for the common `nearby_items(...)` family/shape searches used by alarm and trigger bodies -- structured rendering now upgrades the simpler selector loops to real `for item in nearby_items(...)` output instead of raw `loopscr` comment runs -- a second common selector family now renders as readable `selector_0x42(arg0=..., arg1=..., arg2=..., origin=...)` signatures, and the simpler back-edge cases upgrade to `for ... in selector_0x42(...)` instead of raw `loopscr 0x42` comment runs -- full corpus export regenerated through `tools/export_usecode_pseudocode.py`, so the checked-in pseudocode corpus matches the improved renderer +- the map-viewer decompiler already structures a growing set of branches, loops, selectors, list operations, and switch-like dispatches, with focused JavaScript regression tests +- versioned `crusader-usecode-archive-source` v1 and per-event `crusader-usecode-source` v2 JSON snapshots preserve original archive/class/event/body bytes; the per-event overlay validates guarded fixed-width immediate edits and can produce a clearly labeled edited-IR preview, while broader edit support, editor integration, and compilation remain open +- the workspace Python parser/exporter supplies per-slot byte-backed IR, pseudocode, extracted corpus data, and comparison fixtures +- both sources provide useful evidence, but neither currently completes the edit → compile → rebuild → in-game validation loop -Still open after this batch: +Still required in the map-viewer product path: -- broader selector mini-language coverage beyond the common `nearby_items(...)` forms and the currently opaque but readable `selector_0x42(...)` fallback -- more wrapper aliasing than the currently verified `FREE.waitNTimerTicks` seed entry -- a more authoritative opcode metadata table instead of the current mixed declarative/heuristic decoder -- corpus-level clustering/index outputs feeding back into inline annotations +- improve semantic and structural decompilation based on concrete corpus failures +- formalize the lossless editable format and connect it to an editor experience +- implement compilation, relocation/offset updates, and safe archive rebuilding +- add byte-identical round-trip, edit-regression, and Remorse/Regret runtime tests ## Priority 1: Authoritative opcode metadata @@ -50,11 +48,11 @@ From Pentagram and `crusader-disasm`: ### Why it matters -The current parser already decodes enough to produce readable pseudocode, but some opcodes are still treated more heuristically than declaratively. That is fine for proof-of-concept output, but it becomes fragile once more control-flow and loop idioms are added. +The map-viewer decompiler already produces readable structured output for a growing subset, but opcode semantics and operand formats still need evidence-backed coverage. Heuristic rendering must remain distinct from the lossless representation used by the future compiler. ### Concrete change -Move the per-opcode knowledge into a single explicit table describing: +Move the map-viewer per-opcode knowledge into a single explicit table describing: - mnemonic - stack effect where known @@ -80,13 +78,13 @@ From the older disassembly corpus: ### Why it matters -Right now the parser preserves loop selector bytes faithfully, but readable pseudocode still shows comments like `loopscr value_u8=0x40` instead of the underlying search semantics. +The map-viewer already renders several common selector forms. Remaining selector forms should be added there as evidence and regression cases are established; keep unknown forms visible rather than guessing semantics. That is the main reason scripts like `ALARMHAT` still read as partially machine-shaped even though the overall behavior is already understandable. ### Concrete change -Introduce a small loop-selector IR layer so common loop forms render as something closer to: +Extend the map-viewer loop-selector IR so supported forms render as something closer to: ```text for item in nearby_items(shape=0x04D0, origin=arg_06): @@ -162,7 +160,7 @@ From Pentagram's symbol-info/debug-symbol handling: The JELYHACK pass already showed how important this is. Tiny scripts are easy to misread if post-`ret` metadata gets rendered as live code. -The current parser now avoids that in readable pseudocode, but the boundary logic should become a first-class part of the IR rather than a readability-only safeguard. +The current renderers avoid some of these misclassifications, but the map-viewer IR/compiler path must make code and trailer boundaries first-class so edits cannot accidentally treat metadata as executable bytes. ### Concrete change @@ -224,7 +222,7 @@ From the local repo workflow rather than directly from Pentagram: ### Why it matters -The parser is strongest when its readable output can be tied back to the compiled loader and sequencer. That keeps the decompiler grounded instead of drifting into pure script aesthetics. +The map-viewer decompiler is strongest when its readable output can be tied back to the compiled loader and sequencer. Keep those runtime anchors attached as evidence, without letting them replace the lossless byte representation needed for compilation. ### Concrete change @@ -245,16 +243,17 @@ Expand the export and annotation path so pseudocode/index output can carry verif ## Suggested implementation order -1. stabilize opcode metadata tables -2. formalize trailer parsing in IR -3. implement first real loop-selector decoder for common `shape` and `family` searches -4. add intrinsic metadata with confidence levels -5. add corpus clustering/index helpers -6. extend runtime-anchor export/import integration +1. Continue improving the map-viewer decoder, operand model, control-flow structuring, and trailer handling against extracted fixtures. +2. Keep each semantic or rendering improvement covered by focused and real-corpus regressions in the map-viewer test suite. +3. Define the map-viewer's versioned, lossless editable IR and source/editor experience; retain raw bytes and provenance for unsupported instructions. +4. Implement a bounded assembler, label/branch resolution, and deterministic class/FLEX archive rebuild in the same product path. +5. Prove byte-identical output for unchanged inputs, then test supported edits and reject unsafe edits clearly. +6. Run controlled Remorse and Regret game tests before declaring a supported round-trip workflow. ## What not to do yet -- Do not chase full round-tripping first. Readability is still the higher-value frontier. +- Do not treat readable pseudocode as compilable source or let the Python proof of concept become a second editor/compiler. +- Do not stop at readability: the intended outcome is an editor/decompiler/recompiler that produces working in-game USECODE. - Do not mass-promote intrinsic or event names from Pentagram or the old disasm corpus without current-binary support. - Do not try to solve every loop/selector form before landing the small repeated set that already appears across the alarm and trigger families. diff --git a/docs/usecode-tooling-comparison.md b/docs/usecode-tooling-comparison.md index dc2d4f5..2bfd6cd 100644 --- a/docs/usecode-tooling-comparison.md +++ b/docs/usecode-tooling-comparison.md @@ -2,11 +2,12 @@ ## Purpose -This note compares three different USECODE-facing tool lines now in use around the Crusader work: +This note compares four different USECODE-facing tool lines now in use around the Crusader work: 1. Pentagram's built-in Crusader usecode converter/disassembler 2. the local `crusader-disasm` corpus and helper scripts -3. the current workspace parser/decompiler in `tools/poc_crusader_usecode_parser.py` +3. the workspace research parser/decompiler in `tools/poc_crusader_usecode_parser.py` +4. the newer map-viewer decompiler in `crusader_map_viewer/map_renderer` The goal is not to rank them abstractly. The goal is to state what each one is actually good at, what assumptions it bakes in, and why the current local parser had to diverge. @@ -16,7 +17,9 @@ Pentagram is a game-engine-side disassembler/converter with generic Crusader hoo `crusader-disasm` is mostly a generated disassembly corpus plus small maintenance scripts that mine or preserve information from that corpus. -Our current parser is the first tool in this workspace that is explicitly built around the validated owner-loaded `EUSECODE.FLX` structure recovered from the retail binary and then pushed further into readable pseudocode export. +The Python parser is the research/reference pipeline built around the validated owner-loaded `EUSECODE.FLX` structure recovered from the retail binary. + +The map-viewer decompiler is the primary product-development path. Continue improving it into the actual USECODE editor, decompiler, and recompiler; do not build a parallel user-facing editor/compiler around the Python proof of concept. ## Pentagram: what it does @@ -155,7 +158,7 @@ So this is again a maintenance aid around a text corpus, not a first-principles In practice, `crusader-disasm` has been most useful as a vocabulary/evidence source, not as the final tool we run to generate the readable corpus. -## Our current parser/decompiler: what it does differently +## Workspace research parser/decompiler: what it does differently The current local tool line is centered on: @@ -260,7 +263,21 @@ So the best current workflow is still hybrid: - use Pentagram for structural/reference behavior - use `crusader-disasm` for opcode vocabulary and corpus evidence -- use the local parser for validated owner-loaded extraction, IR, pseudocode, and batch readability export +- use the local parser/extractor for validated owner-loaded data, research IR, fixtures, and independent pseudocode comparisons +- use the map-viewer decompiler as the primary implementation and future user-facing USECODE editor/compiler + +## Map-viewer decompiler: primary development target + +The newer implementation lives in `crusader_map_viewer/map_renderer`, principally in `src/lib/usecode-decompiler.js`, with renderer regressions in `scripts/test-usecode-structuring.mjs`. Its later control-flow, loop, list, selector, and switch rendering work makes it the right foundation for the user-facing editor/decompiler. + +It is not yet a recompiler. Development should continue there to: + +- improve decompilation against the extracted corpus and binary evidence +- add a stable, lossless editable source/IR representation and editor workflow +- implement a bounded assembler and deterministic class/FLEX archive rebuild +- prove unchanged byte-identical round trips and validate edited output in both games + +The Python parser and extracted artifacts remain valuable as independent evidence, fixtures, and comparison outputs. They should inform and test the map-viewer decompiler, not become a competing product path. ## Best current summary @@ -268,9 +285,11 @@ Pentagram is a converter/disassembler. `crusader-disasm` is a disassembly corpus with helper scripts. -Our script is the first repo-local tool that is explicitly trying to be a readable decompiler over the validated extracted `EUSECODE` corpus. +The Python parser is the research tool that established readable decompilation over the validated extracted `EUSECODE` corpus. -That is why the current parser looks less like a classic disassembler and more like a layered RE workbench: +The map-viewer decompiler is where the actual editor/decompiler/recompiler should be built. + +The research parser remains a layered RE workbench: - extractor-backed local format understanding - structured IR @@ -279,4 +298,4 @@ That is why the current parser looks less like a classic disassembler and more l - batch corpus export - runtime-annotation hints tied to the current Crusader notes -The tradeoff is that our current script is newer and more heuristic. It is better at producing something a human can read across the whole corpus, but it is not yet as mature or as battle-tested at raw opcode coverage as the older reference tools. \ No newline at end of file +The tradeoff is that the research parser is newer and more heuristic. It helps produce human-readable corpus output and acts as a cross-check, while the map-viewer implementation still needs the editing, compilation, and archive-writing stages required for a working in-game round trip. \ No newline at end of file diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index 7a3eadc..f6c8956 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace remorse { @@ -56,6 +57,11 @@ struct TeleporterProcessEntry { u8 extra[0x04]; } CR_PACKED; +struct ClearAvatarInStasisProcessEntry { + EntityDispatchEntryBase base; + u8 extra[0x01]; +} CR_PACKED; + struct AnimPrimitiveProcessEntry { EntityDispatchEntryBase base; u8 extra[0x29]; @@ -82,6 +88,9 @@ struct EntityDispatchEntryRuntimeState { } CR_PACKED; CR_PACK_POP +static_assert(sizeof(ClearAvatarInStasisProcessEntry) == 0x33, + "Clear-avatar-stasis process size must match allocation evidence"); + static_assert(sizeof(EntityDispatchEntryBase) == 0x32, "EntityDispatchEntryBase size must match allocation evidence"); static_assert(sizeof(StandProcessEntry) == 0x42, "StandProcessEntry size must match allocation evidence"); static_assert(sizeof(GravityProcessEntry) == 0x42, "GravityProcessEntry size must match allocation evidence"); @@ -127,6 +136,10 @@ public: ControllerProcessEntry* createControllerProcess(u8 activeGroup, u16 (&groupCounts)[32]); TeleporterProcessEntry* createTeleporterProcess(u8 activeGroup, u16 mapNumber, u16 teleportId, u16 (&groupCounts)[32]); + TeleporterProcessEntry* createTeleporterProcess(u8 activeGroup, u16 mapNumber, u16 teleportId, + u16 (&groupCounts)[32], bool doStasis, bool avatarTeleporting, bool& avatarInStasis); + bool runClearAvatarInStasisProcess(u16 processId, bool& avatarInStasis, + u16 (&groupCounts)[32]); AnimPrimitiveProcessEntry* createAnimPrimitiveProcess(u8 activeGroup, u16 itemNumber, u16 animationNumber, u8 direction, const AnimationClip& clip, u16 (&groupCounts)[32]); EntityVmContextProcessEntry* createUsecodeProcess(u8 activeGroup, u16 (&groupCounts)[32]); @@ -172,6 +185,8 @@ public: std::size_t capacity() const; private: + ClearAvatarInStasisProcessEntry* createClearAvatarInStasisProcess(u8 activeGroup, + bool& avatarInStasis, u16 (&groupCounts)[32]); void releaseOwnedProcess(u16 id); void refreshItemPresence(u16 itemNumber); void refreshItemProcessType(u16 itemNumber, u16 eventType); @@ -183,12 +198,14 @@ private: std::vector> ownedGravityProcesses_; std::vector> ownedAnimPrimitiveProcesses_; std::vector> ownedTeleporterProcesses_; + std::vector> ownedClearAvatarInStasisProcesses_; std::vector> ownedUsecodeProcesses_; std::unique_ptr systemTimerProcess_; std::unique_ptr keyboardProcess_; std::unique_ptr keyDaemonProcess_; std::unique_ptr controllerProcess_; std::vector keyboardSubscriberIds_; + std::vector> processWaits_; std::array pendingKeyEvents_{}; u8 nextKeyEventOffset_ = 0; u8 keyEventOffset_ = 0; @@ -255,6 +272,11 @@ public: u16 currentMapNumber, const std::vector& shapes); }; +class ClearAvatarInStasisProcess { +public: + static constexpr u16 vtableOffset = 0x0f5e; +}; + class KeyboardProcess { public: static bool handleKeyEvent(KeyboardProcessEntry& process, u16 selector, u16 filter, diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index ca1ecc7..0bd6737 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -132,6 +132,7 @@ public: std::optional> hatchGlobEgg(u16 eggItemNumber, const GlobObject& glob, const std::vector& shapes); bool isGlobHatched(u16 eggItemNumber) const; + bool setItemShape(u16 itemNumber, u16 shape); bool setItemFrame(u16 itemNumber, u8 frame); bool moveItem(u16 itemNumber, u16 x, u16 y, u8 z); std::optional> grabItem(u16 itemNumber, const std::vector& shapes, diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index c813b00..ea1c5c6 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -195,6 +195,44 @@ TeleporterProcessEntry* ProcessKernel::createTeleporterProcess(u8 activeGroup, u return result; } +TeleporterProcessEntry* ProcessKernel::createTeleporterProcess(u8 activeGroup, u16 mapNumber, + u16 teleportId, u16 (&groupCounts)[32], bool doStasis, bool avatarTeleporting, + bool& avatarInStasis) +{ + auto* teleporter = createTeleporterProcess(activeGroup, mapNumber, teleportId, groupCounts); + if (doStasis && !avatarTeleporting) { + auto* clearStasis = createClearAvatarInStasisProcess(activeGroup, avatarInStasis, groupCounts); + processWaits_.emplace_back(readLe16(teleporter->base, 0x02), + readLe16(clearStasis->base, 0x02)); + } + return teleporter; +} + +ClearAvatarInStasisProcessEntry* ProcessKernel::createClearAvatarInStasisProcess(u8 activeGroup, + bool& avatarInStasis, u16 (&groupCounts)[32]) +{ + if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + throw std::overflow_error("process table exhausted"); + } + if (std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) { + processes_.reserve(processes_.size() + 30); + allocationSizes_.reserve(allocationSizes_.size() + 30); + processNames_.reserve(processNames_.size() + 30); + } + ownedClearAvatarInStasisProcesses_.reserve(ownedClearAvatarInStasisProcesses_.size() + 1); + auto process = std::make_unique(); + EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts); + writeLe16(process->base, 0x00, ClearAvatarInStasisProcess::vtableOffset); + process->extra[0] = avatarInStasis ? 1 : 0; + avatarInStasis = true; + setLastAllocationSize(sizeof(ClearAvatarInStasisProcessEntry)); + const u16 id = addProcess(process->base); + processNames_[id] = "ClearAvatarInStasis"; + ClearAvatarInStasisProcessEntry* result = process.get(); + ownedClearAvatarInStasisProcesses_.push_back(std::move(process)); + return result; +} + bool TeleporterProcess::run(const TeleporterProcessEntry& process, LiveFixedMapItems& items, u16 currentMapNumber, const std::vector& shapes) { @@ -211,6 +249,27 @@ bool TeleporterProcess::run(const TeleporterProcessEntry& process, LiveFixedMapI return destination && items.teleportAvatar(*destination, static_cast(targetMap)); } +bool ProcessKernel::runClearAvatarInStasisProcess(u16 processId, bool& avatarInStasis, + u16 (&groupCounts)[32]) +{ + EntityDispatchEntryBase* entry = processAt(processId); + const auto ownedProcess = std::find_if(ownedClearAvatarInStasisProcesses_.begin(), + ownedClearAvatarInStasisProcesses_.end(), [entry](const auto& process) { + return &process->base == entry; + }); + if (entry == nullptr || readLe16(*entry, 0x00) != ClearAvatarInStasisProcess::vtableOffset || + ownedProcess == ownedClearAvatarInStasisProcesses_.end()) { + return false; + } + const auto* process = reinterpret_cast(entry); + if (process->extra[0] == 0) { + avatarInStasis = false; + } + entry->bytes[0x18] |= 0x04; + terminateProcess(processId, groupCounts); + return true; +} + EntityVmContextProcessEntry* ProcessKernel::createUsecodeProcess(u8 activeGroup, u16 (&groupCounts)[32]) { @@ -690,6 +749,9 @@ void ProcessKernel::clearProcessSlot(u16 id) if (id >= processes_.size()) { throw std::out_of_range("process ID outside table"); } + processWaits_.erase(std::remove_if(processWaits_.begin(), processWaits_.end(), [id](const auto& wait) { + return wait.first == id || wait.second == id; + }), processWaits_.end()); processes_[id] = nullptr; allocationSizes_[id] = 0; processNames_[id] = nullptr; @@ -723,6 +785,13 @@ void ProcessKernel::releaseOwnedProcess(u16 id) ownedTeleporterProcesses_.erase(teleporter); return; } + const auto clearAvatarInStasis = std::find_if(ownedClearAvatarInStasisProcesses_.begin(), + ownedClearAvatarInStasisProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); + if (clearAvatarInStasis != ownedClearAvatarInStasisProcesses_.end()) { + ownedClearAvatarInStasisProcesses_.erase(clearAvatarInStasis); + return; + } const auto usecode = std::find_if(ownedUsecodeProcesses_.begin(), ownedUsecodeProcesses_.end(), [entry](const auto& process) { return &process->base == entry; }); if (usecode != ownedUsecodeProcesses_.end()) { @@ -771,6 +840,9 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) const bool ownedTeleporterProcess = std::any_of(ownedTeleporterProcesses_.begin(), ownedTeleporterProcesses_.end(), [entry](const auto& process) { return &process->base == entry; }); + const bool ownedClearAvatarInStasisProcess = std::any_of(ownedClearAvatarInStasisProcesses_.begin(), + ownedClearAvatarInStasisProcesses_.end(), + [entry](const auto& process) { return &process->base == entry; }); if (itemNumber != 0 && (stand == ownedStandProcesses_.end() && !ownedItemProcess && !ownedGravityProcess && !ownedAnimationProcess && !ownedUsecodeProcess || id < 3 || readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 || @@ -778,7 +850,7 @@ void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32]) throw std::logic_error("item process child cleanup is not ported"); } if (stand == ownedStandProcesses_.end() && !ownedGravityProcess && !ownedAnimationProcess && - !ownedUsecodeProcess && !ownedTeleporterProcess && + !ownedUsecodeProcess && !ownedTeleporterProcess && !ownedClearAvatarInStasisProcess && std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(), [entry](const auto& process) { return process.get() == entry; })) { throw std::logic_error("external process ownership is not ported"); @@ -923,7 +995,21 @@ void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDisp try { for (std::size_t id = 0; id < processes_.size(); ++id) { EntityDispatchEntryBase* entry = processes_[id]; - if (entry != nullptr && (readLe16(*entry, 0x16) & 0x08) == 0) { + bool waitingForProcess = false; + if (entry != nullptr) { + const u16 processId = readLe16(*entry, 0x02); + const auto wait = std::find_if(processWaits_.begin(), processWaits_.end(), + [processId](const auto& candidate) { return candidate.first == processId; }); + if (wait != processWaits_.end()) { + const EntityDispatchEntryBase* target = processAt(wait->second); + waitingForProcess = target != nullptr && + (readLe16(*target, 0x16) & 0x08) == 0; + if (!waitingForProcess) { + processWaits_.erase(wait); + } + } + } + if (entry != nullptr && !waitingForProcess && (readLe16(*entry, 0x16) & 0x08) == 0) { if ((readLe16(*entry, 0x18) & 0x1000) != 0) { const u32 sleepStart = readLe16(*entry, 0x0a) | (static_cast(readLe16(*entry, 0x0c)) << 16); const u32 sleepLength = readLe16(*entry, 0x0e) | (static_cast(readLe16(*entry, 0x10)) << 16); diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index e419081..539458e 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -854,6 +854,18 @@ bool LiveFixedMapItems::isGlobHatched(u16 eggItemNumber) const return eggItemNumber < hatchedGlobIds_.size() && hatchedGlobIds_[eggItemNumber]; } +bool LiveFixedMapItems::setItemShape(u16 itemNumber, u16 shape) +{ + const auto item = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& candidate) { + return candidate.itemNumber == itemNumber; + }); + if (item == items_.end()) { + return false; + } + item->data.shape = shape; + return true; +} + bool LiveFixedMapItems::setItemFrame(u16 itemNumber, u8 frame) { const auto item = std::find_if(items_.begin(), items_.end(), [itemNumber](const auto& candidate) { diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index 10f9be6..b19a0ea 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -299,8 +299,16 @@ 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 == 0x24 && argumentBytes == 6) { + const remorse::u16 shape = static_cast(arguments[4] | + (static_cast(arguments[5]) << 8)); + if (!app.liveItems || !app.liveItems->setItemShape(*itemNumber, shape)) { + return std::nullopt; + } + app.usecodeWorldMutationPending = true; + return remorse::u16{0}; + } if (ordinal == 0x59 && argumentBytes == 6) { - std::lock_guard lock(app.sceneMutex); const remorse::u8 frame = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); if (!app.liveItems || !app.liveItems->setItemFrame(*itemNumber, frame)) { @@ -526,15 +534,51 @@ void loadSceneAsync(HWND window, AppState& state) for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { teleporterKernel.createProcess(1, teleporterGroupCounts); } + bool avatarInStasis = false; auto* teleporter = teleporterKernel.createTeleporterProcess(1, - static_cast(state.mapIndex), 0x1e, teleporterGroupCounts); + static_cast(state.mapIndex), 0x1e, teleporterGroupCounts, + true, false, avatarInStasis); const remorse::u16 processId = static_cast(teleporter->base.bytes[2] | (static_cast(teleporter->base.bytes[3]) << 8)); - const bool teleported = remorse::TeleporterProcess::run(*teleporter, liveItems, - static_cast(state.mapIndex), *shapeTypes); - teleporter->base.bytes[0x18] |= 4; - teleporterKernel.terminateProcess(processId, teleporterGroupCounts); - if (!teleported) { + struct StartupContext { + remorse::ProcessKernel& kernel; + remorse::LiveFixedMapItems& items; + const std::vector& shapes; + remorse::u16 (&groupCounts)[32]; + bool& avatarInStasis; + remorse::u16 mapNumber; + bool teleported = false; + bool valid = true; + } startup{teleporterKernel, liveItems, *shapeTypes, teleporterGroupCounts, + avatarInStasis, static_cast(state.mapIndex)}; + const auto runStartupProcess = [](remorse::EntityDispatchEntryBase& entry, + void* opaque) { + auto& context = *static_cast(opaque); + const remorse::u16 processId = static_cast(entry.bytes[2] | + (static_cast(entry.bytes[3]) << 8)); + if (processId < 3) return; + const remorse::u16 vtable = static_cast(entry.bytes[0] | + (static_cast(entry.bytes[1]) << 8)); + if (vtable == remorse::ClearAvatarInStasisProcess::vtableOffset) { + context.valid = context.kernel.runClearAvatarInStasisProcess(processId, + context.avatarInStasis, context.groupCounts); + } else if (vtable == remorse::TeleporterProcess::vtableOffset) { + const auto& teleporterProcess = + *reinterpret_cast(&entry); + context.teleported = remorse::TeleporterProcess::run(teleporterProcess, + context.items, context.mapNumber, context.shapes); + entry.bytes[0x18] |= 4; + context.kernel.terminateProcess(processId, context.groupCounts); + } else { + context.valid = false; + } + }; + for (unsigned pass = 0; pass < 2 && teleporterKernel.processAt(processId) != nullptr; + ++pass) { + teleporterKernel.scanRunnableProcesses(1, runStartupProcess, &startup); + } + if (!startup.valid || !startup.teleported || avatarInStasis || + teleporterKernel.processAt(processId) != nullptr) { setLoadFailure(state, L"The teleporter process could not resolve its map and egg destination."); PostMessageW(window, sceneReadyMessage, 0, 0); return; @@ -968,6 +1012,7 @@ void updatePlayer(HWND window, AppState& state) runUsecodeTasks(state); const auto movement = state.controllerMovement.request(); state.diagnosticKernel.deliverSystemTimerEvent(); + bool gravityMoved = false; if (state.diagnostics) { const bool wasSleeping = (state.diagnosticStand->base.bytes[0x19] & 0x10) != 0; const remorse::u32 previousSleepStart = standSleepStart(*state.diagnosticStand); @@ -1016,8 +1061,13 @@ void updatePlayer(HWND window, AppState& state) if (wasSleeping && standSleepStart(*state.diagnosticStand) != previousSleepStart) { ++state.standWakeCount; } + } else if (state.liveItems) { + gravityMoved = state.diagnosticKernel.scanResolvedGravity( + state.diagnosticKernel.activeGroup(), *state.liveItems, state.shapeTypes, + remorse::calculateFastAreaRange(avatarWorld(state)), 1, + state.diagnosticKernel.systemTimerTick(), state.diagnosticGroupCounts) != 0; } - changed = changed || state.diagnostics; + changed = changed || state.diagnostics || gravityMoved; if (movement.animation == 0) { if (state.animationProcessId != 0) { auto* process = state.diagnosticKernel.processAt(state.animationProcessId); @@ -1028,6 +1078,13 @@ void updatePlayer(HWND window, AppState& state) changed = changed || state.playerAnimation != 0 || state.playerFrame != 0; state.playerAnimation = 0; state.playerFrame = 0; + const bool usecodeMutation = state.usecodeWorldMutationPending; + state.usecodeWorldMutationPending = false; + changed = changed || usecodeMutation; + if (state.renderThread.joinable() && (gravityMoved || usecodeMutation)) { + state.renderRequested = true; + state.renderWake.notify_one(); + } continue; } @@ -1078,7 +1135,7 @@ void updatePlayer(HWND window, AppState& state) *state.liveItems, *state.renderer, remorse::calculateFastAreaRange(avatarWorld(state))); const bool usecodeMutation = state.usecodeWorldMutationPending; state.usecodeWorldMutationPending = false; - if (state.renderThread.joinable() && (moved || hatched || usecodeMutation)) { + if (state.renderThread.joinable() && (moved || hatched || usecodeMutation || gravityMoved)) { state.renderRequested = true; state.renderWake.notify_one(); } diff --git a/rebuild/remorse/tests/fixed_map_tests.cpp b/rebuild/remorse/tests/fixed_map_tests.cpp index f4b84a2..b91f2bf 100644 --- a/rebuild/remorse/tests/fixed_map_tests.cpp +++ b/rebuild/remorse/tests/fixed_map_tests.cpp @@ -180,6 +180,11 @@ int main() liveKernel.createProcess(1, liveGroups); } assert(!liveItems.findItem(0x106) && !liveItems.moveItem(0x106, 0, 0, 0)); + const auto originalShape = liveItems.findItem(0x100)->data.shape; + assert(liveItems.setItemShape(0x100, 0x1234)); + assert(liveItems.findItem(0x100)->data.shape == 0x1234 && blockItems[0].data.shape == originalShape); + assert(!liveItems.setItemShape(0x106, 0)); + assert(liveItems.setItemShape(0x100, originalShape)); assert(!liveItems.moveItem(0x100, 0x8000, 0, 0)); assert(liveItems.moveItem(0x100, 768, 511, 81)); assert(liveItems.findItem(0x100)->data.x == 768 && blockItems[0].data.x == 511); diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index 64a41ff..40b4316 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -250,14 +250,48 @@ int main() for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { teleporterKernel.createProcess(1, teleporterGroups); } - auto* teleporterProcess = teleporterKernel.createTeleporterProcess(1, 1, 0x1e, teleporterGroups); + bool avatarInStasis = false; + auto* teleporterProcess = teleporterKernel.createTeleporterProcess(1, 1, 0x1e, + teleporterGroups, true, false, avatarInStasis); const remorse::u16 teleporterProcessId = static_cast( teleporterProcess->base.bytes[2] | (static_cast(teleporterProcess->base.bytes[3]) << 8)); + assert(avatarInStasis && teleporterKernel.allocationSizeAt(4) == 0x33 && + teleporterKernel.processAt(4)->bytes[0] == 0x5e && + teleporterKernel.processAt(4)->bytes[1] == 0x0f); assert(!remorse::TeleporterProcess::run(*teleporterProcess, spawnSearchWorld, 2, *typeFlags)); assert(spawnSearchWorld.findItem(1)->data.x == 0 && spawnSearchWorld.findItem(1)->data.y == 0); - assert(remorse::TeleporterProcess::run(*teleporterProcess, spawnSearchWorld, 1, *typeFlags)); - teleporterProcess->base.bytes[0x18] |= 4; - teleporterKernel.terminateProcess(teleporterProcessId, teleporterGroups); + struct TeleporterPassContext { + remorse::ProcessKernel& kernel; + remorse::LiveFixedMapItems& items; + const std::vector& shapes; + remorse::u16 (&groupCounts)[32]; + bool& avatarInStasis; + bool teleported = false; + } teleporterPass{teleporterKernel, spawnSearchWorld, *typeFlags, teleporterGroups, avatarInStasis}; + const auto runTeleporterPass = [](remorse::EntityDispatchEntryBase& entry, void* opaque) { + auto& context = *static_cast(opaque); + const remorse::u16 processId = static_cast(entry.bytes[2] | + (static_cast(entry.bytes[3]) << 8)); + if (processId < 3) return; + const remorse::u16 vtable = static_cast(entry.bytes[0] | + (static_cast(entry.bytes[1]) << 8)); + if (vtable == remorse::ClearAvatarInStasisProcess::vtableOffset) { + assert(context.kernel.runClearAvatarInStasisProcess(processId, + context.avatarInStasis, context.groupCounts)); + } else if (vtable == remorse::TeleporterProcess::vtableOffset) { + const auto& process = *reinterpret_cast(&entry); + context.teleported = remorse::TeleporterProcess::run(process, context.items, 1, + context.shapes); + entry.bytes[0x18] |= 4; + context.kernel.terminateProcess(processId, context.groupCounts); + } + }; + teleporterKernel.scanRunnableProcesses(1, runTeleporterPass, &teleporterPass); + assert(!avatarInStasis && !teleporterPass.teleported && + teleporterKernel.processAt(teleporterProcessId) == &teleporterProcess->base && + spawnSearchWorld.findItem(1)->data.x == 0 && spawnSearchWorld.findItem(1)->data.y == 0); + teleporterKernel.scanRunnableProcesses(1, runTeleporterPass, &teleporterPass); + assert(teleporterPass.teleported); assert(teleporterKernel.processAt(teleporterProcessId) == nullptr && teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 3); assert(spawnEgg->recordIndex < fixedMap->entries.size()); From e00f9f3186220c6b93db7f497e5ce3f6b376b7a5 Mon Sep 17 00:00:00 2001 From: Maddo Date: Tue, 6 Oct 2026 21:07:35 +0200 Subject: [PATCH 12/14] Enhance teleporter and map rendering tests - Added initialization of startup processes in flex_archive_tests to ensure proper setup before teleporter operations. - Updated assertions to verify the correct allocation and state of processes during teleporter execution. - Introduced new tests in map_renderer_tests to validate shape rendering, including isolated shape rendering and player sprite integration. - Enhanced map_sorter_tests with additional checks for occlusion handling and boundary conditions in render order resolution. --- .../hypothetical-player-concussion-grenade.md | 124 +++++ docs/remorse-windows-rebuild-roadmap.md | 38 +- docs/usecode-jelyhack-analysis.md | 246 ++------- docs/usecode-unreferenced-candidates.md | 105 ++++ .../include/remorse/detail/map_sorter.h | 1 - .../include/remorse/entity_dispatch_entry.h | 4 + rebuild/remorse/include/remorse/fixed_map.h | 3 + .../remorse/include/remorse/map_renderer.h | 12 +- rebuild/remorse/src/entity_dispatch_entry.cpp | 42 ++ rebuild/remorse/src/fixed_map.cpp | 22 + rebuild/remorse/src/map_renderer.cpp | 34 +- rebuild/remorse/src/map_sorter.cpp | 86 +++- rebuild/remorse/src/windowed_game_main.cpp | 470 +++++++++++------- rebuild/remorse/tests/flex_archive_tests.cpp | 66 ++- rebuild/remorse/tests/map_renderer_tests.cpp | 77 +++ rebuild/remorse/tests/map_sorter_tests.cpp | 22 + 16 files changed, 954 insertions(+), 398 deletions(-) create mode 100644 docs/hypothetical-player-concussion-grenade.md create mode 100644 docs/usecode-unreferenced-candidates.md diff --git a/docs/hypothetical-player-concussion-grenade.md b/docs/hypothetical-player-concussion-grenade.md new file mode 100644 index 0000000..c7b8d90 --- /dev/null +++ b/docs/hypothetical-player-concussion-grenade.md @@ -0,0 +1,124 @@ +# Hypothetical Player-Usable Grenade Family + +**Status:** Design sketch, not recovered retail code and not ready to compile +**Targets:** No Remorse shapes `0x034E` (`CONCUSSION GRENADE`), `0x034F` (`NERVE GAS GRENADE`), and `0x0350` (`EMP GRENADE`) +**Design basis:** The surviving Remorse `GRENADE` class (`0x0343`), not `BLASTPAC` or `FUSPAC` + +## Goal + +Give all three removed grenade shapes separate player `use` paths while keeping the surviving old `GRENADE` behavior intact. Give each shape its own class record selected by the runtime shape selector, based on the surviving `GRENADE` callbacks, and add event-slot `0x01` handlers. Do not change the existing `0x0343` class until the new paths have been tested. + +This separates three things that otherwise look deceptively similar: + +- The retail name table preserves all three labels: `CONCUSSION GRENADE`, `NERVE GAS GRENADE`, and `EMP GRENADE`. +- Current map metadata marks all three as terrain and `invitem: false`; the labels do not make them ordinary inventory objects. +- The local Remorse USECODE indexes have a `GRENADE` class for `0x0343`, but no separate class/body for these three shapes. + +## Verified Base Behavior + +The extracted Remorse `GRENADE` class is class id `0x0343` (entry `184`). It has two non-empty common event bodies and no `use` body: + +```c +function grenade_hit() +{ + set_info(0x020B, *(arg_06)); + process_exclude(); + return; +} + +function grenade_gotHit() +{ + set_info(0x020C, *(arg_06)); + process_exclude(); + return; +} +``` + +These bodies assign process-info values and exclude their current process. Preserve them byte-for-byte in the first copied-class experiment. Their downstream meaning is not fully established here; do not treat `0x020B` or `0x020C` as explosion-type constants. + +The vending-machine evidence is creation, not player-use behavior. `PEPSINS::use` and `PEPSIEW::use` each have a random branch that attempts `Item.legalCreateAtPoint(..., 0x0343, item)`; the scripts do not add a `GRENADE::use` event. The supplied enemy-use observation is consistent with a non-player producer, but the specific enemy creation path still needs an independently traced callsite before being treated as closed evidence. + +References: [removed-item investigation](./removed_items.md), [GRENADE hit body](../USECODE/EUSECODE_extracted/pseudocode/GRENADE/slot_05_hit.txt), [GRENADE gotHit body](../USECODE/EUSECODE_extracted/pseudocode/GRENADE/slot_06_gotHit.txt), [PEPSINS use body](../USECODE/EUSECODE_extracted/pseudocode/PEPSINS/slot_01_use.txt), and [PEPSIEW use body](../USECODE/EUSECODE_extracted/pseudocode/PEPSIEW/slot_01_use.txt). + +## Proposed Class/Event Shape + +Use the executable's regular-shape class selector to determine each shape's class id; do not assume an archive class id solely from the shape number. Each new class record should contain: + +| Event slot | Proposed content | +|---:|---| +| `0x01` (`use`) | Variant-specific player-use wrapper described below. | +| `0x05` (`hit`) | Copy the current `GRENADE::hit` body unchanged for the initial test. | +| `0x06` (`gotHit`) | Copy the current `GRENADE::gotHit` body unchanged for the initial test. | + +Create independent rows for `0x034E`, `0x034F`, and `0x0350`; do not point all three selectors at one mutable class record. All other rows can remain absent unless testing shows a native caller requires them. Each class/event row is six bytes: retain its unknown leading word and write a valid code offset for each new body. The archive's class object index is derived from the class id; rebuild the class/event offsets and FLEX directory consistently. + +`Item_Use` requests event `0x01`. The native dispatcher first resolves the item's class selector, then checks the owner-row event capability bits before creating an event process. A body without the corresponding `use` capability will not run. The current [format specification](./usecode-format-specification.md) describes this dispatch model. + +## Specific Player-Use Handlers + +These are source-level usecode sketches, not recovered or compilable retail bodies. Each is a distinct slot-`0x01` event. They call a proposed `GrenadeFx.playerUse` native helper because the local corpus does not establish a complete script-level throw, fuse, area-target, and actor-status API. The helper and its ordinal do not exist yet; do not encode these calls as intrinsic `0x0017`. + +```c +function concussion_grenade_use() +{ + GrenadeFx.playerUse(this, GRENADE_KIND_CONCUSSION); + return; +} + +function nerve_grenade_use() +{ + GrenadeFx.playerUse(this, GRENADE_KIND_NERVE); + return; +} + +function emp_grenade_use() +{ + GrenadeFx.playerUse(this, GRENADE_KIND_EMP); + return; +} +``` + +`GRENADE_KIND_*` are proposed dispatch tags, not the `exptype` argument to `Item::I_explode`. Keep the kind-to-effect mapping out of the explosion-type field: the converter calls `Item::I_explode(Item *, exptype, destroy_item)` a hint, and the compatibility implementation uses that field for ordinary explosion presentation/damage scaling, not nerve or EMP semantics. + +### Shared Launch Contract + +The proposed `GrenadeFx.playerUse(item, kind)` must: + +1. Resolve the controlled actor from the native `Item_Use` event context and confirm this exact item is in that actor's inventory. +2. Compute a facing/aim-based landing point and reject an illegal launch without consuming the item. +3. Remove only this item from inventory, create one world projectile, and attach the existing-style fuse/impact lifecycle. Never call `Item::I_explode` on the inventory-resident item: the explosion must use the projectile's world position. +4. On impact or fuse expiry, dispatch exactly one variant effect below, then destroy the projectile. Failed launch leaves the inventory item untouched. + +The launch/fuse routine is shared behavior; the target filters and detonation effects remain variant-specific. Usecode alone may be able to orchestrate part of this, but no verified Remorse implementation for the complete contract has been identified. + +### Variant Effects + +| Shape | First-playtest behavior | Target policy | +|---|---|---| +| `0x034E` Concussion | Standard grenade blast damage, retaining the engine's ordinary hit reaction rather than adding a custom status. Use the normal Crusader explosion path (`Item::explode(projectile, 0, true)` in the compatibility implementation). | Ordinary blast radius; affects any damageable actor in range, including the player. | +| `0x034F` Nerve gas | On impact, create a gas cloud for 6 seconds, pulsing once per second. Each pulse deals 2 damage and interrupts eligible actors. These are starting balance values, not recovered values. | Hostile human actors only. Exclude androids, the player, allies, and neutral humans. | +| `0x0350` EMP | On impact, emit one pulse: 20 damage plus an 8-second inhibitor-like lock that interrupts attacks and prevents movement/attacks. These are starting balance values, not recovered values. | Hostile android actors only. Organic actors receive no EMP damage or lock. | + +Nerve and EMP need target enumeration, hostility/species classification, and timed status effects. Implement those operations in a new native helper/process or prove an existing retail process can do them before assigning USECODE opcodes. Do not emulate a timed lock by setting an actor's activity once; that does not establish a persistent stun or a reliable recovery timer. + +There is a useful but limited compatibility-runtime clue for EMP: ScummVM's Crusader `Actor::receiveHitCru` has a special interruption branch for hit types `0x0F` and `7`; it includes shape `899` (commented as Android), `0x338`, `0x385`, and `0x4E6`, and can pause an attack process for a randomized 8-17 seconds. This supports testing an Android interruption effect, but it does **not** prove those values are the original retail inhibitor mechanic or cover every Android variant. Prefer a deterministic, explicitly reversible EMP lock for the first custom implementation, then compare its behavior with the original inhibitor if that executable path is recovered. + +The standard `Item::explode` compatibility path applies ordinary splash damage through FireType `4`; it has no Nerve-vs-EMP target filter. Thus only the concussion variant should use it unchanged. Reusing it for Nerve or EMP would also damage non-targets and would not create the requested status effects. + +## Work Required To Make It Usable In-Game + +1. **Enable normal inventory treatment.** Update the actual item/shape definitions so `0x034E`, `0x034F`, and `0x0350` are carryable inventory bombs, not just terrain-shaped map objects. Check each inventory family, icon/frame, weight/stack behavior, and pickup flags. Update map metadata separately if the viewer should present them as inventory-capable. +2. **Add three class records.** Resolve the runtime-selected class id for each shape and create an independent record for each, preserving the existing `0x0343` `GRENADE` record. Copy the known `hit` and `gotHit` rows as the first compatibility baseline. +3. **Add event `0x01` to each class.** Write the three variant-specific wrapper bodies, fix each class-local code offset/body bound, and ensure every loaded owner row advertises the `use` capability bit. Preserve each unknown event-row word unless its meaning is established. +4. **Implement the shared native launch helper.** Add and register `GrenadeFx.playerUse(item, kind)` or prove an existing helper has the required contract. Verify event actor context, inventory transfer, legal launch, projectile ownership, fuse timing, single consumption, and cancellation behavior. Assign an intrinsic ordinal only after checking the target build's table and ABI. +5. **Implement and tune the three effects.** Keep concussion on the normal blast path. Add human-hostile filtering and timed gas damage for Nerve, and android-hostile filtering plus a reversible inhibitor-like lock for EMP. Validate the actor taxonomy against the complete target executable; the trial damage values/durations above are gameplay knobs. +6. **Expose each item to the player.** Add all three through a legitimate inventory/loadout/map source and test ordinary pickup. Forced pickup alone does not test the `invitem`/inventory configuration. +7. **Rebuild and validate a disposable game copy.** Check pickup, inventory rendering/name, one-use behavior, each target filter, player/friendly/neutral exclusions, damage/status expiry, collision callbacks, blocked launch, save/load, and that legacy vending/enemy uses of `0x0343` remain unchanged. + +The repository's current USECODE tooling does not yet provide a complete compiler and archive writer. The source-level handler and class-record sketches cannot be installed by editing pseudocode alone; implementing the new native helper also requires rebuilding the native executable. A lossless USECODE assembler/rebuilder and a carefully validated executable patch workflow are required. See the [round-trip roadmap](./usecode-roundtrip-ir.md). + +## Confidence Summary + +- **Verified:** `GRENADE` is class `0x0343`; only `hit` and `gotHit` have bodies; both set process info and exclude the process; Pepsi vending scripts create shape `0x0343` on a branch; the retail name table preserves the three removed grenade names; current map metadata marks all three as non-inventory terrain. +- **Supported design choice, not proven:** separate class records with copied `hit`/`gotHit` and new `use` events are the least invasive way to preserve the old `0x0343` behavior while adding three player items. +- **Hypothetical:** the `GrenadeFx.playerUse` API, launch/fuse path, Nerve target filter and gas status, EMP Android classifier and inhibitor-like lock, and all first-playtest balance values. Normal `Item::I_explode` is a candidate only for the concussion variant; verify its exact behavior against the target retail build before installing. diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 998383f..0a78ad3 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -17,17 +17,31 @@ The exported files are evidence, not directly compilable game source. Keep them - Do not claim whole-game recompilation until startup, game ticks, interactions, mission flow, save/load, and presentation are driven by ported game code and playable on modern Windows using the original data. ## Source-Backed In-Game Vertical Slice -The immediate target is a fresh game on retail map 1 at the original starting teleporter, with an avatar owned by the ported item/NPC runtime, a tick and input path that actually drive that avatar, a changing world image, and at least one original-script-backed interaction. The current host item/process movement and live-item rendering are useful verified steps, but do **not** count as the original loop or interaction. Keep the diagnostic traversal view separate while replacing its behavior; no DOSBox parity gate is required for this Windows milestone. +The immediate target is a fresh game on retail map 1 that follows the original start sequence from the staging teleporter to the level-start pad, with an avatar owned by the ported item/NPC runtime, a tick and input path that actually drive that avatar, a changing world image, and at least one original-script-backed interaction. The current host item/process movement and live-item rendering are useful verified steps, but do **not** count as the original loop or interaction. Keep the diagnostic traversal view separate while replacing its behavior; no DOSBox parity gate is required for this Windows milestone. -1. **Startup and spawn:** port the fresh-game branch of `Game_Start` (`1020:0000`) through `Teleporter_CreateProcessDirect(1, 0x1e, 1)` and its placement callee. Resolve egg `0x1e` from original map data, not from the map bounds, and prove its coordinates and the spawned avatar/item ID in a retail-data test. Do not implement intro movies, main menu, save loading, or warp overrides for this slice. +1. **Startup and spawn:** port the fresh-game branch of `Game_Start` (`1020:0000`) through `Teleporter_CreateProcessDirect(1, 0x1e, 1)` and its placement callee. Resolve egg `0x1e` from original map data, then follow the nearby active `0x63` teleporter to destination egg item 6812 at `(30328, 29656, 16)`. The host path and retail test now verify item 1 reaches that pad; the original `Game_Start` call chain remains unported. Do not implement intro movies, main menu, save loading, or warp overrides for this slice. 2. **Live world ownership:** initialize the original item cache and NPC/avatar state for that map. The displayed avatar must be the same numbered, mutable item advanced by the process runtime; reject a separately drawn or separately positioned stand-in. 3. **Tick and input:** port the minimal recovered cycle/scheduler and keyboard queue/control chain that moves that avatar. Route Win32 key/timer events through the host boundary into those routines; test deterministic state changes with recorded inputs, including idle and blocked movement. 4. **Gameplay presentation:** render the live item/sprite state in source draw order each tick and follow the recovered camera state. Verify that movement, facing, and at least one changed world item appear on screen, without relying on a single prepainted fixed-map image. 5. **Real interaction:** implement one reachable map-1 usecode event through the original item find/grab, VM dispatch, and resulting world-state mutation. Demonstrate a repeatable before/input/after trace and visible effect; a script lookup or release-request counter is not an interaction. -6. **Acceptance:** launch the normal Windows executable with retail data, start map 1 at egg `0x1e`, move and interact without a diagnostic shortcut, and verify on-screen state plus a deterministic integration test. Keep absent combat, audio, menus, persistence, and broader missions listed as limitations, not silently simulated features. +6. **Acceptance:** launch the normal Windows executable with retail data, follow map 1's fresh-start sequence from egg `0x1e` through the active `0x63` trigger to the level-start pad, then move and interact without a diagnostic shortcut. Verify on-screen state plus a deterministic integration test. Keep absent combat, audio, menus, persistence, and broader missions listed as limitations, not silently simulated features. + +### Progress Update (2026-10-06) + +The normal map-1 host startup now follows the two-hop placement: start egg item 1597 (`0x1e`) reaches active trigger item 1598 (shape `0x0194`, frame 0, ID `0x63`), which places item 1 at destination egg item 6812 (`30328, 29656, 16`). The retail regression verifies the trigger, destination, avatar coordinates, and preservation of the timer, keyboard, and controller processes. The renderer centers on the destination, and the player sprite now uses the same frame-anchor convention as map objects. The MSVC gate passed all 15 CTests and the retail harness; the user confirms the avatar now appears at the correct location. + +This remains a host-modeled startup, not execution through `Game_Start`, `Teleporter_CreateProcessDirect`, or the original scheduler. A destination-area eligible-use scan, reachable original-script mutation, and original loop/render parity remain open. + +### Historical Staging-Point Snapshot + +The following blocker details were recorded before the second hop was implemented. In particular, the no-eligible-use result and candidate distances refer to the old staging coordinate near `(6399, 6399, 0)`; they do not establish which interactions are reachable from the current destination `(30328, 29656, 16)`. Current blocker: the normal host window resolves egg `0x1e` from map 1 and places host item 1 at that retail record, then routes queued input through host controller and animation processes that mutate the same live item. Startup now models the constructor's clear-stasis waiter and schedules the same-map teleporter over two kernel scans, but these remain host models, not calls through `Game_Start`, `Teleporter_CreateProcessDirect`, or the original scheduler. The ordinary host tick now also scans ready `Gravity` processes through the live-item collision sweep and requests a redraw when a falling item moves, including while the avatar is idle; this is not original scheduler parity. Idle ticks also consume pending usecode frame mutations and wake the renderer, rather than waiting for another movement input. The production-equivalent item search at the egg spawn still finds one candidate and no eligible `use` event. A retail scan finds 218 map-1 use-eligible items; the nearest is `PANELNS` item 288 at `(2919, 1061, 48)`, frame 0, quality 6, map-array 134, at horizontal Manhattan distance 8,818 staged-coordinate units from spawn `(6399, 6399, 0)`. Its recovered handler exits on frame 0 and nonzero map-array. A nearby `CARD_NS` at staged `(2783, 1055, 40)` has frame 0 and `QLo=6`; its `SWITCH::ordinal21` path needs keycard 6 to authorize the visible frame-4 state, and the fresh-game host keycard set is empty. The nearest chest candidate is `CHEST_EW` map-source record 151 at staged `(1087, 2559, 0)`, frame 0, `QLo=5`, 9,152 horizontal units from spawn. Its handler calls `FREE.slot_2d` to test a same-family legal swap to shape `0x054b`, then animates frames 0 through 4 and dispatches `TRIGGER` if the swap succeeds. The host currently lacks that shape-swap service, and no collision route from spawn to this chest has been verified. The nearest frame-0 `BOX_NS` is 18,048 staged-coordinate units away. The BOX_NS effect test remains fixture-origin coverage; no reachable retail interaction or original item/event dispatch is established. +### Current Blocker + +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. + ## Current Inputs - `exports/src_remorse/export_manifest.json` reports `CRUSADER.EXE`, 2,984 exported function files, 9 fallback function files, 57 global buckets, and 15,403 global definitions. @@ -227,9 +241,9 @@ 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 an optional fixed-map index from 0 through 255. +`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. -The default window now opens directly onto the retail-map traversal test with no diagnostic HUD, synthetic Stand/keyboard processes, or `F` release shortcut. 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. +The default window now opens directly onto the retail-map traversal test with no diagnostic HUD, synthetic Stand/keyboard processes, or `F` release shortcut. Its map-1 host startup follows the staging egg `0x1e` through active trigger `0x63` to destination egg item 6812 at `(30328, 29656, 16)` before rendering. Pass `--diagnostics` (before or after the map number) to restore the diagnostic harness and its HUD. The map-1 startup midpoint is checked against the same collision bodies as the window, with at least one legal neighboring move. This is a **retail-data movement test**, not yet the real game: the player is host-created, rendering uses a static map preview, movement uses host polling/step policy, and neither the original startup/game loop nor item USECODE/mission interactions are running. Do not use this mode split as the roadmap's playable-game exit criterion. From the repository root: @@ -238,6 +252,14 @@ rebuild\remorse\build_msvc.cmd Debug .\rebuild\remorse\out\build-nmake\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 +``` + +The window title reports the resolved map and direct coordinates. Coordinates must be X/Y `0..32767` and Z `0..255`. + The application builds the selected retail map scene and player assets on a worker thread, then displays a resizable Win32 window with the game palette and dependency-sorted map art. Shape 1 uses `ANIM.DAT` actions 0 (stand), 1 (walk), and 3 (unarmed run); frame metadata selects the `SHAPES.FLX` pose, horizontal flip, and movement delta. The original keypad direction mapping is supported alongside WASD/arrows and diagonal combinations. Shift and Caps Lock select walk/run using the controller's same-state rule. A 40 Hz host simulation tick advances frame steps against fixed-map and expanded-glob solid volumes; it now catches up after long paints instead of discarding all elapsed time beyond 50 ms. The retail signed displacement decoder is unchanged. The prototype's forward-only host movement step skips the small backward stride on walk frames 4 and 12 of directions 6/7/10/11, which had made both actor and following camera reverse mid-stride. This comfort policy and host tick rate are not recovered controller behavior. The persistent GDI back buffer avoids painting each moving frame directly to the window. The opt-in diagnostic HUD shows map, world position, facing, and locomotion state. Collision is an axis-aligned TYPEFLAG approximation; it does not reproduce original AreaSearch shape sweeps or step-up behavior, and the fixed-map record bounds remain the outer movement limit. The second HUD row is an observable, separate process-runtime diagnostic: the host 40 Hz step delivers a registered SystemTimer event, advances the recovered scheduler scan, and runs an owned Stand entry through its verified off-screen sleep branch. Tick, remaining sleep ticks, and wake count update while the window is active. Three base entries reserve the low process IDs; the Stand entry and NPC number are diagnostic fixtures, not map NPCs or the player process. Host tick frequency is not the original DOS timer interrupt rate. @@ -515,9 +537,9 @@ After the first source-backed interaction, complete the original player/item loo ## Near-Term Next Actions -1. **Close the event path:** identify and reach an eligible retail `use` target from the original map-1 spawn. The exact production-equivalent search at egg `0x1e` still returns one candidate and no eligible event. 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 prove reachability and implement only the required recovered services, then 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 same-map teleporter over two scheduler scans, 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 same-map egg resolution and the 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. **Close the event path:** identify and reach an eligible retail `use` target from the actual level-start pad at `(30328, 29656, 16)`. The exact production-equivalent search at egg `0x1e` still returns one candidate and no eligible event, but that is the intermediate staging point, not the current avatar location; rerun the search from the destination. 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 prove reachability and implement only the required recovered services, then 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. ## Current Bottom Line -The host now materializes archive-backed USECODE chunks and builds tested 0x124-byte contexts with bounded source pointers and an initialized 0x82-byte call stack. Its window routes use-request candidates through owner-row selection into a context-backed task; the BOX_NS regression verifies VM-driven frame changes, rendered output, and cleanup, while a separate retail test confirms no eligible event at the original spawn and identifies only guarded/far map-wide candidates so far. Retail egg selection and placement of item 1 are covered, and the typed `TeleporterProcess` now runs after the host-modelled clear-stasis wait in a scheduler-driven two-pass test. A deterministic host input/tick test still 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. +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; destination candidates still need to be scanned. 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. diff --git a/docs/usecode-jelyhack-analysis.md b/docs/usecode-jelyhack-analysis.md index e2fcccf..ac0cb43 100644 --- a/docs/usecode-jelyhack-analysis.md +++ b/docs/usecode-jelyhack-analysis.md @@ -1,236 +1,84 @@ -# JELYHACK USECODE Analysis +# JELYHACK: What It Does and What We Know -## Scope +## Short answer -This note focuses on the currently exported pseudocode and byte-level decode for `JELYHACK` class `277` / class id `0x04D3`, especially its only non-zero event body: slot `0x01` (`use`). +In the Remorse USECODE archive, `JELYHACK` has one active event: `use`. If the player uses an object running this class, the handler sets process info `0x0207`, excludes the current process, and returns. It does not directly display text, play a sound, open a camera, change an item, or call a puzzle/event script. -Current generated pseudocode lives at: +Think of `JELYHACK` more as an **internal handle** than as the gadget that runs a puzzle. Its descriptor exposes one field, `referent`: an identity/reference the runtime can use to associate this record with other data. Newer VM analysis suggests referent-only records can own or connect a payload chain. Richer camera and trigger behavior exists in nearby classes such as `SURCAMNS` and `SURCAMEW`, but the evidence does not show that using `JELYHACK` directly launches those handlers. -- `USECODE/EUSECODE_extracted/pseudocode/JELYHACK/slot_01_use.txt` -- `USECODE/EUSECODE_extracted/pseudocode/JELYH2/slot_01_use.txt` +We also do not yet have a verified mission/map placement for a `JELYHACK` instance. The extracted scene files show map items and trigger eggs, but do not identify those items by USECODE class name. “Island” is therefore a useful label for this descriptor cluster, not a confirmed in-game location for this class. -## Plain-language answer +## What happens when it is used -If you want the short version first: - -- `JELYHACK` does not look like the object that contains the real island gameplay script. -- It looks more like a small anchor object that gives the engine a `referent` identity and a tiny shared `use` stub. -- When the player uses it, the stub appears to register a generic interaction/info value (`0x0207`) and then immediately exits. -- The richer gameplay behavior is more likely carried by nearby event-bearing records such as `REE_BOOT`, `SURCAMEW`, or `SFXTRIG`. - -So in easy words: `JELYHACK` currently looks less like "the script that does the JELYHACK puzzle" and more like "the map object or anchor that other real trigger objects point at or work beside." - -That also answers "what uses it" in the safest current sense: - -- the referent/owner side of the runtime uses it as an anchor-like record -- the player can still `use` it, but that `use` body is tiny and generic -- the surrounding event-bearing attachment records are the more likely carriers of the actual gameplay logic - -## Direct decompilation result - -Current readable decompilation for `JELYHACK::use`: +The Remorse event table gives `JELYHACK` (entry 277, class id `0x04D3`) a body only in slot `0x01` (`use`). The same is true of its sibling `JELYH2` (entry 280, class id `0x04D6`). The exported handler is: ```text -function jelyhack_use() /* entry=277 class_id=0x04D3 slot=0x01 */ -{ - entry: - set_info(0x0207, *(arg_06)); - process_exclude(); - return; - -} -``` - -Byte-faithful decode of the same body: - -```text -00D4: 5A init local_bytes=0x0 -00D6: 5C symbol_info symbol=JELYHACK -00E2: 0B push_word_immediate value_u16=0x0207 -00E5: 40 push_local_dword [BP+06h] -00E7: 4C push_indirect size=0x2 -00E9: 77 set_info -00EA: 78 process_exclude -00EB: 5B line_number line_number=0x00DB -00EE: 50 ret -``` - -That readable pseudocode is currently hiding one important detail: there is a small trailer after `ret`. - -Pentagram's older disassembly shows the body like this: - -```text -Func_1 (Event 1) JELYHACK::use(): - 0001: 5A init 00 - 0003: 5C symbol info offset 001Ch = "JELYHACK" - 000F: 0B push 0207h - 0012: 40 push dword [BP+06h] - 0014: 4C push indirect 02h bytes - 0016: 77 set info - 0017: 78 process exclude - 0018: 5B line number 219 (00DBh) - 001B: 50 ret -00: 01 type=69 (i) [BP+00h] (00) 00 referent - 002A: 7A end -``` - -So the extra bytes are not currently best read as hidden live code. The strongest reading is: - -- executable body ends at `ret` -- one post-return debug/local-symbol record follows -- that record names one slot/argument as `referent` -- then the body terminates with `0x7A end` - -That matters because it argues against the dramatic interpretation that we found a chopped-off second script. Right now the evidence fits "metadata trailer" much better than "cut content." - -## What the trailer most likely represents - -Current best explanation of the bytes after `ret`: - -- they are post-return symbol/debug metadata, not a second reachable instruction stream -- they preserve the name `referent`, which matches the descriptor-side picture where `JELYHACK` only exposes a `referent` field -- they reinforce the idea that this class is an anchor/owner record, not a rich event script - -In practical terms, the trailer is telling us something like: "this body knows about one meaningful value here, and that value is called `referent`." - -That is useful evidence, but it is not new gameplay logic. - -## Suggested readable pseudocode form - -For human reading, the most honest pseudocode form is probably this: - -```text -function jelyhack_use() /* entry=277 class_id=0x04D3 slot=0x01 */ +function jelyhack_use() { set_info(0x0207, *(arg_06)); process_exclude(); return; - - /* post-return metadata (not executable): - debug_symbol referent [BP+00h] type=0x69 - */ } ``` -That presentation keeps the important distinction visible: +The native VM confirms that these are process-control operations, not display commands. Opcode `0x77` stores two values on the running process: the used item's id as its source item, and `0x0207` as its process/event type. Opcode `0x78` then checks for another live process with the same item id and type. The final `0x50 ret` returns normally if execution continues. There is no branch, spawn, class/event call, text-file call, sound call, or item mutation in this handler. -- the function really returns where it looks like it returns -- there is still meaningful trailer data after that return -- the trailer is metadata, not currently credible as reachable lost code +**Likely player-visible result:** nothing obvious happens from this handler alone. Its practical job is bookkeeping and duplicate suppression: associate the running process with this item under type `0x0207`, then let the first matching process proceed while a duplicate takes the interpreter's early-completion path. The item is also marked in the engine's process-presence bitmap while it has a process; native termination refreshes that flag and clears it when no process remains for the item. The script itself does not show text, play audio, animate a screen, or change the world. -## What is directly supported +The number `0x0207` is not identified as a named gameplay action. In the native process entry, it occupies the process-type field; the duplicate check compares that field together with the item id. The exact English label or wider purpose of this tag remains unknown. It is common rather than JELYHACK-specific: the same `set_info(0x0207, item)` pattern appears in 117 exported Remorse event bodies. Do not interpret it as a message number, a camera command, or a special JELYHACK action. `process_exclude` does not hide or delete the object; it ends a competing process for the same item/type pair. -1. `JELYHACK` is not an active event hub in the same sense as `EVENT`, `NPCTRIG`, or `_BOOT` classes. -2. Its only non-zero slot is `0x01` (`use`), with `raw_event_entry_word = 0x002A`, `raw_code_offset = 0x00000001`, and body range `0x00D4..0x00FE` (`42` bytes). -3. The actual executable body is tiny: one `set_info(0x0207, *(arg_06))`, one `process_exclude()`, then return. -4. `JELYH2` is the same script body for practical purposes. The only pre-return differences are the symbol label string and line-number metadata; control flow and active ops are otherwise the same. -5. A post-return trailer still preserves `referent` metadata, which lines up with the descriptor-side fact that `JELYHACK` only exposes `referent`. -6. `JELYHACK` still exposes only the `referent` field on the descriptor side, which keeps it in the `referent-anchor` category rather than the event-bearing category. +This is backed by live Remorse Ghidra analysis: `Interpreter_NextUsecodeOp` opcode `0x77` calls `EntityDispatchEntry::SetEventTypeChecked` and `SetSourceType`; opcode `0x78` calls `Kernel_GetNumProcesses(itemno, proctype)` and exits when the count exceeds one. `SetSourceType` marks the item-process-presence bitmap. The type-specific item-process bits are only updated for `0xF0..0xF7`, so `0x0207` does not set one of those special flags. -## Comparison against the exported pseudocode corpus +The Remorse body window is `0x00D4..0x00FE` (42 bytes). The executable instructions return before the trailing symbol record naming `referent`, followed by the `0x7A end` marker. That trailer is metadata, not a second gameplay routine. -The `JELYHACK::use` body is not unique. Normalizing away only the function header, the exact same readable body currently appears in these seven exports: +## What the referent evidence means -- `AVATAR/slot_01_use.txt` -- `GRAVITON/slot_01_use.txt` -- `IONIC/slot_01_use.txt` -- `JELYHACK/slot_01_use.txt` -- `JELYH2/slot_01_use.txt` -- `PLASMA/slot_01_use.txt` -- `WEA_BOOT/slot_01_use.txt` +The Remorse descriptor for `JELYHACK` contains only `referent`; `JELYH2` has the same descriptor shape and the same active `use` behavior. Newer VM analysis identifies referent-only records as likely owners/identities in a runtime payload chain. This is a better explanation than treating the class as a complete puzzle script. -That matters because it argues against a special-purpose `JELYHACK` event implementation. The more defensible reading is that this is one small generic `use` stub reused across several classes. +The extracted descriptor neighborhood places `JELYHACK` near `SURCAMNS`, `REE_BOOT`, `SURCAMEW`, and `SFXTRIG`, alongside other records with `referent` fields. Some of those records also expose `event` or `eventTrigger` fields. This supports a model in which referent records and event-bearing records participate in a shared data-driven group. -There is also a second useful comparison: other classes often start with the same `set_info(...); process_exclude();` prologue and then continue into much richer logic. `DATALINK::use` is a good example: it begins with the same opening but then expands into a larger branch-heavy routine. So the `set_info/process_exclude` pair is best treated as a common preamble, not the whole semantic payload of a class family. +Important limit: these are descriptor-table relationships and runtime-family evidence. They do not prove the records are physically adjacent in a level, that each one points to this particular JELYHACK instance, or that a direct call runs from JELYHACK to any neighbor. A search of the exported pseudocode found no direct class/event call to class ids `0x04D3` or `0x04D6`. -## What `JELYHACK::use` most likely does +## Where the richer behavior lives -Current safest reading: +The closest concrete gameplay logic is in the camera callback classes, not in `JELYHACK::use`: -- It performs a small generic `use`-entry setup using info id `0x0207` and the dereferenced word at `arg_06`. -- It then marks the current process or handler for exclusion/suppression through `process_exclude()`. -- It does not itself implement the richer trigger logic one would expect from an active gameplay event script. +- `SURCAMNS::use` checks status bit `0x1000`; when set, it starts the class's high-slot handler `0x20`. +- `SURCAMNS::slot_20` follows link/quality values, checks nearby monitor/value-box objects, can request text-file handling, and starts trigger and camera-related handlers. +- `SURCAMNS::slot_21` creates a screen-related item and searches for matching camera eggs and mechanical actors, with waits and input checks. +- `SURCAMEW` contains a parallel callback family, with related screen and camera-object handling. -The unresolved part is the exact gameplay meaning of `set_info(0x0207, *(arg_06))`. The exported corpus shows this exact pattern in multiple unrelated classes, so `0x0207` currently looks more like a shared UI/message/interaction setup code than a JELYHACK-specific action. +These field names and operations make the surrounding cluster look like a security-monitor/camera interaction system. That is a useful gameplay interpretation of `SURCAMNS`/`SURCAMEW`; it is **not** proof that clicking a `JELYHACK` object opens that system. The missing link is an instance-level referent or map-data connection. -That leads to the simplest current gameplay explanation: +## Where it is used, and what remains unknown -- the object can be "used" -- the engine records a generic interaction fact about that use -- the object then gets out of the way -- anything interesting that happens next probably belongs to a neighboring event-bearing attachment, not to `JELYHACK` itself +What the current evidence establishes: -## What it probably does not do +- `JELYHACK` and `JELYH2` are present as separate classes in the Remorse USECODE archive. +- Both have only the small `use` handler in their common event slots, and their Remorse descriptors expose only `referent`. +- Their likely role is to provide a referent identity for the surrounding data-driven behavior group. +- The camera/trigger classes contain substantial behavior, but no direct call from JELYHACK to them has been recovered. -The current evidence argues against several stronger claims: +What it does **not** establish: -- It is probably not the main script that drives the JELYHACK gameplay behavior by itself. -- It is probably not the actual event-bearing payload that reaches the richer runtime opcode lanes recovered around `000d:208b`, `000d:21ed`, and `000d:22bc`. -- It is probably not a unique script template specialized only for the JELYHACK object. -- The bytes after `ret` are probably not a hidden reachable second branch or a simple "return was moved upward" cut-content remnant. +- the exact level, map coordinates, or visible object that uses class `JELYHACK`; +- the player-visible meaning of `set_info(0x0207, ...)`; +- which concrete event-bearing record shares a referent with a particular JELYHACK instance; +- that JELYHACK itself is a puzzle switch, camera terminal, key, or island controller. -If this were cut executable content, we would want to see stronger signs such as: +To answer those questions, the next useful evidence is an instance-level link: a map/object record bound to this class plus its referent value, cross-checked against the corresponding event-bearing records. Class-table proximity alone cannot supply that link. -- a branch target that lands in the trailer -- a sensible opcode stream after `ret` -- different trailers between `JELYHACK` and `JELYH2` that might hint at divergent behavior +## Variant note -At the moment we have the opposite pattern: a small named metadata record, a clean `end`, and strong similarity across the twin classes. +This conclusion about the `referent` descriptor is for the current Remorse extraction. Regret also contains classes named `JELYHACK` and `JELYH2`, and their readable `use` pseudocode has the same short operations, but their records are not interchangeable: the Regret `JELYHACK` event window is 13 bytes rather than Remorse's 42-byte window, and its descriptor decode does not expose the same `referent` field. Keep the class names and visible handler separate from the variant-specific descriptor evidence. -## Relationship to JELYH2 and the surrounding island +## Evidence files -`JELYHACK` and `JELYH2` remain the clearest referent-anchor twins in the extracted USECODE data: - -- same lone live slot `0x01` -- same event-table row shape (`0x002A / 0x00000001`) -- same `42`-byte body length -- same readable `use` body before return -- same descriptor-side role: `referent-anchor` - -This fits the broader neighborhood evidence already captured elsewhere: - -- `JELYHACK` / `JELYH2` sit beside event-bearing neighbors such as `REE_BOOT`, `SURCAMEW`, and `SFXTRIG` -- those neighbors expose `event` or `eventTrigger` fields and carry materially richer behavior bodies -- the current best model is therefore still `referent anchor + neighboring event-bearing attachment`, not `JELYHACK as a standalone active event core` - -## Comparison with nearby event-bearing neighbors - -The generated pseudocode reinforces that split. - -`REE_BOOT` slot `0x0A` and `SFXTRIG` slot `0x0A` diverge immediately from the JELYHACK body: - -- they use `set_info(0x0211, *(arg_06))` instead of `0x0207` -- they perform status checks, helper calls, spawns, waits/suspends, and other active logic -- they therefore look like genuine event-bearing routines rather than passive anchor stubs - -`DATALINK` slot `0x01` is also instructive in the other direction: - -- it starts with the same `set_info/process_exclude` preamble -- but it then continues into a much larger routine -- so the shared opening is not enough to classify a body as anchor-only or event-bearing by itself - -## Current best conclusion - -The decompiled `JELYHACK::use` body is important mainly because it supports a negative result cleanly: - -- `JELYHACK` is not hiding a large active event script in its only live slot -- its visible `use` handler is a minimal generic stub shared with several other classes -- the bytes after `ret` look like a metadata trailer naming `referent`, not like secret live code -- the interesting gameplay semantics around the JELYHACK island are still more likely to live in neighboring event-bearing descriptors attached to the same referent context - -So the current best human-readable model remains: - -```text -anchor JELYHACK(referent) -anchor JELYH2(referent) - -use: - set_info(shared_use_code_0x0207, deref(arg_06)) - process_exclude() - return - -actual island behavior: - likely carried by neighboring event-bearing attachments such as REE_BOOT / SURCAMEW / SFXTRIG -``` - -That is a stronger and cleaner claim than the older vague label `referent anchor`: the exported pseudocode now shows that the anchor really does have code, but the code is a tiny shared interaction stub, not the island's main behavior engine. \ No newline at end of file +- [Remorse JELYHACK use pseudocode](../USECODE/EUSECODE_extracted/pseudocode/JELYHACK/slot_01_use.txt) +- [Remorse JELYH2 use pseudocode](../USECODE/EUSECODE_extracted/pseudocode/JELYH2/slot_01_use.txt) +- [Remorse class/event index](../USECODE/EUSECODE_extracted/class_event_index.tsv) +- [Descriptor neighborhood graph](../USECODE/EUSECODE_extracted/jelyhack_island_graph.md) +- [Readable descriptor templates](../USECODE/EUSECODE_extracted/readable_descriptor_templates.md) +- [Runtime/readable script analysis](../USECODE/EUSECODE_extracted/readable_script_ir.md) +- [Descriptor-family runtime evidence](../USECODE/EUSECODE_extracted/runtime_descriptor_family_rankings.md) +- [USECODE opcode and runtime caveats](usecode-format-specification.md) \ No newline at end of file diff --git a/docs/usecode-unreferenced-candidates.md b/docs/usecode-unreferenced-candidates.md new file mode 100644 index 0000000..4f023aa --- /dev/null +++ b/docs/usecode-unreferenced-candidates.md @@ -0,0 +1,105 @@ +# Crusader USECODE Unreferenced-Body Candidates + +**Status:** Static reference scan with a separately identified debug-only class +**Scope:** Main local Remorse and Regret `EUSECODE.FLX` corpora +**Scanned:** 2026-10-06 + +## Result + +The current bytecode scan found **20 Remorse** and **24 Regret** non-empty high-slot event bodies with no incoming explicit class/event call or spawn reference from any decoded body in the same corpus. The `FLICTEST` slot-`0x21` bodies are identified below as debug movie-player code, confirmed unused as ordinary retail gameplay; the other **19 Remorse** and **23 Regret** entries remain unclassified candidates. + +| Variant | Bodies scanned | Decoded call/spawn references | No-incoming bodies | Confirmed debug-only | Unclassified candidates | +|---|---:|---:|---:|---:|---:| +| Remorse | 977 | 2,878 | 20 | 1 | 19 | +| Regret | 1,152 | 3,415 | 24 | 1 | 23 | + +## Candidate Lists + +A candidate is identified by its class id and event slot. Body size is in bytes. The names are the extracted class-name hints. + +### Remorse + +| Class ID | Class | Slot | Body bytes | +|---:|---|---:|---:| +| `0x0A1E` | `ITEM` | `0x20` | 86 | +| `0x0A1E` | `ITEM` | `0x21` | 159 | +| `0x0A20` | `FLICTEST` | `0x21` | 9,901 | +| `0x0A17` | `TEXTFILE` | `0x22` | 229 | +| `0x0A1E` | `ITEM` | `0x22` | 101 | +| `0x0A09` | `ELEVAT` | `0x25` | 524 | +| `0x0A11` | `NPC` | `0x25` | 203 | +| `0x0A1E` | `ITEM` | `0x25` | 1,093 | +| `0x0A11` | `NPC` | `0x26` | 494 | +| `0x0A1E` | `ITEM` | `0x26` | 968 | +| `0x0A0C` | `FREE` | `0x27` | 223 | +| `0x0A11` | `NPC` | `0x27` | 329 | +| `0x0A0C` | `FREE` | `0x2A` | 224 | +| `0x0A1E` | `ITEM` | `0x2C` | 139 | +| `0x0A0C` | `FREE` | `0x34` | 136 | +| `0x0A0C` | `FREE` | `0x35` | 97 | +| `0x0A0C` | `FREE` | `0x36` | 91 | +| `0x0A0C` | `FREE` | `0x37` | 89 | +| `0x0A0C` | `FREE` | `0x38` | 78 | +| `0x0A0C` | `FREE` | `0x39` | 106 | + +### Regret + +| Class ID | Class | Slot | Body bytes | +|---:|---|---:|---:| +| `0x05D8` | `TRAMFLOR` | `0x20` | 645 | +| `0x0A0A` | `FLICTEST` | `0x21` | 11 | +| `0x0A0C` | `ITEM` | `0x22` | 68 | +| `0x0A16` | `TEXTFILE` | `0x22` | 142 | +| `0x0A0C` | `ITEM` | `0x23` | 43 | +| `0x0A08` | `ELEVAT` | `0x25` | 324 | +| `0x0A0F` | `NPC` | `0x25` | 105 | +| `0x0A0F` | `NPC` | `0x26` | 267 | +| `0x0A0C` | `ITEM` | `0x27` | 655 | +| `0x0A0F` | `NPC` | `0x27` | 193 | +| `0x0A0C` | `ITEM` | `0x28` | 579 | +| `0x0A1D` | `FREE` | `0x28` | 170 | +| `0x0A0F` | `NPC` | `0x2B` | 169 | +| `0x0A0C` | `ITEM` | `0x2E` | 80 | +| `0x0A1D` | `FREE` | `0x2F` | 197 | +| `0x0A1D` | `FREE` | `0x30` | 127 | +| `0x0A1D` | `FREE` | `0x33` | 98 | +| `0x0A1D` | `FREE` | `0x3D` | 93 | +| `0x0A1D` | `FREE` | `0x3E` | 36 | +| `0x0A1D` | `FREE` | `0x3F` | 36 | +| `0x0A1D` | `FREE` | `0x40` | 33 | +| `0x0A1D` | `FREE` | `0x41` | 35 | +| `0x0A1D` | `FREE` | `0x42` | 47 | +| `0x0A1D` | `FREE` | `0x43` | 35 | + +## Confirmed Debug-Only Code + +The `FLICTEST` class is a debug movie-player/helper, not normal retail gameplay content. Its unreferenced slot-`0x21` body appears in each candidate table above: + +- Remorse: class `0x0A20`, `FLICTEST::0x21`, 9,901 bytes. +- Regret: class `0x0A0A`, `FLICTEST::0x21`, 11 bytes. + +This classification is about the feature's retail gameplay status, not whether the code or class exists in the shipped archive. In both variants, `FLICTEST::0x20` has explicit script references and is therefore not in the no-incoming list. The longer class-specific investigation documents the debug movie-browser behavior and the remaining routes/evidence: [FLICTEST usecode investigation](./usecode/flictest-investigation.md). + +## Cross-Reference: Removed Shapes + +The removed-item note describes shapes, while this scan lists non-empty USECODE class/event bodies. A removed shape with no corresponding class is absent from this list by construction; it is not an unreferenced body. + +- **`0x034E` concussion grenade:** not in the candidate list. The Remorse and Regret class/event indexes contain no class with class id `0x034E`; the removed-item investigation also found no separate Remorse USECODE class. The surviving name/map data does not establish a script body. +- **`0x034F` nerve gas grenade and `0x0350` EMP grenade:** likewise, no class/event bodies with those class ids were found in either index. In Regret, `0x0350` is still a resolved bomb display-name entry, but that does not make it a USECODE class. +- **`0x0343` old grenade:** not an unreferenced candidate. It is the separate `GRENADE` class (id `0x0343`), with non-empty `hit` and `gotHit` handlers; the removed-item note also records Pepsi dispenser scripts attempting to create this shape. +- **`0x0548`, `0x0110`, and `0x0112`:** these are suspicious/unmapped shapes in the removed-item note, not class/event ids identified by this body scan. Their absence here says nothing by itself about native item behavior. + +See [removed item shapes](./removed_items.md) for the source evidence and qualifications. + +## Method + +- Scanned every non-empty body in the Remorse [`class_event_index.tsv`](../USECODE/EUSECODE_extracted/class_event_index.tsv) and Regret [`class_event_index.tsv`](../USECODE/REGRET/REGRET_USECODE_extracted/class_event_index.tsv). +- Parsed bodies with the existing [`poc_crusader_usecode_parser.py`](../tools/poc_crusader_usecode_parser.py), collecting explicit targets from bytecodes `0x11` (class/event call), `0x57` (spawn), and `0x58` (inline spawn). +- Counted incoming references by `(class id, event slot)`. Candidates are non-empty bodies at slots `0x20` and above with no incoming reference in that graph. The scan completed with zero parser errors, unknown-opcode bodies, or targets lacking a non-empty indexed body. +- Limited the candidate list to high slots because the common low event slots have engine/native dispatch paths; a body at one of those slots may be an entry point without any bytecode caller. + +## Limits and Interpretation + +"No incoming bytecode reference" is not equivalent to "unused in the final game." The scan cannot rule out native code dispatching a high slot dynamically, references encoded in game data or outside these two archives, behavior reached through unmodeled runtime paths, or content/version differences. It also does not measure whether an explicit call site is actually reachable or executed. The `FLICTEST` classification is based on the separate debug-player investigation and should not be generalized to its explicitly referenced slot-`0x20` body. + +The common event catalog documents native entry points and explains why an empty slot, an unreferenced body, and a confirmed dead body are different claims: [usecode-event-slots-catalog.md](./usecode-event-slots-catalog.md). This list should be upgraded only after checking candidate callers in the executable and references in the corresponding final-game data. diff --git a/rebuild/remorse/include/remorse/detail/map_sorter.h b/rebuild/remorse/include/remorse/detail/map_sorter.h index de81dc6..a949d11 100644 --- a/rebuild/remorse/include/remorse/detail/map_sorter.h +++ b/rebuild/remorse/include/remorse/detail/map_sorter.h @@ -36,7 +36,6 @@ struct RenderSortItem { bool translucent = false; bool animated = false; bool land = false; - bool sprite = false; bool inventoryItem = false; }; diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index f6c8956..2d58a5e 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -224,6 +224,10 @@ private: bool markNewProcesses_ = false; }; +bool runFreshGameTeleporterStartup(ProcessKernel& kernel, LiveFixedMapItems& items, + u16 mapNumber, u16 teleportId, const std::vector& shapes, + u16 (&groupCounts)[32]); + class EntityDispatchEntry { public: static constexpr u16 initBaseSegment = 0x11e0; diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index 0bd6737..c45029a 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -81,6 +81,9 @@ std::optional loadFixedMap(const FixedMapArchive& archive, u32 mapInde std::optional> stageFixedMapItems(const FixedMap& map); std::optional findTeleportEgg( const std::vector& items, const std::vector& shapes, u8 eggId); +std::optional findNearbyActiveTeleportEgg(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, + u8 currentMapNumber); std::optional> stageContainedFixedMapItems( const FixedMap& map, const std::vector& shapes); std::optional nearestStagedFixedMapItem( diff --git a/rebuild/remorse/include/remorse/map_renderer.h b/rebuild/remorse/include/remorse/map_renderer.h index 28425dc..4dadab4 100644 --- a/rebuild/remorse/include/remorse/map_renderer.h +++ b/rebuild/remorse/include/remorse/map_renderer.h @@ -31,6 +31,15 @@ struct WorldPoint { s32 z = 0; }; +struct MapRenderSprite { + WorldPoint position; + u16 shape = 0; + u8 frame = 0; + bool flipped = false; + const DecodedShapeFrame* decoded = nullptr; + const Palette256* palette = nullptr; +}; + struct ScreenPoint { s32 x = 0; s32 y = 0; @@ -59,6 +68,7 @@ struct RenderedMapImage { s32 fullWidth = 0; s32 fullHeight = 0; std::vector pixels; + std::vector coverage; }; struct MapSceneRenderer { @@ -70,7 +80,7 @@ struct MapSceneRenderer { std::map, DecodedShapeFrame> decodedFrames; std::optional render(const MapRenderOptions& options, - const LiveFixedMapItems* liveItems = nullptr); + const LiveFixedMapItems* liveItems = nullptr, const MapRenderSprite* sprite = nullptr); }; std::optional loadMapSceneRenderer(const GameDataRoot& root, u32 mapIndex); diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index ea1c5c6..ebf1cad 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -270,6 +270,48 @@ bool ProcessKernel::runClearAvatarInStasisProcess(u16 processId, bool& avatarInS return true; } +bool runFreshGameTeleporterStartup(ProcessKernel& kernel, LiveFixedMapItems& items, + u16 mapNumber, u16 teleportId, const std::vector& shapes, + u16 (&groupCounts)[32]) +{ + const u8 activeGroup = kernel.activeGroup(); + bool avatarInStasis = false; + auto* teleporter = kernel.createTeleporterProcess(activeGroup, mapNumber, teleportId, + groupCounts, true, false, avatarInStasis); + const u16 teleporterId = readLe16(teleporter->base, 0x02); + struct StartupContext { + ProcessKernel& kernel; + LiveFixedMapItems& items; + const std::vector& shapes; + u16 (&groupCounts)[32]; + bool& avatarInStasis; + u16 mapNumber; + bool teleported = false; + } startup{kernel, items, shapes, groupCounts, avatarInStasis, mapNumber}; + const auto runStartupProcess = [](EntityDispatchEntryBase& entry, void* opaque) { + auto& context = *static_cast(opaque); + const u16 processId = readLe16(entry, 0x02); + if (processId < 3) { + return; + } + const u16 vtable = readLe16(entry, 0x00); + if (vtable == ClearAvatarInStasisProcess::vtableOffset) { + context.kernel.runClearAvatarInStasisProcess(processId, + context.avatarInStasis, context.groupCounts); + } else if (vtable == TeleporterProcess::vtableOffset) { + const auto& process = *reinterpret_cast(&entry); + context.teleported = TeleporterProcess::run(process, context.items, + context.mapNumber, context.shapes); + entry.bytes[0x18] |= 4; + context.kernel.terminateProcess(processId, context.groupCounts); + } + }; + for (unsigned pass = 0; pass < 2 && kernel.processAt(teleporterId) != nullptr; ++pass) { + kernel.scanRunnableProcesses(activeGroup, runStartupProcess, &startup); + } + return startup.teleported && !avatarInStasis && kernel.processAt(teleporterId) == nullptr; +} + EntityVmContextProcessEntry* ProcessKernel::createUsecodeProcess(u8 activeGroup, u16 (&groupCounts)[32]) { diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index 539458e..700e005 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -171,6 +171,28 @@ std::optional findTeleportEgg( return match; } +std::optional findNearbyActiveTeleportEgg(const StagedFixedMapItem& origin, + const std::vector& items, const std::vector& shapes, + u8 currentMapNumber) +{ + for (const auto& item : items) { + if (item.data.shape >= shapes.size() || shapes[item.data.shape].family != 8 || + item.data.frame == 1 || item.data.mapNumber != currentMapNumber) { + continue; + } + const s32 xRange = static_cast((item.data.npcNumber >> 4) & 0x0f) * 64; + const s32 yRange = static_cast(item.data.npcNumber & 0x0f) * 64; + const s32 deltaX = static_cast(origin.data.x) - item.data.x; + const s32 deltaY = static_cast(origin.data.y) - item.data.y; + const s32 deltaZ = static_cast(origin.data.z) - item.data.z; + if (deltaX >= -xRange && deltaX <= xRange && deltaY >= -yRange && deltaY <= yRange && + deltaZ >= -48 && deltaZ <= 48) { + return item; + } + } + return std::nullopt; +} + std::optional> stageContainedFixedMapItems( const FixedMap& map, const std::vector& shapes) { diff --git a/rebuild/remorse/src/map_renderer.cpp b/rebuild/remorse/src/map_renderer.cpp index 568131d..a6b0f86 100644 --- a/rebuild/remorse/src/map_renderer.cpp +++ b/rebuild/remorse/src/map_renderer.cpp @@ -35,11 +35,14 @@ struct SceneItem { u16 quality = 0; u8 mapNumber = 0; bool fromFixed = true; + const DecodedShapeFrame* decodedOverride = nullptr; + const Palette256* paletteOverride = nullptr; }; struct RenderNode { SceneItem item; const DecodedShapeFrame* decoded = nullptr; + const Palette256* paletteOverride = nullptr; s32 left = 0; s32 top = 0; s32 right = 0; @@ -208,7 +211,8 @@ std::vector prepareRenderNodes( nodes.reserve(items.size()); sortItems.reserve(items.size()); for (const SceneItem& item : items) { - const auto* decoded = cachedDecode(shapeArchive, cache, item.shape, item.frame); + const auto* decoded = item.decodedOverride != nullptr + ? item.decodedOverride : cachedDecode(shapeArchive, cache, item.shape, item.frame); if (!decoded) { continue; } @@ -219,6 +223,7 @@ std::vector prepareRenderNodes( RenderNode node; node.item = item; node.decoded = decoded; + node.paletteOverride = item.paletteOverride; node.left = flipped ? bottomX + decoded->frame.xOffset - static_cast(decoded->frame.width) : bottomX - decoded->frame.xOffset; @@ -275,6 +280,7 @@ std::vector prepareRenderNodes( void paintNode(RenderedMapImage& image, const RenderNode& node, const Palette256& palette) { + const Palette256& nodePalette = node.paletteOverride != nullptr ? *node.paletteOverride : palette; const bool flipped = (node.item.flags & flagFlipped) != 0; for (u32 sourceY = 0; sourceY < node.decoded->frame.height; ++sourceY) { const s32 destY = node.top - image.sourceTop + static_cast(sourceY); @@ -292,7 +298,9 @@ void paintNode(RenderedMapImage& image, const RenderNode& node, const Palette256 if (destX < 0 || destX >= static_cast(image.width)) { continue; } - image.pixels[static_cast(destY) * image.width + destX] = scalePaletteColor(palette.colors[colorIndex]); + const std::size_t pixelIndex = static_cast(destY) * image.width + destX; + image.pixels[pixelIndex] = scalePaletteColor(nodePalette.colors[colorIndex]); + image.coverage[pixelIndex] = 1; } } } @@ -343,9 +351,26 @@ std::optional loadMapSceneRenderer(const GameDataRoot& root, u } std::optional MapSceneRenderer::render(const MapRenderOptions& options, - const LiveFixedMapItems* liveItems) + const LiveFixedMapItems* liveItems, const MapRenderSprite* sprite) { - const auto items = collectSceneItems(map, typeFlags, globs, options, liveItems); + auto items = collectSceneItems(map, typeFlags, globs, options, liveItems); + if (sprite != nullptr && sprite->decoded != nullptr && sprite->palette != nullptr && + sprite->shape < typeFlags.size()) { + SceneItem sceneSprite; + sceneSprite.x = sprite->position.x; + sceneSprite.y = sprite->position.y; + sceneSprite.z = sprite->position.z; + sceneSprite.shape = sprite->shape; + sceneSprite.frame = sprite->frame; + sceneSprite.flags = sprite->flipped ? flagFlipped : 0; + sceneSprite.mapNumber = static_cast(options.mapIndex); + sceneSprite.fromFixed = false; + sceneSprite.decodedOverride = sprite->decoded; + sceneSprite.paletteOverride = sprite->palette; + if (inWorldRect(sceneSprite, options.worldRect)) { + items.push_back(sceneSprite); + } + } auto nodes = prepareRenderNodes(items, shapes, typeFlags, decodedFrames); if (nodes.empty()) { return std::nullopt; @@ -385,6 +410,7 @@ std::optional MapSceneRenderer::render(const MapRenderOptions& image.pixels.assign( static_cast(image.width) * image.height, RgbColor{static_cast(10), static_cast(12), static_cast(18)}); + image.coverage.assign(image.pixels.size(), 0); for (const RenderNode& node : nodes) { if (node.right < image.sourceLeft || node.bottom < image.sourceTop || diff --git a/rebuild/remorse/src/map_sorter.cpp b/rebuild/remorse/src/map_sorter.cpp index 3912059..d54324a 100644 --- a/rebuild/remorse/src/map_sorter.cpp +++ b/rebuild/remorse/src/map_sorter.cpp @@ -1,6 +1,9 @@ #include "remorse/detail/map_sorter.h" #include +#include +#include +#include namespace remorse { namespace detail { @@ -13,11 +16,22 @@ struct SortNode { s32 order = -1; }; +constexpr s32 spatialCellSize = 128; + +s32 spatialCell(s32 coordinate) +{ + const s32 quotient = coordinate / spatialCellSize; + return coordinate % spatialCellSize < 0 ? quotient - 1 : quotient; +} + +std::uint64_t spatialKey(s32 x, s32 y) +{ + return (static_cast(static_cast(x)) << 32) | + static_cast(y); +} + bool listLessThan(const RenderSortItem& left, const RenderSortItem& right) { - if (left.sprite != right.sprite) { - return left.sprite < right.sprite; - } if (left.z != right.z) { return left.z < right.z; } @@ -77,10 +91,6 @@ bool occludes(const RenderSortItem& outer, const RenderSortItem& inner) bool below(const RenderSortItem& left, const RenderSortItem& right) { - if (left.sprite != right.sprite) { - return left.sprite < right.sprite; - } - if (left.flat && right.flat) { if (left.z != right.z) { return left.z < right.z; @@ -256,15 +266,49 @@ std::vector resolveRenderOrder(const std::vector& i nodes.push_back(SortNode{item, {}, false, -1}); } - std::vector ordered; - ordered.reserve(nodes.size()); + const auto indexLessThan = [&nodes](std::size_t left, std::size_t right) { + if (listLessThan(nodes[left].item, nodes[right].item)) { + return true; + } + if (listLessThan(nodes[right].item, nodes[left].item)) { + return false; + } + return left < right; + }; + std::set ordered(indexLessThan); + std::unordered_map> spatialBuckets; + spatialBuckets.reserve(nodes.size() * 2); + std::vector visited(nodes.size(), 0); + std::vector candidates; for (std::size_t index = 0; index < nodes.size(); ++index) { - std::size_t insertAt = ordered.size(); - for (std::size_t otherIndex = 0; otherIndex < ordered.size(); ++otherIndex) { - const std::size_t other = ordered[otherIndex]; - if (insertAt == ordered.size() && listLessThan(nodes[index].item, nodes[other].item)) { - insertAt = otherIndex; + candidates.clear(); + const RenderSortItem& current = nodes[index].item; + if (current.right > current.left && current.bottom > current.top) { + const s32 minCellX = spatialCell(current.left); + const s32 maxCellX = spatialCell(current.right - 1); + const s32 minCellY = spatialCell(current.top); + const s32 maxCellY = spatialCell(current.bottom - 1); + for (s32 cellY = minCellY; cellY <= maxCellY; ++cellY) { + for (s32 cellX = minCellX; cellX <= maxCellX; ++cellX) { + const auto bucket = spatialBuckets.find(spatialKey(cellX, cellY)); + if (bucket == spatialBuckets.end()) { + continue; + } + for (const std::size_t other : bucket->second) { + if (visited[other] == index + 1) { + continue; + } + visited[other] = index + 1; + if (rectIntersects(current, nodes[other].item)) { + candidates.push_back(other); + } + } + } } + std::sort(candidates.begin(), candidates.end(), indexLessThan); + } + + for (const std::size_t other : candidates) { if (nodes[other].occluded || !overlaps(nodes[index].item, nodes[other].item)) { continue; } @@ -281,7 +325,19 @@ std::vector resolveRenderOrder(const std::vector& i insertDependencySorted(nodes, index, other); } } - ordered.insert(ordered.begin() + static_cast(insertAt), index); + + ordered.insert(index); + if (current.right > current.left && current.bottom > current.top) { + const s32 minCellX = spatialCell(current.left); + const s32 maxCellX = spatialCell(current.right - 1); + const s32 minCellY = spatialCell(current.top); + const s32 maxCellY = spatialCell(current.bottom - 1); + for (s32 cellY = minCellY; cellY <= maxCellY; ++cellY) { + for (s32 cellX = minCellX; cellX <= maxCellX; ++cellX) { + spatialBuckets[spatialKey(cellX, cellY)].push_back(index); + } + } + } } std::vector painted; diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index b19a0ea..ffc6f47 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -18,10 +18,12 @@ #include "remorse/usecode_vm.h" #include +#include #include #include #include #include +#include #include #include #include @@ -37,15 +39,24 @@ constexpr UINT timerId = 1; constexpr UINT sceneReadyMessage = WM_APP + 1; constexpr remorse::u32 backingWidth = 2560; constexpr remorse::u32 backingHeight = 1440; +constexpr remorse::u32 playerPatchWidth = 512; +constexpr remorse::u32 playerPatchHeight = 384; constexpr int initialClientWidth = 1280; constexpr int initialClientHeight = 760; constexpr double simulationTickSeconds = 0.025; constexpr remorse::s32 diagnosticItemRange = 48; +struct WarpStart { + remorse::u16 x = 0; + remorse::u16 y = 0; + remorse::u8 z = 0; +}; + struct AppState { remorse::GameDataRoot root; remorse::u32 mapIndex = 1; bool diagnostics = false; + std::optional warpStart; remorse::ProcessKernel diagnosticKernel; remorse::u16 diagnosticGroupCounts[32]{}; remorse::UsecodeTaskRegistry usecodeTasks; @@ -66,11 +77,15 @@ struct AppState { bool diagnosticItemCompleted = false; remorse::u32 standWakeCount = 0; remorse::u32 diagnosticKeyEvents = 0; + std::mutex kernelMutex; std::mutex sceneMutex; std::condition_variable renderWake; bool renderRequested = false; + bool renderFullRequested = false; + std::uint64_t renderGeneration = 0; bool renderStop = false; std::optional scene; + std::optional playerPatch; std::optional renderer; std::optional standAnimation; std::optional walkAnimation; @@ -145,6 +160,50 @@ remorse::WorldPoint avatarWorld(const AppState& state) : state.spawn; } +remorse::MapRenderOptions playerPatchOptions(remorse::u32 mapIndex, + const remorse::WorldPoint& center) +{ + remorse::MapRenderOptions options; + options.mapIndex = mapIndex; + options.maxWidth = playerPatchWidth; + options.maxHeight = playerPatchHeight; + options.includeRoofs = true; + options.viewCenter = center; + const remorse::s32 radius = static_cast( + playerPatchWidth + playerPatchHeight * 2 + 1280); + options.worldRect = remorse::WorldRect{ + center.x - radius, center.y - radius, center.x + radius, center.y + radius}; + return options; +} + +std::optional playerRenderSprite(const AppState& state) +{ + const remorse::AnimationClip* clip = nullptr; + if (state.playerAnimation == 1 && state.walkAnimation) { + clip = &*state.walkAnimation; + } else if (state.playerAnimation == 3 && state.runAnimation) { + clip = &*state.runAnimation; + } else if (state.standAnimation) { + clip = &*state.standAnimation; + } + if (!clip) { + return std::nullopt; + } + + const remorse::u8 frameIndex = state.playerAnimation == 0 ? 0 : state.playerFrame; + const auto metadata = remorse::getAnimationFrame(*clip, state.playerDirection, frameIndex); + if (!metadata) { + return std::nullopt; + } + const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata); + if (shapeFrame >= state.playerFrames.size() || !state.playerFrames[shapeFrame]) { + return std::nullopt; + } + return remorse::MapRenderSprite{avatarWorld(state), 1, static_cast(shapeFrame), + remorse::isAnimationFrameFlipped(*metadata), &*state.playerFrames[shapeFrame], + &state.playerPalette}; +} + bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range); @@ -507,99 +566,98 @@ void loadSceneAsync(HWND window, AppState& state) maxY = std::max(maxY, static_cast(entry.y)); } - const auto startingEgg = remorse::findTeleportEgg(*stagedItems, *shapeTypes, 0x1e); - if (state.mapIndex == 1 && !startingEgg) { + const auto startingEgg = state.warpStart + ? std::optional{} + : remorse::findTeleportEgg(*stagedItems, *shapeTypes, 0x1e); + if (!state.warpStart && state.mapIndex == 1 && !startingEgg) { setLoadFailure(state, L"The original map 1 starting teleporter could not be found uniquely."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } - if (state.mapIndex != 1 && !state.diagnostics) { + if (!state.warpStart && state.mapIndex != 1 && !state.diagnostics) { setLoadFailure(state, L"Only map 1 has a source-backed start. Use --diagnostics for other maps."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } - const remorse::WorldPoint spawn = startingEgg - ? remorse::WorldPoint{startingEgg->data.x * 2, startingEgg->data.y * 2, startingEgg->data.z} - : remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0}; + remorse::WorldPoint spawn = state.warpStart + ? remorse::WorldPoint{static_cast(state.warpStart->x) * 2, + static_cast(state.warpStart->y) * 2, state.warpStart->z} + : startingEgg + ? remorse::WorldPoint{startingEgg->data.x * 2, startingEgg->data.y * 2, + startingEgg->data.z} + : remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0}; remorse::MapRenderOptions options; options.mapIndex = state.mapIndex; options.maxWidth = backingWidth; options.maxHeight = backingHeight; + options.includeRoofs = true; options.viewCenter = spawn; remorse::LiveFixedMapItems liveItems(std::move(*stagedItems), std::move(containedItems)); liveItems.initializeAvatar(); if (startingEgg) { - remorse::ProcessKernel teleporterKernel; - remorse::u16 teleporterGroupCounts[32]{}; - for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { - teleporterKernel.createProcess(1, teleporterGroupCounts); - } - bool avatarInStasis = false; - auto* teleporter = teleporterKernel.createTeleporterProcess(1, - static_cast(state.mapIndex), 0x1e, teleporterGroupCounts, - true, false, avatarInStasis); - const remorse::u16 processId = static_cast(teleporter->base.bytes[2] | - (static_cast(teleporter->base.bytes[3]) << 8)); - struct StartupContext { - remorse::ProcessKernel& kernel; - remorse::LiveFixedMapItems& items; - const std::vector& shapes; - remorse::u16 (&groupCounts)[32]; - bool& avatarInStasis; - remorse::u16 mapNumber; - bool teleported = false; - bool valid = true; - } startup{teleporterKernel, liveItems, *shapeTypes, teleporterGroupCounts, - avatarInStasis, static_cast(state.mapIndex)}; - const auto runStartupProcess = [](remorse::EntityDispatchEntryBase& entry, - void* opaque) { - auto& context = *static_cast(opaque); - const remorse::u16 processId = static_cast(entry.bytes[2] | - (static_cast(entry.bytes[3]) << 8)); - if (processId < 3) return; - const remorse::u16 vtable = static_cast(entry.bytes[0] | - (static_cast(entry.bytes[1]) << 8)); - if (vtable == remorse::ClearAvatarInStasisProcess::vtableOffset) { - context.valid = context.kernel.runClearAvatarInStasisProcess(processId, - context.avatarInStasis, context.groupCounts); - } else if (vtable == remorse::TeleporterProcess::vtableOffset) { - const auto& teleporterProcess = - *reinterpret_cast(&entry); - context.teleported = remorse::TeleporterProcess::run(teleporterProcess, - context.items, context.mapNumber, context.shapes); - entry.bytes[0x18] |= 4; - context.kernel.terminateProcess(processId, context.groupCounts); - } else { - context.valid = false; - } - }; - for (unsigned pass = 0; pass < 2 && teleporterKernel.processAt(processId) != nullptr; - ++pass) { - teleporterKernel.scanRunnableProcesses(1, runStartupProcess, &startup); - } - if (!startup.valid || !startup.teleported || avatarInStasis || - teleporterKernel.processAt(processId) != nullptr) { + 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."); 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 { - remorse::StagedFixedMapItem diagnosticStart; - diagnosticStart.data.x = static_cast(spawn.x / 2); - diagnosticStart.data.y = static_cast(spawn.y / 2); - diagnosticStart.data.z = static_cast(spawn.z); - liveItems.teleportAvatar(diagnosticStart, static_cast(state.mapIndex)); + remorse::StagedFixedMapItem directStart; + directStart.data.x = static_cast(spawn.x / 2); + directStart.data.y = static_cast(spawn.y / 2); + directStart.data.z = static_cast(spawn.z); + liveItems.teleportAvatar(directStart, static_cast(state.mapIndex)); } auto renderer = remorse::loadMapSceneRenderer(state.root, state.mapIndex); if (renderer) { hatchGlobsInFastArea(liveItems, *renderer, remorse::calculateFastAreaRange(spawn)); } + const auto initialMetadata = remorse::getAnimationFrame(*standAnimation, 14, 0); + if (!initialMetadata) { + setLoadFailure(state, L"The player stand frame could not be resolved."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + const remorse::u16 initialShapeFrame = remorse::getAnimationShapeFrame(*initialMetadata); + if (initialShapeFrame >= playerFrames.size() || !playerFrames[initialShapeFrame]) { + setLoadFailure(state, L"The player stand frame could not be decoded."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } + const remorse::MapRenderSprite initialPlayer{spawn, 1, + static_cast(initialShapeFrame), + remorse::isAnimationFrameFlipped(*initialMetadata), &*playerFrames[initialShapeFrame], + &*palette}; auto scene = renderer ? renderer->render(options, &liveItems) : std::nullopt; if (!scene) { setLoadFailure(state, L"Map graphics or palette data could not be loaded."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } + auto playerPatch = renderer ? renderer->render( + playerPatchOptions(state.mapIndex, spawn), &liveItems, &initialPlayer) : std::nullopt; + if (!playerPatch) { + setLoadFailure(state, L"The initial player render patch could not be built."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } std::vector dibPixels(scene->pixels.size() * 3); for (std::size_t index = 0; index < scene->pixels.size(); ++index) { @@ -624,6 +682,7 @@ void loadSceneAsync(HWND window, AppState& state) state.maxWorldX = maxX; state.maxWorldY = maxY; state.scene = std::move(scene); + state.playerPatch = std::move(playerPatch); state.renderer = std::move(renderer); state.dibPixels = std::move(dibPixels); state.standAnimation = *standAnimation; @@ -672,7 +731,10 @@ void startLiveRenderer(HWND window, AppState& state) state.renderThread = std::thread([window, &state]() { for (;;) { std::optional snapshot; + std::optional playerSprite; remorse::WorldPoint center{}; + bool fullRender = false; + std::uint64_t generation = 0; { std::unique_lock lock(state.sceneMutex); state.renderWake.wait(lock, [&state]() { return state.renderStop || state.renderRequested; }); @@ -680,41 +742,70 @@ void startLiveRenderer(HWND window, AppState& state) return; } state.renderRequested = false; + fullRender = state.renderFullRequested; + state.renderFullRequested = false; + generation = state.renderGeneration; snapshot.emplace(*state.liveItems); center = avatarWorld(state); + playerSprite = playerRenderSprite(state); } - remorse::MapRenderOptions options; - options.mapIndex = state.mapIndex; - options.maxWidth = backingWidth; - options.maxHeight = backingHeight; - options.viewCenter = center; - const remorse::s32 radius = static_cast( - backingWidth + backingHeight * 2 + 512); - options.worldRect = remorse::WorldRect{ - center.x - radius, center.y - radius, center.x + radius, center.y + radius}; - auto scene = state.renderer->render(options, &*snapshot); - if (!scene) { + std::optional scene; + std::vector pixels; + if (fullRender) { + remorse::MapRenderOptions options; + options.mapIndex = state.mapIndex; + options.maxWidth = backingWidth; + options.maxHeight = backingHeight; + options.includeRoofs = true; + options.viewCenter = center; + const remorse::s32 radius = static_cast( + backingWidth + backingHeight * 2 + 512); + options.worldRect = remorse::WorldRect{ + center.x - radius, center.y - radius, center.x + radius, center.y + radius}; + scene = state.renderer->render(options, &*snapshot); + if (!scene) { + continue; + } + pixels.resize(scene->pixels.size() * 3); + for (std::size_t index = 0; index < scene->pixels.size(); ++index) { + pixels[index * 3] = scene->pixels[index].blue; + pixels[index * 3 + 1] = scene->pixels[index].green; + pixels[index * 3 + 2] = scene->pixels[index].red; + } + } + auto playerPatch = state.renderer->render(playerPatchOptions(state.mapIndex, center), + &*snapshot, playerSprite ? &*playerSprite : nullptr); + if (!playerPatch) { continue; } - std::vector pixels(scene->pixels.size() * 3); - for (std::size_t index = 0; index < scene->pixels.size(); ++index) { - pixels[index * 3] = scene->pixels[index].blue; - pixels[index * 3 + 1] = scene->pixels[index].green; - pixels[index * 3 + 2] = scene->pixels[index].red; - } { std::lock_guard lock(state.sceneMutex); if (state.renderStop) { return; } - state.scene = std::move(scene); - state.dibPixels = std::move(pixels); + if (state.renderGeneration != generation && state.renderFullRequested) { + state.renderRequested = true; + continue; + } + if (fullRender) { + state.scene = std::move(scene); + state.dibPixels = std::move(pixels); + } + state.playerPatch = std::move(playerPatch); } PostMessageW(window, sceneReadyMessage, 0, 0); } }); } +void requestLiveRender(AppState& state, bool fullRender) +{ + state.renderRequested = true; + state.renderFullRequested = state.renderFullRequested || fullRender; + ++state.renderGeneration; + state.renderWake.notify_one(); +} + void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLORREF color, HFONT font) { const int saved = SaveDC(device); @@ -725,76 +816,6 @@ void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLOR RestoreDC(device, saved); } -void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight, - int sourceLeft, int sourceTop, std::size_t viewStride) -{ - const remorse::AnimationClip* clip = nullptr; - if (state.playerAnimation == 1 && state.walkAnimation) { - clip = &*state.walkAnimation; - } else if (state.playerAnimation == 3 && state.runAnimation) { - clip = &*state.runAnimation; - } else if (state.standAnimation) { - clip = &*state.standAnimation; - } - if (!clip || state.playerFrames.empty()) { - return; - } - - const remorse::u8 frameIndex = state.playerAnimation == 0 ? 0 : state.playerFrame; - const auto metadata = remorse::getAnimationFrame(*clip, state.playerDirection, frameIndex); - if (!metadata) { - return; - } - const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata); - if (shapeFrame >= state.playerFrames.size() || !state.playerFrames[shapeFrame]) { - return; - } - - const remorse::DecodedShapeFrame& sprite = *state.playerFrames[shapeFrame]; - const auto avatarScreen = remorse::projectToScreen(avatarWorld(state)); - const int actorX = avatarScreen.x - state.scene->sourceLeft - sourceLeft; - const int actorY = avatarScreen.y - state.scene->sourceTop - sourceTop; - const int spriteLeft = actorX + sprite.frame.xOffset; - const int spriteTop = actorY + sprite.frame.yOffset; - const bool flipped = remorse::isAnimationFrameFlipped(*metadata); - - for (remorse::u32 y = 0; y < sprite.frame.height; ++y) { - const int destinationY = spriteTop + static_cast(y); - if (destinationY < 0 || destinationY >= viewHeight) { - continue; - } - for (remorse::u32 x = 0; x < sprite.frame.width; ++x) { - const int destinationX = spriteLeft + static_cast(x); - if (destinationX < 0 || destinationX >= viewWidth) { - continue; - } - const remorse::u32 sourceX = flipped ? sprite.frame.width - 1 - x : x; - const remorse::s16 paletteIndex = sprite.pixels[ - static_cast(y) * sprite.frame.width + sourceX]; - if (paletteIndex < 0) { - continue; - } - const remorse::RgbColor& color = state.playerPalette.colors[ - static_cast(paletteIndex)]; - const std::size_t pixelOffset = static_cast(destinationY) * viewStride + - static_cast(destinationX) * 3; - state.viewPixels[pixelOffset] = static_cast(color.blue * 255 / 63); - state.viewPixels[pixelOffset + 1] = static_cast(color.green * 255 / 63); - state.viewPixels[pixelOffset + 2] = static_cast(color.red * 255 / 63); - } - } - - BITMAPINFO bitmap{}; - bitmap.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); - bitmap.bmiHeader.biWidth = viewWidth; - bitmap.bmiHeader.biHeight = -viewHeight; - bitmap.bmiHeader.biPlanes = 1; - bitmap.bmiHeader.biBitCount = 24; - bitmap.bmiHeader.biCompression = BI_RGB; - StretchDIBits(device, 0, 0, viewWidth, viewHeight, 0, 0, viewWidth, viewHeight, - state.viewPixels.data(), &bitmap, DIB_RGB_COLORS, SRCCOPY); -} - void drawLoadingScreen(HDC device, const RECT& client, const AppState& state) { HBRUSH background = CreateSolidBrush(RGB(13, 23, 28)); @@ -885,6 +906,9 @@ void paintWindow(HWND window, AppState& state) const int centeredTop = avatarScreen.y - state.scene->sourceTop - viewHeight / 2; const int sourceLeft = std::clamp(centeredLeft, 0, static_cast(state.scene->width) - viewWidth); const int sourceTop = std::clamp(centeredTop, 0, static_cast(state.scene->height) - viewHeight); + if ((sourceLeft != centeredLeft || sourceTop != centeredTop) && state.renderThread.joinable()) { + requestLiveRender(state, true); + } const std::size_t viewStride = (static_cast(viewWidth) * 3 + 3) & ~std::size_t(3); state.viewPixels.resize(viewStride * static_cast(viewHeight)); @@ -896,7 +920,43 @@ void paintWindow(HWND window, AppState& state) std::memcpy(state.viewPixels.data() + viewOffset, state.dibPixels.data() + sceneOffset, static_cast(viewWidth) * 3); } - compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride); + if (state.playerPatch) { + const remorse::RenderedMapImage& patch = *state.playerPatch; + const int patchLeft = patch.sourceLeft - (state.scene->sourceLeft + sourceLeft); + const int patchTop = patch.sourceTop - (state.scene->sourceTop + sourceTop); + for (int patchY = 0; patchY < static_cast(patch.height); ++patchY) { + const int destY = patchTop + patchY; + if (destY < 0 || destY >= viewHeight) { + continue; + } + for (int patchX = 0; patchX < static_cast(patch.width); ++patchX) { + const int destX = patchLeft + patchX; + if (destX < 0 || destX >= viewWidth) { + continue; + } + const std::size_t sourceIndex = static_cast(patchY) * patch.width + patchX; + if (patch.coverage[sourceIndex] == 0) { + continue; + } + const remorse::RgbColor& color = patch.pixels[sourceIndex]; + const std::size_t destIndex = static_cast(destY) * viewStride + + static_cast(destX) * 3; + state.viewPixels[destIndex] = color.blue; + state.viewPixels[destIndex + 1] = color.green; + state.viewPixels[destIndex + 2] = color.red; + } + } + } + BITMAPINFO bitmapInfo{}; + bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + bitmapInfo.bmiHeader.biWidth = viewWidth; + bitmapInfo.bmiHeader.biHeight = -viewHeight; + bitmapInfo.bmiHeader.biPlanes = 1; + bitmapInfo.bmiHeader.biBitCount = 24; + bitmapInfo.bmiHeader.biCompression = BI_RGB; + bitmapInfo.bmiHeader.biSizeImage = static_cast(state.viewPixels.size()); + StretchDIBits(device, 0, 0, viewWidth, viewHeight, 0, 0, viewWidth, viewHeight, + state.viewPixels.data(), &bitmapInfo, DIB_RGB_COLORS, SRCCOPY); if (!state.diagnostics) { finishPaint(); return; @@ -1069,6 +1129,7 @@ void updatePlayer(HWND window, AppState& state) } changed = changed || state.diagnostics || gravityMoved; if (movement.animation == 0) { + const bool playerSpriteChanged = state.playerAnimation != 0 || state.playerFrame != 0; if (state.animationProcessId != 0) { auto* process = state.diagnosticKernel.processAt(state.animationProcessId); process->bytes[0x18] |= 4; @@ -1081,13 +1142,16 @@ void updatePlayer(HWND window, AppState& state) const bool usecodeMutation = state.usecodeWorldMutationPending; state.usecodeWorldMutationPending = false; changed = changed || usecodeMutation; - if (state.renderThread.joinable() && (gravityMoved || usecodeMutation)) { - state.renderRequested = true; - state.renderWake.notify_one(); + if (state.renderThread.joinable() && + (gravityMoved || usecodeMutation || playerSpriteChanged)) { + requestLiveRender(state, gravityMoved || usecodeMutation); } continue; } + const remorse::u8 previousPlayerAnimation = state.playerAnimation; + const remorse::u8 previousPlayerDirection = state.playerDirection; + const remorse::u8 previousPlayerFrame = state.playerFrame; const remorse::u8 requestedAnimation = movement.animation; const remorse::AnimationClip& clip = requestedAnimation == 1 ? *state.walkAnimation : *state.runAnimation; @@ -1135,9 +1199,11 @@ void updatePlayer(HWND window, AppState& state) *state.liveItems, *state.renderer, remorse::calculateFastAreaRange(avatarWorld(state))); const bool usecodeMutation = state.usecodeWorldMutationPending; state.usecodeWorldMutationPending = false; - if (state.renderThread.joinable() && (moved || hatched || usecodeMutation || gravityMoved)) { - state.renderRequested = true; - state.renderWake.notify_one(); + const bool playerSpriteChanged = state.playerAnimation != previousPlayerAnimation || + state.playerDirection != previousPlayerDirection || state.playerFrame != previousPlayerFrame; + if (state.renderThread.joinable() && + (moved || hatched || usecodeMutation || gravityMoved || playerSpriteChanged)) { + requestLiveRender(state, hatched || usecodeMutation || gravityMoved); } changed = true; } @@ -1172,7 +1238,10 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA return 0; case WM_KILLFOCUS: state->controllerMovement.clear(); - while (state->diagnosticKernel.popPendingKeyEvent()) {} + { + std::lock_guard lock(state->kernelMutex); + while (state->diagnosticKernel.popPendingKeyEvent()) {} + } return 0; case WM_KEYDOWN: case WM_KEYUP: @@ -1204,6 +1273,7 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA if (GetKeyState(VK_LSHIFT) & 0x8000) event.modifiers |= 1; if (GetKeyState(VK_RSHIFT) & 0x8000) event.modifiers |= 2; event.field8 = message == WM_KEYDOWN ? 1 : 0; + std::lock_guard lock(state->kernelMutex); state->diagnosticKernel.queuePendingKeyEvent(event); } if (message == WM_KEYUP) return 0; @@ -1290,19 +1360,78 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo remorse::installCrashDiagnostics(); remorse::u32 mapIndex = 1; bool diagnostics = false; - std::wistringstream arguments(commandLine ? commandLine : L""); + std::optional warpStart; + constexpr std::array missionBaseMaps{ + 0, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 40}; + std::wistringstream argumentStream(commandLine ? commandLine : L""); + std::vector arguments; std::wstring argument; - while (arguments >> argument) { - if (argument == L"--diagnostics") { + while (argumentStream >> argument) { + arguments.push_back(argument); + } + const auto parseInteger = [](const std::wstring& text, long minimum, long maximum, long& value) { + wchar_t* end = nullptr; + const long parsed = std::wcstol(text.c_str(), &end, 0); + if (end == text.c_str() || *end != L'\0' || parsed < minimum || parsed > maximum) { + return false; + } + value = parsed; + return true; + }; + long warpMission = 0; + long mapOffset = 0; + bool warpRequested = false; + bool invalidArguments = false; + for (std::size_t index = 0; index < arguments.size(); ++index) { + const std::wstring& current = arguments[index]; + if (current == L"--diagnostics") { diagnostics = true; + } else if (current == L"-warp") { + long x = 0; + long y = 0; + long z = 0; + if (warpRequested || index + 4 >= arguments.size() || + !parseInteger(arguments[index + 1], 0, + static_cast(missionBaseMaps.size() - 1), warpMission) || + !parseInteger(arguments[index + 2], 0, 0x7fff, x) || + !parseInteger(arguments[index + 3], 0, 0x7fff, y) || + !parseInteger(arguments[index + 4], 0, 0xff, z)) { + invalidArguments = true; + break; + } + warpStart = WarpStart{static_cast(x), + static_cast(y), static_cast(z)}; + warpRequested = true; + index += 4; + } else if (current == L"-mapoff") { + if (index + 1 >= arguments.size() || + !parseInteger(arguments[index + 1], -255, 255, mapOffset)) { + invalidArguments = true; + break; + } + ++index; } else { - wchar_t* end = nullptr; - const unsigned long parsed = std::wcstoul(argument.c_str(), &end, 0); - if (end != argument.c_str() && *end == L'\0' && parsed <= 255) { + long parsed = 0; + if (parseInteger(current, 0, 255, parsed)) { mapIndex = static_cast(parsed); } } } + if (warpRequested) { + const long targetMap = missionBaseMaps[static_cast(warpMission)] + mapOffset; + if (targetMap < 0 || targetMap > 255) { + invalidArguments = true; + } else { + mapIndex = static_cast(targetMap); + } + } + if (invalidArguments) { + MessageBoxW(nullptr, + L"Usage: remorse_game.exe -warp [-mapoff ]\n" + L"Mission must be 0..16, map 0..255, X/Y 0..32767, and Z 0..255.", + L"Invalid warp arguments", MB_OK | MB_ICONERROR); + return 2; + } wchar_t executablePath[MAX_PATH]{}; GetModuleFileNameW(nullptr, executablePath, MAX_PATH); @@ -1321,6 +1450,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo state.root = *root; state.mapIndex = mapIndex; state.diagnostics = diagnostics; + state.warpStart = warpStart; for (int index = 0; index < 3; ++index) { state.diagnosticKernel.createProcess(1, state.diagnosticGroupCounts); } @@ -1348,8 +1478,16 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo RECT bounds{0, 0, initialClientWidth, initialClientHeight}; AdjustWindowRect(&bounds, WS_OVERLAPPEDWINDOW, FALSE); - HWND window = CreateWindowExW(0, windowClassName, - diagnostics ? L"Crusader: No Remorse | Diagnostics" : L"Crusader: No Remorse | Traversal Test", + std::wstring windowTitle = diagnostics + ? L"Crusader: No Remorse | Diagnostics" : L"Crusader: No Remorse | Traversal Test"; + if (state.warpStart) { + std::wostringstream title; + title << L"Crusader: No Remorse | Warp map " << state.mapIndex << L" (" + << state.warpStart->x << L", " << state.warpStart->y << L", " + << static_cast(state.warpStart->z) << L")"; + windowTitle = title.str(); + } + HWND window = CreateWindowExW(0, windowClassName, windowTitle.c_str(), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, bounds.right - bounds.left, bounds.bottom - bounds.top, nullptr, nullptr, instance, &state); diff --git a/rebuild/remorse/tests/flex_archive_tests.cpp b/rebuild/remorse/tests/flex_archive_tests.cpp index 40b4316..1467dff 100644 --- a/rebuild/remorse/tests/flex_archive_tests.cpp +++ b/rebuild/remorse/tests/flex_archive_tests.cpp @@ -250,14 +250,27 @@ int main() for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { teleporterKernel.createProcess(1, teleporterGroups); } + auto* startupTimer = teleporterKernel.createSystemTimerProcess(1, teleporterGroups); + auto* startupKeyboard = teleporterKernel.createKeyboardProcess(1, teleporterGroups); + auto* startupController = teleporterKernel.createControllerProcess(1, teleporterGroups); + assert(startupTimer && startupKeyboard && startupController); + const auto processIdOf = [](const auto& process) { + return static_cast(process->base.bytes[2] | + (static_cast(process->base.bytes[3]) << 8)); + }; + const remorse::u16 startupTimerId = processIdOf(startupTimer); + const remorse::u16 startupKeyboardId = processIdOf(startupKeyboard); + const remorse::u16 startupControllerId = processIdOf(startupController); bool avatarInStasis = false; auto* teleporterProcess = teleporterKernel.createTeleporterProcess(1, 1, 0x1e, teleporterGroups, true, false, avatarInStasis); const remorse::u16 teleporterProcessId = static_cast( teleporterProcess->base.bytes[2] | (static_cast(teleporterProcess->base.bytes[3]) << 8)); - assert(avatarInStasis && teleporterKernel.allocationSizeAt(4) == 0x33 && - teleporterKernel.processAt(4)->bytes[0] == 0x5e && - teleporterKernel.processAt(4)->bytes[1] == 0x0f); + const remorse::u16 clearStasisProcessId = static_cast(teleporterProcessId + 1); + assert(avatarInStasis && clearStasisProcessId > startupControllerId && + teleporterKernel.allocationSizeAt(clearStasisProcessId) == 0x33 && + teleporterKernel.processAt(clearStasisProcessId)->bytes[0] == 0x5e && + teleporterKernel.processAt(clearStasisProcessId)->bytes[1] == 0x0f); assert(!remorse::TeleporterProcess::run(*teleporterProcess, spawnSearchWorld, 2, *typeFlags)); assert(spawnSearchWorld.findItem(1)->data.x == 0 && spawnSearchWorld.findItem(1)->data.y == 0); struct TeleporterPassContext { @@ -288,12 +301,19 @@ int main() }; teleporterKernel.scanRunnableProcesses(1, runTeleporterPass, &teleporterPass); assert(!avatarInStasis && !teleporterPass.teleported && + teleporterKernel.processAt(startupTimerId) == &startupTimer->base && + teleporterKernel.processAt(startupKeyboardId) == &startupKeyboard->base && + teleporterKernel.processAt(startupControllerId) == &startupController->base && + teleporterKernel.processAt(clearStasisProcessId) == nullptr && teleporterKernel.processAt(teleporterProcessId) == &teleporterProcess->base && spawnSearchWorld.findItem(1)->data.x == 0 && spawnSearchWorld.findItem(1)->data.y == 0); teleporterKernel.scanRunnableProcesses(1, runTeleporterPass, &teleporterPass); assert(teleporterPass.teleported); assert(teleporterKernel.processAt(teleporterProcessId) == nullptr && - teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 3); + teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 6 && + teleporterKernel.processAt(startupTimerId) == &startupTimer->base && + teleporterKernel.processAt(startupKeyboardId) == &startupKeyboard->base && + teleporterKernel.processAt(startupControllerId) == &startupController->base); assert(spawnEgg->recordIndex < fixedMap->entries.size()); const auto& startingEggRecord = fixedMap->entries[spawnEgg->recordIndex]; const auto* spawnedAvatar = spawnSearchWorld.findItem(1); @@ -302,6 +322,44 @@ int main() assert(spawnedAvatar && spawnedAvatar->itemNumber == 1 && spawnedAvatar->data.x == spawnEgg->data.x && spawnedAvatar->data.y == spawnEgg->data.y && spawnedAvatar->data.z == spawnEgg->data.z && spawnedAvatar->data.mapNumber == 1); + remorse::LiveFixedMapItems integratedStartupWorld(*stagedItems); + assert(integratedStartupWorld.initializeAvatar()); + remorse::ProcessKernel integratedStartupKernel; + remorse::u16 integratedStartupGroups[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + integratedStartupKernel.createProcess(1, integratedStartupGroups); + } + auto* integratedTimer = integratedStartupKernel.createSystemTimerProcess(1, integratedStartupGroups); + auto* integratedKeyboard = integratedStartupKernel.createKeyboardProcess(1, integratedStartupGroups); + auto* integratedController = integratedStartupKernel.createControllerProcess(1, integratedStartupGroups); + assert(remorse::runFreshGameTeleporterStartup(integratedStartupKernel, integratedStartupWorld, + 1, 0x1e, *typeFlags, integratedStartupGroups)); + const auto* integratedAvatar = integratedStartupWorld.findItem(1); + assert(integratedTimer && integratedKeyboard && integratedController && integratedAvatar && + integratedAvatar->data.x == spawnEgg->data.x && integratedAvatar->data.y == spawnEgg->data.y && + integratedAvatar->data.mapNumber == 1 && integratedStartupGroups[1] == 6 && + integratedStartupKernel.processAt(processIdOf(integratedTimer)) == &integratedTimer->base && + integratedStartupKernel.processAt(processIdOf(integratedKeyboard)) == &integratedKeyboard->base && + integratedStartupKernel.processAt(processIdOf(integratedController)) == &integratedController->base); + const auto stagingTeleporter = remorse::findNearbyActiveTeleportEgg(*integratedAvatar, + integratedStartupWorld.mapItems(), *typeFlags, 1); + const auto levelStartEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x63); + assert(stagingTeleporter && stagingTeleporter->itemNumber == 1598 && + stagingTeleporter->data.shape == 0x0194 && stagingTeleporter->data.frame == 0 && + stagingTeleporter->data.quality == 0x0063 && stagingTeleporter->data.mapNumber == 1 && + levelStartEgg && levelStartEgg->itemNumber == 6812 && levelStartEgg->data.x == 30328 && + levelStartEgg->data.y == 29656 && levelStartEgg->data.z == 16); + assert(remorse::runFreshGameTeleporterStartup(integratedStartupKernel, integratedStartupWorld, + stagingTeleporter->data.mapNumber, + static_cast(stagingTeleporter->data.quality & 0xff), *typeFlags, + integratedStartupGroups)); + integratedAvatar = integratedStartupWorld.findItem(1); + assert(integratedAvatar && integratedAvatar->data.x == levelStartEgg->data.x && + integratedAvatar->data.y == levelStartEgg->data.y && integratedAvatar->data.z == levelStartEgg->data.z && + integratedAvatar->data.mapNumber == 1 && integratedStartupGroups[1] == 6 && + integratedStartupKernel.processAt(processIdOf(integratedTimer)) == &integratedTimer->base && + integratedStartupKernel.processAt(processIdOf(integratedKeyboard)) == &integratedKeyboard->base && + integratedStartupKernel.processAt(processIdOf(integratedController)) == &integratedController->base); const auto spawnUseCandidates = remorse::itemGrabSearchCandidates( *spawnedAvatar, spawnSearchWorld.mapItems(), *typeFlags); assert(spawnUseCandidates); diff --git a/rebuild/remorse/tests/map_renderer_tests.cpp b/rebuild/remorse/tests/map_renderer_tests.cpp index d4197da..7ae8fbf 100644 --- a/rebuild/remorse/tests/map_renderer_tests.cpp +++ b/rebuild/remorse/tests/map_renderer_tests.cpp @@ -3,6 +3,7 @@ #include "remorse/fixed_map.h" #include "remorse/glob_archive.h" #include "remorse/map_renderer.h" +#include "remorse/shape_archive.h" #include "remorse/type_flags.h" #include @@ -80,6 +81,31 @@ int main() remorse::LiveFixedMapItems liveSceneItems(*stagedItems); auto cachedRenderer = remorse::loadMapSceneRenderer(*root, 1); assert(cachedRenderer); + const auto shape60Item = std::find_if(stagedItems->begin(), stagedItems->end(), [](const auto& item) { + return item.data.shape == 0x003c; + }); + assert(shape60Item != stagedItems->end()); + const auto shape60Frame = remorse::decodeShapeFrame(cachedRenderer->shapes, 0x003c, + shape60Item->data.frame); + assert(shape60Frame && std::any_of(shape60Frame->pixels.begin(), shape60Frame->pixels.end(), + [](remorse::s16 color) { return color >= 0; })); + assert(((*shapeTypes)[0x003c].flags & 0x400) != 0); + remorse::MapSceneRenderer isolatedShape60 = *cachedRenderer; + isolatedShape60.map.entries = {fixedMap->entries[shape60Item->recordIndex]}; + remorse::MapRenderOptions shape60Options; + shape60Options.mapIndex = 1; + shape60Options.maxWidth = 320; + shape60Options.maxHeight = 200; + shape60Options.includeHiddenMarkers = true; + shape60Options.viewCenter = remorse::WorldPoint{ + static_cast(fixedMap->entries[shape60Item->recordIndex].x), + static_cast(fixedMap->entries[shape60Item->recordIndex].y), + fixedMap->entries[shape60Item->recordIndex].z}; + assert(!isolatedShape60.render(shape60Options)); + shape60Options.includeRoofs = true; + const auto isolatedShape60Image = isolatedShape60.render(shape60Options); + assert(isolatedShape60Image && isolatedShape60Image->renderItemCount == 1 && + isolatedShape60Image->decodedItemCount == 1 && isolatedShape60Image->paintedItemCount == 1); const auto liveBefore = cachedRenderer->render(options, &liveSceneItems); const auto samePixels = [](const auto& left, const auto& right) { return left.size() == right.size() && std::equal(left.begin(), left.end(), right.begin(), @@ -88,6 +114,57 @@ int main() }); }; assert(liveBefore && samePixels(liveBefore->pixels, startingScene->pixels)); + const auto playerFrame = remorse::decodeShapeFrame(cachedRenderer->shapes, 1, 0); + assert(playerFrame); + const remorse::MapRenderSprite playerSprite{spawn, 1, 0, false, + &*playerFrame, &cachedRenderer->palette}; + const auto sceneWithPlayer = cachedRenderer->render(options, &liveSceneItems, &playerSprite); + assert(sceneWithPlayer && sceneWithPlayer->renderItemCount == liveBefore->renderItemCount + 1 && + !samePixels(sceneWithPlayer->pixels, liveBefore->pixels)); + assert(sceneWithPlayer->coverage.size() == sceneWithPlayer->pixels.size() && + std::any_of(sceneWithPlayer->coverage.begin(), sceneWithPlayer->coverage.end(), + [](remorse::u8 covered) { return covered != 0; })); + remorse::MapRenderOptions fullPlayerReferenceOptions = options; + fullPlayerReferenceOptions.maxWidth = 512; + fullPlayerReferenceOptions.maxHeight = 384; + const auto fullPlayerReference = cachedRenderer->render( + fullPlayerReferenceOptions, &liveSceneItems, &playerSprite); + assert(fullPlayerReference); + remorse::MapRenderOptions playerPatchOptions = fullPlayerReferenceOptions; + playerPatchOptions.worldRect = remorse::WorldRect{ + spawn.x - 2048, spawn.y - 2048, spawn.x + 2048, spawn.y + 2048}; + const auto playerPatch = cachedRenderer->render(playerPatchOptions, &liveSceneItems, &playerSprite); + assert(playerPatch && playerPatch->sourceLeft == fullPlayerReference->sourceLeft && + playerPatch->sourceTop == fullPlayerReference->sourceTop); + for (std::size_t index = 0; index < playerPatch->coverage.size(); ++index) { + if (playerPatch->coverage[index] != 0) { + assert(playerPatch->pixels[index].red == fullPlayerReference->pixels[index].red && + playerPatch->pixels[index].green == fullPlayerReference->pixels[index].green && + playerPatch->pixels[index].blue == fullPlayerReference->pixels[index].blue); + } + } + const remorse::WorldPoint warpPosition{30463 * 2, 29951 * 2, 0}; + const remorse::MapRenderSprite warpPlayer{warpPosition, 1, 0, false, + &*playerFrame, &cachedRenderer->palette}; + remorse::MapRenderOptions warpReferenceOptions = fullPlayerReferenceOptions; + warpReferenceOptions.includeRoofs = true; + warpReferenceOptions.viewCenter = warpPosition; + const auto warpReference = cachedRenderer->render(warpReferenceOptions, nullptr, &warpPlayer); + assert(warpReference); + remorse::MapRenderOptions warpPatchOptions = warpReferenceOptions; + warpPatchOptions.worldRect = remorse::WorldRect{ + warpPosition.x - 2560, warpPosition.y - 2560, + warpPosition.x + 2560, warpPosition.y + 2560}; + const auto warpPatch = cachedRenderer->render(warpPatchOptions, nullptr, &warpPlayer); + assert(warpPatch && warpPatch->sourceLeft == warpReference->sourceLeft && + warpPatch->sourceTop == warpReference->sourceTop); + for (std::size_t index = 0; index < warpPatch->coverage.size(); ++index) { + if (warpPatch->coverage[index] != 0) { + assert(warpPatch->pixels[index].red == warpReference->pixels[index].red && + warpPatch->pixels[index].green == warpReference->pixels[index].green && + warpPatch->pixels[index].blue == warpReference->pixels[index].blue); + } + } const remorse::s32 redrawRadius = static_cast( options.maxWidth + options.maxHeight * 2 + 512); options.worldRect = remorse::WorldRect{spawn.x - redrawRadius, spawn.y - redrawRadius, diff --git a/rebuild/remorse/tests/map_sorter_tests.cpp b/rebuild/remorse/tests/map_sorter_tests.cpp index 2c1e00c..32133b4 100644 --- a/rebuild/remorse/tests/map_sorter_tests.cpp +++ b/rebuild/remorse/tests/map_sorter_tests.cpp @@ -49,6 +49,28 @@ int main() assert(order[0] == 1); assert(order[1] == 0); + remorse::detail::RenderSortItem occluder = elevated; + occluder.occludes = true; + const std::vector occludedPlayerItems{occluder, ground}; + const std::vector occludedPlayerOrder = + remorse::detail::resolveRenderOrder(occludedPlayerItems); + assert(occludedPlayerOrder.size() == 1 && occludedPlayerOrder[0] == 0); + + remorse::detail::RenderSortItem boundaryOccluder = occluder; + boundaryOccluder.left = 120; + boundaryOccluder.top = 120; + boundaryOccluder.right = 184; + boundaryOccluder.bottom = 184; + remorse::detail::RenderSortItem boundaryPlayer = ground; + boundaryPlayer.left = 128; + boundaryPlayer.top = 128; + boundaryPlayer.right = 160; + boundaryPlayer.bottom = 160; + const std::vector boundaryItems{ + boundaryOccluder, boundaryPlayer}; + const std::vector boundaryOrder = remorse::detail::resolveRenderOrder(boundaryItems); + assert(boundaryOrder.size() == 1 && boundaryOrder[0] == 0); + remorse::detail::RenderSortItem animatedFlat = elevated; animatedFlat.x = 64; animatedFlat.xLeft = 64; From a76b071049c776f9384d859790ecff33e59ffb4d Mon Sep 17 00:00:00 2001 From: Maddo Date: Wed, 7 Oct 2026 00:18:08 +0200 Subject: [PATCH 13/14] Enhance animation and control tests; improve rendering and shape loading validation - Added tests for player animations in animation_archive_tests to ensure all animations are loaded correctly. - Updated entity_dispatch_entry_tests to validate animation direction updates and added tests for sixteen-direction animations. - Expanded isometric_controls_tests with comprehensive key event handling and action requests for various controller states. - Improved map_renderer_tests by adding viewport rendering tests to compare unbounded and bounded views. - Enhanced shape_archive_tests to validate shape frame loading and decoding consistency. --- .github/copilot-instructions.md | 2 +- .../shell-operations.instructions.md | 14 +- .../idata/01/~00000015.db/change.data.gbf | Bin 147456 -> 147456 bytes .../idata/01/~00000015.db/change.map.gbf | Bin 32768 -> 32768 bytes .../~00000015.db/{db.133.gbf => db.135.gbf} | Bin 24461312 -> 24461312 bytes Crusader.rep/projectState | 319 +++++++++++++++- .../00/~00000008.db/{db.61.gbf => db.68.gbf} | Bin 81920 -> 81920 bytes .../00/~00000008.db/{db.62.gbf => db.69.gbf} | Bin 81920 -> 81920 bytes build_output.txt | 67 ++++ docs/pentagram-rendering-comparison.md | 86 +++++ docs/remorse-windows-rebuild-roadmap.md | 27 +- docs/scummvm-rendering-comparison.md | 86 +++++ play-remorse-rebuild.bat | 17 + py_mcp_query.py | 28 ++ .../include/remorse/entity_dispatch_entry.h | 2 + rebuild/remorse/include/remorse/fixed_map.h | 1 + .../include/remorse/isometric_controls.h | 344 ++++++++++++++++- .../remorse/include/remorse/shape_archive.h | 1 + rebuild/remorse/src/entity_dispatch_entry.cpp | 37 +- rebuild/remorse/src/fixed_map.cpp | 1 + rebuild/remorse/src/map_renderer.cpp | 44 ++- rebuild/remorse/src/shape_archive.cpp | 20 +- rebuild/remorse/src/windowed_game_main.cpp | 351 ++++++++++++------ .../remorse/tests/animation_archive_tests.cpp | 23 +- .../tests/entity_dispatch_entry_tests.cpp | 24 ++ .../tests/isometric_controls_tests.cpp | 250 ++++++++++++- rebuild/remorse/tests/map_renderer_tests.cpp | 16 + rebuild/remorse/tests/shape_archive_tests.cpp | 4 + 28 files changed, 1609 insertions(+), 155 deletions(-) rename Crusader.rep/idata/01/~00000015.db/{db.133.gbf => db.135.gbf} (99%) rename Crusader.rep/user/00/~00000008.db/{db.61.gbf => db.68.gbf} (99%) rename Crusader.rep/user/00/~00000008.db/{db.62.gbf => db.69.gbf} (99%) create mode 100644 build_output.txt create mode 100644 docs/pentagram-rendering-comparison.md create mode 100644 docs/scummvm-rendering-comparison.md create mode 100644 play-remorse-rebuild.bat create mode 100644 py_mcp_query.py diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 135c749..a25908f 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -18,4 +18,4 @@ applyTo: '**' - Keep read-only analysis separate from any explicit writable workflow. - For authored map-placement or link investigation in Crusader-Map-Viewer, prefer decompressed `.cache/scene-cache//map-*//scene.json` over `site/data`; the cache scenes preserve direct item objects and world coordinates. - Never write documentation into `k:\ghidra\crusader_map_viewer` unless the user explicitly asks for documentation changes in that repo. -- If the shell becomes stuck on multiline input or otherwise unhealthy, you could try to press esc in the shell to see if it gets unstuck, otherwise immediately use `vscode_askQuestions` to ask the user to fix the terminal state, then continue the task once the user confirms it is fixed. \ No newline at end of file +- If the shell becomes stuck on multiline input or otherwise unhealthy, you could try to press esc in the shell to see if it gets unstuck, otherwise immediately use `vscode_askQuestions` to ask the user to fix the terminal state, then continue the task once the user confirms it is fixed. diff --git a/.github/instructions/shell-operations.instructions.md b/.github/instructions/shell-operations.instructions.md index 20ad90f..29c3049 100644 --- a/.github/instructions/shell-operations.instructions.md +++ b/.github/instructions/shell-operations.instructions.md @@ -43,4 +43,16 @@ Use these rules when running shell commands from this workspace. - Prefer explicit PowerShell cmdlets over aliases in reusable commands. - Avoid commands that rely on interactive input. - Prefer one focused command per terminal invocation so failures are easier to attribute. -- When posting HTTP form data from PowerShell, prefer compact one-line request bodies over multiline literal blocks in the shared shell. \ No newline at end of file +- When posting HTTP form data from PowerShell, prefer compact one-line request bodies over multiline literal blocks in the shared shell. + +# GitHub Copilot Instructions for PowerShell + +**Environment:** I am using **Windows** and all terminal commands *must* be compatible with **PowerShell** (or **PowerShell Core/PS7**). + +**CRITICAL COMMAND SYNTAX:** +* **NEVER** use `&&` for command chaining. +* **ALWAYS** use the **semicolon (`;`)** for chaining or separating multiple commands on a single line. + * **Good Example:** `npm install; npm start` + * **Bad Example (Avoid):** `npm install && npm start` +* Prefer built-in PowerShell cmdlets (e.g., `Get-ChildItem` instead of `ls` or `dir`) whenever possible, or use common aliases like `ls` if they are working. +* Use Windows-style backslashes for paths and quote paths with spaces. \ No newline at end of file diff --git a/Crusader.rep/idata/01/~00000015.db/change.data.gbf b/Crusader.rep/idata/01/~00000015.db/change.data.gbf index dc747b1a0f769e1ba03e52c6355c81a8d8d52d59..9935711d7e25ca38d6d68f043b0085c4e576f46a 100644 GIT binary patch literal 147456 zcmeI5ca&Du+4j$V+6*xB%$Y)OTSWyyK~TXCf(jNa*ei%A8j8UNiVB+8qd@F+>{zi! zV?&KPc4F_MSVm0@Z+!DQi7~$SIrs0*`z=@2`+a|9W#zl~TI_3n*S(+T+50;C?3obH zFm%|4LpB;TWWBb+laEe}8*Z5-Nl22>$q&-xYj2)_C*TQq0-k^;;0bsFo`5Id33vjY zfG6Mycmke)C*TQq0-k^;;0bsFo`5Id33vjYfG6Mycmke)C*TQq0-k^;;0bsFo`5Id z33vjYfG6Mycmke)C*TQq0-k^;;0bsFo`5Id33vjYfG6T4t zQ_jETpY_T9Ii7$g;0bsFo`5Id33vjYfG6Mycmke)C*TQq0-k^;;0bsFo`5Id33vjY zfG6Mycmke)C*TQq0-k^;;0bsFo`5Id33vjYfG6Mycmke)C*TQq0-k^;;0bsFo`5Id z33vjYfG6Mycmke)CqM!rd-T8Z1MPoe+4@2IS_W)=yg@-=q(L!Bw)(R{N#GuXvcOCO zS5Lqb@B};oPrwuK1Uvyxz!UHUJONL@6YvB)0Z+ga@B};oPrwuK1Uvyxz!UHUJONL@ z6YvB)0Z+ga@B};oPrwuK1Uvyxz!UHUJONL@6YvB)0Z+ga@B};oPrwuK1Uvyxz!UHU zJb{131RBO1dgz>KM;{%>PMJx{q;#dd2RNmY3!6^rX4*<;>OlEaVYQ24*hAIH!}a@;3n#uz|GX{*CMn~x8ID=mHJ%9cZ27_-Qg499`K29Pk27ui~NmyQ$LA% zAL_<^sh>=}A9dsY)K8%vsT*Uvcmke)C*TQq0-k^;;0bsFo`5Id33vjYfG6Mycmke) zC*TQq0-k^;;0bsFo`5Id33vjYfG6Mycmke)C*TQq0-k^;;0bsFo`5Id33vjYfG6My zcmke)C*TQq0-k^;;0bsFo`5Id3HO;^gLi`K;ho_sJP~eycY#xQSGW=04Q_&WhnwL^a0|Q#+!fvv?gsA#cZc_ed%*j^ zJ>h-fUhsZ!Z+L&W4}1XJ7d{Z~2Ok8xcmke)C*TQq0-k^;;0bsFo`5Id33vjYfG6My zcmke)C*TQq0-k^;;0bsFo`5Id33vjYfG6Mycmke)C*TQq0-k^;;0bsFo`5Id33vjY zfG6Mycmke)C*TQq0-k^;;0bsFo`5Id3H-|?P?l%=!~6gE`TsO9U7r6>d9L4{|4(@i zKjHcRl;`df#-%)WpYZ&D%5(Gy&;O@9H=pqQf68<53D5thJm;S9{C^sm51(7N2F&yS z>6$R}NY{dyN8LIw&;O@`V4nX^*MoWfzqAR=yh|ftp8qe6f>}ptQ<&%fOPj+y|6key zW}T%iVV?gVG8*Rj{~`AK7I^-@&X`>4?DsG5{C}PO{so@@ue0Bm!1Mog_WKd~>*wrb zzYih8_WKaXwa%Da>+JU*kZYa&zJme!`jY*=g0+?F?Dr3ld!7CMfpxV$(0Cx@4^~aM zE_H{%T$h2<;K8Z`XTn2N>*mAjs}5NRZ=gEhba*Iy20To)?reBN_#Ak+>X3`z5!A1P zH$rbfH%4zl*+(T~+eb^Ovyb8}F#9Op4sWI!?||7?aT(0Mig&{7t9Tc@m1?{j-Wt9K z9<5rsA0C4~fU@u66EOQOJ_)n$O2*r&AD^PW9ozbvp!*I@R2d>x)d{SBD=pk&PN{iu73`d+G~ zx8c22<2&#^)Q!21;=9!Mqi(#va{QF~0q|!q_g(2*nEPzNcQE(afWN|%QR6Af1HQ+% z`_OnQ^}kU+6g8ek{RjNRR7=K(E3ZvCnXX@yjgNp!7)Qc3;3sf}`V7^zYv7sGjb~A> zr9PXw@ln(}QU57*<2lqjQ$L!z@iEl9P(PNs@o~!a&D4)q4PD{6s^vcLJnF_LQ146q zMC!)#srRFP5_RK~;dQB>qB>?EyZ{~qb8ZIXQ>m{<{WR6Uxtsiq`ufy=4sQUT4s-4% zXTY4h$(bf@XK)MrxoTw-xE&q|e*td_e+h36f2CU80{$KKL*U=TQ(>-i zUKZ>8D31C zeOFlmv+pVw!tA@sMKJrWav99Nt6UDV?}~esI%{?*TN;$>UD5g zwQvJmQLPx)z&BE7-&U5w?Az+CF#EQ88_d3~E`!;(RnE7-zOCLxoqb!q8)n~D?VL{4 zuij6ceO!4MW*=7`ftyt;kHYNhD(9;GTvuIAy&K~nhr7d1z&+q6;hr$(YUrh0<=hOt zskbq{5Bx0L7k&=z2R{$@hhKmr%()rXfH^0^n(#{1uonCgJOKU}UK?HouLFMuuM2+; z4}`hz?dQ%4_kCE8I`@4TtX$x}wVy)^+^1oE>fEPc1DN|R428Mx!Z773_gUCbc{}c# zFkHET>kvl3zG195#W;HE_-iCf6`Z>x0QPaPAEzSNl15Fu4ZK!NKGj zw&3-HRKu1qxrMD@atm84*BFncK14N)p>Dhlb#e`3sT+@@PR?Ol>c-nqC-<;Db>s2M zBgrXDP#(*=!VWO&3OmBAE9|6P!@9!G)Qu;?qgBH$FzXDvD%Y@1`#E>4@$S@FcbLTM zjrX8V4q;E29PH=X8gdAGQzwV85ASEZFLiPW`%yREpE@~(17LCr2g2kO4uZ)k9IQNc zH`Op1W}RUQ%sRs%FzXCcVdfbQg_&oVrd-23!(r5o52wz&!*rN=ha;5NW!~XPUeCP4 zPvFU_VFt{+!%UcYhFQur%rneZF7m$ND46#RKjrntbExw<;b`i{$H07UI99pA_&8qA zJnVlLj5VIi>zP-W$LpC_I00r};Y8&w%qz^NZhR7T<{3_=ZhQ)L<{1`HH(p4cd52S} z8=t0JH2xXmk5>&pr_MUU=`iaEXE2_5hcjX39nON8cQ_kn-r*d0foeEcwZZro%3WAT zIFCB(2-bcTzXLi}xePa5r`1 zdth=6_rl~F?&I~Xs^Na>?hsfH)u=iw*e7vSH(FTqd2zlEQMUxA;2UxnM?*WhR2*J0+-@CM90 z8s3JPN5ebti>eLp!py7q9{e)(58)N?N|<>!d;~M^hL2(9-LMK~-VL9?%)9&NF!OHs z5`I&);Vbwp_;)btYWO|Ox*EQQSy#g!VAj>J8h&53;Tu)&JpoU^6YvB)0Z+ga@B};o zPrwuK1Uvyxz!UHUJONL@6YvB)0Z+ga@B};oPrwuK1Uvyxz!UHU{(Tdu6l87T$It(d zxW4zgC-!=U|IX&$clEw9PrwuK1Uvyxz!UHUJONL@6YvB)0Z+ga@B};oPrwuK1Uvyx zz!UHUJONL@6YvB)0Z+ga@B};oPrwuK1Uvyxz!UHUJONL@6YvB)0Z+ga@B};oPrwuK z1Uvyxz!UHUJONL@6YvB)0Z-sxBY_%u{y%*AuQKo`fD@WBL`VDwwsdQMxqQ=3`UAtaXdhrOCD@mk*|B|7=sito4l2 ziGQ1^VAgs?>C$AcM@$8?);mgoH%cddo2g*d`bFu) z|Hf1>YyG2iX|gXl?90EKlSK9RTVN`~vbIK)E=~61dhPd|VAj@*(ux0rsbJRDiqfUY z{;XsF-kB+FK$I>`4&eG9(2$wZ){fGNf2FBl*4ByArOAQJ_rU&{DQ(>-o%mOq3TAC! zlrBvUI>l5lYlEV6X>xF9Q^BmQ7o`(_ys2Q;21n_{Uv4UxwINZuG&zKQb;#_@l(v49 zE={J+G8N3)22r{+na2Gx?WD|A)J@*P@vzZETb-9TrYA70jBR%fpJ#M1fQ^Go@`Cr4!cuAex!dwu{oG z!%DiZMKe>{_EEZYRHN<-(ae;l`*>92_fbIV-)E*Yz24)Cmq&qAG&7~`5Tz5o)l@KR zJ4Wfmf5=oYYdb~h((#>jUZR;PZRaSR`0tqtW^H1WE*)R5*FiKhrR@@>6JK)@%}i;# zM(NUB%l%CSv$k85PJG?(qM0de_b8qCdVNJRQ`)2`UAj;0UrhzGru%7f_2np#ie{#? zJ)?B#JIpKUXv}rR^7` zOXr4)sbJRjkJ5>+`&~3Mr5zBZ6MvzpVAc+d(uv<@Dwwr{qIBZ_*;FuV2S@4Bxdpv0 zqM0d8@Bg_a=2NPuolJ@HMLL&#D2jgwzV4&Br5*66;va5`e<=KOQ~YW0HKzE7DVJ+Z z@p<3!ApAl2({o-_(DPUn{|NOv>-rXTo{WDa{xVbipXA)yV~i>O4CS7)P4QuAA=nrQLSNpM$TtF70+G{?WPr zK&6{0{xLZ(PaZVIKQ`x;jZc~4AE(@;^I6$s^EqDquJ@WUey(!2p{Drra&AwaHN`&x z{-Y`WiONCO+a7Ga^VJ{3_(6YU{7LGM(Cg4XVkW+x3+-c;Xno8Q{8MsXUHrime}QsI z-)D8n-e;lu<$`IV?NoRhQ+z%5S6A*+zj7b`&vNbv(G*|rhmJ4>e+s_tn~vfp>K8Y` zKSQ~s`>ms7`|V8p{Y@EvR>qC;$5g(|+SyUM#-#9jQ^BmA6QyfRiu;-hX6@W4o%s3s zGR;hBzlhQ`COV%?GgI1mQ99vUO$D=dew3~;sr=GZFl&pVbd5<(t*Kzv7DwqClTOX1 zf?3P2tN3}YnW~-ezMZR4jK-vM75@VGJ5&4%mAm}K6#pV+{r=UM{Qdja#p*X~Z_4=m z+;2=8c)x}V@h@due!ok775-)T?WXvbE2sH&Z%k6V?pNTm-qhB6B|g_VJ&X6bD)(#G z)axjUe|7Gs4LwcqTXXJ_9-m-F+ou}Aqx{A=-FH^sj$=Yb8YP4TZ+?$=_9 ze}i)WM@{i>R9^ErQ~aB99#tA=ioaC3R@XJEwkQ70>Q^=AQPp<*ThwpXJV!NKp1NOm z9h%>#jiQXdEg!$@@K;UoZ_jxF_m?Q`jwoL=F3_LvGR0q}ey9BBn#Kj4cEi6@{eGQI z@$bs{O#Qi|Q564f^*hZo#lI)#Ma)N(b}xQ@zBMjN?0mZq{~c4t->)2+O!0pO^M3a4 zy(SOfzirC+2bBv$O!0pWPc_AV2-fSlsIV0OVfBl8pDrr?1^1U?+FDq}=#T0)9JkAvVx9};Z_^;%=l6@{p)BAH}(ETfl z|5}tU8dnz9HO1HSYh^+An<)MpI<7d$6#q@-QrQ&$E#(&d{<5;=JAAz#R`zJodXE-- zz28>$I2r$B{CAamHk;zV2Wy@ydwz!hzWTjJnBsqsb36Hn(sZA-2R)}n@mEIqqOm>v z&J_P6W&L~0#`eM}{EzYVylgMrioZ(zqMmc@#bx+-%<;hiSb$48HHn4k2A%ug>|2FlqcYK!k=i0uj}t9Pr{#spP$Q39p$Ng^_-mQs_kd@c;`fA?nBw<>?=!{E&q4XTxA5P>@1qSr(Ag26u-Z6G5`M4Jiho2epJ7fb=9tgzlQoF~u3qA04e@`wPLH!8){QhsAT(|-M2K)`- zPfYQLD;M>8PA>MxAAx_QDgH*vrCFx<`T5d3xx7IA@&f!#;2TZxM=E#P(-eP{a+k5D z__}WBYdH`)7- z!GF;-$y?Y4{@N5@*Wa3)p8KNshZ0)%bgU`wVWY*zUWZ zsy{^cW809u7(Yk-p(9Q4kA|N!#Xm-QSjiNh`3)O}KMeo4oLBJkk0}1}>KE2A#h(j5 zZ;C%px%j>*zJ4EFQ9f7w^11jYD%VUj#hjQ+^!{4Wr8E91_-C2o zFHo*~-4uVJa#hc_6;(Um^!rNtW_RRuQO2L9y!j2L_&-zLQqQOMEhpjs9RE^N{L_`U zYBR+@LwW1BO!4(x?g(Gxz9_z~v!kHJ|e~$Xa38wgZojUaI|C>ee zf1%^bsVV+>Ft7Xj^*tY7&)bf&owtkdb^mmfpXYrRXMRhq?!!#Ag(XqG5YF?=6#tj_ z`F<1sef<3XZ>bIWb;%U}LLFbo_kT-m!S??}_*a=S{$lt~rudgA7w^DgE0z4*uAU!9Ndq5nNaizt5neXFHM zxv$pC_Wk7=EA20#JUgFulo@HdiYaQe7zpAZZ-aD{2P_) z^L^M7>nGsfgr9#O6aQfRrT9;o;@_-X-OLpK7Wj9j__r#j_nYG12ESv9f4g#He*U+_ zMmzuWb3r)Y@0l`wnT~IoYl^S?CbsB)5yiht$F=D7k1bc=-;J-=Gqzlfe-A#N)3OZz zUVMAq-T3$6x0&Lz{+9fHY>6#)KmLkwZaNIn&Rg_Pqf5tLH%w4|8aP}DgG16Jq|O)e^R;U_on#2QSS4c zDL(tP?;Q2}&cV;m$ClVPKVLJ&e@4gk>u!qA_3J-C{r&^+pH+^dP4RUeayRF`D863r zVTsOP6#s=NU$hJhJDK9Y2w!N5|B`ZXsww`@Jf^~ zT1FT2J`%-$RsCYCDgJB94TqcJzn=5>RGwzBR>X-b3|%nLczr{wF$axbCm%!|gozRQ*j$ zri}kgd2C-({LkSvP4U}vo?AN86#on58r=_bYg+NYRDaEfP1X0_6YvB)0Z+ga@B};o YPrwuK1Uvyxz!UHUJONMO-!p;#2L7rZIsgCw literal 147456 zcmeI5ca&9Cw(j>j=hUg9s5-SPPy`7}MFjytP{9a@0Sp*0#{xu<2CJONL@6YvB)0Z+ga@B};oPrwuK1Uvyxz!UHUJONL@6YvB)0Z+ga@B};o zPrwuK1Uvyxz!UHUJONL@6YvB)0Z+ga@B};oPrwuK1Uvyxz!UHUJONL@6YvB)0Z+ga z@B};oPrwuSpO`?y*dvZOcG_{r#c?wxA3c5Aam=w=9wtu;#jH!dj+96NPd9DD548AqKs?FVmG&fX?uU2XPWCr+Mq!nFVEU6TCQ z-AlDHY2NH9b7uYE)m8ue)!|)vZ~2p?yjo7^sN;{CbF`gG>7Tzo=_{|z{xpr7eEhWO zbB>)CfA|i04F4bVZ`xt<@sszNcZ}rlgEb^;C6jE7w29lRCj7eiiQ`~CCt%_ZaFy!B9pN&(6I>1N4A;Qp;V$q5 zxE9_8?h5Y;*TK8N_3-X+1)c~uz>*xQ|z;t>3Kjpc8 zd;UM=IsAm@|5Kj3PZ*c-+)sGmp9rVV?g_2f{r6pKc8E{C{Z+n0c2*!aV<98U=G6r7dBe|1WI~ z^Zb8l8<_JfZ42}K|KKq&&;Jj$&s*U6|2kuGsk6^t;Q9YL`}_r-|F5&pOW^tcI{SQt zetMkU?DG&JY@dffu64%bT4$esK(2N6c?bRV^(Fhff(?}G?DGf6z0N*=U?Z&$Fdo48 z!&MWmOWhQh>oQ;(JVflB2CaV3nPpI|VD5wXF3jhCl#KUN zKfXtOf7O!l0n|UE&V3Yr3m?SzZ{dSg`~MX_1pXUr_nk5KS^w{-+kIx-#_Ru1eKKmy zec1nd{HdxX<0F(epqxz8FRF}>gi9FHVH+?5E>k~Bb%SbnCUxTRqTG zP2G47^;+u3P&fWD^{&*9rEYwja(y%P<5dIuesTiids9D=y75WW`%s@t-FP1LzSK{q zZhQ*75%u}1V+X(s;DPX|s=@d)>KjvENS%E&Vc#4(g!<{KV>f}%fZ0crpTO*+$xmVS z(d10!u$5|Z7Q7vNHarGC2ey6aT$p_*IS(Gk`14ik*@uz~s2g8MeMiP$MBR8X^_{3+ zOx<`1^_{8zjJok9)W=i5l)CX{@C53YtJd!VUjgq5UkTg3b`{LNmRt?9uO-*O>}$!j zF#B3^9n8L#T(2CA+o`k9B{#tAbIFY``&@Dp%s!Xg471NAwi4S#?%U)6 znEN()P`Q4gYVr`weUUt@ye{i9`8j+c;~!x>>o9o~W?dz}P!7yHd5k*qP9BGuck%?x zypktjj+^{aIV@LA(C`$D);|Y7ty=#A{0#gm{44l%cm@0p{4D$~%=^~A4|h=i0DfMz z>O*)X_20nEqy7{4Mb!8%a3}Rk z;XlKd!K~BrRWR$cd^OBEEnfq(PAk{KtkbeF>$Gy6)@@lpVD`b#7v{bX{ovKAA*zLZw!9y?gzcyskETveVGMQSvDC>eY){>I9CdOGJ5V>?QF$ci9d=S4 z$2`N%F!K!KVdfboC|5JjunTqLUEwjRVKdY&g0W+`g6UH--@Kcz1gfn605zc~{M>rc^s2a{uZ7@DpxhwMu=TT=~;e6^G zCtLt?oNyt``-F>N-X|=Ed7p5xa<%ai>b!6G8Fk}JsB@ffDRtw^lpBmMXFT%=SHR38 zTnRIea22mNz8Yp;;Tq*}%qv{0Ty15!7sy4!@q`~fnSAx1-}NbfM187h2MamgWrTZ;CJBX;df!? z-S8gFyo>L{%)8+u_$Aeb)iCGL@EiCQ>L0_a;7?%Av*A;i^X&dP%y~Ba4(2=?zJxi? zhTp@SXTu-hw^SRxg5QS!2$Ms@T9_OfzE<|$6YvB)0Z+ga@B};oPrwuK1Uvyxz!UHU zJONL@6YvB)0Z+ga@B};oPrwuK1Uvyxz!UHUJONL@6R-rz1^Fuc@cI7{H?OnNDZO6h z|Ff~NuAYD=;0bsFo`5Id33vjYfG6Mycmke)C*TQq0-k^;;0bsFo`5Id33vjYfG6My zcmke)C*TQq0-k^;;0bsFo`5Id33vjYfG6Mycmke)C*TQq0-k^;;0bsFo`5Id33vjY zfG6Mycmke)C-C2sK(##oA3p!#^ZzkBSpAoum}V%g5T#3#aD=H~){0R&@xL_{%vvc* zmnMZ#rh-|kiqeTc##AtCqzbZK%h=W*~lnJKM* zlrBvU;rbuakeSjph|-CFt*KzvHjL7x$)U{m(0-XIZKEii_}7~XW^F)}E=>+Q%~UXJ z1EX|la(Jz&VAeK{(uqIbR4{9UqIBXfHx9%$V_QNqjciGXeyYsVNtp?nMwXL7Yb%=(-Xet znJH~VlrBx?v){}wWu~;vqIBXIcwS%K{ z;_G@B%}i;BMCrs|WGa}oL!)%!cbE!h?XW1F_*I~_w+4#CItQosR>tmPTpO*95;`gTb3zbXyK5I+%K8w_^ zDwrnPPKUQQ#n*j*ZTTVf%MaoIBR4{87Md=!o^3O~Kv$i-&*O*k-m?_Z6{KfZrmu71PLri{<`{l=t$_iMNm z|4PQ?_q)_T!M_TBjVb=s%4vSx8i4ZR#lJ7-v-RhW zMp69x)$cOT6#s#o7c(DG+JpG{{?@oSvHk5K{C7|bK=iuE<@jG(vC_ZnBZ~Ptpcldf=tt#xB`=atD=0-xH{;%6UG0v`h|^5@n3~?ovi-HI??-cb#ao` zi<21tx^k(?6kqqR)h+scK@|T@9oM796#p&wR8#!7m3uau;_Lmex~JwKim&(E>Ruys ze6JDs@8vAJlqvrE%0c(nHTHX_lMnEJZ_4-&mG$2n8`l&@;p;kEQ_y`*6o0jjFY5lZ zrnn6MH|m#uXNv!^a@9Jf_@BTxnBwdGxwfGDfhhiG`MA#HW>b94t24PB|91S(l?xY| z;;(`Ae(e0m{rH9Y#YR)c>-lsR55qqU|I3Vu7O!4!5ylGWce!pajpWlZ~tIGT3 z<3;iRmh;<%T2uUdUu#;O=yedq|9d`eb;$4cCQPID)UO(5ieH2`H^nc(JDB3@{5q?2orvO>88^`szZ#xoieCfIHO21&YyO>83-I$C zo0Izd{WHbynvEAe(Gn&MaBlT7g&;3rJ+^ZTJW*6Z;_@f&qq z{Z*#;P0HQQHpS1^Q}cLTx0&MS`?&D>QH)ISyTNlz@mt{~rug0AhfMK%z;B!4_f!u3 zP4RodSDWJJ`)Tv|!n5iZp2hF2T+F|3G>#OnC#b0EaZ>HR3UsL>ipK5OF zI!^trhzV{&d!&NRgzt6aF)6n}f=(jlh!nqzy-Me5gFgrD#G z&F!^o)UREGzoT;3vMK&f@ZP5QJHxk`;*VEu(0!}Dp%s6E`l;@d?djS0yQtr&>%3k5 z#-F#K_j7wov({Uh@pn`1c9$vs?#iv2XM5{c_!HIdPHx>V#@|Ezo_ZbHdydB66aPL_ z{JoTW>;2c>doVt^^m$h6eV)bF_0-gCbg#c2PhBa{D$s*)24p;W>dybhV?$`D8Gb1Mg1C`e@BhYf2#U*pPMrN z2<7_arue$QbX10@Um1dbB&_GvQMm+vI{wS1_%oEdYu+8*55(8~x}*CF>MQVdpY7<& zdGwuv|05kY@B~x*S?~j<__LJ<>3!ER$nLwN)gP?usAKScjGv?a(2=J2$G|I1@qes5 ztYnIREUe!*I))9yKQ8xI@$-);{_*M;HZ;Z8^ITPU0sjU36P1e}nBt$LTy?%F{#@ni ziKh7TlxxPC;_LV0RW(cTm*StI+*R+dRb6ZG=i{GaioZa)?hRA?Qazpbj+{&rgK zui5GzQ^qe;-uf0({6)&!>b|mO+e!HP{b|j%S5m(c{|x2rI!y6@qCEO-Q~aOi+!?+w z#XnQIpzEZwFcSYPd_8Vw!H%o@duMTi){7GuuX%OqzuPy9;-9PIs!~(@^I*NcomJ=K z8|!}CS!Mg}1&r7A(^+Nf=fccysnKm{43z$rug}F zYN^qGug(zb5y4=>G@NB8q>l`c-{Q@%8+BjL>{U@vqOv z#qv;7{QUc0ORW1y{ko6vZ-75D#lI0=Yl?r9a(%uITVlPf!<+H*??2)n&Un49v3>>h z75KL*SGF?6zYYGqDgILB^kGx{+u?Uj@$XP>%=iD6*l7Fzo%p&=W8+1Pzf1k5xu*Dc zE4S!%jxBaS=KD)aY|-l`%J^lB=Q^}pkFV=5wpe``{(X$U-xS}t1HS|R0XV-O<@k0# zK8XLODdQhf?p8F#C&z9L_zn0!hnr0CAA#33#eWpu#1#J*@TR8tkHK4*;y(_bV2b~Q za%(Wfe-fT=ivLUH9!Hwu=RcRU#Gc=&-}5{Cr<8lIG{t{fxzDkt_|L%kzSt7`T!8;8 z_4{@=#b@33>#u&l{`mPm+Y;j#_2U@)=W>?2*%V*b!LUTXA$znb&-} z%0<1OW)vU9e;fZ3Q~Y<7^}h$T%qX3Kulv!A(k0X{!GBM=yY2@wy5EcczWO}}n&N+; z+-r#`{)ftawl&4q{e4E?Z`JSnE&gidq4Q1gf1^BH*TszCwx4{g{+1=vByWN9AJ<3y zaeeSVh1WC1|19UZrL#@(f2&-r>tSwnJO1bDulKmA`rdm2o`5Id33vjYfG6Mycmke) UC*TQq0-k^;;0bsF|15$31dDPHa{vGU diff --git a/Crusader.rep/idata/01/~00000015.db/change.map.gbf b/Crusader.rep/idata/01/~00000015.db/change.map.gbf index 8d3985644701afc1e81cdef460eab1e1a79848bf..c626b4f6ab40a1792467d0afbd87f0c131b4f209 100644 GIT binary patch delta 43 zcmV+`0M!40fC7Mk0uV1SF)TDGEGm}tu;nrO%AJuAA_PSGw3CrGRRn+T!yB=Waerj# B5*z>k delta 43 zcmZo@U}|V!63{m=)G^W2(ULR#b>#fI^R5#GlvrYZT)#KbER-d6Rki!Z{=#|yOi&RM diff --git a/Crusader.rep/idata/01/~00000015.db/db.133.gbf b/Crusader.rep/idata/01/~00000015.db/db.135.gbf similarity index 99% rename from Crusader.rep/idata/01/~00000015.db/db.133.gbf rename to Crusader.rep/idata/01/~00000015.db/db.135.gbf index bf00a39ca9154c791f4fe2ae39f872375a981f16..fab06629de12595e63abe782938889cf7d55d09a 100644 GIT binary patch delta 17933 zcmd^`cYIW3-uCZ1Wf({xA%T#dlR8OAnG_P5Ff>6yKsvT$k_^c}k_nRuAQC5t1VteT zYOp|ps8~RnFp3M4RaX>6ifx7U0UPQn*w$4n_+Hm3i2Lk5zRy4JKkxZ`e&3wy+~wTo zuD^57NlVLHAuX`zd}~2YaaK2FD{je%-dM8M{|*UEEXNvo3hwjNrS4XufB6`M%Ks@|ksy{K*yU6THP9Azm^>BE)iCOhfUlvve{2Ifx`f z_=U(fGMN4<#3M$?F^B~eUfgy1Cr~y$XvTga^7iXu=1PeEx|o$CMD7QM7y!|3h~W@r zh8PDCV2D~Fa*i3I6(ZRXFALHCA>q{?eAc%@WWT2e&E76V)^1%~(;`IXNkbfh=x2yu zg|N)l#kFYpj5b|d7bZmd1w(9r7@&*mlY~gCGDL?Eqf&3y)eT-DQl8UASr3RHL*R*$ zuQ5cI5Xy_XsBl44`qlgzTDtF|l(Tc0d)6nEm7P{>X4G#BU zrP5wo>u@U#_Qpm>qcVC{j^e3tHYydhuF84J9G82c-Cc$2;}mDT$AvJ5QgNfl!H_z; z$Agsi`YNT-W3OiF3B0aGs&_2%;IgA3@7G`3(?X(p`??oK$%*n^Ur0-oGs5@q+NhD1 z*d#C79ij=(! z@rp<^GE|%vZ=6U)o8N5+G;^}naS?4T+FUQsII#yp>yQZfs}M=I>1kw|5Q#=K`G61! zTKA3|7w{59o*pgm1SX^kZ5Tw3Gvlst59vW6gM^6vTo<9ZYixxsdUg{c=8z$lLTE!i za$MASA)>4Gkf?GY`rT;=R94hGhS(-VU%eV9^SMjpC9hKZf5>v5#IST?X~k7)gEcD^f(td6t~OeQEHuy9<}4L_ctm9MJ3k3 z)&W(;YWH>6D{GW`SADLduEBF7&Z-~L>*to zT_r=jcTKIayB$@^0(-5q%IXqsy4DyRZSFb4MfoZ{0GeoJZaa8KHSc&1zWT;3- zrHiSYj#^9*oCPpB)H4@t%D6aRRM)yH?6pdjvk|#fM%3i1wcpgB=E5nWJvk(*kN3_| zt_CNb+^$baxs6Q?4Yf{`)Vio(V6Hmr==Z#s_5W2hE_6FlT)iHf8j)dDlUnbb%nFJM z(e#7nl!ht|HTFhFZULvl_Dwgf>+5aROT>6av;RLSi&hj}0^26`eb6uo1A4uu-tluraX9VPj$AU{}DdgpG$yfL#Tf2%7|(47(aO1vV8n4K^J% z12z*j3pN{e4eVOjb+GGUH^9nZEy<5IYRf7vfe!L_rKUL_dh`hKLqo=*2WK5SW3qBNigv5Lo($_B4cV(TM6bgMCR$ zs?7nBqg-_jPAs_y?ABC2uimw=ensld)vy|v6E+t%4^|7SgE8C%YkZl&2BWTNeSh2{BMxm?JU+QSyOr>mh-UKc2m zMY;%H3ei^+HH?<4`R@@mfq4)%J;VfGB{xD74T$9xIde6&h>7|?uL~0fK=zZGXkke9 zFhkhk2XmS@3eSpL=l7$ zB+4#2%n@ruGeol%Z9UVZy`_mxRpe^oF^W{}B_v`8MT+L&L_DJk&Et;fqDWRzq= zfHnN`=@ZKe3I|!stk$9;by587N@3x^Ay_pVU9}7J1-`+Bl}umx-D<8}{;C#YUCrkD z+|>Sla#Y{ynwgrjuGro5F)qD{)%xFWf_2#LQLy@>KpxGLXmr#%Dm_^Fj613;s2!!@ zqi{vUJ=-@8iRwG2daAw7p=b$Q?p%*6caGhiYox1nx#l%Bs166c8Lo_Tob_1U>+Fs5 zhQLiiUKKYgbxpM%XG5(+sdLo1+&8LaT;Qy7xQyCT7g*Q)scN}g?)(Zay~a&y9JT7J zNrRJKhpXP9dQA&mC{=YGeJ{ptROYx{b!rJ}T?>^8r-yGYa6o>mNR|oZLHV`k?%25? zRz|fi4z2F*caI+?o8;&#rqy5$R`fR;-ScT|P(6l5@Y|jS(UA)W6<8XTDo10b+u1;OF<19j(Zd=& z?xsqQtE0eLF8labUo}i#*|*iUyw%p)YFp82yRFrBd#i0_tL=_f+nuepRjszwt+uvS z+nQF}UH977c9$twp4YyrP6Bwx!`wai6h|Wt^P>=j+PN@qfe1AOM){yKhIkyJ%MedM z;FUr>%uiy9KW&Ju5c>>)7mb0~pimF%sb6TH zeE39s$kxVQy0)tkx^H!#*DkbQ{lSU2_G@}p-`4)+uP1tj-nG^JsTzW*SkF8*UB6If zT!_>!6sZ@?TVuXcFSJko;6!};sgU3Dig}*_c;CN5Pij7+UkFk!^w?^Cn-}of-9F+p z3i@QhOR6r9IIKnpeX?MueqonvZ#{c#9lS3Qe3iYb3h%{o!(C4nEYZW;Wqb0uWB0;U z`+ax~!^1`KCN)E!@20g=UX)|dA=fSNavx%7j@mvfB%Bv*4G$Mf(b7XI^^jZMLBBk! zi)HMji!@NJdxGmZD}A^UbOK_e9*u5R-VcUA26_53 zD5ixFntKqgm@riHrs&bSS@HaNeRO5UsL$1FSTT==7;A*gga|i;9lLm68Uot@Igc9R zW(azEXluoM7%q;s#Q<>};yyhj6P`!*yN2*y1~pMvmAPOnhKY; zTf&`5ZNov^L(rEqx1+;WH%!L1U#moISTU@59qew{J+OOW?XdN*`(XFO9)LXvW896f z4p=8_6YL?_X4u29M_`Y_w!j{PJq~*U_9Sd8Y#Zz;*ml?s*iP6k*lyU>_qA5}_ zafnomW0BfOloMAGgZc85YT+r?Fp(;O6!bHZa*}wNzyc^z9wJzdlqH0dm_dvp*q>7p zh#o-l_rym8pC%dONF-x=5XtL_<%F9k1H8!-cshv4AR-BvP|gyViiCnLEtIE;c49Gc zJz*m-uL{KkBz;Dp$BU%x#9E?>m_=a96-lhEBtB*$3z&Ei&o2_Wq$jQ-8i=Vx34wWD zB>YUABG@hoj}W&J7@ZK+KE8X5tot z`Ni0XBp~_%&-xL*;oT1%4C_cck|6tZya#^Z>lJ$_J0#2mzp&O(k2pLobmaWQArn_j zO+N&C74{nJuy1Pm>w8bg5qo+Zc{YGmiKF>;yavCcor`9a(#m$=(R>F4ABsowomgbP z)6PXRDnEalAyz}Md3iLW)8(_wJet>Fkzu>>Xub=A?aZSY_lVD9ZSZJbhoBVgTr}T} zMdnT44a?Twlto-T?fys{V07m9?zMQHm{HmvRNX__8SuOmB@fleI13$vAgl zLc6@yUX3&ty_3#&-z^E%a~sXvvM$N3xcFjjqiP*?_r<)t%*^vI`3yL#=M%zwGB3%; zT5&O-tL*N17qj_yxkL?NF7Q3KGM9d8E>^3xtayOElDVkO>1BIfe1;8oZ6EiJo@yym zC0vqfU;$I%XQr}>%BnK%-2Q7)zn*j@lWH%t+6@QVjimO*N~g1|%31By9@=}+x7$AM zDJG|D%;bgYow1KwW~~~eCZDRlz)i%)ec5z%n|VZi)o5+|xn>IX|2dOg@+8|zKGgCH zUC8{hf6K43w3NkB(|SFXHD%ZlzHy4W@jcBo1$+1Zn$a;mqkLvma7jjmY9}!Yq2@D6 z`z7Ij%I+C0yPj-auiojj2i2PQclk}kX1|u%<#;pxcct6R?BLM4SUSta1}m*BQA=0j zus4)7)z>=f=aq4pE>nL5L{zn|X1Y|zdaHS#o=Z7%(FOwB4!KxaS!ynI4tKSqjK52i z@t44Vlbw;<1HSBnBd2@Gmwh3&Bdq~mPD7>Vh<6FjMWr06r4JIExJua{N-K%0iQz;Z z0pDDda=t6!a#nJNU@j$``AYo6E`rl=2^W+S%qpUUvu4SBqEh65(|9_D;6z@+*|8*= zfQbQL6CV)AJ4P%UD@n6Ji z#6H6N7TP6#W zc|Wm~V9jT;M`d0~loF{#FyOU(3tCtN%PRzXre!0+C$aFx7LEE}1Kl99GiE2g$M~irW>Trl@V%DO_->Dm=xa*l-M(?Xc5FBK zqTV`oQ*`c#5%}=P?a6i3*WRc!);PJPkDo7`b#;y^C%!Yl)hgX}b2M(;i&qWxa{*b^ z{^VQOp`3m0SVG#x?*SUMPaBK`xo+(ng-UpB9h=h1Wt?1iFJ2BHI6{H7Fh~`_7GVT$ozshK^!9fL_9%oXl0`9MdmVM0l~M5Ob(RH zNyJEE0Fg;>sAl#eBzug7)3W6gg85s}TZN^I*iAf2+(+C=Ac3&B2?xRX$ugc8Mida} zUc%Ck;IPc#bd`a=Br-lE-X=IRDZPfR8->O?xLKRt_xC&GvTAdRzA z+NZ=x;&tNB#M8tU;(h`nLZr12oUzj85VMI1#BidJNau)6i{@zvka~gmn)rx#hhS@` z?k9E-n~8gg+leKFi>M%`6XS>>L>`e$^dY(dDL)ctiPMDl4e}*|D?-XvqJvmVEGHHb z^N1UWs|k#3ky1)z6A45(5eOvzllYAI8^LEtWgZ5C@2D#Djo0=?=W3hu+LzB_eIV7{M$F>X8dIH#p7X-v90*E zC|}Q_#J9`##i~IoCN2H~cGfp(@wv88??EjTUIV5?c7FB1V7HX(=i*lgn=T~&S`3{S5oXH_3hBxt=l$pP^mw1eZ4; z*Er4uaU+OSAoeHXL*fNu6VXC2UhH5ZjR*x|J||u#b`zW(Vpb6Ii7R}kmS1p3`kL;$ zU9Jzw2gfmmzl0tNz1>M#^{OiiQmrV87ncutB!LhyWsx2qJ=|zhQ$(-v5vc z_J`QI$;hzw#I~qj9XXS_$y@!W!PUJ3n(w}M{ZV{Gx2`>0{kzuRV(%tbZj{dbA!aE< z+e7b+>f=);44vH5zaz#hFPHX>N^}&x3u(#4&;DH} zV&&1$@X_Z#-^YDb?RwB_{#!nYl_P_Dtr?1|`kWAS$p8Eou`;k{+jr+vWfmg4v|ab5&49bC?E=nBBGcWK$H-r#6V&YF_;)a43+*J2QHJd zmv+a>#Luz=BK;AzVe+~l?_QyxTJZf-kq|wGXktAps{1-kbW)hLFYqEBQ^hDPWCumJ z2Q={vh3Q*Obg5#zCO9@k@Mc}`^QU0#b8&wDgvl(ps{QMr9gFm@pZy z947b;d55)gVHyZQzlDcs5Cj)@9wtmadGs!Ln1Ej zTmf;fCcMIQB@`VP9;WdSGqiJIngCH^2>2!aqYQyNX8+R=lOWzU#AJxQhJgE;O&^Vi zX$l0MP(4gjA(C;5=SL9SuB^YS0T6JkvvwL{21Jt~WoeNV#{7O!J3y zjg+qjdKci{ndrzOGlK{MEN6%=f=;1j9x;|+7s~jac%9fx+(Dpwhz#C8Ljvh<5W9#q zL@j~wp})NH9@xwQUSOBTRt~U&K>rhI7|S9piwFl&dArn8#BPFqRq9d#JwT*lIEhr= zI5iST`Gz=3Y$tg46pn}#zN@5QZW1Z+fc759c;4hEsBa~z2@G)kosV}{z9smu%EQER z0=-gyt5a~6#3gam+8S1c>zzR}0}k z{+E%`+1KwoIZ}Qb`ag75#K*yjU;NRaP-Chqf%wC&tH))TB1bzrwqVHgZaeVlNC}K0 zMiXO*%ZahXIO#v|=@s(Rzj6mF?$b&5j}kcnPUK|yV6Zm`>Ek%C<6a`z&EuMh znM5(cx{LjlU{{YlNNgci5t#f%>{ucZi20HDfOw8z`^Hof!--fRn&Tpx{XM!vU_yw# zk*6HP*qz0$>`w$8gMNK4Kj)kKj0oDj-ztN z*2(hYUL7g-OqQws7r+Ik>_1*_kQRq&NL$H+lO=F9F@=~)Oe3ZfGl-eeU-IBA`DUdw z?+=+Rw@a@XsRytu1KuQ_Ce{<2kOsiz5Cd4p17d*UUx<^$^TgxCZ3OGMm^D<)L08-l zC}K4gv7(DGT13${@^ zjte#uob(D9xqyW(NFlld)-MSRK4E2TTiG$xFJ7z*apu*2_+-{rww(IKOa6O2^Anu} zA2HuUOeL}jM$S7+V8n~Oodg>)Z!uvfE+Y~MK3wj{#4E%$;x3|zrOt)#Byt%$H<<_q zR4+7#6_>-TbM7J74|A?3MiA))AF)5n(I1nI=+CN9eaZgp@%J!ep$>x`)!f8%VM0YQi2bg$@~NctR=H0a1C)SaUF3zaRX6CloNKMf~X{_ zq~BWNkjvVu=5HwSEmm!uza6;iBTOsPTb0JqiOf&?#Np_wg zZinb)h?N)!$2H*<@(!q7M$nxQ?1DVxDu_buT*%cB5r)9H$$Z@qYapI71cpl{qN;~n z3o*(Nm{ZhW;i=`_7)9^kM6G^_L2BvbbsX|uh;sE5q8%dF5SY#JpYz(mPt-HE8RCA3 z3PU^q(bo_dRO!4C54iyX*{g@#2w{&kR0mX?Av!VgPWoRt=#bF~m=5}NoUOiA_VbVY z*ded#=KT-5!k4pB|i z5KdyQ^dJ0Uo*X$WF&6CH;Z*4YFH=JPyaEL7q(UpV{0Xd-sYttR*#XK_U6`x!$SF zk9K^uvq2`wM-J?2kWoQb8k@i7y=ugZJNf3_nhxEM^f=6qDd2BAi{?GL&c|gO=BNGP zdmH5UfrBvg)C*53_=D}QGF1xmHeGYJ#bMs6fC$$Q^OGC*HOR4poSHW8Qg9NX{+lAN zn0M-$YakBu4h2NGeweqn*^nNXPq?Muwy#kh`itC)it)(%%>IYXNpiOI|8l!W7AE_T eJmHa_2K!I$@W?eL|1zIPS_A#>?DNR1<^Kn@RDqHJ delta 12211 zcmYkC2YeJo|HfxhE+HX>9O>K{46N8d$gcPC-|M;1=ru|U5&=u&ZYdkDqdxNr(qh!VQiSJ#Pfr+S2 zT)c6Eef!HBriRIv76*RRCvdJ1&%d<2;-mI{a?Rp3yT=8t79x1f;`lv%<&9b6_tcEv zBOyP?9}0j1Arlk?1w##>5GWLC2!%o6Py`eSHG-lbGt^iazbATGxop29B<8Smcm7$3 zd{tP`ut?GQZj)EBKv9K);ivQvk+PB^r`{XLS&9M%n>1+YYp>22*)+u48&kMQgt&ZLJ0eO!>kk{ zq zAp-6y;bnO}{oK(=bmv50)6GtS!*N72E}u!$Ofwq$6wQ>;WE|HFVggfS7|b}^M#CT~ zwibq2B!u;lVRpc{XxzfwQGAIYzol168=_~NCzm6xf9N%S2Vpws#{X*}Qm5%A7s2uoLL{s)%o{?)-!#ld zm?+J3XUF44YNj7eY`ty*+QPhJn65Cd>ZZYHn7*1>ChrJQ5a1%zG zFXlR4JL&`Nv^s&w6FF09+&(Wa(lg-4lV!@smrs7>r?l&p*E-7Mx^^;LSvxXsXpD^T zgjDBMDRZjxW?}F-r9kMs+GTClqqe8FKD6Mnl?Puuf{QBI5Ywp35|kA zLt~()p|Q|7s0tbnO@Jmslc34aGtjfp6zDlhphl$WlkP930N!n0HGaq4|= z2A;vT^{rlG!V{8Xw_)%U;~1x#Ak007@ELa`!h;>HzgFcEu=aGrpgkG-KJOBULWce* z<`Oqx=IN(Nv^Ar`Ftf1N>EU+yV=b`F)oc8Z!L-y(06t^IHmZ!iv@=F33)(MsrFiOx z9^9kU4_$1F_YAbegw^1g0a^krgDn0ZH2Z$+oAWN9nellfj)pfgg%0HLA#+n&|XM|>YUYG)#A>337)5j;7_C%x zGldOI;gwT%qyHksOT0i-5*>+bA{!7)y3PB5$qj7I`{m%v~qtROfL2?Ge8m%u2* zGXvt!5<7?`1g{s*XvOCfk%WVYC6v+zM-D}J&+O?SqrA4`$+EHcTkw0&;IZdJ)VjTc zN|{*GGvf$!6gmcdru5ACeCOA)ct^>@T1 zoCC!SX)!}z+?yyRvIt(K7!pN45$A~g1Y6`Ts$;R1m_dvo*q9V+21}zyK6500nG% zfeFax2<2ZTc$s`=W2{ZhnP(;KV7_xi$m_>kh?hKE)KaX2*|rba6!pCNvH%TOx|+hC4!O3V`TDr z5^ae*BAIZ9g1PsIE5sRMAF-A260Z^**<5ByZeOB3kx!%$jB+j{ny_O{z9s63w~09f zKii};!Mit!0&?y!|8kh9ISfF~o5W0l-Ok}na;!unAo~IF3vr(Klu(E@#A1S<%^pWQ zPB5Rd8UAdBKbzst_6M?V5^SYA>vI-4L$VmSEKZKB7YWX|tf52?q8(90Fg3E+qD;mu z^Ez>XI7J*FJ|NZ;D~VcyZOi1CX0mOW4->iQzsQ7yldW-nM!ZjW38s|ud14gNhiFD{ zS#`1rj{g!&Ovg!r9dYo+4$ch+^T@%DIG!LFeh1^>-~}9JA%+WwMA6PG*uNn55bqMN z5Nxo0Ai)6GT|^qeyW9EMj9bKii2cM4f+LwRmtg*7JmneH;doM(?E#F90keHYFjls$ z1Q%}GEP}1I4e@O0aJ;{p>xVUtFahbe3En9E7{RemUqvuO)29%_h^_>?na-g~XL6?f zMO-FM5KOnUcZh|=bYeKcu}*7EIQb};h8PLUec~E%nqZJE{IG=sYkAK5VMmKBGqK~T z%ay-69v>a!sk|`G8ZLq+ju=u^IhGkIg!g7xocvLFq~iF-*qY2K$DtES=9H5cJIF#M zr2eE$x-G(j6U`M-+b~6D8|DUPz$VR%;DvGmHN$mAWNS~q<|=^!%5J08Fcu;GIhc-NYbrv8!|wi>t*P)J=RTjP{kwTo;cNjBbP)Z$!7I z(xn_rpZHaXH*P>vxkTw0zU6b1^5^N3)8agxrY@T6dAntd*>iX5qF1~fE8EB@<rW6ar{Vd-Z?mZ94di46OJ_m zhF>^1BNau)UE*irJK`j@gA`f{TCU`>I{ZI;~8Qkf#eYx z-H39cm|$o!5{Ym^0(j#KTp{?VVf&1zC$4Ih-L)?;OcDz(qphdR56cS#^UqR2aMUaesD+)iBoU!N>R-e) z;!ENX;7;Ai;u?b2N@W_PP9PY)RCX+t%}QmnQrWCjHYq{sQW%Pf>`o#>lX#9`UM0RkJWo79u<40b zK$`-g%JYX$4TWBK&6yD$FkPF#Llf{3i=&c17`OIKr=4K(i~1Qw>MXJPT-c zg}&@9%^fLYJQ3$l1u1vGJ~chu`(bnsX|6ea?G*F{bQ(GXorTUpUqW9&Uqk1iZ=i3X z@1P6NMd&}u>1*E?_mP{Fkg`kt)0BxrE=2};-~LC+1&Vd#rQ0&We=ysD7vBLEu(8XZ z(*Z}Mzo+}%b15~sqc1@}K$oE(p)1f;=o<8sk~{k6^QYx1Pe|GIb;`c7>+_oXqwh84 zQ?En6DCJXctZ3+F&ijsku<-3R%zc;@hIs%pT{jZ{ItCdA&e6&+7-mP3Vf?Ye{ns!7 zFy9yk)6KryFeZ$zeTCtIV5S=;7-o=A8qM^(oZ^kF?JonA%y({-O69w*M=l4~ytL(p z^3s-Ht7~OC0(f&>g0gSG&3Uo@f3k-YZbG-9-=N#j@6a9S59m+mE_4t23;G-SFZ7R6 zKH>i1FzLk0{`->xE7+1mCUqj0rbM( zsah#(A;ORFCjy8-saCBt$v0L>KQ**0NSY(U&0EAnxO^930nOf=Zb9-zPv1)iQW|M5 zFHt{|w@1CY8I`q-JmJeuxYRd?1j#XP%E~>V!BRF<8g_2AI!vvK50>|Xy))8-Wtk_u z*quGU})G$2BVP@*9bMuZa)L?qFOh$75V?P_f-cdd{fHKe|=Y>=y3Z#0%=q27u2 z8p~G8)ke})tD*=*6EQ?A5hqpkUc7wtpj?iRCdhRO>b|cN4cTAN%gmT88U8;T%v|n+vWKn z^~a!8S?Z@|ylj_#R<-X&yX@CU-TclZnImi0t9HUcIEhRmi^wK?r!-+Hm&hYrL_SeK z6cR;5F;PM^C7KbIPW!v39HnDE!! zyM}2F^QB?%RFG>d5~h|g#v);A1vAJvtu+k(;5$s%Tyv#iO7YF(pkd0~aNGiUnA*b3 z(aOS94)c^@(6uJnhG`GO4Vs4u(<|p^tt?Cr!}tQp8mtsK`u-tISPpXd%)rC+2uz_? zb_>&^aQbR4Or7u@he^xB)EVXrtt?DkV742kE6ifU-~l3gqG7tj^fU~1;Ou{6iVZ#M zJEI1t_+AR2|F{tzy0U7FD(t#hxW4Z&^?`{pOkX_H|2q)BRZqZhJ>_AlfO*kZgu!*4Pa0+@Oom~GVTzwO z3{LrX&oWiQpn<-_gdue#7-qOg7WRvV8-ZP>-Y{4e?RDxsQ>lzd_0HHkMy^zY?WOWU zP-9`iIc7^3pErC*pr7<+y244GLL`2T~pomx+%F zHb3P_^k1ap5WG|JG2(5ais(Qj0ZD%lUlKbBwj=2U0tqLQx)MbM(~=($iEL3Kub0SY zW4sjre5FM!O(HP0)l&z`<;ZByu1 zM*x~{KcJOGz!xwK9FKt0jo`5G`;LG!NUeX=l7o-RVX5AmDHU?0`b*~?^15H`jjNAJ zpcB!V=t6Xr>W!=2WRgdA!q(hft_XBT;!26P365vtdj!{x#34jGB8P|u5`HI66CV-( zAKOl}4k7}G=ZuKwQWw8~7(;M$OR*u2CvVj#hBwBOF^&-LSPkob^MDXsu->8GM zU#d-Ni@^SJOT1siQg5e}{xa3u6?FJlj-9NP)bP~)@~OtEx3Iq)?^jz`(q94th=If) z;&Eay@dQyp3?YUR!-yxPT3Avkt80C)b9n1 zVS)_vJQD4SVP?P_GK?E$tzoKRY78@zRl^O3l+5m6m{~9m!(b)P4l)eFo^{4Bb6|ED zrUr%s%tK;D%9^Z|g~VEx)!Q&H!^CUGEhJ{D@8>T5LC%BW$n%h|!XOg9L(YfkZx~F$ z%xJ?P$(?r$vk>NtVX(0{aWmf`7sHG)3=+%98HfJkMoTd*t{7FX!K^im2ZpJ_LoS0U z^A%xU#|-)1FmJ%{X^02E3*w!LcE}Ylyb%w%67%L;tt=$cFyq|>!+GI`8m0~=UH$Y> zrHo7V%-r*RNA>$3D&)njuf$zkbg z?fOY_ZeZ9ktwm(OQP0fN{miO)>m<3v6o$!T9P(Lpg)&LD^bfml{0aa5<2l)6fLZ - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Crusader.rep/user/00/~00000008.db/db.61.gbf b/Crusader.rep/user/00/~00000008.db/db.68.gbf similarity index 99% rename from Crusader.rep/user/00/~00000008.db/db.61.gbf rename to Crusader.rep/user/00/~00000008.db/db.68.gbf index a1c4178cbf4fa84da7ffb6844097d72e08fb0d41..21855502db8f7258712e5944ab3e60dd9fc1d950 100644 GIT binary patch delta 387 zcmXw!!A`0ttERWy; z_vQ%GuoMUVdJCi@*1$%1l8Sbo_PV7;62<@c3@qG4Ucxcy_i*5;FA!mLW2OHe8Co5OqFZM!7CxiaA9jOvNdN!< delta 335 zcmZo@U~On%70@>@)G^W2(PAt!l4SVw??|J-Q~^d_Mz)QLzBbddZ5Vg3`Y|vt-I(rR z%Xnz|4tqw)=`wbVCPHqddC4W2`FTO9C8b4qA(aKG)5Gl;y#<3q979|c{2YBC5rf!YY_P>7FDPDxG9F*Hj{EK+dEEG|eaNzRCO&M&C+ORXpg zN=?o$N^vX7&kX`vr~$XgNTDFHC^0wQP)7kn%t%K;6E0{1RcNdUbekP7myNzpVsS~l LPkwSDC>-nnE6r@3 diff --git a/Crusader.rep/user/00/~00000008.db/db.62.gbf b/Crusader.rep/user/00/~00000008.db/db.69.gbf similarity index 99% rename from Crusader.rep/user/00/~00000008.db/db.62.gbf rename to Crusader.rep/user/00/~00000008.db/db.69.gbf index 392b73af9c61f438a166b6dd4b647fa3c29693b7..830c99a080d08189c4d98706ce31beec93a6a42c 100644 GIT binary patch delta 387 zcmXw!K}!Nb6vr7ufyblSxw1a(bqi&K!R4zx<-D_n)aUQ&0-+y&X7) z>>KDqP7So1NPNm?16{~h6Ty>-Hs#Dj%|xLfl@i*KYZfZ5m)USgsF0Tyx_Y$hb-M*M z+o_mpyL|09m0ClEM(ZZ-L&1G|r&_5ESe9YKtzB)#voZ^O5`yRvpkyo{H`Y(Hod-d{ z^TPlOw+EcKjC;T$0j#^&%pYgN0TVFCLMQ5WNuL9z9$@btQ+LVZ1bg69kBrY@#BmT1 z4tn7vcc$k%d2sPyF#qd^F!Duj!F40fV>HkNDR>h%cSDA~2hWckFhp delta 335 zcmZo@U~On%70@>@)G^W2(GuLfSg5aNo?4^8Q~^d_Mz)QLzBbddZ5Vg3`Y|vt-I(rR z%Xnz|4tqw)=`wbVCPHqddC4W2`FTO9C8b4qA(aKG)5Gl;y#<3q979|c{2YBC5rf!YY_P>7FDPDxG9F*Hj{EK+dEEG|eaNzRCO&M&C+ORXpg zN=?o$N^vX7&kX`vr~$XgNTDFHC^0wQP)7kn%t%K;6E0{1RcNdUbekP7myNzpVsS~l LPkwSDC>-nn0HbVn diff --git a/build_output.txt b/build_output.txt new file mode 100644 index 0000000..f601ca6 --- /dev/null +++ b/build_output.txt @@ -0,0 +1,67 @@ +********************************************************************** +** Visual Studio 2026 Developer Command Prompt v18.5.0 +** Copyright (c) 2026 Microsoft Corporation +********************************************************************** +[vcvarsall.bat] Environment initialized for: 'x64' +-- Selecting Windows SDK version 10.0.26100.0 to target Windows 10.0.22631. +-- Configuring done (0.0s) +-- Generating done (0.2s) +-- Build files have been written to: K:/ghidra/Crusader_Decomp/rebuild/remorse/out/build +MSBuild version 18.5.4+cb4e32d21 for .NET Framework + + remorse_core.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\remorse_core.lib + combat_tactics_tests.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\combat_tactics_tests.exe + entity_dispatch_entry_tests.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\entity_dispatch_entry_tests.exe + file_system_tests.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\file_system_tests.exe + fixed_map_tests.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\fixed_map_tests.exe + flex_archive_tests.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\flex_archive_tests.exe + glob_archive_tests.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\glob_archive_tests.exe + map_renderer_tests.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\map_renderer_tests.exe + palette_tests.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\palette_tests.exe + remorse_map_preview.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\remorse_map_preview.exe + remorse_rebuild.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\remorse_rebuild.exe + shape_archive_tests.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\shape_archive_tests.exe + type_flags_tests.vcxproj -> K:\ghidra\Crusader_Decomp\rebuild\remorse\out\build\Debug\type_flags_tests.exe +Test project K:/ghidra/Crusader_Decomp/rebuild/remorse/out/build + Start 1: entity_dispatch_entry_tests + 1/10 Test #1: entity_dispatch_entry_tests ...... Passed 0.01 sec + Start 2: file_system_tests + 2/10 Test #2: file_system_tests ................ Passed 0.01 sec + Start 3: palette_tests + 3/10 Test #3: palette_tests .................... Passed 0.01 sec + Start 4: flex_archive_tests + 4/10 Test #4: flex_archive_tests ............... Passed 0.01 sec + Start 5: fixed_map_tests + 5/10 Test #5: fixed_map_tests .................. Passed 0.01 sec + Start 6: glob_archive_tests + 6/10 Test #6: glob_archive_tests ............... Passed 0.02 sec + Start 7: type_flags_tests + 7/10 Test #7: type_flags_tests ................. Passed 0.01 sec + Start 8: shape_archive_tests + 8/10 Test #8: shape_archive_tests .............. Passed 0.10 sec + Start 9: map_renderer_tests + 9/10 Test #9: map_renderer_tests ............... Passed 0.62 sec + Start 10: combat_tactics_tests +10/10 Test #10: combat_tactics_tests ............. Passed 0.01 sec + +100% tests passed, 0 tests failed out of 10 + +Total Test time (real) = 0.80 sec +Crusader: No Remorse rebuild harness +Program: CRUSADER.EXE +Export root: K:\\ghidra\\Crusader_Decomp\\exports\\src_remorse +Function files: 2984 +Fallback function files: 9 +Global buckets: 57 +Global definitions: 15403 +Status: host runtime scaffold is alive; exported game code is not linked yet. +Game data root: K:\ghidra\Crusader_Decomp +GAMEPAL.PAL bytes: 768 +GAMEPAL.PAL colors: 256 +COMBAT.DAT populated entries: 14 +COMBAT.DAT tactics: 14 +FIXED.DAT maps: 256 +FIXED.DAT first non-empty map: 1 +FIXED.DAT first non-empty entries: 7547 +GLOB.FLX objects: 3072 +TYPEFLAG.DAT shapes: 2048 diff --git a/docs/pentagram-rendering-comparison.md b/docs/pentagram-rendering-comparison.md new file mode 100644 index 0000000..d19972f --- /dev/null +++ b/docs/pentagram-rendering-comparison.md @@ -0,0 +1,86 @@ +# Pentagram Rendering Compared With The Windows Rebuild + +## Scope + +This note compares the checked-in Pentagram renderer with the current native renderer in `rebuild/remorse`. It describes source-level behavior, not a claim that Pentagram is a pixel-perfect Crusader reference or that its code can be dropped into the rebuild unchanged. The Pentagram tree was inspected read-only; no game data or generated scene data was copied between repositories. + +## Summary + +Pentagram renders the current world view from live map items on each paint. It activates map chunks around the camera, adds only those chunk items to a per-frame display list, rejects fully clipped sprites before sorting, resolves overlapping-item order, and draws each frame directly to a clipped software surface. + +The rebuild instead constructs a player-centered bitmap, stores it as a scene backing image, and paints a crop of that image plus a separate player patch. A full-scene refresh reconstructs the item/node list and sort order, then replaces the backing image. The camera-prefetch change starts that refresh before the crop is exhausted, but it is still a whole-scene refresh rather than Pentagram-style active-area rendering. + +The main transferable idea is therefore **spatially bounded live rendering**, not a different graphics API. Pentagram's order resolver and game-specific item rules still need Crusader verification before reuse. + +## Pipeline Comparison + +| Concern | Pentagram | Current Windows rebuild | +|---|---|---| +| World candidates | `CurrentMap` stores items in a 64 x 64 grid. `GameMapGump::PaintThis` visits active (`fast`) chunks only. | `collectSceneItems` stages fixed/live items and expands glob contents for the render. Full-scene options currently have no world rectangle, so the full item set participates in each scene render. | +| Camera/visibility | `CameraProcess::GetLerped` updates a screen-space fast area. `CurrentMap::updateFastArea` uses coarse chunk bounds plus a projected chunk-rectangle check and a margin around the viewport. | A 2560 x 1440 player-centered backing image is cropped for the 1280 x 760 client. Near the crop margin, the UI asks the worker to build a new backing image around the player. | +| Sprite culling | `ItemSorter::AddItem` gets frame bounds and calls `RenderSurface::CheckClipped` before adding a sprite to the dependency/sort list. The software painter also clips rows and pixels. | Scene nodes are prepared and sorted before `MapSceneRenderer::render` tests their rectangles against the output crop. The output loop avoids painting off-crop nodes, but most have already incurred node preparation and sort work. | +| Draw order | `ItemSorter` incrementally builds overlap dependencies from item bounding boxes, including occlusion tests, then recursively paints dependencies before their dependents. | `prepareRenderNodes` builds a complete vector of sort items and `resolveRenderOrder` computes a full order for the collected render set. | +| Allocation reuse | `ItemSorter` recycles `SortItem` objects and each item's dependency-list nodes between display lists. | Vectors are reserved per render, but scene items, render nodes, sort items, and order are rebuilt on every render. Decoded frames are cached by shape/frame in `MapSceneRenderer`; the parsed-frame table is local to a render call. | +| Shape representation | `ShapeArchive::cache` loads a `Shape` on demand and retains it in the archive. Each `Shape` retains `ShapeFrame` metadata; `ShapeFrame` keeps line offsets and compressed RLE bytes, which the software painter walks directly. | Shape frames are decoded into pixel buffers and palette colors for rendering. The decoded-frame cache persists on the renderer, while scene nodes and ordering do not. | +| Pixel destination | The normal `RenderSurface::SetVideoMode` path requests an SDL software surface. `SoftRenderSurface` paints shape RLE directly into it; `EndPainting` presents with `SDL_Flip`. | The renderer fills a 2560 x 1440 `RenderedMapImage`, converts it to BGR DIB pixels, and `paintWindow` copies the visible crop, overlays the player patch, then calls `StretchDIBits`. | +| Update cadence | `GUIApp::paint` paints the desktop/gump tree each frame. `GameMapGump` obtains an interpolated camera position and builds/paints the world display list for that view. | The UI paints the cached scene crop each window paint. A background worker handles player patches and full backing-image refreshes; ordinary movement does not rebuild the full image unless a recenter or world mutation requires it. | + +## Pentagram Details + +### Active Map Area + +`CurrentMap` keeps a chunk grid and a separate fast-area bitset. For Crusader, the chunk size is 1024 world units; the same class uses 512 for Ultima VIII. `updateFastArea` expands the camera's from/to bounds by viewport and chunk margins, checks a coarse chunk range, then calls `ChunkOnScreen` to test projected chunk bounds. `setChunkFast` and `unsetChunkFast` notify items entering or leaving the active area. + +`CameraProcess::GetLerped` updates this area using the camera's interpolated interval. This keeps world activation ahead of camera movement rather than waiting until a fixed offscreen bitmap is exhausted. + +### Display List And Visibility + +`GameMapGump::PaintThis` calls `BeginDisplayList` with the interpolated camera, loops the chunk grid, skips chunks that are not fast, and submits items from active chunks. It also applies runtime filters for roofs, editor objects, and the special invisible-avatar case. + +`ItemSorter::AddItem` obtains the shape frame and its dimensions, computes world and projected bounding boxes, and rejects fully clipped sprite rectangles before doing overlap/dependency work. Visible candidates are compared with existing candidates; overlap and occlusion relationships become dependency links. `PaintDisplayList` walks those links so objects behind an occluder paint first and fully occluded nodes are skipped. + +This is not a simple global depth sort. It models Crusader/U8 item overlap rules using footpad bounds and projected geometry. It is also not automatically faster for every workload: each accepted item compares against earlier list entries, so a crowded active area can make insertion expensive. Pentagram gets its benefit primarily from limiting the candidate set and clipping before dependency construction. + +### Shape And Pixel Path + +`ShapeArchive::getShape` calls `cache`; a loaded `Shape` is retained in the archive's indexed shape vector. `Shape` creates frame objects once. `ShapeFrame` stores dimensions, offsets, line offsets, and an RLE data pointer. `SoftRenderSurface.inl` walks those runs and maps palette indices directly to destination pixels, with per-line and per-pixel clipping. It does not first expand every frame into a full RGB bitmap. + +The standard surface is software-backed in the checked-in implementation: `RenderSurface::SetVideoMode(..., use_opengl=true)` reports OpenGL disabled, and the normal path selects `SDL_SWSURFACE` plus `SoftRenderSurface`. There is conditional D3D code behind an experimental compile flag, but it is not the default path. + +## Differences That Matter For The Rebuild + +1. **Selection happens too late in the rebuild.** The current full render creates nodes and resolves order for the full map before the final output-crop intersection. Pentagram's fast chunks reduce the set before its display list is sorted, and its clip test rejects off-surface frames before dependency insertion. +2. **The rebuild has a backing-image boundary.** Crossing its prefetch threshold triggers a full scene render and replacement. Pentagram shifts the active world area with the camera and paints the current surface every frame; it does not need to rebuild a large player-centered bitmap to move the view. +3. **The rebuild repeats preparation work.** Decoded pixels are retained, but scene collection, render-node construction, and order resolution are repeated for each full refresh. Pentagram also rebuilds a display list each paint, but does so only for active chunks and reuses its node/dependency allocations. +4. **The pixel strategies differ.** Pentagram pays the RLE walk and palette conversion while drawing clipped pixels. The rebuild pays frame decode and buffer memory up front, then copies RGB pixels during rasterization and DIB presentation. Which wins depends on active-item count, sprite coverage, and movement; source inspection alone does not establish a universal timing winner. +5. **Their sorting contracts are related, not identical.** The rebuild already ports several `ItemSorter` concepts, but Pentagram's `SortItem` flags, overlap tests, transparency behavior, roof rules, and insertion/dependency order should be compared case-by-case before claiming parity. + +One instrumented map-1 launch of the rebuild after widening the initial scene selection produced 16,542 render candidates, 16,540 decoded nodes, and 1,355 painted nodes. The initial scene published in about 0.76 seconds on that run. This is evidence that scene creation is currently sub-second on this machine, but it also shows that most prepared nodes did not touch the initial viewport. It does not measure repeated camera recentering or establish how long a crowded region takes. + +## Practical Directions + +1. Add a native spatial index over map chunks or projected bounds. Query only chunks intersecting the camera's visible area plus a measured overscan margin; update membership before the player reaches the edge. Preserve a conservative overlap margin for tall sprites and glob contents. +2. Use conservative sprite bounds from TYPEFLAG dimensions and frame metadata to reject offscreen candidates before full pixel decoding and order resolution. Keep the final per-pixel clip as the correctness boundary. +3. Reuse stable render-node and sorting storage, or cache static-map preparation separately from mutable/live items. Invalidate only when relevant map content changes; do not reuse a stale sorted list across changed flags, positions, frames, globs, or roofs. +4. Keep avatar animation work independent in priority from whole-scene refreshes. The current worker now publishes the player patch before a full scene render and coalesces camera-prefetch requests; measure whether that removes the observed animation stall before adding a second concurrent renderer. +5. Instrument per-frame counts and durations: chunks visited/active, items submitted, rejected by clip, decoded-frame cache hits/misses, sort comparisons, nodes painted, and time in collection/sort/raster/presentation. This will identify whether chunk activation, early culling, cache reuse, or incremental redraw has the best payoff. + +Pentagram's 6 x 5 dirty-tile renderer documented in the original Crusader draw-list analysis is a separate original-executable mechanism; it should not be inferred from Pentagram's `CurrentMap` fast chunks. Fast chunks activate world objects, while Pentagram's checked-in `GameMapGump` still paints its display list to the current render surface each frame. + +## Source References + +### Pentagram + +- [`GameMapGump::PaintThis`](../../../misc/pentagram/gumps/GameMapGump.cpp) +- [`ItemSorter::BeginDisplayList`, `AddItem`, and `PaintDisplayList`](../../../misc/pentagram/world/ItemSorter.cpp) +- [`CurrentMap::updateFastArea`, `ChunkOnScreen`, and fast-area transitions`](../../../misc/pentagram/world/CurrentMap.cpp) +- [`CameraProcess::GetLerped`](../../../misc/pentagram/world/CameraProcess.cpp) +- [`ShapeArchive::getShape` and `cache`](../../../misc/pentagram/graphics/ShapeArchive.cpp) +- [`Shape` frame loading](../../../misc/pentagram/graphics/Shape.cpp), [`ShapeFrame`](../../../misc/pentagram/graphics/ShapeFrame.cpp), and [`SoftRenderSurface` RLE painter](../../../misc/pentagram/graphics/SoftRenderSurface.inl) +- [`RenderSurface` backend selection](../../../misc/pentagram/graphics/RenderSurface.cpp), [`GUIApp::paint`](../../../misc/pentagram/kernel/GUIApp.cpp), and [`BaseSoftRenderSurface::EndPainting`](../../../misc/pentagram/graphics/BaseSoftRenderSurface.cpp) + +### Native Rebuild + +- [`MapSceneRenderer::render`, item collection, and node preparation](../rebuild/remorse/src/map_renderer.cpp) +- [`fullSceneOptions`, `startLiveRenderer`, `paintWindow`, and camera-prefetch requests](../rebuild/remorse/src/windowed_game_main.cpp) +- [Original draw-list/tile-visibility notes](raw-0007-rendering.md) \ No newline at end of file diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 0a78ad3..6c8dd97 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -123,6 +123,19 @@ Work: Exit criteria: the user can launch the host build, view a map, move the camera/avatar test object, and observe stable tick/update behavior. +#### ScummVM-Style Live Viewport, Zoom, And Smooth Camera + +After live item state and source draw-order behavior are available, replace the fixed player-centered scene bitmap as the primary world-rendering path with a live viewport renderer based on ScummVM's useful architecture: select nearby world candidates, clip before sorting, build a reusable display list, and paint the current view each frame. Retain the fixed-scene/offline renderer as a diagnostic and regression oracle during migration. Do not copy `CurrentMap` fast-area activation directly for render culling: ScummVM's fast-area enter/leave callbacks also affect gameplay objects. + +1. **Bound render candidates:** index fixed, live, and expanded-glob items by world chunk or another measured spatial structure. Query the camera's visible world bounds plus an overscan margin; keep this render set separate from gameplay activation and process scheduling. +2. **Cull before sorting:** compute conservative projected frame bounds, reject candidates outside the viewport clip before decoded-frame misses and dependency comparisons, and retain final per-pixel clipping. Preserve Crusader-specific overlap/order rules and add regressions for tall sprites, roofs, transparency, flipped frames, inventory items, and player overlays. +3. **Reuse per-frame work:** reuse display-list, node, dependency, and frame-cache storage. Invalidate cached geometry/order on position, frame, flag, roof, glob-hatch, or world-mutation changes. Measure candidate counts, clip rejects, sorter comparisons, allocations/cache hits, and collection/sort/raster/presentation time before selecting an indexed-frame or palette-expanded cache policy. +4. **Separate camera projection:** represent camera position and zoom independently of avatar/world state. Centralize world-to-screen projection and its inverse; derive the queried world bounds and sprite clip bounds from viewport dimensions and zoom. Keep HUD and window controls in screen space. Preserve a pixel-art-friendly sampling policy and test zoom limits, viewport resize, and edge clipping. +5. **Add optional smooth follow:** keep the recovered/legacy camera behavior as the parity mode and add a selectable host-only smooth-follow mode. Interpolate camera position using elapsed time toward a configurable target/offset, independent of the fixed simulation tick; apply zoom around a stable screen anchor so zoom changes do not jump the avatar. Camera motion must not alter gameplay coordinates, animation state, or simulation tick counts. +6. **Integrate animation and presentation:** choose animation frames from simulation state and render interpolation without blocking camera updates on a full-scene rebuild. Keep mutable/player animation responsive while scene candidates are gathered and painted; remove the backing-image recenter dependency from the normal viewport path only after the live path meets parity and performance gates. + +Exit criteria: deterministic tests cover camera projection/inverse bounds, zoom in/out and resize, smooth-camera convergence at different frame rates, and unchanged world/avatar state under camera-only motion. A retail map regression checks item ordering, clipping, animation, and screen-edge behavior at minimum/default/maximum zoom. Profiling demonstrates bounded candidate/sort work and no camera-induced animation stalls. The smooth-follow mode remains opt-in and is documented as a modernization, not original-binary parity. + ### Phase 6: USECODE / VM Runtime Goal: execute game scripts from original `EUSECODE.FLX`. @@ -277,7 +290,7 @@ The `Item_Grab` creation branch applies the verified `FUN_11d0_3f95(itemNumber, The first Phase 6 resource slice is compiled into `remorse_core`: a bounded `EUSECODE.FLX` class/name/event-body reader follows the owner-loaded `classId + 2`, 13-byte name-table, `+0x14` six-byte row, and `codeBase + relativeOffset - 1` body rules verified in `docs/raw-000a-000d.md`. Retail tests confirm `EVENT` (`class 0x361`, slot `0x0a`, code base `0xd4`, body length `0x1fd6`) and `RECHFLNS` (`class 0x138`, release slot `9`, body length `102`, owner mask `0x200`). Raw extracted `CARD_NS`, `BOX_NS`, and `RECHFLNS` bodies confirm a 14-byte metadata prefix followed by the first opcode at offset `0x0e`; its exact field meanings remain unknown. The named offset is shared by the host task runner and tested against these retail bodies. Retail integration tests execute `CARD_NS` spawning `SWITCH` and `BOX_NS` through timer yields to a changed item frame and rendered scene. The Windows diagnostic release callback also resolves and queues an eligible body, but this is host-side dispatch and task initialization, not `Usecode_ItemCallEvent` or `EntityVmContext::CreateFromSlotIndex`. The interpreter covers only a subset of opcodes/services, and unsupported operations halt tasks; original context memory, far-pointer execution, general event dispatch, and runtime parity remain open. The recovered `CreateFromSlotIndex` call selects a class/slot and passes a four-byte parameter into `Inter_1418_0244` (`1418:0244`) and `Interpreter_1418_00e8` (`1418:00e8`). Even the short `RECHFLNS` release event branches through item surface-weight logic and `FREE.slot_33`; the current host service table does not complete that path. -The walk/run modifier choice is the isolated branch from `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. The same selector's Num Lock-off directional scan branch (`0x47/48/49/4b/4d/4f/50/51`) is now compiled in the controls helper, regression-tested across all eight mappings, and called by Win32 movement polling. Win32 still supplies modifiers and held-key state; NPC state, weapon-dependent actions, original keyboard events, and the remainder of the controller selector are not ported. Retail ANIM.DAT regression checks retain the signed reverse steps in the decoder while testing the host-only forward movement filter across all four affected walk directions. +The Windows controller slice now consumes queued key events through the registered host keyboard-process subscription. It preserves the original event-mode (`KeyEvent +0x08`) and press/release (`+0x09`) bytes, translates Shift/Caps Lock and Alt/Ctrl modifier bits, and implements the recovered Num Lock-off eight-direction mappings plus Num Lock-on relative turns and facing-aligned forward/reverse requests. Walk/run selection follows `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. The current action subset maps the recovered Alt/Ctrl animation indices, loads the corresponding player clips from ANIM.DAT, advances valid stationary animation frames, and retires one-shot animation processes on clip completion or blocked movement. Focused tests cover event transitions, modifier isolation, Num Lock modes, action selection, and retail clip/frame references. This remains a host controller model: `Controller_PickNextAnimByKeyevent`'s full NPC busy/dead/stasis branches, weapon-dependent paired actions, crosshair/target updates, complete turn handling, original controller process dispatch, vertical jump response, and exact original collision response are not ported. Host 40 Hz timing and map collision remain approximations; the source scheduler does not yet drive this player path. On Windows, `remorse_game.exe`, `remorse_rebuild.exe`, and `remorse_map_preview.exe` configure crash reports at startup. All CTest binaries now link a test-only startup initializer for the same diagnostics, so an assertion before `main` cannot open an Abort/Retry/Debug modal that blocks the build terminal. The timeout-bounded child probes exercise both a Debug CRT assertion and C++ termination, verifying prompt-free nonzero exits. The terminate handler reports active C++ exception messages to the Visual Studio Debug output and stderr when available. Escaped/unhandled Windows exceptions log their code/address and suppress the fault popup. The GUI executable has no console stderr by default, so attach a debugger to see that output. This does not replace a full crash dump or catch process termination that bypasses user-mode handlers. @@ -535,6 +548,18 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat After the first source-backed interaction, complete the original player/item loop, save/load, combat, mission flow, audio, frontend, and retail-map coverage. Keep the current preview and window as test hosts until recovered runtime behavior replaces their stand-ins. +## Track B Recovery Work Order + +Use this sequence to move the normal Windows launch path from host-modeled behavior back to the intended decompiled-source port. Keep the current executable, data readers, preview, and tests; treat host gameplay implementations as temporary until their original call paths replace them. + +1. **Freeze and classify the normal path:** do not add more host-only gameplay behavior to the default launch path. For startup, ticking, input, movement, interaction, and drawing, record the controlling original function/address, current host implementation, required host-service boundary, and status as translated, verified, or stand-in. Keep diagnostic-only behavior behind `--diagnostics`. +2. **Prove the source-to-build pipeline:** choose a small, already-understood exported function used by the runtime (for example, a process sleep/timer primitive), clean its types, globals, layout, and calling convention, then compile and link that implementation into `remorse_core`. Replace the matching host-authored behavior with this compiled function and test its state changes against the export and Ghidra evidence. The import helper is staging only; do not count a staged export or isolated test as integrated. +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. +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. +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 exact production-equivalent search at egg `0x1e` still returns one candidate and no eligible event, but that is the intermediate staging point, not the current avatar location; rerun the search from the destination. 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 prove reachability and implement only the required recovered services, then 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. diff --git a/docs/scummvm-rendering-comparison.md b/docs/scummvm-rendering-comparison.md new file mode 100644 index 0000000..9cd9a42 --- /dev/null +++ b/docs/scummvm-rendering-comparison.md @@ -0,0 +1,86 @@ +# ScummVM Rendering Compared With The Windows Rebuild + +## Scope + +This note compares the current ScummVM Ultima 8 engine's Crusader rendering path with `rebuild/remorse`. ScummVM is a modern reimplementation, not an exact transcription of every original runtime behavior. Its source is useful as an implementation and data-format reference, but original-binary parity still requires separate verification. The ScummVM checkout was inspected read-only; no ScummVM code or game data was copied into this repository. + +## Summary + +ScummVM renders the current viewport from live world items. `CurrentMap` maintains a camera-relative fast area over a 64 x 64 chunk grid. `GameMapGump` collects objects from active chunks, and `ItemSorter` rejects completely clipped frame rectangles before constructing overlap dependencies and drawing. Shape data is cached by the archive; raw RLE frames are expanded once into retained 8-bit indexed `ShapeFrame` surfaces. Each paint maps those indexed pixels through the shape palette into ScummVM's managed screen surface. + +The native rebuild instead collects a map scene, prepares and orders render nodes, draws a player-centered backing bitmap, and copies a crop of that bitmap to the window. It currently processes the full map item set for full-scene renders, then uses a background worker to recenter the bitmap and render the player patch. It caches decoded frames, but rebuilds the node/order structures for each full scene render. + +The strongest ScummVM ideas for the rebuild are active-area candidate selection and early frame-rectangle culling. Its fast-area machinery also drives item lifecycle behavior, and its sorter is game-specific; neither should be copied as a rendering-only optimization without preserving those contracts. + +## Pipeline Comparison + +| Concern | ScummVM | Current Windows rebuild | +|---|---|---| +| World candidates | `CurrentMap` stores map items by chunk. `GameMapGump::PaintThis` visits the 64 x 64 grid and submits items only from chunks marked fast. | `collectSceneItems` stages fixed/live records and expands globs. Full-scene options currently omit `worldRect`, so all renderable map items enter full-scene preparation. | +| Camera and active area | `CameraProcess::GetLerped` updates `CurrentMap::updateFastArea` over the camera's from/to positions. Coarse chunk bounds are refined using projected chunk rectangles and a viewport margin. | `paintWindow` crops a 2560 x 1440 player-centered backing image. Near a crop margin it queues a background full-scene recenter. | +| Early visibility | `ItemSorter::AddItem` fetches frame dimensions, computes the projected frame rectangle, and rejects a rectangle outside the render clip before overlap/dependency sorting. | `prepareRenderNodes` prepares and orders items before `MapSceneRenderer::render` intersects node rectangles with the output crop. The raster loop avoids off-crop pixels, but off-crop nodes have already been prepared and sorted. | +| Occlusion/order | `SortItem::below`, `overlap`, and `occludes` drive dependency links and painter order. ScummVM adds Crusader-specific sprite and inventory-item ordering fields/rules. | A complete sort-item vector is passed to `resolveRenderOrder`; this ports several Pentagram/ScummVM geometry rules but is rebuilt for each full render. | +| Sort storage | `GameMapGump` constructs `ItemSorter(2048)`. `BeginDisplayList` recycles the prior list into an unused pool; more nodes are allocated if needed. Per-item dependency storage is also reused. | Render vectors reserve capacity per call, but scene items, nodes, sort items, and the resolved order are reconstructed each full render. | +| Shape cache | `ShapeArchive::getShape` lazily caches a `Shape` by shape number. `Shape` builds `ShapeFrame` objects once; each frame retains a decoded CLUT8 pixel surface. | `MapSceneRenderer` retains decoded `DecodedShapeFrame` entries by shape/frame, including palette-expanded pixel colors. Parsed frame collections are local to a render call. | +| Pixel path | `RenderSurface::Paint` walks the cached indexed frame surface and maps pixels through the palette into a `Graphics::ManagedSurface`. The engine paints the gump tree, ends painting, and calls `Graphics::Screen::update()`. | The renderer creates a `RenderedMapImage`, converts it to BGR DIB pixels, copies the visible crop, overlays a separate player patch, and calls `StretchDIBits`. | +| Update cadence | `Ultima8Engine::paint` paints the desktop/gump tree each frame; `GameMapGump` rebuilds and paints the current display list at the interpolated camera position. | The window paints the cached bitmap on `WM_PAINT`; a worker handles player patches and occasional full-scene recentering. Player patch work is now published before a full refresh. | + +## ScummVM Details + +### Camera-Relative Fast Area + +`CurrentMap` uses a 64 x 64 chunk grid. Its chunk size is 1024 world units for Crusader and 512 for Ultima VIII. `updateFastArea` builds a projected screen-space region from the camera's `from`/`to` positions and map-gump dimensions, expands it by a coarse margin, then checks candidate chunks with `ChunkOnScreen`. Chunks changing state call `setChunkFast` or `unsetChunkFast`, which notify their items through `enterFastArea` and `leaveFastArea`. + +The camera calls this update while interpolating. Therefore the active area follows camera movement before the viewport reaches its new position. Importantly, fast-area transitions are also gameplay lifecycle events: eggs and other items can perform work on entry/exit. A native renderer should initially build a separate render-candidate index unless it is also ready to model those world-state transitions. + +### Clipped Display List And Crusader Ordering + +`GameMapGump::PaintThis` obtains the interpolated camera, determines a roof Z limit, begins a display list with the surface clip rectangle, and submits eligible items from fast chunks. It filters roof/editor content and preserves a special path for the invisible main actor. `ItemSorter::AddItem` computes footpad and frame bounds, then skips a frame that does not intersect the clip before scanning existing visible entries for overlap and ordering dependencies. + +`SortItem::below` includes geometry-based ordering plus special cases for Crusader sprites, inventory items, translucent/animated/flat pieces, roofs, and other shape flags. `PaintDisplayList` recursively paints dependencies and skips occluded nodes. There is an experimental occlusion grouping path behind `SORTITEM_OCCLUSION_EXPERIMENTAL`; it is not the default contract. Like Pentagram, insertion compares a new visible item against prior list entries, so reducing the active/clipped candidate count is central to keeping this sorter practical. + +### Cached Indexed Frames And Managed Surface + +`ShapeArchive::cache` loads a shape on first use and retains it in the archive's shape vector. `Shape` parses each raw frame into an intermediate `RawShapeFrame`, constructs a `ShapeFrame`, then releases the intermediate. `ShapeFrame` expands RLE into a `Graphics::Surface` in CLUT8 format and retains that indexed image. `RenderSurface::Paint` maps the indexed pixels through the shape's native palette into the active 8-, 16-, or 32-bit surface path supported by that method. + +This differs from both nearby implementations: Pentagram's software painter walks RLE runs while drawing, while the rebuild stores palette-expanded decoded pixels in its renderer cache. ScummVM pays a one-time indexed-frame expansion and keeps palette mapping separate from frame pixels. + +`Ultima8Engine::paint` wraps gump rendering with `BeginPainting`/`EndPainting` and then calls `_screen->update()`. The render surface is backed by ScummVM's `Graphics::ManagedSurface`/`Graphics::Screen`; this source path is a CPU pixel renderer feeding ScummVM's presentation system, not a dedicated GPU scene renderer. + +ScummVM also has useful diagnostic hooks: `PAINT_TIMING` can report average paint time, and the debugger command `RenderSurface::benchmark ` measures normal, translucent, mirrored, invisible, and highlighted shape draws. Those hooks can guide a controlled comparison, but no ScummVM benchmark was run for this note. + +## Differences That Matter For The Rebuild + +1. **Candidate selection precedes ordering in ScummVM.** The rebuild's output crop is applied after node preparation and global ordering. A native chunk/spatial index plus conservative frame bounds could reject most map items before decode and sorting. +2. **ScummVM keeps rendering in world coordinates.** It doesn't depend on a player-centered cached map image with a recenter edge. The rebuild's current prefetch avoids waiting for that edge, but a full scene refresh still rebuilds the map-wide candidate/node/order pipeline. +3. **ScummVM separates frame color indices from screen format.** Its retained CLUT8 frames use less memory than a same-sized RGB cache and can be mapped for the current output format. The tradeoff is palette lookup during each draw. Benchmark memory, decode time, and raster time before changing the rebuild's RGB cache. +4. **Its active area is simulation-visible.** `enterFastArea`/`leaveFastArea` have item callbacks. Rendering-only culling should not deactivate gameplay objects or scripts by accident. +5. **The sorter is not an interchangeable library.** ScummVM's current comparison paths include Crusader-specific `_sprite`/`_invitem` flags, clip handling, and ordering corrections. Preserve local tests and compare these cases one by one rather than copying the entire class. +6. **The display-list pool doesn't eliminate sort cost.** It avoids repeated node allocation, but each paint still gathers active items, tests visible candidates pairwise, resolves dependencies, and rasterizes the display list. Benefits depend on keeping the fast area bounded. + +## Practical Directions + +1. Build a native chunk index over fixed/live map records and glob-expanded placements. Query the viewport plus a configurable overscan margin; keep its membership separate from gameplay activation until item enter/leave behavior is ported. +2. Move conservative projected frame-rectangle rejection ahead of node creation, decoded-frame misses, and dependency comparisons. Keep final pixel clipping for correctness. +3. Reuse node and dependency storage, or cache static geometry/order and update only mutable entries. Invalidate on position/frame/flag changes, glob hatch changes, roofs, transparency, and world-script mutations. +4. Benchmark the three frame representations explicitly: Pentagram's direct RLE walk, ScummVM's cached CLUT8 frame, and the rebuild's palette-expanded decoded frame. Measure a representative map and movement, not only an isolated sprite. +5. Record active chunk/item counts, clip rejects, frame-cache hits/misses, sorter comparisons, painted nodes, pixel coverage, and separate collection/sort/raster/present times. The rebuild's instrumented map-1 run previously produced 16,542 candidates, 16,540 decoded nodes, and 1,355 painted nodes in about 0.76 seconds for initial publication; repeated full recenter cost and animation contention need separate measurements. + +The original Crusader executable's 6 x 5 dirty-tile draw system is a separate mechanism documented in [raw-0007-rendering.md](raw-0007-rendering.md). ScummVM's fast chunks control which world items are active and considered; they are not that original screen-tile dirty map. + +## Source References + +### ScummVM + +- [`GameMapGump::PaintThis`](../../../misc/scummvm/engines/ultima/ultima8/gumps/game_map_gump.cpp) +- [`ItemSorter::BeginDisplayList`, `AddItem`, and `PaintDisplayList`](../../../misc/scummvm/engines/ultima/ultima8/world/item_sorter.cpp) +- [`SortItem` geometry and ordering rules](../../../misc/scummvm/engines/ultima/ultima8/world/sort_item.cpp) +- [`CurrentMap::updateFastArea` and chunk transitions](../../../misc/scummvm/engines/ultima/ultima8/world/current_map.cpp), [`CameraProcess`](../../../misc/scummvm/engines/ultima/ultima8/world/camera_process.cpp) +- [`ShapeArchive` lazy shape cache](../../../misc/scummvm/engines/ultima/ultima8/gfx/shape_archive.cpp), [`Shape` frame construction](../../../misc/scummvm/engines/ultima/ultima8/gfx/shape.cpp), and [`ShapeFrame` indexed decode](../../../misc/scummvm/engines/ultima/ultima8/gfx/shape_frame.cpp) +- [`RenderSurface`](../../../misc/scummvm/engines/ultima/ultima8/gfx/render_surface.cpp), [`Ultima8Engine::paint`](../../../misc/scummvm/engines/ultima/ultima8/ultima8.cpp), and [`RenderSurface::benchmark`](../../../misc/scummvm/engines/ultima/ultima8/misc/debugger.cpp) + +### Native Rebuild + +- [`MapSceneRenderer::render`, item collection, and node preparation](../rebuild/remorse/src/map_renderer.cpp) +- [`fullSceneOptions`, `startLiveRenderer`, and `paintWindow`](../rebuild/remorse/src/windowed_game_main.cpp) +- [Existing map-renderer format and sorting notes](map-rendering.md) \ No newline at end of file diff --git a/play-remorse-rebuild.bat b/play-remorse-rebuild.bat new file mode 100644 index 0000000..7b88c98 --- /dev/null +++ b/play-remorse-rebuild.bat @@ -0,0 +1,17 @@ +@echo off +setlocal +set "ROOT=%~dp0" +set "GAME=%ROOT%rebuild\remorse\out\build-controller-verify\remorse_game.exe" + +if not exist "%GAME%" ( + echo Could not find the rebuild executable: + echo %GAME% + pause + exit /b 1 +) + +pushd "%ROOT%" +"%GAME%" %* +set "RESULT=%ERRORLEVEL%" +popd +exit /b %RESULT% \ No newline at end of file diff --git a/py_mcp_query.py b/py_mcp_query.py new file mode 100644 index 0000000..d802e0a --- /dev/null +++ b/py_mcp_query.py @@ -0,0 +1,28 @@ +import json + +addrs = ["000d:44df","000d:4c99","000d:7000","000d:46ec"] +results = {} + +try: + import ghidra_mcp +except Exception as e: + print(json.dumps({"error": "missing ghidra_mcp module", "exc": str(e)})) + raise SystemExit(1) + +for a in addrs: + entry = {} + try: + entry['decompile'] = ghidra_mcp.decompile_function(a) + except Exception as e: + entry['decompile_error'] = str(e) + try: + entry['disassemble'] = ghidra_mcp.disassemble_function(a) + except Exception as e: + entry['disassemble_error'] = str(e) + try: + entry['xrefs'] = ghidra_mcp.get_xrefs(a) + except Exception as e: + entry['xrefs_error'] = str(e) + results[a] = entry + +print(json.dumps(results)) diff --git a/rebuild/remorse/include/remorse/entity_dispatch_entry.h b/rebuild/remorse/include/remorse/entity_dispatch_entry.h index 2d58a5e..343f2dd 100644 --- a/rebuild/remorse/include/remorse/entity_dispatch_entry.h +++ b/rebuild/remorse/include/remorse/entity_dispatch_entry.h @@ -145,6 +145,8 @@ public: EntityVmContextProcessEntry* createUsecodeProcess(u8 activeGroup, u16 (&groupCounts)[32]); bool startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items, const AnimationClip& clip, u8 frameSkip = 0); + std::optional updateAnimPrimitiveDirection(u16 processId, LiveFixedMapItems& items, + u8 direction); std::optional advanceGroundedAnimPrimitive(u16 processId, LiveFixedMapItems& items, const AnimationClip& clip, const std::vector& shapes, const FastAreaRange& fastArea); diff --git a/rebuild/remorse/include/remorse/fixed_map.h b/rebuild/remorse/include/remorse/fixed_map.h index c45029a..e2469ba 100644 --- a/rebuild/remorse/include/remorse/fixed_map.h +++ b/rebuild/remorse/include/remorse/fixed_map.h @@ -110,6 +110,7 @@ struct NpcAnimationState { u16 lastAnimation = 0xffff; u8 frame = 0; u8 moreFlags = 0; + u8 direction = 0; }; class LiveFixedMapItems { diff --git a/rebuild/remorse/include/remorse/isometric_controls.h b/rebuild/remorse/include/remorse/isometric_controls.h index 3120aad..59fdc44 100644 --- a/rebuild/remorse/include/remorse/isometric_controls.h +++ b/rebuild/remorse/include/remorse/isometric_controls.h @@ -4,10 +4,15 @@ #include "remorse/compat.h" #include +#include #include namespace remorse { +inline constexpr std::array controllerAnimationIndices{ + 0, 1, 2, 3, 4, 0x0b, 0x10, 0x17, 0x18, 0x1c, 0x1d, 0x20, 0x22, + 0x24, 0x26, 0x28, 0x29, 0x2e, 0x30, 0x37, 0x38, 0x3a, 0x3b, 0x3d, 0x3e}; + struct WorldPositionD { double x = 0.0; double y = 0.0; @@ -20,6 +25,48 @@ inline bool controllerWalkRequested(u16 modifiers) return shiftDown == capsLockOn; } +inline bool controllerAllowsInPlaceDirectionUpdate(u8 animation) +{ + switch (animation) { + case 1: case 3: case 4: case 7: case 8: case 10: case 12: case 13: case 15: + case 25: case 34: case 35: case 36: case 37: case 38: case 39: case 42: case 43: + case 44: case 45: case 46: case 47: case 48: case 49: case 50: case 54: + return true; + default: + return false; + } +} + +inline bool controllerLastAnimationIsRunning(u8 animation) +{ + switch (animation) { + case 1: case 3: case 34: case 35: case 38: case 48: case 49: case 56: + return true; + default: + return false; + } +} + +inline bool controllerLastAnimationIsRunningJumping(u8 animation) +{ + switch (animation) { + case 3: case 48: case 49: case 56: + return true; + default: + return false; + } +} + +inline bool controllerLastAnimationIsNotCombat(u8 animation) +{ + switch (animation) { + case 0: case 1: case 11: case 16: case 32: case 55: case 58: case 59: + return true; + default: + return false; + } +} + inline std::optional controllerDirectionFromScan(u8 scanCode) { // Controller_PickNextAnimByKeyevent (1130:12d6), directional keys with Num Lock off. @@ -39,41 +86,324 @@ inline std::optional controllerDirectionFromScan(u8 scanCode) struct ControllerMovementRequest { u8 animation = 0; u8 direction = 14; + bool oneShot = false; + bool updateDirectionInPlace = false; +}; + +enum class ControllerCommand : u8 { + FireWeapon, + SelectNextItem, + CycleWeaponForward, + OpenInventory +}; + +struct ControllerCommandRequest { + ControllerCommand command = ControllerCommand::FireWeapon; +}; + +struct ControllerActorState { + u16 npcNumber = 1; + u16 mapNumber = 1; + u8 direction = 14; + u8 lastAnimation = 0; + bool controllerEnabled = true; + bool dead = false; + bool avatarInStasis = false; + bool kneeling = false; + bool activeWeapon = false; + bool busy = false; + bool lastAnimationNotCombat = true; + bool avatarSomethingCombatty = false; }; class ControllerMovementState { public: + void setActorState(const ControllerActorState& state) + { + if (state.direction != actor_.direction) { + lastDirection_ = state.direction; + } + actor_ = state; + setFacingDirection(state.direction); + crouched_ = state.kneeling; + } + void handleDirectionalKey(u8 scanCode, u16 modifiers, bool pressed) { - modifiers_ = modifiers; - const auto direction = controllerDirectionFromScan(scanCode); - if (!direction) { + handleKeyEvent(scanCode, modifiers, 1, pressed ? 1 : 0, pressed ? 1 : 0); + } + + void handleKeyEvent(u8 scanCode, u16 modifiers, u8 eventMode, u8 keyState, + u16 keyAction = 1, u16 eventFlags = 0) + { + if (!actor_.controllerEnabled || actor_.npcNumber == 0 || actor_.dead || + (actor_.npcNumber == 1 && actor_.avatarInStasis)) { return; } + modifiers_ = modifiers; + if (eventMode == 0) { + return; + } + if (keyState != 0 && keyAction == 1 && actor_.npcNumber == 1 && + (scanCode == 0x0f || scanCode == 0x24)) { + if (!actor_.busy || (actor_.lastAnimation != 56 && + controllerLastAnimationIsRunningJumping(actor_.lastAnimation))) { + pendingAction_ = ControllerMovementRequest{56, actor_.direction, true}; + } + return; + } + if (keyState != 0 && keyAction == 1 && actor_.npcNumber == 1) { + if ((scanCode == 0x39 || scanCode == 0x52) && actor_.mapNumber != 0x40 && + !actor_.busy && (scanCode != 0x52 || eventFlags == 0)) { + pendingCommand_ = ControllerCommandRequest{ControllerCommand::FireWeapon}; + return; + } + if (scanCode == 0x4a) { + pendingCommand_ = ControllerCommandRequest{ControllerCommand::SelectNextItem}; + return; + } + if (scanCode == 0x37 && eventFlags == 0) { + pendingCommand_ = ControllerCommandRequest{ControllerCommand::CycleWeaponForward}; + return; + } + if (scanCode == 0x4e || (scanCode == 0x53 && eventFlags == 0)) { + pendingCommand_ = ControllerCommandRequest{ControllerCommand::OpenInventory}; + return; + } + } const auto held = std::find(heldScans_.begin(), heldScans_.end(), scanCode); if (held != heldScans_.end()) { heldScans_.erase(held); } - if (pressed && (modifiers & 0x20) == 0) { + constexpr u16 actionModifierMask = 0x0f00; + if ((modifiers & actionModifierMask) != 0) { + if (keyState != 0) { + queueModifiedAction(scanCode, modifiers, keyAction); + } + return; + } + const bool numLockOn = (modifiers & 0x20) != 0; + if (keyState != 0 && !numLockOn && actor_.mapNumber != 0x40 && !actor_.busy && + actor_.avatarSomethingCombatty && (scanCode == 0x4b || scanCode == 0x4d)) { + const int turn = scanCode == 0x4b ? -1 : 1; + lastDirection_ = static_cast((actor_.direction + turn + 16) & 0x0f); + pendingAction_ = ControllerMovementRequest{ + static_cast(actor_.kneeling ? 0x2e : 4), lastDirection_, true}; + return; + } + if (numLockOn && (scanCode == 0x4b || scanCode == 0x4d)) { + if (keyState != 0) { + if (actor_.busy) { + if (controllerAllowsInPlaceDirectionUpdate(actor_.lastAnimation)) { + pendingInPlaceDirection_ = static_cast(scanCode == 0x4b ? 0x12 : 0x11); + } + } else { + const int turn = scanCode == 0x4b ? -turnStep_ : turnStep_; + lastDirection_ = static_cast((facingDirection_ + turn + 16) & 0x0f); + } + } + return; + } + if (numLockOn && scanCode != 0x48 && scanCode != 0x50) { + return; + } + const auto direction = controllerDirectionFromScan(scanCode); + if (!direction) { + if (keyState != 0) { + queueModifiedAction(scanCode, modifiers, keyAction); + } + return; + } + if (keyState != 0) { heldScans_.push_back(scanCode); } + if (keyState != 0) { + queueModifiedAction(scanCode, modifiers, keyAction); + } } ControllerMovementRequest request() const { + if (!actor_.controllerEnabled || actor_.npcNumber == 0 || actor_.dead || + (actor_.npcNumber == 1 && actor_.avatarInStasis)) { + return {0, actor_.direction}; + } + if (pendingInPlaceDirection_) { + return {actor_.lastAnimation, *pendingInPlaceDirection_, false, true}; + } if (heldScans_.empty()) { return {0, lastDirection_}; } - lastDirection_ = *controllerDirectionFromScan(heldScans_.back()); - return {static_cast(controllerWalkRequested(modifiers_) ? 1 : 3), lastDirection_}; + const u8 runAnimation = actor_.activeWeapon ? 0x30 : 3; + const u8 scanCode = heldScans_.back(); + const bool numLockOn = (modifiers_ & 0x20) != 0; + const u8 requestedDirection = numLockOn && (scanCode == 0x48 || scanCode == 0x50) + ? facingDirection_ : *controllerDirectionFromScan(scanCode); + lastDirection_ = requestedDirection; + const bool walkRequested = controllerWalkRequested(modifiers_); + if (actor_.mapNumber == 0x40) { + if (controllerLastAnimationIsRunning(actor_.lastAnimation)) { + return {static_cast(walkRequested ? 1 : runAnimation), requestedDirection}; + } + if (requestedDirection == actor_.direction) { + return {static_cast(walkRequested ? 1 : 0x26), requestedDirection}; + } + return {0, requestedDirection}; + } + if (!walkRequested && requestedDirection == actor_.direction && + !controllerLastAnimationIsRunning(actor_.lastAnimation)) { + return {0x22, requestedDirection}; + } + if ((modifiers_ & 0x20) != 0) { + if (scanCode == 0x48) { + return {static_cast(walkRequested ? 1 : runAnimation), requestedDirection}; + } + if (scanCode == 0x50) { + return {2, requestedDirection}; + } + } + return {static_cast(walkRequested ? 1 : runAnimation), requestedDirection}; } - void clear() { heldScans_.clear(); } + std::optional takeInPlaceDirectionUpdate() + { + auto direction = pendingInPlaceDirection_; + pendingInPlaceDirection_.reset(); + return direction; + } + + void setFacingDirection(u8 direction) + { + if (direction <= 15) { + facingDirection_ = direction; + } + } + + void setTurnStep(u8 step) + { + turnStep_ = step == 1 ? 1 : 2; + } + + std::optional takeActionRequest() + { + auto action = pendingAction_; + pendingAction_.reset(); + return action; + } + + std::optional takeCommandRequest() + { + auto command = pendingCommand_; + pendingCommand_.reset(); + return command; + } + + void clear() + { + heldScans_.clear(); + pendingAction_.reset(); + pendingCommand_.reset(); + pendingInPlaceDirection_.reset(); + modifiers_ = 0; + } private: + void queueModifiedAction(u8 scanCode, u16 modifiers, u16 keyAction) + { + constexpr u16 altMask = 0x0a00; + constexpr u16 ctrlMask = 0x0500; + constexpr u8 animationNone = 0x40; + u8 animation = animationNone; + u8 actionDirection = lastDirection_; + if (scanCode == 0x4c) { + if (keyAction == 1) { + animation = crouched_ ? 0x29 : 0x28; + } + } else if ((modifiers & (altMask | ctrlMask)) == 0 && scanCode == 0x35) { + if (actor_.mapNumber != 0x40 && !controllerLastAnimationIsRunning(actor_.lastAnimation)) { + animation = 0x24; + } + } else if ((modifiers & altMask) != 0) { + const bool numLockOn = (modifiers & 0x20) != 0; + const auto scanDirection = controllerDirectionFromScan(scanCode); + if (numLockOn && scanDirection) { + int newDirection = *scanDirection; + if (scanCode == 0x4b) { + newDirection = 0x12; + } else if (scanCode == 0x4d) { + newDirection = 0x11; + } + const int direction = actor_.direction; + const int directionDelta = newDirection < direction + ? direction - newDirection : direction + 0x10 - newDirection; + if (0x10 - directionDelta < directionDelta) { + animation = 0x1d; + actionDirection = static_cast((newDirection - 4) & 0x0f); + } else { + animation = 0x1c; + actionDirection = static_cast((newDirection + 4) & 0x0f); + } + } else { + switch (scanCode) { + case 0x48: animation = 0x24; break; + case 0x4b: animation = 0x1c; break; + case 0x4d: animation = 0x1d; break; + case 0x50: animation = 2; break; + default: break; + } + } + } else if ((modifiers & ctrlMask) != 0) { + const auto requestedDirection = controllerDirectionFromScan(scanCode); + if ((modifiers & 0x20) == 0 && requestedDirection && + (scanCode == 0x47 || scanCode == 0x49 || scanCode == 0x4f || scanCode == 0x51)) { + const int direction = actor_.direction; + const int directionDelta = *requestedDirection < direction + ? direction - *requestedDirection : direction + 0x10 - *requestedDirection; + if (0x10 - directionDelta < directionDelta) { + animation = 0x18; + actionDirection = static_cast((*requestedDirection - 4) & 0x0f); + } else { + animation = 0x17; + actionDirection = static_cast((*requestedDirection + 4) & 0x0f); + } + } else switch (scanCode) { + case 0x48: + if (crouched_) { + animation = 0x29; + } else if (!actor_.lastAnimationNotCombat) { + animation = 0x0b; + } else if (actor_.npcNumber == 1) { + animation = 0x3a; + } + break; + case 0x4b: animation = crouched_ ? 0x17 : 0x3d; break; + case 0x4d: animation = crouched_ ? 0x18 : 0x3e; break; + case 0x50: + if (keyAction == 1) { + animation = crouched_ ? 0x29 : 0x28; + } + break; + default: break; + } + } + if (animation != animationNone) { + pendingAction_ = ControllerMovementRequest{animation, actionDirection, true}; + if (animation == 0x28 || animation == 0x29) { + crouched_ = !crouched_; + } + } + } + std::vector heldScans_; + std::optional pendingAction_; + std::optional pendingCommand_; + std::optional pendingInPlaceDirection_; u16 modifiers_ = 0; mutable u8 lastDirection_ = 14; + u8 facingDirection_ = 14; + u8 turnStep_ = 2; + bool crouched_ = false; + ControllerActorState actor_{}; }; inline std::optional hostMovementStep( diff --git a/rebuild/remorse/include/remorse/shape_archive.h b/rebuild/remorse/include/remorse/shape_archive.h index dcd574c..fddd3b1 100644 --- a/rebuild/remorse/include/remorse/shape_archive.h +++ b/rebuild/remorse/include/remorse/shape_archive.h @@ -30,6 +30,7 @@ struct ShapeArchive { std::optional loadShapeArchive(const std::filesystem::path& path); std::optional> loadShapeFrames(const ShapeArchive& archive, u32 shapeIndex); +std::optional decodeShapeFrame(const ShapeFrame& frame); std::optional decodeShapeFrame(const ShapeArchive& archive, u32 shapeIndex, u32 frameIndex); } // namespace remorse diff --git a/rebuild/remorse/src/entity_dispatch_entry.cpp b/rebuild/remorse/src/entity_dispatch_entry.cpp index ebf1cad..e4f2365 100644 --- a/rebuild/remorse/src/entity_dispatch_entry.cpp +++ b/rebuild/remorse/src/entity_dispatch_entry.cpp @@ -367,6 +367,37 @@ bool ProcessKernel::startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& return true; } +std::optional ProcessKernel::updateAnimPrimitiveDirection(u16 processId, + LiveFixedMapItems& items, u8 direction) +{ + auto* process = processAt(processId); + if (direction > 0x12 || process == nullptr || + allocationSizeAt(processId) != sizeof(AnimPrimitiveProcessEntry) || + (readLe16(*process, 0x16) & 0x08) != 0 || process->bytes[0x3a] == 0 || + std::none_of(ownedAnimPrimitiveProcesses_.begin(), ownedAnimPrimitiveProcesses_.end(), + [process](const auto& owned) { return &owned->base == process; })) { + return std::nullopt; + } + auto* npc = items.editNpcAnimation(readLe16(*process, 0x04)); + if (npc == nullptr) { + return std::nullopt; + } + const bool relative = direction >= 0x10; + const bool turnClockwise = direction == 0x11; + const bool turnCounterclockwise = direction == 0x12; + direction = relative ? npc->direction : direction; + if ((process->bytes[0x4d] & 0x40) == 0) { + direction = static_cast(direction & 0x0e); + } + if (turnClockwise || turnCounterclockwise) { + const u8 step = (process->bytes[0x4d] & 0x40) == 0 ? 2 : 1; + direction = static_cast((direction + (turnClockwise ? step : 16 - step)) & 0x0f); + } + process->bytes[0x38] = direction; + npc->direction = direction; + return direction; +} + std::optional ProcessKernel::advanceGroundedAnimPrimitive(u16 processId, LiveFixedMapItems& items, const AnimationClip& clip, const std::vector& shapes, const FastAreaRange& fastArea) @@ -400,9 +431,13 @@ std::optional ProcessKernel::advanceGroundedAnimPrimitive(u16 processId, } const u8 direction = process->bytes[0x38]; const auto metadata = getAnimationFrame(clip, direction, nextFrame); - if (!metadata || (metadata->bytes[5] & 2) == 0) { + if (!metadata) { return std::nullopt; } + if ((metadata->bytes[5] & 2) == 0) { + npc->frame = nextFrame; + return true; + } const auto step = decodeAnimationDisplacement(*metadata, direction, (clip.header[2] & 0x10) != 0); if (!step) { return std::nullopt; diff --git a/rebuild/remorse/src/fixed_map.cpp b/rebuild/remorse/src/fixed_map.cpp index 700e005..9ab9dd8 100644 --- a/rebuild/remorse/src/fixed_map.cpp +++ b/rebuild/remorse/src/fixed_map.cpp @@ -501,6 +501,7 @@ bool LiveFixedMapItems::initializeAvatar() avatar_->data.shape = 1; avatar_->data.npcNumber = 1; npcAnimations_.resize(2); + npcAnimations_[1].direction = 14; return true; } diff --git a/rebuild/remorse/src/map_renderer.cpp b/rebuild/remorse/src/map_renderer.cpp index a6b0f86..81a894c 100644 --- a/rebuild/remorse/src/map_renderer.cpp +++ b/rebuild/remorse/src/map_renderer.cpp @@ -9,6 +9,7 @@ #include #include #include +#include namespace remorse { namespace { @@ -71,16 +72,6 @@ RgbColor scalePaletteColor(const RgbColor& color) return scaled; } -std::optional findGlobObject(const std::vector& globs, u32 index) -{ - for (const GlobObject& object : globs) { - if (object.index == index) { - return object; - } - } - return std::nullopt; -} - std::vector collectSceneItems( const FixedMap& fixedMap, const std::vector& typeFlags, @@ -88,6 +79,12 @@ std::vector collectSceneItems( const MapRenderOptions& options, const LiveFixedMapItems* liveItems) { + std::unordered_map globsByIndex; + globsByIndex.reserve(globs.size()); + for (const GlobObject& glob : globs) { + globsByIndex.try_emplace(glob.index, &glob); + } + std::vector pending; pending.reserve(fixedMap.entries.size()); std::vector liveByRecord; @@ -145,9 +142,9 @@ std::vector collectSceneItems( const auto* stagedEgg = liveByRecord.empty() || index >= liveByRecord.size() ? nullptr : liveByRecord[index]; const auto glob = stagedEgg && liveItems->isGlobHatched(stagedEgg->itemNumber) - ? std::nullopt : findGlobObject(globs, item.quality); - if (glob) { - for (const GlobObjectEntry& entry : glob->entries) { + ? globsByIndex.end() : globsByIndex.find(item.quality); + if (glob != globsByIndex.end()) { + for (const GlobObjectEntry& entry : glob->second->entries) { pending.push_back(SceneItem{ (item.x & globCoordMask) + (static_cast(entry.x) << globCoordShift) + globCoordOffset, (item.y & globCoordMask) + (static_cast(entry.y) << globCoordShift) + globCoordOffset, @@ -184,6 +181,7 @@ s32 screenY(const SceneItem& item) const DecodedShapeFrame* cachedDecode( const ShapeArchive& archive, + std::map>& parsedFrames, std::map, DecodedShapeFrame>& cache, u32 shape, u32 frame) @@ -193,7 +191,18 @@ const DecodedShapeFrame* cachedDecode( if (found != cache.end()) { return &found->second; } - const auto decoded = decodeShapeFrame(archive, shape, frame); + auto parsed = parsedFrames.find(shape); + if (parsed == parsedFrames.end()) { + auto frames = loadShapeFrames(archive, shape); + if (!frames) { + return nullptr; + } + parsed = parsedFrames.emplace(shape, std::move(*frames)).first; + } + if (frame >= parsed->second.size()) { + return nullptr; + } + const auto decoded = decodeShapeFrame(parsed->second[frame]); if (!decoded) { return nullptr; } @@ -203,6 +212,7 @@ const DecodedShapeFrame* cachedDecode( std::vector prepareRenderNodes( const std::vector& items, const ShapeArchive& shapeArchive, + std::map>& parsedFrames, const std::vector& typeFlags, std::map, DecodedShapeFrame>& cache) { @@ -212,7 +222,8 @@ std::vector prepareRenderNodes( sortItems.reserve(items.size()); for (const SceneItem& item : items) { const auto* decoded = item.decodedOverride != nullptr - ? item.decodedOverride : cachedDecode(shapeArchive, cache, item.shape, item.frame); + ? item.decodedOverride : cachedDecode( + shapeArchive, parsedFrames, cache, item.shape, item.frame); if (!decoded) { continue; } @@ -371,7 +382,8 @@ std::optional MapSceneRenderer::render(const MapRenderOptions& items.push_back(sceneSprite); } } - auto nodes = prepareRenderNodes(items, shapes, typeFlags, decodedFrames); + std::map> parsedFrames; + auto nodes = prepareRenderNodes(items, shapes, parsedFrames, typeFlags, decodedFrames); if (nodes.empty()) { return std::nullopt; } diff --git a/rebuild/remorse/src/shape_archive.cpp b/rebuild/remorse/src/shape_archive.cpp index 5e4faef..bf448a0 100644 --- a/rebuild/remorse/src/shape_archive.cpp +++ b/rebuild/remorse/src/shape_archive.cpp @@ -185,21 +185,27 @@ std::optional> loadShapeFrames(const ShapeArchive& archi return frames; } -std::optional decodeShapeFrame(const ShapeArchive& archive, u32 shapeIndex, u32 frameIndex) +std::optional decodeShapeFrame(const ShapeFrame& frame) { - const auto frames = loadShapeFrames(archive, shapeIndex); - if (!frames || frameIndex >= frames->size()) { - return std::nullopt; - } - const auto pixels = decodePixels((*frames)[frameIndex]); + const auto pixels = decodePixels(frame); if (!pixels) { return std::nullopt; } DecodedShapeFrame decoded; - decoded.frame = (*frames)[frameIndex]; + decoded.frame = frame; decoded.pixels = *pixels; return decoded; } +std::optional decodeShapeFrame( + const ShapeArchive& archive, u32 shapeIndex, u32 frameIndex) +{ + const auto frames = loadShapeFrames(archive, shapeIndex); + if (!frames || frameIndex >= frames->size()) { + return std::nullopt; + } + return decodeShapeFrame((*frames)[frameIndex]); +} + } // namespace remorse diff --git a/rebuild/remorse/src/windowed_game_main.cpp b/rebuild/remorse/src/windowed_game_main.cpp index ffc6f47..3acb299 100644 --- a/rebuild/remorse/src/windowed_game_main.cpp +++ b/rebuild/remorse/src/windowed_game_main.cpp @@ -66,6 +66,8 @@ struct AppState { remorse::StandProcessEntry* diagnosticStand = nullptr; remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr; remorse::ControllerMovementState controllerMovement; + std::optional lastControllerCommand; + std::optional activeOneShotMovement; remorse::u16 animationProcessId = 0; std::optional liveItems; std::optional diagnosticItem; @@ -82,14 +84,12 @@ struct AppState { std::condition_variable renderWake; bool renderRequested = false; bool renderFullRequested = false; - std::uint64_t renderGeneration = 0; + bool renderFullInFlight = false; bool renderStop = false; std::optional scene; std::optional playerPatch; std::optional renderer; - std::optional standAnimation; - std::optional walkAnimation; - std::optional runAnimation; + std::array, 0x40> playerAnimations; std::vector> playerFrames; remorse::CollisionBody playerCollisionBody{}; std::vector collisionBodies; @@ -111,7 +111,10 @@ struct AppState { remorse::u8 playerAnimation = 0; remorse::u8 playerDirection = 14; remorse::u8 playerFrame = 0; + bool playerKneeling = false; + bool playerHasActiveWeapon = false; std::wstring loadError; + bool loadErrorShown = false; bool sceneLoaded = false; std::thread sceneThread; std::thread renderThread; @@ -153,6 +156,29 @@ void setLoadFailure(AppState& state, const std::wstring& message) state.sceneLoaded = true; } +void reportLoadFailure(HWND window, AppState& state, const std::wstring& message) +{ + setLoadFailure(state, message); + if (!PostMessageW(window, sceneReadyMessage, 0, 0)) { + InvalidateRect(window, nullptr, FALSE); + } +} + +void displayLoadFailure(HWND window, AppState& state) +{ + std::wstring message; + { + std::lock_guard lock(state.sceneMutex); + if (state.loadError.empty() || state.loadErrorShown) { + return; + } + state.loadErrorShown = true; + message = state.loadError; + } + InvalidateRect(window, nullptr, FALSE); + MessageBoxW(window, message.c_str(), L"Crusader map loading failed", MB_OK | MB_ICONERROR); +} + remorse::WorldPoint avatarWorld(const AppState& state) { const auto* avatar = state.liveItems ? state.liveItems->findItem(1) : nullptr; @@ -176,19 +202,25 @@ remorse::MapRenderOptions playerPatchOptions(remorse::u32 mapIndex, return options; } +remorse::MapRenderOptions fullSceneOptions(remorse::u32 mapIndex, + const remorse::WorldPoint& center) +{ + remorse::MapRenderOptions options; + options.mapIndex = mapIndex; + options.maxWidth = backingWidth; + options.maxHeight = backingHeight; + options.includeRoofs = true; + options.viewCenter = center; + return options; +} + std::optional playerRenderSprite(const AppState& state) { - const remorse::AnimationClip* clip = nullptr; - if (state.playerAnimation == 1 && state.walkAnimation) { - clip = &*state.walkAnimation; - } else if (state.playerAnimation == 3 && state.runAnimation) { - clip = &*state.runAnimation; - } else if (state.standAnimation) { - clip = &*state.standAnimation; - } - if (!clip) { + if (state.playerAnimation >= state.playerAnimations.size() || + !state.playerAnimations[state.playerAnimation]) { return std::nullopt; } + const remorse::AnimationClip* clip = &*state.playerAnimations[state.playerAnimation]; const remorse::u8 frameIndex = state.playerAnimation == 0 ? 0 : state.playerFrame; const auto metadata = remorse::getAnimationFrame(*clip, state.playerDirection, frameIndex); @@ -438,7 +470,8 @@ void runUsecodeTasks(AppState& state) void loadSceneAsync(HWND window, AppState& state) { - state.sceneThread = std::thread([window, &state]() { + try { + state.sceneThread = std::thread([window, &state]() { try { const auto fixedPath = remorse::resolveGameDataPath( state.root, std::filesystem::path("STATIC") / "FIXED.DAT"); @@ -458,7 +491,7 @@ void loadSceneAsync(HWND window, AppState& state) } const auto archive = remorse::loadFixedMapArchive(*fixedPath); - const auto map = archive ? remorse::loadFixedMap(*archive, state.mapIndex) : std::nullopt; + auto map = archive ? remorse::loadFixedMap(*archive, state.mapIndex) : std::nullopt; if (!map || map->entries.empty()) { setLoadFailure(state, L"The selected map could not be loaded or contains no records."); PostMessageW(window, sceneReadyMessage, 0, 0); @@ -470,9 +503,8 @@ void loadSceneAsync(HWND window, AppState& state) PostMessageW(window, sceneReadyMessage, 0, 0); return; } - const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath); - const auto globObjects = remorse::loadGlobObjects(*globPath); + auto globObjects = remorse::loadGlobObjects(*globPath); if (!shapeTypes || !globObjects || shapeTypes->size() <= 1) { setLoadFailure(state, L"Collision shape metadata could not be loaded."); PostMessageW(window, sceneReadyMessage, 0, 0); @@ -508,22 +540,23 @@ void loadSceneAsync(HWND window, AppState& state) } const auto animationArchive = remorse::loadAnimationArchive(*animationPath); - const auto shapeArchive = remorse::loadShapeArchive(*shapesPath); + auto shapeArchive = remorse::loadShapeArchive(*shapesPath); const auto palette = remorse::loadPalette256(*palettePath); - const auto standAnimation = animationArchive - ? remorse::loadAnimationClip(*animationArchive, 1, 0) : std::nullopt; - const auto walkAnimation = animationArchive - ? remorse::loadAnimationClip(*animationArchive, 1, 1) : std::nullopt; - const auto runAnimation = animationArchive - ? remorse::loadAnimationClip(*animationArchive, 1, 3) : std::nullopt; + std::array, 0x40> playerAnimations; + if (animationArchive) { + for (const remorse::u8 index : remorse::controllerAnimationIndices) { + playerAnimations[index] = remorse::loadAnimationClip( + *animationArchive, 1, index); + } + } const auto shapeFrames = shapeArchive ? remorse::loadShapeFrames(*shapeArchive, 1) : std::nullopt; - if (!shapeArchive || !palette || !standAnimation || !walkAnimation || !runAnimation || !shapeFrames) { + if (!shapeArchive || !palette || !playerAnimations[0] || !playerAnimations[1] || + !playerAnimations[3] || !shapeFrames) { setLoadFailure(state, L"The player stand, walk, or run animation could not be loaded."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } - std::vector> playerFrames(shapeFrames->size()); const auto cacheAnimationFrames = [&](const remorse::AnimationClip& clip) { for (remorse::u8 direction = 0; direction < 16; ++direction) { @@ -538,7 +571,7 @@ void loadSceneAsync(HWND window, AppState& state) return false; } if (!playerFrames[shapeFrame]) { - auto decoded = remorse::decodeShapeFrame(*shapeArchive, 1, shapeFrame); + auto decoded = remorse::decodeShapeFrame((*shapeFrames)[shapeFrame]); if (!decoded) { return false; } @@ -548,13 +581,13 @@ void loadSceneAsync(HWND window, AppState& state) } return true; }; - if (!cacheAnimationFrames(*standAnimation) || !cacheAnimationFrames(*walkAnimation) || - !cacheAnimationFrames(*runAnimation)) { - setLoadFailure(state, L"A player animation references a missing shape frame."); - PostMessageW(window, sceneReadyMessage, 0, 0); - return; + for (const auto& clip : playerAnimations) { + if (clip && !cacheAnimationFrames(*clip)) { + setLoadFailure(state, L"A player animation references a missing shape frame."); + PostMessageW(window, sceneReadyMessage, 0, 0); + return; + } } - remorse::s32 minX = map->entries.front().x; remorse::s32 minY = map->entries.front().y; remorse::s32 maxX = minX; @@ -586,12 +619,7 @@ void loadSceneAsync(HWND window, AppState& state) ? remorse::WorldPoint{startingEgg->data.x * 2, startingEgg->data.y * 2, startingEgg->data.z} : remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0}; - remorse::MapRenderOptions options; - options.mapIndex = state.mapIndex; - options.maxWidth = backingWidth; - options.maxHeight = backingHeight; - options.includeRoofs = true; - options.viewCenter = spawn; + remorse::MapRenderOptions options = fullSceneOptions(state.mapIndex, spawn); remorse::LiveFixedMapItems liveItems(std::move(*stagedItems), std::move(containedItems)); liveItems.initializeAvatar(); if (startingEgg) { @@ -625,11 +653,11 @@ void loadSceneAsync(HWND window, AppState& state) directStart.data.z = static_cast(spawn.z); liveItems.teleportAvatar(directStart, static_cast(state.mapIndex)); } - auto renderer = remorse::loadMapSceneRenderer(state.root, state.mapIndex); - if (renderer) { - hatchGlobsInFastArea(liveItems, *renderer, remorse::calculateFastAreaRange(spawn)); - } - const auto initialMetadata = remorse::getAnimationFrame(*standAnimation, 14, 0); + remorse::MapSceneRenderer renderer{ + std::move(*map), std::move(*globObjects), std::move(*shapeArchive), + *palette, *shapeTypes, {}}; + hatchGlobsInFastArea(liveItems, renderer, remorse::calculateFastAreaRange(spawn)); + const auto initialMetadata = remorse::getAnimationFrame(*playerAnimations[0], 14, 0); if (!initialMetadata) { setLoadFailure(state, L"The player stand frame could not be resolved."); PostMessageW(window, sceneReadyMessage, 0, 0); @@ -645,27 +673,25 @@ void loadSceneAsync(HWND window, AppState& state) static_cast(initialShapeFrame), remorse::isAnimationFrameFlipped(*initialMetadata), &*playerFrames[initialShapeFrame], &*palette}; - auto scene = renderer ? renderer->render(options, &liveItems) : std::nullopt; + auto scene = renderer.render(options, &liveItems); if (!scene) { setLoadFailure(state, L"Map graphics or palette data could not be loaded."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } - auto playerPatch = renderer ? renderer->render( - playerPatchOptions(state.mapIndex, spawn), &liveItems, &initialPlayer) : std::nullopt; + auto playerPatch = renderer.render( + playerPatchOptions(state.mapIndex, spawn), &liveItems, &initialPlayer); if (!playerPatch) { setLoadFailure(state, L"The initial player render patch could not be built."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } - std::vector dibPixels(scene->pixels.size() * 3); for (std::size_t index = 0; index < scene->pixels.size(); ++index) { dibPixels[index * 3] = scene->pixels[index].blue; dibPixels[index * 3 + 1] = scene->pixels[index].green; dibPixels[index * 3 + 2] = scene->pixels[index].red; } - { std::lock_guard lock(state.sceneMutex); state.spawn = spawn; @@ -685,9 +711,9 @@ void loadSceneAsync(HWND window, AppState& state) state.playerPatch = std::move(playerPatch); state.renderer = std::move(renderer); state.dibPixels = std::move(dibPixels); - state.standAnimation = *standAnimation; - state.walkAnimation = *walkAnimation; - state.runAnimation = *runAnimation; + state.playerAnimations = std::move(playerAnimations); + state.controllerMovement.setTurnStep( + state.playerAnimations[1]->directionCount == 8 ? 2 : 1); state.playerFrames = std::move(playerFrames); state.playerPalette = *palette; state.liveItems.emplace(std::move(liveItems)); @@ -699,7 +725,12 @@ void loadSceneAsync(HWND window, AppState& state) setLoadFailure(state, L"An unexpected error occurred while building the map scene."); } PostMessageW(window, sceneReadyMessage, 0, 0); - }); + }); + } catch (const std::exception& error) { + reportLoadFailure(window, state, widen(error.what())); + } catch (...) { + reportLoadFailure(window, state, L"Could not start the map-loading worker thread."); + } } bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, @@ -728,13 +759,14 @@ bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, void startLiveRenderer(HWND window, AppState& state) { - state.renderThread = std::thread([window, &state]() { + try { + state.renderThread = std::thread([window, &state]() { + try { for (;;) { std::optional snapshot; std::optional playerSprite; remorse::WorldPoint center{}; bool fullRender = false; - std::uint64_t generation = 0; { std::unique_lock lock(state.sceneMutex); state.renderWake.wait(lock, [&state]() { return state.renderStop || state.renderRequested; }); @@ -744,27 +776,34 @@ void startLiveRenderer(HWND window, AppState& state) state.renderRequested = false; fullRender = state.renderFullRequested; state.renderFullRequested = false; - generation = state.renderGeneration; + state.renderFullInFlight = fullRender; snapshot.emplace(*state.liveItems); center = avatarWorld(state); playerSprite = playerRenderSprite(state); } + auto playerPatch = state.renderer->render(playerPatchOptions(state.mapIndex, center), + &*snapshot, playerSprite ? &*playerSprite : nullptr); + if (!playerPatch) { + reportLoadFailure(window, state, L"The live player-patch renderer returned no image."); + return; + } + { + std::lock_guard lock(state.sceneMutex); + if (state.renderStop) { + return; + } + state.playerPatch = std::move(playerPatch); + } + PostMessageW(window, sceneReadyMessage, 0, 0); + std::optional scene; std::vector pixels; if (fullRender) { - remorse::MapRenderOptions options; - options.mapIndex = state.mapIndex; - options.maxWidth = backingWidth; - options.maxHeight = backingHeight; - options.includeRoofs = true; - options.viewCenter = center; - const remorse::s32 radius = static_cast( - backingWidth + backingHeight * 2 + 512); - options.worldRect = remorse::WorldRect{ - center.x - radius, center.y - radius, center.x + radius, center.y + radius}; + remorse::MapRenderOptions options = fullSceneOptions(state.mapIndex, center); scene = state.renderer->render(options, &*snapshot); if (!scene) { - continue; + reportLoadFailure(window, state, L"The live full-map renderer returned no image."); + return; } pixels.resize(scene->pixels.size() * 3); for (std::size_t index = 0; index < scene->pixels.size(); ++index) { @@ -772,37 +811,36 @@ void startLiveRenderer(HWND window, AppState& state) pixels[index * 3 + 1] = scene->pixels[index].green; pixels[index * 3 + 2] = scene->pixels[index].red; } - } - auto playerPatch = state.renderer->render(playerPatchOptions(state.mapIndex, center), - &*snapshot, playerSprite ? &*playerSprite : nullptr); - if (!playerPatch) { - continue; - } - { - std::lock_guard lock(state.sceneMutex); - if (state.renderStop) { - return; - } - if (state.renderGeneration != generation && state.renderFullRequested) { - state.renderRequested = true; - continue; - } - if (fullRender) { + { + std::lock_guard lock(state.sceneMutex); + if (state.renderStop) { + return; + } state.scene = std::move(scene); state.dibPixels = std::move(pixels); + state.renderFullInFlight = false; } - state.playerPatch = std::move(playerPatch); + PostMessageW(window, sceneReadyMessage, 0, 0); } - PostMessageW(window, sceneReadyMessage, 0, 0); } - }); + } catch (const std::exception& error) { + reportLoadFailure(window, state, widen(error.what())); + } catch (...) { + reportLoadFailure(window, state, L"An unexpected error occurred in the live map renderer."); + } + }); + } catch (const std::exception& error) { + reportLoadFailure(window, state, widen(error.what())); + } catch (...) { + reportLoadFailure(window, state, L"Could not start the live map-rendering worker thread."); + } } -void requestLiveRender(AppState& state, bool fullRender) +void requestLiveRender(AppState& state, bool fullRender, bool forceFullRender = false) { state.renderRequested = true; - state.renderFullRequested = state.renderFullRequested || fullRender; - ++state.renderGeneration; + state.renderFullRequested = state.renderFullRequested || + (fullRender && (!state.renderFullInFlight || forceFullRender)); state.renderWake.notify_one(); } @@ -904,9 +942,16 @@ void paintWindow(HWND window, AppState& state) const auto avatarScreen = remorse::projectToScreen(avatarWorld(state)); const int centeredLeft = avatarScreen.x - state.scene->sourceLeft - viewWidth / 2; const int centeredTop = avatarScreen.y - state.scene->sourceTop - viewHeight / 2; - const int sourceLeft = std::clamp(centeredLeft, 0, static_cast(state.scene->width) - viewWidth); - const int sourceTop = std::clamp(centeredTop, 0, static_cast(state.scene->height) - viewHeight); - if ((sourceLeft != centeredLeft || sourceTop != centeredTop) && state.renderThread.joinable()) { + const int maxSourceLeft = static_cast(state.scene->width) - viewWidth; + const int maxSourceTop = static_cast(state.scene->height) - viewHeight; + const int sourceLeft = std::clamp(centeredLeft, 0, maxSourceLeft); + const int sourceTop = std::clamp(centeredTop, 0, maxSourceTop); + const int prefetchMarginX = std::max(1, viewWidth / 4); + const int prefetchMarginY = std::max(1, viewHeight / 4); + const bool nearingSceneEdge = centeredLeft < prefetchMarginX || + centeredLeft > maxSourceLeft - prefetchMarginX || + centeredTop < prefetchMarginY || centeredTop > maxSourceTop - prefetchMarginY; + if (nearingSceneEdge && state.renderThread.joinable()) { requestLiveRender(state, true); } @@ -1058,19 +1103,78 @@ void updatePlayer(HWND window, AppState& state) bool changed = false; while (state.simulationAccumulator >= simulationTickSeconds) { state.simulationAccumulator -= simulationTickSeconds; + remorse::ControllerActorState controllerActor; + controllerActor.mapNumber = static_cast(state.mapIndex); + controllerActor.direction = state.playerDirection; + controllerActor.lastAnimation = state.playerAnimation; + controllerActor.lastAnimationNotCombat = remorse::controllerLastAnimationIsNotCombat( + state.playerAnimation); + controllerActor.kneeling = state.playerKneeling; + controllerActor.activeWeapon = state.playerHasActiveWeapon; + controllerActor.busy = state.animationProcessId != 0 && + state.diagnosticKernel.processAt(state.animationProcessId) != nullptr; + state.controllerMovement.setActorState(controllerActor); state.diagnosticKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& entry, remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { auto& app = *static_cast(context); if (entry.bytes[0] == 0xa6 && entry.bytes[1] == 0x3a && selector == 0x10 && filter == 0) { - app.controllerMovement.handleDirectionalKey(event.scanCode, event.modifiers, event.field8 != 0); + app.controllerMovement.handleKeyEvent( + event.scanCode, event.modifiers, event.field8, event.field9, + event.fieldA, event.field6); } }, &state); + if (auto command = state.controllerMovement.takeCommandRequest()) { + state.lastControllerCommand = command; + if (command->command == remorse::ControllerCommand::CycleWeaponForward) { + state.playerHasActiveWeapon = !state.playerHasActiveWeapon; + controllerActor.activeWeapon = state.playerHasActiveWeapon; + state.controllerMovement.setActorState(controllerActor); + } + } if (state.useRequested) { state.useRequested = false; changed = startNearbyUsecode(state) || changed; } runUsecodeTasks(state); - const auto movement = state.controllerMovement.request(); + if (state.activeOneShotMovement && (state.animationProcessId == 0 || + state.diagnosticKernel.processAt(state.animationProcessId) == nullptr)) { + state.activeOneShotMovement.reset(); + state.animationProcessId = 0; + state.playerAnimation = 0; + state.playerFrame = 0; + } + if (const auto action = state.controllerMovement.takeActionRequest()) { + state.activeOneShotMovement = action; + if (action->animation == 0x28) { + state.playerKneeling = true; + } else if (action->animation == 0x29) { + state.playerKneeling = false; + } + } + auto movement = state.activeOneShotMovement + ? *state.activeOneShotMovement : state.controllerMovement.request(); + bool directionUpdatedInPlace = false; + if (movement.updateDirectionInPlace) { + const auto requestedDirection = state.controllerMovement.takeInPlaceDirectionUpdate(); + if (requestedDirection && state.liveItems && state.animationProcessId != 0) { + const auto updatedDirection = state.diagnosticKernel.updateAnimPrimitiveDirection( + state.animationProcessId, *state.liveItems, *requestedDirection); + if (updatedDirection) { + movement.animation = state.playerAnimation; + movement.direction = *updatedDirection; + directionUpdatedInPlace = true; + } + } + if (!directionUpdatedInPlace) { + movement = state.activeOneShotMovement + ? *state.activeOneShotMovement : state.controllerMovement.request(); + } + } + if (movement.animation >= state.playerAnimations.size() || + !state.playerAnimations[movement.animation]) { + state.activeOneShotMovement.reset(); + movement = state.controllerMovement.request(); + } state.diagnosticKernel.deliverSystemTimerEvent(); bool gravityMoved = false; if (state.diagnostics) { @@ -1129,22 +1233,27 @@ void updatePlayer(HWND window, AppState& state) } changed = changed || state.diagnostics || gravityMoved; if (movement.animation == 0) { + const bool facingChanged = state.playerDirection != movement.direction; + state.playerDirection = movement.direction; const bool playerSpriteChanged = state.playerAnimation != 0 || state.playerFrame != 0; if (state.animationProcessId != 0) { auto* process = state.diagnosticKernel.processAt(state.animationProcessId); - process->bytes[0x18] |= 4; - state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts); + if (process != nullptr) { + process->bytes[0x18] |= 4; + state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts); + } state.animationProcessId = 0; } changed = changed || state.playerAnimation != 0 || state.playerFrame != 0; state.playerAnimation = 0; state.playerFrame = 0; + changed = changed || facingChanged; const bool usecodeMutation = state.usecodeWorldMutationPending; state.usecodeWorldMutationPending = false; changed = changed || usecodeMutation; if (state.renderThread.joinable() && - (gravityMoved || usecodeMutation || playerSpriteChanged)) { - requestLiveRender(state, gravityMoved || usecodeMutation); + (gravityMoved || usecodeMutation || playerSpriteChanged || facingChanged)) { + requestLiveRender(state, gravityMoved || usecodeMutation, true); } continue; } @@ -1153,10 +1262,9 @@ void updatePlayer(HWND window, AppState& state) const remorse::u8 previousPlayerDirection = state.playerDirection; const remorse::u8 previousPlayerFrame = state.playerFrame; const remorse::u8 requestedAnimation = movement.animation; - const remorse::AnimationClip& clip = requestedAnimation == 1 - ? *state.walkAnimation : *state.runAnimation; - if (state.animationProcessId == 0 || state.playerAnimation != requestedAnimation || - state.playerDirection != movement.direction) { + const remorse::AnimationClip& clip = *state.playerAnimations[requestedAnimation]; + if (!directionUpdatedInPlace && (state.animationProcessId == 0 || + state.playerAnimation != requestedAnimation || state.playerDirection != movement.direction)) { if (state.animationProcessId != 0) { auto* process = state.diagnosticKernel.processAt(state.animationProcessId); process->bytes[0x18] |= 4; @@ -1179,12 +1287,22 @@ void updatePlayer(HWND window, AppState& state) [](remorse::EntityDispatchEntryBase& entry, void* context) { auto& app = *static_cast(context); if (&entry == app.diagnosticKernel.processAt(app.animationProcessId)) { - const remorse::AnimationClip& activeClip = app.playerAnimation == 1 - ? *app.walkAnimation : *app.runAnimation; + const remorse::AnimationClip& activeClip = *app.playerAnimations[app.playerAnimation]; const auto* item = app.liveItems->findItem(1); - app.diagnosticKernel.advanceGroundedAnimPrimitive(app.animationProcessId, + const auto advanced = app.diagnosticKernel.advanceGroundedAnimPrimitive(app.animationProcessId, *app.liveItems, activeClip, app.shapeTypes, remorse::calculateFastAreaRange({item->data.x, item->data.y, item->data.z})); + if (app.activeOneShotMovement && (!advanced || !*advanced)) { + auto* finished = app.diagnosticKernel.processAt(app.animationProcessId); + if (finished != nullptr) { + finished->bytes[0x18] |= 4; + app.diagnosticKernel.terminateProcess( + app.animationProcessId, app.diagnosticGroupCounts); + } + app.animationProcessId = 0; + app.playerAnimation = 0; + app.playerFrame = 0; + } } }, &state); state.fastArea = fastArea; @@ -1203,7 +1321,7 @@ void updatePlayer(HWND window, AppState& state) state.playerDirection != previousPlayerDirection || state.playerFrame != previousPlayerFrame; if (state.renderThread.joinable() && (moved || hatched || usecodeMutation || gravityMoved || playerSpriteChanged)) { - requestLiveRender(state, hatched || usecodeMutation || gravityMoved); + requestLiveRender(state, hatched || usecodeMutation || gravityMoved, true); } changed = true; } @@ -1233,6 +1351,7 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA return 0; case WM_TIMER: if (wParam == timerId) { + displayLoadFailure(window, *state); updatePlayer(window, *state); } return 0; @@ -1272,7 +1391,15 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA wParam == 'Z' || wParam == 'C') event.modifiers &= ~0x20; if (GetKeyState(VK_LSHIFT) & 0x8000) event.modifiers |= 1; if (GetKeyState(VK_RSHIFT) & 0x8000) event.modifiers |= 2; - event.field8 = message == WM_KEYDOWN ? 1 : 0; + if (GetKeyState(VK_LMENU) & 0x8000 || GetKeyState(VK_RMENU) & 0x8000) { + event.modifiers |= 0x0a00; + } + if (GetKeyState(VK_LCONTROL) & 0x8000 || GetKeyState(VK_RCONTROL) & 0x8000) { + event.modifiers |= 0x0500; + } + event.field8 = 1; + event.field9 = message == WM_KEYDOWN ? 1 : 0; + event.fieldA = message == WM_KEYDOWN ? 1 : 0; std::lock_guard lock(state->kernelMutex); state->diagnosticKernel.queuePendingKeyEvent(event); } @@ -1319,12 +1446,16 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA paintWindow(window, *state); return 0; case sceneReadyMessage: { + bool shouldStartRenderer = false; { std::lock_guard lock(state->sceneMutex); - if (state->sceneLoaded && state->renderer && !state->renderThread.joinable()) { - startLiveRenderer(window, *state); - } + shouldStartRenderer = state->sceneLoaded && state->renderer.has_value() && + !state->renderThread.joinable(); } + if (shouldStartRenderer) { + startLiveRenderer(window, *state); + } + displayLoadFailure(window, *state); InvalidateRect(window, nullptr, FALSE); return 0; } diff --git a/rebuild/remorse/tests/animation_archive_tests.cpp b/rebuild/remorse/tests/animation_archive_tests.cpp index b88fae4..bc68278 100644 --- a/rebuild/remorse/tests/animation_archive_tests.cpp +++ b/rebuild/remorse/tests/animation_archive_tests.cpp @@ -4,6 +4,7 @@ #include "remorse/shape_archive.h" #include +#include #include namespace { @@ -100,6 +101,14 @@ int main() assert(stand.has_value() && stand->frameCount > 0); assert(walk.has_value() && walk->frameCount == 17); assert(run.has_value() && run->frameCount == 12); + std::array, 0x40> playerAnimations; + for (const remorse::u8 index : remorse::controllerAnimationIndices) { + playerAnimations[index] = remorse::loadAnimationClip( + *animationArchive, 1, index); + } + for (const remorse::u8 animation : remorse::controllerAnimationIndices) { + assert(playerAnimations[animation] && playerAnimations[animation]->frameCount != 0); + } for (const remorse::AnimationClip* clip : {&*walk, &*run}) { assert(clip->header[1] == 5); for (remorse::u8 direction = 0; direction < 16; ++direction) { @@ -148,7 +157,10 @@ int main() const auto playerFrames = remorse::loadShapeFrames(*shapeArchive, 1); assert(playerFrames.has_value() && playerFrames->size() >= walk->frameCount); std::vector referencedFrames(playerFrames->size(), false); - for (const remorse::AnimationClip* clip : {&*stand, &*walk, &*run}) { + for (const auto& clip : playerAnimations) { + if (!clip) { + continue; + } for (remorse::u8 direction = 0; direction < 16; ++direction) { for (remorse::u8 frame = 0; frame < clip->frameCount; ++frame) { const auto metadata = remorse::getAnimationFrame(*clip, direction, frame); @@ -159,14 +171,13 @@ int main() } } } - bool decodedReferencedFrame = false; for (std::size_t frame = 0; frame < referencedFrames.size(); ++frame) { if (referencedFrames[frame]) { - assert(remorse::decodeShapeFrame(*shapeArchive, 1, static_cast(frame)).has_value()); - decodedReferencedFrame = true; - break; + assert(remorse::decodeShapeFrame((*playerFrames)[frame]).has_value()); } } - assert(decodedReferencedFrame); + assert(std::any_of(referencedFrames.begin(), referencedFrames.end(), [](bool referenced) { + return referenced; + })); return 0; } \ No newline at end of file diff --git a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp index 38ce7aa..3998fb2 100644 --- a/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp +++ b/rebuild/remorse/tests/entity_dispatch_entry_tests.cpp @@ -997,6 +997,10 @@ int main() assert(animationKernel.startAnimPrimitiveProcess(3, animationItems, walking)); const auto* npcAnimation = animationItems.findNpcAnimation(1); assert(npcAnimation && npcAnimation->lastAnimation == 1 && npcAnimation->frame == 0); + assert(animationKernel.updateAnimPrimitiveDirection(3, animationItems, 7) == 6); + assert(animation->extra[6] == 6 && npcAnimation->frame == 0 && npcAnimation->direction == 6); + assert(animationKernel.updateAnimPrimitiveDirection(3, animationItems, 0x11) == 8); + assert(animationKernel.updateAnimPrimitiveDirection(3, animationItems, 0x12) == 6); assert(!animationKernel.startAnimPrimitiveProcess(3, animationItems, walking)); auto* repeatedWalk = animationKernel.createAnimPrimitiveProcess(1, 1, 1, 6, walking, animationGroups); assert(animationKernel.startAnimPrimitiveProcess(4, animationItems, walking)); @@ -1004,6 +1008,21 @@ int main() auto* turning = animationKernel.createAnimPrimitiveProcess(1, 1, 0, 6, walking, animationGroups); assert(animationKernel.startAnimPrimitiveProcess(5, animationItems, walking)); assert(turning->base.bytes[0x3a] == 1 && animationItems.findNpcAnimation(1)->frame == 0); + remorse::ProcessKernel sixteenDirectionKernel; + remorse::u16 sixteenDirectionGroups[32]{}; + for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) { + sixteenDirectionKernel.createProcess(1, sixteenDirectionGroups); + } + auto sixteenWalking = walking; + sixteenWalking.header[3] |= 0x40; + auto* sixteenDirection = sixteenDirectionKernel.createAnimPrimitiveProcess(1, 1, 1, 6, + sixteenWalking, sixteenDirectionGroups); + remorse::LiveFixedMapItems sixteenItems({}); + assert(sixteenItems.initializeAvatar()); + assert(sixteenDirectionKernel.startAnimPrimitiveProcess(3, sixteenItems, sixteenWalking)); + assert(sixteenDirectionKernel.updateAnimPrimitiveDirection(3, sixteenItems, 0x11) == 15); + assert(sixteenDirection->extra[6] == 15); + assert(sixteenDirectionKernel.updateAnimPrimitiveDirection(3, sixteenItems, 0x12) == 14); remorse::StagedFixedMapItem animationSpawn{}; animationSpawn.data.x = 512; animationSpawn.data.y = 512; @@ -1022,6 +1041,11 @@ int main() walking, animationShapes, animationArea) == true); assert(animationItems.findItem(1)->data.x == 514 && animationItems.findItem(1)->data.y == 514); assert(movingNpc.frame == 1); + nextWalkFrame.bytes[5] = 0; + assert(animationKernel.advanceGroundedAnimPrimitive(3, animationItems, + walking, animationShapes, animationArea) == true); + assert(animationItems.findItem(1)->data.x == 514 && movingNpc.frame == 2); + nextWalkFrame.bytes[5] = 2; nextWalkFrame.bytes[4] = 100; movingNpc.frame = 0; remorse::StagedFixedMapItem animationWall{}; diff --git a/rebuild/remorse/tests/isometric_controls_tests.cpp b/rebuild/remorse/tests/isometric_controls_tests.cpp index a9bd432..36bee98 100644 --- a/rebuild/remorse/tests/isometric_controls_tests.cpp +++ b/rebuild/remorse/tests/isometric_controls_tests.cpp @@ -9,12 +9,258 @@ int main() assert(controller.request().animation == 0); controller.handleDirectionalKey(0x48, 0, true); assert(controller.request().animation == 1 && controller.request().direction == 14); + controller.handleKeyEvent(0x50, 0, 0, 1); + assert(controller.request().direction == 14); + controller.handleKeyEvent(0x48, 0x0a00, 1, 1); + const auto jump = controller.takeActionRequest(); + assert(jump && jump->animation == 0x24 && jump->direction == 14 && jump->oneShot); + remorse::ControllerMovementState keypadKneelController; + keypadKneelController.handleKeyEvent(0x4c, 0, 1, 1, 0); + assert(!keypadKneelController.takeActionRequest()); + keypadKneelController.handleKeyEvent(0x4c, 0, 1, 1, 1); + assert(keypadKneelController.takeActionRequest()->animation == 0x28); + keypadKneelController.handleKeyEvent(0x4c, 0, 1, 1, 1); + assert(keypadKneelController.takeActionRequest()->animation == 0x29); + remorse::ControllerMovementState ctrlDownKneelController; + ctrlDownKneelController.handleKeyEvent(0x50, 0x0100, 1, 1, 0); + assert(!ctrlDownKneelController.takeActionRequest()); + ctrlDownKneelController.handleKeyEvent(0x50, 0x0100, 1, 1, 1); + assert(ctrlDownKneelController.takeActionRequest()->animation == 0x28); + ctrlDownKneelController.handleKeyEvent(0x50, 0x0100, 1, 1, 1); + assert(ctrlDownKneelController.takeActionRequest()->animation == 0x29); + remorse::ControllerMovementState commandController; + commandController.handleKeyEvent(0x39, 0, 1, 1, 1); + assert(commandController.takeCommandRequest()->command == remorse::ControllerCommand::FireWeapon); + commandController.handleKeyEvent(0x52, 0, 1, 1, 1); + assert(commandController.takeCommandRequest()->command == remorse::ControllerCommand::FireWeapon); + commandController.handleKeyEvent(0x52, 0x0100, 1, 1, 1, 0); + assert(commandController.takeCommandRequest()->command == remorse::ControllerCommand::FireWeapon); + commandController.handleKeyEvent(0x4a, 0, 1, 1, 1); + assert(commandController.takeCommandRequest()->command == remorse::ControllerCommand::SelectNextItem); + commandController.handleKeyEvent(0x37, 0, 1, 1, 1, 1); + assert(!commandController.takeCommandRequest()); + commandController.handleKeyEvent(0x37, 0, 1, 1, 1, 0); + assert(commandController.takeCommandRequest()->command == remorse::ControllerCommand::CycleWeaponForward); + commandController.handleKeyEvent(0x4e, 0, 1, 1, 1); + assert(commandController.takeCommandRequest()->command == remorse::ControllerCommand::OpenInventory); + commandController.handleKeyEvent(0x53, 0x0100, 1, 1, 1, 0); + assert(commandController.takeCommandRequest()->command == remorse::ControllerCommand::OpenInventory); + commandController.handleKeyEvent(0x53, 0, 1, 1, 1, 1); + assert(!commandController.takeCommandRequest()); + commandController.handleKeyEvent(0x53, 0, 1, 1, 1, 0); + assert(commandController.takeCommandRequest()->command == remorse::ControllerCommand::OpenInventory); + commandController.handleKeyEvent(0x39, 0, 1, 1, 0); + assert(!commandController.takeCommandRequest()); + remorse::ControllerActorState restrictedCommandActor; + restrictedCommandActor.mapNumber = 0x40; + commandController.setActorState(restrictedCommandActor); + commandController.handleKeyEvent(0x39, 0, 1, 1, 1); + assert(!commandController.takeCommandRequest()); + restrictedCommandActor.mapNumber = 1; + restrictedCommandActor.npcNumber = 2; + commandController.setActorState(restrictedCommandActor); + commandController.handleKeyEvent(0x4a, 0, 1, 1, 1); + assert(!commandController.takeCommandRequest()); + remorse::ControllerMovementState altNumLockRight; + remorse::ControllerActorState altTurnActor; + altTurnActor.direction = 14; + altNumLockRight.setActorState(altTurnActor); + altNumLockRight.handleKeyEvent(0x4d, 0x0a20, 1, 1); + const auto altTurn = altNumLockRight.takeActionRequest(); + assert(altTurn && altTurn->animation == 0x1d && altTurn->direction == 13); + remorse::ControllerMovementState jumpController; + jumpController.handleKeyEvent(0x35, 0, 1, 1); + const auto slashJump = jumpController.takeActionRequest(); + assert(slashJump && slashJump->animation == 0x24 && slashJump->oneShot); + jumpController.handleKeyEvent(0x35, 0, 1, 0); + assert(!jumpController.takeActionRequest()); + remorse::ControllerMovementState modifierReleaseController; + modifierReleaseController.handleKeyEvent(0x48, 0, 1, 1); + assert(modifierReleaseController.request().animation == 1); + modifierReleaseController.handleKeyEvent(0x1d, 0x0100, 1, 1); + modifierReleaseController.handleKeyEvent(0x48, 0x0100, 1, 0); + assert(modifierReleaseController.request().animation == 0); + remorse::ControllerMovementState combatTurnController; + remorse::ControllerActorState combatTurnActor; + combatTurnActor.avatarSomethingCombatty = true; + combatTurnActor.direction = 14; + combatTurnController.setActorState(combatTurnActor); + combatTurnController.handleKeyEvent(0x4b, 0, 1, 1); + const auto combatTurn = combatTurnController.takeActionRequest(); + assert(combatTurn && combatTurn->animation == 4 && combatTurn->direction == 13); + combatTurnActor.kneeling = true; + combatTurnActor.direction = 13; + combatTurnController.setActorState(combatTurnActor); + combatTurnController.handleKeyEvent(0x4d, 0, 1, 1); + const auto kneelingCombatTurn = combatTurnController.takeActionRequest(); + assert(kneelingCombatTurn && kneelingCombatTurn->animation == 0x2e && kneelingCombatTurn->direction == 14); + remorse::ControllerMovementState ctrlDiagonalController; + remorse::ControllerActorState ctrlDiagonalActor; + ctrlDiagonalActor.direction = 14; + ctrlDiagonalController.setActorState(ctrlDiagonalActor); + ctrlDiagonalController.handleKeyEvent(0x47, 0x0100, 1, 1); + const auto ctrlDiagonalLeft = ctrlDiagonalController.takeActionRequest(); + assert(ctrlDiagonalLeft && ctrlDiagonalLeft->animation == 0x17 && ctrlDiagonalLeft->direction == 0); + ctrlDiagonalController.handleKeyEvent(0x49, 0x0100, 1, 1); + const auto ctrlDiagonalRight = ctrlDiagonalController.takeActionRequest(); + assert(ctrlDiagonalRight && ctrlDiagonalRight->animation == 0x18 && ctrlDiagonalRight->direction == 12); + ctrlDiagonalController.handleKeyEvent(0x47, 0x0120, 1, 1); + assert(!ctrlDiagonalController.takeActionRequest()); + modifierReleaseController.handleKeyEvent(0x48, 0x0100, 1, 1); + assert(modifierReleaseController.takeActionRequest()->animation == 0x3a); + modifierReleaseController.handleKeyEvent(0x48, 0x0100, 1, 0); + assert(modifierReleaseController.request().animation == 0); + controller.handleKeyEvent(0x4b, 0x0500, 1, 1); + const auto combatStep = controller.takeActionRequest(); + assert(combatStep && combatStep->animation == 0x3d && combatStep->oneShot); + controller.handleKeyEvent(0x4c, 0x0500, 1, 1); + const auto crouch = controller.takeActionRequest(); + assert(crouch && crouch->animation == 0x28); + controller.handleKeyEvent(0x4c, 0x0500, 1, 1); + assert(controller.takeActionRequest()->animation == 0x29); + remorse::ControllerMovementState numLockController; + numLockController.setFacingDirection(14); + numLockController.setTurnStep(2); + numLockController.handleKeyEvent(0x4d, 0x20, 1, 1); + assert(numLockController.request().animation == 0 && numLockController.request().direction == 0); + numLockController.setFacingDirection(0); + numLockController.handleKeyEvent(0x48, 0x21, 1, 1); + assert(numLockController.request().animation == 3 && numLockController.request().direction == 0); + numLockController.handleKeyEvent(0x50, 0x20, 1, 1); + assert(numLockController.request().animation == 2 && numLockController.request().direction == 0); + numLockController.handleKeyEvent(0x50, 0x20, 1, 0); + assert(numLockController.request().animation == 1 && numLockController.request().direction == 0); + remorse::ControllerMovementState gatedController; + remorse::ControllerActorState actorState; + actorState.controllerEnabled = false; + gatedController.setActorState(actorState); + gatedController.handleDirectionalKey(0x48, 0, true); + assert(gatedController.request().animation == 0); + actorState.controllerEnabled = true; + actorState.avatarInStasis = true; + gatedController.setActorState(actorState); + gatedController.handleDirectionalKey(0x48, 0, true); + assert(gatedController.request().animation == 0); + actorState.npcNumber = 2; + gatedController.setActorState(actorState); + gatedController.handleDirectionalKey(0x48, 0, true); + assert(gatedController.request().animation == 1); + assert(remorse::controllerAllowsInPlaceDirectionUpdate(0x30)); + assert(!remorse::controllerAllowsInPlaceDirectionUpdate(0x28)); + constexpr remorse::u8 nonCombatAnimations[] = {0, 1, 11, 16, 32, 55, 58, 59}; + for (const remorse::u8 animation : nonCombatAnimations) { + assert(remorse::controllerLastAnimationIsNotCombat(animation)); + } + assert(!remorse::controllerLastAnimationIsNotCombat(4)); + assert(!remorse::controllerLastAnimationIsNotCombat(3)); + assert(remorse::controllerLastAnimationIsRunningJumping(3)); + assert(remorse::controllerLastAnimationIsRunningJumping(48)); + assert(remorse::controllerLastAnimationIsRunningJumping(49)); + assert(remorse::controllerLastAnimationIsRunningJumping(56)); + assert(!remorse::controllerLastAnimationIsRunningJumping(34)); + remorse::ControllerMovementState jumpKeyController; + jumpKeyController.handleKeyEvent(0x0f, 0, 1, 1, 1); + assert(jumpKeyController.takeActionRequest()->animation == 56); + remorse::ControllerActorState busyRunner; + busyRunner.busy = true; + busyRunner.lastAnimation = 3; + jumpKeyController.setActorState(busyRunner); + jumpKeyController.handleKeyEvent(0x24, 0, 1, 1, 1); + assert(jumpKeyController.takeActionRequest()->animation == 56); + busyRunner.lastAnimation = 56; + jumpKeyController.setActorState(busyRunner); + jumpKeyController.handleKeyEvent(0x0f, 0, 1, 1, 1); + assert(!jumpKeyController.takeActionRequest()); + busyRunner.lastAnimation = 4; + jumpKeyController.setActorState(busyRunner); + jumpKeyController.handleKeyEvent(0x0f, 0, 1, 1, 1); + assert(!jumpKeyController.takeActionRequest()); + remorse::ControllerMovementState busyTurnController; + actorState.npcNumber = 1; + actorState.avatarInStasis = false; + actorState.busy = true; + actorState.lastAnimation = 1; + busyTurnController.setActorState(actorState); + busyTurnController.handleKeyEvent(0x4d, 0x20, 1, 1); + const auto busyTurn = busyTurnController.request(); + assert(busyTurn.updateDirectionInPlace && busyTurn.animation == 1 && busyTurn.direction == 0x11); + assert(busyTurnController.takeInPlaceDirectionUpdate() == 0x11); + actorState.lastAnimation = 0x28; + busyTurnController.setActorState(actorState); + busyTurnController.handleKeyEvent(0x4d, 0x20, 1, 1); + assert(!busyTurnController.takeInPlaceDirectionUpdate()); + assert(busyTurnController.request().animation == 0 && busyTurnController.request().direction == 14); + remorse::ControllerMovementState clearedBusyTurnController; + actorState.lastAnimation = 1; + clearedBusyTurnController.setActorState(actorState); + clearedBusyTurnController.handleKeyEvent(0x4d, 0x20, 1, 1); + assert(clearedBusyTurnController.request().updateDirectionInPlace); + clearedBusyTurnController.clear(); + assert(!clearedBusyTurnController.request().updateDirectionInPlace); + remorse::ControllerMovementState armedRunController; + actorState.busy = false; + actorState.activeWeapon = true; + actorState.mapNumber = 1; + actorState.direction = 14; + actorState.lastAnimation = 0; + armedRunController.setActorState(actorState); + armedRunController.handleKeyEvent(0x48, 0x01, 1, 1); + assert(armedRunController.request().animation == 0x22); + actorState.lastAnimation = 48; + armedRunController.setActorState(actorState); + assert(armedRunController.request().animation == 0x30); + remorse::ControllerMovementState unarmedRunController; + actorState.activeWeapon = false; + actorState.lastAnimation = 0; + unarmedRunController.setActorState(actorState); + unarmedRunController.handleKeyEvent(0x48, 0x01, 1, 1); + assert(unarmedRunController.request().animation == 0x22); + actorState.lastAnimation = 0x22; + unarmedRunController.setActorState(actorState); + assert(unarmedRunController.request().animation == 3); + remorse::ControllerMovementState combatControlController; + actorState.lastAnimationNotCombat = false; + actorState.kneeling = false; + actorState.npcNumber = 1; + combatControlController.setActorState(actorState); + combatControlController.handleKeyEvent(0x48, 0x0100, 1, 1); + assert(combatControlController.takeActionRequest()->animation == 0x0b); + remorse::ControllerMovementState kneelingControlController; + actorState.kneeling = true; + kneelingControlController.setActorState(actorState); + kneelingControlController.handleKeyEvent(0x48, 0x0100, 1, 1); + assert(kneelingControlController.takeActionRequest()->animation == 0x29); + remorse::ControllerMovementState nonAvatarControlController; + actorState.kneeling = false; + actorState.lastAnimationNotCombat = true; + actorState.npcNumber = 2; + nonAvatarControlController.setActorState(actorState); + nonAvatarControlController.handleKeyEvent(0x48, 0x0100, 1, 1); + assert(!nonAvatarControlController.takeActionRequest()); + remorse::ControllerMovementState mapFortyController; + actorState.mapNumber = 0x40; + actorState.lastAnimation = 0; + actorState.direction = 14; + mapFortyController.setActorState(actorState); + mapFortyController.handleKeyEvent(0x48, 0x01, 1, 1); + assert(mapFortyController.request().animation == 0x26); + remorse::ControllerMovementState mapFortyContinuation; + actorState.lastAnimation = 38; + mapFortyContinuation.setActorState(actorState); + mapFortyContinuation.handleKeyEvent(0x48, 0x01, 1, 1); + assert(mapFortyContinuation.request().animation == 3); + remorse::ControllerMovementState mapFortyMisfacing; + actorState.lastAnimation = 0; + actorState.direction = 12; + mapFortyMisfacing.setActorState(actorState); + mapFortyMisfacing.handleKeyEvent(0x48, 0x01, 1, 1); + assert(mapFortyMisfacing.request().animation == 0); controller.handleDirectionalKey(0x4d, 1, true); assert(controller.request().animation == 3 && controller.request().direction == 2); controller.handleDirectionalKey(0x4d, 1, false); - assert(controller.request().animation == 3 && controller.request().direction == 14); + assert(controller.request().animation == 0 && controller.request().direction == 2); controller.handleDirectionalKey(0x48, 0, false); - assert(controller.request().animation == 0 && controller.request().direction == 14); + assert(controller.request().animation == 0 && controller.request().direction == 2); controller.handleDirectionalKey(0x49, 0x20, true); assert(controller.request().animation == 0); controller.handleDirectionalKey(0x47, 0x40, true); diff --git a/rebuild/remorse/tests/map_renderer_tests.cpp b/rebuild/remorse/tests/map_renderer_tests.cpp index 7ae8fbf..90ad489 100644 --- a/rebuild/remorse/tests/map_renderer_tests.cpp +++ b/rebuild/remorse/tests/map_renderer_tests.cpp @@ -114,6 +114,22 @@ int main() }); }; assert(liveBefore && samePixels(liveBefore->pixels, startingScene->pixels)); + remorse::MapRenderOptions viewportOptions; + viewportOptions.mapIndex = 1; + viewportOptions.maxWidth = 2560; + viewportOptions.maxHeight = 1440; + viewportOptions.includeRoofs = true; + viewportOptions.viewCenter = spawn; + const auto unboundedViewport = cachedRenderer->render(viewportOptions, &liveSceneItems); + const remorse::s32 viewportRadius = 2560 + 1440 * 2 + 512; + viewportOptions.worldRect = remorse::WorldRect{ + spawn.x - viewportRadius, spawn.y - viewportRadius, + spawn.x + viewportRadius, spawn.y + viewportRadius}; + const auto boundedViewport = cachedRenderer->render(viewportOptions, &liveSceneItems); + assert(unboundedViewport && boundedViewport); + assert(samePixels(unboundedViewport->pixels, boundedViewport->pixels)); + assert(unboundedViewport->coverage == boundedViewport->coverage); + assert(boundedViewport->renderItemCount < unboundedViewport->renderItemCount); const auto playerFrame = remorse::decodeShapeFrame(cachedRenderer->shapes, 1, 0); assert(playerFrame); const remorse::MapRenderSprite playerSprite{spawn, 1, 0, false, diff --git a/rebuild/remorse/tests/shape_archive_tests.cpp b/rebuild/remorse/tests/shape_archive_tests.cpp index 4d0197b..c6ceeba 100644 --- a/rebuild/remorse/tests/shape_archive_tests.cpp +++ b/rebuild/remorse/tests/shape_archive_tests.cpp @@ -21,6 +21,10 @@ int main() if (frame && !frame->pixels.empty()) { assert(frame->frame.width > 0); assert(frame->frame.height > 0); + const auto parsedFrames = remorse::loadShapeFrames(*archive, shape); + assert(parsedFrames && !parsedFrames->empty()); + const auto decodedFromParsed = remorse::decodeShapeFrame(parsedFrames->front()); + assert(decodedFromParsed && decodedFromParsed->pixels == frame->pixels); decodedFrame = true; break; } From 25f258393fc5cc2c38eb17842ddb779fa956e91d Mon Sep 17 00:00:00 2001 From: Maddo Date: Wed, 7 Oct 2026 00:20:26 +0200 Subject: [PATCH 14/14] Roadmap update --- docs/remorse-windows-rebuild-roadmap.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/remorse-windows-rebuild-roadmap.md b/docs/remorse-windows-rebuild-roadmap.md index 6c8dd97..da0e8ea 100644 --- a/docs/remorse-windows-rebuild-roadmap.md +++ b/docs/remorse-windows-rebuild-roadmap.md @@ -552,7 +552,19 @@ After the first source-backed interaction, complete the original player/item loo Use this sequence to move the normal Windows launch path from host-modeled behavior back to the intended decompiled-source port. Keep the current executable, data readers, preview, and tests; treat host gameplay implementations as temporary until their original call paths replace them. -1. **Freeze and classify the normal path:** do not add more host-only gameplay behavior to the default launch path. For startup, ticking, input, movement, interaction, and drawing, record the controlling original function/address, current host implementation, required host-service boundary, and status as translated, verified, or stand-in. Keep diagnostic-only behavior behind `--diagnostics`. +### Normal-Path Classification (2026-10-07) + +**Step 1 complete:** freeze further host-only gameplay additions to the default path and classify its current implementation. The default executable is `remorse_game`; `--diagnostics` adds separate fixtures and HUD behavior. The table distinguishes translated rules from an integrated original call path. The current CMake target builds hand-maintained `remorse_core` sources; exported function slices remain staging input and are not directly linked. + +| Path | Current normal-path implementation | Original path and status | Host boundary and recovery target | +|---|---|---|---| +| Startup and spawn | [`loadSceneAsync`](../rebuild/remorse/src/windowed_game_main.cpp#L471) loads retail data, 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. | +| 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. | +| 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:** choose a small, already-understood exported function used by the runtime (for example, a process sleep/timer primitive), clean its types, globals, layout, and calling convention, then compile and link that implementation into `remorse_core`. Replace the matching host-authored behavior with this compiled function and test its state changes against the export and Ghidra evidence. The import helper is staging only; do not count a staged export or isolated test as integrated. 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. 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.