Enhance animation and control tests; improve rendering and shape loading validation

- Added tests for player animations in animation_archive_tests to ensure all animations are loaded correctly.
- Updated entity_dispatch_entry_tests to validate animation direction updates and added tests for sixteen-direction animations.
- Expanded isometric_controls_tests with comprehensive key event handling and action requests for various controller states.
- Improved map_renderer_tests by adding viewport rendering tests to compare unbounded and bounded views.
- Enhanced shape_archive_tests to validate shape frame loading and decoding consistency.
This commit is contained in:
Maddo 2026-10-07 00:18:08 +02:00
commit a76b071049
28 changed files with 1608 additions and 154 deletions

View file

@ -0,0 +1,86 @@
# Pentagram Rendering Compared With The Windows Rebuild
## Scope
This note compares the checked-in Pentagram renderer with the current native renderer in `rebuild/remorse`. It describes source-level behavior, not a claim that Pentagram is a pixel-perfect Crusader reference or that its code can be dropped into the rebuild unchanged. The Pentagram tree was inspected read-only; no game data or generated scene data was copied between repositories.
## Summary
Pentagram renders the current world view from live map items on each paint. It activates map chunks around the camera, adds only those chunk items to a per-frame display list, rejects fully clipped sprites before sorting, resolves overlapping-item order, and draws each frame directly to a clipped software surface.
The rebuild instead constructs a player-centered bitmap, stores it as a scene backing image, and paints a crop of that image plus a separate player patch. A full-scene refresh reconstructs the item/node list and sort order, then replaces the backing image. The camera-prefetch change starts that refresh before the crop is exhausted, but it is still a whole-scene refresh rather than Pentagram-style active-area rendering.
The main transferable idea is therefore **spatially bounded live rendering**, not a different graphics API. Pentagram's order resolver and game-specific item rules still need Crusader verification before reuse.
## Pipeline Comparison
| Concern | Pentagram | Current Windows rebuild |
|---|---|---|
| World candidates | `CurrentMap` stores items in a 64 x 64 grid. `GameMapGump::PaintThis` visits active (`fast`) chunks only. | `collectSceneItems` stages fixed/live items and expands glob contents for the render. Full-scene options currently have no world rectangle, so the full item set participates in each scene render. |
| Camera/visibility | `CameraProcess::GetLerped` updates a screen-space fast area. `CurrentMap::updateFastArea` uses coarse chunk bounds plus a projected chunk-rectangle check and a margin around the viewport. | A 2560 x 1440 player-centered backing image is cropped for the 1280 x 760 client. Near the crop margin, the UI asks the worker to build a new backing image around the player. |
| Sprite culling | `ItemSorter::AddItem` gets frame bounds and calls `RenderSurface::CheckClipped` before adding a sprite to the dependency/sort list. The software painter also clips rows and pixels. | Scene nodes are prepared and sorted before `MapSceneRenderer::render` tests their rectangles against the output crop. The output loop avoids painting off-crop nodes, but most have already incurred node preparation and sort work. |
| Draw order | `ItemSorter` incrementally builds overlap dependencies from item bounding boxes, including occlusion tests, then recursively paints dependencies before their dependents. | `prepareRenderNodes` builds a complete vector of sort items and `resolveRenderOrder` computes a full order for the collected render set. |
| Allocation reuse | `ItemSorter` recycles `SortItem` objects and each item's dependency-list nodes between display lists. | Vectors are reserved per render, but scene items, render nodes, sort items, and order are rebuilt on every render. Decoded frames are cached by shape/frame in `MapSceneRenderer`; the parsed-frame table is local to a render call. |
| Shape representation | `ShapeArchive::cache` loads a `Shape` on demand and retains it in the archive. Each `Shape` retains `ShapeFrame` metadata; `ShapeFrame` keeps line offsets and compressed RLE bytes, which the software painter walks directly. | Shape frames are decoded into pixel buffers and palette colors for rendering. The decoded-frame cache persists on the renderer, while scene nodes and ordering do not. |
| Pixel destination | The normal `RenderSurface::SetVideoMode` path requests an SDL software surface. `SoftRenderSurface` paints shape RLE directly into it; `EndPainting` presents with `SDL_Flip`. | The renderer fills a 2560 x 1440 `RenderedMapImage`, converts it to BGR DIB pixels, and `paintWindow` copies the visible crop, overlays the player patch, then calls `StretchDIBits`. |
| Update cadence | `GUIApp::paint` paints the desktop/gump tree each frame. `GameMapGump` obtains an interpolated camera position and builds/paints the world display list for that view. | The UI paints the cached scene crop each window paint. A background worker handles player patches and full backing-image refreshes; ordinary movement does not rebuild the full image unless a recenter or world mutation requires it. |
## Pentagram Details
### Active Map Area
`CurrentMap` keeps a chunk grid and a separate fast-area bitset. For Crusader, the chunk size is 1024 world units; the same class uses 512 for Ultima VIII. `updateFastArea` expands the camera's from/to bounds by viewport and chunk margins, checks a coarse chunk range, then calls `ChunkOnScreen` to test projected chunk bounds. `setChunkFast` and `unsetChunkFast` notify items entering or leaving the active area.
`CameraProcess::GetLerped` updates this area using the camera's interpolated interval. This keeps world activation ahead of camera movement rather than waiting until a fixed offscreen bitmap is exhausted.
### Display List And Visibility
`GameMapGump::PaintThis` calls `BeginDisplayList` with the interpolated camera, loops the chunk grid, skips chunks that are not fast, and submits items from active chunks. It also applies runtime filters for roofs, editor objects, and the special invisible-avatar case.
`ItemSorter::AddItem` obtains the shape frame and its dimensions, computes world and projected bounding boxes, and rejects fully clipped sprite rectangles before doing overlap/dependency work. Visible candidates are compared with existing candidates; overlap and occlusion relationships become dependency links. `PaintDisplayList` walks those links so objects behind an occluder paint first and fully occluded nodes are skipped.
This is not a simple global depth sort. It models Crusader/U8 item overlap rules using footpad bounds and projected geometry. It is also not automatically faster for every workload: each accepted item compares against earlier list entries, so a crowded active area can make insertion expensive. Pentagram gets its benefit primarily from limiting the candidate set and clipping before dependency construction.
### Shape And Pixel Path
`ShapeArchive::getShape` calls `cache`; a loaded `Shape` is retained in the archive's indexed shape vector. `Shape` creates frame objects once. `ShapeFrame` stores dimensions, offsets, line offsets, and an RLE data pointer. `SoftRenderSurface.inl` walks those runs and maps palette indices directly to destination pixels, with per-line and per-pixel clipping. It does not first expand every frame into a full RGB bitmap.
The standard surface is software-backed in the checked-in implementation: `RenderSurface::SetVideoMode(..., use_opengl=true)` reports OpenGL disabled, and the normal path selects `SDL_SWSURFACE` plus `SoftRenderSurface`. There is conditional D3D code behind an experimental compile flag, but it is not the default path.
## Differences That Matter For The Rebuild
1. **Selection happens too late in the rebuild.** The current full render creates nodes and resolves order for the full map before the final output-crop intersection. Pentagram's fast chunks reduce the set before its display list is sorted, and its clip test rejects off-surface frames before dependency insertion.
2. **The rebuild has a backing-image boundary.** Crossing its prefetch threshold triggers a full scene render and replacement. Pentagram shifts the active world area with the camera and paints the current surface every frame; it does not need to rebuild a large player-centered bitmap to move the view.
3. **The rebuild repeats preparation work.** Decoded pixels are retained, but scene collection, render-node construction, and order resolution are repeated for each full refresh. Pentagram also rebuilds a display list each paint, but does so only for active chunks and reuses its node/dependency allocations.
4. **The pixel strategies differ.** Pentagram pays the RLE walk and palette conversion while drawing clipped pixels. The rebuild pays frame decode and buffer memory up front, then copies RGB pixels during rasterization and DIB presentation. Which wins depends on active-item count, sprite coverage, and movement; source inspection alone does not establish a universal timing winner.
5. **Their sorting contracts are related, not identical.** The rebuild already ports several `ItemSorter` concepts, but Pentagram's `SortItem` flags, overlap tests, transparency behavior, roof rules, and insertion/dependency order should be compared case-by-case before claiming parity.
One instrumented map-1 launch of the rebuild after widening the initial scene selection produced 16,542 render candidates, 16,540 decoded nodes, and 1,355 painted nodes. The initial scene published in about 0.76 seconds on that run. This is evidence that scene creation is currently sub-second on this machine, but it also shows that most prepared nodes did not touch the initial viewport. It does not measure repeated camera recentering or establish how long a crowded region takes.
## Practical Directions
1. Add a native spatial index over map chunks or projected bounds. Query only chunks intersecting the camera's visible area plus a measured overscan margin; update membership before the player reaches the edge. Preserve a conservative overlap margin for tall sprites and glob contents.
2. Use conservative sprite bounds from TYPEFLAG dimensions and frame metadata to reject offscreen candidates before full pixel decoding and order resolution. Keep the final per-pixel clip as the correctness boundary.
3. Reuse stable render-node and sorting storage, or cache static-map preparation separately from mutable/live items. Invalidate only when relevant map content changes; do not reuse a stale sorted list across changed flags, positions, frames, globs, or roofs.
4. Keep avatar animation work independent in priority from whole-scene refreshes. The current worker now publishes the player patch before a full scene render and coalesces camera-prefetch requests; measure whether that removes the observed animation stall before adding a second concurrent renderer.
5. Instrument per-frame counts and durations: chunks visited/active, items submitted, rejected by clip, decoded-frame cache hits/misses, sort comparisons, nodes painted, and time in collection/sort/raster/presentation. This will identify whether chunk activation, early culling, cache reuse, or incremental redraw has the best payoff.
Pentagram's 6 x 5 dirty-tile renderer documented in the original Crusader draw-list analysis is a separate original-executable mechanism; it should not be inferred from Pentagram's `CurrentMap` fast chunks. Fast chunks activate world objects, while Pentagram's checked-in `GameMapGump` still paints its display list to the current render surface each frame.
## Source References
### Pentagram
- [`GameMapGump::PaintThis`](../../../misc/pentagram/gumps/GameMapGump.cpp)
- [`ItemSorter::BeginDisplayList`, `AddItem`, and `PaintDisplayList`](../../../misc/pentagram/world/ItemSorter.cpp)
- [`CurrentMap::updateFastArea`, `ChunkOnScreen`, and fast-area transitions`](../../../misc/pentagram/world/CurrentMap.cpp)
- [`CameraProcess::GetLerped`](../../../misc/pentagram/world/CameraProcess.cpp)
- [`ShapeArchive::getShape` and `cache`](../../../misc/pentagram/graphics/ShapeArchive.cpp)
- [`Shape` frame loading](../../../misc/pentagram/graphics/Shape.cpp), [`ShapeFrame`](../../../misc/pentagram/graphics/ShapeFrame.cpp), and [`SoftRenderSurface` RLE painter](../../../misc/pentagram/graphics/SoftRenderSurface.inl)
- [`RenderSurface` backend selection](../../../misc/pentagram/graphics/RenderSurface.cpp), [`GUIApp::paint`](../../../misc/pentagram/kernel/GUIApp.cpp), and [`BaseSoftRenderSurface::EndPainting`](../../../misc/pentagram/graphics/BaseSoftRenderSurface.cpp)
### Native Rebuild
- [`MapSceneRenderer::render`, item collection, and node preparation](../rebuild/remorse/src/map_renderer.cpp)
- [`fullSceneOptions`, `startLiveRenderer`, `paintWindow`, and camera-prefetch requests](../rebuild/remorse/src/windowed_game_main.cpp)
- [Original draw-list/tile-visibility notes](raw-0007-rendering.md)

View file

@ -123,6 +123,19 @@ Work:
Exit criteria: the user can launch the host build, view a map, move the camera/avatar test object, and observe stable tick/update behavior.
#### ScummVM-Style Live Viewport, Zoom, And Smooth Camera
After live item state and source draw-order behavior are available, replace the fixed player-centered scene bitmap as the primary world-rendering path with a live viewport renderer based on ScummVM's useful architecture: select nearby world candidates, clip before sorting, build a reusable display list, and paint the current view each frame. Retain the fixed-scene/offline renderer as a diagnostic and regression oracle during migration. Do not copy `CurrentMap` fast-area activation directly for render culling: ScummVM's fast-area enter/leave callbacks also affect gameplay objects.
1. **Bound render candidates:** index fixed, live, and expanded-glob items by world chunk or another measured spatial structure. Query the camera's visible world bounds plus an overscan margin; keep this render set separate from gameplay activation and process scheduling.
2. **Cull before sorting:** compute conservative projected frame bounds, reject candidates outside the viewport clip before decoded-frame misses and dependency comparisons, and retain final per-pixel clipping. Preserve Crusader-specific overlap/order rules and add regressions for tall sprites, roofs, transparency, flipped frames, inventory items, and player overlays.
3. **Reuse per-frame work:** reuse display-list, node, dependency, and frame-cache storage. Invalidate cached geometry/order on position, frame, flag, roof, glob-hatch, or world-mutation changes. Measure candidate counts, clip rejects, sorter comparisons, allocations/cache hits, and collection/sort/raster/presentation time before selecting an indexed-frame or palette-expanded cache policy.
4. **Separate camera projection:** represent camera position and zoom independently of avatar/world state. Centralize world-to-screen projection and its inverse; derive the queried world bounds and sprite clip bounds from viewport dimensions and zoom. Keep HUD and window controls in screen space. Preserve a pixel-art-friendly sampling policy and test zoom limits, viewport resize, and edge clipping.
5. **Add optional smooth follow:** keep the recovered/legacy camera behavior as the parity mode and add a selectable host-only smooth-follow mode. Interpolate camera position using elapsed time toward a configurable target/offset, independent of the fixed simulation tick; apply zoom around a stable screen anchor so zoom changes do not jump the avatar. Camera motion must not alter gameplay coordinates, animation state, or simulation tick counts.
6. **Integrate animation and presentation:** choose animation frames from simulation state and render interpolation without blocking camera updates on a full-scene rebuild. Keep mutable/player animation responsive while scene candidates are gathered and painted; remove the backing-image recenter dependency from the normal viewport path only after the live path meets parity and performance gates.
Exit criteria: deterministic tests cover camera projection/inverse bounds, zoom in/out and resize, smooth-camera convergence at different frame rates, and unchanged world/avatar state under camera-only motion. A retail map regression checks item ordering, clipping, animation, and screen-edge behavior at minimum/default/maximum zoom. Profiling demonstrates bounded candidate/sort work and no camera-induced animation stalls. The smooth-follow mode remains opt-in and is documented as a modernization, not original-binary parity.
### Phase 6: USECODE / VM Runtime
Goal: execute game scripts from original `EUSECODE.FLX`.
@ -277,7 +290,7 @@ The `Item_Grab` creation branch applies the verified `FUN_11d0_3f95(itemNumber,
The first Phase 6 resource slice is compiled into `remorse_core`: a bounded `EUSECODE.FLX` class/name/event-body reader follows the owner-loaded `classId + 2`, 13-byte name-table, `+0x14` six-byte row, and `codeBase + relativeOffset - 1` body rules verified in `docs/raw-000a-000d.md`. Retail tests confirm `EVENT` (`class 0x361`, slot `0x0a`, code base `0xd4`, body length `0x1fd6`) and `RECHFLNS` (`class 0x138`, release slot `9`, body length `102`, owner mask `0x200`). Raw extracted `CARD_NS`, `BOX_NS`, and `RECHFLNS` bodies confirm a 14-byte metadata prefix followed by the first opcode at offset `0x0e`; its exact field meanings remain unknown. The named offset is shared by the host task runner and tested against these retail bodies. Retail integration tests execute `CARD_NS` spawning `SWITCH` and `BOX_NS` through timer yields to a changed item frame and rendered scene. The Windows diagnostic release callback also resolves and queues an eligible body, but this is host-side dispatch and task initialization, not `Usecode_ItemCallEvent` or `EntityVmContext::CreateFromSlotIndex`. The interpreter covers only a subset of opcodes/services, and unsupported operations halt tasks; original context memory, far-pointer execution, general event dispatch, and runtime parity remain open. The recovered `CreateFromSlotIndex` call selects a class/slot and passes a four-byte parameter into `Inter_1418_0244` (`1418:0244`) and `Interpreter_1418_00e8` (`1418:00e8`). Even the short `RECHFLNS` release event branches through item surface-weight logic and `FREE.slot_33`; the current host service table does not complete that path.
The walk/run modifier choice is the isolated branch from `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. The same selector's Num Lock-off directional scan branch (`0x47/48/49/4b/4d/4f/50/51`) is now compiled in the controls helper, regression-tested across all eight mappings, and called by Win32 movement polling. Win32 still supplies modifiers and held-key state; NPC state, weapon-dependent actions, original keyboard events, and the remainder of the controller selector are not ported. Retail ANIM.DAT regression checks retain the signed reverse steps in the decoder while testing the host-only forward movement filter across all four affected walk directions.
The Windows controller slice now consumes queued key events through the registered host keyboard-process subscription. It preserves the original event-mode (`KeyEvent +0x08`) and press/release (`+0x09`) bytes, translates Shift/Caps Lock and Alt/Ctrl modifier bits, and implements the recovered Num Lock-off eight-direction mappings plus Num Lock-on relative turns and facing-aligned forward/reverse requests. Walk/run selection follows `Controller_PickNextAnimByKeyevent` (`1130:12d6`) and `KeyEvent_IsShiftDown` (`11c8:016c`): bits `1|2` select Shift, bit `0x40` selects Caps Lock, and walk is selected when their Boolean states match. The current action subset maps the recovered Alt/Ctrl animation indices, loads the corresponding player clips from ANIM.DAT, advances valid stationary animation frames, and retires one-shot animation processes on clip completion or blocked movement. Focused tests cover event transitions, modifier isolation, Num Lock modes, action selection, and retail clip/frame references. This remains a host controller model: `Controller_PickNextAnimByKeyevent`'s full NPC busy/dead/stasis branches, weapon-dependent paired actions, crosshair/target updates, complete turn handling, original controller process dispatch, vertical jump response, and exact original collision response are not ported. Host 40 Hz timing and map collision remain approximations; the source scheduler does not yet drive this player path.
On Windows, `remorse_game.exe`, `remorse_rebuild.exe`, and `remorse_map_preview.exe` configure crash reports at startup. All CTest binaries now link a test-only startup initializer for the same diagnostics, so an assertion before `main` cannot open an Abort/Retry/Debug modal that blocks the build terminal. The timeout-bounded child probes exercise both a Debug CRT assertion and C++ termination, verifying prompt-free nonzero exits. The terminate handler reports active C++ exception messages to the Visual Studio Debug output and stderr when available. Escaped/unhandled Windows exceptions log their code/address and suppress the fault popup. The GUI executable has no console stderr by default, so attach a debugger to see that output. This does not replace a full crash dump or catch process termination that bypasses user-mode handlers.
@ -535,6 +548,18 @@ python rebuild/remorse/tools/import_export_slice.py classes/Remorse/EntityDispat
After the first source-backed interaction, complete the original player/item loop, save/load, combat, mission flow, audio, frontend, and retail-map coverage. Keep the current preview and window as test hosts until recovered runtime behavior replaces their stand-ins.
## Track B Recovery Work Order
Use this sequence to move the normal Windows launch path from host-modeled behavior back to the intended decompiled-source port. Keep the current executable, data readers, preview, and tests; treat host gameplay implementations as temporary until their original call paths replace them.
1. **Freeze and classify the normal path:** do not add more host-only gameplay behavior to the default launch path. For startup, ticking, input, movement, interaction, and drawing, record the controlling original function/address, current host implementation, required host-service boundary, and status as translated, verified, or stand-in. Keep diagnostic-only behavior behind `--diagnostics`.
2. **Prove the source-to-build pipeline:** choose a small, already-understood exported function used by the runtime (for example, a process sleep/timer primitive), clean its types, globals, layout, and calling convention, then compile and link that implementation into `remorse_core`. Replace the matching host-authored behavior with this compiled function and test its state changes against the export and Ghidra evidence. The import helper is staging only; do not count a staged export or isolated test as integrated.
3. **Restore the original startup and tick path:** port the minimum dependency chain for `Game_Start` (`1020:0000`), teleporter placement/waiting, kernel scheduler, timer, and item/NPC ownership. Route normal startup and simulation through these compiled functions; retain modeled startup and host polling only as diagnostics until parity checks pass.
4. **Move player behavior onto that path:** replace host-created avatar/controller state, movement-step policy, and approximate collision with the recovered item, keyboard, controller, animation, and collision call chain. Feed Win32 input and timing into explicit host-service adapters; the game logic must not depend directly on Win32 APIs.
5. **Reconnect presentation and interaction:** render the live mutable world through recovered draw-list/order and camera behavior, then complete one reachable map-1 interaction through original item search, event dispatch, VM execution, and a visible world mutation. Keep the static preview as a regression oracle, not the normal gameplay renderer.
6. **Gate each replacement:** for every slice, record source address, exported function, unresolved decompiler assumptions, host substitutions, and tests; verify it is compiled into and called by `remorse_game`. Remove a stand-in from the normal path only after deterministic behavior checks pass. Update the function counts and parity status in this roadmap as slices land.
7. **Preserve the portability path:** keep recovered game logic and resource formats platform-neutral, with Win32 window/input/timing services behind replaceable interfaces. Once the original loop works through those interfaces, select and validate a portable host such as SDL; do not count the current Win32-only window as multi-platform support.
## Near-Term Next Actions
1. **Close the event path:** identify and reach an eligible retail `use` target from the actual level-start pad at `(30328, 29656, 16)`. The exact production-equivalent search at egg `0x1e` still returns one candidate and no eligible event, but that is the intermediate staging point, not the current avatar location; rerun the search from the destination. Map-wide evidence includes the inactive/map-array `PANELNS`, a `CARD_NS` whose authorized state requires keycard 6, and a frame-0 `CHEST_EW` at staged `(1087, 2559, 0)` whose recovered handler attempts a legal shape swap to `0x054b` before animating. The host implements `Item.setShape` (`0x24`), but `FREE.slot_2d`'s family check, `Item.legal_create`, and temporary-item lifecycle are still missing; the chest's collision route is unverified. Next prove reachability and implement only the required recovered services, then exercise owner selection, context creation, VM execution, and a process/world-state effect. The BOX_NS regression still verifies candidate-driven selection and visible frame output from a fixture origin only; it does not close this action or establish `Usecode_ItemCallEvent` parity.

View file

@ -0,0 +1,86 @@
# ScummVM Rendering Compared With The Windows Rebuild
## Scope
This note compares the current ScummVM Ultima 8 engine's Crusader rendering path with `rebuild/remorse`. ScummVM is a modern reimplementation, not an exact transcription of every original runtime behavior. Its source is useful as an implementation and data-format reference, but original-binary parity still requires separate verification. The ScummVM checkout was inspected read-only; no ScummVM code or game data was copied into this repository.
## Summary
ScummVM renders the current viewport from live world items. `CurrentMap` maintains a camera-relative fast area over a 64 x 64 chunk grid. `GameMapGump` collects objects from active chunks, and `ItemSorter` rejects completely clipped frame rectangles before constructing overlap dependencies and drawing. Shape data is cached by the archive; raw RLE frames are expanded once into retained 8-bit indexed `ShapeFrame` surfaces. Each paint maps those indexed pixels through the shape palette into ScummVM's managed screen surface.
The native rebuild instead collects a map scene, prepares and orders render nodes, draws a player-centered backing bitmap, and copies a crop of that bitmap to the window. It currently processes the full map item set for full-scene renders, then uses a background worker to recenter the bitmap and render the player patch. It caches decoded frames, but rebuilds the node/order structures for each full scene render.
The strongest ScummVM ideas for the rebuild are active-area candidate selection and early frame-rectangle culling. Its fast-area machinery also drives item lifecycle behavior, and its sorter is game-specific; neither should be copied as a rendering-only optimization without preserving those contracts.
## Pipeline Comparison
| Concern | ScummVM | Current Windows rebuild |
|---|---|---|
| World candidates | `CurrentMap` stores map items by chunk. `GameMapGump::PaintThis` visits the 64 x 64 grid and submits items only from chunks marked fast. | `collectSceneItems` stages fixed/live records and expands globs. Full-scene options currently omit `worldRect`, so all renderable map items enter full-scene preparation. |
| Camera and active area | `CameraProcess::GetLerped` updates `CurrentMap::updateFastArea` over the camera's from/to positions. Coarse chunk bounds are refined using projected chunk rectangles and a viewport margin. | `paintWindow` crops a 2560 x 1440 player-centered backing image. Near a crop margin it queues a background full-scene recenter. |
| Early visibility | `ItemSorter::AddItem` fetches frame dimensions, computes the projected frame rectangle, and rejects a rectangle outside the render clip before overlap/dependency sorting. | `prepareRenderNodes` prepares and orders items before `MapSceneRenderer::render` intersects node rectangles with the output crop. The raster loop avoids off-crop pixels, but off-crop nodes have already been prepared and sorted. |
| Occlusion/order | `SortItem::below`, `overlap`, and `occludes` drive dependency links and painter order. ScummVM adds Crusader-specific sprite and inventory-item ordering fields/rules. | A complete sort-item vector is passed to `resolveRenderOrder`; this ports several Pentagram/ScummVM geometry rules but is rebuilt for each full render. |
| Sort storage | `GameMapGump` constructs `ItemSorter(2048)`. `BeginDisplayList` recycles the prior list into an unused pool; more nodes are allocated if needed. Per-item dependency storage is also reused. | Render vectors reserve capacity per call, but scene items, nodes, sort items, and the resolved order are reconstructed each full render. |
| Shape cache | `ShapeArchive::getShape` lazily caches a `Shape` by shape number. `Shape` builds `ShapeFrame` objects once; each frame retains a decoded CLUT8 pixel surface. | `MapSceneRenderer` retains decoded `DecodedShapeFrame` entries by shape/frame, including palette-expanded pixel colors. Parsed frame collections are local to a render call. |
| Pixel path | `RenderSurface::Paint` walks the cached indexed frame surface and maps pixels through the palette into a `Graphics::ManagedSurface`. The engine paints the gump tree, ends painting, and calls `Graphics::Screen::update()`. | The renderer creates a `RenderedMapImage`, converts it to BGR DIB pixels, copies the visible crop, overlays a separate player patch, and calls `StretchDIBits`. |
| Update cadence | `Ultima8Engine::paint` paints the desktop/gump tree each frame; `GameMapGump` rebuilds and paints the current display list at the interpolated camera position. | The window paints the cached bitmap on `WM_PAINT`; a worker handles player patches and occasional full-scene recentering. Player patch work is now published before a full refresh. |
## ScummVM Details
### Camera-Relative Fast Area
`CurrentMap` uses a 64 x 64 chunk grid. Its chunk size is 1024 world units for Crusader and 512 for Ultima VIII. `updateFastArea` builds a projected screen-space region from the camera's `from`/`to` positions and map-gump dimensions, expands it by a coarse margin, then checks candidate chunks with `ChunkOnScreen`. Chunks changing state call `setChunkFast` or `unsetChunkFast`, which notify their items through `enterFastArea` and `leaveFastArea`.
The camera calls this update while interpolating. Therefore the active area follows camera movement before the viewport reaches its new position. Importantly, fast-area transitions are also gameplay lifecycle events: eggs and other items can perform work on entry/exit. A native renderer should initially build a separate render-candidate index unless it is also ready to model those world-state transitions.
### Clipped Display List And Crusader Ordering
`GameMapGump::PaintThis` obtains the interpolated camera, determines a roof Z limit, begins a display list with the surface clip rectangle, and submits eligible items from fast chunks. It filters roof/editor content and preserves a special path for the invisible main actor. `ItemSorter::AddItem` computes footpad and frame bounds, then skips a frame that does not intersect the clip before scanning existing visible entries for overlap and ordering dependencies.
`SortItem::below` includes geometry-based ordering plus special cases for Crusader sprites, inventory items, translucent/animated/flat pieces, roofs, and other shape flags. `PaintDisplayList` recursively paints dependencies and skips occluded nodes. There is an experimental occlusion grouping path behind `SORTITEM_OCCLUSION_EXPERIMENTAL`; it is not the default contract. Like Pentagram, insertion compares a new visible item against prior list entries, so reducing the active/clipped candidate count is central to keeping this sorter practical.
### Cached Indexed Frames And Managed Surface
`ShapeArchive::cache` loads a shape on first use and retains it in the archive's shape vector. `Shape` parses each raw frame into an intermediate `RawShapeFrame`, constructs a `ShapeFrame`, then releases the intermediate. `ShapeFrame` expands RLE into a `Graphics::Surface` in CLUT8 format and retains that indexed image. `RenderSurface::Paint` maps the indexed pixels through the shape's native palette into the active 8-, 16-, or 32-bit surface path supported by that method.
This differs from both nearby implementations: Pentagram's software painter walks RLE runs while drawing, while the rebuild stores palette-expanded decoded pixels in its renderer cache. ScummVM pays a one-time indexed-frame expansion and keeps palette mapping separate from frame pixels.
`Ultima8Engine::paint` wraps gump rendering with `BeginPainting`/`EndPainting` and then calls `_screen->update()`. The render surface is backed by ScummVM's `Graphics::ManagedSurface`/`Graphics::Screen`; this source path is a CPU pixel renderer feeding ScummVM's presentation system, not a dedicated GPU scene renderer.
ScummVM also has useful diagnostic hooks: `PAINT_TIMING` can report average paint time, and the debugger command `RenderSurface::benchmark <shape> <frame> <iterations>` measures normal, translucent, mirrored, invisible, and highlighted shape draws. Those hooks can guide a controlled comparison, but no ScummVM benchmark was run for this note.
## Differences That Matter For The Rebuild
1. **Candidate selection precedes ordering in ScummVM.** The rebuild's output crop is applied after node preparation and global ordering. A native chunk/spatial index plus conservative frame bounds could reject most map items before decode and sorting.
2. **ScummVM keeps rendering in world coordinates.** It doesn't depend on a player-centered cached map image with a recenter edge. The rebuild's current prefetch avoids waiting for that edge, but a full scene refresh still rebuilds the map-wide candidate/node/order pipeline.
3. **ScummVM separates frame color indices from screen format.** Its retained CLUT8 frames use less memory than a same-sized RGB cache and can be mapped for the current output format. The tradeoff is palette lookup during each draw. Benchmark memory, decode time, and raster time before changing the rebuild's RGB cache.
4. **Its active area is simulation-visible.** `enterFastArea`/`leaveFastArea` have item callbacks. Rendering-only culling should not deactivate gameplay objects or scripts by accident.
5. **The sorter is not an interchangeable library.** ScummVM's current comparison paths include Crusader-specific `_sprite`/`_invitem` flags, clip handling, and ordering corrections. Preserve local tests and compare these cases one by one rather than copying the entire class.
6. **The display-list pool doesn't eliminate sort cost.** It avoids repeated node allocation, but each paint still gathers active items, tests visible candidates pairwise, resolves dependencies, and rasterizes the display list. Benefits depend on keeping the fast area bounded.
## Practical Directions
1. Build a native chunk index over fixed/live map records and glob-expanded placements. Query the viewport plus a configurable overscan margin; keep its membership separate from gameplay activation until item enter/leave behavior is ported.
2. Move conservative projected frame-rectangle rejection ahead of node creation, decoded-frame misses, and dependency comparisons. Keep final pixel clipping for correctness.
3. Reuse node and dependency storage, or cache static geometry/order and update only mutable entries. Invalidate on position/frame/flag changes, glob hatch changes, roofs, transparency, and world-script mutations.
4. Benchmark the three frame representations explicitly: Pentagram's direct RLE walk, ScummVM's cached CLUT8 frame, and the rebuild's palette-expanded decoded frame. Measure a representative map and movement, not only an isolated sprite.
5. Record active chunk/item counts, clip rejects, frame-cache hits/misses, sorter comparisons, painted nodes, pixel coverage, and separate collection/sort/raster/present times. The rebuild's instrumented map-1 run previously produced 16,542 candidates, 16,540 decoded nodes, and 1,355 painted nodes in about 0.76 seconds for initial publication; repeated full recenter cost and animation contention need separate measurements.
The original Crusader executable's 6 x 5 dirty-tile draw system is a separate mechanism documented in [raw-0007-rendering.md](raw-0007-rendering.md). ScummVM's fast chunks control which world items are active and considered; they are not that original screen-tile dirty map.
## Source References
### ScummVM
- [`GameMapGump::PaintThis`](../../../misc/scummvm/engines/ultima/ultima8/gumps/game_map_gump.cpp)
- [`ItemSorter::BeginDisplayList`, `AddItem`, and `PaintDisplayList`](../../../misc/scummvm/engines/ultima/ultima8/world/item_sorter.cpp)
- [`SortItem` geometry and ordering rules](../../../misc/scummvm/engines/ultima/ultima8/world/sort_item.cpp)
- [`CurrentMap::updateFastArea` and chunk transitions](../../../misc/scummvm/engines/ultima/ultima8/world/current_map.cpp), [`CameraProcess`](../../../misc/scummvm/engines/ultima/ultima8/world/camera_process.cpp)
- [`ShapeArchive` lazy shape cache](../../../misc/scummvm/engines/ultima/ultima8/gfx/shape_archive.cpp), [`Shape` frame construction](../../../misc/scummvm/engines/ultima/ultima8/gfx/shape.cpp), and [`ShapeFrame` indexed decode](../../../misc/scummvm/engines/ultima/ultima8/gfx/shape_frame.cpp)
- [`RenderSurface`](../../../misc/scummvm/engines/ultima/ultima8/gfx/render_surface.cpp), [`Ultima8Engine::paint`](../../../misc/scummvm/engines/ultima/ultima8/ultima8.cpp), and [`RenderSurface::benchmark`](../../../misc/scummvm/engines/ultima/ultima8/misc/debugger.cpp)
### Native Rebuild
- [`MapSceneRenderer::render`, item collection, and node preparation](../rebuild/remorse/src/map_renderer.cpp)
- [`fullSceneOptions`, `startLiveRenderer`, and `paintWindow`](../rebuild/remorse/src/windowed_game_main.cpp)
- [Existing map-renderer format and sorting notes](map-rendering.md)