Crusader_Decomp/docs/scummvm/phase-0-evidence-compatibility-gate.md
Marco 3b2561b053 Add build scripts, documentation, and smooth camera analysis for ScummVM's Ultima VIII engine
- Introduced `build-scummvm.ps1` and `run-scummvm.ps1` scripts for building and running the ScummVM project with MSVC.
- Created `phase-0-evidence-compatibility-gate.md` to outline the evidence and compatibility gate for the Crusader project.
- Added `smooth-camera-analysis.md` detailing the proposed smooth camera behavior and regression checks.
- Documented the Visual Studio build process in `visual-studio-build.md`, including prerequisites and steps for generating the Ultima solution.
- Updated `startup-map-patch-file.md` to clarify the behavior of the fixed-map and glob archives in the GOG installation.
2026-10-09 16:59:29 +02:00

307 lines
No EOL
27 KiB
Markdown

# ScummVM Crusader Phase 0: Evidence and Compatibility Gate
**Status:** Work plan; no ScummVM source changes made
**Parent plan:** [ScummVM Crusader enhancement feasibility](../scummvm-crusader-enhancement-feasibility.md)
**Scope:** No Remorse and No Regret in ScummVM's Ultima VIII engine
## Purpose
Phase 0 establishes a trustworthy behavior and data-format baseline before adding player-facing features, external map content, or custom USECODE. Its job is to distinguish a verified retail rule from an implementation assumption, identify which differences are shared and which are variant-specific, and produce tests that can detect regressions without distributing game data.
This is an evidence and compatibility gate, not a content-mod implementation phase. It may add test fixtures, local-only comparison scripts, or narrow input-validation fixes if Phase 0 demonstrates that malformed data can reach an unsafe read. It must not change retail gameplay behavior merely to make the tests pass. Any such behavioral change should be proposed as a separately reviewed accuracy fix, backed by the evidence and regression case assembled here.
## Phase 0 Outcomes
At completion, the project should have:
1. A reproducible baseline for the exact ScummVM checkout, build configuration, and local Remorse and Regret game-data sets.
2. A per-variant discrepancy ledger that ties each claim to binary/source evidence and an observable regression test.
3. A closed or explicitly isolated answer for the Crusader USECODE class/event-count disagreement. Custom-script compatibility remains blocked while this is unresolved.
4. Deterministic movement, targeting-reticle, and manual-crosshair cases, including display-size changes and weapon/run animation states.
5. Read-only structural validation for retail and synthetic fixed-map, glob, and USECODE inputs, including malformed/truncated cases.
6. A no-regression smoke result showing that both supported games still start and play through the tested baseline paths.
Phase 0 does not need to settle every low-confidence behavior. An issue can pass the gate as **isolated** when the uncertainty is bounded, the implementation avoids making a new compatibility promise based on it, and a follow-up has a clear evidence path. The event-count discrepancy cannot be isolated while modified USECODE archives are being advertised or loaded as supported content.
## Scope Boundaries
### Included
- Remorse and Regret executable/data identity and evidence provenance.
- Existing ScummVM behavior at the source paths named in the discrepancy ledger.
- Running turns, especially with a weapon drawn; automatic target selection; the separate projectile crosshair.
- USECODE class headers, event tables, class/event range checks, and archive bounds.
- `static/fixed.dat` map records and `static/glob.flx` glob records.
- Retail startup, map transition, and save/load smoke paths needed to check that baseline behavior remains intact.
### Excluded
- The player cheat/debug gump, smooth camera feature, mod manager, custom mission launcher, and mod packaging.
- New weapons, enemies, items, or native intrinsics.
- Reimplementing the original DOS usecode debugger UI.
- Broad cleanup of ScummVM's Ultima VIII engine or unrelated U8 behavior.
- Distribution or check-in of retail executable, archive, save, screenshot, or extracted content bytes.
## Evidence Rules
Every ledger entry and test expectation should use these labels:
| Label | Meaning |
|---|---|
| `Retail-observed` | Reproduced in the named retail game build or directly verified in its executable/data. |
| `Decompiled` | Supported by a named function/address and its call/data context; note whether the evidence is Remorse, Regret, or both. |
| `ScummVM-source` | Directly observed in the recorded ScummVM revision and source path. |
| `Cross-implementation` | Appears in ScummVM and another implementation; useful evidence, not proof when retail data disagrees. |
| `Hypothesis` | Plausible interpretation awaiting a discriminating test or stronger source evidence. |
| `Synthetic-test` | Proven only against constructed inputs; do not present as retail parity. |
For every binary-derived claim, record the game, executable edition/language, SHA-256, and address convention. Do not infer Regret behavior from Remorse, or vice versa. Keep file addresses, segment:offset addresses, and any flattened addresses in separate fields. Preserve unknown bytes and raw values when a format interpretation is unsettled.
Retail game files remain local inputs. Test reports may include hashes, counts, class/event IDs, record indices, and mismatch descriptions, but not copied proprietary payloads. Commit only synthetic fixtures and code that is permitted by the repository's contribution rules.
## Baseline Capture
Before source or test changes, record the following in the Phase 0 run log:
| Area | Required record |
|---|---|
| ScummVM tree | Repository revision, dirty/clean state, and hashes of locally modified files relevant to the engine. Do not assume the checkout is pristine. |
| Build | Host OS/compiler, engine enablement, debug/release mode, renderer/backend, and exact build command. |
| Display | Logical render dimensions, host window dimensions, fullscreen/scaling settings, and whether the render surface can resize during a session. |
| Game data | Remorse/Regret edition, language, installed directory, and hashes/sizes for the executable and archives used by Phase 0. Keep paths private to the local run log if they expose user-specific directories. |
| Startup | Fresh game to controllable avatar; record map, spawn route, game variant, and any startup warnings. |
| Save/load | Create a save at a repeatable point, load it, and verify current map, controlled actor, weapon/combat mode, and camera state. |
| Evidence | Ghidra notes/export revision or evidence document, function/address, test input, expected result, actual result, and confidence. |
Capture at least the standard ScummVM Crusader rendering size and one materially larger viewport. Record actual dimensions; do not assume a configuration option changes the logical map viewport until measured. Use the same input sequence, game build, save state, and camera/avatar state for comparisons.
## Discrepancy Ledger
Keep this table as the Phase 0 index. Expand each row with links to a test case and evidence record as work proceeds.
| ID | Topic | Initial status | Current evidence and question | Phase 0 disposition |
|---|---|---|---|---|
| `MOVE-001` | Direction changes during running weapon animations | Open | Retail Remorse decomp notes accept start-run, start-run-small/large-weapon, and combat-run-small/large-weapon movement states. The checked-out ScummVM `_isAnimRunningWalking()` currently accepts only `run`, `combatRunSmallWeapon`, and `walk`, despite the local tap-turn note claiming the helper was widened. Reconcile the source/note mismatch and separately inspect Regret. | Exact eligible states and turn quantization are tested for each supported game; any remaining variant gap is explicit. |
| `AIM-001` | Auto-target eligibility changes with viewport size | Hypothesis, high priority | `GameMapGump::RenderSurfaceChanged()` resizes the world view to its parent. `CurrentMap::findBestTargetItem()` requires a partly-on-screen candidate, but its distance score only ranks candidates and imposes no maximum. Does the larger map viewport admit targets the original target scope excluded? What is the retail logical selection rectangle and its camera/actor anchor? | Same world state returns the same target at standard and expanded host sizes, using a retail-derived target bound if confirmed. If not confirmed, retain current behavior and block a parity claim. |
| `AIM-002` | Auto-target scoring and refresh | Open | ScummVM prioritizes occluder flag, actor status, then max-axis distance among candidates in the exact 16-direction bucket; target process refresh cadence is separate from manual aim. Verify retail candidate eligibility, tie-breaks, refresh triggers, and no-target behavior for both games. | Candidate order, tie cases, direction edges, broken/absent objects, movement refresh, and variant differences have expected results. |
| `AIM-003` | Manual projectile crosshair | Open | `CrosshairProcess` positions shape `0x4cc` at a fixed 400 world units using the mover combat angle. `Item::fire` may use that point when no target is selected. This is not the animated target reticle (`0x59a`). Verify origin, angle convention, height, weapon-dependent offsets, and target fallback separately. | Firing destination and crosshair position are independently tested with and without a selected target. |
| `UC-001` | Crusader event-count formula | Blocking for custom USECODE | ScummVM reads the dword at class bytes `8..11`, subtracts one for the class base, and computes event count as `(base + 19) / 6`. Local samples instead fit `(raw_dword - 20) / 6`; observed raw values include `0x00d4`, `0x00da`, and `0x00e6`, giving 32, 33, and 35 rows under the local rule. `Usecode::get_class_event()` warns for an event ID beyond the count but continues to read the six-byte row. Determine which layout is valid for each exact archive/build. | Formula is resolved per corpus/build, or custom USECODE remains explicitly unsupported. No silent fallback between formulas. |
| `MAP-001` | Fixed-map record extent | Open | ScummVM takes `size / 16` fixed records and reads 16 bytes per entry. A non-multiple-of-16 remainder is ignored by that loop; determine whether retail archives contain remainders and validate them. Check map archive entry count against the 256 map slots. | Retail records parse identically; truncated/remainder fixtures are rejected or reported before unsafe parsing. |
| `MAP-002` | Glob record extent and references | Open | ScummVM reads a little-endian `u16` item count followed by six-byte entries `(x,y,z,shape,frame)`. `MapGlob::read()` asserts that the stream is at least `2 + count * 6` bytes. Verify all retail entries, glob references from eggs, shape/frame validity, and safe failure behavior. | Retail glob contents and references validate; undersized synthetic input cannot reach an assertion or out-of-bounds read through any future mod path. |
| `VAR-001` | Shared behavior versus game-specific rules | Open | Remorse and Regret have different converter/intrinsic tables, globals, startup details, and possible input/targeting differences. | Each claim is explicitly variant-scoped or cross-checked in both games. |
Suggested status values: `Open`, `Evidence gathering`, `Test ready`, `Confirmed`, `Isolated`, `Blocked`. `Confirmed` requires an expected result and a repeatable test. A code comment, converter name, or single screenshot alone is not sufficient evidence.
## Work Packages
### WP0.1: Freeze the Test Baseline
1. Record ScummVM revision and working-tree state before making edits.
2. Identify the exact Remorse and Regret executable/resource editions locally available; hash inputs rather than copying them into the repository.
3. Build the Ultima VIII engine using the project's normal supported configuration. Save the complete command and output summary.
4. Run the same fresh-start and save/load smoke path for both games.
5. Record renderer logical dimensions and window dimensions at standard and expanded sizes.
**Deliverable:** a reproducible run record that names the inputs and distinguishes failures already present in the checkout from Phase 0 findings.
### WP0.2: Turn Evidence Into Testable Claims
For each discrepancy, write a short evidence card with:
- ID and game variant/build.
- Retail function/address or format bytes; identify whether evidence is disassembly, decompilation, archive inspection, or runtime observation.
- ScummVM revision, file, function, and behavior.
- Exact difference or unresolved assumption.
- One input sequence or fixture that distinguishes competing explanations.
- Expected observable result and what would falsify it.
- Confidence and known limitations.
Use the ledger above as the index. Keep raw evidence in existing subsystem notes where appropriate; do not duplicate large decompilation narratives here.
### WP0.3: Movement Turn Matrix
Use a fixed save or controlled input harness so animation state and movement flags are known. For Remorse and Regret separately, test:
| State | Input | Expected observation |
|---|---|---|
| Walking, weapon stowed | Hold forward; tap each turn direction | Turn is accepted and movement resumes in the intended direction. |
| Run startup, weapon stowed | Hold run+forward; tap left/right before the run loop begins | Tap is neither lost nor applied twice. |
| Sustained run, weapon stowed | Hold run+forward; tap left/right | One deterministic direction step while run remains held. |
| Start-run with weapon drawn | Enter combat/run startup; tap left/right | Compare against retail-supported startup animation states; record animation and facing. |
| Small-weapon combat run | Keep weapon ready and tap/hold left/right while running | Short taps and held turns follow the recovered distinction; weapon stays in the expected mode. |
| Large-weapon combat run | Repeat with a large weapon where available | Do not infer support from the small-weapon branch. |
| Direction-mode boundary | Repeat where the active animation is 8-dir versus 16-dir | Quantization matches the animation's direction mode and retail behavior. |
| Released turn key | Tap then release before animation completion | Pending input is consumed once and cleared; no delayed extra turn. |
Log the last animation, movement flags before/after input, actor direction, mover angle, selected next animation, and whether an actor-animation process was canceled/restarted. This separates input sampling defects from animation eligibility and angle-update defects.
The existing [tap-turn note](../scummvm-crusader-movement-tap-turn.md) states that the ScummVM helper was widened, but the source reviewed for this plan has the narrower three-animation condition. Phase 0 must first establish which checkout the note describes. Do not apply the documented list as an unconditional patch before this source and variant check.
### WP0.4: Target Scope and Crosshair Matrix
Treat three behaviors as separate test subjects:
1. `TargetReticleProcess`: chooses an object and draws the animated target reticle.
2. `CurrentMap::findBestTargetItem()`: shared candidate-selection implementation, also used by firing logic; identify all call sites before changing its contract.
3. `CrosshairProcess`: positions the manual projectile-aim marker; it does not perform target selection.
For the auto-target path, construct a repeatable scene/save with controlled actor location, direction, and candidate items. Include candidates:
- On the same direction ray/bucket at near, far, and very far distances.
- Just inside and just outside the retail-derived logical target rectangle.
- Partly visible and fully outside the viewport.
- In front of/behind an occluder, with and without `SI_OCCL`.
- Actor and non-actor candidates at equal and unequal distances.
- Broken candidates, destroyed/missing object IDs, equal-score ties, and no candidates.
- A target that enters/leaves eligibility after movement or a display resize.
Run each case at standard and expanded render sizes without changing world coordinates or the camera target. Record selected object ID, target-reticle state, and whether selection changes solely because the host surface was resized.
The local rendering evidence records a 640-pixel-wide retail viewport (`x=0..639`) and a height derived from the active screen height, but does not yet prove that these values are the target-selection rectangle. Inspect the retail target-selection and viewport call paths to determine:
- Whether selection uses screen-space clipping, a fixed world-space radius, a directional cone, or another candidate gate.
- Whether the logical area is centered on the camera, the avatar, the crosshair, or a different point.
- Whether original HUD/status areas are excluded from the target scope.
- Whether the gate considers an item's anchor, target point, or projected sprite bounds.
- Whether Remorse and Regret share the same boundary and tie-breaks.
If evidence confirms a legacy viewport bound, model it as a target-only logical rectangle transformed with the same camera projection as the map. Do not clamp the actual ScummVM render surface. Prefer passing a policy or explicit bounds into the player-reticle path over silently changing a shared selector used by NPCs or firing. Require equality of selected target across standard and expanded host sizes for candidates outside the legacy scope, while retaining the larger visible world.
For manual aim, separately record crosshair screen/world positions and the resulting projectile destination when no target is selected. Then add a selected target and verify that target acquisition does not accidentally override or reposition manual aim unless retail evidence says it should.
### WP0.5: Resolve the USECODE Event-Count Disagreement
The two candidate interpretations must be evaluated on the same exact raw class objects, not on class names or converter tables alone.
#### Candidate calculations
For a class object whose little-endian dword at bytes `8..11` is `raw`:
- ScummVM currently computes `base = raw - 1`, then `count = (base + 19) / 6`.
- Local extraction computes `count = (raw - 20) / 6`, requires a nonnegative extent divisible by six, and uses `raw - 1` as the body-offset anchor.
The local formula fits sampled Remorse records, but those samples do not settle every archive, language, or Regret build. Keep both calculations in the comparison output until the evidence selects a rule.
#### Required comparison
1. Inventory every nonempty class object in each exact Remorse and Regret USECODE archive. Preserve archive object index, class ID, name hint, object size, raw dword, and raw bytes hash.
2. Emit both candidate counts and table ends for every class. Flag negative extents, non-six-byte extents, counts whose six-byte table exceeds the object, and formulas that produce different results.
3. For every in-range slot under either formula, preserve the two-byte unknown word and four-byte raw event offset. Derive candidate body windows without rewriting the archive.
4. Compare candidate event rows and body windows against observed class/event use, ScummVM runtime lookup, and local extraction results. Keep name hints separate from slot identity.
5. Inspect boundary cases where one formula admits a slot the other excludes. Trace actual native and usecode callers to determine whether those ordinals are requested and what bytes the runtime reads.
6. Check whether the discrepancy correlates with variant, language, executable edition, archive generation, or a different valid class-record layout.
7. Record the selected rule and all exclusions per archive family. If evidence remains ambiguous, block custom archive editing/loading and retain the retail loader unchanged.
ScummVM's `Usecode::get_class_event()` warns when `eventid` is at or above the reported count but continues to read the six-byte event row. Therefore, tests must verify actual row bounds and malformed event requests; checking the warning text alone is not a safety gate. Do not use a malformed synthetic event ID to probe the retail executable.
The existing [USECODE format specification](../usecode-format-specification.md) and local [`extract_eusecode_flx.py`](../../tools/extract_eusecode_flx.py) are starting evidence/tools, not independent ground truth. The extractor uses the local count interpretation, so its agreement with that formula cannot by itself resolve the disagreement.
#### Required synthetic cases
- Empty archive object and non-class objects 0/1.
- Class object shorter than the 20-byte prefix.
- Raw dword below 20, raw dword not divisible into six-byte rows, and event table ending exactly at object end.
- Event table one byte beyond the object end.
- Empty event offset, one event, last event, and sparse slots.
- Event offset before the code anchor, at the first valid body byte, equal offsets, descending offsets, and offset beyond object end.
- Event ID exactly at the accepted count, one above it, and a very large unsigned ID.
- FLEX table entry whose data window overflows the archive or overlaps the next object unexpectedly.
Synthetic cases should exercise a validator/parser under test, not depend on memory layout or assertion configuration to make invalid access observable.
### WP0.6: Validate Fixed Maps and Globs
Create a read-only validation pass that reports archive and entry structure without creating runtime `Item` instances or changing a retail file.
#### Fixed-map checks
- Validate the outer archive table and report number of entries; identify any map index outside ScummVM's 256 initialized map slots.
- For each fixed-map object, report byte size, complete 16-byte record count, and remainder bytes. The current ScummVM reader uses integer division by 16, so a remainder must be visible rather than silently treated as a valid map.
- Decode fields only within a complete record: unsigned disk coordinates, Z, shape, frame, flags, quality, NPC number, map number, and `next` word.
- Check coordinate conversion and value ranges before applying ScummVM world-coordinate helpers.
- Where shape metadata is available, check shape/frame references. Report unknown metadata separately from invalid references.
- Preserve container-depth semantics and order in the report; do not flatten nested records for comparison.
#### Glob checks
- Validate the FLEX object boundary before parsing each glob.
- Require a complete two-byte item count and at least `2 + count * 6` bytes before reading entries.
- Report trailing bytes as an observation; do not silently strip them until retail files establish they are padding.
- Decode each item as byte X/Y/Z, `u16` shape, byte frame. Validate its shape/frame when metadata is available.
- Validate every fixed-map glob-egg reference against the loaded glob count, including empty or null glob entries.
- Check coordinate expansion with the Crusader-specific 1024-unit block mask, 2-bit coordinate shift, and 2-unit offset, using representative eggs near block edges.
For malformed inputs, the expected result is a structured validation error before the current runtime parser reaches an assert or out-of-range stream read. If test evidence shows the existing parser cannot fail safely, open a narrow ScummVM hardening fix; do not make a permissive parser that truncates or invents records.
### WP0.7: Baseline Runtime and Final Gate Review
After structural and behavior tests are assembled, repeat the startup/save-load smoke path for both games from the same ScummVM revision and data hashes. Review warnings and logs against the baseline, and run the relevant ScummVM build/test targets selected in WP0.1.
For each ledger item, assign one final Phase 0 disposition:
- **Confirmed:** original rule and ScummVM expectation are supported by both evidence and a repeatable test.
- **Isolated:** uncertainty remains, but it is bounded and no later phase relies on an unsupported behavior claim.
- **Blocked:** current evidence does not permit safe implementation or compatibility claims. Name the missing artifact or observation.
- **Implementation-ready:** exact expected behavior and test are established; move the proposed code change to a separate review/implementation task.
## Test and Artifact Plan
### Tests
- Small synthetic fixtures for FLEX entry bounds, fixed-record divisibility, glob counts, and USECODE class/event bounds.
- Retail-data comparison reports executed locally against both variants; reports contain hashes and summaries, not retail bytes.
- Movement input/animation matrix with repeatable saves or a deterministic input harness.
- Target selection tests at standard and larger host viewport dimensions, with the logical retail selection area held constant when its contract is proven.
- Separate manual-crosshair/projectile destination tests.
- Fresh-start, map-transition, and save/load smoke checks for Remorse and Regret.
No Ultima8-specific test files were located in the initial filename search. Before choosing a test path, inspect current ScummVM test conventions and use the narrowest supported harness. If asset-dependent integration tests cannot be upstreamed, keep their runner and results local and commit asset-free synthetic tests.
### Artifacts
- This document's discrepancy ledger, updated with evidence and test links.
- A local run record with ScummVM revision/build config and retail-data hashes.
- A local structural report for each archive and game variant.
- Asset-free synthetic regression fixtures and tests, if supported by the ScummVM test conventions.
- A short gate decision recording `Passed`, `Passed with isolated items`, or `Blocked`, with outstanding IDs.
Do not commit generated retail extracts, proprietary archive members, savegames, or binary screenshots. Where visual behavior matters, prefer a written coordinate/selection assertion and keep any capture local.
## Exit Criteria
Phase 0 is **passed** only when all of the following hold:
- The exact ScummVM and retail-data inputs are recorded and both games pass the agreed baseline smoke path.
- Every Phase 0 ledger row has an evidence label, test/disposition, and variant scope.
- Gun-running turn behavior has explicit cases for start-run, sustained run, small/large weapon state, tap/hold/release, and 8/16-direction modes, or is clearly isolated where a retail variant cannot be tested.
- Auto-target tests show whether display resizing changes eligible targets. Any proposed fixed logical viewport is backed by a retail-derived rectangle and is isolated to the correct player selection path.
- Manual projectile crosshair and target-reticle behavior have separate expected results.
- The USECODE formula disagreement is resolved per supported archive, or custom USECODE changes remain blocked and the current retail behavior is not modified on guesswork.
- Fixed-map and glob validators report malformed synthetic inputs before unsafe runtime parsing; retail reports identify all ignored remainders, invalid indices, and unresolved references.
- No unsupported data files were added, and the baseline comparison shows no unintended changes to retail startup, map loading, targeting, or save/load.
If only the USECODE discrepancy remains open, Phase 0 may be **passed with an explicit block** for custom USECODE work, but the report must not claim mod-script compatibility. If movement/target behavior lacks a retail-derived expected result, those rows remain open and must not be presented as confirmed parity.
## Source and Evidence References
- [Parent feasibility study](../scummvm-crusader-enhancement-feasibility.md)
- [ScummVM Crusader reference inventory](../scummvm-crusader-reference.md)
- [Movement tap-turn analysis](../scummvm-crusader-movement-tap-turn.md)
- [USECODE format specification](../usecode-format-specification.md)
- [USECODE round-trip and parser work](../usecode-roundtrip-ir.md)
- [Raw rendering and viewport evidence](../raw-0007-rendering.md)
- [Remorse gameplay/input evidence](../ne-segment1.md)
- [Regret-specific evidence index](../raw-porting-progress.md)
- [Local EUSECODE extractor](../../tools/extract_eusecode_flx.py)
ScummVM source paths reviewed for this plan:
- `engines/ultima/ultima8/world/actors/cru_avatar_mover_process.cpp`
- `engines/ultima/ultima8/world/target_reticle_process.cpp`
- `engines/ultima/ultima8/world/crosshair_process.cpp`
- `engines/ultima/ultima8/world/current_map.cpp`
- `engines/ultima/ultima8/gumps/game_map_gump.cpp`
- `engines/ultima/ultima8/world/map.cpp`
- `engines/ultima/ultima8/world/map_glob.cpp`
- `engines/ultima/ultima8/usecode/usecode_flex.cpp`
- `engines/ultima/ultima8/usecode/usecode.cpp`