Add comprehensive tests for collision detection, entity dispatch, file system, isometric controls, map rendering, and sorting
- Implemented collision tests to verify overlap and movement logic for collision bodies. - Enhanced entity dispatch entry tests to cover initialization, group ID management, and process handling. - Expanded file system tests to include crash diagnostics and ensure proper game data root detection. - Created isometric controls tests to validate movement requests and screen projection calculations. - Added map renderer tests to check fixed map loading and rendering functionality. - Introduced map sorter tests to confirm correct rendering order for various items.
This commit is contained in:
parent
8907604b84
commit
202679f857
27 changed files with 3530 additions and 81 deletions
|
|
@ -4,7 +4,17 @@
|
|||
|
||||
This note records the current effort to turn the live Ghidra analysis and the exported C decompilation of `CRUSADER.EXE` into a source tree that can be recompiled and eventually run on Windows, including modern Windows.
|
||||
|
||||
The short version: the project now has enough decompiled coverage to start a real rebuild lane, but the exported files are still evidence, not directly compilable game source. The safest path is to keep the export as an input corpus and move cleaned, subsystem-sized slices into a separate host rebuild tree with explicit ABI and platform boundaries.
|
||||
The deliverable is a functioning modern Windows game compiled from cleaned, traceable decompiled `CRUSADER.EXE` game code. Replace DOS/Phar Lap and hardware services at their call boundaries; retain and repair the original control flow, data structures, scheduler, rendering, input semantics, and gameplay logic wherever recoverable. This is a source port, not a clean-room engine reconstruction. Modding is a later goal, not an initial acceptance criterion.
|
||||
|
||||
The exported files are evidence, not directly compilable game source. Keep them unchanged and move verified, subsystem-sized function bodies into the rebuild tree, recording each original address and any corrections to decompiler artifacts. Do not substitute a newly designed gameplay implementation for an unported function and call that function complete.
|
||||
|
||||
## Recompilation Gate
|
||||
|
||||
- Every claimed port identifies its original NE address, exported function, unresolved decompiler ambiguities, and host-only substitutions. Distinguish direct translations, behaviorally verified ports, and temporary stand-ins.
|
||||
- Compile recovered game functions into `remorse_core`; call them from the runtime path that needs them, not only from isolated tests. Tests should compare state transitions, side effects, and error paths with binary/decompiler evidence where possible.
|
||||
- Keep DOS file, memory, timing, input, video, and audio replacements behind explicit platform boundaries. Resource parsers and the current preview/window remain useful diagnostics, but are not substitutes for porting the original game loop and its callees.
|
||||
- At each milestone, count original functions translated and exercised in the Windows build, platform calls replaced, and parity checks passed. A rendered scene or a controllable stand-in actor alone does not pass a game-code milestone.
|
||||
- Do not claim whole-game recompilation until startup, game ticks, interactions, mission flow, save/load, and presentation are driven by ported game code and playable on modern Windows using the original data.
|
||||
|
||||
## Current Inputs
|
||||
|
||||
|
|
@ -35,22 +45,27 @@ Current scaffold files:
|
|||
- `rebuild/remorse/include/remorse/palette.h`: first game-data parser for 256-color RGB palette files.
|
||||
- `rebuild/remorse/include/remorse/runtime.h`: minimal runtime/export-manifest surface.
|
||||
- `rebuild/remorse/include/remorse/shape_archive.h`: typed `SHAPES.FLX` shape-frame parser and row-RLE decoder.
|
||||
- `rebuild/remorse/include/remorse/animation_archive.h`: bounds-checked raw `ANIM.DAT` lookup, direction/frame metadata, sprite-frame and flip extraction, and authored movement-step decoding.
|
||||
- `rebuild/remorse/include/remorse/collision.h`: TYPEFLAG-sized collision volumes, swept movement query, and fixed-map/GLOB solid-volume extraction.
|
||||
- `rebuild/remorse/include/remorse/type_flags.h`: typed `TYPEFLAG.DAT` shape-family and flag decoder.
|
||||
- `rebuild/remorse/src/combat_tactics.cpp`: parses tactic names, four block offsets, and bytecode payloads from `COMBAT.DAT` entries.
|
||||
- `rebuild/remorse/src/entity_dispatch_entry.cpp`: minimal host-side `EntityDispatchEntry` behavior stubs for compile-time shape and early probing.
|
||||
- `rebuild/remorse/src/collision.cpp`: builds conservative solid volumes from fixed-map records and expanded glob children, then sweeps the player footpad against them.
|
||||
- `rebuild/remorse/src/entity_dispatch_entry.cpp`: partial source translation of process lifecycle, the `11d0:0255` scan, `Process_Sleep`/`Unlink`, the 0x42-byte Stand constructor fields, `StandProcess::Run` (`1100:0359`), and a kernel-owned SystemTimer constructor/counter (`11c0:0000/00f8`). The harness executes the NPC decision tree through host services and delivers timer events explicitly; real NPC data, timer interrupts/rescheduling, keyboard lane, and complete game tick remain unported.
|
||||
- `rebuild/remorse/src/file_system.cpp`: repository/retail data-root discovery using modern `std::filesystem`.
|
||||
- `rebuild/remorse/src/flex_archive.cpp`: loader for count-at-`0x54`, table-at-`0x80` FLEX archives.
|
||||
- `rebuild/remorse/src/fixed_map.cpp`: loader for `FIXED.DAT` map tables and scaled fixed-map item coordinates.
|
||||
- `rebuild/remorse/src/glob_archive.cpp`: parser for glob object entry lists inside `GLOB.FLX`.
|
||||
- `rebuild/remorse/src/map_preview_main.cpp`: command-line preview executable for writing a viewable BMP image.
|
||||
- `rebuild/remorse/src/windowed_game_main.cpp`: native Windows game shell, with async retail map/player/collision loading, shape-1 stand/walk/run sprites, metadata-driven 8-way movement, a following camera, and a position HUD.
|
||||
- `rebuild/remorse/src/map_renderer.cpp`: combines fixed maps, glob expansion, typeflags, shape frames, and palette data into a painted preview image.
|
||||
- `rebuild/remorse/src/palette.cpp`: `GAMEPAL.PAL`-style 768-byte palette parser.
|
||||
- `rebuild/remorse/src/runtime.cpp`: loads a summary from the Ghidra export manifest.
|
||||
- `rebuild/remorse/src/shape_archive.cpp`: ports the documented Crusader frame-table and row-RLE decode rules.
|
||||
- `rebuild/remorse/src/animation_archive.cpp`: parses shape-indexed animation tables and direction-major frame metadata from raw `ANIM.DAT`.
|
||||
- `rebuild/remorse/src/type_flags.cpp`: ports the verified 9-byte Crusader typeflag decode from the map-rendering tool.
|
||||
- `rebuild/remorse/src/main.cpp`: starts the host harness and prints the export status.
|
||||
- `rebuild/remorse/tests/combat_tactics_tests.cpp`: checks `COMBAT.DAT` parses to 14 tactics and entry 0 is `Dumb`.
|
||||
- `rebuild/remorse/tests/entity_dispatch_entry_tests.cpp`: first host-side check for the confirmed `EntityDispatchEntry` offsets.
|
||||
- `rebuild/remorse/tests/entity_dispatch_entry_tests.cpp`: checks entry offsets, group counters, ID assignment, 30-slot growth, lifecycle, scheduler gates/spawn/cleanup, sleep writes, strict wake deadline, the owned Stand layout, NPC-gated `Run` branches, and timer-counter carry.
|
||||
- `rebuild/remorse/tests/file_system_tests.cpp`: first host-side check that the current repository root can be recognized as a game-data root.
|
||||
- `rebuild/remorse/tests/flex_archive_tests.cpp`: checks `STATIC/COMBAT.DAT` as a small FLEX archive with 14 populated records.
|
||||
- `rebuild/remorse/tests/fixed_map_tests.cpp`: checks `STATIC/FIXED.DAT` map count and map 0 item-record loading.
|
||||
|
|
@ -58,10 +73,12 @@ Current scaffold files:
|
|||
- `rebuild/remorse/tests/map_renderer_tests.cpp`: checks map 1 can produce a non-empty preview image.
|
||||
- `rebuild/remorse/tests/palette_tests.cpp`: checks that `STATIC/GAMEPAL.PAL` parses into 256 colors.
|
||||
- `rebuild/remorse/tests/shape_archive_tests.cpp`: checks `STATIC/SHAPES.FLX` can decode at least one visible frame.
|
||||
- `rebuild/remorse/tests/animation_archive_tests.cpp`: checks ANIM.DAT parsing, signed displacement and direction rotation, sprite-frame/flip decoding, and retail shape-1 stand/walk/run references.
|
||||
- `rebuild/remorse/tests/collision_tests.cpp`: checks TYPEFLAG extents, swept obstruction, vertical clearance, flipped footprints, and fixed-map/GLOB placement extraction.
|
||||
- `rebuild/remorse/tests/type_flags_tests.cpp`: checks `STATIC/TYPEFLAG.DAT` parses 2,048 shape records and includes glob-family records.
|
||||
- `rebuild/remorse/tools/import_export_slice.py`: stages one exported function folder into `rebuild/remorse/imported/` for manual cleanup review.
|
||||
|
||||
This is not the game yet. It is the first buildable shell that future cleaned subsystems can link into without mutating the raw Ghidra export.
|
||||
This is not the game yet. It is a buildable diagnostic host with a source-backed itemless process lifecycle, partial scheduler scan, owned Stand process layout, and recovered Stand `Run`/NPC decision and timer-counter branches. It does not have the original NPC service data, timer interrupt registration, or game loop.
|
||||
|
||||
## Why The Export Does Not Compile Yet
|
||||
|
||||
|
|
@ -87,7 +104,7 @@ It must preserve segmented pointers, far-call provenance, original-style packing
|
|||
|
||||
### Track B: Windows Source Port
|
||||
|
||||
This track uses the recovered source, object layouts, and resource formats to build a behaviorally equivalent Windows program.
|
||||
This track compiles corrected decompiled game source, retaining original behavior and object layouts while replacing only the OS/hardware-facing calls needed to run it on Windows.
|
||||
|
||||
It can replace DOS extender, VGA, sound, input, timing, file, and memory services with host implementations, but it should initially preserve exact-width data layouts and far-pointer provenance so behavior can be compared back to the original.
|
||||
|
||||
|
|
@ -95,18 +112,18 @@ For the stated goal of running on modern Windows, Track B is the practical prima
|
|||
|
||||
## Conversion Strategy
|
||||
|
||||
1. Keep `exports/src_remorse/` as generated evidence.
|
||||
2. Move one subsystem at a time into `rebuild/remorse/` as cleaned C++.
|
||||
1. Keep `exports/src_remorse/` as generated evidence; keep a function-address ledger of what was translated, what is still a stand-in, and which callers actually execute the translation.
|
||||
2. Move one original call chain at a time into `rebuild/remorse/` as minimally corrected C/C++ with a documented address mapping and tests for the observed side effects.
|
||||
3. Compile every moved slice immediately, even before it is runnable game logic.
|
||||
4. Replace Ghidra pseudo-types with `remorse::u8`, `remorse::u16`, `remorse::u32`, `remorse::FarPtr16`, and explicit packed structs.
|
||||
5. Convert Ghidra calling-convention tokens into marker macros from `compat.h` until the final host calling surface is chosen.
|
||||
6. Keep raw address provenance in comments or mapping tables for every imported function.
|
||||
7. Build host runtime shims for platform services before trying to run gameplay.
|
||||
8. Validate behavior with extracted resources and deterministic smoke tests.
|
||||
7. Implement host runtime shims at the DOS/hardware call boundaries encountered by the ported chain; avoid duplicating game logic in the shim.
|
||||
8. Validate recovered behavior with binary evidence, retail resources, and deterministic trace/state comparisons; connect each port to its caller in the Windows runtime.
|
||||
|
||||
## Full Rebuild Plan
|
||||
|
||||
The practical target is Track B first: a modern Windows source port that loads original data and reproduces gameplay behavior. Track A remains an evidence constraint for layout, calling convention, far-pointer provenance, and validation.
|
||||
The practical target is Track B: recompile recovered game logic for Windows and replace the DOS platform boundary. Track A remains an evidence constraint for layout, calling convention, far-pointer provenance, and validation. The phases below describe supporting capabilities, not permission to implement an independent game first: prioritize ported startup -> tick -> player/item process -> renderer/interaction call chains over further standalone host features.
|
||||
|
||||
### Phase 0: Build And Evidence Discipline
|
||||
|
||||
|
|
@ -117,6 +134,7 @@ Exit criteria:
|
|||
- `rebuild\remorse\build_msvc.cmd Debug` passes from the repository root
|
||||
- every imported subsystem has address/source provenance in code or docs
|
||||
- generated Ghidra exports remain input evidence, not hand-edited source
|
||||
- at least one corrected exported function is compiled, tested against its documented side effects, and invoked by a host caller; list remaining placeholder behavior explicitly
|
||||
|
||||
### Phase 1: Host Runtime Foundation
|
||||
|
||||
|
|
@ -262,7 +280,52 @@ Exit criteria: a clean checkout/build can run against a retail data directory wi
|
|||
|
||||
## Current Execution Focus
|
||||
|
||||
The current active phase is Phase 2, core resource loaders. The immediate path is `FIXED.DAT` map table and item-record loading, then glob expansion, then shape-frame decoding, then a minimal map scene smoke test.
|
||||
The current active work must shift from Phase 3 host presentation to decompiled source conversion and call-chain integration (Phases 0 and 4). Core Phase 2 loaders, the footpad-aware overlap sorter, and the Windows map window are diagnostic infrastructure. The actor uses retail stand/walk/run metadata, authored XYZ displacements, and the original 16-way direction table, but its 20 Hz host tick, conservative TYPEFLAG collision, and fixed-map boundary are not the recovered player process or original AreaSearch. Floor support, step-up/ledge handling, moving items, interactions, and USECODE remain unported. Keep the window as a test host, not as the implementation template for game logic.
|
||||
|
||||
First narrow conversion: `Remorse::EntityDispatchEntry::SetGroupId` at `11e0:02a8` (older `0008:bca8`) validates 1..31, updates the group byte at `+0x08`, and adjusts 16-bit counters through the far table pointer at `DS:39c5`. Live disassembly confirms the entry far pointer at `[BP+6]`, group byte at `[BP+0xa]`, and word-sized counter operations; the decompiler's `_group_id` alias is not a real implicit argument. The host receives the entry and table explicitly. `InitBase` at `11e0:0000` stamps the function-table words `0x3b06` (`+0x00`), `0x2d10` (`+0x1e`), `0x3afe` (`+0x28`), initializes the observed scalars, and seeds the group through `SetGroupId`. The seed comes from `DS:39c9` (written by `Kernel_11d0_19b5`); the host receives it as explicit runtime state. The unknown `+0x09` is not deliberately written. The host-owned path performs allocate -> initialize -> register, records default name/new-process metadata, executes the conditional current-process extflag branch, and applies the post-registration sync predicate. Itemless termination and slot reclamation are present. The scheduler scan applies normal-process group/flag gates and timer wake logic at `11d0:0255`, and its callback invokes the compiled `StandProcess::Run` branch for the 0x42-byte host-owned Stand entry. The `1100:026e` NPC decision gates are compiled, with their item/visibility/activity operations passed through host services. Owned Stand entries now maintain the per-item presence bit; the kernel-owned timer and keyboard constructors register their diagnostic processes. This is **not** a complete constructor or process system: stack-segment assertion, nonempty item child teardown, NPC service implementations, DOS timer/keyboard event delivery, end-of-pass work, other process `Run` functions, and far-memory behavior remain absent. `IncrementGroupId`, `SetSourceType`, and `SetEventTypeChecked` remain stand-ins; runtime binary parity is not established.
|
||||
|
||||
### Process Source-Port Ledger
|
||||
|
||||
| Exported function | Compiled status | Evidence and remaining boundary |
|
||||
|---|---|---|
|
||||
| `SetGroupId@11e0_02a8.c` (`0008:bca8`) | Partial translation; invoked from host `InitBase`, CTest transitions and invalid IDs | Live `11e0:02ae-031b`: group byte parameter at `[BP+0xa]`, far entry pointer at `[BP+6]`, 2-byte counter stride via `DS:39c5`, overwrite entire `+0x08` byte when changing group. Host exception replaces `AssertError`; counter-table ownership and runtime trace still need verification. |
|
||||
| `InitBase@11e0_0000.c` (`0008:ba00`) | Function-table/scalar/group-seed subset plus host-owned allocate/register path; harness-invoked, CTest offsets, counters, IDs | Live `11e0:0006-014e`: optional alloc `11e0:014f`, table words `0x3b06/0x2d10/0x3afe`, group from `DS:39c9`, then `SetGroupId`, `Kernel_AddProcess` (`11d0:0aff`), conditional `Kernel_GetSomeProcId_11d0_177c` branch, `Process_11d0_19cd`. Host updates extflags `+0x18 |= 4` on an addressable, unterminated current process with bit `2` set; it still omits stack-segment assertion and segmented-pointer relocation. |
|
||||
| `Kernel_GetNextFreeProcId` (`11d0:0a97`), `Kernel_11d0_0716` | First-free slot and 30-slot growth translated; registered in host harness and CTest | Live decompile scans far process-pointer slots, grows parallel pointer/size/name arrays by 30 up to 1020 entries. Host stores native pointers, sizes, and default names; the original far-address mapping is not implemented. `Process_GetProcById` (`11d0:0bf3`) treats ID 0 as null even though the raw slot allocator may choose it. |
|
||||
| `Kernel_AddProcess` (`11d0:0aff`) | Process pointer, ID, allocation-size, count, optional new-process flag/counter, default-name subset translated | Live disassembly stamps `procid` at `+0x02`, consumes `g_kernelLastProcessAllocSize`, increments count, optionally sets `ExtProc_NewlyCreated` (`0x200`), and names the slot `Default`. Host omits initialized-state assertion, far-pointer representation, and runtime parity. |
|
||||
| `Process_11d0_19cd` / `Process_11d0_19ec` | Sync-flag predicate translated on the host creation path | Live `11d0:19ef-1a07` tests kernel flag and `procid > current ID`; `11d0:19e2-19e5` ORs `0x40` into process flags at `+0x16`. The conditional `InitBase` current-process extflag branch is also translated, without runtime parity. |
|
||||
| `Kernel_TerminteProcessByPid` (`11d0:18a3`), `Process_SetTerminatedState` | Immediate and deferred termination translated for host-owned base and zero-child-state Stand entries | Live `11d0:18e5-1939`: decrement group count; if extflags `+0x18 & 4`, clear slot and free immediately; otherwise set flags `+0x16 & 8`, increment terminated count; decrement live process count in either case. Host refreshes the per-item bit after termination; child lists, special event callbacks, and teardown for non-owned entries remain unported. |
|
||||
| `Kernel_ClearProcessSomethingAndName` (`11d0:1972`), `Kernel_11d0_1dcc` | Slot pointer/size/name clear and deferred cleanup for IDs >= 3 translated; ID reuse exercised | Live cleanup scans from ID 3, requires `+0x1a == 0`, clears the slot, frees the entry, and decrements terminated count. The clear helper itself does not decrement live process count. Other scheduler cleanup paths and process destructor dispatch remain unported. |
|
||||
| `FUN_11d0_0255` (`11d0:0255`) | Normal-process scan and timer wake translated; harness callback invokes compiled Stand `Run`, tests cover sleep/wake and scheduler gates | Live `11d0:02b4-03ac`: skip terminated, process sleep via `11e0:0379`, clear `Proc_Syncing` for one pass, skip nonzero `+0x24/+0x26`, `Proc_Waiting`, and off-group entries unless daemon or group 30/31; set current ID around vtable run call. Host receives an explicit timer tick, uses the original strict `start+duration < tick` wake comparison, and recognizes Stand's verified no-op completion slot (`1100:0fe3`); other completion targets remain unsupported. Immediate timer/keyboard interrupts, early-stop/group advance/table-maintenance tails, and general vtable dispatch remain unported. |
|
||||
| `Process_Sleep` (`11e0:0320`), `EntityDispatchEntry::Unlink` (`11e0:0353`) | Flag and 32-bit timer writes/clear translated; exact byte offsets and wake deadline tested | Live sleep ORs `0x1000` at `+0x18`, snapshots timer into `+0x0a/+0x0c`, writes duration to `+0x0e/+0x10`; unlink clears the flag and those four words. Host receives a tick instead of reading the original timer-process pointer. |
|
||||
| `NPCActionProcess::Create` (`1100:0000`), `StandProcess::CreateProcess` (`1100:02ed`) | Owned 0x42-byte Stand entry registered and run in harness; constructor fields, item number, and presence-bit transitions tested | Live chain stamps `+0x16 |= 0x300`, clears derived words `+0x32..0x3e`, stores NPC number at `+0x40`, ORs `0x101` at `+0x32`, sets Stand vtable `0x1f0f`, process name `Stand`, and event `0x258`. Host marks the item bit on registration and refreshes it after terminating a zero-child-state Stand, following `Item_MarkProcessPresent`/`Item_RefreshProcessPresenceFlag` (`11d0:3e0b/3e7f`). Item animation/cache reset, nonempty child-list destruction, and real NPC item ownership remain unported. |
|
||||
| `NPC_StartBehaviorInField0x8IfCanSeeControlledNPC` (`1100:026e`), `StandProcess::Run` (`1100:0359`) | Compiled NPC decision/Stand run branches; tests cover off-screen sleep, visible behavior start, already-current sleep, and strict wake | Live `1100:0274-02e9` reads NPC number from `+0x40`, tests entirely-on-screen, nonzero field-8 activity, not-current activity `0x71`, can-see-controlled-NPC, and starts the next behavior; `1100:035c-0382` sleeps 60 on false. `1478:1f0f` starts with far `Run` pointer `1100:0359`. Host services supply visibility/activity/item effects and timer tick; no real NPC item, general vtable resolver, or binary trace parity. |
|
||||
| `SystemTimerProcess_CreateProcess` (`11c0:0000`), `Process_RegisterForTimerEvents` (`11e0:19ba`), `Kernel_RegisterProcForTimerEvents` (`11d0:2dd8`), `SystemTimerProcess_Increment` (`11c0:00f8`) | Partial 0x4a-byte owned constructor and registered counter linked to harness and Windows diagnostic scheduler; zero initialization, 16-bit carry, uniqueness, process flags, registration gate, and strict Stand wake boundary tested | Exported `ConstructVtable3AD2/3AA6` (`11e0:14fb/1814`) sets interrupt/realtime flags and zeros the periodic tail; constructor stores period `0x3c` at `+0x36`, tail bit `2` at `+0x32`, and waiting/daemon/active-counter flags. Registration sets `Proc_GetTimerEvents` (`0x400`) and records the process ID; host delivery requires both. Increment carries from `+0x40` to `+0x42`. Original randomized reschedule, event type, active-counter globals, general timer list/dispatch, DOS interrupt source, and general timer teardown remain unported. |
|
||||
| `KeyboardProcess_CreateProcess` (`11b8:02e1`), `Process_RegisterForKeyboardEvents` (`11e0:172a`), `Kernel_RegisterForKeyboardEvents` (`11d0:3b74`), `Process_SetKeyboardInterruptFlag` (`11e0:17a4`), `KeyboardProcess_HandleKeyEvent` (`11b8:03ad`) | Partial owned 0x36-byte keyboard process registered by harness and diagnostic window; layout, flags, singleton, exhaustion, teardown refusal, and accepted/rejected callback copies tested | Inherits `ConstructVtable3AD2` (`11e0:14fb`) interrupt flag `0x100`, registers `ExtProc_KeyboardEvents` (`0x80`) once, sets `Proc_Waiting|Proc_Daemon` (`0x3`) and `ExtProc_KeyboardInterrupt` (`0x100`). Live disassembly at `11b8:03c5-0418` and bytes `11b8:041a-041f` confirm filter pair `0x10,0`; a nonzero character and field `+0x08` copy 12 bytes from `g_lastKeyEvent` to the supplied event and clear tail `+0x32 & ~0x10`. Window `WM_CHAR` supplies a host-synthesized event for the diagnostic count only; original callback registry, `KeyDaemon`, event queue, modifier state, and player-input routing remain unported. |
|
||||
| `KeyDaemon_CreateProcess` (`11b8:0000`) | Partial owned 0x40-byte constructor invoked after keyboard registration in harness and window; layout, singleton, and teardown refusal tested | Inherits `ConstructVtable3AD2/3AA6` (`11e0:14fb/1814`) interrupt/realtime flags `0x300`, sets `Proc_Daemon|Proc_Waiting` (`0x3`), `Proc_ImmediateTimer` (`0x2000`), timer-event bit `0x400`, derived tail `+0x32 |= 2`, and period `0x2d` at `+0x36`. The randomized schedule, timer list dispatch, held-key repeat callback, and DOS input state are not linked. |
|
||||
|
||||
Live Ghidra MCP decompilation and disassembly have resolved local stack ABI, scheduler gates, and call order, not runtime state parity. Do not promote the Stand harness trace to gameplay behavior until its host-supplied NPC services and remaining tick services can be checked against execution.
|
||||
|
||||
## First Interactive Windows Game Shell
|
||||
|
||||
`rebuild/remorse/out/build-nmake/remorse_game.exe` is the first windowed application target. It locates the game data root from its own executable path (or the current directory), defaults to map 1, and accepts an optional fixed-map index from 0 through 255.
|
||||
|
||||
From the repository root:
|
||||
|
||||
```powershell
|
||||
rebuild\remorse\build_msvc.cmd Debug
|
||||
.\rebuild\remorse\out\build-nmake\remorse_game.exe 1
|
||||
```
|
||||
|
||||
The application builds the selected retail map scene and player assets on a worker thread, then displays a resizable Win32 window with the game palette and dependency-sorted map art. Shape 1 uses `ANIM.DAT` actions 0 (stand), 1 (walk), and 3 (unarmed run); frame metadata selects the `SHAPES.FLX` pose, horizontal flip, and movement delta. The original keypad direction mapping is supported alongside WASD/arrows and diagonal combinations. Shift and Caps Lock select walk/run using the controller's same-state rule. A 40 Hz host simulation tick advances frame steps against fixed-map and expanded-glob solid volumes; it now catches up after long paints instead of discarding all elapsed time beyond 50 ms. The retail signed displacement decoder is unchanged. The prototype's forward-only host movement step skips the small backward stride on walk frames 4 and 12 of directions 6/7/10/11, which had made both actor and following camera reverse mid-stride. This comfort policy and host tick rate are not recovered controller behavior. The persistent GDI back buffer avoids painting each moving frame directly to the window. The HUD shows map, world position, facing, and locomotion state. Collision is an axis-aligned TYPEFLAG approximation; it does not reproduce original AreaSearch shape sweeps or step-up behavior, and the fixed-map record bounds remain the outer movement limit.
|
||||
|
||||
The second HUD row is an observable, separate process-runtime diagnostic: the host 40 Hz step delivers a registered SystemTimer event, advances the recovered scheduler scan, and runs an owned Stand entry through its verified off-screen sleep branch. Tick, remaining sleep ticks, and wake count update while the window is active. Three base entries reserve the low process IDs; the Stand entry and NPC number are diagnostic fixtures, not map NPCs or the player process. Host tick frequency is not the original DOS timer interrupt rate.
|
||||
The diagnostic kernel also registers a partial KeyboardProcess and KeyDaemon at startup. Text-capable Win32 key messages exercise the recovered keyboard filter/copy callback and update the key-event count on the HUD. The daemon does not receive timer events yet. The visible WASD/keypad controls still use host polling; these processes do not yet deliver player input.
|
||||
|
||||
The walk/run modifier choice is the isolated branch from `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. Win32 supplies modifier bits; NPC state, weapon-dependent actions, original keyboard events, and the remainder of the controller selector are not ported. Retail ANIM.DAT regression checks retain the signed reverse steps in the decoder while testing the host-only forward movement filter across all four affected walk directions.
|
||||
|
||||
On Windows, `remorse_game.exe`, `remorse_rebuild.exe`, and `remorse_map_preview.exe` configure crash reports at startup. Debug CRT assertions do not open Abort/Retry/Ignore windows; the terminate handler reports active C++ exception messages to the Visual Studio Debug output and stderr when available. Escaped/unhandled Windows exceptions log their code/address and suppress the fault popup. The GUI executable has no console stderr by default, so attach a debugger to see that output. A timeout-bounded CTest child process exercises the terminate reporter without a modal prompt. This does not replace a full crash dump or catch process termination that bypasses user-mode handlers.
|
||||
|
||||
This is the first interactive gameplay slice, not yet a playable game: movement has no actor collision response, and there are no enemies, triggers, sound, saves, or USECODE execution. The rendered map is the retail static scene, not a live simulation.
|
||||
|
||||
## Import-Slice Tool
|
||||
|
||||
|
|
@ -300,13 +363,13 @@ The first Windows runtime should prefer clear host abstractions over direct Win3
|
|||
|
||||
## Recommended First Subsystems
|
||||
|
||||
The first source slices should be small enough to compile and test without the entire game loop.
|
||||
Keep source slices small enough to compile and test while following original call edges, not independently designing a replacement engine.
|
||||
|
||||
1. Compatibility/runtime layer: exact types, packed layout helpers, far-pointer wrappers, host file paths, and logging.
|
||||
2. Resource/file loading helpers from the low segments, with DOS file calls replaced by host file services.
|
||||
3. Palette and fixed-format data structures, validated against known assets.
|
||||
4. `EntityDispatchEntry` as the first class-like family because it already has a named export folder and prior class-lifting notes.
|
||||
5. Sprite/node or map rendering data structures after basic resource loading is stable.
|
||||
1. Finish the `EntityDispatchEntry`/`Process` constructor, group-table, and scheduler path, including its globals and kernel calls; `SetGroupId` alone is only a partial foothold.
|
||||
2. Trace original startup and tick entrypoints into the process/player call chain, recording each address and the exact host service boundary it reaches.
|
||||
3. Port resource/file functions actually called by that chain, mapping only DOS-facing calls to the existing host file service.
|
||||
4. Port the original item/draw-list and render functions that consume the live process state; reuse decoded retail assets as parity fixtures.
|
||||
5. Lift the input, movement, interaction, and VM calls reachable from the playable path, replacing prototype logic when original code becomes available.
|
||||
|
||||
## First Hand-Maintained Game Skeleton
|
||||
|
||||
|
|
@ -319,7 +382,7 @@ Current evidence used:
|
|||
- older note anchor recorded in the decompiler comment: `0008:ba00`
|
||||
- allocation size visible in the decompiled initializer: `0x32` bytes
|
||||
|
||||
The current rebuild skeleton preserves the 0x32-byte object size and provides host-side stubs for base init, group-id update, source/item update, and event/proc-type update. The first confirmed offsets from the exported setter bodies are: source item at `+0x04`, event/proc type at `+0x06`, and group id in the low five bits at `+0x08`. These names are still conservative because the surrounding `Process` layout is not fully lifted into typed fields yet.
|
||||
The current rebuild skeleton preserves the 0x32-byte object size, translates group-ID counter transitions, and translates the table word stamps, scalar writes, and group-seed call from base init. A host-owned path now registers and reclaims itemless entries with first-free IDs, allocation-size/name bookkeeping, and the post-registration sync predicate. Source/item update and event/proc-type update remain stand-ins. The first confirmed offsets are: source item at `+0x04`, event/proc type at `+0x06`, and group ID in the low five bits at `+0x08`. The remaining item callbacks, kernel branches, and scheduler must be lifted before the process family can drive gameplay.
|
||||
|
||||
## First Windows Runtime Shim
|
||||
|
||||
|
|
@ -458,9 +521,9 @@ Validated preview:
|
|||
- painted items in the preview crop: 178
|
||||
- full scene bounds: 30,977 x 15,617
|
||||
|
||||
This is still a smoke renderer, not the final game renderer. It uses a simple stable paint order rather than the full engine/item-sorter dependency graph, but it proves the rebuild tree can now load original resources and produce a visible world image.
|
||||
This is still a smoke renderer, not the final game renderer. It now derives world boxes from `TYPEFLAG.DAT`, resolves overlapping sprite bounds with the engine-style dependency graph, and applies the recovered `below()` ordering and occlusion rules. Runtime-only sprite sorting and specialized cases remain outside this host preview.
|
||||
|
||||
After reviewing the first preview, the chosen next direction is render correctness: port fuller item sorting, improve roof/hidden-object policy, and add better crop/navigation controls before moving to an interactive runtime.
|
||||
The next renderer work is to validate window presentation and roof/hidden-object policy, then replace the debug marker with recovered player art and process behavior.
|
||||
|
||||
## Immediate Build Loop
|
||||
|
||||
|
|
@ -470,9 +533,9 @@ Until CMake and MSVC are available in PATH, the source scaffold can be edited an
|
|||
|
||||
Current local toolchain finding:
|
||||
|
||||
- Visual Studio Community 2026 is installed at `I:\Apps\VS\18\Community`.
|
||||
- After installing the Desktop C++ workload, `vcvars64.bat`, MSVC `19.50.35729.0`, and VS-bundled CMake `4.2.3` are usable through the Visual Studio developer environment.
|
||||
- Plain `cmake` is still not available before the Visual Studio environment is initialized, so `build_msvc.cmd` uses `vswhere` and `vcvars64.bat` before invoking CMake.
|
||||
- `vswhere` selects the registered Visual Studio Community 2026 installation at `C:\Program Files\Microsoft Visual Studio\18\Community`; the existing `out/build` cache points at an older `I:\Apps\VS\18\Community` path that CMake cannot resolve as an installed instance.
|
||||
- `vcvars64.bat`, MSVC `19.51.36246.0`, and VS-bundled CMake `4.2.3` are usable through the registered Visual Studio developer environment.
|
||||
- Plain `cmake` is still not available before the Visual Studio environment is initialized. `build_msvc.cmd` initializes MSVC with `vswhere`/`vcvars64.bat` and configures a separate NMake build under `out/build-nmake`.
|
||||
|
||||
### Host Harness
|
||||
|
||||
|
|
@ -493,6 +556,8 @@ From the repository root, the repeatable MSVC path is:
|
|||
rebuild\remorse\build_msvc.cmd Debug
|
||||
```
|
||||
|
||||
The wrapper's NMake build writes `remorse_rebuild.exe` directly under `rebuild/remorse/out/build-nmake/`; it leaves the existing Visual Studio generator cache under `out/build/` untouched.
|
||||
|
||||
### Staging One Export Slice
|
||||
|
||||
From the repository root:
|
||||
|
|
@ -511,6 +576,13 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat
|
|||
- Added an import-slice tool for staging individual exported function folders without linking them yet.
|
||||
- Ran the importer on `classes/Remorse/EntityDispatchEntry`; it staged 24 files, replaced 62 calling-convention tokens, and reported `CONCAT22`, `unaff_CS`, and `unaff_SS` as cleanup signals.
|
||||
- Added the first hand-maintained `EntityDispatchEntry` source skeleton and wired it into the CMake target.
|
||||
- Translated `11e0:02a8` group-ID validation, counter transitions, and no-op on an unchanged group into the compiled skeleton; other methods still have incomplete or placeholder behavior.
|
||||
- Replaced `InitBase`'s blanket clear with live-confirmed `11e0:0000` function-table stamps, scalar assignments, and the active-group `SetGroupId` call; seeded-byte tests protect unknown bytes while the rest of the constructor remains unported.
|
||||
- Added an owned host allocate/init/register call path, porting the first-free ID, 30-slot growth, process-ID/size/count bookkeeping, and `Process_11d0_19cd` syncing predicate. The harness now registers a process (ID 0); this does not run the original scheduler.
|
||||
- Added default process-name storage, optional `ExtProc_NewlyCreated` flag/counter, immediate and deferred itemless termination, and slot cleanup/ID reuse. The harness also terminates ID 3, cleans its slot, and registers another process at ID 3; normal ID 0 lookup is a special case.
|
||||
- Ported the conditional `InitBase` current-process extflag branch and the normal-process scan gates of `11d0:0255`. Tests cover group selection, one-pass sync, creation from a run callback, and cleanup during the scan.
|
||||
- Ported the original `Process_Sleep`/`Unlink` timer writes and wake check, then executed `StandProcess::Run` under the scheduler in the diagnostic harness. It now uses an owned 0x42-byte Stand entry, compiled `1100:026e` NPC decision gates with host-supplied services, and a timer value produced by `SystemTimerProcess_Increment`. CTest checks off-screen sleep, the strict 60-tick deadline, visible behavior start, already-current activity, Stand's no-op completion slot, and timer carry. Host-owned Stand termination now refreshes the per-item bit; tests cover two processes for one item, deferred reclamation, and final immediate removal. Live Ghidra names `Item_MarkProcessPresent`/`Item_ClearProcessPresent`/`Item_RefreshProcessPresenceFlag` at `11d0:3e0b/3e44/3e7f` anchor the port.
|
||||
- Configured the Windows GUI and console executables to emit CRT and unexpected-exception details to debugger output/stderr instead of modal crash prompts. CTest resets the CRT assert mode to window mode and verifies the installer removes it, then captures a deliberately terminating child process without a popup.
|
||||
- Split the scaffold into a `remorse_core` library, host executable, and first CTest target for `EntityDispatchEntry` setters.
|
||||
- Added the first host file-system shim and CTest target for game-data root discovery.
|
||||
- Extended the host file-system shim with case-insensitive data-path resolution, parent-traversal blocking, and binary file reads.
|
||||
|
|
@ -523,9 +595,17 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat
|
|||
- Added a typed `TYPEFLAG.DAT` parser for shape family, flags, dimensions, and animation metadata.
|
||||
- Added a typed `SHAPES.FLX` parser and row-RLE decoder for renderable frame pixels.
|
||||
- Added the first visual map preview renderer and BMP output command.
|
||||
- Added `remorse_game.exe`, a native Win32 window that asynchronously loads a retail map, displays the graph-sorted scene, and supports bounded WASD/arrow movement with a following camera.
|
||||
- Added a persistent GDI back buffer and disabled background erase for the window's movement redraw path.
|
||||
- Mapped keyboard movement to screen-cardinal directions through the inverse isometric transform and added a four-direction projection regression.
|
||||
- Added a camera-centered render origin and a renderer test covering fixed-size viewport output.
|
||||
- Documented the windowed app command and clearly scoped its current debug-marker/no-collision limitations.
|
||||
- Replaced the host preview's scalar paint key with a footpad-aware dependency graph based on the local Ultima 8/Crusader sorter, including pairwise overlap, `below()` rules, and occlusion handling.
|
||||
- Added a synthetic regression proving vertical separation can override the old `x+y` order, and retained the retail-data map-render smoke test.
|
||||
- Validated `remorse_map_preview` by rendering map 1 to `rebuild/remorse/out/preview/map1-preview.bmp` from original retail data.
|
||||
- Verified the scaffold with Visual Studio Community 2026: CMake configure succeeded, MSVC build succeeded, `ctest -C Debug` passed 2/2 tests, and `remorse_rebuild.exe` ran against `exports/src_remorse/export_manifest.json`.
|
||||
- Added `build_msvc.cmd` so the working build/test/harness loop is repeatable from the repository root.
|
||||
- Added `build_msvc.cmd` so the MSVC build/test/harness loop is repeatable from the repository root; it uses an isolated NMake build tree to avoid the local CMake Visual Studio-instance resolution failure.
|
||||
- Revalidated the wrapper with MSVC `19.51.36246.0`: all C++ targets built, all 11 CTest tests passed, and the host harness loaded the export manifest and retail resource summaries.
|
||||
- Documented the current blockers between the Ghidra export and compiler-ready source.
|
||||
- Split the goal into historical reconstruction and Windows source-port tracks.
|
||||
- Chose Visual Studio Build Tools plus CMake as the first intended Windows host toolchain.
|
||||
|
|
@ -535,27 +615,29 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat
|
|||
- Keep the host scaffold building as new source slices are added.
|
||||
- Lift the confirmed `EntityDispatchEntry` byte offsets into named packed fields once the surrounding `Process` layout is stable.
|
||||
- Convert the compatibility header from placeholders into enforced layout macros with static assertions.
|
||||
- Pick the first real subsystem slice and move it into `rebuild/remorse/`.
|
||||
- Extend the translated `SetGroupId` slice to its original initializer/callers and record the ported function addresses and parity checks.
|
||||
- Expand the host file-system shim into DOS file-handle replacements and writable save/config locations.
|
||||
- Model far pointers and segmented memory in a way that can support both trace comparison and Windows execution.
|
||||
- Normalize Ghidra exported types into valid C++ names without losing address provenance.
|
||||
- Replace raw global-byte exports with typed data definitions or resource loaders.
|
||||
- Define resource fixture tests for palette, shape, map, and usecode data.
|
||||
- Replace the current preview painter's simple ordering with a fuller item-sorter dependency graph.
|
||||
- Decide whether the first interactive window should use SDL, raw Win32/GDI, or another host layer.
|
||||
- Decide the graphics/input/audio platform layer for the Windows runtime.
|
||||
- Add explicit crop/navigation controls and tests for bounded map previews.
|
||||
- Validate roof/hidden-object rendering policy against selected retail scenes.
|
||||
- Keep the current Win32/GDI window as a diagnostic host while lifting the original player/process loop; choose other platform layers only as original DOS/hardware boundaries require them.
|
||||
- Replace the windowed prototype movement/collision with ported player and AreaSearch behavior, using retail art and the existing renderer for presentation.
|
||||
- Connect triggers and object interaction to the USECODE runtime after its value/context model is lifted.
|
||||
- Add CI-style smoke tests once the host toolchain and first resource loader compile reliably.
|
||||
|
||||
## Near-Term Next Actions
|
||||
|
||||
1. Open a Developer PowerShell with MSVC and CMake available, then run the CMake scaffold build.
|
||||
2. Replace the current `EntityDispatchEntry` byte-array fields with named packed fields as evidence allows.
|
||||
3. Add a small host-side test for the confirmed `+0x04`, `+0x06`, and `+0x08` setters once the MSVC/CMake toolchain is available.
|
||||
4. Map the first old DOS file functions onto the new host file-system shim.
|
||||
5. Add writable save/config path handling.
|
||||
6. Add layout assertions for the first recovered packed structs.
|
||||
7. Start a render/runtime decision note once the first resource smoke test passes.
|
||||
1. Verify the live `Process` group-table allocation/initialization and the active-group writer `11d0:19b5`; compare `11e0:02a8` side effects with an execution trace (including counter ownership and error paths).
|
||||
2. Complete `InitBase` (`11e0:0000`) and the kernel lifecycle by resolving the segment assertion, conditional kernel branch, item-linked teardown, process destructor dispatch and far-pointer storage; compare the host registry to real process snapshots.
|
||||
3. Trace `Init_Everything` -> `FUN_11d0_0255` -> the player process and additional vtable `Run` targets; verify Stand's ported presence-bit lifecycle against original snapshots, then port animation-cache and nonempty-child teardown against real NPC state.
|
||||
4. Port the real timer process and NPC service implementations, then scheduler keyboard, active-group advancement, remaining sleep-completion dispatch and table-maintenance tails; compare deterministic process-order/state traces before connecting the Windows window.
|
||||
5. Replace DOS file and memory APIs encountered by the ported chain with narrow host adapters; validate far-pointer/layout conversions against live evidence.
|
||||
6. Port original movement and AreaSearch/collision behavior before promoting the host actor movement from stand-in to gameplay code.
|
||||
7. Feed original item/draw-list output into the existing renderer, then lift USECODE dispatch, save/load, audio, and frontend chains as required for playable mission progression.
|
||||
|
||||
## Current Bottom Line
|
||||
|
||||
The project is now at the start of the recompilation lane: there is a buildable host target scaffold, a compatibility surface, and a documented path for importing cleaned decompiler output. The major remaining work is systematic conversion, platform replacement, and behavior validation, not another bulk export.
|
||||
The project has a buildable diagnostic host, retail resource loaders, a tested process lifecycle for host-owned base and zero-child-state Stand entries, a partial original scheduler scan, and an owned 0x42-byte Stand entry executing recovered NPC-decision and `Run` branches against a source-backed timer counter (`StandProcess Run sleep ticks: 60`, three other host callbacks). Creation and termination update the per-item presence bit, but this is **not** a game milestone: real NPC item ownership, nonempty-child teardown, visibility/activity service implementations, timer-process construction and interrupts, the complete tick, startup, player, renderer, and interaction chains remain unported; `remorse_game.exe` is not connected to this registry. The next measure of progress is a real item-linked Stand/NPC instance running on the original call chain with state trace parity.
|
||||
|
|
|
|||
63
docs/scummvm-crusader-movement-tap-turn.md
Normal file
63
docs/scummvm-crusader-movement-tap-turn.md
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
# ScummVM Crusader Movement Tap-Turn Fix
|
||||
|
||||
This note records the ScummVM-side movement fix for Crusader: No Remorse tap-turning while running.
|
||||
|
||||
## Problem
|
||||
|
||||
In ScummVM's Crusader implementation, quickly tapping left or right while holding run/forward could fail to rotate the Silencer. The code already had a pending-turn path for short key taps, but it only applied that path while the last animation was `run`, `combatRunSmallWeapon`, or `walk`.
|
||||
|
||||
That left out the start-run animations and the large-weapon combat-run animation. If a left/right tap arrived while the actor was still in `startRun`, `startRunSmallWeapon`, `startRunLargeWeapon`, or `combatRunLargeWeapon`, the pending turn could be cleared before it was applied.
|
||||
|
||||
## Decompiled Source Evidence
|
||||
|
||||
The exported Ghidra decompilation for retail `CRUSADER.EXE` shows the original controller treats more than plain run/walk as direction-adjustable movement.
|
||||
|
||||
Evidence files:
|
||||
|
||||
- `exports/src_remorse/functions/segments/seg_1130/Controller_PickNextAnimByKeyevent@1130_12d6.c`
|
||||
- `exports/src_remorse/functions/segments/seg_1130/Controller_UpdateAvatarAngle@1130_10cf.c`
|
||||
- `exports/src_remorse/functions/segments/seg_1130/Anim_1130_0f94@1130_0f94.c`
|
||||
|
||||
Relevant behavior:
|
||||
|
||||
- Left and right key events use the `0x11` / `0x12` temporary direction markers, then convert them into one direction step right or left according to the target animation's 8-dir or 16-dir mode.
|
||||
- If the controlled NPC is busy, `Controller_PickNextAnimByKeyevent` still allows a keydown turn to update the active animation direction when `Anim_1130_0f94` says the current animation supports direction updates.
|
||||
- `Anim_1130_0f94` includes `Anim_Walk`, `Anim_Run`, `Anim_StartRunning`, `Anim_CombatRun_SmallWpn`, `Anim_CombatRun_LargeWpn`, `Anim_StartRun_SmallWpn`, and `Anim_StartRun_LargeWpn` in that supported set.
|
||||
|
||||
So the original behavior does not limit tap-turn handling to only the settled run/walk loops. It also accepts direction changes during run startup and combat-run variants.
|
||||
|
||||
## ScummVM Change
|
||||
|
||||
Updated ScummVM file:
|
||||
|
||||
- `engines/ultima/ultima8/world/actors/cru_avatar_mover_process.cpp`
|
||||
|
||||
The `_isAnimRunningWalking` helper now returns true for:
|
||||
|
||||
- `Animation::run`
|
||||
- `Animation::startRun`
|
||||
- `Animation::combatRunSmallWeapon`
|
||||
- `Animation::combatRunLargeWeapon`
|
||||
- `Animation::startRunSmallWeapon`
|
||||
- `Animation::startRunLargeWeapon`
|
||||
- `Animation::walk`
|
||||
|
||||
This keeps the existing ScummVM pending-turn design, but widens the eligible animation window to match the original controller's supported movement animations. A quick left/right tap while run-forward is active can now be consumed during run startup or either combat-run variant instead of being discarded.
|
||||
|
||||
## Validation
|
||||
|
||||
Static validation performed:
|
||||
|
||||
- Confirmed the changed symbols already exist in ScummVM's Crusader animation enum.
|
||||
- Confirmed the ScummVM change is limited to the Crusader mover helper that gates pending turn application.
|
||||
|
||||
Runtime validation still needed:
|
||||
|
||||
- Build ScummVM with the Ultima engine enabled.
|
||||
- Start Crusader: No Remorse.
|
||||
- Hold run plus forward, tap left/right during run startup and while fully running, and confirm the Silencer rotates one direction step without releasing run/forward.
|
||||
- Repeat with weapon-ready combat run when possible, including a large weapon if available.
|
||||
|
||||
## Notes
|
||||
|
||||
The live Ghidra MCP bridge was not reachable during this pass, so the evidence above comes from the checked-out exported Ghidra decompilation under `exports/src_remorse/` rather than a fresh live decompile.
|
||||
|
|
@ -3,13 +3,16 @@ cmake_minimum_required(VERSION 3.20)
|
|||
project(remorse_rebuild LANGUAGES CXX)
|
||||
|
||||
add_library(remorse_core
|
||||
src/animation_archive.cpp
|
||||
src/combat_tactics.cpp
|
||||
src/collision.cpp
|
||||
src/entity_dispatch_entry.cpp
|
||||
src/file_system.cpp
|
||||
src/flex_archive.cpp
|
||||
src/fixed_map.cpp
|
||||
src/glob_archive.cpp
|
||||
src/map_renderer.cpp
|
||||
src/map_sorter.cpp
|
||||
src/palette.cpp
|
||||
src/runtime.cpp
|
||||
src/shape_archive.cpp
|
||||
|
|
@ -31,6 +34,13 @@ add_executable(remorse_map_preview
|
|||
|
||||
target_link_libraries(remorse_map_preview PRIVATE remorse_core)
|
||||
|
||||
if(WIN32)
|
||||
add_executable(remorse_game WIN32
|
||||
src/windowed_game_main.cpp
|
||||
)
|
||||
target_link_libraries(remorse_game PRIVATE remorse_core user32 gdi32)
|
||||
endif()
|
||||
|
||||
enable_testing()
|
||||
|
||||
add_executable(entity_dispatch_entry_tests
|
||||
|
|
@ -105,6 +115,38 @@ target_link_libraries(map_renderer_tests PRIVATE remorse_core)
|
|||
|
||||
add_test(NAME map_renderer_tests COMMAND map_renderer_tests)
|
||||
|
||||
add_executable(map_sorter_tests
|
||||
tests/map_sorter_tests.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(map_sorter_tests PRIVATE remorse_core)
|
||||
|
||||
add_test(NAME map_sorter_tests COMMAND map_sorter_tests)
|
||||
|
||||
add_executable(isometric_controls_tests
|
||||
tests/isometric_controls_tests.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(isometric_controls_tests PRIVATE remorse_core)
|
||||
|
||||
add_test(NAME isometric_controls_tests COMMAND isometric_controls_tests)
|
||||
|
||||
add_executable(animation_archive_tests
|
||||
tests/animation_archive_tests.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(animation_archive_tests PRIVATE remorse_core)
|
||||
|
||||
add_test(NAME animation_archive_tests COMMAND animation_archive_tests)
|
||||
|
||||
add_executable(collision_tests
|
||||
tests/collision_tests.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(collision_tests PRIVATE remorse_core)
|
||||
|
||||
add_test(NAME collision_tests COMMAND collision_tests)
|
||||
|
||||
add_executable(combat_tactics_tests
|
||||
tests/combat_tactics_tests.cpp
|
||||
)
|
||||
|
|
@ -117,7 +159,14 @@ if(MSVC)
|
|||
target_compile_options(remorse_core PRIVATE /W4 /permissive-)
|
||||
target_compile_options(combat_tactics_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(map_renderer_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(map_sorter_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(isometric_controls_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(animation_archive_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(collision_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(remorse_map_preview PRIVATE /W4 /permissive-)
|
||||
if(WIN32)
|
||||
target_compile_options(remorse_game PRIVATE /W4 /permissive-)
|
||||
endif()
|
||||
target_compile_options(remorse_rebuild PRIVATE /W4 /permissive-)
|
||||
target_compile_options(entity_dispatch_entry_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(file_system_tests PRIVATE /W4 /permissive-)
|
||||
|
|
@ -131,7 +180,14 @@ else()
|
|||
target_compile_options(remorse_core PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(combat_tactics_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(map_renderer_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(map_sorter_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(isometric_controls_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(animation_archive_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(collision_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(remorse_map_preview PRIVATE -Wall -Wextra -Wpedantic)
|
||||
if(WIN32)
|
||||
target_compile_options(remorse_game PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
target_compile_options(remorse_rebuild PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(entity_dispatch_entry_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(file_system_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
|
|
|
|||
|
|
@ -30,11 +30,12 @@ call "%VCVARS%" || exit /b 2
|
|||
|
||||
cd /d "%REPO_ROOT%" || exit /b 2
|
||||
|
||||
cmake -S rebuild/remorse -B rebuild/remorse/out/build || exit /b 1
|
||||
cmake --build rebuild/remorse/out/build --config "%CONFIG%" || exit /b 1
|
||||
ctest --test-dir rebuild/remorse/out/build -C "%CONFIG%" --output-on-failure || exit /b 1
|
||||
set "BUILD_DIR=rebuild/remorse/out/build-nmake"
|
||||
cmake -S rebuild/remorse -B "%BUILD_DIR%" -G "NMake Makefiles" -DCMAKE_BUILD_TYPE="%CONFIG%" || exit /b 1
|
||||
cmake --build "%BUILD_DIR%" || exit /b 1
|
||||
ctest --test-dir "%BUILD_DIR%" --output-on-failure || exit /b 1
|
||||
|
||||
set "EXE=rebuild\remorse\out\build\%CONFIG%\remorse_rebuild.exe"
|
||||
set "EXE=%BUILD_DIR%\remorse_rebuild.exe"
|
||||
if not exist "%EXE%" (
|
||||
echo Built executable was not found at "%EXE%".
|
||||
exit /b 1
|
||||
|
|
|
|||
47
rebuild/remorse/include/remorse/animation_archive.h
Normal file
47
rebuild/remorse/include/remorse/animation_archive.h
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
#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;
|
||||
std::optional<AnimationDisplacement> decodeAnimationDisplacement(
|
||||
const AnimationFrameMetadata& metadata,
|
||||
u8 direction,
|
||||
bool rotateDirection);
|
||||
|
||||
} // namespace remorse
|
||||
30
rebuild/remorse/include/remorse/collision.h
Normal file
30
rebuild/remorse/include/remorse/collision.h
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
#pragma once
|
||||
|
||||
#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;
|
||||
};
|
||||
|
||||
CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped = false);
|
||||
bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right);
|
||||
bool canMoveCollisionBody(
|
||||
const CollisionBody& body,
|
||||
WorldPoint destination,
|
||||
const std::vector<CollisionBody>& obstacles);
|
||||
std::vector<CollisionBody> collectMapCollisionBodies(
|
||||
const FixedMap& map,
|
||||
const std::vector<ShapeTypeInfo>& shapeTypes,
|
||||
const std::vector<GlobObject>& globObjects);
|
||||
|
||||
} // namespace remorse
|
||||
46
rebuild/remorse/include/remorse/detail/map_sorter.h
Normal file
46
rebuild/remorse/include/remorse/detail/map_sorter.h
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
#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 sprite = false;
|
||||
bool inventoryItem = false;
|
||||
};
|
||||
|
||||
std::vector<std::size_t> resolveRenderOrder(const std::vector<RenderSortItem>& items);
|
||||
|
||||
} // namespace detail
|
||||
} // namespace remorse
|
||||
|
|
@ -2,6 +2,10 @@
|
|||
|
||||
#include "remorse/compat.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
namespace remorse {
|
||||
|
||||
CR_PACK_PUSH_1
|
||||
|
|
@ -9,23 +13,139 @@ struct EntityDispatchEntryBase {
|
|||
u8 bytes[0x32];
|
||||
} CR_PACKED;
|
||||
|
||||
struct StandProcessEntry {
|
||||
EntityDispatchEntryBase base;
|
||||
u8 extra[0x10];
|
||||
} CR_PACKED;
|
||||
|
||||
struct SystemTimerProcessEntry {
|
||||
EntityDispatchEntryBase base;
|
||||
u8 extra[0x18];
|
||||
} CR_PACKED;
|
||||
|
||||
struct KeyboardProcessEntry {
|
||||
EntityDispatchEntryBase base;
|
||||
u8 extra[0x04];
|
||||
} CR_PACKED;
|
||||
|
||||
struct KeyDaemonProcessEntry {
|
||||
EntityDispatchEntryBase base;
|
||||
u8 extra[0x0e];
|
||||
} CR_PACKED;
|
||||
|
||||
struct KeyEvent {
|
||||
u8 character;
|
||||
u8 scanCode;
|
||||
u16 modifiers;
|
||||
u16 field4;
|
||||
u16 field6;
|
||||
u8 field8;
|
||||
u8 field9;
|
||||
u16 fieldA;
|
||||
} CR_PACKED;
|
||||
|
||||
struct EntityDispatchEntryRuntimeState {
|
||||
u8 bytes[0x18];
|
||||
} CR_PACKED;
|
||||
CR_PACK_POP
|
||||
|
||||
static_assert(sizeof(EntityDispatchEntryBase) == 0x32, "EntityDispatchEntryBase size must match allocation evidence");
|
||||
static_assert(sizeof(StandProcessEntry) == 0x42, "StandProcessEntry size must match allocation evidence");
|
||||
static_assert(sizeof(SystemTimerProcessEntry) == 0x4a, "SystemTimerProcessEntry size must match allocation evidence");
|
||||
static_assert(sizeof(KeyboardProcessEntry) == 0x36, "KeyboardProcessEntry size must match allocation evidence");
|
||||
static_assert(sizeof(KeyDaemonProcessEntry) == 0x40, "KeyDaemonProcessEntry size must match allocation evidence");
|
||||
static_assert(sizeof(KeyEvent) == 0x0c, "KeyEvent size must match keyboard event copy");
|
||||
|
||||
struct NpcBehaviorServices {
|
||||
bool (*isEntirelyOnScreen)(u16 npcNumber, void* context);
|
||||
u16 (*getActivity)(u16 npcNumber, void* context);
|
||||
bool (*isCurrentActivitySpecifiedBy)(u16 npcNumber, u16 activity, void* context);
|
||||
bool (*canSeeControlledNPC)(u16 npcNumber, void* context);
|
||||
void (*startNextBehavior)(u16 npcNumber, u16 activity, void* context);
|
||||
void* context;
|
||||
};
|
||||
|
||||
class ProcessKernel {
|
||||
public:
|
||||
EntityDispatchEntryBase* createProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
StandProcessEntry* createStandProcess(u8 activeGroup, u16 npcNumber, u16 (&groupCounts)[32]);
|
||||
SystemTimerProcessEntry* createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
KeyboardProcessEntry* createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
KeyDaemonProcessEntry* createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
void deliverSystemTimerEvent();
|
||||
u32 systemTimerTick() const;
|
||||
void setSyncContext(bool enabled, u16 currentProcessId);
|
||||
void setMarkNewProcesses(bool enabled);
|
||||
void setLastAllocationSize(u16 size);
|
||||
u16 addProcess(EntityDispatchEntryBase& entry);
|
||||
void clearProcessSlot(u16 id);
|
||||
void terminateProcess(u16 id, u16 (&groupCounts)[32]);
|
||||
void clearTerminatedProcesses();
|
||||
void scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, u32 timerTick = 0);
|
||||
EntityDispatchEntryBase* processAt(u16 id) const;
|
||||
u16 allocationSizeAt(u16 id) const;
|
||||
const char* processNameAt(u16 id) const;
|
||||
bool itemHasProcess(u16 itemNumber) const;
|
||||
u16 processCount() const;
|
||||
u16 terminatedProcessCount() const;
|
||||
u16 newlyCreatedCount() const;
|
||||
std::size_t capacity() const;
|
||||
|
||||
private:
|
||||
void releaseOwnedProcess(u16 id);
|
||||
std::vector<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::unique_ptr<SystemTimerProcessEntry> systemTimerProcess_;
|
||||
std::unique_ptr<KeyboardProcessEntry> keyboardProcess_;
|
||||
std::unique_ptr<KeyDaemonProcessEntry> keyDaemonProcess_;
|
||||
u16 systemTimerProcessId_ = 0xffff;
|
||||
std::vector<u8> itemProcessPresence_;
|
||||
u16 lastAllocationSize_ = 0;
|
||||
u16 processCount_ = 0;
|
||||
u16 terminatedProcessCount_ = 0;
|
||||
u16 newlyCreatedCount_ = 0;
|
||||
u16 currentProcessId_ = 0;
|
||||
bool syncEnabled_ = false;
|
||||
bool markNewProcesses_ = false;
|
||||
};
|
||||
|
||||
class EntityDispatchEntry {
|
||||
public:
|
||||
static constexpr u16 initBaseSegment = 0x11e0;
|
||||
static constexpr u16 initBaseOffset = 0x0000;
|
||||
|
||||
static EntityDispatchEntryBase* initBase(EntityDispatchEntryBase* entry);
|
||||
static void setGroupId(EntityDispatchEntryBase& entry, u8 groupId);
|
||||
static EntityDispatchEntryBase* initBase(EntityDispatchEntryBase* entry, u8 activeGroup, u16 (&groupCounts)[32]);
|
||||
static void setGroupId(EntityDispatchEntryBase& entry, u8 groupId, u16 (&groupCounts)[32]);
|
||||
static void incrementGroupId(EntityDispatchEntryBase& entry);
|
||||
static void setSourceType(EntityDispatchEntryBase& entry, u16 sourceType);
|
||||
static void setEventTypeChecked(EntityDispatchEntryBase& entry, u16 eventType);
|
||||
static void sleep(EntityDispatchEntryBase& entry, u32 timerTick, u32 duration);
|
||||
static void unlinkSleep(EntityDispatchEntryBase& entry);
|
||||
};
|
||||
|
||||
class StandProcess {
|
||||
public:
|
||||
static constexpr u16 runOffset = 0x0359;
|
||||
static constexpr u16 vtableOffset = 0x1f0f;
|
||||
|
||||
static void run(EntityDispatchEntryBase& entry, bool (*startBehavior)(const EntityDispatchEntryBase&, void*),
|
||||
void* context, u32 timerTick);
|
||||
static void run(StandProcessEntry& entry, const NpcBehaviorServices& services, u32 timerTick);
|
||||
};
|
||||
|
||||
class SystemTimerProcess {
|
||||
public:
|
||||
static u32 tick(const SystemTimerProcessEntry& entry);
|
||||
static void increment(SystemTimerProcessEntry& entry);
|
||||
};
|
||||
|
||||
class KeyboardProcess {
|
||||
public:
|
||||
static bool handleKeyEvent(KeyboardProcessEntry& process, u16 selector, u16 filter,
|
||||
KeyEvent& event, const KeyEvent& lastEvent);
|
||||
};
|
||||
|
||||
} // namespace remorse
|
||||
|
|
|
|||
42
rebuild/remorse/include/remorse/isometric_controls.h
Normal file
42
rebuild/remorse/include/remorse/isometric_controls.h
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
#pragma once
|
||||
|
||||
#include "remorse/animation_archive.h"
|
||||
#include "remorse/compat.h"
|
||||
|
||||
namespace remorse {
|
||||
|
||||
struct WorldPositionD {
|
||||
double x = 0.0;
|
||||
double y = 0.0;
|
||||
};
|
||||
|
||||
inline bool controllerWalkRequested(u16 modifiers)
|
||||
{
|
||||
const bool shiftDown = (modifiers & 0x03) != 0;
|
||||
const bool capsLockOn = (modifiers & 0x40) != 0;
|
||||
return shiftDown == capsLockOn;
|
||||
}
|
||||
|
||||
inline std::optional<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
|
||||
|
|
@ -17,6 +17,17 @@ struct WorldRect {
|
|||
s32 maxY = 0;
|
||||
};
|
||||
|
||||
struct WorldPoint {
|
||||
s32 x = 0;
|
||||
s32 y = 0;
|
||||
s32 z = 0;
|
||||
};
|
||||
|
||||
struct ScreenPoint {
|
||||
s32 x = 0;
|
||||
s32 y = 0;
|
||||
};
|
||||
|
||||
struct MapRenderOptions {
|
||||
u32 mapIndex = 1;
|
||||
u32 maxWidth = 1600;
|
||||
|
|
@ -24,6 +35,7 @@ struct MapRenderOptions {
|
|||
bool expandGlobs = true;
|
||||
bool includeRoofs = false;
|
||||
bool includeHiddenMarkers = false;
|
||||
std::optional<WorldPoint> viewCenter;
|
||||
std::optional<WorldRect> worldRect;
|
||||
};
|
||||
|
||||
|
|
@ -42,6 +54,7 @@ struct RenderedMapImage {
|
|||
};
|
||||
|
||||
std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options);
|
||||
ScreenPoint projectToScreen(const WorldPoint& point);
|
||||
bool writeBmp24(const std::filesystem::path& path, const RenderedMapImage& image);
|
||||
|
||||
} // namespace remorse
|
||||
|
|
|
|||
|
|
@ -20,5 +20,6 @@ struct ExportManifestSummary {
|
|||
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
|
||||
|
|
|
|||
135
rebuild/remorse/src/animation_archive.cpp
Normal file
135
rebuild/remorse/src/animation_archive.cpp
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
#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;
|
||||
}
|
||||
|
||||
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
|
||||
156
rebuild/remorse/src/collision.cpp
Normal file
156
rebuild/remorse/src/collision.cpp
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
#include "remorse/collision.h"
|
||||
|
||||
#include <algorithm>
|
||||
#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
|
||||
|
||||
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};
|
||||
}
|
||||
|
||||
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
|
||||
|
|
@ -1,5 +1,9 @@
|
|||
#include "remorse/entity_dispatch_entry.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace remorse {
|
||||
|
||||
namespace {
|
||||
|
|
@ -12,23 +16,437 @@ void writeLe16(EntityDispatchEntryBase& entry, u16 offset, u16 value)
|
|||
entry.bytes[offset] = static_cast<u8>(value & 0xff);
|
||||
entry.bytes[offset + 1] = static_cast<u8>(value >> 8);
|
||||
}
|
||||
|
||||
u16 readLe16(const EntityDispatchEntryBase& entry, u16 offset)
|
||||
{
|
||||
return static_cast<u16>(entry.bytes[offset] | (static_cast<u16>(entry.bytes[offset + 1]) << 8));
|
||||
}
|
||||
|
||||
EntityDispatchEntryBase* EntityDispatchEntry::initBase(EntityDispatchEntryBase* entry)
|
||||
void clearBytes(EntityDispatchEntryBase& entry, u16 begin, u16 end)
|
||||
{
|
||||
for (u16 offset = begin; offset < end; ++offset) {
|
||||
entry.bytes[offset] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EntityDispatchEntryBase* ProcessKernel::createProcess(u8 activeGroup, u16 (&groupCounts)[32])
|
||||
{
|
||||
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
throw std::overflow_error("process table exhausted");
|
||||
}
|
||||
if (std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
processes_.reserve(processes_.size() + 30);
|
||||
allocationSizes_.reserve(allocationSizes_.size() + 30);
|
||||
processNames_.reserve(processNames_.size() + 30);
|
||||
}
|
||||
ownedProcesses_.reserve(ownedProcesses_.size() + 1);
|
||||
auto entry = std::make_unique<EntityDispatchEntryBase>();
|
||||
EntityDispatchEntry::initBase(entry.get(), activeGroup, groupCounts);
|
||||
setLastAllocationSize(sizeof(EntityDispatchEntryBase));
|
||||
const u16 id = addProcess(*entry);
|
||||
if (syncEnabled_) {
|
||||
EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_);
|
||||
if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) {
|
||||
current->bytes[0x18] |= 0x04;
|
||||
}
|
||||
if (id > currentProcessId_) {
|
||||
entry->bytes[0x16] |= 0x40;
|
||||
}
|
||||
}
|
||||
EntityDispatchEntryBase* result = entry.get();
|
||||
ownedProcesses_.push_back(std::move(entry));
|
||||
return result;
|
||||
}
|
||||
|
||||
StandProcessEntry* ProcessKernel::createStandProcess(u8 activeGroup, u16 npcNumber, u16 (&groupCounts)[32])
|
||||
{
|
||||
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
throw std::overflow_error("process table exhausted");
|
||||
}
|
||||
if (std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
processes_.reserve(processes_.size() + 30);
|
||||
allocationSizes_.reserve(allocationSizes_.size() + 30);
|
||||
processNames_.reserve(processNames_.size() + 30);
|
||||
}
|
||||
ownedStandProcesses_.reserve(ownedStandProcesses_.size() + 1);
|
||||
auto process = std::make_unique<StandProcessEntry>();
|
||||
EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts);
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x300));
|
||||
writeLe16(process->base, 0x04, npcNumber);
|
||||
writeLe16(process->base, 0x06, 0x258);
|
||||
writeLe16(process->base, 0x00, StandProcess::vtableOffset);
|
||||
process->extra[0x00] |= 0x01;
|
||||
process->extra[0x01] |= 0x01;
|
||||
process->extra[0x0e] = static_cast<u8>(npcNumber);
|
||||
process->extra[0x0f] = static_cast<u8>(npcNumber >> 8);
|
||||
setLastAllocationSize(sizeof(StandProcessEntry));
|
||||
const u16 id = addProcess(process->base);
|
||||
processNames_[id] = "Stand";
|
||||
if (syncEnabled_) {
|
||||
EntityDispatchEntryBase* current = currentProcessId_ == 0 ? nullptr : processAt(currentProcessId_);
|
||||
if (current != nullptr && (current->bytes[0x16] & 0x08) == 0 && (current->bytes[0x18] & 0x02) != 0) {
|
||||
current->bytes[0x18] |= 0x04;
|
||||
}
|
||||
if (id > currentProcessId_) {
|
||||
process->base.bytes[0x16] |= 0x40;
|
||||
}
|
||||
}
|
||||
StandProcessEntry* result = process.get();
|
||||
ownedStandProcesses_.push_back(std::move(process));
|
||||
const std::size_t itemByte = npcNumber >> 3;
|
||||
if (itemProcessPresence_.size() <= itemByte) {
|
||||
itemProcessPresence_.resize(itemByte + 1, 0);
|
||||
}
|
||||
itemProcessPresence_[itemByte] |= static_cast<u8>(1u << (npcNumber & 7));
|
||||
return result;
|
||||
}
|
||||
|
||||
SystemTimerProcessEntry* ProcessKernel::createSystemTimerProcess(u8 activeGroup, u16 (&groupCounts)[32])
|
||||
{
|
||||
if (systemTimerProcess_ != nullptr) {
|
||||
throw std::logic_error("system timer process already exists");
|
||||
}
|
||||
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
throw std::overflow_error("process table exhausted");
|
||||
}
|
||||
auto process = std::make_unique<SystemTimerProcessEntry>();
|
||||
EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts);
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x300));
|
||||
process->extra[0] = 0x02;
|
||||
process->extra[4] = 0x3c;
|
||||
setLastAllocationSize(sizeof(SystemTimerProcessEntry));
|
||||
const u16 id = addProcess(process->base);
|
||||
processNames_[id] = "SystemTimer";
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x2403));
|
||||
systemTimerProcessId_ = id;
|
||||
systemTimerProcess_ = std::move(process);
|
||||
return systemTimerProcess_.get();
|
||||
}
|
||||
|
||||
KeyboardProcessEntry* ProcessKernel::createKeyboardProcess(u8 activeGroup, u16 (&groupCounts)[32])
|
||||
{
|
||||
if (keyboardProcess_ != nullptr) {
|
||||
throw std::logic_error("keyboard process already exists");
|
||||
}
|
||||
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
throw std::overflow_error("process table exhausted");
|
||||
}
|
||||
auto process = std::make_unique<KeyboardProcessEntry>();
|
||||
EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts);
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x103));
|
||||
setLastAllocationSize(sizeof(KeyboardProcessEntry));
|
||||
const u16 id = addProcess(process->base);
|
||||
processNames_[id] = "KeyboardProcess";
|
||||
writeLe16(process->base, 0x18, static_cast<u16>(readLe16(process->base, 0x18) | 0x180));
|
||||
keyboardProcess_ = std::move(process);
|
||||
return keyboardProcess_.get();
|
||||
}
|
||||
|
||||
KeyDaemonProcessEntry* ProcessKernel::createKeyDaemonProcess(u8 activeGroup, u16 (&groupCounts)[32])
|
||||
{
|
||||
if (keyDaemonProcess_ != nullptr) {
|
||||
throw std::logic_error("key daemon process already exists");
|
||||
}
|
||||
if (processes_.size() == 1020 && std::find(processes_.begin(), processes_.end(), nullptr) == processes_.end()) {
|
||||
throw std::overflow_error("process table exhausted");
|
||||
}
|
||||
auto process = std::make_unique<KeyDaemonProcessEntry>();
|
||||
EntityDispatchEntry::initBase(&process->base, activeGroup, groupCounts);
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x300));
|
||||
process->extra[0] = 0x02;
|
||||
process->extra[4] = 0x2d;
|
||||
setLastAllocationSize(sizeof(KeyDaemonProcessEntry));
|
||||
const u16 id = addProcess(process->base);
|
||||
processNames_[id] = "KeyDaemon";
|
||||
writeLe16(process->base, 0x16, static_cast<u16>(readLe16(process->base, 0x16) | 0x2403));
|
||||
keyDaemonProcess_ = std::move(process);
|
||||
return keyDaemonProcess_.get();
|
||||
}
|
||||
|
||||
void ProcessKernel::deliverSystemTimerEvent()
|
||||
{
|
||||
if (systemTimerProcess_ == nullptr) {
|
||||
throw std::logic_error("system timer process is not registered");
|
||||
}
|
||||
if (processAt(systemTimerProcessId_) != &systemTimerProcess_->base ||
|
||||
(readLe16(systemTimerProcess_->base, 0x16) & 0x400) == 0) {
|
||||
throw std::logic_error("system timer event registration is invalid");
|
||||
}
|
||||
SystemTimerProcess::increment(*systemTimerProcess_);
|
||||
}
|
||||
|
||||
u32 ProcessKernel::systemTimerTick() const
|
||||
{
|
||||
if (systemTimerProcess_ == nullptr) {
|
||||
throw std::logic_error("system timer process is not registered");
|
||||
}
|
||||
return SystemTimerProcess::tick(*systemTimerProcess_);
|
||||
}
|
||||
|
||||
void ProcessKernel::setSyncContext(bool enabled, u16 currentProcessId)
|
||||
{
|
||||
syncEnabled_ = enabled;
|
||||
currentProcessId_ = currentProcessId;
|
||||
}
|
||||
|
||||
void ProcessKernel::setMarkNewProcesses(bool enabled)
|
||||
{
|
||||
markNewProcesses_ = enabled;
|
||||
}
|
||||
|
||||
void ProcessKernel::setLastAllocationSize(u16 size)
|
||||
{
|
||||
lastAllocationSize_ = size;
|
||||
}
|
||||
|
||||
u16 ProcessKernel::addProcess(EntityDispatchEntryBase& entry)
|
||||
{
|
||||
auto freeSlot = std::find(processes_.begin(), processes_.end(), nullptr);
|
||||
if (freeSlot == processes_.end()) {
|
||||
if (processes_.size() + 30 > 1023) {
|
||||
throw std::overflow_error("process table exhausted");
|
||||
}
|
||||
const std::size_t oldCapacity = processes_.size();
|
||||
processes_.resize(oldCapacity + 30, nullptr);
|
||||
allocationSizes_.resize(oldCapacity + 30, 0);
|
||||
processNames_.resize(oldCapacity + 30, nullptr);
|
||||
freeSlot = processes_.begin() + oldCapacity;
|
||||
}
|
||||
const u16 id = static_cast<u16>(freeSlot - processes_.begin());
|
||||
*freeSlot = &entry;
|
||||
entry.bytes[0x02] = static_cast<u8>(id & 0xff);
|
||||
entry.bytes[0x03] = static_cast<u8>(id >> 8);
|
||||
allocationSizes_[id] = lastAllocationSize_;
|
||||
lastAllocationSize_ = 0;
|
||||
++processCount_;
|
||||
if (markNewProcesses_) {
|
||||
++newlyCreatedCount_;
|
||||
entry.bytes[0x19] |= 0x02;
|
||||
}
|
||||
processNames_[id] = "Default";
|
||||
return id;
|
||||
}
|
||||
|
||||
void ProcessKernel::clearProcessSlot(u16 id)
|
||||
{
|
||||
if (id >= processes_.size()) {
|
||||
throw std::out_of_range("process ID outside table");
|
||||
}
|
||||
processes_[id] = nullptr;
|
||||
allocationSizes_[id] = 0;
|
||||
processNames_[id] = nullptr;
|
||||
}
|
||||
|
||||
void ProcessKernel::releaseOwnedProcess(u16 id)
|
||||
{
|
||||
EntityDispatchEntryBase* entry = processes_[id];
|
||||
clearProcessSlot(id);
|
||||
const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(),
|
||||
[entry](const auto& process) { return &process->base == entry; });
|
||||
if (stand != ownedStandProcesses_.end()) {
|
||||
ownedStandProcesses_.erase(stand);
|
||||
return;
|
||||
}
|
||||
const auto owned = std::find_if(ownedProcesses_.begin(), ownedProcesses_.end(),
|
||||
[entry](const auto& process) { return process.get() == entry; });
|
||||
ownedProcesses_.erase(owned);
|
||||
}
|
||||
|
||||
void ProcessKernel::terminateProcess(u16 id, u16 (&groupCounts)[32])
|
||||
{
|
||||
EntityDispatchEntryBase* entry = processAt(id);
|
||||
if (id == 0 || entry == nullptr) {
|
||||
throw std::out_of_range("process ID is not addressable");
|
||||
}
|
||||
const u16 itemNumber = readLe16(*entry, 0x04);
|
||||
if (systemTimerProcess_ != nullptr && entry == &systemTimerProcess_->base) {
|
||||
throw std::logic_error("system timer teardown is not ported");
|
||||
}
|
||||
if (keyboardProcess_ != nullptr && entry == &keyboardProcess_->base) {
|
||||
throw std::logic_error("keyboard process teardown is not ported");
|
||||
}
|
||||
if (keyDaemonProcess_ != nullptr && entry == &keyDaemonProcess_->base) {
|
||||
throw std::logic_error("key daemon process teardown is not ported");
|
||||
}
|
||||
const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(),
|
||||
[entry](const auto& process) { return &process->base == entry; });
|
||||
if (itemNumber != 0 && (stand == ownedStandProcesses_.end() || id < 3 ||
|
||||
readLe16(*entry, 0x24) != 0 || readLe16(*entry, 0x26) != 0 ||
|
||||
readLe16(*entry, 0x2e) != 0 || readLe16(*entry, 0x30) != 0)) {
|
||||
throw std::logic_error("item process child cleanup is not ported");
|
||||
}
|
||||
if (stand == ownedStandProcesses_.end() && std::none_of(ownedProcesses_.begin(), ownedProcesses_.end(),
|
||||
[entry](const auto& process) { return process.get() == entry; })) {
|
||||
throw std::logic_error("external process ownership is not ported");
|
||||
}
|
||||
const bool immediate = (entry->bytes[0x18] & 0x04) != 0;
|
||||
if (!immediate && (entry->bytes[0x16] & 0x08) != 0) {
|
||||
throw std::logic_error("process is already terminated");
|
||||
}
|
||||
--groupCounts[entry->bytes[0x08] & 0x1f];
|
||||
if (immediate) {
|
||||
releaseOwnedProcess(id);
|
||||
} else {
|
||||
entry->bytes[0x16] |= 0x08;
|
||||
++terminatedProcessCount_;
|
||||
}
|
||||
--processCount_;
|
||||
if (itemNumber != 0) {
|
||||
const bool stillPresent = std::any_of(processes_.begin() + 3, processes_.end(),
|
||||
[itemNumber](const EntityDispatchEntryBase* process) {
|
||||
return process != nullptr && readLe16(*process, 0x04) == itemNumber &&
|
||||
(readLe16(*process, 0x16) & 0x08) == 0;
|
||||
});
|
||||
if (!stillPresent) {
|
||||
itemProcessPresence_[itemNumber >> 3] &= static_cast<u8>(~(1u << (itemNumber & 7)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessKernel::clearTerminatedProcesses()
|
||||
{
|
||||
for (std::size_t id = 3; id < processes_.size() && terminatedProcessCount_ != 0; ++id) {
|
||||
EntityDispatchEntryBase* entry = processes_[id];
|
||||
if (entry == nullptr || (entry->bytes[0x16] & 0x08) == 0) {
|
||||
continue;
|
||||
}
|
||||
if (entry->bytes[0x1a] != 0 || entry->bytes[0x1b] != 0) {
|
||||
throw std::logic_error("terminated process has linked state");
|
||||
}
|
||||
releaseOwnedProcess(static_cast<u16>(id));
|
||||
--terminatedProcessCount_;
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessKernel::scanRunnableProcesses(u8 activeGroup, void (*run)(EntityDispatchEntryBase&, void*), void* context, u32 timerTick)
|
||||
{
|
||||
if (run == nullptr) {
|
||||
throw std::invalid_argument("process run slot is required");
|
||||
}
|
||||
const bool priorSyncEnabled = syncEnabled_;
|
||||
const u16 priorProcessId = currentProcessId_;
|
||||
syncEnabled_ = true;
|
||||
try {
|
||||
for (std::size_t id = 0; id < processes_.size(); ++id) {
|
||||
EntityDispatchEntryBase* entry = processes_[id];
|
||||
if (entry != nullptr && (readLe16(*entry, 0x16) & 0x08) == 0) {
|
||||
if ((readLe16(*entry, 0x18) & 0x1000) != 0) {
|
||||
const u32 sleepStart = readLe16(*entry, 0x0a) | (static_cast<u32>(readLe16(*entry, 0x0c)) << 16);
|
||||
const u32 sleepLength = readLe16(*entry, 0x0e) | (static_cast<u32>(readLe16(*entry, 0x10)) << 16);
|
||||
if (sleepStart + sleepLength < timerTick) {
|
||||
if ((readLe16(*entry, 0x16) & 0x100) != 0) {
|
||||
const auto stand = std::find_if(ownedStandProcesses_.begin(), ownedStandProcesses_.end(),
|
||||
[entry](const auto& process) { return &process->base == entry; });
|
||||
if (stand == ownedStandProcesses_.end() ||
|
||||
readLe16(*entry, 0x00) != StandProcess::vtableOffset) {
|
||||
throw std::logic_error("sleep completion dispatch is not ported");
|
||||
}
|
||||
}
|
||||
EntityDispatchEntry::unlinkSleep(*entry);
|
||||
}
|
||||
}
|
||||
if ((readLe16(*entry, 0x16) & 0x40) != 0) {
|
||||
writeLe16(*entry, 0x16, static_cast<u16>(readLe16(*entry, 0x16) & ~0x40));
|
||||
} else {
|
||||
const u8 groupId = entry->bytes[0x08] & 0x1f;
|
||||
const u16 flags = readLe16(*entry, 0x16);
|
||||
if ((readLe16(*entry, 0x18) & 0x1000) == 0 && readLe16(*entry, 0x24) == 0 &&
|
||||
readLe16(*entry, 0x26) == 0 && (flags & 1) == 0 &&
|
||||
((flags & 2) != 0 || groupId == activeGroup || groupId == 30 || groupId == 31)) {
|
||||
currentProcessId_ = static_cast<u16>(id);
|
||||
run(*entry, context);
|
||||
currentProcessId_ = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
clearTerminatedProcesses();
|
||||
}
|
||||
} catch (...) {
|
||||
syncEnabled_ = priorSyncEnabled;
|
||||
currentProcessId_ = priorProcessId;
|
||||
throw;
|
||||
}
|
||||
syncEnabled_ = priorSyncEnabled;
|
||||
currentProcessId_ = priorProcessId;
|
||||
}
|
||||
|
||||
EntityDispatchEntryBase* ProcessKernel::processAt(u16 id) const
|
||||
{
|
||||
return id < processes_.size() ? processes_[id] : nullptr;
|
||||
}
|
||||
|
||||
u16 ProcessKernel::allocationSizeAt(u16 id) const
|
||||
{
|
||||
return id < allocationSizes_.size() ? allocationSizes_[id] : 0;
|
||||
}
|
||||
|
||||
const char* ProcessKernel::processNameAt(u16 id) const
|
||||
{
|
||||
return id < processNames_.size() ? processNames_[id] : nullptr;
|
||||
}
|
||||
|
||||
bool ProcessKernel::itemHasProcess(u16 itemNumber) const
|
||||
{
|
||||
const std::size_t itemByte = itemNumber >> 3;
|
||||
return itemByte < itemProcessPresence_.size() &&
|
||||
(itemProcessPresence_[itemByte] & (1u << (itemNumber & 7))) != 0;
|
||||
}
|
||||
|
||||
u16 ProcessKernel::processCount() const
|
||||
{
|
||||
return processCount_;
|
||||
}
|
||||
|
||||
u16 ProcessKernel::terminatedProcessCount() const
|
||||
{
|
||||
return terminatedProcessCount_;
|
||||
}
|
||||
|
||||
u16 ProcessKernel::newlyCreatedCount() const
|
||||
{
|
||||
return newlyCreatedCount_;
|
||||
}
|
||||
|
||||
std::size_t ProcessKernel::capacity() const
|
||||
{
|
||||
return processes_.size();
|
||||
}
|
||||
|
||||
EntityDispatchEntryBase* EntityDispatchEntry::initBase(EntityDispatchEntryBase* entry, u8 activeGroup, u16 (&groupCounts)[32])
|
||||
{
|
||||
if (entry == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
for (u8& byte : entry->bytes) {
|
||||
byte = 0;
|
||||
}
|
||||
writeLe16(*entry, 0x00, 0x3b06);
|
||||
writeLe16(*entry, 0x1e, 0x2d10);
|
||||
writeLe16(*entry, 0x28, 0x3afe);
|
||||
clearBytes(*entry, 0x02, 0x06);
|
||||
writeLe16(*entry, 0x06, 1);
|
||||
entry->bytes[0x08] = 0;
|
||||
clearBytes(*entry, 0x0a, 0x1e);
|
||||
writeLe16(*entry, 0x18, 1);
|
||||
clearBytes(*entry, 0x20, 0x28);
|
||||
clearBytes(*entry, 0x2a, 0x32);
|
||||
setGroupId(*entry, activeGroup, groupCounts);
|
||||
return entry;
|
||||
}
|
||||
|
||||
void EntityDispatchEntry::setGroupId(EntityDispatchEntryBase& entry, u8 groupId)
|
||||
void EntityDispatchEntry::setGroupId(EntityDispatchEntryBase& entry, u8 groupId, u16 (&groupCounts)[32])
|
||||
{
|
||||
entry.bytes[groupIdOffset] = static_cast<u8>((entry.bytes[groupIdOffset] & 0xe0) | (groupId & 0x1f));
|
||||
if (groupId == 0 || groupId > 31) {
|
||||
throw std::invalid_argument("process group ID must be in 1..31");
|
||||
}
|
||||
const u8 oldGroupId = entry.bytes[groupIdOffset] & 0x1f;
|
||||
if (oldGroupId == groupId) {
|
||||
return;
|
||||
}
|
||||
if (oldGroupId != 0) {
|
||||
--groupCounts[oldGroupId];
|
||||
}
|
||||
entry.bytes[groupIdOffset] = groupId;
|
||||
++groupCounts[groupId];
|
||||
}
|
||||
|
||||
void EntityDispatchEntry::incrementGroupId(EntityDispatchEntryBase& entry)
|
||||
|
|
@ -46,4 +464,77 @@ void EntityDispatchEntry::setEventTypeChecked(EntityDispatchEntryBase& entry, u1
|
|||
writeLe16(entry, eventTypeOffset, eventType);
|
||||
}
|
||||
|
||||
void EntityDispatchEntry::sleep(EntityDispatchEntryBase& entry, u32 timerTick, u32 duration)
|
||||
{
|
||||
writeLe16(entry, 0x18, static_cast<u16>(readLe16(entry, 0x18) | 0x1000));
|
||||
writeLe16(entry, 0x0a, static_cast<u16>(timerTick));
|
||||
writeLe16(entry, 0x0c, static_cast<u16>(timerTick >> 16));
|
||||
writeLe16(entry, 0x0e, static_cast<u16>(duration));
|
||||
writeLe16(entry, 0x10, static_cast<u16>(duration >> 16));
|
||||
}
|
||||
|
||||
void EntityDispatchEntry::unlinkSleep(EntityDispatchEntryBase& entry)
|
||||
{
|
||||
writeLe16(entry, 0x18, static_cast<u16>(readLe16(entry, 0x18) & ~0x1000));
|
||||
clearBytes(entry, 0x0a, 0x12);
|
||||
}
|
||||
|
||||
void StandProcess::run(EntityDispatchEntryBase& entry,
|
||||
bool (*startBehavior)(const EntityDispatchEntryBase&, void*), void* context, u32 timerTick)
|
||||
{
|
||||
if (startBehavior == nullptr) {
|
||||
throw std::invalid_argument("NPC behavior boundary is required");
|
||||
}
|
||||
if (!startBehavior(entry, context)) {
|
||||
EntityDispatchEntry::sleep(entry, timerTick, 0x3c);
|
||||
}
|
||||
}
|
||||
|
||||
void StandProcess::run(StandProcessEntry& entry, const NpcBehaviorServices& services, u32 timerTick)
|
||||
{
|
||||
if (services.isEntirelyOnScreen == nullptr || services.getActivity == nullptr ||
|
||||
services.isCurrentActivitySpecifiedBy == nullptr || services.canSeeControlledNPC == nullptr ||
|
||||
services.startNextBehavior == nullptr) {
|
||||
throw std::invalid_argument("NPC behavior services are required");
|
||||
}
|
||||
const u16 npcNumber = static_cast<u16>(entry.extra[0x0e] | (static_cast<u16>(entry.extra[0x0f]) << 8));
|
||||
bool started = false;
|
||||
if (services.isEntirelyOnScreen(npcNumber, services.context) &&
|
||||
services.getActivity(npcNumber, services.context) != 0 &&
|
||||
!services.isCurrentActivitySpecifiedBy(npcNumber, 0x71, services.context) &&
|
||||
services.canSeeControlledNPC(npcNumber, services.context)) {
|
||||
services.startNextBehavior(npcNumber, 0x71, services.context);
|
||||
started = true;
|
||||
}
|
||||
run(entry.base, [](const EntityDispatchEntryBase&, void* context) {
|
||||
return *static_cast<bool*>(context);
|
||||
}, &started, timerTick);
|
||||
}
|
||||
|
||||
u32 SystemTimerProcess::tick(const SystemTimerProcessEntry& entry)
|
||||
{
|
||||
return static_cast<u32>(entry.extra[0x0e] | (static_cast<u16>(entry.extra[0x0f]) << 8)) |
|
||||
(static_cast<u32>(entry.extra[0x10] | (static_cast<u16>(entry.extra[0x11]) << 8)) << 16);
|
||||
}
|
||||
|
||||
void SystemTimerProcess::increment(SystemTimerProcessEntry& entry)
|
||||
{
|
||||
const u32 nextTick = tick(entry) + 1;
|
||||
entry.extra[0x0e] = static_cast<u8>(nextTick);
|
||||
entry.extra[0x0f] = static_cast<u8>(nextTick >> 8);
|
||||
entry.extra[0x10] = static_cast<u8>(nextTick >> 16);
|
||||
entry.extra[0x11] = static_cast<u8>(nextTick >> 24);
|
||||
}
|
||||
|
||||
bool KeyboardProcess::handleKeyEvent(KeyboardProcessEntry& process, u16 selector, u16 filter,
|
||||
KeyEvent& event, const KeyEvent& lastEvent)
|
||||
{
|
||||
if (selector != 0x10 || filter != 0 || event.character == 0 || event.field8 == 0) {
|
||||
return false;
|
||||
}
|
||||
std::memcpy(&event, &lastEvent, sizeof(event));
|
||||
process.extra[0] &= static_cast<u8>(~0x10);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace remorse
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@
|
|||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
remorse::installCrashDiagnostics();
|
||||
const std::filesystem::path manifestPath = argc > 1
|
||||
? std::filesystem::path(argv[1])
|
||||
: remorse::defaultManifestPath(std::filesystem::current_path());
|
||||
|
|
@ -24,9 +25,48 @@ int main(int argc, char** argv)
|
|||
}
|
||||
|
||||
remorse::printStartupReport(*manifest);
|
||||
remorse::EntityDispatchEntryBase entry{};
|
||||
remorse::EntityDispatchEntry::initBase(&entry);
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 1);
|
||||
remorse::ProcessKernel kernel;
|
||||
remorse::u16 groupCounts[32]{};
|
||||
const auto* entry = kernel.createProcess(1, groupCounts);
|
||||
std::cout << "Registered process ID: " << (entry ? entry->bytes[0x02] : 0) << '\n';
|
||||
for (int index = 0; index < 3; ++index) {
|
||||
kernel.createProcess(1, groupCounts);
|
||||
}
|
||||
kernel.createSystemTimerProcess(1, groupCounts);
|
||||
kernel.createKeyboardProcess(1, groupCounts);
|
||||
kernel.createKeyDaemonProcess(1, groupCounts);
|
||||
kernel.terminateProcess(3, groupCounts);
|
||||
kernel.clearTerminatedProcesses();
|
||||
auto* reused = kernel.createStandProcess(1, 1, groupCounts);
|
||||
std::cout << "Reused Stand process ID: " << (reused ? reused->base.bytes[0x02] : 0) << '\n';
|
||||
remorse::NpcBehaviorServices npcServices{
|
||||
[](remorse::u16, void*) { return false; },
|
||||
[](remorse::u16, void*) -> remorse::u16 { return 0; },
|
||||
[](remorse::u16, remorse::u16, void*) { return false; },
|
||||
[](remorse::u16, void*) { return false; },
|
||||
[](remorse::u16, remorse::u16, void*) {},
|
||||
nullptr
|
||||
};
|
||||
struct ScanContext {
|
||||
remorse::StandProcessEntry* standing;
|
||||
remorse::NpcBehaviorServices* npcServices;
|
||||
remorse::u32 timerTick;
|
||||
int hostCallbacks = 0;
|
||||
} scanContext{reused, &npcServices, 0};
|
||||
for (int tick = 0; tick < 100; ++tick) {
|
||||
kernel.deliverSystemTimerEvent();
|
||||
}
|
||||
scanContext.timerTick = kernel.systemTimerTick();
|
||||
kernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& process, void* context) {
|
||||
auto& scan = *static_cast<ScanContext*>(context);
|
||||
if (process.bytes[0] == 0x0f && process.bytes[1] == 0x1f) {
|
||||
remorse::StandProcess::run(*scan.standing, *scan.npcServices, scan.timerTick);
|
||||
} else {
|
||||
++scan.hostCallbacks;
|
||||
}
|
||||
}, &scanContext, scanContext.timerTick);
|
||||
std::cout << "Scheduler scan host callbacks: " << scanContext.hostCallbacks << '\n';
|
||||
std::cout << "StandProcess Run sleep ticks: " << static_cast<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';
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
#include "remorse/file_system.h"
|
||||
#include "remorse/map_renderer.h"
|
||||
#include "remorse/runtime.h"
|
||||
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
|
|
@ -7,6 +8,7 @@
|
|||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
remorse::installCrashDiagnostics();
|
||||
const auto root = remorse::findGameDataRoot(std::filesystem::current_path());
|
||||
if (!root) {
|
||||
std::cerr << "Could not locate Crusader game data root.\n";
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
#include "remorse/fixed_map.h"
|
||||
#include "remorse/glob_archive.h"
|
||||
#include "remorse/detail/map_sorter.h"
|
||||
#include "remorse/shape_archive.h"
|
||||
#include "remorse/type_flags.h"
|
||||
|
||||
|
|
@ -14,7 +15,12 @@ namespace {
|
|||
|
||||
constexpr u16 flagInvisible = 0x0010;
|
||||
constexpr u16 flagFlipped = 0x0020;
|
||||
constexpr u32 siSolid = 0x0002;
|
||||
constexpr u32 siLand = 0x0008;
|
||||
constexpr u32 siOccl = 0x0010;
|
||||
constexpr u32 siDraw = 0x0100;
|
||||
constexpr u32 siRoof = 0x0400;
|
||||
constexpr u32 siTranslucent = 0x0800;
|
||||
constexpr s32 globCoordMask = ~0x3ff;
|
||||
constexpr s32 globCoordShift = 2;
|
||||
constexpr s32 globCoordOffset = 2;
|
||||
|
|
@ -139,12 +145,12 @@ std::vector<SceneItem> collectSceneItems(
|
|||
|
||||
s32 screenX(const SceneItem& item)
|
||||
{
|
||||
return (item.x - item.y) / 4;
|
||||
return projectToScreen(WorldPoint{item.x, item.y, item.z}).x;
|
||||
}
|
||||
|
||||
s32 screenY(const SceneItem& item)
|
||||
{
|
||||
return (item.x + item.y) / 8 - item.z;
|
||||
return projectToScreen(WorldPoint{item.x, item.y, item.z}).y;
|
||||
}
|
||||
|
||||
std::optional<DecodedShapeFrame> cachedDecode(
|
||||
|
|
@ -166,10 +172,16 @@ std::optional<DecodedShapeFrame> cachedDecode(
|
|||
return decoded;
|
||||
}
|
||||
|
||||
std::vector<RenderNode> prepareRenderNodes(const std::vector<SceneItem>& items, const ShapeArchive& shapeArchive)
|
||||
std::vector<RenderNode> prepareRenderNodes(
|
||||
const std::vector<SceneItem>& items,
|
||||
const ShapeArchive& shapeArchive,
|
||||
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 = cachedDecode(shapeArchive, cache, item.shape, item.frame);
|
||||
if (!decoded) {
|
||||
|
|
@ -188,24 +200,52 @@ std::vector<RenderNode> prepareRenderNodes(const std::vector<SceneItem>& items,
|
|||
node.top = bottomY - node.decoded.frame.yOffset;
|
||||
node.right = node.left + static_cast<s32>(node.decoded.frame.width);
|
||||
node.bottom = node.top + static_cast<s32>(node.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);
|
||||
}
|
||||
|
||||
std::sort(nodes.begin(), nodes.end(), [](const RenderNode& left, const RenderNode& right) {
|
||||
const s32 leftKey = left.item.x + left.item.y;
|
||||
const s32 rightKey = right.item.x + right.item.y;
|
||||
if (leftKey != rightKey) {
|
||||
return leftKey < rightKey;
|
||||
}
|
||||
if (left.item.z != right.item.z) {
|
||||
return left.item.z < right.item.z;
|
||||
}
|
||||
if (left.item.y != right.item.y) {
|
||||
return left.item.y < right.item.y;
|
||||
}
|
||||
return left.item.x < right.item.x;
|
||||
});
|
||||
return nodes;
|
||||
const std::vector<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)
|
||||
|
|
@ -248,6 +288,11 @@ void writeLe32(std::ofstream& output, u32 value)
|
|||
|
||||
} // namespace
|
||||
|
||||
ScreenPoint projectToScreen(const WorldPoint& point)
|
||||
{
|
||||
return ScreenPoint{(point.x - point.y) / 4, (point.x + point.y) / 8 - point.z};
|
||||
}
|
||||
|
||||
std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const MapRenderOptions& options)
|
||||
{
|
||||
const auto fixedPath = resolveGameDataPath(root, std::filesystem::path("STATIC") / "FIXED.DAT");
|
||||
|
|
@ -270,7 +315,7 @@ std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const
|
|||
}
|
||||
|
||||
const auto items = collectSceneItems(*fixedMap, *typeFlags, *globs, options);
|
||||
auto nodes = prepareRenderNodes(items, *shapeArchive);
|
||||
auto nodes = prepareRenderNodes(items, *shapeArchive, *typeFlags);
|
||||
if (nodes.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
|
@ -290,12 +335,22 @@ std::optional<RenderedMapImage> renderMapPreview(const GameDataRoot& root, const
|
|||
image.rawItemCount = static_cast<u32>(fixedMap->entries.size());
|
||||
image.renderItemCount = static_cast<u32>(items.size());
|
||||
image.decodedItemCount = static_cast<u32>(nodes.size());
|
||||
image.sourceLeft = nodes[0].left;
|
||||
image.sourceTop = nodes[0].top;
|
||||
image.fullWidth = maxRight - minLeft;
|
||||
image.fullHeight = maxBottom - minTop;
|
||||
image.width = std::min(options.maxWidth, static_cast<u32>(std::max<s32>(1, image.fullWidth)));
|
||||
image.height = std::min(options.maxHeight, static_cast<u32>(std::max<s32>(1, image.fullHeight)));
|
||||
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)});
|
||||
|
|
|
|||
316
rebuild/remorse/src/map_sorter.cpp
Normal file
316
rebuild/remorse/src/map_sorter.cpp
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
#include "remorse/detail/map_sorter.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace remorse {
|
||||
namespace detail {
|
||||
namespace {
|
||||
|
||||
struct SortNode {
|
||||
RenderSortItem item;
|
||||
std::vector<std::size_t> dependencies;
|
||||
bool occluded = false;
|
||||
s32 order = -1;
|
||||
};
|
||||
|
||||
bool listLessThan(const RenderSortItem& left, const RenderSortItem& right)
|
||||
{
|
||||
if (left.sprite != right.sprite) {
|
||||
return left.sprite < right.sprite;
|
||||
}
|
||||
if (left.z != right.z) {
|
||||
return left.z < right.z;
|
||||
}
|
||||
return left.flat > right.flat;
|
||||
}
|
||||
|
||||
bool rectIntersects(const RenderSortItem& left, const RenderSortItem& right)
|
||||
{
|
||||
return left.left < right.right && left.right > right.left &&
|
||||
left.top < right.bottom && left.bottom > right.top;
|
||||
}
|
||||
|
||||
bool rectContains(const RenderSortItem& outer, const RenderSortItem& inner)
|
||||
{
|
||||
return outer.left <= inner.left && outer.top <= inner.top &&
|
||||
outer.right >= inner.right && outer.bottom >= inner.bottom;
|
||||
}
|
||||
|
||||
bool overlaps(const RenderSortItem& left, const RenderSortItem& right)
|
||||
{
|
||||
if (!rectIntersects(left, right)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const s32 topDiffX = left.sxTop - right.sxBottom;
|
||||
const s32 topDiffY = left.syTop - right.syBottom;
|
||||
const s32 bottomDiffX = left.sxBottom - right.sxTop;
|
||||
const s32 bottomDiffY = left.syBottom - right.syTop;
|
||||
const bool rightClear = left.sxRight <= right.sxLeft;
|
||||
const bool leftClear = left.sxLeft >= right.sxRight;
|
||||
const bool topLeftClear = topDiffX + topDiffY * 2 >= 0;
|
||||
const bool topRightClear = -topDiffX + topDiffY * 2 >= 0;
|
||||
const bool bottomLeftClear = bottomDiffX - bottomDiffY * 2 >= 0;
|
||||
const bool bottomRightClear = -bottomDiffX - bottomDiffY * 2 >= 0;
|
||||
return !(rightClear || leftClear || topLeftClear || topRightClear || bottomLeftClear || bottomRightClear);
|
||||
}
|
||||
|
||||
bool occludes(const RenderSortItem& outer, const RenderSortItem& inner)
|
||||
{
|
||||
if (!rectContains(outer, inner)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const s32 topDiffX = outer.sxTop - inner.sxTop;
|
||||
const s32 topDiffY = outer.syTop - inner.syTop;
|
||||
const s32 bottomDiffX = outer.sxBottom - inner.sxBottom;
|
||||
const s32 bottomDiffY = outer.syBottom - inner.syBottom;
|
||||
const bool rightResult = outer.sxRight >= inner.sxRight;
|
||||
const bool leftResult = outer.sxLeft <= inner.sxLeft;
|
||||
const bool topLeftResult = topDiffX + topDiffY * 2 <= 0;
|
||||
const bool topRightResult = -topDiffX + topDiffY * 2 <= 0;
|
||||
const bool bottomLeftResult = bottomDiffX - bottomDiffY * 2 <= 0;
|
||||
const bool bottomRightResult = -bottomDiffX - bottomDiffY * 2 <= 0;
|
||||
return rightResult && leftResult && topLeftResult && topRightResult &&
|
||||
bottomLeftResult && bottomRightResult;
|
||||
}
|
||||
|
||||
bool below(const RenderSortItem& left, const RenderSortItem& right)
|
||||
{
|
||||
if (left.sprite != right.sprite) {
|
||||
return left.sprite < right.sprite;
|
||||
}
|
||||
|
||||
if (left.flat && right.flat) {
|
||||
if (left.z != right.z) {
|
||||
return left.z < right.z;
|
||||
}
|
||||
} else if (left.inventoryItem == right.inventoryItem) {
|
||||
if (left.zTop <= right.z) {
|
||||
return true;
|
||||
}
|
||||
if (left.z >= right.zTop) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const bool yFlatLeft = left.yFar == left.y;
|
||||
const bool yFlatRight = right.yFar == right.y;
|
||||
if (yFlatLeft && yFlatRight) {
|
||||
if (left.y / 32 != right.y / 32) {
|
||||
return left.y < right.y;
|
||||
}
|
||||
} else {
|
||||
if (left.y <= right.yFar) {
|
||||
return true;
|
||||
}
|
||||
if (left.yFar >= right.y) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const bool xFlatLeft = left.xLeft == left.x;
|
||||
const bool xFlatRight = right.xLeft == right.x;
|
||||
if (xFlatLeft && xFlatRight) {
|
||||
if (left.x / 32 != right.x / 32) {
|
||||
return left.x < right.x;
|
||||
}
|
||||
} else {
|
||||
if (left.x <= right.xLeft) {
|
||||
return true;
|
||||
}
|
||||
if (left.xLeft >= right.x) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (left.zTop - 8 <= right.z && left.z < right.zTop - 8) {
|
||||
return true;
|
||||
}
|
||||
if (left.z >= right.zTop - 8 && left.zTop - 8 > right.z) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (yFlatLeft != yFlatRight) {
|
||||
if (left.y / 32 <= right.yFar / 32) {
|
||||
return true;
|
||||
}
|
||||
if (left.yFar / 32 >= right.y / 32) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const s32 yCenterLeft = (left.yFar / 32 + left.y / 32) / 2;
|
||||
const s32 yCenterRight = (right.yFar / 32 + right.y / 32) / 2;
|
||||
if (yCenterLeft != yCenterRight) {
|
||||
return yCenterLeft < yCenterRight;
|
||||
}
|
||||
}
|
||||
|
||||
if (xFlatLeft != xFlatRight) {
|
||||
if (left.x / 32 <= right.xLeft / 32) {
|
||||
return true;
|
||||
}
|
||||
if (left.xLeft / 32 >= right.x / 32) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const s32 xCenterLeft = (left.xLeft / 32 + left.x / 32) / 2;
|
||||
const s32 xCenterRight = (right.xLeft / 32 + right.x / 32) / 2;
|
||||
if (xCenterLeft != xCenterRight) {
|
||||
return xCenterLeft < xCenterRight;
|
||||
}
|
||||
}
|
||||
|
||||
if (left.flat || right.flat) {
|
||||
if (left.z != right.z) {
|
||||
return left.z < right.z;
|
||||
}
|
||||
if (left.inventoryItem != right.inventoryItem) {
|
||||
return left.inventoryItem < right.inventoryItem;
|
||||
}
|
||||
if (left.flat != right.flat) {
|
||||
return left.flat > right.flat;
|
||||
}
|
||||
if (left.translucent != right.translucent) {
|
||||
return left.translucent < right.translucent;
|
||||
}
|
||||
if (left.animated != right.animated) {
|
||||
return left.animated < right.animated;
|
||||
}
|
||||
if (left.draw != right.draw) {
|
||||
return left.draw > right.draw;
|
||||
}
|
||||
if (left.solid != right.solid) {
|
||||
return left.solid > right.solid;
|
||||
}
|
||||
if (left.occludes != right.occludes) {
|
||||
return left.occludes > right.occludes;
|
||||
}
|
||||
if (left.bigFlatSquare != right.bigFlatSquare) {
|
||||
return left.bigFlatSquare > right.bigFlatSquare;
|
||||
}
|
||||
}
|
||||
|
||||
if (left.x == right.x && left.y == right.y && left.translucent != right.translucent) {
|
||||
return left.translucent < right.translucent;
|
||||
}
|
||||
if (left.land && right.land && left.roof != right.roof) {
|
||||
return left.roof < right.roof;
|
||||
}
|
||||
if (left.roof != right.roof) {
|
||||
return left.roof > right.roof;
|
||||
}
|
||||
if (left.z != right.z) {
|
||||
return left.z < right.z;
|
||||
}
|
||||
|
||||
if (xFlatLeft || xFlatRight || yFlatLeft || yFlatRight) {
|
||||
if (left.sxLeft != right.sxLeft) {
|
||||
return left.sxLeft > right.sxLeft;
|
||||
}
|
||||
if (left.syBottom != right.syBottom) {
|
||||
return left.syBottom < right.syBottom;
|
||||
}
|
||||
}
|
||||
|
||||
if (left.x + left.y != right.x + right.y) {
|
||||
return left.x + left.y < right.x + right.y;
|
||||
}
|
||||
if (left.xLeft + left.yFar != right.xLeft + right.yFar) {
|
||||
return left.xLeft + left.yFar < right.xLeft + right.yFar;
|
||||
}
|
||||
if (left.y != right.y) {
|
||||
return left.y < right.y;
|
||||
}
|
||||
if (left.x != right.x) {
|
||||
return left.x < right.x;
|
||||
}
|
||||
if (left.shape != right.shape) {
|
||||
return left.shape < right.shape;
|
||||
}
|
||||
return left.frame < right.frame;
|
||||
}
|
||||
|
||||
void insertDependencySorted(std::vector<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});
|
||||
}
|
||||
|
||||
std::vector<std::size_t> ordered;
|
||||
ordered.reserve(nodes.size());
|
||||
for (std::size_t index = 0; index < nodes.size(); ++index) {
|
||||
std::size_t insertAt = ordered.size();
|
||||
for (std::size_t otherIndex = 0; otherIndex < ordered.size(); ++otherIndex) {
|
||||
const std::size_t other = ordered[otherIndex];
|
||||
if (insertAt == ordered.size() && listLessThan(nodes[index].item, nodes[other].item)) {
|
||||
insertAt = otherIndex;
|
||||
}
|
||||
if (nodes[other].occluded || !overlaps(nodes[index].item, nodes[other].item)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (below(nodes[index].item, nodes[other].item)) {
|
||||
if (nodes[other].item.occludes && occludes(nodes[other].item, nodes[index].item)) {
|
||||
nodes[index].occluded = true;
|
||||
break;
|
||||
}
|
||||
insertDependencySorted(nodes, other, index);
|
||||
} else if (nodes[index].item.occludes && occludes(nodes[index].item, nodes[other].item)) {
|
||||
nodes[other].occluded = true;
|
||||
} else {
|
||||
insertDependencySorted(nodes, index, other);
|
||||
}
|
||||
}
|
||||
ordered.insert(ordered.begin() + static_cast<std::ptrdiff_t>(insertAt), 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
|
||||
|
|
@ -5,9 +5,59 @@
|
|||
#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);
|
||||
|
|
@ -42,6 +92,23 @@ u32 readJsonU32(const std::string& json, const char* key)
|
|||
|
||||
} // namespace
|
||||
|
||||
void installCrashDiagnostics()
|
||||
{
|
||||
#ifdef _WIN32
|
||||
SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
|
||||
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
|
||||
_set_error_mode(_OUT_TO_STDERR);
|
||||
#ifdef _DEBUG
|
||||
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
|
||||
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
|
||||
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
|
||||
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
|
||||
#endif
|
||||
SetUnhandledExceptionFilter(reportUnhandledException);
|
||||
std::set_terminate(reportTermination);
|
||||
#endif
|
||||
}
|
||||
|
||||
std::optional<ExportManifestSummary> loadExportManifestSummary(const std::filesystem::path& manifestPath)
|
||||
{
|
||||
const std::string json = readTextFile(manifestPath);
|
||||
|
|
@ -73,7 +140,7 @@ void printStartupReport(const ExportManifestSummary& manifest)
|
|||
std::cout << "Fallback function files: " << manifest.fallbackFunctionFiles << '\n';
|
||||
std::cout << "Global buckets: " << manifest.globalBuckets << '\n';
|
||||
std::cout << "Global definitions: " << manifest.globalDefinitions << '\n';
|
||||
std::cout << "Status: host runtime scaffold is alive; exported game code is not linked yet.\n";
|
||||
std::cout << "Status: StandProcess Run, registered timer, and keyboard diagnostic callback active; original key queue, NPC services, and game loop not linked.\n";
|
||||
}
|
||||
|
||||
} // namespace remorse
|
||||
|
|
|
|||
770
rebuild/remorse/src/windowed_game_main.cpp
Normal file
770
rebuild/remorse/src/windowed_game_main.cpp
Normal file
|
|
@ -0,0 +1,770 @@
|
|||
#define NOMINMAX
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
#include "remorse/animation_archive.h"
|
||||
#include "remorse/collision.h"
|
||||
#include "remorse/entity_dispatch_entry.h"
|
||||
#include "remorse/file_system.h"
|
||||
#include "remorse/fixed_map.h"
|
||||
#include "remorse/glob_archive.h"
|
||||
#include "remorse/isometric_controls.h"
|
||||
#include "remorse/map_renderer.h"
|
||||
#include "remorse/palette.h"
|
||||
#include "remorse/runtime.h"
|
||||
#include "remorse/shape_archive.h"
|
||||
#include "remorse/type_flags.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <iomanip>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr wchar_t windowClassName[] = L"CrusaderRemorseGameWindow";
|
||||
constexpr UINT timerId = 1;
|
||||
constexpr UINT sceneReadyMessage = WM_APP + 1;
|
||||
constexpr remorse::u32 backingWidth = 2560;
|
||||
constexpr remorse::u32 backingHeight = 1440;
|
||||
constexpr int initialClientWidth = 1280;
|
||||
constexpr int initialClientHeight = 760;
|
||||
constexpr double simulationTickSeconds = 0.025;
|
||||
|
||||
struct AppState {
|
||||
remorse::GameDataRoot root;
|
||||
remorse::u32 mapIndex = 1;
|
||||
remorse::ProcessKernel diagnosticKernel;
|
||||
remorse::u16 diagnosticGroupCounts[32]{};
|
||||
remorse::StandProcessEntry* diagnosticStand = nullptr;
|
||||
remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr;
|
||||
remorse::u32 standWakeCount = 0;
|
||||
remorse::u32 diagnosticKeyEvents = 0;
|
||||
std::mutex sceneMutex;
|
||||
std::optional<remorse::RenderedMapImage> scene;
|
||||
std::optional<remorse::AnimationClip> standAnimation;
|
||||
std::optional<remorse::AnimationClip> walkAnimation;
|
||||
std::optional<remorse::AnimationClip> runAnimation;
|
||||
std::vector<std::optional<remorse::DecodedShapeFrame>> playerFrames;
|
||||
remorse::CollisionBody playerCollisionBody{};
|
||||
std::vector<remorse::CollisionBody> collisionBodies;
|
||||
remorse::Palette256 playerPalette{};
|
||||
std::vector<std::uint8_t> dibPixels;
|
||||
std::vector<std::uint8_t> viewPixels;
|
||||
remorse::WorldPoint spawn{};
|
||||
remorse::WorldPoint playerWorld{};
|
||||
remorse::s32 minWorldX = 0;
|
||||
remorse::s32 minWorldY = 0;
|
||||
remorse::s32 maxWorldX = 0;
|
||||
remorse::s32 maxWorldY = 0;
|
||||
double playerOffsetX = 0.0;
|
||||
double playerOffsetY = 0.0;
|
||||
double simulationAccumulator = 0.0;
|
||||
remorse::u8 playerAnimation = 0;
|
||||
remorse::u8 playerDirection = 14;
|
||||
remorse::u8 playerFrame = 0;
|
||||
std::wstring loadError;
|
||||
bool sceneLoaded = false;
|
||||
std::thread sceneThread;
|
||||
HDC backBufferDc = nullptr;
|
||||
HBITMAP backBufferBitmap = nullptr;
|
||||
HBITMAP previousBackBufferBitmap = nullptr;
|
||||
int backBufferWidth = 0;
|
||||
int backBufferHeight = 0;
|
||||
LARGE_INTEGER lastTick{};
|
||||
LARGE_INTEGER ticksPerSecond{};
|
||||
};
|
||||
|
||||
remorse::u32 standSleepStart(const remorse::StandProcessEntry& stand)
|
||||
{
|
||||
const auto& bytes = stand.base.bytes;
|
||||
return bytes[0x0a] | (static_cast<remorse::u32>(bytes[0x0b]) << 8) |
|
||||
(static_cast<remorse::u32>(bytes[0x0c]) << 16) |
|
||||
(static_cast<remorse::u32>(bytes[0x0d]) << 24);
|
||||
}
|
||||
|
||||
std::wstring widen(const std::string& value)
|
||||
{
|
||||
if (value.empty()) {
|
||||
return {};
|
||||
}
|
||||
const int length = MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), nullptr, 0);
|
||||
if (length <= 0) {
|
||||
return L"Map loading failed.";
|
||||
}
|
||||
std::wstring result(static_cast<std::size_t>(length), L'\0');
|
||||
MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), result.data(), length);
|
||||
return result;
|
||||
}
|
||||
|
||||
void setLoadFailure(AppState& state, const std::wstring& message)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(state.sceneMutex);
|
||||
state.loadError = message;
|
||||
state.sceneLoaded = true;
|
||||
}
|
||||
|
||||
void loadSceneAsync(HWND window, AppState& state)
|
||||
{
|
||||
state.sceneThread = std::thread([window, &state]() {
|
||||
try {
|
||||
const auto fixedPath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "FIXED.DAT");
|
||||
const auto typeFlagsPath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT");
|
||||
const auto globPath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "GLOB.FLX");
|
||||
if (!fixedPath) {
|
||||
setLoadFailure(state, L"STATIC\\FIXED.DAT was not found under the game data root.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
if (!typeFlagsPath || !globPath) {
|
||||
setLoadFailure(state, L"STATIC\\TYPEFLAG.DAT or STATIC\\GLOB.FLX was not found.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
const auto archive = remorse::loadFixedMapArchive(*fixedPath);
|
||||
const auto map = archive ? remorse::loadFixedMap(*archive, state.mapIndex) : std::nullopt;
|
||||
if (!map || map->entries.empty()) {
|
||||
setLoadFailure(state, L"The selected map could not be loaded or contains no records.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath);
|
||||
const auto globObjects = remorse::loadGlobObjects(*globPath);
|
||||
if (!shapeTypes || !globObjects || shapeTypes->size() <= 1) {
|
||||
setLoadFailure(state, L"Collision shape metadata could not be loaded.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
auto collisionBodies = remorse::collectMapCollisionBodies(*map, *shapeTypes, *globObjects);
|
||||
|
||||
const auto animationPath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "ANIM.DAT");
|
||||
const auto shapesPath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "SHAPES.FLX");
|
||||
const auto palettePath = remorse::resolveGameDataPath(
|
||||
state.root, std::filesystem::path("STATIC") / "GAMEPAL.PAL");
|
||||
if (!animationPath || !shapesPath || !palettePath) {
|
||||
setLoadFailure(state, L"The player animation, shape, or palette resource is missing.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
const auto animationArchive = remorse::loadAnimationArchive(*animationPath);
|
||||
const auto shapeArchive = remorse::loadShapeArchive(*shapesPath);
|
||||
const auto palette = remorse::loadPalette256(*palettePath);
|
||||
const auto standAnimation = animationArchive
|
||||
? remorse::loadAnimationClip(*animationArchive, 1, 0) : std::nullopt;
|
||||
const auto walkAnimation = animationArchive
|
||||
? remorse::loadAnimationClip(*animationArchive, 1, 1) : std::nullopt;
|
||||
const auto runAnimation = animationArchive
|
||||
? remorse::loadAnimationClip(*animationArchive, 1, 3) : std::nullopt;
|
||||
const auto shapeFrames = shapeArchive
|
||||
? remorse::loadShapeFrames(*shapeArchive, 1) : std::nullopt;
|
||||
if (!shapeArchive || !palette || !standAnimation || !walkAnimation || !runAnimation || !shapeFrames) {
|
||||
setLoadFailure(state, L"The player stand, walk, or run animation could not be loaded.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<std::optional<remorse::DecodedShapeFrame>> playerFrames(shapeFrames->size());
|
||||
const auto cacheAnimationFrames = [&](const remorse::AnimationClip& clip) {
|
||||
for (remorse::u8 direction = 0; direction < 16; ++direction) {
|
||||
for (remorse::u32 frameIndex = 0; frameIndex < clip.frameCount; ++frameIndex) {
|
||||
const auto metadata = remorse::getAnimationFrame(
|
||||
clip, direction, static_cast<remorse::u8>(frameIndex));
|
||||
if (!metadata) {
|
||||
return false;
|
||||
}
|
||||
const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata);
|
||||
if (shapeFrame >= playerFrames.size()) {
|
||||
return false;
|
||||
}
|
||||
if (!playerFrames[shapeFrame]) {
|
||||
auto decoded = remorse::decodeShapeFrame(*shapeArchive, 1, shapeFrame);
|
||||
if (!decoded) {
|
||||
return false;
|
||||
}
|
||||
playerFrames[shapeFrame] = std::move(*decoded);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
if (!cacheAnimationFrames(*standAnimation) || !cacheAnimationFrames(*walkAnimation) ||
|
||||
!cacheAnimationFrames(*runAnimation)) {
|
||||
setLoadFailure(state, L"A player animation references a missing shape frame.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
remorse::s32 minX = map->entries.front().x;
|
||||
remorse::s32 minY = map->entries.front().y;
|
||||
remorse::s32 maxX = minX;
|
||||
remorse::s32 maxY = minY;
|
||||
for (const remorse::FixedMapEntry& entry : map->entries) {
|
||||
minX = std::min(minX, static_cast<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));
|
||||
}
|
||||
|
||||
const remorse::WorldPoint spawn{(minX + maxX) / 2, (minY + maxY) / 2, 0};
|
||||
remorse::MapRenderOptions options;
|
||||
options.mapIndex = state.mapIndex;
|
||||
options.maxWidth = backingWidth;
|
||||
options.maxHeight = backingHeight;
|
||||
options.viewCenter = spawn;
|
||||
auto scene = remorse::renderMapPreview(state.root, options);
|
||||
if (!scene) {
|
||||
setLoadFailure(state, L"Map graphics or palette data could not be loaded.");
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> dibPixels(scene->pixels.size() * 3);
|
||||
for (std::size_t index = 0; index < scene->pixels.size(); ++index) {
|
||||
dibPixels[index * 3] = scene->pixels[index].blue;
|
||||
dibPixels[index * 3 + 1] = scene->pixels[index].green;
|
||||
dibPixels[index * 3 + 2] = scene->pixels[index].red;
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(state.sceneMutex);
|
||||
state.spawn = spawn;
|
||||
state.playerWorld = spawn;
|
||||
state.playerCollisionBody = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]);
|
||||
state.collisionBodies = std::move(collisionBodies);
|
||||
state.minWorldX = minX;
|
||||
state.minWorldY = minY;
|
||||
state.maxWorldX = maxX;
|
||||
state.maxWorldY = maxY;
|
||||
state.scene = std::move(scene);
|
||||
state.dibPixels = std::move(dibPixels);
|
||||
state.standAnimation = *standAnimation;
|
||||
state.walkAnimation = *walkAnimation;
|
||||
state.runAnimation = *runAnimation;
|
||||
state.playerFrames = std::move(playerFrames);
|
||||
state.playerPalette = *palette;
|
||||
state.sceneLoaded = true;
|
||||
}
|
||||
} catch (const std::exception& error) {
|
||||
setLoadFailure(state, widen(error.what()));
|
||||
} catch (...) {
|
||||
setLoadFailure(state, L"An unexpected error occurred while building the map scene.");
|
||||
}
|
||||
PostMessageW(window, sceneReadyMessage, 0, 0);
|
||||
});
|
||||
}
|
||||
|
||||
void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLORREF color, HFONT font)
|
||||
{
|
||||
const int saved = SaveDC(device);
|
||||
SetBkMode(device, TRANSPARENT);
|
||||
SetTextColor(device, color);
|
||||
SelectObject(device, font);
|
||||
DrawTextW(device, text, -1, const_cast<RECT*>(&bounds), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
|
||||
RestoreDC(device, saved);
|
||||
}
|
||||
|
||||
bool isKeyDown(int key)
|
||||
{
|
||||
return (GetAsyncKeyState(key) & 0x8000) != 0;
|
||||
}
|
||||
|
||||
std::optional<remorse::u8> readMovementDirection()
|
||||
{
|
||||
if (isKeyDown(VK_HOME) || isKeyDown(VK_NUMPAD7) || isKeyDown('Q')) return static_cast<remorse::u8>(12);
|
||||
if (isKeyDown(VK_PRIOR) || isKeyDown(VK_NUMPAD9) || isKeyDown('E')) return static_cast<remorse::u8>(0);
|
||||
if (isKeyDown(VK_END) || isKeyDown(VK_NUMPAD1) || isKeyDown('Z')) return static_cast<remorse::u8>(8);
|
||||
if (isKeyDown(VK_NEXT) || isKeyDown(VK_NUMPAD3) || isKeyDown('C')) return static_cast<remorse::u8>(4);
|
||||
|
||||
const bool up = isKeyDown(VK_UP) || isKeyDown('W') || isKeyDown(VK_NUMPAD8);
|
||||
const bool right = isKeyDown(VK_RIGHT) || isKeyDown('D') || isKeyDown(VK_NUMPAD6);
|
||||
const bool down = isKeyDown(VK_DOWN) || isKeyDown('S') || isKeyDown(VK_NUMPAD2);
|
||||
const bool left = isKeyDown(VK_LEFT) || isKeyDown('A') || isKeyDown(VK_NUMPAD4);
|
||||
if (up && left) return static_cast<remorse::u8>(12);
|
||||
if (up && right) return static_cast<remorse::u8>(0);
|
||||
if (down && left) return static_cast<remorse::u8>(8);
|
||||
if (down && right) return static_cast<remorse::u8>(4);
|
||||
if (up) return static_cast<remorse::u8>(14);
|
||||
if (right) return static_cast<remorse::u8>(2);
|
||||
if (down) return static_cast<remorse::u8>(6);
|
||||
if (left) return static_cast<remorse::u8>(10);
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool isWalkRequested()
|
||||
{
|
||||
remorse::u16 modifiers = (GetKeyState(VK_CAPITAL) & 1) != 0 ? 0x40 : 0;
|
||||
if (isKeyDown(VK_LSHIFT)) modifiers |= 0x01;
|
||||
if (isKeyDown(VK_RSHIFT)) modifiers |= 0x02;
|
||||
return remorse::controllerWalkRequested(modifiers);
|
||||
}
|
||||
|
||||
void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight,
|
||||
int sourceLeft, int sourceTop, std::size_t viewStride)
|
||||
{
|
||||
const remorse::AnimationClip* clip = nullptr;
|
||||
if (state.playerAnimation == 1 && state.walkAnimation) {
|
||||
clip = &*state.walkAnimation;
|
||||
} else if (state.playerAnimation == 3 && state.runAnimation) {
|
||||
clip = &*state.runAnimation;
|
||||
} else if (state.standAnimation) {
|
||||
clip = &*state.standAnimation;
|
||||
}
|
||||
if (!clip || state.playerFrames.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const remorse::u8 frameIndex = state.playerAnimation == 0 ? 0 : state.playerFrame;
|
||||
const auto metadata = remorse::getAnimationFrame(*clip, state.playerDirection, frameIndex);
|
||||
if (!metadata) {
|
||||
return;
|
||||
}
|
||||
const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata);
|
||||
if (shapeFrame >= state.playerFrames.size() || !state.playerFrames[shapeFrame]) {
|
||||
return;
|
||||
}
|
||||
|
||||
const remorse::DecodedShapeFrame& sprite = *state.playerFrames[shapeFrame];
|
||||
const int actorX = static_cast<int>(state.scene->width / 2) +
|
||||
static_cast<int>(std::lround(state.playerOffsetX)) - sourceLeft;
|
||||
const int actorY = static_cast<int>(state.scene->height / 2) +
|
||||
static_cast<int>(std::lround(state.playerOffsetY)) - sourceTop;
|
||||
const int spriteLeft = actorX + sprite.frame.xOffset;
|
||||
const int spriteTop = actorY + sprite.frame.yOffset;
|
||||
const bool flipped = remorse::isAnimationFrameFlipped(*metadata);
|
||||
|
||||
for (remorse::u32 y = 0; y < sprite.frame.height; ++y) {
|
||||
const int destinationY = spriteTop + static_cast<int>(y);
|
||||
if (destinationY < 0 || destinationY >= viewHeight) {
|
||||
continue;
|
||||
}
|
||||
for (remorse::u32 x = 0; x < sprite.frame.width; ++x) {
|
||||
const int destinationX = spriteLeft + static_cast<int>(x);
|
||||
if (destinationX < 0 || destinationX >= viewWidth) {
|
||||
continue;
|
||||
}
|
||||
const remorse::u32 sourceX = flipped ? sprite.frame.width - 1 - x : x;
|
||||
const remorse::s16 paletteIndex = sprite.pixels[
|
||||
static_cast<std::size_t>(y) * sprite.frame.width + sourceX];
|
||||
if (paletteIndex < 0) {
|
||||
continue;
|
||||
}
|
||||
const remorse::RgbColor& color = state.playerPalette.colors[
|
||||
static_cast<remorse::u8>(paletteIndex)];
|
||||
const std::size_t pixelOffset = static_cast<std::size_t>(destinationY) * viewStride +
|
||||
static_cast<std::size_t>(destinationX) * 3;
|
||||
state.viewPixels[pixelOffset] = static_cast<std::uint8_t>(color.blue * 255 / 63);
|
||||
state.viewPixels[pixelOffset + 1] = static_cast<std::uint8_t>(color.green * 255 / 63);
|
||||
state.viewPixels[pixelOffset + 2] = static_cast<std::uint8_t>(color.red * 255 / 63);
|
||||
}
|
||||
}
|
||||
|
||||
BITMAPINFO bitmap{};
|
||||
bitmap.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
|
||||
bitmap.bmiHeader.biWidth = viewWidth;
|
||||
bitmap.bmiHeader.biHeight = -viewHeight;
|
||||
bitmap.bmiHeader.biPlanes = 1;
|
||||
bitmap.bmiHeader.biBitCount = 24;
|
||||
bitmap.bmiHeader.biCompression = BI_RGB;
|
||||
StretchDIBits(device, 0, 0, viewWidth, viewHeight, 0, 0, viewWidth, viewHeight,
|
||||
state.viewPixels.data(), &bitmap, DIB_RGB_COLORS, SRCCOPY);
|
||||
}
|
||||
|
||||
void drawLoadingScreen(HDC device, const RECT& client, const AppState& state)
|
||||
{
|
||||
HBRUSH background = CreateSolidBrush(RGB(13, 23, 28));
|
||||
FillRect(device, &client, background);
|
||||
DeleteObject(background);
|
||||
|
||||
RECT title = client;
|
||||
title.bottom = title.top + 70;
|
||||
HFONT titleFont = CreateFontW(-30, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,
|
||||
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
|
||||
DEFAULT_PITCH | FF_DONTCARE, L"Bahnschrift");
|
||||
drawCenteredText(device, title, L"CRUSADER / NO REMORSE", RGB(228, 220, 191), titleFont);
|
||||
DeleteObject(titleFont);
|
||||
|
||||
RECT status = client;
|
||||
status.top = title.bottom;
|
||||
HFONT bodyFont = CreateFontW(-18, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
|
||||
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
|
||||
DEFAULT_PITCH | FF_DONTCARE, L"Consolas");
|
||||
const std::wstring message = state.loadError.empty()
|
||||
? L"Building the retail map scene..."
|
||||
: state.loadError;
|
||||
drawCenteredText(device, status, message.c_str(), state.loadError.empty()
|
||||
? RGB(74, 207, 184) : RGB(245, 157, 119), bodyFont);
|
||||
DeleteObject(bodyFont);
|
||||
}
|
||||
|
||||
void paintWindow(HWND window, AppState& state)
|
||||
{
|
||||
PAINTSTRUCT paint{};
|
||||
HDC paintDc = BeginPaint(window, &paint);
|
||||
RECT client{};
|
||||
GetClientRect(window, &client);
|
||||
|
||||
const int clientWidth = static_cast<int>(std::max(1L, client.right - client.left));
|
||||
const int clientHeight = static_cast<int>(std::max(1L, client.bottom - client.top));
|
||||
if (state.backBufferWidth != clientWidth || state.backBufferHeight != clientHeight) {
|
||||
if (state.backBufferDc) {
|
||||
SelectObject(state.backBufferDc, state.previousBackBufferBitmap);
|
||||
DeleteObject(state.backBufferBitmap);
|
||||
DeleteDC(state.backBufferDc);
|
||||
state.backBufferDc = nullptr;
|
||||
state.backBufferBitmap = nullptr;
|
||||
state.previousBackBufferBitmap = nullptr;
|
||||
}
|
||||
state.backBufferDc = CreateCompatibleDC(paintDc);
|
||||
if (state.backBufferDc) {
|
||||
state.backBufferBitmap = CreateCompatibleBitmap(paintDc, clientWidth, clientHeight);
|
||||
if (state.backBufferBitmap) {
|
||||
state.previousBackBufferBitmap = static_cast<HBITMAP>(
|
||||
SelectObject(state.backBufferDc, state.backBufferBitmap));
|
||||
state.backBufferWidth = clientWidth;
|
||||
state.backBufferHeight = clientHeight;
|
||||
} else {
|
||||
DeleteDC(state.backBufferDc);
|
||||
state.backBufferDc = nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
HDC device = state.backBufferDc ? state.backBufferDc : paintDc;
|
||||
const auto finishPaint = [&]() {
|
||||
if (device != paintDc) {
|
||||
BitBlt(paintDc, 0, 0, clientWidth, clientHeight, device, 0, 0, SRCCOPY);
|
||||
}
|
||||
EndPaint(window, &paint);
|
||||
};
|
||||
|
||||
std::lock_guard<std::mutex> lock(state.sceneMutex);
|
||||
if (!state.sceneLoaded || !state.scene) {
|
||||
drawLoadingScreen(device, client, state);
|
||||
finishPaint();
|
||||
return;
|
||||
}
|
||||
if (!state.loadError.empty()) {
|
||||
drawLoadingScreen(device, client, state);
|
||||
finishPaint();
|
||||
return;
|
||||
}
|
||||
|
||||
HBRUSH clearBrush = CreateSolidBrush(RGB(10, 17, 22));
|
||||
FillRect(device, &client, clearBrush);
|
||||
DeleteObject(clearBrush);
|
||||
|
||||
const int viewWidth = std::min(clientWidth, static_cast<int>(state.scene->width));
|
||||
const int viewHeight = std::min(clientHeight, static_cast<int>(state.scene->height));
|
||||
const int centeredLeft = static_cast<int>(state.scene->width / 2) +
|
||||
static_cast<int>(std::lround(state.playerOffsetX)) - viewWidth / 2;
|
||||
const int centeredTop = static_cast<int>(state.scene->height / 2) +
|
||||
static_cast<int>(std::lround(state.playerOffsetY)) - viewHeight / 2;
|
||||
const int sourceLeft = std::clamp(centeredLeft, 0, static_cast<int>(state.scene->width) - viewWidth);
|
||||
const int sourceTop = std::clamp(centeredTop, 0, static_cast<int>(state.scene->height) - viewHeight);
|
||||
|
||||
const std::size_t viewStride = (static_cast<std::size_t>(viewWidth) * 3 + 3) & ~std::size_t(3);
|
||||
state.viewPixels.resize(viewStride * static_cast<std::size_t>(viewHeight));
|
||||
const std::size_t sceneStride = static_cast<std::size_t>(state.scene->width) * 3;
|
||||
for (int row = 0; row < viewHeight; ++row) {
|
||||
const std::size_t sceneOffset = static_cast<std::size_t>(sourceTop + row) * sceneStride +
|
||||
static_cast<std::size_t>(sourceLeft) * 3;
|
||||
const std::size_t viewOffset = static_cast<std::size_t>(row) * viewStride;
|
||||
std::memcpy(state.viewPixels.data() + viewOffset, state.dibPixels.data() + sceneOffset,
|
||||
static_cast<std::size_t>(viewWidth) * 3);
|
||||
}
|
||||
compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride);
|
||||
|
||||
RECT hud{0, 0, viewWidth, 62};
|
||||
HBRUSH hudBrush = CreateSolidBrush(RGB(14, 24, 29));
|
||||
FillRect(device, &hud, hudBrush);
|
||||
DeleteObject(hudBrush);
|
||||
HPEN hudLine = CreatePen(PS_SOLID, 1, RGB(43, 204, 178));
|
||||
HGDIOBJ oldPen = SelectObject(device, hudLine);
|
||||
MoveToEx(device, 0, hud.bottom - 1, nullptr);
|
||||
LineTo(device, viewWidth, hud.bottom - 1);
|
||||
SelectObject(device, oldPen);
|
||||
DeleteObject(hudLine);
|
||||
|
||||
std::wostringstream label;
|
||||
label << L"MAP " << std::setw(3) << std::setfill(L'0') << state.mapIndex
|
||||
<< L" X " << state.playerWorld.x
|
||||
<< L" Y " << state.playerWorld.y
|
||||
<< L" Z " << static_cast<int>(state.playerWorld.z)
|
||||
<< L" DIR " << std::setw(2) << static_cast<int>(state.playerDirection)
|
||||
<< L" " << (state.playerAnimation == 3 ? L"RUN" : state.playerAnimation == 1 ? L"WALK" : L"IDLE")
|
||||
<< L" WASD / KEYPAD SHIFT RUN";
|
||||
HFONT hudFont = CreateFontW(-16, 0, 0, 0, FW_MEDIUM, FALSE, FALSE, FALSE,
|
||||
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
|
||||
DEFAULT_PITCH | FF_DONTCARE, L"Consolas");
|
||||
RECT labelBounds{20, 0, viewWidth - 12, 36};
|
||||
const int saved = SaveDC(device);
|
||||
SetBkMode(device, TRANSPARENT);
|
||||
SetTextColor(device, RGB(224, 229, 214));
|
||||
SelectObject(device, hudFont);
|
||||
DrawTextW(device, label.str().c_str(), -1, &labelBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE);
|
||||
const remorse::EntityDispatchEntryBase& stand = state.diagnosticStand->base;
|
||||
const remorse::u32 sleepStart = standSleepStart(*state.diagnosticStand);
|
||||
const remorse::u32 sleepLength = stand.bytes[0x0e] | (static_cast<remorse::u32>(stand.bytes[0x0f]) << 8);
|
||||
std::wostringstream diagnostics;
|
||||
diagnostics << L"HOST 40Hz | KERNEL TICK " << state.diagnosticKernel.systemTimerTick()
|
||||
<< L" | STAND #" << static_cast<int>(stand.bytes[0x02])
|
||||
<< L" " << ((stand.bytes[0x19] & 0x10) != 0 ? L"SLEEP " : L"READY ")
|
||||
<< ((stand.bytes[0x19] & 0x10) != 0
|
||||
? static_cast<remorse::u32>(sleepStart + sleepLength - state.diagnosticKernel.systemTimerTick() + 1)
|
||||
: 0)
|
||||
<< L" | WAKEUPS " << state.standWakeCount
|
||||
<< L" | KEY EVENTS " << state.diagnosticKeyEvents;
|
||||
RECT diagnosticsBounds{20, 36, viewWidth - 12, hud.bottom - 1};
|
||||
SetTextColor(device, RGB(74, 207, 184));
|
||||
DrawTextW(device, diagnostics.str().c_str(), -1, &diagnosticsBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
|
||||
RestoreDC(device, saved);
|
||||
DeleteObject(hudFont);
|
||||
|
||||
finishPaint();
|
||||
}
|
||||
|
||||
void updatePlayer(HWND window, AppState& state)
|
||||
{
|
||||
LARGE_INTEGER now{};
|
||||
QueryPerformanceCounter(&now);
|
||||
const double elapsed = std::clamp(
|
||||
static_cast<double>(now.QuadPart - state.lastTick.QuadPart) /
|
||||
static_cast<double>(state.ticksPerSecond.QuadPart),
|
||||
0.0, 0.25);
|
||||
state.lastTick = now;
|
||||
|
||||
if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) {
|
||||
DestroyWindow(window);
|
||||
return;
|
||||
}
|
||||
if (GetForegroundWindow() != window) {
|
||||
return;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(state.sceneMutex);
|
||||
if (!state.sceneLoaded || !state.scene || !state.loadError.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.simulationAccumulator += elapsed;
|
||||
const auto direction = readMovementDirection();
|
||||
bool changed = false;
|
||||
while (state.simulationAccumulator >= simulationTickSeconds) {
|
||||
state.simulationAccumulator -= simulationTickSeconds;
|
||||
state.diagnosticKernel.deliverSystemTimerEvent();
|
||||
const bool wasSleeping = (state.diagnosticStand->base.bytes[0x19] & 0x10) != 0;
|
||||
const remorse::u32 previousSleepStart = standSleepStart(*state.diagnosticStand);
|
||||
state.diagnosticKernel.scanRunnableProcesses(1, [](remorse::EntityDispatchEntryBase& entry, void* context) {
|
||||
auto& app = *static_cast<AppState*>(context);
|
||||
if (&entry == &app.diagnosticStand->base) {
|
||||
remorse::StandProcess::run(entry,
|
||||
[](const remorse::EntityDispatchEntryBase&, void*) { return false; },
|
||||
nullptr, app.diagnosticKernel.systemTimerTick());
|
||||
}
|
||||
}, &state, state.diagnosticKernel.systemTimerTick());
|
||||
if (wasSleeping && standSleepStart(*state.diagnosticStand) != previousSleepStart) {
|
||||
++state.standWakeCount;
|
||||
}
|
||||
changed = true;
|
||||
if (!direction) {
|
||||
changed = changed || state.playerAnimation != 0 || state.playerFrame != 0;
|
||||
state.playerAnimation = 0;
|
||||
state.playerFrame = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
const remorse::u8 requestedAnimation = isWalkRequested() ? 1 : 3;
|
||||
const remorse::AnimationClip& clip = requestedAnimation == 1
|
||||
? *state.walkAnimation : *state.runAnimation;
|
||||
if (state.playerAnimation != requestedAnimation) {
|
||||
state.playerAnimation = requestedAnimation;
|
||||
state.playerFrame = 0;
|
||||
} else {
|
||||
state.playerFrame = static_cast<remorse::u8>(
|
||||
(state.playerFrame + 1) % clip.frameCount);
|
||||
}
|
||||
state.playerDirection = *direction;
|
||||
|
||||
const auto metadata = remorse::getAnimationFrame(clip, state.playerDirection, state.playerFrame);
|
||||
if (metadata) {
|
||||
const auto step = remorse::hostMovementStep(
|
||||
*metadata, state.playerDirection, (clip.header[2] & 0x10) != 0);
|
||||
if (step) {
|
||||
const remorse::WorldPoint destination{
|
||||
state.playerWorld.x + step->x,
|
||||
state.playerWorld.y + step->y,
|
||||
state.playerWorld.z + step->z};
|
||||
const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(destination);
|
||||
const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn);
|
||||
const double nextOffsetX = destinationScreen.x - spawnScreen.x;
|
||||
const double nextOffsetY = destinationScreen.y - spawnScreen.y;
|
||||
const bool withinMapBounds = destination.x >= state.minWorldX &&
|
||||
destination.x <= state.maxWorldX && destination.y >= state.minWorldY &&
|
||||
destination.y <= state.maxWorldY;
|
||||
const bool withinSceneBounds = std::abs(nextOffsetX) <= backingWidth / 2 - 16 &&
|
||||
std::abs(nextOffsetY) <= backingHeight / 2 - 16;
|
||||
if (withinMapBounds && withinSceneBounds && remorse::canMoveCollisionBody(
|
||||
state.playerCollisionBody, destination, state.collisionBodies)) {
|
||||
state.playerWorld = destination;
|
||||
state.playerCollisionBody.location = destination;
|
||||
state.playerOffsetX = nextOffsetX;
|
||||
state.playerOffsetY = nextOffsetY;
|
||||
}
|
||||
}
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
}
|
||||
}
|
||||
|
||||
LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
AppState* state = reinterpret_cast<AppState*>(GetWindowLongPtrW(window, GWLP_USERDATA));
|
||||
if (message == WM_NCCREATE) {
|
||||
const auto* create = reinterpret_cast<const CREATESTRUCTW*>(lParam);
|
||||
state = static_cast<AppState*>(create->lpCreateParams);
|
||||
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(state));
|
||||
}
|
||||
if (!state) {
|
||||
return DefWindowProcW(window, message, wParam, lParam);
|
||||
}
|
||||
|
||||
switch (message) {
|
||||
case WM_CREATE:
|
||||
QueryPerformanceFrequency(&state->ticksPerSecond);
|
||||
QueryPerformanceCounter(&state->lastTick);
|
||||
SetTimer(window, timerId, 16, nullptr);
|
||||
loadSceneAsync(window, *state);
|
||||
return 0;
|
||||
case WM_TIMER:
|
||||
if (wParam == timerId) {
|
||||
updatePlayer(window, *state);
|
||||
}
|
||||
return 0;
|
||||
case WM_CHAR:
|
||||
if (wParam > 0 && wParam <= 0xff) {
|
||||
remorse::KeyEvent lastEvent{};
|
||||
lastEvent.character = static_cast<remorse::u8>(wParam);
|
||||
lastEvent.scanCode = static_cast<remorse::u8>((lParam >> 16) & 0xff);
|
||||
lastEvent.field8 = 1;
|
||||
remorse::KeyEvent event = lastEvent;
|
||||
if (remorse::KeyboardProcess::handleKeyEvent(*state->diagnosticKeyboard, 0x10, 0, event, lastEvent)) {
|
||||
++state->diagnosticKeyEvents;
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
case WM_SIZE:
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
return 0;
|
||||
case WM_ERASEBKGND:
|
||||
return 1;
|
||||
case WM_PAINT:
|
||||
paintWindow(window, *state);
|
||||
return 0;
|
||||
case sceneReadyMessage:
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
KillTimer(window, timerId);
|
||||
if (state->sceneThread.joinable()) {
|
||||
state->sceneThread.join();
|
||||
}
|
||||
if (state->backBufferDc) {
|
||||
SelectObject(state->backBufferDc, state->previousBackBufferBitmap);
|
||||
DeleteObject(state->backBufferBitmap);
|
||||
DeleteDC(state->backBufferDc);
|
||||
}
|
||||
PostQuitMessage(0);
|
||||
return 0;
|
||||
default:
|
||||
return DefWindowProcW(window, message, wParam, lParam);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCommand)
|
||||
{
|
||||
remorse::installCrashDiagnostics();
|
||||
remorse::u32 mapIndex = 1;
|
||||
if (commandLine && *commandLine) {
|
||||
wchar_t* end = nullptr;
|
||||
const unsigned long parsed = std::wcstoul(commandLine, &end, 0);
|
||||
if (end != commandLine && parsed <= 255) {
|
||||
mapIndex = static_cast<remorse::u32>(parsed);
|
||||
}
|
||||
}
|
||||
|
||||
wchar_t executablePath[MAX_PATH]{};
|
||||
GetModuleFileNameW(nullptr, executablePath, MAX_PATH);
|
||||
auto root = remorse::findGameDataRoot(std::filesystem::path(executablePath).parent_path());
|
||||
if (!root) {
|
||||
root = remorse::findGameDataRoot(std::filesystem::current_path());
|
||||
}
|
||||
if (!root) {
|
||||
MessageBoxW(nullptr,
|
||||
L"Could not locate CRUSADER.EXE, STATIC, and USECODE. Place this application below the game data folder or launch it from that folder.",
|
||||
L"Crusader Rebuild", MB_OK | MB_ICONERROR);
|
||||
return 2;
|
||||
}
|
||||
|
||||
AppState state;
|
||||
state.root = *root;
|
||||
state.mapIndex = mapIndex;
|
||||
for (int index = 0; index < 3; ++index) {
|
||||
state.diagnosticKernel.createProcess(1, state.diagnosticGroupCounts);
|
||||
}
|
||||
state.diagnosticKernel.createSystemTimerProcess(1, state.diagnosticGroupCounts);
|
||||
state.diagnosticKeyboard = state.diagnosticKernel.createKeyboardProcess(1, state.diagnosticGroupCounts);
|
||||
state.diagnosticKernel.createKeyDaemonProcess(1, state.diagnosticGroupCounts);
|
||||
state.diagnosticStand = state.diagnosticKernel.createStandProcess(1, 1, state.diagnosticGroupCounts);
|
||||
|
||||
WNDCLASSEXW windowClass{};
|
||||
windowClass.cbSize = sizeof(windowClass);
|
||||
windowClass.style = CS_HREDRAW | CS_VREDRAW;
|
||||
windowClass.lpfnWndProc = windowProcedure;
|
||||
windowClass.hInstance = instance;
|
||||
windowClass.hCursor = LoadCursorW(nullptr, MAKEINTRESOURCEW(32512));
|
||||
windowClass.hIcon = LoadIconW(nullptr, MAKEINTRESOURCEW(32512));
|
||||
windowClass.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
|
||||
windowClass.lpszClassName = windowClassName;
|
||||
if (!RegisterClassExW(&windowClass)) {
|
||||
MessageBoxW(nullptr, L"Could not register the game window.", L"Crusader Rebuild", MB_OK | MB_ICONERROR);
|
||||
return 3;
|
||||
}
|
||||
|
||||
RECT bounds{0, 0, initialClientWidth, initialClientHeight};
|
||||
AdjustWindowRect(&bounds, WS_OVERLAPPEDWINDOW, FALSE);
|
||||
HWND window = CreateWindowExW(0, windowClassName, L"Crusader: No Remorse | Rebuild", WS_OVERLAPPEDWINDOW,
|
||||
CW_USEDEFAULT, CW_USEDEFAULT, bounds.right - bounds.left, bounds.bottom - bounds.top,
|
||||
nullptr, nullptr, instance, &state);
|
||||
if (!window) {
|
||||
MessageBoxW(nullptr, L"Could not create the game window.", L"Crusader Rebuild", MB_OK | MB_ICONERROR);
|
||||
return 4;
|
||||
}
|
||||
|
||||
ShowWindow(window, showCommand);
|
||||
UpdateWindow(window);
|
||||
MSG message{};
|
||||
while (GetMessageW(&message, nullptr, 0, 0) > 0) {
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
return static_cast<int>(message.wParam);
|
||||
}
|
||||
149
rebuild/remorse/tests/animation_archive_tests.cpp
Normal file
149
rebuild/remorse/tests/animation_archive_tests.cpp
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
#include "remorse/animation_archive.h"
|
||||
#include "remorse/file_system.h"
|
||||
#include "remorse/isometric_controls.h"
|
||||
#include "remorse/shape_archive.h"
|
||||
|
||||
#include <cassert>
|
||||
#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);
|
||||
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 remorse::AnimationClip* clip : {&*stand, &*walk, &*run}) {
|
||||
for (remorse::u8 direction = 0; direction < 16; ++direction) {
|
||||
for (remorse::u8 frame = 0; frame < clip->frameCount; ++frame) {
|
||||
const auto metadata = remorse::getAnimationFrame(*clip, direction, frame);
|
||||
assert(metadata.has_value());
|
||||
const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata);
|
||||
assert(shapeFrame < referencedFrames.size());
|
||||
referencedFrames[shapeFrame] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
bool decodedReferencedFrame = false;
|
||||
for (std::size_t frame = 0; frame < referencedFrames.size(); ++frame) {
|
||||
if (referencedFrames[frame]) {
|
||||
assert(remorse::decodeShapeFrame(*shapeArchive, 1, static_cast<remorse::u32>(frame)).has_value());
|
||||
decodedReferencedFrame = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert(decodedReferencedFrame);
|
||||
return 0;
|
||||
}
|
||||
72
rebuild/remorse/tests/collision_tests.cpp
Normal file
72
rebuild/remorse/tests/collision_tests.cpp
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
#include "remorse/collision.h"
|
||||
|
||||
#include <cassert>
|
||||
|
||||
int main()
|
||||
{
|
||||
const remorse::CollisionBody actor{{100, 100, 0}, 96, 96, 80};
|
||||
const remorse::CollisionBody wall{{300, 100, 0}, 64, 96, 128};
|
||||
assert(!remorse::collisionBodiesOverlap(actor, wall));
|
||||
assert(remorse::canMoveCollisionBody(actor, {200, 100, 0}, {wall}));
|
||||
assert(!remorse::canMoveCollisionBody(actor, {260, 100, 0}, {wall}));
|
||||
assert(!remorse::canMoveCollisionBody(actor, {400, 100, 0}, {wall}));
|
||||
|
||||
const remorse::CollisionBody floorBelow{{300, 100, -20}, 64, 96, 20};
|
||||
const remorse::CollisionBody overhead{{300, 100, 80}, 64, 96, 32};
|
||||
assert(!remorse::collisionBodiesOverlap(actor, floorBelow));
|
||||
assert(!remorse::collisionBodiesOverlap(actor, overhead));
|
||||
|
||||
const remorse::CollisionBody initiallyOverlapping{{250, 100, 0}, 96, 96, 80};
|
||||
assert(remorse::canMoveCollisionBody(initiallyOverlapping, {200, 100, 0}, {wall}));
|
||||
assert(!remorse::canMoveCollisionBody(initiallyOverlapping, {400, 100, 0}, {wall}));
|
||||
|
||||
remorse::ShapeTypeInfo actorInfo;
|
||||
actorInfo.x = 3;
|
||||
actorInfo.y = 3;
|
||||
actorInfo.z = 10;
|
||||
actorInfo.flags = 0x2;
|
||||
const remorse::CollisionBody authoredActor = remorse::makeCollisionBody({100, 100, 0}, actorInfo);
|
||||
assert(authoredActor.extentX == 96);
|
||||
assert(authoredActor.extentY == 96);
|
||||
assert(authoredActor.extentZ == 80);
|
||||
|
||||
remorse::ShapeTypeInfo obstacleInfo;
|
||||
obstacleInfo.x = 2;
|
||||
obstacleInfo.y = 4;
|
||||
obstacleInfo.z = 8;
|
||||
const remorse::CollisionBody flipped = remorse::makeCollisionBody({300, 300, 0}, obstacleInfo, true);
|
||||
assert(flipped.extentX == 128);
|
||||
assert(flipped.extentY == 64);
|
||||
|
||||
remorse::FixedMap map;
|
||||
remorse::FixedMapEntry solid;
|
||||
solid.x = 500;
|
||||
solid.y = 600;
|
||||
solid.shape = 1;
|
||||
map.entries.push_back(solid);
|
||||
remorse::FixedMapEntry globParent;
|
||||
globParent.x = 0x480;
|
||||
globParent.y = 0x640;
|
||||
globParent.shape = 2;
|
||||
globParent.quality = 7;
|
||||
map.entries.push_back(globParent);
|
||||
|
||||
std::vector<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;
|
||||
}
|
||||
|
|
@ -1,11 +1,30 @@
|
|||
#include "remorse/entity_dispatch_entry.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
int main()
|
||||
{
|
||||
remorse::EntityDispatchEntryBase entry{};
|
||||
remorse::EntityDispatchEntry::initBase(&entry);
|
||||
remorse::u16 groupCounts[32]{};
|
||||
for (remorse::u8& byte : entry.bytes) {
|
||||
byte = 0xa5;
|
||||
}
|
||||
assert(remorse::EntityDispatchEntry::initBase(&entry, 1, groupCounts) == &entry);
|
||||
assert(entry.bytes[0x00] == 0x06 && entry.bytes[0x01] == 0x3b);
|
||||
assert(entry.bytes[0x09] == 0xa5);
|
||||
assert(entry.bytes[0x1e] == 0x10 && entry.bytes[0x1f] == 0x2d);
|
||||
assert(entry.bytes[0x28] == 0xfe && entry.bytes[0x29] == 0x3a);
|
||||
for (remorse::u16 offset : {remorse::u16{0x02}, remorse::u16{0x04}, remorse::u16{0x0a}, remorse::u16{0x12}, remorse::u16{0x16}, remorse::u16{0x1a}, remorse::u16{0x20}, remorse::u16{0x26}, remorse::u16{0x2a}, remorse::u16{0x30}}) {
|
||||
assert(entry.bytes[offset] == 0 && entry.bytes[offset + 1] == 0);
|
||||
}
|
||||
assert(entry.bytes[0x06] == 1 && entry.bytes[0x07] == 0);
|
||||
assert(entry.bytes[0x08] == 1 && groupCounts[1] == 1);
|
||||
assert(entry.bytes[0x18] == 1 && entry.bytes[0x19] == 0);
|
||||
assert(remorse::EntityDispatchEntry::initBase(nullptr, 1, groupCounts) == nullptr);
|
||||
assert(groupCounts[1] == 1);
|
||||
|
||||
remorse::EntityDispatchEntry::setSourceType(entry, 0x1234);
|
||||
assert(entry.bytes[0x04] == 0x34);
|
||||
|
|
@ -15,12 +34,446 @@ int main()
|
|||
assert(entry.bytes[0x06] == 0xf2);
|
||||
assert(entry.bytes[0x07] == 0x00);
|
||||
|
||||
entry.bytes[0x08] = 0xe0;
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 0x23);
|
||||
assert(entry.bytes[0x08] == 0xe3);
|
||||
remorse::EntityDispatchEntry::sleep(entry, 0x12345678, 0x0001003c);
|
||||
assert(entry.bytes[0x18] == 0x01 && entry.bytes[0x19] == 0x10);
|
||||
assert(entry.bytes[0x0a] == 0x78 && entry.bytes[0x0b] == 0x56);
|
||||
assert(entry.bytes[0x0c] == 0x34 && entry.bytes[0x0d] == 0x12);
|
||||
assert(entry.bytes[0x0e] == 0x3c && entry.bytes[0x0f] == 0x00);
|
||||
assert(entry.bytes[0x10] == 0x01 && entry.bytes[0x11] == 0x00);
|
||||
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 3, groupCounts);
|
||||
assert(groupCounts[1] == 0 && groupCounts[3] == 1);
|
||||
entry.bytes[0x08] = 0xe3;
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 3, groupCounts);
|
||||
assert(entry.bytes[0x08] == 0xe3 && groupCounts[3] == 1);
|
||||
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 3, groupCounts);
|
||||
assert(groupCounts[3] == 1);
|
||||
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, 4, groupCounts);
|
||||
assert(entry.bytes[0x08] == 4 && groupCounts[3] == 0 && groupCounts[4] == 1);
|
||||
|
||||
for (remorse::u8 invalidId : {remorse::u8{0}, remorse::u8{32}}) {
|
||||
bool rejected = false;
|
||||
try {
|
||||
remorse::EntityDispatchEntry::setGroupId(entry, invalidId, groupCounts);
|
||||
} catch (const std::invalid_argument&) {
|
||||
rejected = true;
|
||||
}
|
||||
assert(rejected && entry.bytes[0x08] == 4 && groupCounts[4] == 1);
|
||||
}
|
||||
|
||||
remorse::EntityDispatchEntry::incrementGroupId(entry);
|
||||
assert(entry.bytes[0x08] == 0xe4);
|
||||
assert(entry.bytes[0x08] == 5);
|
||||
|
||||
remorse::ProcessKernel kernel;
|
||||
kernel.setLastAllocationSize(sizeof(entry));
|
||||
assert(kernel.addProcess(entry) == 0);
|
||||
assert(entry.bytes[0x02] == 0 && entry.bytes[0x03] == 0);
|
||||
assert(kernel.processAt(0) == &entry);
|
||||
assert(kernel.allocationSizeAt(0) == 0x32);
|
||||
assert(kernel.processCount() == 1 && kernel.capacity() == 30);
|
||||
assert(std::strcmp(kernel.processNameAt(0), "Default") == 0);
|
||||
remorse::EntityDispatchEntryBase second{};
|
||||
kernel.setMarkNewProcesses(true);
|
||||
assert(kernel.addProcess(second) == 1);
|
||||
assert(second.bytes[0x02] == 1 && second.bytes[0x03] == 0);
|
||||
assert(kernel.allocationSizeAt(1) == 0);
|
||||
assert(second.bytes[0x19] == 0x02 && kernel.newlyCreatedCount() == 1);
|
||||
kernel.setMarkNewProcesses(false);
|
||||
kernel.clearProcessSlot(1);
|
||||
assert(kernel.processAt(1) == nullptr && kernel.allocationSizeAt(1) == 0);
|
||||
assert(kernel.processNameAt(1) == nullptr && kernel.processCount() == 2);
|
||||
remorse::EntityDispatchEntryBase reused{};
|
||||
assert(kernel.addProcess(reused) == 1 && kernel.processAt(1) == &reused);
|
||||
std::vector<remorse::EntityDispatchEntryBase> additional(29);
|
||||
for (auto& process : additional) {
|
||||
kernel.addProcess(process);
|
||||
}
|
||||
assert(kernel.processAt(30) == &additional.back());
|
||||
assert(kernel.capacity() == 60 && kernel.processCount() == 32);
|
||||
|
||||
remorse::ProcessKernel createdKernel;
|
||||
remorse::u16 createdGroups[32]{};
|
||||
auto* created = createdKernel.createProcess(2, createdGroups);
|
||||
assert(created != nullptr && createdKernel.processAt(0) == created);
|
||||
assert(createdKernel.processCount() == 1 && createdKernel.allocationSizeAt(0) == 0x32);
|
||||
assert(created->bytes[0x02] == 0 && created->bytes[0x03] == 0);
|
||||
assert(created->bytes[0x08] == 2 && createdGroups[2] == 1);
|
||||
createdKernel.setSyncContext(true, 1);
|
||||
auto* next = createdKernel.createProcess(2, createdGroups);
|
||||
assert(createdKernel.processAt(1) == next && createdGroups[2] == 2);
|
||||
assert(next->bytes[0x02] == 1 && next->bytes[0x03] == 0);
|
||||
assert(next->bytes[0x16] == 0);
|
||||
createdKernel.setSyncContext(true, 0);
|
||||
auto* syncing = createdKernel.createProcess(2, createdGroups);
|
||||
assert(createdKernel.processAt(2) == syncing && createdGroups[2] == 3);
|
||||
assert(syncing->bytes[0x16] == 0x40 && syncing->bytes[0x17] == 0);
|
||||
|
||||
createdKernel.setSyncContext(true, 1);
|
||||
next->bytes[0x18] |= 0x02;
|
||||
auto* retiring = createdKernel.createProcess(2, createdGroups);
|
||||
assert(createdKernel.processAt(3) == retiring && createdKernel.processCount() == 4);
|
||||
assert(next->bytes[0x18] == 0x07 && retiring->bytes[0x16] == 0x40);
|
||||
createdKernel.terminateProcess(3, createdGroups);
|
||||
assert(createdKernel.processAt(3) == retiring && (retiring->bytes[0x16] & 0x08) != 0);
|
||||
assert(createdKernel.processCount() == 3 && createdKernel.terminatedProcessCount() == 1);
|
||||
assert(createdGroups[2] == 3);
|
||||
bool alreadyTerminated = false;
|
||||
try {
|
||||
createdKernel.terminateProcess(3, createdGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
alreadyTerminated = true;
|
||||
}
|
||||
assert(alreadyTerminated && createdGroups[2] == 3 && createdKernel.terminatedProcessCount() == 1);
|
||||
createdKernel.setSyncContext(true, 3);
|
||||
auto* afterTerminated = createdKernel.createProcess(2, createdGroups);
|
||||
assert((retiring->bytes[0x18] & 0x04) == 0 && (afterTerminated->bytes[0x16] & 0x40) != 0);
|
||||
createdKernel.terminateProcess(4, createdGroups);
|
||||
createdKernel.clearTerminatedProcesses();
|
||||
assert(createdKernel.processAt(3) == nullptr && createdKernel.allocationSizeAt(3) == 0);
|
||||
assert(createdKernel.processNameAt(3) == nullptr && createdKernel.terminatedProcessCount() == 0);
|
||||
auto* recycled = createdKernel.createProcess(2, createdGroups);
|
||||
assert(createdKernel.processAt(3) == recycled && recycled->bytes[0x02] == 3);
|
||||
assert(createdKernel.processCount() == 4 && createdGroups[2] == 4);
|
||||
|
||||
auto* immediate = createdKernel.createProcess(2, createdGroups);
|
||||
immediate->bytes[0x18] |= 0x04;
|
||||
createdKernel.terminateProcess(4, createdGroups);
|
||||
assert(createdKernel.processAt(4) == nullptr && createdKernel.processCount() == 4);
|
||||
assert(createdKernel.terminatedProcessCount() == 0 && createdGroups[2] == 4);
|
||||
|
||||
remorse::ProcessKernel fullKernel;
|
||||
std::vector<remorse::EntityDispatchEntryBase> fullTable(1020);
|
||||
for (auto& process : fullTable) {
|
||||
fullKernel.addProcess(process);
|
||||
}
|
||||
remorse::u16 fullGroups[32]{};
|
||||
bool exhausted = false;
|
||||
try {
|
||||
fullKernel.createProcess(2, fullGroups);
|
||||
} catch (const std::overflow_error&) {
|
||||
exhausted = true;
|
||||
}
|
||||
assert(exhausted && fullKernel.processCount() == 1020 && fullGroups[2] == 0);
|
||||
exhausted = false;
|
||||
try {
|
||||
fullKernel.createKeyboardProcess(2, fullGroups);
|
||||
} catch (const std::overflow_error&) {
|
||||
exhausted = true;
|
||||
}
|
||||
assert(exhausted && fullKernel.processCount() == 1020 && fullGroups[2] == 0);
|
||||
exhausted = false;
|
||||
try {
|
||||
fullKernel.createSystemTimerProcess(2, fullGroups);
|
||||
} catch (const std::overflow_error&) {
|
||||
exhausted = true;
|
||||
}
|
||||
assert(exhausted && fullKernel.processCount() == 1020 && fullGroups[2] == 0);
|
||||
|
||||
remorse::ProcessKernel scheduler;
|
||||
remorse::u16 scheduledGroups[32]{};
|
||||
auto* otherGroup = scheduler.createProcess(1, scheduledGroups);
|
||||
auto* matching = scheduler.createProcess(2, scheduledGroups);
|
||||
auto* syncingProcess = scheduler.createProcess(2, scheduledGroups);
|
||||
auto* specialGroup = scheduler.createProcess(30, scheduledGroups);
|
||||
syncingProcess->bytes[0x16] = 0x40;
|
||||
std::vector<remorse::u16> ran;
|
||||
auto recordRun = [](remorse::EntityDispatchEntryBase& process, void* context) {
|
||||
auto& ids = *static_cast<std::vector<remorse::u16>*>(context);
|
||||
ids.push_back(static_cast<remorse::u16>(process.bytes[0x02] | process.bytes[0x03] << 8));
|
||||
};
|
||||
scheduler.scanRunnableProcesses(2, recordRun, &ran);
|
||||
assert((ran == std::vector<remorse::u16>{1, 3}));
|
||||
assert(syncingProcess->bytes[0x16] == 0 && otherGroup->bytes[0x16] == 0);
|
||||
ran.clear();
|
||||
matching->bytes[0x16] = 1;
|
||||
scheduler.scanRunnableProcesses(2, recordRun, &ran);
|
||||
assert((ran == std::vector<remorse::u16>{2, 3}));
|
||||
assert(specialGroup->bytes[0x08] == 30);
|
||||
|
||||
remorse::ProcessKernel spawningKernel;
|
||||
remorse::u16 spawningGroups[32]{};
|
||||
spawningKernel.createProcess(1, spawningGroups);
|
||||
auto* spawningProcess = spawningKernel.createProcess(2, spawningGroups);
|
||||
spawningProcess->bytes[0x18] |= 0x02;
|
||||
struct SpawnContext {
|
||||
remorse::ProcessKernel* kernel;
|
||||
remorse::u16 (*groups)[32];
|
||||
remorse::EntityDispatchEntryBase* spawned = nullptr;
|
||||
int runs = 0;
|
||||
} spawnContext{&spawningKernel, &spawningGroups};
|
||||
auto spawnRun = [](remorse::EntityDispatchEntryBase&, void* context) {
|
||||
auto& state = *static_cast<SpawnContext*>(context);
|
||||
++state.runs;
|
||||
if (state.spawned == nullptr) {
|
||||
state.spawned = state.kernel->createProcess(2, *state.groups);
|
||||
}
|
||||
};
|
||||
spawningKernel.scanRunnableProcesses(2, spawnRun, &spawnContext);
|
||||
assert(spawnContext.runs == 1 && spawnContext.spawned == spawningKernel.processAt(2));
|
||||
assert(spawningProcess->bytes[0x18] == 0x07 && spawnContext.spawned->bytes[0x16] == 0);
|
||||
|
||||
remorse::ProcessKernel retiringKernel;
|
||||
remorse::u16 retiringGroups[32]{};
|
||||
for (int index = 0; index < 3; ++index) {
|
||||
retiringKernel.createProcess(1, retiringGroups);
|
||||
}
|
||||
retiringKernel.createProcess(2, retiringGroups);
|
||||
struct RetireContext {
|
||||
remorse::ProcessKernel* kernel;
|
||||
remorse::u16 (*groups)[32];
|
||||
} retireContext{&retiringKernel, &retiringGroups};
|
||||
auto retireRun = [](remorse::EntityDispatchEntryBase& process, void* context) {
|
||||
auto& state = *static_cast<RetireContext*>(context);
|
||||
state.kernel->terminateProcess(static_cast<remorse::u16>(process.bytes[0x02]), *state.groups);
|
||||
};
|
||||
retiringKernel.scanRunnableProcesses(2, retireRun, &retireContext);
|
||||
assert(retiringKernel.processAt(3) == nullptr && retiringKernel.terminatedProcessCount() == 0);
|
||||
assert(retiringKernel.processCount() == 3 && retiringGroups[2] == 0);
|
||||
|
||||
remorse::ProcessKernel sleepingKernel;
|
||||
remorse::u16 sleepingGroups[32]{};
|
||||
auto* sleeper = sleepingKernel.createProcess(2, sleepingGroups);
|
||||
remorse::EntityDispatchEntry::sleep(*sleeper, 100, 60);
|
||||
ran.clear();
|
||||
sleepingKernel.scanRunnableProcesses(2, recordRun, &ran, 160);
|
||||
assert(ran.empty() && sleeper->bytes[0x19] == 0x10);
|
||||
sleepingKernel.scanRunnableProcesses(2, recordRun, &ran, 161);
|
||||
assert((ran == std::vector<remorse::u16>{0}));
|
||||
assert(sleeper->bytes[0x19] == 0);
|
||||
for (remorse::u16 offset = 0x0a; offset < 0x12; ++offset) {
|
||||
assert(sleeper->bytes[offset] == 0);
|
||||
}
|
||||
|
||||
remorse::ProcessKernel standKernel;
|
||||
remorse::u16 standGroups[32]{};
|
||||
standKernel.createProcess(2, standGroups);
|
||||
assert(!standKernel.itemHasProcess(0x1234) && !standKernel.itemHasProcess(0x1235));
|
||||
auto* standEntry = standKernel.createStandProcess(2, 0x1234, standGroups);
|
||||
auto* standing = &standEntry->base;
|
||||
assert(standKernel.processAt(1) == standing && standKernel.allocationSizeAt(1) == 0x42);
|
||||
assert(std::strcmp(standKernel.processNameAt(1), "Stand") == 0 && standGroups[2] == 2);
|
||||
assert(standing->bytes[0] == 0x0f && standing->bytes[1] == 0x1f);
|
||||
assert(standing->bytes[0x04] == 0x34 && standing->bytes[0x05] == 0x12);
|
||||
assert(standing->bytes[0x06] == 0x58 && standing->bytes[0x07] == 0x02);
|
||||
assert(standing->bytes[0x17] == 0x03 && standEntry->extra[0] == 0x01 && standEntry->extra[1] == 0x01);
|
||||
assert(standEntry->extra[0x0e] == 0x34 && standEntry->extra[0x0f] == 0x12);
|
||||
assert(standKernel.itemHasProcess(0x1234) && !standKernel.itemHasProcess(0x1235));
|
||||
bool itemTeardownRejected = false;
|
||||
try {
|
||||
standKernel.terminateProcess(1, standGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
itemTeardownRejected = true;
|
||||
}
|
||||
assert(itemTeardownRejected && standGroups[2] == 2 && standKernel.processAt(1) == standing);
|
||||
struct StandContext {
|
||||
remorse::u32 tick;
|
||||
bool visible;
|
||||
remorse::u16 activity = 0;
|
||||
bool currentActivity = false;
|
||||
bool canSee = false;
|
||||
remorse::u16 startedNpc = 0;
|
||||
remorse::u16 startedActivity = 0;
|
||||
int starts = 0;
|
||||
int runs = 0;
|
||||
remorse::StandProcessEntry* entry = nullptr;
|
||||
remorse::NpcBehaviorServices* services = nullptr;
|
||||
} standContext{99, false};
|
||||
remorse::NpcBehaviorServices standServices{
|
||||
[](remorse::u16 npcNumber, void* context) {
|
||||
assert(npcNumber == 0x1234);
|
||||
return static_cast<StandContext*>(context)->visible;
|
||||
},
|
||||
[](remorse::u16 npcNumber, void* context) {
|
||||
assert(npcNumber == 0x1234);
|
||||
return static_cast<StandContext*>(context)->activity;
|
||||
},
|
||||
[](remorse::u16 npcNumber, remorse::u16 activity, void* context) {
|
||||
assert(npcNumber == 0x1234 && activity == 0x71);
|
||||
return static_cast<StandContext*>(context)->currentActivity;
|
||||
},
|
||||
[](remorse::u16 npcNumber, void* context) {
|
||||
assert(npcNumber == 0x1234);
|
||||
return static_cast<StandContext*>(context)->canSee;
|
||||
},
|
||||
[](remorse::u16 npcNumber, remorse::u16 activity, void* context) {
|
||||
auto& state = *static_cast<StandContext*>(context);
|
||||
state.startedNpc = npcNumber;
|
||||
state.startedActivity = activity;
|
||||
++state.starts;
|
||||
},
|
||||
&standContext
|
||||
};
|
||||
standContext.entry = standEntry;
|
||||
standContext.services = &standServices;
|
||||
auto standRun = [](remorse::EntityDispatchEntryBase& process, void* context) {
|
||||
auto& state = *static_cast<StandContext*>(context);
|
||||
if (process.bytes[0] != 0x0f || process.bytes[1] != 0x1f) {
|
||||
return;
|
||||
}
|
||||
++state.runs;
|
||||
remorse::StandProcess::run(*state.entry, *state.services, state.tick);
|
||||
};
|
||||
standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick);
|
||||
assert(standContext.runs == 1 && standing->bytes[0x19] == 0x10);
|
||||
assert(standing->bytes[0x0a] == 99 && standing->bytes[0x0e] == 60);
|
||||
assert(standContext.starts == 0);
|
||||
standContext.tick = 159;
|
||||
standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick);
|
||||
assert(standContext.runs == 1 && standing->bytes[0x19] == 0x10);
|
||||
standContext.tick = 160;
|
||||
standContext.visible = true;
|
||||
standContext.activity = 0x71;
|
||||
standContext.canSee = true;
|
||||
standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick);
|
||||
assert(standContext.runs == 2 && standing->bytes[0x19] == 0 && standing->bytes[0x0e] == 0);
|
||||
assert(standContext.starts == 1 && standContext.startedNpc == 0x1234 && standContext.startedActivity == 0x71);
|
||||
standContext.tick = 161;
|
||||
standContext.currentActivity = true;
|
||||
standKernel.scanRunnableProcesses(2, standRun, &standContext, standContext.tick);
|
||||
assert(standContext.runs == 3 && standContext.starts == 1 && standing->bytes[0x0e] == 60);
|
||||
|
||||
remorse::ProcessKernel itemKernel;
|
||||
remorse::u16 itemGroups[32]{};
|
||||
for (int index = 0; index < 3; ++index) {
|
||||
itemKernel.createProcess(1, itemGroups);
|
||||
}
|
||||
auto* firstStand = itemKernel.createStandProcess(2, 0x1234, itemGroups);
|
||||
auto* secondStand = itemKernel.createStandProcess(2, 0x1234, itemGroups);
|
||||
auto* otherStand = itemKernel.createStandProcess(2, 0x1235, itemGroups);
|
||||
assert(itemKernel.itemHasProcess(0x1234) && itemKernel.itemHasProcess(0x1235));
|
||||
itemKernel.terminateProcess(3, itemGroups);
|
||||
assert(itemKernel.itemHasProcess(0x1234) && itemKernel.processAt(3) == &firstStand->base);
|
||||
itemKernel.clearTerminatedProcesses();
|
||||
assert(itemKernel.processAt(3) == nullptr && itemKernel.itemHasProcess(0x1234));
|
||||
secondStand->base.bytes[0x18] |= 0x04;
|
||||
itemKernel.terminateProcess(4, itemGroups);
|
||||
assert(itemKernel.processAt(4) == nullptr && !itemKernel.itemHasProcess(0x1234));
|
||||
assert(itemKernel.itemHasProcess(0x1235) && itemKernel.processAt(5) == &otherStand->base);
|
||||
assert(itemGroups[2] == 1 && itemKernel.processCount() == 4);
|
||||
|
||||
remorse::SystemTimerProcessEntry systemTimer{};
|
||||
systemTimer.extra[0x0e] = 0xff;
|
||||
systemTimer.extra[0x0f] = 0xff;
|
||||
assert(remorse::SystemTimerProcess::tick(systemTimer) == 0xffff);
|
||||
remorse::SystemTimerProcess::increment(systemTimer);
|
||||
assert(remorse::SystemTimerProcess::tick(systemTimer) == 0x10000);
|
||||
assert(systemTimer.extra[0x0e] == 0 && systemTimer.extra[0x0f] == 0);
|
||||
assert(systemTimer.extra[0x10] == 1 && systemTimer.extra[0x11] == 0);
|
||||
|
||||
remorse::ProcessKernel timerKernel;
|
||||
remorse::u16 timerGroups[32]{};
|
||||
bool missingTimerRejected = false;
|
||||
try {
|
||||
timerKernel.deliverSystemTimerEvent();
|
||||
} catch (const std::logic_error&) {
|
||||
missingTimerRejected = true;
|
||||
}
|
||||
assert(missingTimerRejected);
|
||||
for (int index = 0; index < 3; ++index) {
|
||||
timerKernel.createProcess(1, timerGroups);
|
||||
}
|
||||
auto* registeredTimer = timerKernel.createSystemTimerProcess(1, timerGroups);
|
||||
assert(timerKernel.processAt(3) == ®isteredTimer->base);
|
||||
assert(timerKernel.allocationSizeAt(3) == 0x4a && timerGroups[1] == 4);
|
||||
assert(std::strcmp(timerKernel.processNameAt(3), "SystemTimer") == 0);
|
||||
assert(registeredTimer->base.bytes[0x16] == 3 && registeredTimer->base.bytes[0x17] == 0x27);
|
||||
assert(registeredTimer->base.bytes[0x18] == 1 && registeredTimer->extra[0] == 2);
|
||||
assert(registeredTimer->extra[4] == 0x3c && timerKernel.systemTimerTick() == 0);
|
||||
registeredTimer->base.bytes[0x17] &= static_cast<remorse::u8>(~0x04);
|
||||
bool registrationRejected = false;
|
||||
try {
|
||||
timerKernel.deliverSystemTimerEvent();
|
||||
} catch (const std::logic_error&) {
|
||||
registrationRejected = true;
|
||||
}
|
||||
assert(registrationRejected && timerKernel.systemTimerTick() == 0);
|
||||
registeredTimer->base.bytes[0x17] |= 0x04;
|
||||
bool duplicateTimerRejected = false;
|
||||
try {
|
||||
timerKernel.createSystemTimerProcess(1, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
duplicateTimerRejected = true;
|
||||
}
|
||||
assert(duplicateTimerRejected && timerGroups[1] == 4);
|
||||
bool timerTeardownRejected = false;
|
||||
try {
|
||||
timerKernel.terminateProcess(3, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
timerTeardownRejected = true;
|
||||
}
|
||||
assert(timerTeardownRejected && timerGroups[1] == 4);
|
||||
auto* timedStand = timerKernel.createStandProcess(1, 7, timerGroups);
|
||||
remorse::EntityDispatchEntry::sleep(timedStand->base, timerKernel.systemTimerTick(), 60);
|
||||
for (int tick = 0; tick < 60; ++tick) {
|
||||
timerKernel.deliverSystemTimerEvent();
|
||||
}
|
||||
ran.clear();
|
||||
timerKernel.scanRunnableProcesses(1, recordRun, &ran, timerKernel.systemTimerTick());
|
||||
assert(ran.size() == 3 && timedStand->base.bytes[0x19] == 0x10);
|
||||
timerKernel.deliverSystemTimerEvent();
|
||||
ran.clear();
|
||||
timerKernel.scanRunnableProcesses(1, recordRun, &ran, timerKernel.systemTimerTick());
|
||||
assert((ran == std::vector<remorse::u16>{0, 1, 2, 4}));
|
||||
assert(timedStand->base.bytes[0x19] == 0 && timerKernel.systemTimerTick() == 61);
|
||||
|
||||
auto* keyboard = timerKernel.createKeyboardProcess(1, timerGroups);
|
||||
assert(timerKernel.processAt(5) == &keyboard->base && timerKernel.allocationSizeAt(5) == 0x36);
|
||||
assert(std::strcmp(timerKernel.processNameAt(5), "KeyboardProcess") == 0);
|
||||
assert(keyboard->base.bytes[0x16] == 3 && keyboard->base.bytes[0x17] == 1);
|
||||
assert(keyboard->base.bytes[0x18] == 0x81 && keyboard->base.bytes[0x19] == 1);
|
||||
assert(keyboard->extra[0] == 0 && keyboard->extra[3] == 0 && timerGroups[1] == 6);
|
||||
bool duplicateKeyboardRejected = false;
|
||||
try {
|
||||
timerKernel.createKeyboardProcess(1, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
duplicateKeyboardRejected = true;
|
||||
}
|
||||
assert(duplicateKeyboardRejected && timerGroups[1] == 6);
|
||||
bool keyboardTeardownRejected = false;
|
||||
try {
|
||||
timerKernel.terminateProcess(5, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
keyboardTeardownRejected = true;
|
||||
}
|
||||
assert(keyboardTeardownRejected && timerGroups[1] == 6);
|
||||
|
||||
auto* keyDaemon = timerKernel.createKeyDaemonProcess(1, timerGroups);
|
||||
assert(timerKernel.processAt(6) == &keyDaemon->base && timerKernel.allocationSizeAt(6) == 0x40);
|
||||
assert(std::strcmp(timerKernel.processNameAt(6), "KeyDaemon") == 0);
|
||||
assert(keyDaemon->base.bytes[0x16] == 3 && keyDaemon->base.bytes[0x17] == 0x27);
|
||||
assert(keyDaemon->extra[0] == 2 && keyDaemon->extra[4] == 0x2d && timerGroups[1] == 7);
|
||||
bool duplicateDaemonRejected = false;
|
||||
try {
|
||||
timerKernel.createKeyDaemonProcess(1, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
duplicateDaemonRejected = true;
|
||||
}
|
||||
assert(duplicateDaemonRejected && timerGroups[1] == 7);
|
||||
bool daemonTeardownRejected = false;
|
||||
try {
|
||||
timerKernel.terminateProcess(6, timerGroups);
|
||||
} catch (const std::logic_error&) {
|
||||
daemonTeardownRejected = true;
|
||||
}
|
||||
assert(daemonTeardownRejected && timerGroups[1] == 7);
|
||||
|
||||
remorse::KeyEvent keyboardEvent{0x41, 0x1e, 1, 2, 3, 1, 4, 5};
|
||||
const remorse::KeyEvent lastEvent{0x42, 0x30, 6, 7, 8, 9, 10, 11};
|
||||
keyboard->extra[0] = 0x31;
|
||||
assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x11, 0, keyboardEvent, lastEvent));
|
||||
assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 1, keyboardEvent, lastEvent));
|
||||
assert(keyboardEvent.character == 0x41 && keyboard->extra[0] == 0x31);
|
||||
keyboardEvent.field8 = 0;
|
||||
assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent));
|
||||
keyboardEvent.field8 = 1;
|
||||
keyboardEvent.character = 0;
|
||||
assert(!remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent));
|
||||
keyboardEvent.character = 0x41;
|
||||
assert(remorse::KeyboardProcess::handleKeyEvent(*keyboard, 0x10, 0, keyboardEvent, lastEvent));
|
||||
assert(std::memcmp(&keyboardEvent, &lastEvent, sizeof(keyboardEvent)) == 0);
|
||||
assert(keyboard->extra[0] == 0x21);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,98 @@
|
|||
#include "remorse/file_system.h"
|
||||
#include "remorse/runtime.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <exception>
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
int main()
|
||||
#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
|
||||
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_WNDW);
|
||||
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW);
|
||||
#endif
|
||||
remorse::installCrashDiagnostics();
|
||||
assert((GetErrorMode() & SEM_NOGPFAULTERRORBOX) != 0);
|
||||
#ifdef _DEBUG
|
||||
assert((_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_REPORT_MODE) & _CRTDBG_MODE_WNDW) == 0);
|
||||
assert((_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_REPORT_MODE) & _CRTDBG_MODE_DEBUG) != 0);
|
||||
assert((_CrtSetReportMode(_CRT_ERROR, _CRTDBG_REPORT_MODE) & _CRTDBG_MODE_WNDW) == 0);
|
||||
#endif
|
||||
|
||||
wchar_t executable[MAX_PATH]{};
|
||||
if (GetModuleFileNameW(nullptr, executable, MAX_PATH) == 0) {
|
||||
return 1;
|
||||
}
|
||||
std::wstring commandLine = L"\"" + std::wstring(executable) + L"\" --crash-probe";
|
||||
SECURITY_ATTRIBUTES pipeSecurity{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
|
||||
HANDLE readPipe = nullptr;
|
||||
HANDLE writePipe = nullptr;
|
||||
if (!CreatePipe(&readPipe, &writePipe, &pipeSecurity, 0)) {
|
||||
return 1;
|
||||
}
|
||||
if (!SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0)) {
|
||||
CloseHandle(readPipe);
|
||||
CloseHandle(writePipe);
|
||||
return 1;
|
||||
}
|
||||
STARTUPINFOW startup{};
|
||||
startup.cb = sizeof(startup);
|
||||
startup.dwFlags = STARTF_USESTDHANDLES;
|
||||
startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
|
||||
startup.hStdOutput = writePipe;
|
||||
startup.hStdError = writePipe;
|
||||
PROCESS_INFORMATION child{};
|
||||
if (!CreateProcessW(nullptr, commandLine.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW,
|
||||
nullptr, nullptr, &startup, &child)) {
|
||||
CloseHandle(readPipe);
|
||||
CloseHandle(writePipe);
|
||||
return 1;
|
||||
}
|
||||
CloseHandle(writePipe);
|
||||
const DWORD waitResult = WaitForSingleObject(child.hProcess, 5000);
|
||||
if (waitResult == WAIT_TIMEOUT) {
|
||||
TerminateProcess(child.hProcess, 2);
|
||||
WaitForSingleObject(child.hProcess, INFINITE);
|
||||
}
|
||||
char buffer[512];
|
||||
DWORD count = 0;
|
||||
std::string crashOutput;
|
||||
while (ReadFile(readPipe, buffer, sizeof(buffer), &count, nullptr) && count != 0) {
|
||||
crashOutput.append(buffer, count);
|
||||
}
|
||||
DWORD exitCode = 0;
|
||||
const BOOL gotExitCode = GetExitCodeProcess(child.hProcess, &exitCode);
|
||||
CloseHandle(readPipe);
|
||||
CloseHandle(child.hThread);
|
||||
CloseHandle(child.hProcess);
|
||||
if (!gotExitCode || waitResult != WAIT_OBJECT_0 || exitCode != 1 ||
|
||||
crashOutput.find("Unhandled C++ exception: diagnostic probe") == std::string::npos) {
|
||||
std::fprintf(stderr, "Crash probe wait=%lu exit=0x%08lX output=%s\n",
|
||||
waitResult, exitCode, crashOutput.c_str());
|
||||
return 1;
|
||||
}
|
||||
#endif
|
||||
const auto root = remorse::findGameDataRoot(std::filesystem::current_path());
|
||||
assert(root.has_value());
|
||||
assert(root->hasExecutable);
|
||||
|
|
|
|||
54
rebuild/remorse/tests/isometric_controls_tests.cpp
Normal file
54
rebuild/remorse/tests/isometric_controls_tests.cpp
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
#include "remorse/isometric_controls.h"
|
||||
#include "remorse/map_renderer.h"
|
||||
|
||||
#include <cassert>
|
||||
|
||||
int main()
|
||||
{
|
||||
assert(remorse::controllerWalkRequested(0));
|
||||
assert(!remorse::controllerWalkRequested(0x01));
|
||||
assert(!remorse::controllerWalkRequested(0x02));
|
||||
assert(!remorse::controllerWalkRequested(0x40));
|
||||
assert(remorse::controllerWalkRequested(0x41));
|
||||
assert(remorse::controllerWalkRequested(0x42));
|
||||
constexpr remorse::s32 originX = 1024;
|
||||
constexpr remorse::s32 originY = 2048;
|
||||
const remorse::ScreenPoint origin = remorse::projectToScreen({originX, originY, 0});
|
||||
|
||||
const auto east = remorse::worldPositionAtScreenOffset(originX, originY, 1.0, 0.0);
|
||||
const remorse::ScreenPoint eastProjection = remorse::projectToScreen({
|
||||
static_cast<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;
|
||||
}
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
#include "remorse/file_system.h"
|
||||
#include "remorse/fixed_map.h"
|
||||
#include "remorse/map_renderer.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <filesystem>
|
||||
|
||||
|
|
@ -21,5 +23,33 @@ int main()
|
|||
assert(!image->pixels.empty());
|
||||
assert(image->decodedItemCount > 0);
|
||||
assert(image->paintedItemCount > 0);
|
||||
|
||||
const auto fixedPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "FIXED.DAT");
|
||||
assert(fixedPath.has_value());
|
||||
const auto archive = remorse::loadFixedMapArchive(*fixedPath);
|
||||
assert(archive.has_value());
|
||||
const auto fixedMap = remorse::loadFixedMap(*archive, options.mapIndex);
|
||||
assert(fixedMap.has_value());
|
||||
remorse::s32 minX = fixedMap->entries.front().x;
|
||||
remorse::s32 minY = fixedMap->entries.front().y;
|
||||
remorse::s32 maxX = minX;
|
||||
remorse::s32 maxY = minY;
|
||||
for (const remorse::FixedMapEntry& entry : fixedMap->entries) {
|
||||
minX = std::min(minX, static_cast<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));
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
70
rebuild/remorse/tests/map_sorter_tests.cpp
Normal file
70
rebuild/remorse/tests/map_sorter_tests.cpp
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
#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 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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue