Compare commits

..

No commits in common. "25f258393fc5cc2c38eb17842ddb779fa956e91d" and "6ca3b18c3eb85c03b9079ae5c591205dd2b4e9d1" have entirely different histories.

86 changed files with 298 additions and 17070 deletions

View file

@ -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/<game>/map-*/<hash>/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.
- 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.

View file

@ -43,16 +43,4 @@ 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.
# 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.
- When posting HTTP form data from PowerShell, prefer compact one-line request bodies over multiline literal blocks in the shared shell.

2
.gitignore vendored
View file

@ -46,8 +46,6 @@ exports/**
out/**
binary/**
psx-map-exporter/.output-render/**
rebuild/**/out/**
rebuild/**/imported/**
# JavaScript / Node
**/node_modules/**

View file

@ -3,328 +3,15 @@
<PROJECT_DATA_XML_NAME NAME="DISPLAY_DATA">
<SAVE_STATE>
<ARRAY NAME="EXPANDED_PATHS" TYPE="string">
<A VALUE="Crusader:psx:" />
<A VALUE="Crusader:psx:remorse:" />
<A VALUE="Crusader:" />
</ARRAY>
<STATE NAME="SHOW_TABLE" TYPE="boolean" VALUE="false" />
</SAVE_STATE>
</PROJECT_DATA_XML_NAME>
<TOOL_MANAGER ACTIVE_WORKSPACE="Workspace">
<WORKSPACE NAME="Workspace" ACTIVE="true">
<RUNNING_TOOL TOOL_NAME="CodeBrowser">
<ROOT_NODE X_POS="57" Y_POS="112" WIDTH="1637" HEIGHT="931" EX_STATE="0">
<SPLIT_NODE WIDTH="100" HEIGHT="100" DIVIDER_LOCATION="0" ORIENTATION="VERTICAL">
<SPLIT_NODE WIDTH="1621" HEIGHT="816" DIVIDER_LOCATION="148" ORIENTATION="VERTICAL">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Entropy" OWNER="EntropyPlugin" TITLE="Entropy" ACTIVE="false" GROUP="Header" INSTANCE_ID="3207819926581772885" />
<COMPONENT_INFO NAME="Overview" OWNER="OverviewPlugin" TITLE="Overview" ACTIVE="false" GROUP="Header" INSTANCE_ID="3207819926581772883" />
</COMPONENT_NODE>
<SPLIT_NODE WIDTH="1625" HEIGHT="836" DIVIDER_LOCATION="143" ORIENTATION="HORIZONTAL">
<SPLIT_NODE WIDTH="232" HEIGHT="836" DIVIDER_LOCATION="640" ORIENTATION="VERTICAL">
<SPLIT_NODE WIDTH="232" HEIGHT="532" DIVIDER_LOCATION="502" ORIENTATION="VERTICAL">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Program Tree" OWNER="ProgramTreePlugin" TITLE="Program Trees" ACTIVE="true" GROUP="Default" INSTANCE_ID="3756557308145916186" />
</COMPONENT_NODE>
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Symbol Tree" OWNER="SymbolTreePlugin" TITLE="Symbol Tree" ACTIVE="true" GROUP="Default" INSTANCE_ID="3756557308145916181" />
</COMPONENT_NODE>
</SPLIT_NODE>
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="DataTypes Provider" OWNER="DataTypeManagerPlugin" TITLE="Data Type Manager" ACTIVE="true" GROUP="Default" INSTANCE_ID="3756557311851583771" />
</COMPONENT_NODE>
</SPLIT_NODE>
<SPLIT_NODE WIDTH="1389" HEIGHT="836" DIVIDER_LOCATION="785" ORIENTATION="VERTICAL">
<SPLIT_NODE WIDTH="1386" HEIGHT="638" DIVIDER_LOCATION="705" ORIENTATION="VERTICAL">
<SPLIT_NODE WIDTH="1389" HEIGHT="653" DIVIDER_LOCATION="679" ORIENTATION="HORIZONTAL">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Listing" OWNER="CodeBrowserPlugin" TITLE="Listing: CRUSADER.EXE" ACTIVE="true" GROUP="Core" INSTANCE_ID="3756557310916253956" />
</COMPONENT_NODE>
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Decompiler" OWNER="DecompilePlugin" TITLE="Decompile: Dispatch_CopyNextRecordFromRing" ACTIVE="true" GROUP="Default" INSTANCE_ID="3756261757801364123" />
<COMPONENT_INFO NAME="Bytes" OWNER="ByteViewerPlugin" TITLE="Bytes: CRUSADER.EXE" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557308145916189" />
<COMPONENT_INFO NAME="Data Window" OWNER="DataWindowPlugin" TITLE="Defined Data" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557312157767946" />
<COMPONENT_INFO NAME="Defined Strings" OWNER="ViewStringsPlugin" TITLE="Defined Strings" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557312157767950" />
<COMPONENT_INFO NAME="Equates Table" OWNER="EquateTablePlugin" TITLE="Equates Table" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557310916253954" />
<COMPONENT_INFO NAME="External Programs" OWNER="ReferencesPlugin" TITLE="External Programs" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557310916253957" />
<COMPONENT_INFO NAME="Functions Window" OWNER="FunctionWindowPlugin" TITLE="Functions" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557310916253960" />
<COMPONENT_INFO NAME="Relocation Table" OWNER="RelocationTablePlugin" TITLE="Relocation Table" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557312157767949" />
</COMPONENT_NODE>
</SPLIT_NODE>
<SPLIT_NODE WIDTH="1386" HEIGHT="189" DIVIDER_LOCATION="495" ORIENTATION="HORIZONTAL">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Data Type Preview" OWNER="DataTypePreviewPlugin" TITLE="Data Type Preview" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557311570565397" />
</COMPONENT_NODE>
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Virtual Disassembler - Current Instruction" OWNER="DisassembledViewPlugin" TITLE="Disassembled View" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557310916253953" />
</COMPONENT_NODE>
</SPLIT_NODE>
</SPLIT_NODE>
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Console" OWNER="ConsolePlugin" TITLE="Console" ACTIVE="true" GROUP="Default" INSTANCE_ID="3756557308145916188" />
<COMPONENT_INFO NAME="Bookmarks" OWNER="BookmarkPlugin" TITLE="Bookmarks" ACTIVE="false" GROUP="Core.Bookmarks" INSTANCE_ID="3756557308145916185" />
</COMPONENT_NODE>
</SPLIT_NODE>
</SPLIT_NODE>
</SPLIT_NODE>
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Function Call Trees" OWNER="CallTreePlugin" TITLE="Function Call Trees" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557308145916182" />
</COMPONENT_NODE>
</SPLIT_NODE>
<WINDOW_NODE X_POS="426" Y_POS="178" WIDTH="1033" HEIGHT="689">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Script Manager" OWNER="GhidraScriptMgrPlugin" TITLE="Script Manager" ACTIVE="false" GROUP="Script Group" INSTANCE_ID="3756557308145916183" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="423" Y_POS="144" WIDTH="927" HEIGHT="370">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Memory Map" OWNER="MemoryMapPlugin" TITLE="Memory Map" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557308145916164" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="383" Y_POS="7" WIDTH="1020" HEIGHT="1038">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Function Graph" OWNER="FunctionGraphPlugin" TITLE="Function Graph" ACTIVE="false" GROUP="Function Graph" INSTANCE_ID="3756557312157767951" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="550" Y_POS="206" WIDTH="655" HEIGHT="509">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Register Manager" OWNER="RegisterPlugin" TITLE="Register Manager" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557310916253959" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="287" Y_POS="186" WIDTH="1424" HEIGHT="666">
<SPLIT_NODE WIDTH="1408" HEIGHT="559" DIVIDER_LOCATION="573" ORIENTATION="HORIZONTAL">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Symbol Table" OWNER="SymbolTablePlugin" TITLE="Symbol Table" ACTIVE="false" GROUP="symbolTable" INSTANCE_ID="3756557312157767947" />
</COMPONENT_NODE>
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Symbol References" OWNER="SymbolTablePlugin" TITLE="Symbol References" ACTIVE="false" GROUP="symbolTable" INSTANCE_ID="3756557312157767948" />
</COMPONENT_NODE>
</SPLIT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="-1" Y_POS="-1" WIDTH="0" HEIGHT="0">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Checksum Generator" OWNER="ComputeChecksumsPlugin" TITLE="Checksum Generator" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557310916253955" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="-1" Y_POS="-1" WIDTH="0" HEIGHT="0">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Function Tags" OWNER="FunctionTagPlugin" TITLE="Function Tags" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557311851583772" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="-1" Y_POS="-1" WIDTH="0" HEIGHT="0">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Comment Window" OWNER="CommentWindowPlugin" TITLE="Comments" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557312157767945" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="-1" Y_POS="-1" WIDTH="0" HEIGHT="0">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Python" OWNER="InterpreterPanelPlugin" TITLE="Python" ACTIVE="false" GROUP="Default" INSTANCE_ID="3207819978370941531" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="0" Y_POS="0" WIDTH="0" HEIGHT="0">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="PyGhidra" OWNER="PyGhidra" TITLE="PyGhidra" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557312157767944" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="0" Y_POS="0" WIDTH="0" HEIGHT="0">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Source Files and Transforms" OWNER="SourceFilesTablePlugin" TITLE="Source Files and Transforms" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557310916253958" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="0" Y_POS="0" WIDTH="0" HEIGHT="0">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Bundle Manager" OWNER="GhidraScriptMgrPlugin" TITLE="Bundle Manager" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557308145916184" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="0" Y_POS="0" WIDTH="0" HEIGHT="0">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Jython" OWNER="Jython" TITLE="Jython" ACTIVE="false" GROUP="Default" INSTANCE_ID="3756557311851583773" />
</COMPONENT_NODE>
</WINDOW_NODE>
<WINDOW_NODE X_POS="0" Y_POS="0" WIDTH="0" HEIGHT="0">
<COMPONENT_NODE TOP_INFO="0">
<COMPONENT_INFO NAME="Function Call Graph" OWNER="FunctionCallGraphPlugin" TITLE="Function Call Graph" ACTIVE="false" GROUP="Function Call Graph" INSTANCE_ID="3756557311570565398" />
</COMPONENT_NODE>
</WINDOW_NODE>
</ROOT_NODE>
<DATA_STATE>
<PLUGIN NAME="NavigationHistoryPlugin">
<XML NAME="HISTORY_LIST_0">
<SAVE_STATE>
<STATE NAME="CURRENT_LOC_INDEX" TYPE="int" VALUE="1" />
<STATE NAME="LOCATION_COUNT" TYPE="int" VALUE="2" />
<STATE NAME="MEMENTO_CLASS0" TYPE="string" VALUE="ghidra.app.plugin.core.gotoquery.DefaultNavigatableLocationMemento" />
<STATE NAME="MEMENTO_CLASS1" TYPE="string" VALUE="ghidra.app.plugin.core.gotoquery.DefaultNavigatableLocationMemento" />
<XML NAME="MEMENTO_DATA0">
<SAVE_STATE>
<XML NAME="MEMENTO0">
<SAVE_STATE>
<STATE NAME="CURSOR_OFFSET" TYPE="int" VALUE="0" />
<STATE NAME="MEMENTO_CLASS" TYPE="string" VALUE="ghidra.app.plugin.core.codebrowser.CodeViewerLocationMemento" />
<STATE NAME="NAV_ID" TYPE="long" VALUE="3756261767657978500" />
<STATE NAME="PROGRAM_ID" TYPE="long" VALUE="3721129048497902283" />
<STATE NAME="PROGRAM_PATH_" TYPE="string" VALUE="Crusader:/CRUSADER.EXE" />
<STATE NAME="_ADDRESS" TYPE="string" VALUE="1000:0000" />
<STATE NAME="_BYTE_ADDR" TYPE="string" VALUE="1000:0000" />
<STATE NAME="_CHAR_OFFSET" TYPE="int" VALUE="0" />
<STATE NAME="_CLASSNAME" TYPE="string" VALUE="ghidra.program.util.MemoryBlockStartFieldLocation" />
<STATE NAME="_COLUMN" TYPE="int" VALUE="0" />
<ARRAY NAME="_COMMENT" TYPE="string">
<A VALUE="//" />
<A VALUE="// Code1" />
<A VALUE="// ram:1000:0000-ram:1000:83ff" />
<A VALUE="//" />
</ARRAY>
<STATE NAME="_ROW" TYPE="int" VALUE="0" />
<STATE NAME="_TYPE" TYPE="int" VALUE="-1" />
</SAVE_STATE>
</XML>
<STATE NAME="MEMENTO_CLASS" TYPE="string" VALUE="ghidra.app.plugin.core.gotoquery.DefaultNavigatableLocationMemento" />
<STATE NAME="NUM_MEMENTOS" TYPE="int" VALUE="1" />
<STATE NAME="PROGRAM_ID" TYPE="long" VALUE="3721129048497902283" />
<STATE NAME="PROGRAM_PATH_" TYPE="string" VALUE="Crusader:/CRUSADER.EXE" />
<STATE NAME="_ADDRESS" TYPE="string" VALUE="1000:0000" />
<STATE NAME="_BYTE_ADDR" TYPE="string" VALUE="1000:0000" />
<STATE NAME="_CHAR_OFFSET" TYPE="int" VALUE="0" />
<STATE NAME="_CLASSNAME" TYPE="string" VALUE="ghidra.program.util.MemoryBlockStartFieldLocation" />
<STATE NAME="_COLUMN" TYPE="int" VALUE="0" />
<ARRAY NAME="_COMMENT" TYPE="string">
<A VALUE="//" />
<A VALUE="// Code1" />
<A VALUE="// ram:1000:0000-ram:1000:83ff" />
<A VALUE="//" />
</ARRAY>
<STATE NAME="_ROW" TYPE="int" VALUE="0" />
<STATE NAME="_TYPE" TYPE="int" VALUE="-1" />
</SAVE_STATE>
</XML>
<XML NAME="MEMENTO_DATA1">
<SAVE_STATE>
<XML NAME="MEMENTO0">
<SAVE_STATE>
<STATE NAME="CURSOR_OFFSET" TYPE="int" VALUE="311" />
<STATE NAME="MEMENTO_CLASS" TYPE="string" VALUE="ghidra.app.plugin.core.codebrowser.CodeViewerLocationMemento" />
<STATE NAME="NAV_ID" TYPE="long" VALUE="3756261767657978500" />
<STATE NAME="PROGRAM_ID" TYPE="long" VALUE="3721129048497902283" />
<STATE NAME="PROGRAM_PATH_" TYPE="string" VALUE="Crusader:/CRUSADER.EXE" />
<STATE NAME="_ADDRESS" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_BYTE_ADDR" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_CHAR_OFFSET" TYPE="int" VALUE="0" />
<STATE NAME="_CLASSNAME" TYPE="string" VALUE="ghidra.program.util.FunctionReturnTypeFieldLocation" />
<STATE NAME="_COLUMN" TYPE="int" VALUE="0" />
<STATE NAME="_FUNC_ADDRESS" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_RETURN_TYPE" TYPE="string" VALUE="undefined" />
<STATE NAME="_ROW" TYPE="int" VALUE="0" />
<STATE NAME="_SIGNATURE" TYPE="string" VALUE="undefined __cdecl16far Dispatch_CopyNextRecordFromRing(undefined2 param_1, undefined2 param_2, undefined4 param_3)" />
</SAVE_STATE>
</XML>
<STATE NAME="MEMENTO_CLASS" TYPE="string" VALUE="ghidra.app.plugin.core.gotoquery.DefaultNavigatableLocationMemento" />
<STATE NAME="NUM_MEMENTOS" TYPE="int" VALUE="1" />
<STATE NAME="PROGRAM_ID" TYPE="long" VALUE="3721129048497902283" />
<STATE NAME="PROGRAM_PATH_" TYPE="string" VALUE="Crusader:/CRUSADER.EXE" />
<STATE NAME="_ADDRESS" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_BYTE_ADDR" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_CHAR_OFFSET" TYPE="int" VALUE="0" />
<STATE NAME="_CLASSNAME" TYPE="string" VALUE="ghidra.program.util.FunctionReturnTypeFieldLocation" />
<STATE NAME="_COLUMN" TYPE="int" VALUE="0" />
<STATE NAME="_FUNC_ADDRESS" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_RETURN_TYPE" TYPE="string" VALUE="undefined" />
<STATE NAME="_ROW" TYPE="int" VALUE="0" />
<STATE NAME="_SIGNATURE" TYPE="string" VALUE="undefined __cdecl16far Dispatch_CopyNextRecordFromRing(undefined2 param_1, undefined2 param_2, undefined4 param_3)" />
</SAVE_STATE>
</XML>
<STATE NAME="NAV_ID" TYPE="long" VALUE="-1" />
</SAVE_STATE>
</XML>
<STATE NAME="LIST_COUNT" TYPE="int" VALUE="1" />
</PLUGIN>
<PLUGIN NAME="ProgramTreePlugin">
<STATE NAME="Current Viewname" TYPE="string" VALUE="Program Tree" />
<ARRAY NAME="GroupNameProgram Tree0" TYPE="string">
<A VALUE="CRUSADER.EXE" />
</ARRAY>
<STATE NAME="NavigationToggleState" TYPE="boolean" VALUE="false" />
<STATE NAME="NumberOfGroupsProgram Tree" TYPE="int" VALUE="1" />
<STATE NAME="NumberOfViews" TYPE="int" VALUE="1" />
<STATE NAME="TreeName-0" TYPE="string" VALUE="Program Tree" />
</PLUGIN>
<PLUGIN NAME="DecompilePlugin">
<STATE NAME="INDEX" TYPE="int" VALUE="0" />
<STATE NAME="NAV_ID" TYPE="long" VALUE="3756261757801364123" />
<STATE NAME="Num Disconnected" TYPE="int" VALUE="0" />
<STATE NAME="Y_OFFSET" TYPE="int" VALUE="0" />
<STATE NAME="_ADDRESS" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_BYTE_ADDR" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_CHAR_OFFSET" TYPE="int" VALUE="33" />
<STATE NAME="_CLASSNAME" TYPE="string" VALUE="ghidra.program.util.CommentFieldLocation" />
<STATE NAME="_COLUMN" TYPE="int" VALUE="0" />
<ARRAY NAME="_COMMENT" TYPE="string">
<A VALUE="Copies the next 0x18-byte dispatch record out of the 25-slot ring buffer and advances the read index; wrapper 1360:12b2 calls this with the current gump/context." />
</ARRAY>
<STATE NAME="_ROW" TYPE="int" VALUE="0" />
<STATE NAME="_TYPE" TYPE="int" VALUE="1" />
</PLUGIN>
<PLUGIN NAME="ByteViewerPlugin">
<STATE NAME="Block Column" TYPE="int" VALUE="0" />
<STATE NAME="Block Num" TYPE="int" VALUE="0" />
<STATE NAME="Block Offset" TYPE="string" VALUE="0" />
<STATE NAME="Index" TYPE="int" VALUE="0" />
<STATE NAME="NAV_ID" TYPE="long" VALUE="3756261757801364125" />
<STATE NAME="Num Disconnected" TYPE="int" VALUE="0" />
<STATE NAME="X Offset" TYPE="int" VALUE="0" />
<STATE NAME="Y Offset" TYPE="int" VALUE="0" />
</PLUGIN>
<PLUGIN NAME="ProgramManagerPlugin">
<STATE NAME="CURRENT_FILE" TYPE="string" VALUE="CRUSADER.EXE" />
<STATE NAME="LOCATION_0" TYPE="string" VALUE="/K:/ghidra/Crusader_Decomp/" />
<STATE NAME="NUM_PROGRAMS" TYPE="int" VALUE="1" />
<STATE NAME="PATHNAME_0" TYPE="string" VALUE="/CRUSADER.EXE" />
<STATE NAME="PROJECT_NAME_0" TYPE="string" VALUE="Crusader" />
<STATE NAME="VERSION_0" TYPE="int" VALUE="-1" />
<STATE NAME="_ADDRESS" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_BYTE_ADDR" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_CHAR_OFFSET" TYPE="int" VALUE="33" />
<STATE NAME="_CLASSNAME" TYPE="string" VALUE="ghidra.program.util.CommentFieldLocation" />
<STATE NAME="_COLUMN" TYPE="int" VALUE="0" />
<ARRAY NAME="_COMMENT" TYPE="string">
<A VALUE="Copies the next 0x18-byte dispatch record out of the 25-slot ring buffer and advances the read index; wrapper 1360:12b2 calls this with the current gump/context." />
</ARRAY>
<STATE NAME="_ROW" TYPE="int" VALUE="0" />
<STATE NAME="_TYPE" TYPE="int" VALUE="1" />
</PLUGIN>
<PLUGIN NAME="FunctionGraphPlugin">
<SAVE_STATE NAME="COMPLEX_LAYOUT_NAME" TYPE="SaveState">
<COMPLEX_LAYOUT_NAME>
<STATE NAME="LAYOUT_CLASS_NAME" TYPE="string" VALUE="ghidra.app.plugin.core.functiongraph.graph.layout.DecompilerNestedLayoutProvider" />
<STATE NAME="LAYOUT_NAME" TYPE="string" VALUE="Nested Code Layout" />
</COMPLEX_LAYOUT_NAME>
</SAVE_STATE>
<STATE NAME="DISPLAY_POPUPS" TYPE="boolean" VALUE="true" />
<STATE NAME="DISPLAY_SATELLITE" TYPE="boolean" VALUE="true" />
<STATE NAME="DOCK_SATELLITE" TYPE="boolean" VALUE="true" />
<STATE NAME="DOCK_SATELLITE_POSITION" TYPE="string" VALUE="LOWER_RIGHT" />
<STATE NAME="Disconnected Count" TYPE="int" VALUE="0" />
<ENUM NAME="EDGE_HOVER_HIGHLIGHT" TYPE="enum" CLASS="ghidra.app.plugin.core.functiongraph.EdgeDisplayType" VALUE="ScopedFlowsFromVertex" />
<ENUM NAME="EDGE_SELECTION_HIGHLIGHT" TYPE="enum" CLASS="ghidra.app.plugin.core.functiongraph.EdgeDisplayType" VALUE="AllCycles" />
<STATE NAME="NAV_ID" TYPE="long" VALUE="3756261768991767183" />
</PLUGIN>
<PLUGIN NAME="CodeBrowserPlugin">
<STATE NAME="INDEX" TYPE="int" VALUE="394072" />
<STATE NAME="NAV_ID" TYPE="long" VALUE="3756261767657978500" />
<STATE NAME="Num Disconnected" TYPE="int" VALUE="0" />
<STATE NAME="Y_OFFSET" TYPE="int" VALUE="-13" />
<STATE NAME="_ADDRESS" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_BYTE_ADDR" TYPE="string" VALUE="1320:0d0b" />
<STATE NAME="_CHAR_OFFSET" TYPE="int" VALUE="33" />
<STATE NAME="_CLASSNAME" TYPE="string" VALUE="ghidra.program.util.CommentFieldLocation" />
<STATE NAME="_COLUMN" TYPE="int" VALUE="0" />
<ARRAY NAME="_COMMENT" TYPE="string">
<A VALUE="Copies the next 0x18-byte dispatch record out of the 25-slot ring buffer and advances the read index; wrapper 1360:12b2 calls this with the current gump/context." />
</ARRAY>
<STATE NAME="_ROW" TYPE="int" VALUE="0" />
<STATE NAME="_TYPE" TYPE="int" VALUE="1" />
</PLUGIN>
</DATA_STATE>
</RUNNING_TOOL>
</WORKSPACE>
<WORKSPACE NAME="Workspace" ACTIVE="true" />
</TOOL_MANAGER>
</PROJECT>

View file

@ -1,67 +0,0 @@
**********************************************************************
** 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

View file

@ -52,11 +52,7 @@ 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
- `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`
@ -127,28 +123,10 @@ 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. `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` 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:
- 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.

View file

@ -1,124 +0,0 @@
# 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.

View file

@ -1,86 +0,0 @@
# 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)

View file

@ -1,582 +0,0 @@
# 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 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 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.
## 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.
## Source-Backed In-Game Vertical Slice
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, 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, 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.
- `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`.
## Rebuild Scaffold
`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
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 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.
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.
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.
#### 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`.
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.
## Historical Implementation Evidence
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 |
|---|---|---|
| `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. |
| `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. |
| `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, 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 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.
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 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. 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.
## First Interactive Windows Game Shell
`rebuild/remorse/out/build-nmake/remorse_game.exe` is the first windowed application target. It locates the game data root from its own executable path (or the current directory), defaults to map 1, and accepts either an optional fixed-map index from 0 through 255 or the original-style direct warp options.
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:
```powershell
rebuild\remorse\build_msvc.cmd Debug
.\rebuild\remorse\out\build-nmake\remorse_game.exe 1
```
For a direct coordinate warp, use `-warp <mission> <x> <y> <z> [-mapoff <delta>]`. 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.
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.
### First Map-Derived Item/Process Tick
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 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 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`). 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 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.
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
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
Keep source slices small enough to compile and test while following original call edges, not independently designing a replacement engine.
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
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, 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
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 `<u32 offset, u32 size>`
- 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 `<u32 offset, u32 size>`
- 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 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.
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
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:
- `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
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
```
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:
```powershell
python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispatchEntry
```
## What Is Done
- **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. 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.
## Later Scope
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.
### 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.
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.
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. 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.

View file

@ -1,63 +0,0 @@
# 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.

View file

@ -1,86 +0,0 @@
# 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 <shape> <frame> <iterations>` 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)

View file

@ -1,51 +0,0 @@
# `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.

View file

@ -1,183 +0,0 @@
# 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.

View file

@ -4,7 +4,7 @@ This note checks whether the suspicious inherited event labels `combine` (`slot
## Summary
- `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.
- `combine` survives in the inherited event vocabulary, 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,10 +14,6 @@ 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`.
@ -26,17 +22,7 @@ Think of `combine` as an optional reaction hook, not a command to merge items: n
- `remorse-101`
- `remorse-demo`
- `regret`
- 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.
- The same exported pseudocode search also found **zero** `.combine(` callsites.
### What related behavior still exists
@ -46,7 +32,7 @@ The usecode intrinsic `0x00CF` is Remorse-specific: the Regret intrinsic catalog
### Best current read
`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.
`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.
## `cast` (`slot 0x11`)

View file

@ -1,838 +0,0 @@
# 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.

View file

@ -1,396 +0,0 @@
# 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).

View file

@ -1,84 +1,236 @@
# JELYHACK: What It Does and What We Know
# JELYHACK USECODE Analysis
## Short answer
## Scope
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.
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`).
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.
Current generated pseudocode lives at:
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.
- `USECODE/EUSECODE_extracted/pseudocode/JELYHACK/slot_01_use.txt`
- `USECODE/EUSECODE_extracted/pseudocode/JELYH2/slot_01_use.txt`
## What happens when it is used
## Plain-language answer
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:
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`:
```text
function jelyhack_use()
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 */
{
set_info(0x0207, *(arg_06));
process_exclude();
return;
/* post-return metadata (not executable):
debug_symbol referent [BP+00h] type=0x69
*/
}
```
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.
That presentation keeps the important distinction visible:
**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.
- 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
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.
## What is directly supported
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.
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.
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.
## Comparison against the exported pseudocode corpus
## What the referent evidence means
The `JELYHACK::use` body is not unique. Normalizing away only the function header, the exact same readable body currently appears in these seven exports:
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.
- `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 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.
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.
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`.
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.
## Where the richer behavior lives
## What `JELYHACK::use` most likely does
The closest concrete gameplay logic is in the camera callback classes, not in `JELYHACK::use`:
Current safest reading:
- `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.
- 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.
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.
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.
## Where it is used, and what remains unknown
That leads to the simplest current gameplay explanation:
What the current evidence establishes:
- 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
- `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.
## What it probably does not do
What it does **not** establish:
The current evidence argues against several stronger claims:
- 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.
- 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.
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.
If this were cut executable content, we would want to see stronger signs such as:
## Variant note
- 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
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.
At the moment we have the opposite pattern: a small named metadata record, a clean `end`, and strong similarity across the twin classes.
## Evidence files
## Relationship to JELYH2 and the surrounding island
- [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)
`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.

View file

@ -10,12 +10,6 @@ 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:
@ -98,7 +92,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 And Evidence Workflow
## Proof-Of-Concept Parser
Tool path:
@ -115,10 +109,10 @@ Current deliberate limits:
- no full intrinsic name table yet
- no synthetic control-flow graph yet
- no recompilation path in this proof-of-concept tool
- no recompilation path yet
- no Ghidra importer yet
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.
That keeps the parser useful without pretending the VM is fully solved.
## Canonical Ghidra Annotation Import Path

View file

@ -1,4 +1,4 @@
# USECODE Decompiler/Recompiler Roadmap
# USECODE Round-Trip IR Plan
## Purpose
@ -6,61 +6,6 @@ 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
@ -85,7 +30,7 @@ ScummVM also makes one implementation choice explicit that matters for the curre
### Binary-side validation against owner-loaded classes
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.
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.
Confirmed on sampled records (`EVENT`, `NPCTRIG`, `SURCAMNS`, `JELYHACK`, `REE_BOOT`, `SURCAMEW`, `SFXTRIG`):
@ -170,24 +115,25 @@ The first script IR should preserve exact recompilation inputs before it tries t
## Current Parser Views
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:
The current proof-of-concept parser now emits three complementary views for a single class/slot body:
- JSON IR: the machine-facing output for current research tools and a candidate schema source for the future editable map-viewer IR.
- JSON IR: the authoritative machine-facing output for tooling and any future assembler.
- 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 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.
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.
## Current Decompiler Boundary
## Deferred Readability Follow-Ups
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.
Keep these parser-facing readability tasks for later while the current focus stays on broad pseudocode export and class-family understanding:
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.
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.
### Unit of decompilation
@ -821,21 +767,43 @@ 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.
## Open Format And Runtime Questions
## Remaining Binary-Side Gaps
The main blockers for a real round-trip compiler are still on the binary side:
- The meaning of the first two bytes in each 6-byte Crusader event record is still unverified.
- 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 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 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. This limits safe semantic edits, but does not prevent a first opaque-preserving, bounded assembler.
- The full control-flow opcode set and branch encoding are not yet recovered.
- 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.
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.
## Best Current Path
## Historical Decompiler Work (completed milestones; not a current task list)
The strongest present path to a usable compiler/decompiler is:
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.
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).
## **Recent Renderer Work (2026-03-31)**
@ -843,7 +811,7 @@ The 2026-03-26 renderer pass added conservative loop lifting, a syntax/label val
- **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.
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.
- **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.
## **Recent Renderer Work (2026-04-01)**
@ -865,6 +833,7 @@ The follow-up work below continued across the representative families; treat any
- **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)**

View file

@ -1,40 +1,42 @@
# USECODE Map-Viewer Decompiler/Editor Plan
# USECODE Tool Improvement Plan
## Purpose
This note turns the tooling comparison into an implementation plan for the map-viewer USECODE decompiler/editor.
This note turns the earlier tooling comparison into a concrete improvement plan for the local parser/decompiler.
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.
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 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.
- `tools/poc_crusader_usecode_parser.py`
- `tools/export_usecode_pseudocode.py`
- the extracted owner-loaded corpus under `USECODE/EUSECODE_extracted/`
## Short version
The most useful next upgrades in the map-viewer implementation are:
The most useful next upgrades are:
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
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
## Current status
Existing work to build on:
Implemented in the current local parser/exporter batch:
- 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
- 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
Still required in the map-viewer product path:
Still open after this batch:
- 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
- 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
## Priority 1: Authoritative opcode metadata
@ -48,11 +50,11 @@ From Pentagram and `crusader-disasm`:
### Why it matters
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.
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.
### Concrete change
Move the map-viewer per-opcode knowledge into a single explicit table describing:
Move the per-opcode knowledge into a single explicit table describing:
- mnemonic
- stack effect where known
@ -78,13 +80,13 @@ From the older disassembly corpus:
### Why it matters
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.
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.
That is the main reason scripts like `ALARMHAT` still read as partially machine-shaped even though the overall behavior is already understandable.
### Concrete change
Extend the map-viewer loop-selector IR so supported forms render as something closer to:
Introduce a small loop-selector IR layer so common loop forms render as something closer to:
```text
for item in nearby_items(shape=0x04D0, origin=arg_06):
@ -160,7 +162,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 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.
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.
### Concrete change
@ -222,7 +224,7 @@ From the local repo workflow rather than directly from Pentagram:
### Why it matters
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.
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.
### Concrete change
@ -243,17 +245,16 @@ Expand the export and annotation path so pseudocode/index output can carry verif
## Suggested implementation order
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.
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
## What not to do yet
- 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 chase full round-tripping first. Readability is still the higher-value frontier.
- 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.

View file

@ -2,12 +2,11 @@
## Purpose
This note compares four different USECODE-facing tool lines now in use around the Crusader work:
This note compares three 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 workspace research parser/decompiler in `tools/poc_crusader_usecode_parser.py`
4. the newer map-viewer decompiler in `crusader_map_viewer/map_renderer`
3. the current workspace parser/decompiler in `tools/poc_crusader_usecode_parser.py`
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.
@ -17,9 +16,7 @@ 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.
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.
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.
## Pentagram: what it does
@ -158,7 +155,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.
## Workspace research parser/decompiler: what it does differently
## Our current parser/decompiler: what it does differently
The current local tool line is centered on:
@ -263,21 +260,7 @@ 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/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.
- use the local parser for validated owner-loaded extraction, IR, pseudocode, and batch readability export
## Best current summary
@ -285,11 +268,9 @@ Pentagram is a converter/disassembler.
`crusader-disasm` is a disassembly corpus with helper scripts.
The Python parser is the research tool that established readable decompilation over the validated extracted `EUSECODE` corpus.
Our script is the first repo-local tool that is explicitly trying to be a readable decompiler over the validated extracted `EUSECODE` corpus.
The map-viewer decompiler is where the actual editor/decompiler/recompiler should be built.
The research parser remains a layered RE workbench:
That is why the current parser looks less like a classic disassembler and more like a layered RE workbench:
- extractor-backed local format understanding
- structured IR
@ -298,4 +279,4 @@ The research parser remains a layered RE workbench:
- batch corpus export
- runtime-annotation hints tied to the current Crusader notes
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.
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.

View file

@ -1,105 +0,0 @@
# 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.

View file

@ -1,17 +0,0 @@
@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%

View file

@ -1,28 +0,0 @@
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))

View file

@ -1,222 +0,0 @@
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
src/type_flags.cpp
src/usecode_archive.cpp
src/usecode_vm.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)
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
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(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
)
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 usecode_vm_tests)
target_sources(${test_target} PRIVATE $<TARGET_OBJECTS:remorse_test_crash_setup>)
endforeach()
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(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-)
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-)
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(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(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)
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)
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()

View file

@ -1,44 +0,0 @@
@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
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=%BUILD_DIR%\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

View file

@ -1,54 +0,0 @@
#pragma once
#include <array>
#include <filesystem>
#include <optional>
#include <vector>
#include "remorse\compat.h"
namespace remorse {
struct AnimationFrameMetadata {
std::array<u8, 8> bytes{};
};
struct AnimationClip {
std::array<u8, 4> header{};
u8 frameCount = 0;
u8 directionCount = 8;
std::vector<AnimationFrameMetadata> frames;
};
struct AnimationArchive {
std::vector<u8> bytes;
};
struct AnimationDisplacement {
s32 x = 0;
s32 y = 0;
s32 z = 0;
bool onGround = false;
};
std::optional<AnimationArchive> loadAnimationArchive(const std::filesystem::path& path);
std::optional<AnimationClip> loadAnimationClip(const AnimationArchive& archive, u32 shapeIndex, u8 animationIndex);
std::optional<AnimationFrameMetadata> getAnimationFrame(
const AnimationClip& clip,
u8 direction,
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<AnimationDisplacement> decodeAnimationDisplacement(
const AnimationFrameMetadata& metadata,
u8 direction,
bool rotateDirection);
} // namespace remorse

View file

@ -1,92 +0,0 @@
#pragma once
#include <optional>
#include <vector>
#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;
};
struct GravitySweepPlan {
WorldPoint destination{};
s16 nextZSpeed = 0;
};
struct SweepBoundsResult {
WorldPoint destination{};
u8 failedDirections = 0;
bool failed = false;
};
struct SweepItemImpact {
WorldPoint resolved{};
u8 failedDirections = 0;
};
struct SweepCandidateImpact {
u16 itemNumber = 0;
SweepItemImpact impact{};
bool damaging = false;
std::optional<u8> floorGap;
};
struct SweepCollisionResult {
WorldPoint destination{};
u16 firstCollision = 0;
u8 failedDirections = 0;
std::vector<u16> damagingContacts;
u16 supportItem = 0;
std::optional<u8> supportGap;
bool failed = false;
};
struct FastAreaRange {
s32 minSum = 0;
s32 maxSum = 0;
s32 minDifference = 0;
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);
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<SweepItemImpact> sweepSolidItemImpact(
const CollisionBody& moving, WorldPoint destination, const CollisionBody& obstacle);
std::optional<std::vector<SweepCandidateImpact>> collectSweepItemImpacts(
const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination,
const std::vector<ShapeTypeInfo>& shapes, const FastAreaRange& fastArea,
std::optional<u8> floorGapLimit = std::nullopt);
SweepCollisionResult selectSolidSweepImpact(WorldPoint from, WorldPoint destination,
const std::vector<SweepCandidateImpact>& impacts);
std::optional<SweepCollisionResult> resolveSolidLiveSweep(
const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination,
const std::vector<ShapeTypeInfo>& shapes, const FastAreaRange& fastArea,
std::optional<u8> floorGapLimit = std::nullopt);
bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right);
bool canMoveCollisionBody(
const CollisionBody& body,
WorldPoint destination,
const std::vector<CollisionBody>& obstacles);
std::vector<CollisionBody> collectMapCollisionBodies(
const FixedMap& map,
const std::vector<ShapeTypeInfo>& shapeTypes,
const std::vector<GlobObject>& globObjects);
} // namespace remorse

View file

@ -1,22 +0,0 @@
#pragma once
#include <array>
#include <filesystem>
#include <optional>
#include <string>
#include <vector>
#include "remorse/compat.h"
namespace remorse {
struct CombatTactic {
u32 index = 0;
std::string name;
std::array<u16, 4> blockOffsets{};
std::vector<u8> bytecode;
};
std::optional<std::vector<CombatTactic>> loadCombatTactics(const std::filesystem::path& path);
} // namespace remorse

View file

@ -1,48 +0,0 @@
#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 <typename T>
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

View file

@ -1,45 +0,0 @@
#pragma once
#include <cstddef>
#include <vector>
#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 inventoryItem = false;
};
std::vector<std::size_t> resolveRenderOrder(const std::vector<RenderSortItem>& items);
} // namespace detail
} // namespace remorse

View file

@ -1,292 +0,0 @@
#pragma once
#include "remorse/compat.h"
#include <array>
#include <cstddef>
#include <memory>
#include <optional>
#include <utility>
#include <vector>
namespace remorse {
class LiveFixedMapItems;
struct AnimationClip;
struct ShapeTypeInfo;
struct WorldPoint;
struct FastAreaRange;
CR_PACK_PUSH_1
struct EntityDispatchEntryBase {
u8 bytes[0x32];
} CR_PACKED;
struct StandProcessEntry {
EntityDispatchEntryBase base;
u8 extra[0x10];
} CR_PACKED;
struct GravityProcessEntry {
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 ControllerProcessEntry {
EntityDispatchEntryBase base;
u8 extra[0x0e];
} CR_PACKED;
struct TeleporterProcessEntry {
EntityDispatchEntryBase base;
u8 extra[0x04];
} CR_PACKED;
struct ClearAvatarInStasisProcessEntry {
EntityDispatchEntryBase base;
u8 extra[0x01];
} CR_PACKED;
struct AnimPrimitiveProcessEntry {
EntityDispatchEntryBase base;
u8 extra[0x29];
} CR_PACKED;
struct EntityVmContextProcessEntry {
EntityDispatchEntryBase base;
u8 extra[0xf2];
} 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(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");
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(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");
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:
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]);
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<ShapeTypeInfo>* shapes = nullptr,
u16 (*groupCounts)[32] = nullptr);
bool runResolvedGravity(u16 processId, LiveFixedMapItems& items,
const std::vector<ShapeTypeInfo>& shapes, const FastAreaRange& fastArea,
u32 timeScale, u32 timerTick, u16 (&groupCounts)[32]);
u32 scanResolvedGravity(u8 activeGroup, LiveFixedMapItems& items,
const std::vector<ShapeTypeInfo>& 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]);
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]);
bool startAnimPrimitiveProcess(u16 processId, LiveFixedMapItems& items,
const AnimationClip& clip, u8 frameSkip = 0);
std::optional<u8> updateAnimPrimitiveDirection(u16 processId, LiveFixedMapItems& items,
u8 direction);
std::optional<bool> advanceGroundedAnimPrimitive(u16 processId, LiveFixedMapItems& items,
const AnimationClip& clip, const std::vector<ShapeTypeInfo>& shapes,
const FastAreaRange& fastArea);
bool queuePendingKeyEvent(const KeyEvent& event);
std::optional<KeyEvent> 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);
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);
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);
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;
u8 itemProcessTypes(u16 itemNumber) const;
u16 processCount() const;
u16 terminatedProcessCount() const;
u16 newlyCreatedCount() const;
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);
std::vector<EntityDispatchEntryBase*> processes_;
std::vector<u16> allocationSizes_;
std::vector<const char*> processNames_;
std::vector<std::unique_ptr<EntityDispatchEntryBase>> ownedProcesses_;
std::vector<std::unique_ptr<StandProcessEntry>> ownedStandProcesses_;
std::vector<std::unique_ptr<GravityProcessEntry>> ownedGravityProcesses_;
std::vector<std::unique_ptr<AnimPrimitiveProcessEntry>> ownedAnimPrimitiveProcesses_;
std::vector<std::unique_ptr<TeleporterProcessEntry>> ownedTeleporterProcesses_;
std::vector<std::unique_ptr<ClearAvatarInStasisProcessEntry>> ownedClearAvatarInStasisProcesses_;
std::vector<std::unique_ptr<EntityVmContextProcessEntry>> ownedUsecodeProcesses_;
std::unique_ptr<SystemTimerProcessEntry> systemTimerProcess_;
std::unique_ptr<KeyboardProcessEntry> keyboardProcess_;
std::unique_ptr<KeyDaemonProcessEntry> keyDaemonProcess_;
std::unique_ptr<ControllerProcessEntry> controllerProcess_;
std::vector<u16> keyboardSubscriberIds_;
std::vector<std::pair<u16, u16>> processWaits_;
std::array<KeyEvent, 32> pendingKeyEvents_{};
u8 nextKeyEventOffset_ = 0;
u8 keyEventOffset_ = 0;
bool pendingKeyEventOverflowed_ = false;
u16 systemTimerProcessId_ = 0xffff;
std::vector<u8> itemProcessPresence_;
std::vector<u8> 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;
};
bool runFreshGameTeleporterStartup(ProcessKernel& kernel, LiveFixedMapItems& items,
u16 mapNumber, u16 teleportId, const std::vector<ShapeTypeInfo>& shapes,
u16 (&groupCounts)[32]);
class EntityDispatchEntry {
public:
static constexpr u16 initBaseSegment = 0x11e0;
static constexpr u16 initBaseOffset = 0x0000;
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, 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);
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 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);
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<ShapeTypeInfo>& shapes);
};
class ClearAvatarInStasisProcess {
public:
static constexpr u16 vtableOffset = 0x0f5e;
};
class KeyboardProcess {
public:
static bool handleKeyEvent(KeyboardProcessEntry& process, u16 selector, u16 filter,
KeyEvent& event, const KeyEvent& lastEvent);
};
} // namespace remorse

View file

@ -1,20 +0,0 @@
#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;

View file

@ -1,24 +0,0 @@
#pragma once
#include <filesystem>
#include <optional>
#include <vector>
#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<GameDataRoot> findGameDataRoot(const std::filesystem::path& start);
std::optional<std::filesystem::path> resolveGameDataPath(const GameDataRoot& root, const std::filesystem::path& relativePath);
std::optional<std::vector<u8>> readBinaryFile(const std::filesystem::path& path);
} // namespace remorse

View file

@ -1,166 +0,0 @@
#pragma once
#include <filesystem>
#include <optional>
#include <vector>
#include "remorse/compat.h"
namespace remorse {
struct ShapeTypeInfo;
struct WorldRect;
struct GlobObject;
class ProcessKernel;
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<FixedMapEntry> entries;
};
struct StagedFixedMapItem {
u16 itemNumber = 0;
std::size_t recordIndex = 0;
FixedMapEntry data;
};
struct StagedContainedFixedMapItem {
u16 itemNumber = 0;
u16 parentItemNumber = 0;
std::size_t recordIndex = 0;
FixedMapEntry data;
};
struct ItemFindArea {
u16 minX = 0;
u16 minY = 0;
u16 maxX = 0;
u16 maxY = 0;
};
struct StagedItemBlockChains {
std::vector<u16> heads;
std::vector<u16> 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<u8> bytes;
};
std::optional<FixedMapArchive> loadFixedMapArchive(const std::filesystem::path& path);
std::optional<FixedMap> loadFixedMap(const FixedMapArchive& archive, u32 mapIndex);
std::optional<std::vector<StagedFixedMapItem>> stageFixedMapItems(const FixedMap& map);
std::optional<StagedFixedMapItem> findTeleportEgg(
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes, u8 eggId);
std::optional<StagedFixedMapItem> findNearbyActiveTeleportEgg(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes,
u8 currentMapNumber);
std::optional<std::vector<StagedContainedFixedMapItem>> stageContainedFixedMapItems(
const FixedMap& map, const std::vector<ShapeTypeInfo>& shapes);
std::optional<StagedFixedMapItem> nearestStagedFixedMapItem(
const std::vector<StagedFixedMapItem>& 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<u16> itemFindBlockOrder(const ItemFindArea& area);
std::optional<StagedItemBlockChains> buildStagedItemBlockChains(const std::vector<StagedFixedMapItem>& items);
std::vector<u16> itemFindCandidateOrder(const ItemFindArea& area, const StagedItemBlockChains& chains);
std::optional<std::vector<ItemFindZCandidate>> itemFindZMatches(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes, u8 zMatchFlags);
std::optional<std::vector<ItemFindZCandidate>> itemGrabSearchCandidates(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes);
std::optional<std::vector<ItemGrabAction>> planItemGrabActions(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes);
std::optional<std::vector<u16>> dispatchStagedItemGrab(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes,
ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick);
struct NpcAnimationState {
u16 lastAnimation = 0xffff;
u8 frame = 0;
u8 moreFlags = 0;
u8 direction = 0;
};
class LiveFixedMapItems {
public:
explicit LiveFixedMapItems(std::vector<StagedFixedMapItem> items,
std::vector<StagedContainedFixedMapItem> containedItems = {});
bool initializeAvatar();
bool teleportAvatar(const StagedFixedMapItem& egg, u8 mapNumber);
const StagedFixedMapItem* findItem(u16 itemNumber) const;
const std::vector<StagedFixedMapItem>& mapItems() const noexcept { return items_; }
const NpcAnimationState* findNpcAnimation(u16 itemNumber) const;
NpcAnimationState* editNpcAnimation(u16 itemNumber);
u16 containedParent(u16 itemNumber) const;
std::vector<u16> containedChildren(u16 parentItemNumber) const;
std::optional<StagedFixedMapItem> nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const;
std::optional<std::vector<u16>> sweepCandidateIds(const WorldRect& area, u16 excludedItemNumber) const;
std::optional<u16> allocateItem(StagedFixedMapItem item);
bool insertItem(StagedFixedMapItem item);
bool moveItemIntoContainer(u16 itemNumber, u16 containerItemNumber,
const std::vector<ShapeTypeInfo>& shapes);
bool moveContainedItemToWorld(u16 itemNumber, u16 x, u16 y, u8 z);
bool releaseItem(u16 itemNumber, const ProcessKernel& kernel);
std::optional<std::vector<u16>> hatchGlobEgg(u16 eggItemNumber, const GlobObject& glob,
const std::vector<ShapeTypeInfo>& 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<std::vector<u16>> grabItem(u16 itemNumber, const std::vector<ShapeTypeInfo>& shapes,
ProcessKernel& kernel, u16 (&groupCounts)[32], u32 timerTick) const;
std::optional<std::vector<u16>> moveApprovedItem(u16 itemNumber, u16 x, u16 y, u8 z,
const std::vector<ShapeTypeInfo>& shapes, ProcessKernel& kernel,
u16 (&groupCounts)[32], u32 timerTick);
private:
bool unlinkContainedItem(u16 itemNumber);
void refreshContainerQuality(u16 parentItemNumber);
bool insertContainedItemAtHead(u16 parentItemNumber, u16 itemNumber);
std::vector<StagedFixedMapItem> items_;
std::optional<StagedFixedMapItem> avatar_;
std::vector<NpcAnimationState> npcAnimations_;
std::vector<bool> allocatedIds_;
std::vector<bool> hatchedGlobIds_;
std::vector<u16> parentById_;
std::vector<std::optional<FixedMapEntry>> containedItemData_;
std::vector<u16> containedNextById_;
std::vector<u16> containedHeadById_;
std::vector<u16> containedTailById_;
std::vector<u16> freeItemIds_;
u16 nextFreeItemNumber_ = 0x100;
};
} // namespace remorse

View file

@ -1,26 +0,0 @@
#pragma once
#include <filesystem>
#include <optional>
#include <vector>
#include "remorse/compat.h"
namespace remorse {
struct FlexEntry {
u32 index = 0;
u32 offset = 0;
u32 size = 0;
};
struct FlexArchive {
u32 entryCount = 0;
std::vector<FlexEntry> populatedEntries;
std::vector<u8> bytes;
};
std::optional<FlexArchive> loadFlexArchive(const std::filesystem::path& path);
std::optional<std::vector<u8>> readFlexEntry(const FlexArchive& archive, u32 index);
} // namespace remorse

View file

@ -1,26 +0,0 @@
#pragma once
#include <filesystem>
#include <optional>
#include <vector>
#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<GlobObjectEntry> entries;
};
std::optional<std::vector<GlobObject>> loadGlobObjects(const std::filesystem::path& path);
} // namespace remorse

View file

@ -1,431 +0,0 @@
#pragma once
#include "remorse/animation_archive.h"
#include "remorse/compat.h"
#include <algorithm>
#include <array>
#include <vector>
namespace remorse {
inline constexpr std::array<u8, 25> 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;
};
inline bool controllerWalkRequested(u16 modifiers)
{
const bool shiftDown = (modifiers & 0x03) != 0;
const bool capsLockOn = (modifiers & 0x40) != 0;
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<u8> 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;
}
}
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)
{
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);
}
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<u8>((actor_.direction + turn + 16) & 0x0f);
pendingAction_ = ControllerMovementRequest{
static_cast<u8>(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<u8>(scanCode == 0x4b ? 0x12 : 0x11);
}
} else {
const int turn = scanCode == 0x4b ? -turnStep_ : turnStep_;
lastDirection_ = static_cast<u8>((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_};
}
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<u8>(walkRequested ? 1 : runAnimation), requestedDirection};
}
if (requestedDirection == actor_.direction) {
return {static_cast<u8>(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<u8>(walkRequested ? 1 : runAnimation), requestedDirection};
}
if (scanCode == 0x50) {
return {2, requestedDirection};
}
}
return {static_cast<u8>(walkRequested ? 1 : runAnimation), requestedDirection};
}
std::optional<u8> 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<ControllerMovementRequest> takeActionRequest()
{
auto action = pendingAction_;
pendingAction_.reset();
return action;
}
std::optional<ControllerCommandRequest> 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<u8>((newDirection - 4) & 0x0f);
} else {
animation = 0x1c;
actionDirection = static_cast<u8>((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<u8>((*requestedDirection - 4) & 0x0f);
} else {
animation = 0x17;
actionDirection = static_cast<u8>((*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<u8> heldScans_;
std::optional<ControllerMovementRequest> pendingAction_;
std::optional<ControllerCommandRequest> pendingCommand_;
std::optional<u8> pendingInPlaceDirection_;
u16 modifiers_ = 0;
mutable u8 lastDirection_ = 14;
u8 facingDirection_ = 14;
u8 turnStep_ = 2;
bool crouched_ = false;
ControllerActorState actor_{};
};
inline std::optional<AnimationDisplacement> 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

View file

@ -1,93 +0,0 @@
#pragma once
#include <filesystem>
#include <optional>
#include <vector>
#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 <map>
namespace remorse {
struct WorldRect {
s32 minX = 0;
s32 minY = 0;
s32 maxX = 0;
s32 maxY = 0;
};
class LiveFixedMapItems;
struct WorldPoint {
s32 x = 0;
s32 y = 0;
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;
};
struct MapRenderOptions {
u32 mapIndex = 1;
u32 maxWidth = 1600;
u32 maxHeight = 900;
bool expandGlobs = true;
bool includeRoofs = false;
bool includeHiddenMarkers = false;
std::optional<WorldPoint> viewCenter;
std::optional<WorldRect> 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<RgbColor> pixels;
std::vector<u8> coverage;
};
struct MapSceneRenderer {
FixedMap map;
std::vector<GlobObject> globs;
ShapeArchive shapes;
Palette256 palette;
std::vector<ShapeTypeInfo> typeFlags;
std::map<std::pair<u32, u32>, DecodedShapeFrame> decodedFrames;
std::optional<RenderedMapImage> render(const MapRenderOptions& options,
const LiveFixedMapItems* liveItems = nullptr, const MapRenderSprite* sprite = nullptr);
};
std::optional<MapSceneRenderer> loadMapSceneRenderer(const GameDataRoot& root, u32 mapIndex);
std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options);
std::optional<RenderedMapImage> 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);
} // namespace remorse

View file

@ -1,23 +0,0 @@
#pragma once
#include <array>
#include <filesystem>
#include <optional>
#include "remorse/compat.h"
namespace remorse {
struct RgbColor {
u8 red = 0;
u8 green = 0;
u8 blue = 0;
};
struct Palette256 {
std::array<RgbColor, 256> colors{};
};
std::optional<Palette256> loadPalette256(const std::filesystem::path& path);
} // namespace remorse

View file

@ -1,25 +0,0 @@
#pragma once
#include <filesystem>
#include <optional>
#include <string>
#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<ExportManifestSummary> loadExportManifestSummary(const std::filesystem::path& manifestPath);
std::filesystem::path defaultManifestPath(const std::filesystem::path& currentPath);
void printStartupReport(const ExportManifestSummary& manifest);
void installCrashDiagnostics();
} // namespace remorse

View file

@ -1,36 +0,0 @@
#pragma once
#include <filesystem>
#include <optional>
#include <vector>
#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<u32> lineOffsets;
std::vector<u8> rleData;
};
struct DecodedShapeFrame {
ShapeFrame frame;
std::vector<s16> pixels;
};
struct ShapeArchive {
FlexArchive archive;
};
std::optional<ShapeArchive> loadShapeArchive(const std::filesystem::path& path);
std::optional<std::vector<ShapeFrame>> loadShapeFrames(const ShapeArchive& archive, u32 shapeIndex);
std::optional<DecodedShapeFrame> decodeShapeFrame(const ShapeFrame& frame);
std::optional<DecodedShapeFrame> decodeShapeFrame(const ShapeArchive& archive, u32 shapeIndex, u32 frameIndex);
} // namespace remorse

View file

@ -1,23 +0,0 @@
#pragma once
#include <filesystem>
#include <optional>
#include <vector>
#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;
u8 weight = 0;
};
std::optional<std::vector<ShapeTypeInfo>> loadTypeFlags(const std::filesystem::path& path);
} // namespace remorse

View file

@ -1,128 +0,0 @@
#pragma once
#include "remorse/flex_archive.h"
#include <cstddef>
#include <map>
#include <optional>
#include <string>
#include <vector>
namespace remorse {
struct UsecodeClass {
u32 classId = 0;
std::string name;
u32 extraSlotCount = 0;
u32 codeBase = 0;
std::vector<u8> bytes;
};
struct UsecodeSlotOwnerBuffers {
std::vector<u8> descriptors;
std::vector<u16> chunkStates;
};
struct UsecodeEventBody {
u16 length = 0;
u32 relativeOffset = 0;
std::vector<u8> 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<FarPtr16> 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<std::vector<u8>> read(FarPtr16 address, std::size_t byteCount) const;
bool write(FarPtr16 address, const std::vector<u8>& bytes);
std::size_t allocationCount() const noexcept { return allocations_.size(); }
private:
u32 nextSegment_ = 1;
std::map<u16, std::vector<u8>> allocations_;
};
class UsecodeSlotChunkCache {
public:
explicit UsecodeSlotChunkCache(UsecodeClass usecodeClass);
const UsecodeEventBody* ensureLoaded(u16 chunkIndex);
bool release(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<std::optional<UsecodeLoadedChunkProcess>> chunks_;
UsecodeRuntimeMemory runtimeMemory_;
FarPtr16 loadedListHead_{0, 0};
FarPtr16 loadedListTail_{0, 0};
};
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<std::vector<u8>> loadUsecodeOwnerRows(const FlexArchive& archive);
bool ownerRowAllowsEvent(const std::vector<u8>& ownerRows, u16 classId, u32 eventMask);
std::optional<UsecodeClass> loadUsecodeClass(const FlexArchive& archive, u32 classId);
std::optional<UsecodeSlotOwnerBuffers> initializeUsecodeSlotOwnerBuffers(const UsecodeClass& usecodeClass);
std::optional<UsecodeEventBody> readUsecodeEventBody(const UsecodeClass& usecodeClass, u32 eventId);
std::optional<EligibleUsecodeEvent> selectEligibleUsecodeEvent(const FlexArchive& archive,
const std::vector<u8>& ownerRows, const UsecodeItemIdentity& item,
const UsecodeClassBases& bases, u32 eventMask, u16 eventId);
} // namespace remorse

View file

@ -1,173 +0,0 @@
#pragma once
#include <array>
#include <cstddef>
#include <functional>
#include <map>
#include <optional>
#include <vector>
#include "remorse/compat.h"
#include "remorse/usecode_archive.h"
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 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;
u16 segment = 0;
};
enum class UsecodeStepResult {
Advanced,
Returned,
SetInfo,
Spawned,
Yielded,
UnsupportedOpcode,
InvalidInstruction,
StackFault,
ServiceRejected
};
struct UsecodeOpcodeServices {
std::function<std::optional<u16>(u16 offset, u16 segment)> readFarWord;
std::function<bool(u16 eventType, u16 sourceItem)> setInfo;
std::function<u16()> processCount;
std::function<std::optional<u16>(u16 classId, u16 eventSlot, u8 extraArgumentBytes,
u8 itemArgumentSize, u16 itemArgument, const u8* extraArguments)> spawn;
std::function<std::optional<u16>(u16 ordinal, u8 argumentBytes, const u8* arguments)> callIntrinsic;
std::function<u16()> currentProcessId;
};
class UsecodeInterpreterState {
public:
static std::optional<UsecodeInterpreterState> initialize(
const std::vector<u8>& itemParameter, const std::vector<u8>& contextParameter = {},
u16 modeFlags = 0, bool contextParameterPresent = false);
bool pushCodeAddress(u16 offset, u16 segment);
bool pushWord(u16 value);
bool pushDword(u32 value);
std::optional<u16> popWord();
std::optional<u32> popDword();
UsecodeStepResult step(const std::vector<u8>& code, std::size_t& programCounter,
std::vector<u8>& frame, const UsecodeOpcodeServices& services);
std::optional<std::array<u16, 2>> lastSetInfoOperands;
std::array<u8, 0xcc> valueStack{};
std::size_t stackTop = 0xcc;
std::size_t stackHighWatermark = 0xcc;
std::array<UsecodeCallFrame, 32> callFrames{};
u16 callFrameCount = 0;
u16 stackLimit = usecodeInterpreterStackLimit;
u16 temporaryWord = 0;
std::optional<u16> contextParameterOffset;
std::optional<u16> contextParameterStackTop;
bool processExcluded = false;
u16 currentProcessId = 0;
u16 impliedProcessId = 0;
};
struct UsecodeProcessTask {
static std::optional<UsecodeProcessTask> create(u16 processId, u16 classId,
u16 eventSlot, u16 sourceItem, std::vector<u8> code,
u8 itemArgumentSize = 2, std::vector<u8> extraArguments = {},
std::vector<u8> contextParameter = {});
UsecodeStepResult step(const UsecodeOpcodeServices& services);
u16 processId = 0;
u16 classId = 0;
u16 eventSlot = 0;
u16 sourceItem = 0;
std::vector<u8> code;
std::vector<u8> frame;
std::vector<u8> itemMemory;
UsecodeInterpreterState interpreter;
std::size_t programCounter = usecodeEventBytecodeOffset;
bool halted = false;
bool timerDelayProcess = false;
u32 wakeTick = 0;
std::optional<u16> readMappedItemWord(FarPtr16 address) const;
};
struct UsecodeContextFactoryFields {
FarPtr16 ownerSource{};
u16 modeFlags = 0;
u16 slotIndex = 0;
u16 valueAddOffset = 0;
u16 parameterOffset = 0;
};
struct UsecodeContextCreateRequest {
FarPtr16 ownerSource{};
FarPtr16 codeSource{};
FarPtr16 ownerRows{};
std::optional<std::vector<u8>> itemParameter;
std::optional<std::vector<u8>> contextParameter;
u16 modeFlags = 0;
u16 slotIndex = 0;
u16 valueAddOffset = 0;
};
struct UsecodeContextInstance {
FarPtr16 processAddress{0, 0};
FarPtr16 callStackAddress{0, 0};
std::array<u8, usecodeContextProcessSize> processBytes{};
UsecodeInterpreterState interpreter;
};
struct UsecodeEventContext {
UsecodeContextInstance context;
FarPtr16 processIdOutput{0, 0};
std::vector<FarPtr16> ownedRegions;
};
bool writeUsecodeContextFactoryFields(u8* processBytes, std::size_t processSize,
const UsecodeContextFactoryFields& fields);
std::optional<UsecodeContextInstance> createUsecodeContext(UsecodeRuntimeMemory& memory,
const UsecodeContextCreateRequest& request);
bool destroyUsecodeContext(UsecodeRuntimeMemory& memory,
const UsecodeContextInstance& context) noexcept;
std::optional<UsecodeEventContext> createUsecodeEventContext(UsecodeRuntimeMemory& memory,
const std::vector<u8>& ownerRows, u16 classId, u16 eventSlot, u16 sourceItem,
const std::vector<u8>& 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<u16, UsecodeProcessTask> tasks_;
std::map<u16, UsecodeEventContext> contexts_;
UsecodeRuntimeMemory runtimeMemory_;
};
} // namespace remorse

View file

@ -1,158 +0,0 @@
#include "remorse/animation_archive.h"
#include "remorse/file_system.h"
#include <limits>
namespace remorse {
namespace {
std::optional<u32> readU32Le(const std::vector<u8>& bytes, std::size_t offset)
{
if (offset > bytes.size() || bytes.size() - offset < 4) {
return std::nullopt;
}
return static_cast<u32>(bytes[offset]) |
(static_cast<u32>(bytes[offset + 1]) << 8) |
(static_cast<u32>(bytes[offset + 2]) << 16) |
(static_cast<u32>(bytes[offset + 3]) << 24);
}
} // namespace
std::optional<AnimationArchive> loadAnimationArchive(const std::filesystem::path& path)
{
const auto bytes = readBinaryFile(path);
if (!bytes) {
return std::nullopt;
}
return AnimationArchive{*bytes};
}
std::optional<AnimationClip> loadAnimationClip(
const AnimationArchive& archive,
u32 shapeIndex,
u8 animationIndex)
{
if (shapeIndex > std::numeric_limits<std::size_t>::max() / 4) {
return std::nullopt;
}
const auto shapeTableOffset = readU32Le(archive.bytes, static_cast<std::size_t>(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<std::size_t>(*shapeTableOffset) +
static_cast<std::size_t>(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<std::size_t>(clip.frameCount) * clip.directionCount * 8;
const std::size_t metadataOffset = static_cast<std::size_t>(*animationOffset) + clip.header.size();
if (metadataOffset > archive.bytes.size() || metadataSize > archive.bytes.size() - metadataOffset) {
return std::nullopt;
}
clip.frames.resize(static_cast<std::size_t>(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<AnimationFrameMetadata> 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<u16>(metadata.bytes[0]) |
(static_cast<u16>(metadata.bytes[1] & 0x0f) << 8);
}
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<u8>(clip.frameCount / 2);
}
return (flags & 4) != 0 ? static_cast<u8>(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<AnimationDisplacement> 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<u8>((direction + (rotateDirection ? 4 : 0)) & 0x0f);
const u16 packedStride = static_cast<u16>(metadata.bytes[4]) |
(static_cast<u16>(metadata.bytes[5] & 1) << 8);
const s32 signedStride = (packedStride & 0x100) != 0
? static_cast<s32>(packedStride) - 0x200
: static_cast<s32>(packedStride);
return AnimationDisplacement{
static_cast<s32>(directionX[effectiveDirection]) * signedStride * 2,
static_cast<s32>(directionY[effectiveDirection]) * signedStride * 2,
static_cast<s8>(metadata.bytes[2]),
(metadata.bytes[5] & 0x02) != 0};
}
} // namespace remorse

View file

@ -1,409 +0,0 @@
#include "remorse/collision.h"
#include <algorithm>
#include <array>
#include <cstdint>
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<std::int64_t>(location.x,
obstacle.location.x) - std::max<std::int64_t>(
static_cast<std::int64_t>(location.x) - body.extentX,
static_cast<std::int64_t>(obstacle.location.x) - obstacle.extentX);
const std::int64_t overlapY = std::min<std::int64_t>(location.y,
obstacle.location.y) - std::max<std::int64_t>(
static_cast<std::int64_t>(location.y) - body.extentY,
static_cast<std::int64_t>(obstacle.location.y) - obstacle.extentY);
const std::int64_t overlapZ = std::min<std::int64_t>(
static_cast<std::int64_t>(location.z) + body.extentZ,
static_cast<std::int64_t>(obstacle.location.z) + obstacle.extentZ) -
std::max<std::int64_t>(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<GlobObject>& 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<CollisionBody>& bodies, const std::vector<ShapeTypeInfo>& 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
FastAreaRange calculateFastAreaRange(WorldPoint center)
{
const s32 blockX = center.x >> 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) {
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};
if (destination.x < 0 || destination.x > 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<s32>(std::clamp(timeScale, 1u, 4u));
return {{location.x + xSpeed * multiplier, location.y + ySpeed * multiplier,
static_cast<u8>(location.z + zSpeed * multiplier)},
static_cast<s16>(zSpeed - gravity * multiplier)};
}
CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped)
{
const s32 extentX = static_cast<s32>(flipped ? shapeInfo.y : shapeInfo.x) * shapeDimensionScale;
const s32 extentY = static_cast<s32>(flipped ? shapeInfo.x : shapeInfo.y) * shapeDimensionScale;
return CollisionBody{
location,
extentX,
extentY,
static_cast<s32>(shapeInfo.z) * shapeHeightScale};
}
CollisionBody makeSweepItemBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped)
{
const s32 extentX = static_cast<s32>(flipped ? shapeInfo.y : shapeInfo.x) * 16;
const s32 extentY = static_cast<s32>(flipped ? shapeInfo.x : shapeInfo.y) * 16;
const s32 extentZ = shapeInfo.z == 0 && (shapeInfo.flags & 1) == 0 ? 1 :
static_cast<s32>(shapeInfo.z) * shapeHeightScale;
return {location, extentX, extentY, extentZ};
}
std::optional<SweepItemImpact> 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<std::int64_t, 3> origin{moving.location.x, moving.location.y, moving.location.z};
const std::array<std::int64_t, 3> delta{
static_cast<std::int64_t>(destination.x) - origin[0],
static_cast<std::int64_t>(destination.y) - origin[1],
static_cast<std::int64_t>(destination.z) - origin[2]};
const std::array<std::int64_t, 3> obstaclePosition{
obstacle.location.x, obstacle.location.y, obstacle.location.z};
const std::array<std::int64_t, 3> movingExtent{moving.extentX, moving.extentY, moving.extentZ};
const std::array<std::int64_t, 3> obstacleExtent{obstacle.extentX, obstacle.extentY, obstacle.extentZ};
std::array<std::int64_t, 3> lower{};
std::array<std::int64_t, 3> 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<s32, 3> resolved{};
for (std::size_t coordinate = 0; coordinate < 3; ++coordinate) {
resolved[coordinate] = static_cast<s32>(origin[coordinate] +
delta[coordinate] * beforeContact / extent);
}
return SweepItemImpact{{resolved[0], resolved[1], resolved[2]},
static_cast<u8>(1u << axis)};
}
}
}
return std::nullopt;
}
std::optional<std::vector<SweepCandidateImpact>> collectSweepItemImpacts(
const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination,
const std::vector<ShapeTypeInfo>& shapes, const FastAreaRange& fastArea,
std::optional<u8> floorGapLimit)
{
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<SweepCandidateImpact> 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];
const auto obstacle = makeSweepItemBody({item->data.x, item->data.y, item->data.z},
shape, (item->data.flags & flippedFlag) != 0);
std::optional<u8> 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<u8>(gap);
}
if ((shape.flags & (solidFlag | 0x40)) == 0) {
continue;
}
if (const auto impact = sweepSolidItemImpact(movingBody, destination, obstacle)) {
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;
}
SweepCollisionResult selectSolidSweepImpact(WorldPoint from, WorldPoint destination,
const std::vector<SweepCandidateImpact>& impacts)
{
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 && candidate.impact.failedDirections != 0 &&
(std::abs(static_cast<std::int64_t>(point.x) - from.x) <
std::abs(static_cast<std::int64_t>(result.destination.x) - from.x) ||
std::abs(static_cast<std::int64_t>(point.y) - from.y) <
std::abs(static_cast<std::int64_t>(result.destination.y) - from.y) ||
std::abs(static_cast<std::int64_t>(point.z) - from.z) <
std::abs(static_cast<std::int64_t>(result.destination.z) - from.z))) {
result.destination = point;
result.firstCollision = candidate.itemNumber;
}
}
return result;
}
std::optional<SweepCollisionResult> resolveSolidLiveSweep(
const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination,
const std::vector<ShapeTypeInfo>& shapes, const FastAreaRange& fastArea,
std::optional<u8> floorGapLimit)
{
const auto* movingItem = items.findItem(movingItemNumber);
if (movingItem == nullptr || movingItem->data.shape >= shapes.size()) {
return std::nullopt;
}
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<u8>(bounds.failedDirections | 3);
result.failed = true;
return result;
}
const auto impacts = collectSweepItemImpacts(items, movingItemNumber, bounds.destination,
shapes, fastArea, floorGapLimit);
if (!impacts) {
return std::nullopt;
}
auto result = selectSolidSweepImpact(from, bounds.destination, *impacts);
result.failedDirections |= bounds.failedDirections;
return result;
}
bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right)
{
return overlapsAt(left, left.location, right);
}
bool canMoveCollisionBody(
const CollisionBody& body,
WorldPoint destination,
const std::vector<CollisionBody>& obstacles)
{
const std::int64_t dx = static_cast<std::int64_t>(destination.x) - body.location.x;
const std::int64_t dy = static_cast<std::int64_t>(destination.y) - body.location.y;
const std::int64_t dz = static_cast<std::int64_t>(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<std::int64_t>(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<s32>(body.location.x + dx * step / steps),
static_cast<s32>(body.location.y + dy * step / steps),
static_cast<s32>(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<CollisionBody> collectMapCollisionBodies(
const FixedMap& map,
const std::vector<ShapeTypeInfo>& shapeTypes,
const std::vector<GlobObject>& globObjects)
{
std::vector<CollisionBody> 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<s32>(item.x) & globCoordMask) +
(static_cast<s32>(child.x) << globCoordShift) + globCoordOffset,
(static_cast<s32>(item.y) & globCoordMask) +
(static_cast<s32>(child.y) << globCoordShift) + globCoordOffset,
static_cast<s32>(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

View file

@ -1,58 +0,0 @@
#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<u8>& bytes, u32 offset)
{
return static_cast<u16>(bytes[offset] | (static_cast<u16>(bytes[offset + 1]) << 8));
}
std::string readNullPaddedName(const std::vector<u8>& bytes)
{
std::string name;
for (u32 index = 0; index < tacticNameSize; ++index) {
if (bytes[index] == 0) {
break;
}
name.push_back(static_cast<char>(bytes[index]));
}
return name;
}
} // namespace
std::optional<std::vector<CombatTactic>> loadCombatTactics(const std::filesystem::path& path)
{
const auto archive = loadFlexArchive(path);
if (!archive) {
return std::nullopt;
}
std::vector<CombatTactic> 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

File diff suppressed because it is too large Load diff

View file

@ -1,145 +0,0 @@
#include "remorse/file_system.h"
#include <fstream>
#include <string>
namespace remorse {
namespace {
bool pathExists(const std::filesystem::path& path)
{
return std::filesystem::exists(path);
}
std::optional<std::filesystem::path> 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<char>(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<std::filesystem::path> 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<GameDataRoot> 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<std::filesystem::path> 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<std::vector<u8>> 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<u8> bytes(static_cast<std::size_t>(size));
if (!bytes.empty()) {
input.read(reinterpret_cast<char*>(bytes.data()), size);
if (!input) {
return std::nullopt;
}
}
return bytes;
}
} // namespace remorse

View file

@ -1,954 +0,0 @@
#include "remorse/fixed_map.h"
#include "remorse/glob_archive.h"
#include "remorse/entity_dispatch_entry.h"
#include "remorse/file_system.h"
#include "remorse/map_renderer.h"
#include "remorse/type_flags.h"
#include <algorithm>
#include <stdexcept>
#include <utility>
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<u16> readU16Le(const std::vector<u8>& bytes, u32 offset)
{
if (offset + 2 > bytes.size()) {
return std::nullopt;
}
return static_cast<u16>(bytes[offset] | (static_cast<u16>(bytes[offset + 1]) << 8));
}
std::optional<u32> readU32Le(const std::vector<u8>& bytes, u32 offset)
{
if (offset + 4 > bytes.size()) {
return std::nullopt;
}
return static_cast<u32>(bytes[offset]) |
(static_cast<u32>(bytes[offset + 1]) << 8) |
(static_cast<u32>(bytes[offset + 2]) << 16) |
(static_cast<u32>(bytes[offset + 3]) << 24);
}
std::optional<FixedMapEntry> readFixedMapEntry(const std::vector<u8>& 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<u16>(*diskX * crusaderCoordinateScale);
entry.y = static_cast<u16>(*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<FixedMapArchive> 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<u32>(*mapCount) * fixedMapTableRowSize);
if (tableEnd > bytes->size()) {
return std::nullopt;
}
FixedMapArchive archive;
archive.mapCount = *mapCount;
archive.bytes = *bytes;
return archive;
}
std::optional<FixedMap> 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;
}
std::optional<std::vector<StagedFixedMapItem>> stageFixedMapItems(const FixedMap& map)
{
constexpr std::size_t firstFreeItemNumber = 0x100;
constexpr std::size_t freeItemCount = 0x2700;
std::vector<StagedFixedMapItem> 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<u16>(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<u16>(item.data.x / crusaderCoordinateScale);
item.data.y = static_cast<u16>(item.data.y / crusaderCoordinateScale);
item.data.flags &= static_cast<u16>(~1u);
items.push_back(item);
}
return items;
}
std::optional<StagedFixedMapItem> findTeleportEgg(
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes, u8 eggId)
{
std::optional<StagedFixedMapItem> 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<StagedFixedMapItem> findNearbyActiveTeleportEgg(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& 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<s32>((item.data.npcNumber >> 4) & 0x0f) * 64;
const s32 yRange = static_cast<s32>(item.data.npcNumber & 0x0f) * 64;
const s32 deltaX = static_cast<s32>(origin.data.x) - item.data.x;
const s32 deltaY = static_cast<s32>(origin.data.y) - item.data.y;
const s32 deltaZ = static_cast<s32>(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<std::vector<StagedContainedFixedMapItem>> stageContainedFixedMapItems(
const FixedMap& map, const std::vector<ShapeTypeInfo>& shapes)
{
if (map.index == 0) {
return std::nullopt;
}
std::vector<StagedContainedFixedMapItem> contained;
std::vector<u16> parentById(0x2800);
std::vector<u16> 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<u16>(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, record});
} else {
currentParent = 0;
currentDepth = 0;
}
previousItemNumber = itemNumber;
}
return contained;
}
std::optional<StagedFixedMapItem> nearestStagedFixedMapItem(
const std::vector<StagedFixedMapItem>& items, s32 worldX, s32 worldY, s32 maxDistance)
{
if (maxDistance < 0) {
return std::nullopt;
}
const auto limit = static_cast<std::int64_t>(maxDistance) * maxDistance;
auto bestDistance = limit + 1;
const StagedFixedMapItem* best = nullptr;
for (const auto& item : items) {
const auto deltaX = static_cast<std::int64_t>(item.data.x) * crusaderCoordinateScale - worldX;
const auto deltaY = static_cast<std::int64_t>(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<StagedFixedMapItem>(*best);
}
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)
{
if (candidate.itemNumber == 0) {
return 0;
}
const auto height = [](const ShapeTypeInfo& shape) {
return shape.z == 0 && (shape.flags & 1) == 0 ? 1 : static_cast<int>(shape.z) * 8;
};
const int minimumX = static_cast<int>(candidate.data.x) - static_cast<int>(candidateShape.x) * 16 + 1;
const int minimumY = static_cast<int>(candidate.data.y) - static_cast<int>(candidateShape.y) * 16 + 1;
if (minimumX > origin.data.x || minimumY > origin.data.y) {
return 0;
}
const u8 originTop = static_cast<u8>(static_cast<int>(origin.data.z) + height(originShape));
if ((zMatchFlags & 1) != 0 && candidate.data.z == originTop) {
return 1;
}
if ((zMatchFlags & 2) != 0 && origin.data.z == static_cast<int>(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<s16>(value) < 0 ? negativeValue : value;
};
const u16 minX = static_cast<u16>(static_cast<int>(origin.data.x) - originShape.x * 16 + 1);
const u16 minY = static_cast<u16>(static_cast<int>(origin.data.y) - originShape.y * 16 + 1);
const u16 maxX = static_cast<u16>(origin.data.x + 0x100);
const u16 maxY = static_cast<u16>(origin.data.y + 0x100);
return {normalize(minX, 0), normalize(minY, 0),
normalize(maxX, 0x7fff), normalize(maxY, 0x7fff)};
}
std::vector<u16> itemFindBlockOrder(const ItemFindArea& area)
{
std::vector<u16> 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<u16>(blockX * 0x40 + blockY));
}
}
return blocks;
}
std::optional<StagedItemBlockChains> buildStagedItemBlockChains(const std::vector<StagedFixedMapItem>& items)
{
StagedItemBlockChains chains;
chains.heads.resize(0x1000);
chains.next.resize(0x2800);
std::vector<bool> 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<u16> itemFindCandidateOrder(const ItemFindArea& area, const StagedItemBlockChains& chains)
{
std::vector<u16> 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<std::vector<ItemFindZCandidate>> collectZMatches(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& 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<const StagedFixedMapItem*> byId(chains->next.size());
for (const auto& item : items) {
if (item.data.shape >= shapes.size()) {
return std::nullopt;
}
byId[item.itemNumber] = &item;
}
std::vector<ItemFindZCandidate> 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<std::vector<ItemFindZCandidate>> itemFindZMatches(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes, u8 zMatchFlags)
{
return collectZMatches(origin, items, shapes, zMatchFlags, false);
}
std::optional<std::vector<ItemFindZCandidate>> itemGrabSearchCandidates(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes)
{
return collectZMatches(origin, items, shapes, 3, true);
}
std::optional<std::vector<ItemGrabAction>> planItemGrabActions(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes)
{
const auto candidates = itemGrabSearchCandidates(origin, items, shapes);
if (!candidates) {
return std::nullopt;
}
std::vector<const StagedFixedMapItem*> byId(0x2800);
for (const auto& item : items) {
byId[item.itemNumber] = &item;
}
std::vector<ItemGrabAction> 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<std::vector<u16>> dispatchStagedItemGrab(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& 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<u16> 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<u16>(process->bytes[2] | (static_cast<u16>(process->bytes[3]) << 8)));
}
}
return processIds;
}
LiveFixedMapItems::LiveFixedMapItems(std::vector<StagedFixedMapItem> items,
std::vector<StagedContainedFixedMapItem> containedItems)
: 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");
}
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;
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);
}
}
bool LiveFixedMapItems::initializeAvatar()
{
if (avatar_) {
return false;
}
avatar_.emplace();
avatar_->itemNumber = 1;
avatar_->data.shape = 1;
avatar_->data.npcNumber = 1;
npcAnimations_.resize(2);
npcAnimations_[1].direction = 14;
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;
}
}
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<NpcAnimationState*>(
static_cast<const LiveFixedMapItems*>(this)->findNpcAnimation(itemNumber));
}
u16 LiveFixedMapItems::containedParent(u16 itemNumber) const
{
return itemNumber < parentById_.size() ? parentById_[itemNumber] : 0;
}
std::vector<u16> LiveFixedMapItems::containedChildren(u16 parentItemNumber) const
{
std::vector<u16> 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<StagedFixedMapItem> LiveFixedMapItems::nearestItem(s32 worldX, s32 worldY,
s32 maxDistance) const
{
return nearestStagedFixedMapItem(items_, worldX, worldY, maxDistance);
}
std::optional<std::vector<u16>> 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<const StagedFixedMapItem*> byId(chains->next.size());
for (const auto& item : items_) {
byId[item.itemNumber] = &item;
}
const ItemFindArea itemArea{static_cast<u16>(area.minX), static_cast<u16>(area.minY),
static_cast<u16>(area.maxX), static_cast<u16>(area.maxY)};
std::vector<u16> 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<u16> 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_;
}
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 >= 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<u16>(~8u);
}
item.data.z = std::min<u8>(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;
return true;
}
bool LiveFixedMapItems::moveItemIntoContainer(u16 itemNumber, u16 containerItemNumber,
const std::vector<ShapeTypeInfo>& 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<u8>(z, 0xfa);
itemData.flags &= static_cast<u16>(~9u);
items_.push_back({itemNumber, static_cast<std::size_t>(-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;
}
std::optional<std::vector<u16>> LiveFixedMapItems::hatchGlobEgg(u16 eggItemNumber,
const GlobObject& glob, const std::vector<ShapeTypeInfo>& 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<StagedFixedMapItem> children;
children.reserve(glob.entries.size());
for (const auto& entry : glob.entries) {
StagedFixedMapItem child;
child.recordIndex = static_cast<std::size_t>(-1);
child.data.x = static_cast<u16>((egg->data.x & ~0x1ff) + entry.x * 2 + 1);
child.data.y = static_cast<u16>((egg->data.y & ~0x1ff) + entry.y * 2 + 1);
child.data.z = static_cast<u8>(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::size_t>(std::count(
allocatedIds_.begin() + nextFreeItemNumber_, allocatedIds_.end(), false));
if (freeCount < children.size()) {
return std::nullopt;
}
std::vector<u16> 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::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) {
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) {
return false;
}
if (itemNumber == 1) {
if (!avatar_) {
return false;
}
avatar_->data.x = x;
avatar_->data.y = y;
avatar_->data.z = std::min<u8>(z, 0xfa);
return true;
}
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<u8>(z, 0xfa);
std::rotate(item, item + 1, items_.end());
return true;
}
std::optional<std::vector<u16>> LiveFixedMapItems::grabItem(u16 itemNumber,
const std::vector<ShapeTypeInfo>& 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<std::vector<u16>> LiveFixedMapItems::moveApprovedItem(u16 itemNumber, u16 x, u16 y,
u8 z, const std::vector<ShapeTypeInfo>& 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

View file

@ -1,83 +0,0 @@
#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<u32> readU32Le(const std::vector<u8>& bytes, u32 offset)
{
if (offset + 4 > bytes.size()) {
return std::nullopt;
}
return static_cast<u32>(bytes[offset]) |
(static_cast<u32>(bytes[offset + 1]) << 8) |
(static_cast<u32>(bytes[offset + 2]) << 16) |
(static_cast<u32>(bytes[offset + 3]) << 24);
}
} // namespace
std::optional<FlexArchive> 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<std::vector<u8>> 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<u8>(begin, end);
}
}
return std::nullopt;
}
} // namespace remorse

View file

@ -1,56 +0,0 @@
#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<u8>& bytes, u32 offset)
{
return static_cast<u16>(bytes[offset] | (static_cast<u16>(bytes[offset + 1]) << 8));
}
} // namespace
std::optional<std::vector<GlobObject>> loadGlobObjects(const std::filesystem::path& path)
{
const auto archive = loadFlexArchive(path);
if (!archive) {
return std::nullopt;
}
std::vector<GlobObject> 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<u32>(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

View file

@ -1,183 +0,0 @@
#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 "remorse/usecode_archive.h"
#include <filesystem>
#include <iostream>
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());
const auto manifest = remorse::loadExportManifestSummary(manifestPath);
if (!manifest) {
std::cerr << "Could not read export manifest: " << manifestPath.string() << '\n';
return 2;
}
remorse::printStartupReport(*manifest);
remorse::ProcessKernel kernel;
remorse::u16 groupCounts[32]{};
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();
const remorse::u32 schedulerElapsed = kernel.runTimedSchedulerPass(1, [](remorse::EntityDispatchEntryBase& process, void* context) {
auto& scan = *static_cast<ScanContext*>(context);
if (process.bytes[0] == 0x0f && process.bytes[1] == 0x1f) {
remorse::StandProcess::run(*scan.standing, *scan.npcServices, scan.timerTick);
} else {
++scan.hostCallbacks;
}
}, &scanContext);
kernel.refreshActiveGroup(groupCounts);
remorse::EntityDispatchEntry::incrementGroupId(*entry, kernel, groupCounts);
std::cout << "Advanced process group: " << static_cast<int>(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<int>(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<remorse::StagedFixedMapItem> firstStagedItem;
std::optional<remorse::StagedItemBlockChains> stagedBlockChains;
std::optional<std::vector<remorse::StagedFixedMapItem>> 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';
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';
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];
remorse::u16 releaseEventItem = 0;
} itemScan{&kernel, &groupCounts};
auto* itemProcess = kernel.createItemProcess(kernel.activeGroup(), items->front().itemNumber, groupCounts);
const remorse::u16 itemProcessId = static_cast<remorse::u16>(
itemProcess->bytes[2] | (static_cast<remorse::u16>(itemProcess->bytes[3]) << 8));
kernel.scanRunnableProcesses(kernel.activeGroup(), [](remorse::EntityDispatchEntryBase& process, void* context) {
auto& scan = *static_cast<ItemScanContext*>(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<ItemScanContext*>(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;
}
}
}
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';
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';
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");
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;
}

View file

@ -1,53 +0,0 @@
#include "remorse/file_system.h"
#include "remorse/map_renderer.h"
#include "remorse/runtime.h"
#include <filesystem>
#include <iostream>
#include <string>
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";
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<remorse::u32>(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;
}

View file

@ -1,499 +0,0 @@
#include "remorse/map_renderer.h"
#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"
#include <algorithm>
#include <fstream>
#include <map>
#include <unordered_map>
namespace remorse {
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;
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;
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;
s32 bottom = 0;
};
bool isEggFamily(u8 family)
{
return family == 3 || family == 4 || family == 7 || family == 8;
}
bool inWorldRect(const SceneItem& item, const std::optional<WorldRect>& 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<u8>((static_cast<u32>(color.red) * 255) / 63);
scaled.green = static_cast<u8>((static_cast<u32>(color.green) * 255) / 63);
scaled.blue = static_cast<u8>((static_cast<u32>(color.blue) * 255) / 63);
return scaled;
}
std::vector<SceneItem> collectSceneItems(
const FixedMap& fixedMap,
const std::vector<ShapeTypeInfo>& typeFlags,
const std::vector<GlobObject>& globs,
const MapRenderOptions& options,
const LiveFixedMapItems* liveItems)
{
std::unordered_map<u32, const GlobObject*> globsByIndex;
globsByIndex.reserve(globs.size());
for (const GlobObject& glob : globs) {
globsByIndex.try_emplace(glob.index, &glob);
}
std::vector<SceneItem> pending;
pending.reserve(fixedMap.entries.size());
std::vector<const StagedFixedMapItem*> 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<s32>(entry.x) * scale,
static_cast<s32>(entry.y) * scale,
static_cast<s32>(entry.z),
entry.shape,
entry.frame,
entry.flags,
entry.quality,
entry.mapNumber,
true});
}
if (liveItems != nullptr) {
for (const auto& item : liveItems->mapItems()) {
if (item.recordIndex == static_cast<std::size_t>(-1)) {
pending.push_back(SceneItem{static_cast<s32>(item.data.x) * 2,
static_cast<s32>(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<SceneItem> 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* stagedEgg = liveByRecord.empty() || index >= liveByRecord.size()
? nullptr : liveByRecord[index];
const auto glob = stagedEgg && liveItems->isGlobHatched(stagedEgg->itemNumber)
? 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<s32>(entry.x) << globCoordShift) + globCoordOffset,
(item.y & globCoordMask) + (static_cast<s32>(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 projectToScreen(WorldPoint{item.x, item.y, item.z}).x;
}
s32 screenY(const SceneItem& item)
{
return projectToScreen(WorldPoint{item.x, item.y, item.z}).y;
}
const DecodedShapeFrame* cachedDecode(
const ShapeArchive& archive,
std::map<u32, std::vector<ShapeFrame>>& parsedFrames,
std::map<std::pair<u32, u32>, 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;
}
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;
}
return &cache.emplace(key, std::move(*decoded)).first->second;
}
std::vector<RenderNode> prepareRenderNodes(
const std::vector<SceneItem>& items,
const ShapeArchive& shapeArchive,
std::map<u32, std::vector<ShapeFrame>>& parsedFrames,
const std::vector<ShapeTypeInfo>& typeFlags,
std::map<std::pair<u32, u32>, DecodedShapeFrame>& cache)
{
std::vector<RenderNode> nodes;
std::vector<detail::RenderSortItem> sortItems;
nodes.reserve(items.size());
sortItems.reserve(items.size());
for (const SceneItem& item : items) {
const auto* decoded = item.decodedOverride != nullptr
? item.decodedOverride : cachedDecode(
shapeArchive, parsedFrames, 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.paletteOverride = item.paletteOverride;
node.left = flipped
? bottomX + decoded->frame.xOffset - static_cast<s32>(decoded->frame.width)
: bottomX - decoded->frame.xOffset;
node.top = bottomY - decoded->frame.yOffset;
node.right = node.left + static_cast<s32>(decoded->frame.width);
node.bottom = node.top + static_cast<s32>(decoded->frame.height);
const ShapeTypeInfo& info = typeFlags[item.shape];
const s32 xDimension = static_cast<s32>(flipped ? info.y : info.x) * 32;
const s32 yDimension = static_cast<s32>(flipped ? info.x : info.y) * 32;
const s32 zDimension = static_cast<s32>(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);
}
const std::vector<std::size_t> order = detail::resolveRenderOrder(sortItems);
std::vector<RenderNode> 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)
{
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<s32>(sourceY);
if (destY < 0 || destY >= static_cast<s32>(image.height)) {
continue;
}
const std::size_t sourceRow = static_cast<std::size_t>(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<s32>(sourceX);
if (destX < 0 || destX >= static_cast<s32>(image.width)) {
continue;
}
const std::size_t pixelIndex = static_cast<std::size_t>(destY) * image.width + destX;
image.pixels[pixelIndex] = scalePaletteColor(nodePalette.colors[colorIndex]);
image.coverage[pixelIndex] = 1;
}
}
}
void writeLe16(std::ofstream& output, u16 value)
{
output.put(static_cast<char>(value & 0xff));
output.put(static_cast<char>((value >> 8) & 0xff));
}
void writeLe32(std::ofstream& output, u32 value)
{
output.put(static_cast<char>(value & 0xff));
output.put(static_cast<char>((value >> 8) & 0xff));
output.put(static_cast<char>((value >> 16) & 0xff));
output.put(static_cast<char>((value >> 24) & 0xff));
}
} // namespace
ScreenPoint projectToScreen(const WorldPoint& point)
{
return ScreenPoint{(point.x - point.y) / 4, (point.x + point.y) / 8 - point.z};
}
std::optional<MapSceneRenderer> 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");
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, 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;
}
return MapSceneRenderer{std::move(*fixedMap), std::move(*globs), std::move(*shapeArchive),
*palette, std::move(*typeFlags), {}};
}
std::optional<RenderedMapImage> MapSceneRenderer::render(const MapRenderOptions& options,
const LiveFixedMapItems* liveItems, const MapRenderSprite* sprite)
{
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<u8>(options.mapIndex);
sceneSprite.fromFixed = false;
sceneSprite.decodedOverride = sprite->decoded;
sceneSprite.paletteOverride = sprite->palette;
if (inWorldRect(sceneSprite, options.worldRect)) {
items.push_back(sceneSprite);
}
}
std::map<u32, std::vector<ShapeFrame>> parsedFrames;
auto nodes = prepareRenderNodes(items, shapes, parsedFrames, typeFlags, decodedFrames);
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<u32>(map.entries.size());
image.renderItemCount = static_cast<u32>(items.size());
image.decodedItemCount = static_cast<u32>(nodes.size());
image.fullWidth = maxRight - minLeft;
image.fullHeight = maxBottom - minTop;
image.width = options.viewCenter
? options.maxWidth
: std::min(options.maxWidth, static_cast<u32>(std::max<s32>(1, image.fullWidth)));
image.height = options.viewCenter
? options.maxHeight
: std::min(options.maxHeight, static_cast<u32>(std::max<s32>(1, image.fullHeight)));
if (options.viewCenter) {
const ScreenPoint center = projectToScreen(*options.viewCenter);
image.sourceLeft = center.x - static_cast<s32>(image.width / 2);
image.sourceTop = center.y - static_cast<s32>(image.height / 2);
} else {
image.sourceLeft = nodes[0].left;
image.sourceTop = nodes[0].top;
}
image.pixels.assign(
static_cast<std::size_t>(image.width) * image.height,
RgbColor{static_cast<u8>(10), static_cast<u8>(12), static_cast<u8>(18)});
image.coverage.assign(image.pixels.size(), 0);
for (const RenderNode& node : nodes) {
if (node.right < image.sourceLeft || node.bottom < image.sourceTop ||
node.left >= image.sourceLeft + static_cast<s32>(image.width) ||
node.top >= image.sourceTop + static_cast<s32>(image.height)) {
continue;
}
paintNode(image, node, palette);
++image.paintedItemCount;
}
return image;
}
std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options)
{
auto renderer = loadMapSceneRenderer(root, options.mapIndex);
return renderer ? renderer->render(options) : std::nullopt;
}
std::optional<RenderedMapImage> 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<std::size_t>(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<u8> row(rowStride, 0);
for (s32 y = static_cast<s32>(image.height) - 1; y >= 0; --y) {
std::fill(row.begin(), row.end(), static_cast<u8>(0));
for (u32 x = 0; x < image.width; ++x) {
const RgbColor& pixel = image.pixels[static_cast<std::size_t>(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<const char*>(row.data()), row.size());
}
return static_cast<bool>(output);
}
} // namespace remorse

View file

@ -1,372 +0,0 @@
#include "remorse/detail/map_sorter.h"
#include <algorithm>
#include <cstdint>
#include <set>
#include <unordered_map>
namespace remorse {
namespace detail {
namespace {
struct SortNode {
RenderSortItem item;
std::vector<std::size_t> dependencies;
bool occluded = false;
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<std::uint64_t>(static_cast<std::uint32_t>(x)) << 32) |
static_cast<std::uint32_t>(y);
}
bool listLessThan(const RenderSortItem& left, const RenderSortItem& right)
{
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.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<SortNode>& nodes, std::size_t owner, std::size_t dependency)
{
std::vector<std::size_t>& 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<std::size_t> resolveRenderOrder(const std::vector<RenderSortItem>& items)
{
std::vector<SortNode> nodes;
nodes.reserve(items.size());
for (const RenderSortItem& item : items) {
nodes.push_back(SortNode{item, {}, false, -1});
}
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<std::size_t, decltype(indexLessThan)> ordered(indexLessThan);
std::unordered_map<std::uint64_t, std::vector<std::size_t>> spatialBuckets;
spatialBuckets.reserve(nodes.size() * 2);
std::vector<std::size_t> visited(nodes.size(), 0);
std::vector<std::size_t> candidates;
for (std::size_t index = 0; index < nodes.size(); ++index) {
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;
}
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(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<std::size_t> 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<s32>(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

View file

@ -1,23 +0,0 @@
#include "remorse/palette.h"
#include "remorse/file_system.h"
namespace remorse {
std::optional<Palette256> 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

View file

@ -1,146 +0,0 @@
#include "remorse/runtime.h"
#include <fstream>
#include <iostream>
#include <regex>
#include <sstream>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <crtdbg.h>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <exception>
#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<DWORD>(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);
if (!input) {
return {};
}
std::ostringstream buffer;
buffer << input.rdbuf();
return buffer.str();
}
std::optional<std::string> 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<u32>(std::stoul(match[1].str()));
}
} // 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<ExportManifestSummary> 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: StandProcess Run, registered timer, and keyboard diagnostic callback active; original key queue, NPC services, and game loop not linked.\n";
}
} // namespace remorse

View file

@ -1,211 +0,0 @@
#include "remorse/shape_archive.h"
namespace remorse {
namespace {
std::optional<u16> readU16Le(const std::vector<u8>& bytes, u32 offset)
{
if (offset + 2 > bytes.size()) {
return std::nullopt;
}
return static_cast<u16>(bytes[offset] | (static_cast<u16>(bytes[offset + 1]) << 8));
}
std::optional<u32> readU24Le(const std::vector<u8>& bytes, u32 offset)
{
if (offset + 3 > bytes.size()) {
return std::nullopt;
}
return static_cast<u32>(bytes[offset]) |
(static_cast<u32>(bytes[offset + 1]) << 8) |
(static_cast<u32>(bytes[offset + 2]) << 16);
}
std::optional<u32> readU32Le(const std::vector<u8>& bytes, u32 offset)
{
if (offset + 4 > bytes.size()) {
return std::nullopt;
}
return static_cast<u32>(bytes[offset]) |
(static_cast<u32>(bytes[offset + 1]) << 8) |
(static_cast<u32>(bytes[offset + 2]) << 16) |
(static_cast<u32>(bytes[offset + 3]) << 24);
}
std::optional<s32> readS32Le(const std::vector<u8>& bytes, u32 offset)
{
const auto value = readU32Le(bytes, offset);
if (!value) {
return std::nullopt;
}
return static_cast<s32>(*value);
}
std::optional<ShapeFrame> parseFrame(const std::vector<u8>& bytes, u32 frameOffset, u32 frameSize)
{
if (frameOffset > bytes.size() || frameSize > bytes.size() - frameOffset || frameSize < 28) {
return std::nullopt;
}
std::vector<u8> 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<std::vector<s16>> decodePixels(const ShapeFrame& frame)
{
if (frame.width == 0 || frame.height == 0 || frame.width > 4096 || frame.height > 4096) {
return std::nullopt;
}
std::vector<s16> pixels(static_cast<std::size_t>(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<std::size_t>(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<ShapeArchive> 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<std::vector<ShapeFrame>> 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<u32>(*frameCount) * 8 > bytes->size()) {
return std::nullopt;
}
std::vector<ShapeFrame> 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<DecodedShapeFrame> decodeShapeFrame(const ShapeFrame& frame)
{
const auto pixels = decodePixels(frame);
if (!pixels) {
return std::nullopt;
}
DecodedShapeFrame decoded;
decoded.frame = frame;
decoded.pixels = *pixels;
return decoded;
}
std::optional<DecodedShapeFrame> 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

View file

@ -1,39 +0,0 @@
#include "remorse/type_flags.h"
#include "remorse/file_system.h"
namespace remorse {
std::optional<std::vector<ShapeTypeInfo>> loadTypeFlags(const std::filesystem::path& path)
{
const auto bytes = readBinaryFile(path);
if (!bytes || (bytes->size() % 9) != 0) {
return std::nullopt;
}
std::vector<ShapeTypeInfo> 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<u32>(byte0) |
(static_cast<u32>(byte1 & 0x0f) << 8) |
(static_cast<u32>(byte6) << 12);
info.family = static_cast<u8>((byte1 >> 4) + ((byte2 & 1) << 4));
info.x = static_cast<u8>(((byte3 << 3) | (byte2 >> 5)) & 0x1f);
info.y = static_cast<u8>((byte3 >> 2) & 0x1f);
info.z = static_cast<u8>(((byte4 << 1) | (byte3 >> 7)) & 0x1f);
info.animationType = static_cast<u8>(byte4 >> 4);
info.weight = (*bytes)[offset + 7];
infos.push_back(info);
}
return infos;
}
} // namespace remorse

View file

@ -1,417 +0,0 @@
#include "remorse/usecode_archive.h"
#include <algorithm>
#include <limits>
#include <utility>
namespace remorse {
namespace {
u16 readWord(const std::vector<u8>& bytes, std::size_t offset)
{
return static_cast<u16>(bytes[offset] | (static_cast<u16>(bytes[offset + 1]) << 8));
}
u32 readDword(const std::vector<u8>& bytes, std::size_t offset)
{
return static_cast<u32>(bytes[offset]) | (static_cast<u32>(bytes[offset + 1]) << 8) |
(static_cast<u32>(bytes[offset + 2]) << 16) | (static_cast<u32>(bytes[offset + 3]) << 24);
}
void writeWord(std::vector<u8>& bytes, std::size_t offset, u16 value)
{
bytes[offset] = static_cast<u8>(value);
bytes[offset + 1] = static_cast<u8>(value >> 8);
}
void writeDword(std::vector<u8>& bytes, std::size_t offset, u32 value)
{
writeWord(bytes, offset, static_cast<u16>(value));
writeWord(bytes, offset + 2, static_cast<u16>(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<u8> serialize(const UsecodeLoadedChunkProcessLayout& layout)
{
const auto* first = reinterpret_cast<const u8*>(&layout);
return std::vector<u8>(first, first + sizeof(layout));
}
std::optional<UsecodeEventBody> readEventBodyFromDescriptors(const UsecodeClass& usecodeClass,
const std::vector<u8>& 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<std::size_t>(eventId) * 6 + 6) {
return std::nullopt;
}
const std::size_t row = descriptorOffset + static_cast<std::size_t>(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<std::size_t>(offset) - 1;
if (length > usecodeClass.bytes.size() - start) {
return std::nullopt;
}
return UsecodeEventBody{length, offset,
std::vector<u8>(usecodeClass.bytes.begin() + start, usecodeClass.bytes.begin() + start + length)};
}
} // namespace
std::optional<FarPtr16> UsecodeRuntimeMemory::allocate(std::size_t byteCount, u8 initialValue)
{
constexpr std::size_t maxSegmentBytes = static_cast<std::size_t>(std::numeric_limits<u16>::max()) + 1;
if (byteCount == 0 || byteCount > maxSegmentBytes || nextSegment_ > std::numeric_limits<u16>::max()) {
return std::nullopt;
}
const auto segment = static_cast<u16>(nextSegment_++);
allocations_.emplace(segment, std::vector<u8>(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<std::vector<u8>> 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<u8>(allocation->second.begin() + address.offset,
allocation->second.begin() + address.offset + byteCount);
}
bool UsecodeRuntimeMemory::write(FarPtr16 address, const std::vector<u8>& 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) {
return static_cast<u16>(item.itemNumber + bases.npc);
}
if (item.family == 4) {
return static_cast<u16>((item.quality & 0xff) + bases.unknownEgg);
}
return static_cast<u16>(item.shape + bases.regularShape);
}
std::optional<std::vector<u8>> 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<u8>& ownerRows, u16 classId, u32 eventMask)
{
constexpr std::size_t rowSize = 13;
const std::size_t row = static_cast<std::size_t>(classId) * rowSize;
if (eventMask == 0 || row > ownerRows.size() || ownerRows.size() - row < rowSize) {
return false;
}
return (readDword(ownerRows, row) & eventMask) != 0;
}
std::optional<UsecodeClass> 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<std::size_t>(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;
}
std::string name;
for (std::size_t index = 0; index < 9 && (*names)[nameOffset + index] != 0; ++index) {
name.push_back(static_cast<char>((*names)[nameOffset + index]));
}
return UsecodeClass{classId, std::move(name), extraSlotCount, codeBase, std::move(*bytes)};
}
std::optional<UsecodeSlotOwnerBuffers> 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<std::size_t>(usecodeClass.extraSlotCount) * 6;
const std::size_t stateBytes = baseStateBytes +
static_cast<std::size_t>(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<UsecodeEventBody> readUsecodeEventBody(const UsecodeClass& usecodeClass, u32 eventId)
{
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 UsecodeEventBody* UsecodeSlotChunkCache::ensureLoaded(u16 chunkIndex)
{
if (chunkIndex >= chunks_.size()) {
return nullptr;
}
auto& process = chunks_[chunkIndex];
auto& state = ownerBuffers_.chunkStates[chunkIndex];
if (!process) {
if (state != 0xffff || usecodeClass_.classId > std::numeric_limits<u16>::max()) {
return nullptr;
}
auto loadedBody = readEventBodyFromDescriptors(usecodeClass_, ownerBuffers_.descriptors, 0, chunkIndex);
if (!loadedBody) {
return nullptr;
}
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<std::size_t>(chunkIndex) * 6;
const u32 sourceOffset = readDword(ownerBuffers_.descriptors, descriptorOffset + 2);
loadedProcess.layout.savedSource = FarPtr16{
static_cast<u16>(sourceOffset), static_cast<u16>(sourceOffset >> 16)};
loadedProcess.layout.slotIndex = static_cast<u16>(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<u32>(loadedProcessState.layout.chunkBuffer.offset) |
(static_cast<u32>(loadedProcessState.layout.chunkBuffer.segment) << 16));
state = 1;
} else {
if (state >= 29999) {
return nullptr;
}
++state;
}
return &chunks_[chunkIndex]->body;
}
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)
{
if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] != 0 || !chunks_[chunkIndex]) {
return false;
}
auto& process = *chunks_[chunkIndex];
const std::size_t descriptorOffset = static_cast<std::size_t>(chunkIndex) * 6;
writeDword(ownerBuffers_.descriptors, descriptorOffset + 2,
static_cast<u32>(process.layout.savedSource.offset) |
(static_cast<u32>(process.layout.savedSource.segment) << 16));
ownerBuffers_.chunkStates[chunkIndex] = 0xffff;
if (!unlinkLoadedProcess(process.processAddress)) {
writeDword(ownerBuffers_.descriptors, descriptorOffset + 2,
static_cast<u32>(process.layout.chunkBuffer.offset) |
(static_cast<u32>(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;
}
u16 UsecodeSlotChunkCache::inUseCount(u16 chunkIndex) const noexcept
{
if (chunkIndex >= chunks_.size() || ownerBuffers_.chunkStates[chunkIndex] == 0xffff) {
return 0;
}
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<EligibleUsecodeEvent> selectEligibleUsecodeEvent(const FlexArchive& archive,
const std::vector<u8>& 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

View file

@ -1,753 +0,0 @@
#include "remorse/usecode_vm.h"
#include "remorse/usecode_archive.h"
#include <algorithm>
namespace remorse {
namespace {
void writeWord(u8* bytes, std::size_t offset, u16 value)
{
bytes[offset] = static_cast<u8>(value);
bytes[offset + 1] = static_cast<u8>(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> UsecodeInterpreterState::initialize(
const std::vector<u8>& itemParameter, const std::vector<u8>& contextParameter,
u16 modeFlags, bool contextParameterPresent)
{
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() ||
savedPointerBytes > usecodeInterpreterStackLimit - itemParameter.size() - contextParameter.size()) {
return std::nullopt;
}
UsecodeInterpreterState state;
state.stackHighWatermark = state.valueStack.size();
const auto pushBytes = [&state](const std::vector<u8>& bytes) {
state.stackTop -= bytes.size();
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<u16>(state.stackTop - sizeof(u16) * 2);
state.contextParameterStackTop = static_cast<u16>(stackTopBeforeContextParameter);
}
return state;
}
bool UsecodeInterpreterState::pushCodeAddress(u16 offset, u16 segment)
{
if (callFrameCount >= 0x1f) {
return false;
}
callFrames[callFrameCount++] = UsecodeCallFrame{offset, segment};
return true;
}
bool UsecodeInterpreterState::pushWord(u16 value)
{
if (stackTop < sizeof(value)) {
return false;
}
stackTop -= sizeof(value);
valueStack[stackTop] = static_cast<u8>(value);
valueStack[stackTop + 1] = static_cast<u8>(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<u8>(value >> (index * 8));
}
return true;
}
std::optional<u16> UsecodeInterpreterState::popWord()
{
if (stackTop > stackHighWatermark || stackHighWatermark > valueStack.size() ||
stackHighWatermark - stackTop < sizeof(u16)) {
return std::nullopt;
}
const u16 value = static_cast<u16>(valueStack[stackTop] |
(static_cast<u16>(valueStack[stackTop + 1]) << 8));
stackTop += sizeof(u16);
return value;
}
std::optional<u32> 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<u32>(valueStack[stackTop + index]) << (index * 8);
}
stackTop += sizeof(value);
return value;
}
UsecodeStepResult UsecodeInterpreterState::step(const std::vector<u8>& code,
std::size_t& programCounter, std::vector<u8>& 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<s8>(code[programCounter]);
const auto localIndex = static_cast<std::ptrdiff_t>(usecodeFrameBaseOffset) + rawOffset;
const bool byteOperation = opcode == 0x00 || opcode == 0x3e;
const std::size_t valueSize = byteOperation ? sizeof(u8) : sizeof(u16);
if (localIndex < 0 || static_cast<std::size_t>(localIndex) > frame.size() ||
frame.size() - static_cast<std::size_t>(localIndex) < valueSize) {
return UsecodeStepResult::InvalidInstruction;
}
const std::size_t localOffset = static_cast<std::size_t>(localIndex);
if (opcode == 0x3e) {
++programCounter;
return pushWord(frame[localOffset])
? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault;
}
if (opcode == 0x3f) {
++programCounter;
const u16 value = static_cast<u16>(frame[localOffset] |
(static_cast<u16>(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<s16>(static_cast<s8>(code[programCounter++]));
return pushWord(static_cast<u16>(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<u32>(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<u16>(code[programCounter + 1] |
(static_cast<u16>(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<u16>(*left + *right);
else if (opcode == 0x1c) result = static_cast<u16>(*left - *right);
else if (opcode == 0x24) result = static_cast<u16>(*left == *right);
else if (opcode == 0x2a) result = static_cast<u16>(*left <= *right);
else if (opcode == 0x2c) result = static_cast<u16>(static_cast<s16>(*left) > static_cast<s16>(*right));
else result = static_cast<u16>(*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<s16>(code[programCounter] |
(static_cast<u16>(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<std::ptrdiff_t>(programCounter) + relativeOffset;
if (target < 0 || static_cast<std::size_t>(target) >= code.size()) {
return UsecodeStepResult::InvalidInstruction;
}
programCounter = static_cast<std::size_t>(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<u8>(temporaryWord))
? UsecodeStepResult::Advanced : UsecodeStepResult::StackFault;
}
if (opcode == 0x6e) {
if (programCounter >= code.size()) {
return UsecodeStepResult::InvalidInstruction;
}
const auto adjustment = static_cast<s8>(code[programCounter++]);
const auto newTop = static_cast<std::ptrdiff_t>(stackTop) - adjustment;
if (newTop < 0 || newTop > static_cast<std::ptrdiff_t>(valueStack.size())) {
return UsecodeStepResult::StackFault;
}
stackTop = static_cast<std::size_t>(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<u16>(code[programCounter] |
(static_cast<u16>(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<u32>(frame[localIndex]) |
(static_cast<u32>(frame[localIndex + 1]) << 8) |
(static_cast<u32>(frame[localIndex + 2]) << 16) |
(static_cast<u32>(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<u16>(*address),
static_cast<u16>(*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<u16, 2>{*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<u16>(code[programCounter + 2] |
(static_cast<u16>(code[programCounter + 3]) << 8));
const u16 eventSlot = static_cast<u16>(code[programCounter + 4] |
(static_cast<u16>(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<u16>(*itemPointer),
static_cast<u16>(*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> UsecodeProcessTask::create(u16 processId, u16 classId,
u16 eventSlot, u16 sourceItem, std::vector<u8> code, u8 itemArgumentSize,
std::vector<u8> extraArguments, std::vector<u8> contextParameter)
{
if (processId < 3 || code.size() <= usecodeEventBytecodeOffset ||
(itemArgumentSize != 0 && itemArgumentSize != sizeof(u16))) {
return std::nullopt;
}
const std::vector<u8> itemParameter = itemArgumentSize == 0 ? std::vector<u8>{}
: std::vector<u8>{static_cast<u8>(sourceItem), static_cast<u8>(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<u8>(sourceItem);
task.itemMemory[0x101] = static_cast<u8>(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<u16> 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<u16>(itemMemory[address.offset] |
(static_cast<u16>(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<u8>(value);
processBytes[offset + 1] = static_cast<u8>(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<u8>(fields.modeFlags);
processBytes[usecodeContextActiveFlagOffset] = 0;
return true;
}
std::optional<UsecodeContextInstance> 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<u8> itemParameter;
if (request.modeFlags != 0 && request.itemParameter) {
if (request.itemParameter->size() != request.modeFlags) {
return std::nullopt;
}
itemParameter = *request.itemParameter;
}
const std::vector<u8> contextParameter = request.contextParameter.value_or(std::vector<u8>{});
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<u32>(processAddress->offset) +
usecodeContextInterpreterOffset + static_cast<u32>(interpreter->stackTop);
const auto stackBaseOffset = static_cast<u32>(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<u16>(stackTopOffset), processAddress->segment});
writeFarPointer(context.processBytes.data(), usecodeContextStackBaseOffset,
FarPtr16{static_cast<u16>(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<u32>(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<u16>(savedStackOffset), processAddress->segment});
}
std::vector<u8> callStackBytes(usecodeInterpreterCallStackSize, 0);
for (u16 index = 0; index < interpreter->callFrameCount; ++index) {
const std::size_t frameOffset = static_cast<std::size_t>(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<u8> 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<UsecodeEventContext> createUsecodeEventContext(UsecodeRuntimeMemory& memory,
const std::vector<u8>& ownerRows, u16 classId, u16 eventSlot, u16 sourceItem,
const std::vector<u8>& code, u8 itemArgumentSize)
{
constexpr std::size_t ownerRowSize = 13;
const std::size_t ownerRowOffset = static_cast<std::size_t>(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<u8>& bytes)
-> std::optional<FarPtr16> {
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<u8> 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<u8> contextParameter{
static_cast<u8>(outputRegion->offset),
static_cast<u8>(outputRegion->offset >> 8),
static_cast<u8>(outputRegion->segment),
static_cast<u8>(outputRegion->segment >> 8)
};
UsecodeContextCreateRequest request;
request.codeSource = *codeRegion;
request.ownerRows = FarPtr16{4, ownerRowRegion->segment};
if (itemArgumentSize == sizeof(u16)) {
request.itemParameter = std::vector<u8>{static_cast<u8>(sourceItem),
static_cast<u8>(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) {
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;
}
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);
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;
}
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)
{
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

File diff suppressed because it is too large Load diff

View file

@ -1,183 +0,0 @@
#include "remorse/animation_archive.h"
#include "remorse/file_system.h"
#include "remorse/isometric_controls.h"
#include "remorse/shape_archive.h"
#include <cassert>
#include <array>
#include <filesystem>
namespace {
void writeU32Le(std::vector<remorse::u8>& bytes, std::size_t offset, remorse::u32 value)
{
for (std::size_t index = 0; index < 4; ++index) {
bytes[offset + index] = static_cast<remorse::u8>(value >> (index * 8));
}
}
remorse::AnimationArchive makeSyntheticArchive()
{
constexpr remorse::u32 shapeTable = 0x20;
constexpr remorse::u32 clipOffset = 0x440;
std::vector<remorse::u8> 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);
std::array<std::optional<remorse::AnimationClip>, 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) {
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}}) {
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<bool> referencedFrames(playerFrames->size(), false);
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);
assert(metadata.has_value());
const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata);
assert(shapeFrame < referencedFrames.size());
referencedFrames[shapeFrame] = true;
}
}
}
for (std::size_t frame = 0; frame < referencedFrames.size(); ++frame) {
if (referencedFrames[frame]) {
assert(remorse::decodeShapeFrame((*playerFrames)[frame]).has_value());
}
}
assert(std::any_of(referencedFrames.begin(), referencedFrames.end(), [](bool referenced) {
return referenced;
}));
return 0;
}

View file

@ -1,265 +0,0 @@
#include "remorse/collision.h"
#include <cassert>
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));
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 &&
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));
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);
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<remorse::ShapeTypeInfo> 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::collectSweepItemImpacts(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::collectSweepItemImpacts(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);
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);
const std::vector<remorse::SweepCandidateImpact> 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<remorse::SweepCandidateImpact> 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);
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<remorse::u16>{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::collectSweepItemImpacts(liveSweepItems, 0x105,
{700, 512, 0}, sweepShapes, allBlocks));
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<remorse::ShapeTypeInfo> 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;
}

View file

@ -1,23 +0,0 @@
#include "remorse/combat_tactics.h"
#include "remorse/file_system.h"
#include <cassert>
#include <filesystem>
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;
}

File diff suppressed because it is too large Load diff

View file

@ -1,127 +0,0 @@
#include "remorse/file_system.h"
#include "remorse/runtime.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <exception>
#include <filesystem>
#include <stdexcept>
#include <string>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#ifdef _DEBUG
#include <crtdbg.h>
#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
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
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;
}
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);
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);
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
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;
}

View file

@ -1,488 +0,0 @@
#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"
#include <cassert>
#include <filesystem>
#include <vector>
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 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 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;
auto candidate = origin;
candidate.itemNumber = static_cast<remorse::u16>(origin.itemNumber + 1);
candidate.data.z = static_cast<remorse::u8>(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;
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<remorse::u16>(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));
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);
assert(crossingArea.minX == 496 && crossingArea.minY == 496);
assert(crossingArea.maxX == 767 && crossingArea.maxY == 767);
assert((remorse::itemFindBlockOrder(crossingArea) == std::vector<remorse::u16>{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<remorse::u16>{0}));
std::vector<remorse::StagedFixedMapItem> 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<remorse::u16>{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<remorse::ShapeTypeInfo> 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));
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);
const auto sweepBefore = liveItems.sweepCandidateIds({511, 511, 512, 512}, 0x105);
assert(sweepBefore && (*sweepBefore == std::vector<remorse::u16>{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));
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 sweepAfter = reorderedItems.sweepCandidateIds({511, 511, 512, 512}, 0x105);
assert(sweepAfter && (*sweepAfter == std::vector<remorse::u16>{0x100, 0x103, 0x102}));
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 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));
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;
globEgg.data.y = 0x601;
globEgg.data.z = 12;
globEgg.data.shape = 3;
globEgg.data.quality = 7;
remorse::LiveFixedMapItems hatchedItems({globEgg});
std::vector<remorse::ShapeTypeInfo> 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<remorse::u16>{0x101});
const auto* child = hatchedItems.findItem(0x101);
assert(child && child->recordIndex == static_cast<std::size_t>(-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 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<remorse::u16>(
itemOwner->bytes[0x02] | (static_cast<remorse::u16>(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]{};
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());
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) {
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<remorse::u8>(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<RetailScan*>(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<RetailScan*>(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);
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<remorse::ShapeTypeInfo> 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);
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<remorse::u16>{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<remorse::u16>{0x101, 0x103}));
assert((nestedItems.containedChildren(0x101) == std::vector<remorse::u16>{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<remorse::u16>{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<remorse::u16>{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<remorse::u16>{0x103}));
assert((nestedItems.containedChildren(0x101) == std::vector<remorse::u16>{0x102}));
assert(!nestedItems.releaseItem(0x101, noItemProcesses));
std::vector<remorse::StagedContainedFixedMapItem> 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]));
(*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;
}

View file

@ -1,844 +0,0 @@
#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 <algorithm>
#include <array>
#include <cassert>
#include <cstdint>
#include <filesystem>
int main()
{
const auto hasRetailEventEntry = [](const std::vector<remorse::u8>& body,
const std::array<remorse::u8, remorse::usecodeEventBytecodeOffset>& prefix) {
return body.size() > remorse::usecodeEventBytecodeOffset &&
std::equal(prefix.begin(), prefix.end(), body.begin()) &&
body[remorse::usecodeEventBytecodeOffset] == 0x0b;
};
const auto readDescriptorPointer = [](const std::vector<remorse::u8>& descriptors,
std::size_t chunkIndex) {
const std::size_t offset = chunkIndex * 6 + 2;
return static_cast<remorse::u32>(descriptors[offset]) |
(static_cast<remorse::u32>(descriptors[offset + 1]) << 8) |
(static_cast<remorse::u32>(descriptors[offset + 2]) << 16) |
(static_cast<remorse::u32>(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());
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');
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);
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));
remorse::UsecodeSlotChunkCache npcTriggerChunkCache(*npcTriggerClass);
const auto originalNpcTriggerDescriptors = npcTriggerChunkCache.ownerBuffers().descriptors;
std::optional<remorse::u16> 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<remorse::u16>(npcTriggerSourcePointer) &&
loadedNpcTriggerProcess->layout.savedSource.segment == static_cast<remorse::u16>(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<remorse::u32>(loadedNpcTriggerProcess->layout.chunkBuffer.offset) |
(static_cast<remorse::u32>(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));
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 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<remorse::u16>(sourceEventPointer) &&
loadedEventProcess->layout.savedSource.segment == static_cast<remorse::u16>(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<remorse::u32>(loadedEventProcess->layout.chunkBuffer.offset) |
(static_cast<remorse::u32>(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);
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);
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);
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);
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<remorse::u8>{0xaa} &&
secondSyntheticBody && secondSyntheticBody->bytes == std::vector<remorse::u8>{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;
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);
const std::array<remorse::u8, remorse::usecodeEventBytecodeOffset> 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};
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 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* 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<remorse::u16>(process->base.bytes[2] |
(static_cast<remorse::u16>(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<remorse::u16>(
teleporterProcess->base.bytes[2] | (static_cast<remorse::u16>(teleporterProcess->base.bytes[3]) << 8));
const remorse::u16 clearStasisProcessId = static_cast<remorse::u16>(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 {
remorse::ProcessKernel& kernel;
remorse::LiveFixedMapItems& items;
const std::vector<remorse::ShapeTypeInfo>& 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<TeleporterPassContext*>(opaque);
const remorse::u16 processId = static_cast<remorse::u16>(entry.bytes[2] |
(static_cast<remorse::u16>(entry.bytes[3]) << 8));
if (processId < 3) return;
const remorse::u16 vtable = static_cast<remorse::u16>(entry.bytes[0] |
(static_cast<remorse::u16>(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<remorse::TeleporterProcessEntry*>(&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(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] == 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);
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);
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<remorse::u8>(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);
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<remorse::StagedFixedMapItem> 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);
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<unsigned>(children->size());
break;
}
}
}
unsigned scriptChildren = 0;
for (const auto& item : spawnedItems.mapItems()) {
if (item.recordIndex != static_cast<std::size_t>(-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,
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);
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<remorse::u16>(index), 0));
}
assert(!interpreter->pushCodeAddress(0xffff, 0));
assert(interpreter->callFrameCount == 0x1f && interpreter->callFrames[31].offset == 0);
assert(!remorse::UsecodeInterpreterState::initialize(std::vector<remorse::u8>(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<remorse::u8, remorse::usecodeEventBytecodeOffset> cardPrefix{
0x5a, 0x00, 0x5c, 0x24, 0x00, 'C', 'A', 'R', 'D', '_', 'N', 'S', 0x00, 0x00};
assert(hasRetailEventEntry(cardUse->bytes, cardPrefix));
std::vector<remorse::u8> frame(0x80);
frame[remorse::usecodeFrameBaseOffset + 6] = 0x00;
frame[remorse::usecodeFrameBaseOffset + 7] = 0x01;
std::vector<remorse::u8> 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<remorse::u16>(
vmProcess->base.bytes[2] | (static_cast<remorse::u16>(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<remorse::u16> {
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<std::array<remorse::u16, 3>> 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<remorse::u16> {
assert(extraArgumentBytes == 0 && itemArgumentSize == 2);
spawnedUsecode = std::array<remorse::u16, 3>{classId, eventSlot, itemArgument};
auto* child = vmKernel.createUsecodeProcess(1, vmGroupCounts);
spawnedProcessId = static_cast<remorse::u16>(
child->base.bytes[2] | (static_cast<remorse::u16>(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<SwitchScheduleContext*>(context);
const remorse::u16 processId = static_cast<remorse::u16>(
process.bytes[2] | (static_cast<remorse::u16>(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<remorse::u16> {
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<remorse::u16> {
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<remorse::u16> {
const auto itemNumber = [&]() -> std::optional<remorse::u16> {
if (argumentBytes < 4) return std::nullopt;
const remorse::u16 offset = static_cast<remorse::u16>(arguments[0] |
(static_cast<remorse::u16>(arguments[1]) << 8));
const remorse::u16 segment = static_cast<remorse::u16>(arguments[2] |
(static_cast<remorse::u16>(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<remorse::u16>(arguments[0] |
(static_cast<remorse::u16>(arguments[1]) << 8));
return static_cast<remorse::u16>((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<remorse::u16>(item->data.quality & 0xff);
}
if (ordinal == 0x01 && argumentBytes == 4 && item) {
return static_cast<remorse::u16>(item->data.frame);
}
if (ordinal == 0x59 && argumentBytes == 6 && arguments[4] == 4 && item) {
return switchWorld.setItemFrame(*source, arguments[4])
? std::optional<remorse::u16>{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<remorse::u8, remorse::usecodeEventBytecodeOffset> boxPrefix{
0x5a, 0x02, 0x5c, 0xd6, 0x01, 'B', 'O', 'X', '_', 'N', 'S', 0x00, 0x00, 0x00};
assert(hasRetailEventEntry(boxUse->bytes, boxPrefix));
remorse::LiveFixedMapItems boxWorld(*stagedItems);
const auto& boxShape = (*typeFlags)[boxItem->data.shape];
const remorse::u8 boxHeight = boxShape.z == 0 && (boxShape.flags & 1) == 0
? 1 : static_cast<remorse::u8>(boxShape.z * 8);
assert(static_cast<unsigned>(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<remorse::u8>(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<remorse::u8> 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);
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<remorse::u16> {
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<remorse::u16> {
if ((ordinal == 0x15 || ordinal == 0x3a) && argumentBytes == 6) return remorse::u16{0};
if (argumentBytes < 4) return std::nullopt;
const remorse::u16 offset = static_cast<remorse::u16>(arguments[0] |
(static_cast<remorse::u16>(arguments[1]) << 8));
const remorse::u16 segment = static_cast<remorse::u16>(arguments[2] |
(static_cast<remorse::u16>(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<remorse::u8>(arguments[4] |
(static_cast<remorse::u16>(arguments[5]) << 8));
return boxWorld.setItemFrame(*itemNumber, frame)
? std::optional<remorse::u16>{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<remorse::UsecodeProcessTask> 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<remorse::u16> {
if (classId != 0x0a0c || eventSlot != 0x32 || extraArgumentBytes != 2 ||
itemArgumentSize != 0 || itemArgument != 0) return std::nullopt;
lastTimerDelay = static_cast<remorse::u16>(extraArguments[0] |
(static_cast<remorse::u16>(extraArguments[1]) << 8));
std::vector<remorse::u8> 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;
}));
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<remorse::u8> 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;
}

View file

@ -1,28 +0,0 @@
#include "remorse/file_system.h"
#include "remorse/glob_archive.h"
#include <cassert>
#include <filesystem>
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;
}

View file

@ -1,322 +0,0 @@
#include "remorse/isometric_controls.h"
#include "remorse/map_renderer.h"
#include <cassert>
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.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 == 0 && controller.request().direction == 2);
controller.handleDirectionalKey(0x48, 0, false);
assert(controller.request().animation == 0 && controller.request().direction == 2);
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));
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});
const auto east = remorse::worldPositionAtScreenOffset(originX, originY, 1.0, 0.0);
const remorse::ScreenPoint eastProjection = remorse::projectToScreen({
static_cast<remorse::s32>(east.x), static_cast<remorse::s32>(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<remorse::s32>(north.x), static_cast<remorse::s32>(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<remorse::s32>(west.x), static_cast<remorse::s32>(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<remorse::s32>(south.x), static_cast<remorse::s32>(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;
}

View file

@ -1,247 +0,0 @@
#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/shape_archive.h"
#include "remorse/type_flags.h"
#include <algorithm>
#include <cassert>
#include <filesystem>
#include <utility>
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);
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<remorse::s32>(entry.x));
minY = std::min(minY, static_cast<remorse::s32>(entry.y));
maxX = std::max(maxX, static_cast<remorse::s32>(entry.x));
maxY = std::max(maxY, static_cast<remorse::s32>(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<remorse::s32>(options.maxWidth / 2));
assert(centeredImage->sourceTop == center.y - static_cast<remorse::s32>(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 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<remorse::s32>(fixedMap->entries[shape60Item->recordIndex].x),
static_cast<remorse::s32>(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(),
[](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));
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,
&*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<remorse::s32>(
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<remorse::u16>(child->data.x + 512),
static_cast<remorse::u16>(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;
}

View file

@ -1,92 +0,0 @@
#include "remorse/detail/map_sorter.h"
#include <cassert>
#include <vector>
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<remorse::detail::RenderSortItem> items{elevated, ground};
const std::vector<std::size_t> order = remorse::detail::resolveRenderOrder(items);
assert(order.size() == 2);
assert(order[0] == 1);
assert(order[1] == 0);
remorse::detail::RenderSortItem occluder = elevated;
occluder.occludes = true;
const std::vector<remorse::detail::RenderSortItem> occludedPlayerItems{occluder, ground};
const std::vector<std::size_t> 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<remorse::detail::RenderSortItem> boundaryItems{
boundaryOccluder, boundaryPlayer};
const std::vector<std::size_t> boundaryOrder = remorse::detail::resolveRenderOrder(boundaryItems);
assert(boundaryOrder.size() == 1 && boundaryOrder[0] == 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<remorse::detail::RenderSortItem> flatItems{animatedFlat, staticFlat};
const std::vector<std::size_t> flatOrder = remorse::detail::resolveRenderOrder(flatItems);
assert(flatOrder.size() == 2);
assert(flatOrder[0] == 1);
assert(flatOrder[1] == 0);
return 0;
}

View file

@ -1,19 +0,0 @@
#include "remorse/file_system.h"
#include "remorse/palette.h"
#include <cassert>
#include <filesystem>
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;
}

View file

@ -1,34 +0,0 @@
#include "remorse/file_system.h"
#include "remorse/shape_archive.h"
#include <cassert>
#include <filesystem>
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);
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;
}
}
assert(decodedFrame);
return 0;
}

View file

@ -1,11 +0,0 @@
#include "remorse/runtime.h"
namespace {
struct TestCrashSetup {
TestCrashSetup() { remorse::installCrashDiagnostics(); }
};
TestCrashSetup testCrashSetup;
} // namespace

View file

@ -1,33 +0,0 @@
#include "remorse/file_system.h"
#include "remorse/type_flags.h"
#include <cassert>
#include <filesystem>
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);
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) {
if (info.family == 3) {
foundGlobFamily = true;
break;
}
}
assert(foundGlobFamily);
return 0;
}

View file

@ -1,225 +0,0 @@
#include "remorse/usecode_vm.h"
#include "remorse/usecode_archive.h"
#include <cassert>
#include <vector>
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<remorse::u32>(0x12345678));
assert(!emptyStack->popWord().has_value());
const std::vector<remorse::u8> itemParameter{0x34, 0x12};
const std::vector<remorse::u8> 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<remorse::u8>(0xcb), 2));
auto stackLimitState = remorse::UsecodeInterpreterState::initialize(
{}, std::vector<remorse::u8>(remorse::usecodeInterpreterStackLimit - 4), 2);
assert(stackLimitState && stackLimitState->stackTop == 5 &&
stackLimitState->contextParameterOffset == 1);
assert(!remorse::UsecodeInterpreterState::initialize(
{}, std::vector<remorse::u8>(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<remorse::u16>(frameIndex), 0x1418));
}
assert(!frameState->pushCodeAddress(31, 0x1418));
std::array<remorse::u8, remorse::usecodeContextProcessSize> 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));
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<remorse::u8>{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<remorse::u8>(contextInstance->callStackAddress.offset) &&
contextInstance->processBytes[remorse::usecodeContextInterpreterOffset + 2] ==
static_cast<remorse::u8>(contextInstance->callStackAddress.segment));
assert(contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset] == 2 &&
contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 1] == 0 &&
contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 2] ==
static_cast<remorse::u8>(contextCodeBytes->segment) &&
contextInstance->processBytes[remorse::usecodeContextCodeSourceOffset + 3] == 0);
assert(contextInstance->processBytes[remorse::usecodeContextSelfPointerOffset] ==
static_cast<remorse::u8>(contextInstance->processAddress.offset) &&
contextInstance->processBytes[remorse::usecodeContextSelfPointerOffset + 2] ==
static_cast<remorse::u8>(contextInstance->processAddress.segment));
assert(contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset] == 4 &&
contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 1] == 0 &&
contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 2] ==
static_cast<remorse::u8>(contextOwnerRows->segment) &&
contextInstance->processBytes[remorse::usecodeContextOwnerRowsOffset + 3] == 0);
assert(contextInstance->processBytes[remorse::usecodeContextOwnerSourceOffset] == 1 &&
contextInstance->processBytes[remorse::usecodeContextOwnerSourceOffset + 2] ==
static_cast<remorse::u8>(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<remorse::u8>(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<remorse::u8>(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<remorse::u8>{};
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<remorse::u8>{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<remorse::u8> 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<remorse::u8>(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<remorse::u8>(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<remorse::u16>(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<remorse::u16> {
assert(ordinal == 0x1234);
assert(argumentBytes == 2);
assert(arguments[0] == 7 && arguments[1] == 0);
return static_cast<remorse::u16>(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<remorse::u16, 2> 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<remorse::u8>(15, 0));
assert(duplicateTask.has_value());
assert(!registry.add(std::move(*duplicateTask)));
assert(registry.remove(3));
assert(registry.find(3) == nullptr);
return 0;
}

View file

@ -1,150 +0,0 @@
#!/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())