Compare commits

...
7 Commits
111 changed files with 7926 additions and 84 deletions

No files matched your search

+18 -4
View File
@@ -35,12 +35,17 @@ other agents' active changes. Keep updates concise, save detailed evidence to di
Use bounded endian-aware parsers, portable paths, clear C#, deterministic tests, Use bounded endian-aware parsers, portable paths, clear C#, deterministic tests,
and explicit unmanaged ownership. Build frequently. Update `docs/progress.md`, and explicit unmanaged ownership. Build frequently. Update `docs/progress.md`,
`docs/tasks.md`, `docs/decisions.md`, and compatibility evidence before transitions. `docs/tasks.md`, `docs/decisions.md`, and compatibility evidence before transitions.
Current mode is evidence-led architecture continuation. The initial checkpoint is Current mode is user-requested gameplay/gadget implementation. On2026-10-27 the
documented in docs/checkpoint/review.md. Pause feature expansion; use the playable user parked collision recovery and requested gadgets. This overrides the earlier
feature-expansion pause; retain evidence before gameplay assumptions. Preserve
the35a2a66 body milestone/0272f7b release notes and remaining C4/C5 gates for return.
The initial architecture checkpoint is documented in docs/checkpoint/review.md; use the playable
69d0187 baseline as a comparison tool. Read 69d0187 baseline as a comparison tool. Read
docs/checkpoint/README.md, coverage.md and implementation-plan.md before gameplay docs/checkpoint/README.md, coverage.md and implementation-plan.md before gameplay
changes. Only evidence probes or directly evidenced corrections belong in this changes. Current gadget controls/resources/primary-fire findings belong in
checkpoint; distinguish static recovery, port tests and original runtime evidence. docs/gameplay/. Distinguish static recovery, implementation, port tests and original
runtime evidence. Main owns integration/runtime; gadget investigators have
exclusive named files, not shared directories.
Use REA for original-binary investigations from now on, including delegated Use REA for original-binary investigations from now on, including delegated
investigations. Preserve its Evidence and cross-check relevant addresses/bytes; investigations. Preserve its Evidence and cross-check relevant addresses/bytes;
@@ -52,3 +57,12 @@ not changed. Use generated copies, preserve complete Evidence/snapshots, and kee
static decompilation distinct from source execution. Current C3 continuation: static decompilation distinct from source execution. Current C3 continuation:
docs/checkpoint/control-phase-implementation.md; remaining body/wrapper/camera gates docs/checkpoint/control-phase-implementation.md; remaining body/wrapper/camera gates
are in its final section and the implementation ledger. are in its final section and the implementation ledger.
Current C4 follow-up is docs/checkpoint/collision-response.md with ceiling-wrapper,
body-root-registration and camera-handoff reports. The source sphere kernel is
isolated/probed; do not treat it as live capsule replacement. Next integration
report is collision-body-probe.md: source grid/retry component and seven original
dispatcher comparisons, contact/material/friction contracts and ten ordinary-body
observations are recorded. collision-body-implementation.md now records matched
ordinary composition and VR04 static-only live integration. Next: original dynamic
actor eligibility/pair state and special contacts before lab/outside expansion;
shared camera state remains separate. Retain modern render/noclip boundaries.
+34 -4
View File
@@ -5,7 +5,7 @@ using C#/.NET 10, Silk.NET.Vulkan (Vulkan 1.3), and SDL3. Original files remain
untouched in `../Original`. Work is local; no remote operations or runtime online untouched in `../Original`. Work is local; no remote operations or runtime online
services are used. services are used.
**Current direction: architecture recovery; feature expansion paused.** The **Current direction: gameplay gadgets; collision recovery is parked.** The
[checkpoint review](docs/checkpoint/review.md), [coverage map](docs/checkpoint/coverage.md) [checkpoint review](docs/checkpoint/review.md), [coverage map](docs/checkpoint/coverage.md)
and [implementation plan](docs/checkpoint/implementation-plan.md) compare source and [implementation plan](docs/checkpoint/implementation-plan.md) compare source
owners, update order and lifecycles with the port. Clean69d0187 and its packages owners, update order and lifecycles with the port. Clean69d0187 and its packages
@@ -13,8 +13,20 @@ are preserved locally as the playable baseline. Corrections now include task/Car
callbacks, controlled player phase ordering, source static camera queries for the callbacks, controlled player phase ordering, source static camera queries for the
first route and gadget availability through tutorial/return. Full scene scheduling, first route and gadget availability through tutorial/return. Full scene scheduling,
collision and shared camera state remain incomplete. collision and shared camera state remain incomplete.
The user requested this change after milestone35a2a66/0272f7b. Gadget work uses
original controls, state and assets; the collision checkpoint remains available
to resume after this gameplay work.
VR04 now uses recovered static body response/support/friction with original-code
numeric references. Lab/outside retain the capsule until special contacts and
dynamic collision are recovered; see [body implementation](docs/checkpoint/collision-body-implementation.md).
**Current milestone: original gadget screen and playable shrink ray.**
Tab/Space selects owned gadgets and their practice levels; the default device
fires on Enter/Ctrl/left mouse and supports actual VR04 soldier shrink/restore
with original morphs and score effects. Other gadget effects remain incomplete.
See [gadget implementation](docs/gameplay/gadgets-implementation.md) for recovered
rules, modern policies and the verification boundary.
**Current milestone: original lab story, interactions and jet pack practice flow.**
The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard
patrol logic, pickups, objectives, the practice prompt, VR04 powered jumping and patrol logic, pickups, objectives, the practice prompt, VR04 powered jumping and
checkpoint transitions. Collision response, timing and visual fidelity remain checkpoint transitions. Collision response, timing and visual fidelity remain
@@ -66,8 +78,22 @@ centered, objectives stay bottom-right and F2 stays top-left. Use
`--width 1920 --height 1080` for an initial window/offscreen size; resizing and F11 `--width 1920 --height 1080` for an initial window/offscreen size; resizing and F11
update UI placement and clicks. update UI placement and clicks.
The original lab pickup is internally tagged `shrinkray`; the original objective The lab pickup is the combined **shrink ray and jetpack** (inventory item3).
art identifies it as the **jet pack**. Its practice prompt accepts **Y** or a click Hold **Enter, Ctrl or left mouse** to fire the continuous ray; release to stop.
Grounded firing stops forward motion. Eligible original Yokian soldiers can be
shrunk for30 seconds, awarding10 points. Their authored shrink animation holds
its small endpoint; complete enemy AI/combat remains unimplemented.
**Tab or Space** opens the original gadget screen; with another special gadget
equipped, the first press unequips it. Use the mouse or arrows to point, then
Enter/Ctrl or a mouse button to select. Escape or Return closes the screen.
Practice Mode followed by an owned gadget enters its original tutorial directly.
The screen scales uniformly on widescreen and pauses port gameplay while music
continues. Other gadget selection art is present; their special behaviors remain
future work. F1's jetpack availability control also controls shrink-ray ownership.
The pickup's original objective calls its jump action the **jet pack**. Its
practice prompt accepts **Y** or a click
on Yes to enter VR04, and **N** or a click on No to resume. Enter selects the on Yes to enter VR04, and **N** or a click on No to resume. Enter selects the
hovered Yes region, otherwise No. Practice RETURN restores Jimmy and Goddard to hovered Yes region, otherwise No. Practice RETURN restores Jimmy and Goddard to
the saved departure position, retains the lab start's yaw and suppresses its intro. the saved departure position, retains the lab start's yaw and suppresses its intro.
@@ -180,3 +206,7 @@ Native reverse engineering uses the local REA/Ghidra launcher separately from
runtime builds; see [local analysis setup](docs/rea.md). Current source-backed runtime builds; see [local analysis setup](docs/rea.md). Current source-backed
cutscene control/body phase findings are in cutscene control/body phase findings are in
[control-phase implementation](docs/checkpoint/control-phase-implementation.md). [control-phase implementation](docs/checkpoint/control-phase-implementation.md).
The collision continuation adds a probed
[source sphere kernel](docs/checkpoint/collision-response.md) and integrates the
[overhead response](docs/checkpoint/ceiling-wrapper.md); full capsule replacement
and [shared camera handoff](docs/checkpoint/camera-handoff.md) remain open.
+5 -2
View File
@@ -7,10 +7,13 @@ Original DLL/frame and original game comparisons are separate evidence categorie
## Identity ## Identity
The lab pickup's GAM tag SHRINKRAY/PickupIndex301 is a prototype/internal name. The lab pickup's GAM tag SHRINKRAY/PickupIndex301 belongs to the combined device.
Original screens.omt Canv120 says GET JET PACK; its effect grants inventory Original screens.omt Canv120 says GET JET PACK; its effect grants inventory
group0/item3. That exact inventory slot gates the powered-jump code43848E/4385C9. group0/item3. That exact inventory slot gates the powered-jump code43848E/4385C9.
It must not be presented as a shrink-ray weapon. The original readme describes The later gadget recovery corrects the old prototype-name interpretation:
tile14 names SHRINK RAY, controls113 lists both SHRINK and JUMP/JETPACK, and
426E40 fires the default owned-item3 ray. See docs/gameplay/shrink-ray.md.
The original readme describes
Shift/Insert/right mouse as Jump - Jet Pack Burst. The actual C3DShrinkRay class Shift/Insert/right mouse as Jump - Jet Pack Burst. The actual C3DShrinkRay class
has separate ray.ase/ray0000..2.png bindings440035..A6, outside this implementation. has separate ray.ase/ray0000..2.png bindings440035..A6, outside this implementation.
+5
View File
@@ -1,5 +1,10 @@
# Follow-up original collision evidence # Follow-up original collision evidence
Continuation2026-10-26: checkpoint/collision-response.md supersedes the earlier
recursive-sliding inference with REA/byte/probe evidence for47BD80 and its callers.
The source kernel is now a separate tested component; live capsule replacement,
full contact/support order and pivot fidelity remain open.
Static investigation and isolated copied-DLL probes,2026-10-24. The bounded Static investigation and isolated copied-DLL probes,2026-10-24. The bounded
OriginalBodySupport module now translates the vertical support/segment path. OriginalBodySupport module now translates the vertical support/segment path.
This does not supersede the complete provisional SceneCollision solver or prove This does not supersede the complete provisional SceneCollision solver or prove
+39
View File
@@ -5,6 +5,25 @@ SDL3 for platform windowing, input and audio. Linux x64 and Windows x64 are
equally required. Source is `src/GamePort/`; root executable csproj allows equally required. Source is `src/GamePort/`; root executable csproj allows
`dotnet build` and `dotnet run` from GamePort. No runtime network dependencies. `dotnet build` and `dotnet run` from GamePort. No runtime network dependencies.
The first gadget slice separates UI display selection from the equipped raw mode.
`GadgetScreen` owns group0 panel state/hit regions; `GadgetMenuOverlay` loads54
original canvases and applies shared uniform640×480 viewport/pointer transforms.
Closing precedes the inventory selection event. Practice captures the existing
departure context and requests the selected VR01..08 without a pickup prompt.
The panel gates new gameplay SFX; full simulation pause is a declared port policy.
`SceneGadgets` subscribes to the player's existing input phase and owns ray sound,
energy, actual3SOL targets and score callbacks to `SceneInteractions`/TSK.
`ShrinkRay` isolates strict source heading/height/distance/wall gates and texture
clock; `OriginalHeading` implements the copied-DLL numeric references.
`ShrinkSoldier` separates authored/reset AI mode from prior dynamic mode, shrink
timer/marker and provisional NPC body support. `ShrinkSoldierVisuals` samples
original WALK/SHRINK morphs with nonloop hold rather than scaling the mesh.
`ShrinkRayVisuals` captures the effect root/yaw and three source textures.
Generic draw opacity and opaque/alpha/additive variants support the recovered
half-opacity ray. Blended-world depth writes disabled is an explicit renderer
policy. See gameplay/gadgets-implementation.md for evidence and remaining gates.
Original assets stay in `../Original`. Python tools parse undocumented original Original assets stay in `../Original`. Python tools parse undocumented original
formats into generated scene resources under `artifacts/`. The modern application formats into generated scene resources under `artifacts/`. The modern application
loads these original-derived resources and big endian GAM entity data. Portable loads these original-derived resources and big endian GAM entity data. Portable
@@ -23,6 +42,26 @@ verification possible without a desktop; this is distinct from SDL presentation.
Simulation implementation must follow recovered algorithms and timing. A generic Simulation implementation must follow recovered algorithms and timing. A generic
fly camera or rendered model alone does not satisfy the playable-scene requirement. fly camera or rendered model alone does not satisfy the playable-scene requirement.
Collision continuation separates the recovered one-triangle47BD80 kernel
(`OriginalSphereResponse`) from the live capsule adapter. Its explicit nearest
state is caller-owned. `OriginalStaticCollision` composes source FIFO cell visits,
retry and support-grid reduction. Its caller owns body
integration, terminal callbacks and shared nearest/last-polygon reset timing.
Prepared collision metadata retains signed material archive identities and an
explicit completeness flag; source body callers must account for special contacts.
Seven original dispatcher comparisons and ten original ordinary-body reference
observations are in checkpoint/collision-body-probe.md. `OriginalBodyPhysics`
composes that static path for ordinary Jimmy flags/contacts and is used in VR04;
the live bridge supplies zero angular velocity, variable source radius60/100 and
separate published160 speed. Lab/outside retain the capsule. Special callbacks,
other original actor pair eligibility and shared dynamic reclipping remain gated.
Source root and modern feet/sole rendering are distinct adapters; F3 exit still
uses modern capsule occupancy. See checkpoint/collision-body-implementation.md.
The source-root upward ray is supplied separately from the camera debug query:
Jimmy's wrapper reflects upward velocity/cancels mode1 jump/fire before movement,
including while uncontrolled. Fresh input precedes this wrapper; retained input
follows Jimmy/fire. See checkpoint/collision-response.md and ceiling-wrapper.md.
The completed foundation includes a single synchronous Vulkan renderer supporting The completed foundation includes a single synchronous Vulkan renderer supporting
offscreen and SDL surface presentation, an independent SDL WAV stream, bounded offscreen and SDL surface presentation, an independent SDL WAV stream, bounded
GAM/PNG/scene readers, and a retained-topology morph sampler. Prepared scene JSON GAM/PNG/scene readers, and a retained-topology morph sampler. Prepared scene JSON
+22 -1
View File
@@ -1,6 +1,6 @@
# Architecture checkpoint # Architecture checkpoint
Feature expansion is paused. The existing port is a preserved baseline and a tool This records the completed architecture checkpoint. The existing port is a preserved baseline and a tool
for testing interpretations. This checkpoint connects original state ownership, for testing interpretations. This checkpoint connects original state ownership,
update order and lifecycle to the lab → VR04 → lab → outside route; it does not update order and lifecycle to the lab → VR04 → lab → outside route; it does not
require recovering every level or certify complete gameplay fidelity. require recovering every level or certify complete gameplay fidelity.
@@ -29,6 +29,27 @@ backed by [uncontrolled player](uncontrolled-player.md),
[cutscene preparation](cutscene-preparation.md). [REA setup](../rea.md) records [cutscene preparation](cutscene-preparation.md). [REA setup](../rea.md) records
local Ghidra/JDK and Evidence/snapshot use. local Ghidra/JDK and Evidence/snapshot use.
C4 continuation: [sphere response](collision-response.md),
[ceiling wrapper](ceiling-wrapper.md) and [physical re-registration](body-root-registration.md).
The source kernel is isolated/probed; live capsule replacement remains gated.
[Shared camera handoff](camera-handoff.md) records the next C5 state correction.
The next C4 chunk adds [grid traversal](collision-grid-traversal.md),
[contact/material/friction ownership](collision-contact-callbacks.md) and
[dispatcher/body component probes](collision-body-probe.md). The source dispatcher
is implemented and compared with isolated original outputs; whole-body/live
integration and special contacts remain gated. [Independent review](collision-integration-review.md)
records corrections and remaining limits.
The [ordinary-body implementation](collision-body-implementation.md) composes the
ten numeric references and enables the static subset in VR04. Its
[source contract](collision-body-composition-source.md) closes phase/radius fields;
[implementation review](collision-body-implementation-review.md) preserves remaining
dynamic, special-contact, initialization and modern noclip/render boundaries.
User-directed gadget continuation is in ../gameplay/gadgets-implementation.md.
It supersedes older inferred gadget names: raw mode0 is Bubble, menu item3 is the
combined shrink-ray/jetpack and its normal equipped mode remains−1. Numeric
collision findings remain valid independently of those old labels.
Evidence labels used throughout: Evidence labels used throughout:
- **Recovered:** static instructions, serialized original data, or a specifically - **Recovered:** static instructions, serialized original data, or a specifically
+46
View File
@@ -0,0 +1,46 @@
# Retained identity and physical re-registration
2026-10-26. Static evidence, not whole-loader execution. Original EXE SHA256 is
f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8.
Text offsets are VA−400000; body_root_registration.py guards14 instruction
sites and four Jimmy interface targets from PE-mapped bytes.
Ordinary teardown479000 clears physical records/body list695D3C, while game
object identity can survive in registry50999C.46E131 explicitly clears surviving
interfaces'49E registration flag. Jimmy PostLoad4238B4 invokes interface2C→42AB50:
false49E jumps to4623D0 InitPhysics. Identity retention is not physical-list retention.
4623D0 invokes base458910 (470A00 allocation/49E=true), copies current render XYZ
complete44/48/4C through16C→471630, copies angular-unit Euler through174→4716D0,
then calls479A40.479A65 invokes interface150(0,0,0);479A6F invokes Init28 AGAIN,
resolving to Jimmy437890. Only then does it append a12-byte body-list node with
the interface payload and increment695D40. Later PostLoad STRT placement and
final control preparation have their own order; registration's Init is not a
blanket post-placement reset. Existing retained scalar conclusions remain bounded
by the closed437890/generic Init chain, not by an assumption that Init runs once.
| REA routine | Evidence ID |
|---|---|
|4623D0|ev_d60cfc7d2ff8266e19176052e1466ba98f09e7b10b92db828566fbc28d36d281|
|458910|ev_a7ef1cecf9385efe4f91ad8ec48ac37ba24831a1b797f24c3039a912f0b61526|
|479000|ev_bae5aeaa4f8ebad1bba6974e9d33ba801959500e41eadc99be5e6b8631feecc1|
|479A40|ev_40105808ae5a1e83bd8221b627e9aeca89b0f399a68dba068ed01e5b11857438|
Complete replies/exports/closed snapshots: artifacts/body-root-registration/.
Some additional requested leaf/derived entries lacked analyzed Ghidra procedures;
their error replies remain alongside successful Evidence. Instruction bytes and
resolved vtables support the callback chain without claiming complete pseudocode.
Previously recovered dimensions remain: ordinary radius60/support factor1.265,
physics position interface214..220, direct physics-to-render XYZ copy4624B0, shape
min/max bound records1C4/1D4. No recovered capsule height follows from mesh bounds.
The standing animation offsets observed in the older copied-DLL probe were zero;
there is still no source evidence for the port's sole-based model translation.
The port reconstructs body state per scene and carries only mode/hold/fire in
its bounded route container. That agrees with the reset boundary at a coarse
level, but does not reproduce source allocation/physical-list order/new helper
traversal or the complete body338 record. REA's prior40E050/462520 Evidence also
shows base transform work before ownership; port destination-yaw smoothing is
not proven equivalent. These remain C3/C4 implementation gates. No extra state
carry, scale correction or live body-shape replacement is justified by this report.
+40
View File
@@ -0,0 +1,40 @@
# Shared viewport handoff
2026-10-26. Static source evidence; implementation is deferred to the next bounded
C5 chunk. camera_handoff.py guards50 instruction sites, four callbacks and the
DEFAULT threshold; its four Python projections are not original execution.
Text offsets below are preferred VA−400000 for the manifest's original EXE.
Shared viewport pointer509A50 stores eye at44/48/4C. MCA431677..43169D writes this
same eye. DEFAULT447D54 has an already-Jimmy branch; on the other route it restores
raw control, transforms Jimmy-local(0,500,−500) through384, computes Euclidean
distance to the current shared eye, and writes eye only when distance>1000
(447E9D..447EC3). Equality does not snap. This block leaves orientation unchanged.
Walking input/follow438EF7..438F29 reads the current shared eye into complete
714/718/71C every invocation.439722..439742 uses it for desired-eye delta;
4397F8..43982D adds the filtered delta back to the shared viewport. Airborne
439E33..439E51 likewise captures the shared eye into locals. Therefore the first
resumed input uses the final scripted eye, or DEFAULT's snapped eye, without
relying on an old player-owned follow cache.
Normal walking gains are1.6/1.2/1.6 times dt and the separate ray gain. Aim derives
from look point minus PRE-update eye (439830..439865; airborne43A09F..43A0CE),
then quantized OMT angle conversion. The port's LookAt(newEye,target) is a separate
orientation approximation. Other special follow fields/input branches remain open.
REA decompiled setup437740:
ev_d2502f41c45731b86d4365634fbc6f0d1b3b70d880fd5741275fd36f1d585aa4.
Selected DEFAULT/follow/viewport-write entries lacked recognized Ghidra procedures;
explicit-offset attempts also failed. Complete successes/errors/exports/closed
snapshots are under artifacts/camera-handoff/rea/ and rea-offsets/. Those negative
provider results are limitations, not negative claims about the original code.
The handoff conclusion is supported by the guarded direct instructions.
Current port still separates SceneDirector's scripted eye from LabSimulation's
follow eye. C5 should move viewport eye/aim ownership into one state shared by
script and follow, apply strict DEFAULT snapping only on the recovered boundary,
and preserve pre-update-eye aiming. Test below/equal/above1000, already-owned,
CAM/MCA→DEFAULT, held-input resume and RETURN continuity. Keep projection/fog/masks,
full follow branches and original visual comparison separate. This investigation
does not claim that camera handoff is implemented yet.
+52
View File
@@ -0,0 +1,52 @@
# Jimmy's overhead query and cancellation
2026-10-26, static recovery and bounded port correction. Original EXE identity is
the manifest's f5281076…1aea8. Preferred text VAs map to offsets VA−400000;
ceiling_wrapper.py independently maps and guards37 sites,8 targets,6 constants
and four complete bodies. No original ceiling routine was executed in this chunk.
424BE0..424C34 runs before movement437940's raw-control identity gate. It reads
live velocity2BC→471F10; strictly positive Y invokes complete1A4→425170. The
separate1A8→4252E0 downward-distance refresh follows, then movement. These
wrapper queries are not input or camera ownership tests.
425170 reads logical root310→472300.4251B8 adds float150 to rootY;4251FC calls
47C210 with two-sided=false. This is the wall-first/FIFO static predicate shared
with camera queries, not support's nearest reducer and not a capsule-top sweep.
On a hit it rechecks live Vy>0, then writes XYZ through2C4→471F40 with
`Vy=float(min(-double(Vy)*0.6,-85))`, preserving X/Z. It does not correct position.
Optional sound47 depends on selector4F0588 and an elapsed>5 gate; then4252CD
invokes complete1E0→425120.
425120 acts only when complete7C4 mode==1: writes jump7E8=0/mode1, requests FALL,
then zeros owned fire6C0 if present and calls complete140→429910. Hold874,
pending impulse and acceleration are not cleared by these writes.429910 clears
complete1E64/1E68 and saved soundA3C, with a helperA18 cleanup path except selector2.
Those helper/class sound effects are not fully implemented.4252E0's root−2500
nearest ray/shadow placement is separate from this upward response.
REA/Ghidra425120 Evidence:
ev_5fd4a2c55af84285f9b3fe8f9208e08ea88461aba4d1460d74344a9f1cbe3289.
Complete batch replies/export/snapshot are in artifacts/ceiling-wrapper/rea-batch/.
Other wrapper entries were not recognized procedures; explicit mapped-offset
queries also failed, retained in rea-mapped-batch/. Supplementary bytes establish
their bounded contracts; missing pseudocode does not establish missing code.
LabSimulation now performs the source-root query after body integration and before
controlled movement/fire, even without control. Fresh input precedes this Jimmy
wrapper; retained input follows Jimmy/fire, preserving the recovered registry
boundary. For the three recovered route
scenes, Program supplies TraceGeometry independently of the modern camera-only
debug toggle. A ceiling hit reflects velocity and applies mode1 cancellation;
the later owned fire phase independently subtracts dt. Noclip bypasses this path.
Other scenes retain the previous capsule ceiling adapter until their registration
filters are recovered. Capsule position response/root placement remain provisional
even in route scenes; full sound/gadget cleanup and complete wrapper ordering are
explicit gaps, not implied by the new velocity/cancellation contract.
Four Python source/projection groups and one coupled movement group cover the
150-unit root ray, pending-impulse boundary, raw-control independence, mode0/1,
active powered-fire cancellation, hold preservation, post-cancel energy and phase
order. Camera tests check that the modern camera switch neither disables geometry
queries nor overwrites camera diagnostics. Port regressions are separate from the
original kernel probe documented in collision-response.md.
@@ -0,0 +1,173 @@
# Ordinary body composition479D20
2026-10-27 UTC. Independent source investigation for the managed composition
chunk. The EXE SHA256 is
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Preferred VAs below are PE-mapped by body_composition_contract.py; text raw
offsets equal VA−400000 for these supplied bytes. The helper guards the entire
479D20..47A329 body plus81 decisive instruction sites and12 Jimmy vtable targets.
## Evidence and scope
Retained REA479D20 Evidence
`ev_5439072b32ae9f9208795ad2b07bc524e2407b46da487072fb3dfd8c10e7c4b0`
is in artifacts/collision-response/rea-response/01.evidence.json. Its incomplete
prototype/local-variable reconstruction must be checked against instructions;
the actual caller supplies actor interface and dt. Reviewed disassembly is saved
to artifacts/collision-integration/body-composition.instructions.txt; fixed source
anchors/offsets are in body-composition-contract.json. No original executable
entry point or original routine was executed in this independent investigation.
The ten prior copied-code body observations remain separate in
[collision-body-probe.md](collision-body-probe.md).
Focused new REA/Ghidra session used the existing generated EXE copy, exported
Evidence, then closed normally under artifacts/collision-integration/rea-body-radius/:
| Procedure | REA Evidence |
|---|---|
|471240, authored/current radius setter|ev_d77d8a0d308e4d9b71dbb0cccfcf68771bd4552a9d4a09c50d14225ec171b058|
|471B40, live body-radius setter|ev_97d21014bcdac4f44484c1c079e957f22d449b60efd7c2a31be450deddc38871|
437F90 was not recognized as a Ghidra procedure; the complete error remains in
00.json. Its burst call site is supported by reviewed instructions/fixed guards,
not attributed to successful pseudocode. No unchanged failed query was retried.
## Recovered phase order
The body pointer is the game interface, complete-object+C0 for Jimmy. Slot offsets
in this report are interface-relative.
| VA / raw offset | Source operation and ownership |
|---|---|
|479D2E /79D2E|Read support218 and cache previous support in global695D49.|
|479D3D..4E /79D3D|If support handling1C8 is enabled, write current support21C(false).|
|479D58..60 /79D58|Only now test integration210; false returns with the preceding support side effects intact.|
|479D6F..479DD4 /79D6F|Read current root310 and old previous root2F8; compute quick magnitude of their difference and discard its result. This is not a pre-support/gravity cancellation query.|
|479DDA..479E54 /79DDA|Test global geometry4F69E5, independently of prior support. Enabled: anchor2F4(0,−25000,0). Disabled: support21C(true), anchor(0,current-root-Y,0), acceleration278(0,−gravity.Y,0), velocity2C4(oldX,0,oldZ).|
|479E63..479EAC /79E63|Read angular velocity2AC, rotate334(angularXYZ×dt) before consuming impulse.|
|479EBB..479EF2 /79EBB|Read pending impulse284, add XYZ through velocity2CC, clear impulse28C(0,0,0) once.|
|479F01..479F4A /79F01|Read acceleration270, add accelerationXYZ×dt to velocity.|
|479F50..479F7E /79F50|Separately add global gravityXYZ×dt.|
|479F8D..479FD2 /79F8D|Read resulting velocity; store displacementXYZ=velocityXYZ×dt.|
|479FD6..479FF0 /79FD6|Read collision flag220, then world-response1D0 when collision is enabled. These gates are distinct from global geometry and support.|
|47A038..47A096 /7A038|World branch clears last polygon695D4C, sets face695D5C=130000 and edge5CFBE0=radius260, copies current root into previous-root2FC, clears auxiliary695D84.|
|47A090..47A11F /7A090|If displacement.Y>0, dispatch47B4B0 with fullXYZ. If Y<=0, dispatch with XZ/zeroY, then add original falling displacement.Y to candidate.Y. Edges flag is true in both paths.|
|47A123..47A181 /7A123|After terminal contact callback, read fresh previous-root2F8 and live root310 and compare all four floats. Only equality permits final candidate publication.|
|47A187..47A1C4 /7A187|Clamp candidate **Y** below−25000 to−25000, then publish Vec4 via314; if any previous/live component differs, skip clamp/publication.|
|47A22A..47A235 /7A22A|If1C8, run support47B890 after displacement/callback/publication. It uses the original previous support695D49 for landing transition.|
|47A241..47A25A /7A241|Read published scalar268/live160. Equal zero invokes friction47A330; this is not controller scalar608 or a raw-control test.|
|47A298..47A2D1 /7A298|Read suppression scale230/live144. Angular quick magnitude×scale<=0.1 zeros angular velocity2B4.|
|47A2E0..47A31D /7A2E0|Linear quick magnitude×scale<=0.1 plus a fresh268==0 zeros linear velocity2C4.|
Publication from the dispatcher means writing the caller's candidate stack vector,
not necessarily changing actor root310. The later Vec4 equality check preserves
contact-owned transform changes. It compares freshly read previous/live roots;
it is not a comparison with a stale local copy and must include W. Ordinary
370 and nonspecial Jimmy374 do not move the root, so a bounded ordinary adapter
can keep W=1 explicitly. A future special callback must preserve this boundary.
The body does not automatically reset movement mode/jump/fire on support. Source
landing37C for Jimmy is a no-op; later controller/fire callbacks own those states.
Landing observer order and friction details are in
[collision-contact-callbacks.md](collision-contact-callbacks.md).
The rotate334 call's order and XYZ arguments are recovered here; this does not
recover generic334 angle wrapping or logical/render transform synchronization.
The original body fixture substitutes a simple Euler-add virtual, so its angular
cases cannot independently prove the real transform implementation. An ordinary
live bridge supplying zero angular velocity remains within a narrower contract.
## Flag branches and shared state
If220 is true but1D0 is false, source47A1CC..47A220 copies current root to
previous2FC and translates31C(displacement). Support and published-speed friction
still run afterward. It does not initialize/query the static context in this path.
If220 is false,47A264 tests228. When228 is false, it translates31C(displacement);
when true it does not translate. Both skip support and friction, but still run
the suppression tail. The initial support clear remains, if1C8 was enabled.
Treating all of these modes as a single collision/noclip boolean would lose
source state changes. Modern F3 noclip is a separate user-requested policy.
Prior source guards establish ordinary defaults: support1C8/live13B=true,
world1D0/live13C=true, integration210/live13E=true, collision220/live140=true,
228/live141=false. Player overrides prevent-lowering208/live13A=true; direct
dispatcher member42C defaults0. Generic suppression-scale default0.5 is
46FE01→471120→234, and Player friction default0.8 is4373B0→4711B0→24C→live150.
These are initialization contracts, not invariants after authored/script setters.
Static context resets occur once before body world traversal. Retries retain
nearest/last polygon. Dynamic response uses its own face/edge initialization and
can retain the last-polygon global; it remains a separate shared-scene contract.
No new meaning is assigned to auxiliary695D84 in this bounded investigation.
## Init restores authored speed separately from current publication
Retained REA470540 Evidence
`ev_c16f95e608194a8f9fb029430f1c6a01512d34099ebf447cf944946c79631166`
in artifacts/collision-integration/rea-support/02.json covers generic Init's scalar
copy. It is independently linked to Jimmy's vtable and the guarded leaf bodies:
| Source site | Initialization contract |
|---|---|
|4706CF /706CF|Calls Jimmy interface114→471260, reads authored float interface38.|
|4706DB /706DB|Passes that value to interface26C→471B60, writes current published160.|
|46FC08 /6FC08|Constructor zeroes EBX.|
|46FE51..54 /6FE51|Pushes EBX=0, invokes471270 (authored-speed setter).|
|471270 /71270|Stores authored38, then forwards the same value to26C/live160.|
|471B50/471B60 /71B50/71B60|268 reads and26C writes current published160 only.|
Controller437C22..2D publishes through26C after applying movement, so it changes
current160 without changing authored38. Preparation43A750 clears controller608
and velocity but not either speed field38/160. Ordinary/retained Init through
437890→4587F0→470540 therefore reapplies authored speed; constructor default is0
and the current route's Jimmy properties do not assign another authored speed.
The bounded bridge's per-scene PublishedSpeed=0 follows this initialization
chain, rather than being inferred from controller608's separate Init reset.
Init is a copy of authored38, not an unconditional zero invariant. A future caller
of interface118→471270 with a nonzero authored value must preserve that value
through subsequent Init. No new source execution is claimed for this follow-up;
the retained REA Init result plus fixed getter/setter/constructor bytes establish
the route/default contract.
## Burst radius is the same live physics radius
There is no independent interaction-only100 radius in this source path:
| Source link | Structure/write |
|---|---|
|437FA3|Air helper obtains EDI=complete object+C0, the same game interface.|
|4384E4 /4384F3|Allowed burst with an effect pushes100, calls interface264.|
|Jimmy table4A373C+264→471B40|Writes interface15C, current body radius.|
|Table+260→471B30|Reads exactly interface15C;479D20 and47B890 both consume260.|
|PostLoad4236A3→110→471240|Writes authored34 then invokes264, initializing current radius60.|
|Held-state3 landing4386C1..C8|Writes current radius60 directly through264.|
|PostLoad4236B3→100→4711E0→254→471B00|Sets live support factor154=1.265;250→471AF0 reads it.|
Thus radius100 changes both sphere response and radius×factor support clearance
and root offset, to126.5 with the ordinary factor. Grounded Jimmy's ordinary
wrapper restores60 in its later object phase; physics/support must not perform
that restoration early or clear it merely because control is absent. Other
gadget radii (for example Bubble/mode0 radius160) remain outside the ordinary
default-device subset. Gadget continuation corrects the earlier Scooter label;
see ../gameplay/gadget-controls.md for display index versus raw mode.
## Verification and remaining integration questions
`python3 -m unittest discover -s tests -p test_body_composition_contract.py -v`
passes eight groups: original body/site identity; disabled-integration support
clear; phase order; descending split; three distinct flag gates; four-component
publication predicate; shared burst/support radius targets; Init authored/current
speed separation. These fixtures are
explicit source control-flow projections, not original execution or managed body
numeric verification. Existing ten isolated body observations and primary's
managed comparisons provide separate numeric evidence recorded by primary.
Before VR04 live use, compare root/support while radius changes60→100→60, retain
separate published160 versus controller608 across control loss, and verify the
phase owner for restoring radius. Source collision root and modern render foot
translation remain separate: no new capsule height or visual sole correction is
derived here. Full wrapper/registry, exact x87 cell/quick-magnitude boundaries,
special160/164/FENCE/LADDER callbacks, dynamic global context and whole original
game comparison remain open. An ordinary component passing numeric fixtures does
not establish those broader contracts.
@@ -0,0 +1,92 @@
# Ordinary body and VR04 bridge review
2026-10-27 UTC. Independent read-only review of primary's current
OriginalBodyPhysics.cs, LabSimulation.cs and Program.cs against
[the source contract](collision-body-composition-source.md). This investigator
owns only this report. No new original execution or REA session was necessary;
existing retained body/radius Evidence and guards establish the reviewed facts.
## Result
No directly evidenced mismatch was found within the stated subset: enabled
integration/support/collision/world flags, prevent-lowering enabled, lower-edge
override disabled, ordinary Jimmy contacts, fixed factor1.265 and zero angular
velocity in the live bridge. The implemented composition preserves source
impulse→acceleration→gravity, positive-Y/full versus nonpositive-Y/horizontal-first
motion, terminal370 positive-Y clearing, support/landing order, independent
published160 friction gate and final suppression. Fresh per-body nearest context
agrees with the source world branch's explicit resets.
The absence of special Player374 behavior is enforced conservatively by rejecting
any source scene with potentially eligible special-contact material IDs. Omitting
the source Vec4 previous/live-root reentrancy test is justified only inside this
bounded no-root-changing-contact subset; the explanatory source comment says so.
Generic334 angle wrapping/transform behavior remains outside the zero-angular
bridge, and the component's nonzero-angular numeric fixtures use the original
probe's substituted Euler-add virtual rather than real source334 execution.
## Integration checks
- Program selects the source body only for actual VR04; lab/outside keep their
existing adapter. OriginalBodyPhysics rejects special-contact geometry and
StepOriginalPhysics rejects attaching the provisional dynamic resolver.
- The live radius passed to body/support is InteractionRadius. This correctly
incorporates burst100 and later wrapper restoration60, rather than retaining
the old capsule24 radius or treating100 as interaction-only. Constant75.9 is
a conversion between modern feet storage and actor root, not the solver's
variable support offset. Rendering's sole correction remains a modern policy.
- Physics still runs before Jimmy input/controller/fire. Grounded radius60 is
restored in the wrapper before ownership checks. Preparing a script clears
controller speed/velocity while preserving body published160, pending impulse
and independent acceleration. A new scene resets published speed separately.
- The bridge supplies zero angular velocity and derives the next state from
current actor root/velocity/acceleration/impulse/support/published speed each
body pass. Dropping the component's angular output does not lose live angular
state inside this declared zero-angular subset.
- Camera debug enable remains camera-only; the body's geometry and overhead
query do not use it. Modern noclip bypasses the body while enabled and resumes
it with cleared motion through the existing debug policy.
## Scope risks and next gates
1. **Prepared doors are not every original dynamic body.** Program rejects a
nonempty StaticSceneVisuals.DoorColliders sequence in the source subset. This
establishes only absence of those prepared doors. Actual VR04 entities include
3SOL,3ROC,3TRO and other classes; their complete original physical-list and
pair-collision eligibility is not closed by that check. Preserve the explicit
no-dynamic-body-pass limitation and recover source registry/flags before
claiming complete tutorial collision fidelity or extending the adapter.
2. **Modern noclip exit uses the old occupancy policy.** SetNoclip(false) still
checks SceneCollision.CanOccupy with capsule24/render-derived height. Source
body response can subsequently reposition a root that this debug test admitted.
The ordinary flight/return test does not establish radius60/100 admission at
walls or tight gaps. Keep this as a documented debug policy; a later source
occupancy check needs an explicit supported contract rather than silently
treating zero-motion dispatch as a complete overlap query.
3. **Initial/visual placement is still bounded.** SceneCollision.GroundHeight and
floor-derived rendering are used to initialize the modern bridge. The stable
VR04 root/sole tests verify port consistency, not original transform/pivot
equivalence. Source spawn/root settling and wrapper/base logical-to-render
synchronization remain separate comparisons.
4. **Shared dynamic context remains unimplemented.** Fresh source body contexts
must not later be reused for dynamic reclipping without the recovered reset/
last-polygon schedule. Special contact root writes require the source Vec4
publication condition; a generic wall reflection is not an adequate substitute.
5. **Gadget scope remains−1/3.** Source gadget7 has additional374 side effects;
source scooter uses another radius policy. The current bridge does not carry
those contracts into OriginalBodyPhysics. Future gadget-selection expansion
must restrict or implement them before broadening this solver's claim.
These are retained integration boundaries, not failures of the ten-reference
ordinary composition. They do not require changing the verified source arithmetic.
## Verification
`source scripts/env.sh && dotnet run --project tests/GamePort.BodyPhysicsTests --
../Original` passes20 groups independently during this review, logged to
artifacts/collision-integration/body-implementation-review-tests.log. Coverage
includes ten original copied-body references, positive/nonpositive split,
ceiling370, radius100 support, unclamped friction, actual VR04 root/visual
consistency, preparation/published speed, control-independent impulse, retained
flight/landing and ordinary noclip return. These are managed port checks;
primary's headless/native/GPU/whole-route results are recorded separately.
@@ -0,0 +1,86 @@
# Ordinary body implementation and tutorial bridge
2026-10-27 UTC. This chunk composes the recovered static dispatcher with ordinary
Jimmy body integration and enables that bounded path in VR04. It does not close
all collision, dynamic bodies, special contacts or original visual comparison.
## Evidence and implementation
[Source composition](collision-body-composition-source.md) records the whole-body
hash,81 guarded sites,12 virtual targets, callers, offsets, flags, source root
publication condition and new REA radius Evidence. [Original component results](collision-body-probe.md)
provide ten copied479D20/support numeric references. No original game entry point
or full Jimmy instance was executed by this implementation chunk.
OriginalBodyPhysics implements the true210/1C8/220/1D0, false228/42C,
prevent-lowering subset. It clears current support, consumes impulse once, adds
acceleration and gravity separately, splits nonpositive-Y motion into horizontal
response then fallingY, and preserves source callback/support/friction/suppression
order.370 clears positive vertical velocity/acceleration independently. Ordinary
374 and inherited37C do not move the root; special-contact worlds are rejected.
This justifies the fixed-W1/no-root-changing-contact publication subset. Future
special callbacks must implement fresh previous/live Vec4 comparison before314.
Landing diagnostics observe new root/zero acceleration and old velocity/support.
Published speed160 is separate from controller608, copied at the controlled tail.
Script preparation clears controller speed/velocity while preserving published
speed, pending impulse and acceleration. Friction reads the preserved body scalar;
control ownership does not suspend physics. The generic scale0.5 suppression and
unclamped friction0.8 follow source contracts. Nonzero angular component tests use
the probe's substituted334 Euler-add contract; the live bridge passes angular0.
Program selects source body only for VR04. Lab/outside retain their prior capsule
because they contain special contact materials and pending dynamic integration.
The source body rejects attaching the provisional dynamic resolver; Program also
asserts no prepared door colliders in this subset. This does not prove absence of
every original dynamic class: VR04 has3SOL/3ROC/3TRO and other eligibility questions.
Live radius is the existing InteractionRadius, which source260/264 prove is the
same body field15C. Burst60→100 changes both sphere response and support offset
75.9→126.5; later grounded wrapper restoration60 stays after physics and outside
the input ownership gate. The replay now records two support landings rather than
the previous capsule's one; radius/support transitions are retained, not flattened
to preserve the old diagnostic count. Maximum rise changes418.98→418.93 because
the source path removes the modern floor skin. Travel remains403.88 in this input
fixture. These are port observations, not original whole-game trajectory metrics.
ActorRoot/feet conversion remains constant75.9 and sole-based rendering remains
the existing modern bridge. Initial placement still uses the bounded floor query;
this does not derive original visual pivot/height or generic transform semantics.
Modern F3 noclip bypasses source physics and clears motion on exit; admission still
uses the capsule24/render-height occupancy check. It is a debug policy, not a
recovered radius60/100 overlap query. Full wrapper/registry remains open.
## Verification
Twenty managed body groups pass, independently reviewed: all ten original-code
numeric references; prior support/landing ownership; angular-before-suppression;
published-speed cutoffs; special-scene rejection; positive/nonpositive split;
ceiling370; radius100 support/unclamped friction; actual VR04 root/render bridge;
pending jump while uncontrolled; preparation/publication; retained jetpack/steering/
landing and noclip return. These tests compile into GamePort.BodyPhysicsTests and
are included in scripts/test.sh. Two existing explicit-source test projects now
include the new dependencies; the initial suite compilation failure is retained
in artifacts/body-composition/integration-initial.log, not reported as a pass.
Headless VR04300-frame replay and native Linux GTX1070/private Xvfb replay at
1920x1080 both pass with zero enabled Vulkan validation errors. Native SDL receives
move/brake/turn/jump and resizes800x600. Both end supported with one burst,
travel403.88, max rise418.93 and energy20 (VR04 exemption). Saved readback shows
the modern standing-foot bridge remains above the visible floor at the final
replay position; this is a port image check, not source pivot comparison.
Logs/readbacks: artifacts/body-composition/body-tests.log, tutorial-jetpack.log,
tutorial-jetpack.png and native/jetpack.log. Independent review is in
[collision-body-implementation-review.md](collision-body-implementation-review.md).
Full-suite, package and preservation results are recorded in progress.md after
their completion. No native Windows runtime result is inferred from cross-builds.
## Next bounded work
Recover original physical-list and pair-collision eligibility for VR04 actor
classes, plus dynamic nearest/last-polygon/reset order. Recover lab/outside's
Player160/164/FENCE/LADDER policies, including control and root ownership, before
using this body solver there. Keep the existing capsule baseline available for
comparison. Shared camera eye/DEFAULT handoff remains the next independent C5
contract; audio clock/banks and later implementation chunks retain their gates.
+122
View File
@@ -0,0 +1,122 @@
# C4 dispatcher and ordinary-body component evidence
2026-10-26 continuation, verified2026-10-27 UTC. Original EXE SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Originals remain unchanged. This report separates copied-code component execution
from the playable port, full original game behavior and native Windows testing.
## Recovered contracts and evidence
The [grid report](collision-grid-traversal.md) recovers47B4B0 recursion, frozen
query bounds, repeated FIFO cell visits and terminal callback ownership. The
[contact report](collision-contact-callbacks.md) recovers370/374/37C, special
material identity, separate published speed and friction. Those reports retain
addresses, file offsets, byte guards, callers, structures and REA Evidence.
Additional closed/exported REA sessions in artifacts/collision-integration/:
| Procedure | Evidence | Contract |
|---|---|---|
|47A330|ev_8be4a538fe941bcf0ba77ce64f552d4f0e17969ea87713cec5d37d39bc560735|Supported/nonzero-linear friction; published160 gates caller.|
|47C6E0|ev_ad96a93792dcf00534130fbd428fb52fa25e2cf9c2492df43f89f425b80c3f08|All-grid strict nearest support reduction, initial segment magnitude.|
|471120|ev_90314124d5ab1c88911198ef9e8d43ad7cc9e096ca075757d29c5e15cf1f86eb|Authored float8 writes live suppression scale through234.|
|470540|ev_c16f95e608194a8f9fb029430f1c6a01512d34099ebf447cf944946c79631166|Init copies authored flags/scalars through virtual setters.|
Body479D20 remains anchored by ev_5439072b32ae9f9208795ad2b07bc524e2407b46da487072fb3dfd8c10e7c4b0
in artifacts/collision-response/rea-response/. Generated source.json reports
PE-mapped offsets; the five added body hashes cover479D20/47A330/47B890/47C6E0/
469A10, alongside ten existing dispatcher/kernel bodies. Hashes and relocation
sites are checked by test_body_step_evidence.py; no arbitrary scan of executable
values is used at execution time. Short accessor recognition failures in rea-body
are retained beside successful replies, not represented as decompilation success.
## Isolated execution boundary
tools/binary/collision_dispatch_probe.c and body_step_probe.c map a generated,
hash-checked EXE copy into their own32bit process. Preferred-base mapping was
unavailable; existing guarded mapper rebases only explicit in-memory operands.
Fixtures supply synthetic grids, shape/polygon/corner arrays and virtual methods;
the body fixture supplies ordinary flags, radius60, factor1.265, friction0.8,
suppression scale0.5 and gravity(0,−800,0). No game entry point, full Jimmy
instance, source window/input/audio/script lifecycle or dynamic body pass runs.
Landing37C is an observer fixture; real ordinary Jimmy37C is a no-op.
reference_capture.py runs a separate generated Wine prefix/copy with no network
and no original-directory mount. Sources/header/identity metadata and logs are
under artifacts/collision-integration/dispatch/ and body-probe/. Initial fixture
failures are preserved: a missing Euler328 virtual was diagnosed and supplied,
and direct member42C has allocated zero storage. Those were harness omissions,
not original game defects. Automatic approval review temporarily failed due its
usage limit; after its stated reset time, a normal reviewed retry succeeded.
## Observed dispatcher results
All seven original fixtures completed with DISPATCH_COMPONENT_COMPLETE. Managed
OriginalStaticCollision regressions compare these positions and exact counts.
| Fixture | RootXYZ | Passes / primitive visits | Terminal callback |
|---|---|---|---|
|face retry|0,20,10|2 /4|wall0|
|edge retry|107.071068,100,7.07106781|2 /2|wall0|
|edges disabled|105,100,5|1 /1|none|
|zero motion|0,20,20|0 /0|none|
|forced zero/member42C|0,20,20|1 /2|none|
|corner retry|5,20,10.000001|2 /8|wall0|
|ceiling retry|0,90,0|2 /8|ceiling0|
## Observed body results
All ten copied479D20/support fixtures completed with BODY_COMPONENT_COMPLETE;
finite-output assertions pass. These are observations for the next body adapter,
not claims that a managed full-body equivalent already exists. dt is float1/60;
all unspecified vectors are zero. Initial previous support is false except jump.
| Fixture | Initial distinction | Observed result |
|---|---|---|
|floor support|RootY75.9|Y75.9000015, supported, callback sees Vy−13.333334/support=false.|
|spawn settle|RootY26|Same support root/landing observation.|
|pending jump|Supported, impulseY550, accelerationY−264|Y84.7711105, Vy532.266663, unsupported; impulse consumed.|
|fall above floor|Y100, Vy−200|Y96.4444427, Vy−213.333328, unsupported.|
|fall land|Y76, Vy−200|Y75.9000015, Vy0; callback sees old Vy−213.333328/support=false.|
|ground friction|V(100,0,50), angularY12, published speed0|Root(1.66666675,75.9000015,0.833333373); V(98.6666641,0,49.3333321), angularY11.8400002.|
|published speed|Same vectors, published speed100|Same root; V(100,0,50), angularY12, no friction.|
|stationary angular|Linear0, angularY12|AngularY12 remains; zero linear magnitude skips angular friction.|
|small motion|Vx0.125|RootX0.00208333344 then velocity suppressed to0.|
|geometry disabled|Vy200, accelerationY−264|Y75.9000015, Vy0, accelerationY800, supported, no landing callback.|
The geometry-disabled branch479DF7..479E54 sets supported, anchor and acceleration
before impulse/integration. It does not test prior grounded state. This corrects
the earlier C3 support-cancellation interpretation. With geometry enabled, the
jump fixture applies acceleration and gravity normally.
## Implementation and remaining gate
This section records the dispatcher-only stage. The subsequent
[ordinary-body implementation](collision-body-implementation.md) compares all ten
body references and enables the static subset in VR04; special/dynamic/root gates
below remain explicit for further expansion.
OriginalStaticCollision is currently an isolated source dispatcher/support-grid
component, invoked by tests. It preserves duplicate visits, retry state, negative
Z upper-bound quirk and terminal publication. Its explicit geometry-enable input
skips primitive calls but preserves terminal callback. TraceSupport uses strict
nearest reduction. The256-pass rejection is a defensive port boundary; original
recursion has no recovered depth limit. Double cell intermediates/modern quick
magnitude tables do not promise exact x87 boundary equivalence. Triangular route
metadata is required; general polygon fans are rejected by duplicate identity.
Prepared scenes now include signed3DMa archive IDs. Mesh keeps an explicit
identity-completeness flag; source grid construction rejects old prepared metadata.
Camera behavior is unchanged. Lab/outside contain special fence/climb/ladder IDs;
VR04 contains none. This is a scene-data fact, not proof every lab trajectory
contacts one or that all Player374 policies are implemented.
Next coherent implementation: combine the proven dispatcher with ordinary body
integration, negative-Y horizontal-first split, callback370, support/landing order,
published160 friction and suppression, comparing the ten references above. Start
with an explicit ordinary-contact subset (VR04); reject unsupported special policy
rather than silently discarding it. Then test model/root support, airborne input,
ceiling and tutorial/RETURN through the live adapter. Lab/outside require recovered
special160/164/FENCE/LADDER policies and dynamic shared nearest/last-polygon/reclip
ownership before replacement. Whole-scene registry/base transforms, camera shared
eye, original end-to-end comparison and native Windows validation remain open.
@@ -0,0 +1,253 @@
# C4 contact callbacks, landing and friction
2026-10-26. Static recovery for original EXE SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Addresses below are preferred VAs; these text offsets are VA−400000. The helper
maps PE sections independently and retains exact bytes, offsets, 20 virtual
targets and six complete callback hashes in
`artifacts/collision-integration/contacts/source-contract.json`.
## Recovered dispatch and state ownership
The game-interface pointer is complete object+C0. Slots below are relative to
that interface, not the complete-object movement slots130/134.
| Class/interface table |370|374|378|37C|
|---|---|---|---|---|
|C3DObject4D3154|472690|458890|472750|472970|
|C3DAnimated48FE1C|472690|458890|472750|472970|
|C3DPlayer4AF6C4|472690|43AA40|472750|472970|
|C3DJimmy4A373C|472690|42A660|472750|472970|
Static traversal47B4B0 publishes its candidate current root at47B7B1..BD,
then reads last-hit polygon695D4C. If present, it copies polygon+8..14 normal
and dispatches374 at47B80F if normal.Y is strictly greater than float32−0.7
(4A3148, bytes333333BF); otherwise370 at47B82E. Equality dispatches370.
The arguments are a by-value four-float normal and polygon pointer. This occurs
after grid/triangle response, before the body's later support/friction phase;
the supplied original stored normal is not derived from triangle winding.
370→472690 (raw72690, lengthBA) independently reads live velocity2BC and
acceleration270. A strictly positive Y is set to zero through2C0/274;
nonpositive Y and X/Z/W are preserved. It does not project against the supplied
normal or change movement mode, jump latch, fire timer or horizontal speed.
Generic374→458890 (raw58890, length3D) checks interface1D8, then forwards the
four-float normal to378→472750. Jimmy overrides374:42A660 (raw2A660,lengthB4)
forwards to Player43AA40 at42A70B on the ordinary path. It does **not** enter
generic374/378 on that path. Therefore generic reflection/projection must not be
attached to every Jimmy wall contact merely because base378 exists.
No-selection−1 and selected-jetpack3 both take this ordinary branch because
neither equals7 (selection identities recovered in retained-return-cleanup.md).
For a nonspecial metadata ID, neither state adds velocity, position, orientation,
mode, jump or gadget-side effects through374. This bounds the route's supported
states; it does not imply every material on the route is nonspecial.
Jimmy's gadget7 branch additionally checks global4F8210. When set, it invokes
Player contact, zeros global4F82BC/C0, tests their prior two-component magnitude
against60, and may invoke complete-object204 and set interface1D65. Those
gadget effects remain outside ordinary-contact integration.
## Player material handler
43AA40 (raw3AA40,length5A3) first requires interface774 elapsed>3.0. The signed
discriminator comes from polygon+4 → material+0C → database chunk+8; missing
records produce no ordinary effect. The follow-up below proves this is the
3DMa archive resource ID, not an additional custom payload flag. It remains
distinct from a merged render-array index or texture resource ID.
| Metadata ID | Effect after elapsed gate |
|---|---|
|120..129|Calls complete-object160 with supplied normal.|
|110..119|Calls complete-object164.|
|60..69, only mode704==0|Additional rays/orientation/root/action handling ending in FENCE.|
|180, only mode704==0|Additional rays/orientation/root/action handling ending in LADDER.|
|Others|Returns without generic velocity projection or mode/jump reset.|
These are dispatch facts, not complete recovery of the four special policies.
Complete160/164 effects and all ray success/failure transitions need separate
tracing before implementation. The ordinary callback has no raw-control5099E4
gate; controller ownership alone cannot justify suppressing contact effects.
## Material database identity and actual route coverage
OMT2.dll SHA256 is
`3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
The EXE chain above reaches OMediaDBObject's inherited database association:
| DLL VA / raw offset | Proven role |
|---|---|
|10030070 /30070, exported db_link|Arguments are database, OMediaFSChunk*, type.1003007F stores that chunk pointer in material/object+0C; chunk+0C is the reciprocal object pointer.|
|10030260 /30260, DBObjectStreamLink::read_class|Reads link fourcc through100302B3 and signed long ID through100302BF;100302EE calls database get_object(type,ID), stores resulting material pointer in temporary streamlink+4.|
|10003E20 /3E20, Polygon::read_class|10003F56 reads a temporary stream link;10003F5B obtains its pointer at temporary+4;10004277 calls set_material100043F0.10004408 publishes it in polygon+4, with material reference-count bookkeeping. The legacy-version path10004252..5E also uses set_material.|
|1002DEF0 /2DEF0, DataBase::get_object(type,long)|Looks up the requested chunk through formatted-stream slots6C/74, then passes that chunk to object's virtual18/db_link at1002E0B0.|
|10045B70 /45B70, FormattedStream::get_chunk(node,long)|Looks up signed ID in the chunk map, returns the corresponding chunk record (list-node+8).|
|100464C0 /464C0, FormattedStream::load_header|100465A7 reads ID into stack58;100465B4/C1 read offset/size into stack50/54;10046638..46 insert record starting stack50. Thus ID is chunk record+8.|
The on-disk source is the 0MF2 resource-table entry's big-endian32 identity,
not a field inside the 3DMa material payload. The payload parser's trailing BE16
is3 for every used material in all three archives, including special and
ordinary contacts. The helper records each material's exact table ID byte offset,
separate payload offset/size/hash, archive hash, and source shape/polygon identity.
Negative on-disk IDs require signed32 interpretation for policy comparisons;
all special route IDs below are positive.
| Archive | Special ID | Non-NC polygons using ID | Wall-grid polygons eligible for374 |
|---|---:|---:|---:|
|level1b.omt|61|23|20|
|level1b.omt|62|24|24|
|level1b.omt|63|4|4|
|level1b.omt|120|4|4|
|level1b.omt|121|32|20|
|level1b.omt|122|3|3|
|level1b.omt|180|6|6|
|VR04.omt|none|0|0|
|level1.omt|60|62|62|
|level1.omt|61|51|38|
|level1.omt|62|38|26|
|level1.omt|180|32|20|
Eligibility means registered shape and strictly−0.7<stored normal.Y<0.7:
the lower test dispatches374; the upper test is wall-grid registration. Route
checkpoint-name exclusions are zero (camera-ray-predicate.md). Counts do not
prove a particular player trajectory hits these polygons. LV1B examples are
crates/topcrate shapes76/77 with ID61, Box25/83 with62, Object07/91 with63,
Plane41/51 and Object03/73 with120, Cylinder13/22 andCylinder14/23 with121,
Object03/73 with122, Box31/93 with180. Level1 has fence/bush/blocks/ladder-class
polygons; names are explanatory labels, not policy evidence.
The route cannot be declared ordinary-only. Preserve linked3DMa identity in
CollisionPolygons, retain unsupported special callback boundaries, and test any
ordinary-only integration against the actual contacted polygon's ID. Resource
identity is now justified by the loader trace, rather than assumed from naming.
## Landing order
Support47B890's successful branch calls these virtuals in order:
1. 47BB32: publish root318.
2. 47BB4B: acceleration278, Y=0, retaining original X/Z.
3. 47BB5E: landing37C only if previous-support695D49 was false.
4. 47BB74: velocity2C4, Y=0, retaining original X/Z.
5. 47BB80: support21C=true.
6. 47BB91/47BBA1: contact shape34C and polygon33C.
Jimmy37C→472970 (raw72970) is exactly `C3`/return. Thus the landing callback
would observe the new root/zero vertical acceleration but old velocity/support;
Jimmy itself adds no mode/jump/fire reset here. Controlled movement and the
independent fire callback own their later grounded transitions. Do not merge
these source phases into a universal landing-mode reset.
## Friction and speed publication
479D20 calls support47B890 at47A235 when interface1C8 permits it. It then reads
268 at47A241 and calls47A330 at47A25A only if the returned scalar equals0.
268→471B50 reads interface160. The controlled movement tail437C22 reads its
current scalar speed608, pushes it at437C2A and publishes through26C at437C2D;
26C→471B60 writes160. Publication follows ground/air apply and is skipped by
the earlier ownership/modal gates. Treat published160 and controller608 as
separate state with that copy point, not a fresh input query during friction.
47A330 (raw7A330,lengthF1) requires a nonnull body, support218=true and strictly
positive imported quick_magnitude of the full linear XYZ vector. It reads
friction248→471AD0/live150. It adds these deltas through2CC and2B8:
```
linear delta = (-vx * friction * dt, 0, -vz * friction * dt)
angular delta = (-wx * friction * dt, -wy * friction * dt, -wz * friction * dt)
```
No multiplier clamp is present. Zero linear velocity skips angular friction too;
pure vertical linear motion permits angular friction but leaves vertical speed.
No controller pointer, movement mode, jump or animation state gates this helper.
The enclosing body's later suppression is distinct:230→471A70/live144 scales
quick_magnitude. Angular magnitude×144 <=float32(0.1) zeros angular velocity;
linear magnitude×144 <=0.1 zeros linear velocity only when268==0. The finite
equality boundary is included by the AH&41 tests at47A2C5/47A2FA. The semantic
name of144 is not established by this bounded contact investigation. Follow-up
REA471120 and constructor46FE01..08 recover the default0.5; this is called a
suppression scale in the implementation plan without assigning physical units.
Constructor byte confirmation: generic46FDC8→470FA0 sets1C8/live13B true;
46FDD1→470FD0 sets1D0/live13C true;208/live13A starts false at46FDBF but
Player43740D→470F70 overrides it true (EDI=1).220/live140 defaults true through
46FDF4→4710C0 (authored18);228/live141 defaults false through46FDFC→4710F0
(authored19). Generic46FFB1 writes interface42C=BL=0, with EBX zero at46FC08.
These are constructor defaults, not invariants after property/script changes.
## Evidence and verification
Own REA CLI sessions used only the generated
`artifacts/uncontrolled-phases/rea/Neutron.exe`, Ghidra provider. Complete open,
procedure replies, exported evidence, close and snapshot files are preserved in
`artifacts/collision-integration/contacts/rea-callbacks/` and
`rea-offset-followup/`. Both sessions closed. Session analysis errors are also
preserved;42A660 and472750 were unrecognized by both VA and corrected raw-offset
selectors. This is a REA procedure-recognition limitation, not evidence of an
absent function. Their bounded conclusions use reviewed source instructions and
fixed byte/vtable guards; no pseudocode is attributed to those failed queries.
| Procedure | REA Evidence ID |
|---|---|
|472690|ev_122849f87121b02fefe6a3a443f75c7f02fee30c59c816b617d30e1f98fc2cff|
|43AA40|ev_4f2a6aa666451db831efd46f5c587573e22d8072315626b8bc2f844f9c6f0cae|
|47A330|ev_8be4a538fe941bcf0ba77ce64f552d4f0e17969ea87713cec5d37d39bc560735|
|472970|ev_1af0165b36fee8d2c680091bdaa560a63092016b1010baa947b0fe672f790520|
|458890|ev_2e4ec83ea68f06777162a80ab45793cff068e973dc248556d4a408932d24c85a|
Caller/traversal evidence is reused from collision-response.md, especially
479D20 `ev_5439072b32ae9f9208795ad2b07bc524e2407b46da487072fb3dfd8c10e7c4b0`
and47B4B0 `ev_d45e078c585d3773494c0e0dfb1696178dd0b8ce8b696caf133892ff070e552e`.
Reviewed instruction cache: `artifacts/retained-lifecycle/exe-disassembly.txt`.
`python3 -m unittest discover -s tests -p test_collision_contact_callbacks.py -v`
passes eight tests: original identity/50 sites/20 virtuals/six complete bodies,
normal threshold equality, independent positive-Y clearing, material branch
boundaries, no-selection/jetpack gadget exclusion, friction gates/no clamp, and
landing callback observation order;11 DLL linkage/header/publication byte guards plus
decoded route special-ID coverage and payload/table distinction.
The helper fixtures are explicit source projections, not original execution or
x87 numeric identity. No original process ran during the independent callback
investigation; primary's later isolated dispatcher/body executions are documented
separately in collision-body-probe.md.
Confidence is high for guarded targets, finite-input gates and write order;
special callback policy and native runtime equivalence remain unverified.
Follow-up own closed REA sessions and complete exports are in
`artifacts/collision-integration/contacts/rea-material-identity/` and
`rea-material-chunks/` and `rea-polygon-material-link/`, using the generated
asset-probe/game/OMT2.dll copy. All three sessions closed and exported evidence.
| Procedure | REA Evidence ID |
|---|---|
|10030070 db_link|ev_68d90891887ea6865b9caa01929af4c321701bd7c4a2812727fdf42c75cc4007|
|1002DEF0 get_object|ev_81d436d02d94e725815b1f09da5e5a70d12a65a699580a4f4d766fd637e25c9a|
|10030260 stream link|ev_a36a19b371e3f9202b8e7b44f6756593081a18da9f24dcb3a23fcdd92836ad9a|
|10001490 material read|ev_f592b625a60ec683a17627d671c47d78d722eb39d5eb407744d53a283ee2586d|
|10045B70 get_chunk|ev_1eef58e78dd2025953bfc6d29d750992ad031eff3ade40848b565b70493a51af|
|100464C0 load_header|ev_25667da3ab34f3e3a238282bf667878fa957db0b59501f737178637dd8fe2d61|
|100451E0 create_chunk|ev_bb9a4656bc3b4cc1ebd2ce7da540b2f5d633632cc70b9548f30942e52c806868|
|10003E20 polygon read|ev_a611c0c32859d598bd4f02c071cc8f57dec8e85c821593187d3ea6d0b2db18cb|
|100043F0 set_material|ev_66c8163e76d1c4621dd75dbad433b6810d7dc6f69da84d4bdcd6644df935736b|
|10073E00 stream operator|ev_01e2fb540f6adee163371853f0823abcd4a67553b0dc7d067ef88a448ce87740|
## Minimal implementation contract and limits
OriginalSphereResponse currently implements only the bounded triangle kernel;
LabSimulation still calls its capsule adapter at inspection time. Integration
should retain the original traversal's final contact polygon and stored normal,
publish the root before contact dispatch, apply inherited370 positive-Y clearing,
and preserve ordinary374's material-policy boundary. Then run support in its
source order, friction using persisted published160, and separate small-motion
suppression. Contact callbacks are eligible when Jimmy is uncontrolled if the
body phase itself runs; they do not grant input ownership.
Do not add generic horizontal velocity projection, automatic jump/mode reset,
or unconditional friction to compensate for adapter symptoms. Static geometry
order/duplicate visits, dynamic reclipping, negative-Y split and support query
coverage belong to the separate body integration trace. Generic378's complete
reflection arithmetic, special materials, gadget7, runtime-mutated flags,
144 semantics, NaNs and x87 threshold identity remain explicit gaps. Native
Windows gameplay and the lab→tutorial→lab→outside route still require runtime
comparison after integration; these static fixtures do not claim that proof.
+142
View File
@@ -0,0 +1,142 @@
# C4: static grid traversal and retry ownership
2026-10-26. Recovered from EXE SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
These are source facts, with local algorithm fixtures; this investigation did not
execute the original grid dispatcher. VAs below map to EXE offsets by subtracting
400000; uninitialized globals have no file-backed offset. The helper reports PE
mapped offsets and raw bytes independently.
## Dispatcher contract
47B4B0(actor interface, mutable previous-root Vec4 pointer, delta Vec4 by value,
edge-enable byte) computes quick_magnitude(delta) at47B4BB. Actor **member byte
+42C**, not a virtual method, forces processing. Otherwise magnitude below
FLT_EPSILON(1.1920928955078125e-7;4D5E40) returns without moving the root.
Equality processes. Candidate XYZ starts as previous+delta, W=1. Actor virtual260
returns radius. Bounds use extent E=radius+quick_magnitude(delta).
For C(v)=signed16(truncate(v*float(0.002)+130)), the frozen bounds are:
| Bound | Source expression |
|---|---|
|xmin|min(C(previousX−E), C(candidateX−E))|
|xmax|max(C(previousX+E), C(candidateX+E))|
|zmin|min(C(previousZ−E), C(candidateZ−E))|
|zmax|**min**(C(previousZ+E), C(candidateZ+E))|
The asymmetric zmax is explicit:47B61B `cmp di,ax`;47B61E stores DI;
47B624 `jl` keeps DI if smaller, otherwise47B626 stores AX. xmax uses the
opposite comparison at47B59B. Do not substitute a conventional swept-AABB union.
Scale4D6A04 is float0.0020000000949949026; origin49B1FC is130.
X increases in the outer loop, Z in the inner, both inclusive. Coordinates outside
0..259 are skipped. Wall grid509B24 cell record is12bytes at
grid+12*(260*x+z). Its pointer is the circular-list sentinel. Nodes contain next0,
previous4, registration8. Registration contains polygon pointer0 and shape pointer4.
Traversal follows next pointers in insertion order; the same polygon in several
cells is visited repeatedly. Bounds stay frozen while the candidate mutates.
47B6B2 checks global collision-enable4F69E5 per node. A disabled visit still
increments counters and advances the node; dispatcher position publication still
occurs. Before47BBB0, member42C sets695D74=1 when nonzero;47B742 unconditionally
clears it after the wrapper. This is the primitive's lower-edge override, separate
from the caller's edge-enable flag, forwarded unchanged at47B6FE.
47BBB0 receives the previous root **by value**, the shared mutable candidate
pointer, radius, stored polygon normal and edge flag. The first three source
corners are fetched by477F10. A successful47BD80 result stores this polygon in
695D4C and writes the caller's local retry byte at47BD65..47BD6B. Nearest face
695D5C, nearest edge5CFBE0, hit point5CFBE8..5CFBF4 and695D4C persist across all
visits; dispatcher entry does not clear them.
## Retry, publication and callbacks
REA/Ghidra00.pseudo.txt incorrectly reports47B83C unreachable. Missing output
parameter types hide47BBB0's retry-byte mutation. Instruction evidence is decisive:
47B535 clears local byte;47B799 tests it and47B79F branches to47B83C after a hit.
47B83C..47B867 replaces the by-value delta with candidate−*previousRoot.
47B877 pushes the **same previous-root pointer**, then actor, and47B879 recursively
calls47B4B0 with the same edge flag. This body has no explicit recursion-depth
guard;695D78 is an incremented statistic, not a limit. Do not infer dead code or
a depth cap from decompiler output.
The previous-root pointer is not overwritten before retry. Only the deepest pass
with no newly accepted contact writes candidate XYZ and W=1 to it
(47B7A5..47B7BD). If695D4C is nonnull, that final pass reads the **last accepted
polygon** normal+8/+C/+10/+14, even if this pass accepted no contact. It invokes
actor virtual374 when normal.Y>−0.7, otherwise370; equality selects370.
Both callbacks receive normal Vec4 and polygon pointer. Actor logical position
is written later by the enclosing movement caller's virtual314, so publication
through a stack vector does not itself prove the actor transform has changed.
The body integrator479D20 clears last polygon at47A038, initializes face distance
to **130000** at47A03E (bits47FDE800), and edge distance to radius at47A062.
The isolated primitive's −1 face sentinel is not the body-entry initialization.
Dynamic reclip47B364 calls this same dispatcher with edges=false (47B30B), then
publishes actor root through314 at47B399. It inherits nearest state: dynamic
entry separately sets edge=radius at47AB3F and face=−1 at47AB4B. No dynamic clear
of695D4C was found; identified absolute writes are47A038 and47BD65. Its caller
schedule remains relevant when interpreting retained last-polygon callbacks.
## Registration and source layout
479140 walks shape polygon array begin+88/end+8C in48byte strides; it applies
checkpoint4794C0 and game-specific4797A0 filters before registration. Existing
[camera-ray evidence](camera-ray-predicate.md) establishes scene44DBF0's ascending
shape resource-index traversal. No new decorative/material rule is inferred here.
Game filter4797A0 calls the game's virtual134 at4797EC.
Each polygon's **all-corner** X/Z extrema determine registration cells using the
same conversion and inclusive X-outer/Z-inner order. Registration upper Z is a
conventional maximum, unlike query zmax. A28byte registration allocation stores
polygon0, shape4, centerXYZ8/C/10, W14 and radius18; bounds/candidate traversal do
not use this center/radius as a per-visit cull. Record is shared across its cells.
479800 rejects a duplicate polygon pointer within one cell (47985E..479866),
irrespective of shape pointer. New nodes append FIFO to all-grid5CFC7C
(47989F..4798A8), and wall-grid509B24 only when stored normal.Y<0.7
(4798B3..4798CF); equality is excluded. There is no query-wide deduplication.
477F10(out,shape,polygon,signed-short corner) reads polygon+24 corner records,
20bytes each. Their first DWORD is a vertex index into shape+68 Vec4 vertices,
16bytes each. It copies the selected Vec4 without transforming it. The wrapper
uses corners0/1/2 even though registration bounds use all corners.
## Evidence and implementation boundary
Owned REA CLI session used a generated copy, closed normally and retained complete
replies/export/snapshot in artifacts/collision-integration/grid/rea/:
| Procedure | Evidence ID |
|---|---|
|47B4B0|ev_f39128dafc2a3a20b5768613ce22b3c3168fe8653908837d92ad9a69ef5f2ad8|
|479140|ev_c6bffe721e0751327ecdb5e62c27137752574be6624c190a833c5b2c0f5be7b0|
|4797A0|ev_277ddc7e6b8383ea4245072e395a3dda51cd530c56fb160b917823803f55d33f|
dispatcher.instructions.txt retains the reachable retry instructions;
source-anchors.json records raw anchors, offsets, constants and four function-body
hashes. tests/test_collision_grid_traversal.py guards source bytes plus five
fixture groups: asymmetric bounds, clipped/inclusive order, per-cell duplicate
rules, mutable candidate and retained nearest/last-polygon across passes.
Minimal integration: build source-order wall cells; pass an explicit shared nearest
state into existing OriginalSphereResponse; scan frozen bounds with a mutable
candidate; retry revised displacement against unchanged previous root; then publish
and dispatch the last-polygon normal callback once. Reuse this dispatcher for
dynamic reclip without adding implicit state resets. A defensive port recursion
limit would be a documented implementation deviation, not recovered behavior.
Follow-up original dispatcher execution completed seven synthetic grid cases;
see collision-body-probe.md for outputs, fixture boundaries and managed comparison.
OriginalStaticCollision implements the bounded traversal as an isolated component;
it is not yet the live player solver. Geometry-disabled traversal preserves
terminal publication and retained callback; it skips primitive calls per visit.
TraceSupport initializes its strict nearest limit to quick_magnitude(end−start).
Prepared route geometry carries signed archive material IDs and rejects missing
identity metadata before special-contact coverage is assessed.
Unresolved: x87 cell
conversion at integer boundaries and extreme signed-short wrap; full scheduler
ownership of global collision toggles and retained dynamic last-polygon state.
The local projection does not establish numerical identity at those boundaries
or runtime correctness of the integrated port.
@@ -0,0 +1,64 @@
# C4 static dispatcher review
2026-10-26. Independent source review of the uncommitted static dispatcher,
its managed fixtures, saved REA replies and retained original-component output.
No original code was executed and no new REA session was opened by this review.
File ownership for this report only; primary owns integration and corrections.
## Findings and disposition
- **Corrected during review:** `TraceSupport` initially accepted its first
triangle hit without the source's initial nearest-distance limit. Retained
REA support reply `artifacts/collision-integration/rea-support/00.json`,
Evidence `ev_ad96a93792dcf00534130fbd428fb52fa25e2cf9c2492df43f89f425b80c3f08`,
initializes47C6E0's nearest distance to quick_magnitude(end−start), then
requires a strictly smaller hit magnitude. The kernel's parameter-distance
check is separate from the returned hit's magnitude. Primary added that
initial limit and strict comparison. This closes a source-contract omission;
no original numeric boundary probe is claimed.
- **Corrected during review:** old prepared meshes could omit material IDs and
appear ordinary-only. Primary added explicit material-identity completeness
metadata and a `FromRouteScene` rejection requiring newly prepared scenes.
Resolved null-material identity remains distinct from missing metadata.
- **Corrected after review:** `Move` now accepts the source geometry-enable state.
Source47B4B0 reads4F69E5 per node, while its final publication and retained
last-polygon callback can still occur when geometry is disabled. A caller
must not equate disabling geometry with skipping `Move` when it reuses a
context. The added regression checks publication and retained callback without
primitive visits. Dynamic shared-state/reset timing remains a live gate.
- **Live integration gate:** the dispatcher returns a candidate and terminal
polygon; it does not publish the logical actor transform or execute callback
370/374, support, friction or speed publication. Jimmy ordinary374 must retain
the special-material boundary. LV1B/LEV1 contain such materials; VR04's
absence of them is a bounded route-data result, not a general player policy.
- **Documented port limits:** iterative retry rejection after256 passes,
finite inputs, triangular polygons and approximate x87 cell conversion are
explicit boundaries. Do not promote this component to whole-body identity
or claim the source has a recursion cap.
## Verification
`source scripts/env.sh && dotnet run --project
tests/GamePort.StaticCollisionTests` passed seven groups during review. The
seven printed copied-original dispatcher cases in
`artifacts/collision-integration/dispatch/wine.log` match the managed fixtures'
positions, pass/visit counts and terminal polygon observations. The retained
marker is `DISPATCH_COMPONENT_COMPLETE`; the reviewer did not rerun that probe.
This verifies a bounded original component comparison, not live port gameplay.
Primary's subsequent focused run passes eleven groups, adding actual prepared
route material coverage, legacy metadata rejection, geometry-disabled retained
context, equal support ties and zero-length limits. Full integration passes122
Python checks plus HUD/managed/GPU/audio/hash checks; see progress.md for scope.
Registration sorting, X-outer/Z-inner traversal, per-cell duplicate visits,
frozen bounds including source MIN upper-Z, unchanged previous root across
retries, persistent nearest state and terminal-only callback selection agree
with collision-grid-traversal.md and its retained instruction/REA evidence.
Before enabling live body response, extend regression coverage to inherited
nearest/last-polygon state across separate dynamic reclip calls, equal-distance
support ties, and callback ownership/order after publication. Complete the
source contact policies and route/root checks identified by the implementation
ledger. After the stated review reset time, primary retried through normal
approval review and completed the ten-fixture isolated body probe. This closes
that execution blocker, but does not establish live whole-body equivalence.
+109
View File
@@ -0,0 +1,109 @@
# C4: original sphere/triangle response
2026-10-26. Original EXE SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Preferred VAs are used below; EXE text file offsets are VA minus400000.
The helper independently maps PE sections and guards six complete function bodies.
## Recovered contract
479D20 integrates body motion, invokes static response47B4B0, then support47B890
and friction47A330. Static47B4B0 traverses the wall grid, invoking47BBB0 for each
candidate.47BBB0 fetches the first three source polygon vertices through477F10,
then invokes47BD80. Dynamic mode2's twelve box triangles also invoke47BD80
(dynamic-collision.md). Stored polygon normals and winding are independent inputs.
47BD80 takes five by-value four-float records (triangle A/B/C, stored normal,
previous root), a mutable current-root pointer, radius, and an edge-enable byte.
It uses shared nearest state:695D5C face distance,5CFBE0 edge distance,
5CFBE8..5CFBF4 hit point,695D74 lower-edge override. Callers initialize/retain this
state; component tests deliberately supply explicit initial values.
| Path / source range | Recovered transition |
|---|---|
|47BD86..47BE34|Compute normal×radius and endpoint=current−offset, retaining max(currentY,endpointY); build segment469530 from previous root to endpoint.|
|47BEBA..47BFAD|One-sided469B70 triangle ray. A strictly nearer hit updates695D5C and hit point. Root becomes hit+offset in X/Z; Y changes only for normal.Y<−0.7. A farther/equal face returns false without edge fallback.|
|47BFAE..47BFED|Only a failed face query may enter edges. Requires edge flag and strictly −0.7<normal.Y<0.7.|
|47C048..47C08C|4695B0 finds nearest point among the three edge segments, including endpoints. Without695D74, an edge below current root is rejected.|
|47C092..47C150|Normalize root-to-edge using quick_magnitude; require dot(direction,storedNormal)<0 and strictly nearer than5CFBE0 (−1 sentinel allowed).|
|47C194..47C1F8|Write edge point−direction×radius in X/Z, preserve root Y, update edge distance and hit point.|
469880 projects onto a segment using its quick_magnitude-normalized direction,
clamping to either endpoint.4695B0 compares edge distances with quick_magnitude;
ties prefer BC over AB, then CA over either.47B4B0 finally publishes the candidate
and dispatches normal callbacks370/374. The inspected function does not implement
the previously inferred generic recursive capsule slide. That older description
in original-collision.md is superseded by this bounded trace.
## REA evidence
Complete replies, exports and closed-session snapshots are in
artifacts/collision-response/rea-response/ and rea-kernels/.
| Procedure | Evidence ID |
|---|---|
|47BD80|ev_28147145c0fee39c39936e4180890f321711688d6617d1b8314a12bf45a2e565|
|479D20|ev_5439072b32ae9f9208795ad2b07bc524e2407b46da487072fb3dfd8c10e7c4b0|
|47BBB0|ev_6e0dbae6267e87abbd0e4816b613923549b0f0787a26d7003d1a0e38fc733809|
|47B4B0|ev_d45e078c585d3773494c0e0dfb1696178dd0b8ce8b696caf133892ff070e552e|
|469530|ev_4fef4d32d2c8b30c306cd742fb9daeb93aa1fa36d4edf0ecaa87497e314dc50e|
|4695B0|ev_5e39f2668d04b1fdd2c91b298a28413327dc3879e6b8bbffe0a14bc1dcbc1128|
REA/Ghidra has incomplete C++ parameter/stack types here; apparent uninitialized
locals and missing arguments were resolved against instructions and the copied
component probe. The47B9F0 interior query resolved to47B890, not a new function.
Pseudocode is static evidence, separate from the execution below.
## Isolated original execution
collision_response_probe.c maps a copied EXE without its entry point/import
initialization, binds only quick_magnitude to copied OMT2.dll, disables debug
drawing, and executes47BD80 on synthetic geometry. Six callgraph bodies and all
selected absolute memory operands are guarded by collision_response.py. Because
the preferred base was occupied in Wine, only these explicit operands are
rebased in the generated in-memory copy. This fixture relocation is not recovered
source loader behavior. No on-disk original is patched.
The existing reference_capture.py namespace exposes generated copies only, with
no network and no Original mount. Final wine.log records ten cases and
COLLISION_COMPONENT_COMPLETE, exit0. An initial incomplete-prefix attempt failed
to load kernel32; a complete copied prefix fixed that. Two preferred-base attempts
failed before any source execution; guarded rebasing resolved that host issue.
Observed references: wall face/crossing roots(0,20,10), departing contact false,
edge root(107.071068,100,7.07106781), edge flag disabled false; lower-edge mode0
rejects while mode1 yields(105.77375,105,5.7737484); ceiling root(0,90,0).
These are isolated kernel results, not full original gameplay or native Windows.
Reproduction after preparing the isolated copied installation/prefix described in
docs/reference-testing.md (wait for copy completion before starting Wine):
```sh
python3 tools/binary/collision_response.py ../Original \
--target-copy artifacts/collision-response/original-probe/game/Neutron.exe \
--probe-header artifacts/collision-response/collision_response_relocations.h
i686-w64-mingw32-gcc -O0 -Wall -Wextra -Iartifacts/collision-response \
-Wl,--image-base,0x14000000 tools/binary/collision_response_probe.c \
-o artifacts/collision-response/collision_response_probe.exe
python3 tools/recon/reference_capture.py --asset-probe \
--probe-executable artifacts/collision-response/collision_response_probe.exe \
--probe-success COLLISION_COMPONENT_COMPLETE --seconds 9 \
--output artifacts/collision-response/original-probe
```
## Implementation and remaining gate
OriginalSphereResponse.cs translates this bounded kernel, with explicit nearest
state and contact type. Five managed groups cover original numeric references,
winding, edge/lower-edge switches, ceiling Y, nearest/ties and finite input.
Zero-distance edge normalization is explicitly outside the bounded contract; the
port returns no contact instead of propagating the source's undefined arithmetic.
Modern arithmetic is not an x87 boundary oracle.
The live player and dynamic response still use the provisional capsule adapter.
Integration requires original grid bounds/order/duplicate visits, negative-Y
motion split, previous-root writes, normal/landing callbacks, support/friction
and dynamic reclipping. Replacing only a radius would not satisfy that gate.
The narrow lab doorway snapshot from control-phase-implementation.md remains
the first integrated response case. No claimed recovery of stairs or complete
body response follows from this kernel alone.
@@ -73,7 +73,7 @@ the authority for that callback. Partial batches preserve successful Evidence.
Remaining: full424600 wrapper timers/UI/sound cleanup, base40E050/462520 Remaining: full424600 wrapper timers/UI/sound cleanup, base40E050/462520
resource/transform/morph policies, collision-triggered ceiling cancellation, resource/transform/morph policies, collision-triggered ceiling cancellation,
scooter radius160 and other gadget/class cases, original body registration and Bubble/mode0 radius160 and other gadget/class cases, original body registration and
response, complete registry and engine cadence, shared viewport handoff and response, complete registry and engine cadence, shared viewport handoff and
original whole-game comparison. Calling the entire controller with empty input original whole-game comparison. Calling the entire controller with empty input
would not implement these missing phases. Existing capsule/yaw/camera adapters would not implement these missing phases. Existing capsule/yaw/camera adapters
+4 -4
View File
@@ -14,16 +14,16 @@ runtime comparison. Coverage does not mean implementation completeness.
|---|---|---|---|---| |---|---|---|---|---|
| LOOP | Viewport47E4F0 physics before registry473740, including input44DF80; second sync473770; construction order and selective retained-character/new-game ordering. Separate engine morph clock. | Player now integrates prior body state, then fresh input/player/fire or retained player/fire/input. Uncontrolled body/fire now continue while movement/input are gated. Other systems remain grouped; fixed60Hz policy. | S/M/R. Controlled player partial order implemented; bounded raw-owner preparation implemented; full wrapper/registry/cadence open. | C3 continue other callbacks and morph/control phases; C4 support/response remains separate. | | LOOP | Viewport47E4F0 physics before registry473740, including input44DF80; second sync473770; construction order and selective retained-character/new-game ordering. Separate engine morph clock. | Player now integrates prior body state, then fresh input/player/fire or retained player/fire/input. Uncontrolled body/fire now continue while movement/input are gated. Other systems remain grouped; fixed60Hz policy. | S/M/R. Controlled player partial order implemented; bounded raw-owner preparation implemented; full wrapper/registry/cadence open. | C3 continue other callbacks and morph/control phases; C4 support/response remains separate. |
| INPUT | Game interface+8C slot3C4→44DF80→475A70 reads controlled5099E4 and calls3CC; Jimmy interface+C0→426030. | SDL arrows/jump aliases; control gate, modern debug override; mouse/controller incomplete. | S/M/R, user Windows route. Input occurs in object traversal after physics; device sampling/focus and latency open. | Trace event pump, key/mouse and focus gates alongside retained registry order. | | INPUT | Game interface+8C slot3C4→44DF80→475A70 reads controlled5099E4 and calls3CC; Jimmy interface+C0→426030. | SDL arrows/jump aliases; control gate, modern debug override; mouse/controller incomplete. | S/M/R, user Windows route. Input occurs in object traversal after physics; device sampling/focus and latency open. | Trace event pump, key/mouse and focus gates alongside retained registry order. |
| MOVE |437940/439900 ground/air arithmetic; physics479D20 consumes queued impulse once before acceleration/gravity. | Controlled player consumes prior body state before callbacks; fresh/retained input order explicit. Fixed dt and custom yaw/model conventions remain. | S/P/M/R. Controlled partial phase split verified; uncontrolled/full registry and body response open. | Continue C3 uncontrolled phases, then C4 support/response. | | MOVE |437940/439900 ground/air;479D20 impulse→acceleration→gravity; authored114→26C body speed separate from controller608. | Body/fire continue without control; input/controller gated. VR04 uses ordinary source static body and variable radius; lab/outside capsule retained. Fresh/retained order and overhead wrapper explicit. | S/P/M/R. Source body references/phase checks and native VR04 flight pass; complete registry/base/transform/cadence open. | Continue dynamic/special C4 contracts and C3 base transforms; preserve published speed ownership across preparation/Init. |
| JET |437F90 controller;421FB0 effect; fresh constructor order places fire after Jimmy, both after global physics. States0..5, hold>.4,8s, energy. | Explicit state table with post-collision effect ticking and VR immunity. | S/M/R. Fresh same-pass countdown recovered; retained child lifecycle, sound and expiry→animation open. | Trace retained Jimmy/fire resets and phase end events before scheduler integration. | | JET |437F90 controller;421FB0 effect; fresh constructor order places fire after Jimmy, both after global physics. States0..5, hold>.4,8s, energy. | Explicit state table with post-collision effect ticking and VR immunity. | S/M/R. Fresh same-pass countdown recovered; retained child lifecycle, sound and expiry→animation open. | Trace retained Jimmy/fire resets and phase end events before scheduler integration. |
| COLL |479D20/47BD80 body response; support and quick magnitude; dynamic boxes; NC-shape registration exclusion. | Source support and box pieces around modern swept24-unit capsule, feet/root grounding and slide. | S/P/M/R. Response/masks/stairs/contact order not fully recovered; source radius60 is not port capsule24. | C4: isolate response and root convention; replace adapter behind route tests. | | COLL |479D20/47BD80 body;47B4B0 FIFO grid/retries;370/374/37C; signed material IDs; separate160 friction; radius60/100 and support/suppression. | VR04 uses ordinary source static body/support/friction; lab/outside keep24-unit capsule. Root+150 wrapper live for route. Dynamic response remains provisional. | S/P/M/R. Ten original kernel, seven dispatcher, ten body references matched in managed composition;20 body groups and native/headless VR04 replay. Special/dynamic classes and visual transform open. | C4: recover original actor physical/pair eligibility and shared dynamic context; lab/outside need160/164/FENCE/LADDER before solver expansion. |
| ANIM | Engine morph10002DB0; linear interpolation10002F9A; game logical→OMT sync4624B0. | ASE sample timing, unconditional loop closure, pose/action aliases,1/60 advance. | S/P/M/R. Playback flags, rate, completion callbacks, transition order open. | Recover one-shot/loop/end notifications before more aliases. | | ANIM | Engine morph10002DB0; linear interpolation10002F9A; game logical→OMT sync4624B0. | ASE sample timing, unconditional loop closure, pose/action aliases,1/60 advance. | S/P/M/R. Playback flags, rate, completion callbacks, transition order open. | Recover one-shot/loop/end notifications before more aliases. |
| SCRIPT | Source AI/CAM/MCA dispatch and chains; task45F990 objective406F50 BEFORE records BEFORE per-entity424. | Pre-assignment objective selection and per-actor Carl override implemented; bounded synchronous director. | S/M/R. Script callbacks recovered for route; generic class coverage and reentrancy incomplete. | Continue other class-specific callbacks and reentrancy under the recovered owner/phase boundaries. | | SCRIPT | Source AI/CAM/MCA dispatch and chains; task45F990 objective406F50 BEFORE records BEFORE per-entity424. | Pre-assignment objective selection and per-actor Carl override implemented; bounded synchronous director. | S/M/R. Script callbacks recovered for route; generic class coverage and reentrancy incomplete. | Continue other class-specific callbacks and reentrancy under the recovered owner/phase boundaries. |
| CONTROL | Global5099E4 null during valid CAM/MCA; PlayerControlled completion target; DEFAULT447D..447F restores camera/UI/music. | Director raw ownership plus explicit debug effective override; eligible player body/fire continue; only input/controller tail is gated. | S/M/R. Raw/effective control and ordered preparation are implemented; full base/class wrappers and scheduler remain incomplete. | Continue full wrapper/base and collision contact phases around deferred LOAD. | | CONTROL | Global5099E4 null during valid CAM/MCA; PlayerControlled completion target; DEFAULT447D..447F restores camera/UI/music. | Director raw ownership plus explicit debug effective override; eligible player body/fire continue; only input/controller tail is gated. | S/M/R. Raw/effective control and ordered preparation are implemented; full base/class wrappers and scheduler remain incomplete. | Continue full wrapper/base and collision contact phases around deferred LOAD. |
| CAMERA | Shared viewport; strict>1000 DEFAULT snap; source eye correction/gain; first wall-grid hit then general-grid FIFO; per-level far planes. | Static source query now integrated for the three route scenes; other scenes use provisional sweep. Separate chase/script eyes and merged clip maximum remain. | S/M/R. Query/kernel/counts tested; x87 boundaries, shared handoff/previous-eye and input branches open. | C5 next shared viewport/DEFAULT and complete follow state. | | CAMERA | Shared viewport eye is recaptured by ground/air follow after scripts; strict>1000 DEFAULT snap; aim uses pre-update eye; source ray/gain and per-level far planes. | Static source query integrated for the three route scenes; other scenes use provisional sweep. Separate chase/script eyes and merged clip maximum remain. | S/M/R. Handoff source bytes/projections recovered, not implemented; full follow/input/quantization and visual comparison open. | C5 shared viewport eye/aim and DEFAULT transition; preserve source phase boundary. |
| AUDIO | CAM416776..E1 stops music; DEFAULT447F12..45 restarts; bank696008 / gate4F8434; handle47D890 polls inherited software duration and repeat+30. | Separate SDL streams, floating-file-duration cutscene completion, independent per-file SFX. | S/M/R (dummy streams). Source duration/allocation/play-failure/bank/attenuation lifecycle incomplete; speakers/native Windows timing not verified. | C6: explicit bank owner and software channel-clock tests; SDL queue-empty is not the source oracle. | | AUDIO | CAM416776..E1 stops music; DEFAULT447F12..45 restarts; bank696008 / gate4F8434; handle47D890 polls inherited software duration and repeat+30. | Separate SDL streams, floating-file-duration cutscene completion, independent per-file SFX. | S/M/R (dummy streams). Source duration/allocation/play-failure/bank/attenuation lifecycle incomplete; speakers/native Windows timing not verified. | C6: explicit bank owner and software channel-clock tests; SDL queue-empty is not the source oracle. |
| UI |406F50 selector/timer;4043D9 controlled clock;407070/O edge;404D97 practice resume.44 objective flags distinct from selector. | Timed objective subset, modal practice, modern UiViewport/debug. | S/M/R. Other flags/gadgets/highlights/cursor/energy/layout transitions open; source widescreen not recovered. | Keep modern scale policy separate; recover UI dispatcher/mode gates before expanding. | | UI |406F50 selector/timer;4043D9 controlled clock;407070/O edge;404D97 practice resume.44 objective flags distinct from selector. | Timed objective subset, modal practice, modern UiViewport/debug. | S/M/R. Other flags/gadgets/highlights/cursor/energy/layout transitions open; source widescreen not recovered. | Keep modern scale policy separate; recover UI dispatcher/mode gates before expanding. |
| LOAD | CEditor deferred scene request; selective teardown/reuse; Init stored+11→live+139 resolves old-game deletion; Jimmy/Goddard retained. RETURN root/flags and per-object28→40C. | Reconstructed scene with retained input-order identity and bounded mode/hold/fire container; app-owned presentation. | S/P/M/R. Property stream and bounded scalar/companion resets closed; full body/helper timing and fades remain.50988A is editor R input. | Continue full wrapper/body registration/helper traversal; other gadget/level branches remain gated. | | LOAD | Deferred scene request; selective reuse; Init stored+11→live+139; Jimmy/Goddard retained. Physical49E clears and re-registration repeats Init before STRT placement. RETURN root/flags and28→40C. | Reconstructed scene with retained input order and bounded mode/hold/fire; app-owned presentation. | S/P/M/R. Physical registration chain source-guarded; full helper/body allocation/order and fades remain.50988A is editor R input. | Integrate physical list/helper traversal alongside C4; other gadget/level branches remain gated. |
| INVENTORY | PostLoad common prefix enables eight owned gadgets4→1, then VR01..08 disables1→4; full tail re-enables the practice gadget. LV1B disables1/7; other wire values preserved. | Availability pass now applied at level entry and verified across TSK tutorial/return; snapshots preserve raw values. | S/M/R. Full selected-gadget/UI and other level tails remain incomplete; bounded route mode/hold/fire carry is implemented. | Keep availability separate from ownership, task changes and arbitrary state carry. | | INVENTORY | PostLoad common prefix enables eight owned gadgets4→1, then VR01..08 disables1→4; full tail re-enables the practice gadget. LV1B disables1/7; other wire values preserved. | Availability pass now applied at level entry and verified across TSK tutorial/return; snapshots preserve raw values. | S/M/R. Full selected-gadget/UI and other level tails remain incomplete; bounded route mode/hold/fire carry is implemented. | Keep availability separate from ownership, task changes and arbitrary state carry. |
| SAVE | TSK45FEE0 writer /4603F0 reader; records, arrays, return strings, stored departure root; queued460E70→460EA0. | Original-format round-trip and CLI save, scene snapshots; no full source save UI/load lifecycle. | S/M. Source reader duplicates matching task callback then all-entity420 post-task hook; this is distinct from Jimmy placement PostLoad423A90. Current fresh-director path differs. | C7 after C1/C2; test repeated callbacks before adopting loader behavior. | | SAVE | TSK45FEE0 writer /4603F0 reader; records, arrays, return strings, stored departure root; queued460E70→460EA0. | Original-format round-trip and CLI save, scene snapshots; no full source save UI/load lifecycle. | S/M. Source reader duplicates matching task callback then all-entity420 post-task hook; this is distinct from Jimmy placement PostLoad423A90. Current fresh-director path differs. | C7 after C1/C2; test repeated callbacks before adopting loader behavior. |
| CHECKPOINT | Pickup42AF00 stores+1E38 root/+1E48 level separately from+9A8 RETURN root. | Capture exposed, not used for return; source capture consumers unknown. | S/M. Do not interpret as death/respawn until read consumer found. | Track unresolved consumer; no speculative gameplay. | | CHECKPOINT | Pickup42AF00 stores+1E38 root/+1E48 level separately from+9A8 RETURN root. | Capture exposed, not used for return; source capture consumers unknown. | S/M. Do not interpret as death/respawn until read consumer found. | Track unresolved consumer; no speculative gameplay. |
+56
View File
@@ -129,3 +129,59 @@ allowed where it resolves a core-system question, without waiting for every leve
checks above remain separate. Baseline untouched; Windows cross-published only. checks above remain separate. Baseline untouched; Windows cross-published only.
Logs: artifacts/uncontrolled-phases/package*.log. Next work is full wrapper/base Logs: artifacts/uncontrolled-phases/package*.log. Next work is full wrapper/base
ownership, C4 collision/root response and shared camera handoff. ownership, C4 collision/root response and shared camera handoff.
- C4 bounded kernel: REA/byte cross-checks recover47BD80 and helpers, with ten
isolated original Wine32 synthetic cases and a managed numeric-reference module.
Live capsule replacement remains gated on grid traversal/order, negative-Y split,
normal callbacks, support/friction and dynamic reclipping. No source generic
recursive capsule slide was found in the inspected dispatcher.
- C3/C4 wrapper: root+150 upward query and min(−0.6Vy,−85) response now run before
Jimmy movement/fire, regardless of ownership; mode1 cancellation preserves hold
and independent queued/body work. Fresh/retained input boundaries preserved;
camera-only debug switch cannot disable physical query. Other scene filters,
sound and selected-gadget cleanup remain separate.
- Registration: retained registry objects have49E cleared, then physical Init/list
registration repeats Init before placement. Shared-eye capture/pre-update aim
is source-guarded but C5 runtime correction remains next. Detailed reports:
collision-response.md, ceiling-wrapper.md, body-root-registration.md,
camera-handoff.md; complete REA results and provider gaps retained on disk.
- Final C4 bounded continuation validation:104 Python plus HUD,25 movement/five
sphere and remaining managed groups,27 zero-error enabled-validation GPU renders,
SDL dummy lifecycle and539 unchanged originals. Four native GTX1070 window
commands pass (five scene renders). Full capsule replacement, complete camera
state and original whole-game/native Windows validation remain separate gates.
- C4 continuation release: both self-contained packages identify clean57dfcc6
(source_dirty=no); standalone Linux from /tmp passes control/body/fire and
nondefault tutorial/RETURN checks. Release validation unavailable, enabled
source/native checks separate. Package logs in artifacts/collision-response/;
baseline untouched and Windows cross-published only.
- C4 static composition: independent REA grid/contact investigations recover
FIFO duplicate traversal, reachable retries, normal/landing ownership, signed
material archive IDs, separate published160 speed and friction/suppression.
Seven isolated original dispatcher fixtures match the managed component's
positions/counts/callbacks. Ten copied479D20/support fixtures completed; no
managed whole-body equivalent is claimed yet. Reports: collision-body-probe.md,
collision-grid-traversal.md, collision-contact-callbacks.md and independent review.
- Prepared scenes now retain material IDs and completeness; legacy metadata cannot
masquerade as ordinary-only. Actual VR04 has no special contacts; LV1B/LEV1 do.
Geometry-disabled publication/retained callback and strict initial support
distance are explicit. Original geometry-off branch supersedes C3's earlier
support-hit gravity-cancellation inference. Playable body remains baseline.
- Next C4 chunk: ordinary-body composition and ten numeric comparisons, negative-Y
horizontal-first split,370, landing-before-velocity-clear, published160 friction
and suppression; then VR04 live root/input/ceiling/RETURN checks. Trace special
callbacks and dynamic reclip/global context before lab/outside replacement.
- C4 ordinary-body composition implemented and matched against all ten copied
body references. VR04 now selects the source static subset with live radius
60/100, separate published160, control-independent body work and source landing/
friction order. Twenty managed groups and native/headless300-frame jetpack
replay pass; lab/outside capsule retained. Source and independent review:
collision-body-composition-source.md, collision-body-implementation.md and
collision-body-implementation-review.md. Other original VR04 dynamic class
eligibility, special Player callbacks and shared dynamic contexts remain open.
- C4 ordinary-body milestone35a2a66 is clean and packaged for linux-x64/win-x64.
Full integration passes129 Python+HUD/managed/27 GPU/audio/539 hashes; final
Python130 includes the added Init authored114→26C speed regression. Standalone
Linux from /tmp passes source-body VR04 flight and nondefault tutorial/RETURN.
Source/native validation enabled; release layers unavailable; native Windows
comparison remains open. Logs: artifacts/body-composition/.
@@ -47,11 +47,12 @@ navigation still reaches SCENE35→50→60 and the outside LOAD. This is port ev
not original timing/latency fidelity. Source nominal frame rate remains unproven; not original timing/latency fidelity. Source nominal frame rate remains unproven;
the port keeps its explicit60Hz policy. the port keeps its explicit60Hz policy.
The existing capsule/gravity adapter remains. Source479DF7..479E54 can cancel The existing capsule/gravity adapter remains. C4 follow-up corrects the earlier
gravity on a support hit before a queued jump, giving a different first takeoff support-hit interpretation: source479DF7..479E54 cancels gravity and clears
velocity. Applying that cancellation to the provisional capsule's prior support vertical velocity only when global geometry4F69E5 is disabled. It is not a
flag caused false support transitions in the port; it must be integrated with prior-grounded or support-hit branch. The isolated body probe confirms the normal
the recovered pre-integration support/response in C4, not bolted onto that flag. pending-jump fixture consumes550 impulse and applies both−264 acceleration and
−800 gravity, producing Vy532.266663 at dt1/60. See collision-body-probe.md.
No source-fidelity claim is made for jump apex, stairs, wall response or visual No source-fidelity claim is made for jump apex, stairs, wall response or visual
pivot. The underground replay checks clearance of the recovered radius60 body, pivot. The underground replay checks clearance of the recovered radius60 body,
not raw209-unit standing-mesh bounds, which are a separate provisional render not raw209-unit standing-mesh bounds, which are a separate provisional render
+7
View File
@@ -15,6 +15,13 @@ movement and implements bounded ordered preparations. Local REA/Ghidra static
Evidence cross-checks the original gates. See control-phase-implementation.md and Evidence cross-checks the original gates. See control-phase-implementation.md and
rea.md; full wrapper/collision/camera work is still outstanding. rea.md; full wrapper/collision/camera work is still outstanding.
The C4 continuation now has a bounded47BD80 sphere kernel with ten isolated
original-code cases, an integrated source-root overhead response, and retained
physical registration/repeated-Init evidence. Full capsule replacement remains
gated. Shared-eye handoff is documented for the next C5 correction. See
collision-response.md, ceiling-wrapper.md, body-root-registration.md and
camera-handoff.md; these do not certify whole-game or native Windows fidelity.
The initial architecture checkpoint is complete: all requested core systems have The initial architecture checkpoint is complete: all requested core systems have
source anchors, state owners/lifetimes, route interactions, baseline comparison, source anchors, state owners/lifetimes, route interactions, baseline comparison,
explicit unknowns and bounded implementation actions. Feature expansion remains explicit unknowns and bounded implementation actions. Feature expansion remains
+79
View File
@@ -3,6 +3,85 @@
Compilation, native runtime, original behavior and full feature completion are Compilation, native runtime, original behavior and full feature completion are
separate evidence categories. **The game is not fully reconstructed/playable yet.** separate evidence categories. **The game is not fully reconstructed/playable yet.**
Gadgets (2026-10-27 UTC): original gadget screen and combined shrink-ray/jetpack
are implemented; actual VR04 soldiers use original shrink morphs, source timer,
authored AI reset and ordinary10-point score/save effect. First complete run:
157 Python+2 HUD, all managed suites including15 gadget groups,29 main GPU
completions and17 isolated blend/readback checks, zero enabled validation errors.
Heading matches15 original-DLL references and65,540 sweep cases. Final ordering/
authored-mode fixes pass the complete rerun in integration-final.log.
Native Linux GTX1070/private Xvfb verifies1920×1080 menu input/pause/capture and
1280×720 held ray against an actual authored VR04 target, with zero validation
errors. The fixture moves only the player near a settled soldier; it does not
establish gameplay navigation to the platform or original visual parity.
Other effects, full enemy AI/combat, energy warnings and lifecycle gaps remain;
see gameplay/gadgets-implementation.md. Both self-contained packages identify
clean7b5230c (source_dirty=no), with54 canvases and all new animation manifests.
Standalone Linux from /tmp passes widescreen menu and90-frame ray fixtures;
release validation layers are unavailable, distinct from enabled source/native
checks. Windows publishes successfully; native Windows gadget testing is not
claimed. NU1900 vulnerability-metadata warnings do not prevent publication.
All539 originals verify again after packaging. Logs: artifacts/gadget-implementation/.
C4 ordinary body (2026-10-27 UTC): all ten original-code body references match
managed composition. VR04 uses source static response/support/friction and live
radius60/100; lab/outside retain the capsule. Twenty body groups plus full suite
pass:129 Python+2 HUD, managed checks,27 zero-error enabled-validation GPU renders,
SDL dummy lifecycle and539 unchanged originals. Native GTX1070/private Xvfb at
1920x1080 passes300-frame jetpack input/resize/steering/landing. Logs/readback:
artifacts/body-composition/. Source scope/independent review are linked from
checkpoint/collision-body-implementation.md. Original dynamic actor eligibility,
special callbacks, logical/render pivot and modern noclip occupancy remain open.
Native Windows and whole-original-game comparisons remain unverified.
The final expanded Python suite passes130 checks after the Init authored/live
speed closure; the129-check full-integration log predates that extra regression.
Both self-contained packages identify clean35a2a66. Standalone Linux from /tmp
passes source-body tutorial flight and lab/tutorial/RETURN assertions. Release
validation unavailable; enabled source/native checks separate. Both publish steps
succeed despite NU1900 vulnerability-metadata warnings. Windows remains cross-built;
539 original hashes reverified after packaging. Package logs: artifacts/body-composition/.
C4 static composition follow-up: seven copied-original dispatcher fixtures match
the isolated managed grid/retry component; ten copied479D20/support fixtures
complete as references for future body composition. No live capsule replacement
is claimed. Prepared scenes retain signed material IDs; actual lab/outside special
contacts prevent ordinary-only assumptions. See checkpoint/collision-body-probe.md.
The temporary automatic approval usage-limit failure was resolved through normal
review after its stated reset; original component execution then completed.
Full scripts/test.sh passes122 Python plus2 HUD checks, managed suites and27
zero-error enabled-validation GPU completions;11 focused dispatcher groups pass.
SDL dummy lifecycle and539 original hashes pass. Evidence is under
artifacts/collision-integration/. No new native Windows or whole-game original
comparison; preserved baseline and prior release packages are unchanged.
Linux-x64 and win-x64 self-contained publish succeeds into separate build artifact
directories. Restore's NU1900 records unavailable vulnerability metadata; compile/
publish succeeds. No new distribution package or native Windows execution claimed.
C4 continuation (2026-10-26): REA/bytes recover the bounded47BD80 sphere kernel;
ten isolated original Wine32 synthetic cases pass with explicitly guarded fixture
rebasing. The managed component matches numeric references; live capsule replacement
remains gated. Source-root overhead velocity reflection/mode1 jump/fire cancellation
is integrated for LV1B/VR04/LEV1, including without control and with the modern
camera query disabled. Full sound/gadget cleanup and other scene filters remain.
Registration/repeated Init and shared-eye handoff reports distinguish recovery
from pending runtime changes. See checkpoint/collision-response.md and linked reports.
Final scripts/test.sh passes in artifacts/collision-response/integration-final.log:
104 Python checks plus separate HUD checks,25 movement groups, five new sphere
groups, remaining managed checks,27 zero-error enabled-validation GPU completions,
SDL dummy lifecycle and539 unchanged original hashes. Both input-only routes use
the source geometry queries and retain their progression/contact checks. Native
Linux GTX1070 at1280x720 passes Carl/control, jetpack SDL keys/resize and debug
tools/checkpoint reload (four commands, five renders), zero validation errors.
The original component probe is not whole-game or native Windows validation.
Both self-contained packages identify clean57dfcc6, source_dirty=no. Standalone
Linux from /tmp passes the control-phase fixture and nondefault tutorial/RETURN
assertions. These release invocations lack validation layers; enabled source and
native-window evidence above is separate. Logs: artifacts/collision-response/
package.log, package-control.log and package-return.log. Baseline untouched;
Windows cross-publication adds no native Windows runtime claim.
Control-phase continuation (2026-10-26): body/fire eligibility and ordered raw Control-phase continuation (2026-10-26): body/fire eligibility and ordered raw
preparations are source-byte guarded separately from port behavior. Targeted24 preparations are source-byte guarded separately from port behavior. Targeted24
movement groups, coupled director/preparation tests and the airborne control movement groups, coupled director/preparation tests and the airborne control
+35
View File
@@ -165,3 +165,38 @@
Evidence/profile/hash/snapshots and close owned sessions. CLI avoids changing Evidence/profile/hash/snapshots and close owned sessions. CLI avoids changing
the existing MCP registration. Unknown procedure definitions remain unknown; the existing MCP registration. Unknown procedure definitions remain unknown;
they do not invalidate byte/vtable evidence or imply missing game code. they do not invalidate byte/vtable evidence or imply missing game code.
33. **Integrate collision in verified boundaries.** Preserve source sphere kernel
nearest state/face/edge semantics as an isolated component with original-code
probe references. Keep live capsule replacement gated on traversal, callbacks,
support/friction and dynamic response. Independently correct the proven Jimmy
overhead wrapper using its root ray and mode-specific cancellation, retaining
fresh/retained input order. Modern camera debug controls affect camera queries
only. Do not reinterpret this partial correction as complete original physics.
34. **Compose body response only inside recovered contact coverage.** Preserve
signed material database IDs in collision metadata and reject legacy prepared
data lacking identities. An ordinary-only adapter may start with VR04, whose
static materials have no special Player374 policies; lab/outside contain
special contacts. The tested grid dispatcher is an isolated component until
body/landing/friction order and root visuals are compared; dynamic reclip
must explicitly own shared nearest/last-polygon state. Keep source published
speed160 separate from controller608. Geometry-off gravity cancellation must
not be reinterpreted as an ordinary prior-grounded jump rule.
35. **Enable the tested static body subset in VR04.** Compose verified traversal,
support and friction using original body-reference outputs. Reject special
scenes/provisional dynamic resolver and keep lab/outside on the baseline.
Preserve source60/100 radius changes through both sphere response and support;
restore60 in the later Jimmy wrapper. Published speed160 survives control
preparation separately from controller608. No dynamic-door geometry does not
establish absence of other source dynamic actor classes. Modern feet/sole and
noclip admission remain explicit policies; this is not whole-tutorial fidelity.
36. **Keep gadget display, equipped mode and owned effects distinct.** The user
parked collision work and requested gameplay gadgets. Integrate original
group0 resources/state and default item3 first: its display index is3 but raw
mode remains−1. Do not treat the default shrink-ray/jetpack as special mode3
or call Bubble mode0 Scooter. Reuse original heading, strict multi-target
gates and nonloop soldier morph; ordinary hits award10 through the score/save
owner. Expiry restores authored/reset AIState, not pre-hit dynamic mode.
Keep modern full-panel pause, upright effect transform, additive branch and
blended-depth policy explicit. Other gadgets, full AI and warning-audio
lifecycle remain independent evidence gates, not guessed feature completion.
+134
View File
@@ -0,0 +1,134 @@
# Gadget resource inventory
2026-10-27. Read-only asset investigation; no original file was modified or
executed. This report describes serialized resources and inspected pixels.
It does not infer gadget timing, collision, selection policy or model attachment
from filenames. Binary/input contracts belong in [gadget-controls.md](gadget-controls.md).
## Selection screen and original labels
All following Canv IDs are from Original/omt/screens.omt, SHA256
`e8e95231f5d302b41f4fbf33df1c5a08ce4645370f9f519527ff1727b73b7a5e`.
Canvas20 (`menu`) is640×480 and already contains the dim gadget tiles and Return/
Practice labels. Unsuffixed, suffix-b and suffix-c tile art are141×141. Their inspected
appearances are green, white and blue respectively; which state selects a variant
must come from the dispatcher, not the colour. The independent controls investigation
reports constructor404E97..404F8B's inventory0..7-to-tile association; the displayed
labels below are independently visible in the original pixels.
| Group0 item | Original tile label | Unsuffixed / b / c Canv | HUD Canv/name | Control strip |
|---:|---|---|---|---|
|0|BUBBLE|11 /52 /178|94 `1bubble`|109 `BmenuLBubble`|
|1|ROCKETSHIP|12 /46 /171|87 `2rocket`|115 `BmenuLRocketship`|
|2|INVISIBLE|13 /47 /172|88 `3invisible`|111 `BmenuLInvisible`|
|3|SHRINK RAY|14 /48 /173|89 `4raygun`|113 `BmenuLRayGun`|
|4|SCOOTER|15 /49 /174|90 `5scooter`|116 `BmenuLScooter`|
|5|REMOTE|16 /50 /175|91 `6remote`|114 `BmenuLRemote`|
|6|BASEBALL|17 /51 /176|92 `7baseball`|118 `BmenuLBaseball`|
|7|GRAPPLER|18 /45 /177|93 `8grappler`|110 `BmenuLGrappler`|
Do not rename tile3 to Jetpack. The separate jetpack HUD canvas119 is named
`9jetpack`, and control strip112 is `BmenuLJetPack`; strip113 visibly describes
both SHRINK firing and JUMP/JETPACK. This agrees with the port's recovered
item3-powered-jump association, but the art itself does not establish firing logic.
The rendered selection background places bubble/rocket/scooter/remote across its
first row and invisible/shrink/baseball/grappler across its second. Exact hit
rectangles and hover/selected state are source-controller evidence, separate
from this visual layout observation.
The controls investigator specifically recovers white suffix-b as owned idle and
green unsuffixed as mouseover; group0 state0/4 hide both to expose the dim background.
The blue suffix-c resources are available assets but are not part of those current
group0 bindings. Their existence does not justify inventing an unavailable overlay.
Other useful screens.omt resources:
| IDs / names | Dimensions | Asset role |
|---|---|---|
|109..116 plus118 `BmenuL*`|393×69|Nine left-side gadget control strips.|
|108 `BmenuR2`,117 `BmenuR1`|247×69|Right-side instructions with SELECT/DESELECT INVENTIONS text.|
|24/181/182 `return`/`return2`/`return3`|141×78|Return button variants.|
|170/179/180 `practice`/`practice2`/`practice3`|141×78|Practice button variants.|
|87..94 plus119|80×70|Eight gadget HUD icons and separate jetpack icon.|
|84/85 `backpack`/`backpack2`|141×141|Backpack variants.|
|253 `CrossHairs`|15×210|Vertical strip;14 square15×15 frames arithmetically fit. Frame meaning/timing is not inferred.|
## Export and integration
tools/extractors/gadget_resources.py exports54 exact decoded canvases into a
separate directory. It checks original IDs/names/dimensions before writing, uses
the existing bounded OMT/RGB555/colour-key decoder, preserves alpha and records
archive/payload/RGBA SHA256 plus source offsets/sizes. It protects the entire
source asset root, including sibling ASE/png/gam directories when the archive is
under omt/. No image generation or replacement art is used.
```
python3 tools/extractors/gadget_resources.py ../Original/omt/screens.omt --output artifacts/extracted/gadgets
```
The generated gadgets.json uses schema1, referenceWidth640/referenceHeight480 and
textures with id/name/role/width/height/path/png/sourceOffset/sourceBytes/
sourceSha256/rgbaSha256. File paths are local `canvas_ID.rgba` and `.png`.
`tiles` records artItem1..8, literal labels and normal/b/c IDs; suffix roles remain
neutral so the source controller owns availability/highlight interpretation.
This separate manifest leaves the existing eight HUD/practice resources unchanged.
Primary owns prepare.py/package/runtime integration; this investigator did not
edit those files. Runtime should reuse UiViewport scaling and pointer conversion.
Generated inspection images are in artifacts/gadget-assets/: selection-sheet.png
and canvas_20.png. ase-inventory.json records exact hashes/counts for the model
files below. The fixture exporter wrote artifacts/extracted/gadgets/gadgets.json.
Three regression groups pass in artifacts/gadget-assets/tests.log: exact original
resource/pixel/dimension round-trip, rejection of all original asset subtrees, and
rejecting changed dimensions before producing partial output.
## Shipped model and animation candidates
These are file/content observations, not proof that a given runtime action uses
every candidate. The ASE parser maps original coordinates using the existing
verified `(x,z,y)` conversion. Jimmy clips share426 vertices/814 faces with the
prepared standing mesh, so existing morph preparation can preserve its topology.
| Source ASE | Samples / fps | Geometry and bounded use |
|---|---|---|
|jimshoot.ASE|2 /10|426 vertices/814 faces; original shooting pose candidate. Not in current default prepared animation list.|
|jimfly.ASE|2 /10|426/814; already prepared for powered jumping.|
|jimswing.ASE|2 /10|426/814; swing pose candidate.|
|jimscooter.ASE, jimscooterstop.ASE|2 each /10|426/814; scooter poses.|
|jimdrive.ASE|2 /10|426/814; driving pose.|
|jimheadshrink.ASE|7 /5|426/814; distinct authored morph sequence, not an inferred uniform scale.|
|godscooter.ASE, godscooter2.ASE|2 each /30|195 vertices/370 faces; reference `goddard02.png`.|
|godrocket.ASE|3 /5|222 vertices/411 faces; rocket-form candidate.|
|ray.ASE|2 /10|5 vertices/3 faces. Material text references `ray0002.ifl`; supplied PNGs ray0000..ray0003 exist. Sequence binding/cadence remains source work.|
|hook.ASE|1 /10|40 vertices/68 faces; material references hook.bmp, supplied hook.png exists.|
|rope01.ASE,rope02.ASE|1 each /30|6 vertices/6 faces and4 vertices/2 faces.|
|laser02.ASE,missile.ASE|1 each /30|8 vertices/8 faces and7 vertices/10 faces; missile's goo.bmp reference is not a verified gadget attachment.|
scooter.omt contains shape0 `goddard01`, shape1 `wheel`, matching material/canvas
resources0 `goddard128` and1 `scooterwheel2`; archive SHA256
`8d4ffdafee5fd819c5220ee4f608c901a5988fe6b8b13316e15618f5eec75e81`.
inventory.omt is an older-looking icon set with BUBBLE/GODJEEP/SCOOTER/jetpack etc;
its names alone do not justify replacing screens.omt menu art or IDs.
No explicit bubble-named ASE exists in the supplied directory; that bounded
filename search does not prove the original bubble geometry was absent/generated.
## Already prepared sounds
artifacts/extracted/effects/effects.json already preserves original SoundEffects.omt
waves, paths and source byte ranges. Bank SHA256 is
`c71e06d93b8a5ef4f4522a5c40220bc8aeaecb889b5de69445db44817fb9acb1`.
Useful identities are0 `shrinkray`,1 `jetpack`,2 `gravitybubble`,3 `gravitybubbleoff`,
10 `goddard baseballs`,18 `pickupbaseball`,45 `rocketship`,46 `Scooter`,106
`bubble boing` and117 `click shrink ray`. These are archive identity/name facts;
actual activation, repeat, ownership, volume and cancellation still need callers.
The existing resource export is sufficient; no duplicate sound extraction is needed.
## Practical next addition and limits
Original selection art and control labels are complete enough to implement a
source-driven gadget screen without invented icons. For a usable gadget beyond
the current powered jump, shrink firing has original pose, beam geometry/PNG frames
and both successful-fire/click sounds available; it still needs recovered target,
range, timing, energy and interruption policy. The selection3 naming overlap is
an explicit reason to implement the combined shrink/jetpack controls coherently.
Other gadget assets are candidates for later behavior recovery, not evidence that
all eight gadget behaviors are currently implemented.
+83
View File
@@ -0,0 +1,83 @@
# Gadget material opacity and blending
Implemented 2026-10-27. Scope: Vulkan support needed by the recovered shrink-ray
effect. This is a renderer capability, not a claim of complete original material
or fixed-function rendering fidelity.
## Recovered facts
[Shrink-ray investigation](shrink-ray.md) records the underlying REA evidence.
Original EXE SHA256:
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Original engine DLL SHA256:
`3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
| Original location | Fact and dependency |
| --- | --- |
| EXE VA40E4A0 / raw0E4A0, complete-object virtual offset114 | Positive opacity walks shape polygons and nonnull materials; writes material RGB1, alpha=parameter at +4C..58, source blend enum6 at +30, destination enum7 or1 at +34, and sets flag38 bit0. It does not multiply a previous alpha or scale geometry. |
| EXE VA440000 / raw40000, Init; VA440180 / raw40180, update | Effect initialization and texture changes invoke that setter with0.5. The material opacity applies to all three animated ray textures. |
| EXE global509A13; store VA476BBE / raw76BBE | False selects destination enum1; true selects enum7. Store comes from graphics setup. Complete hardware/settings fallback semantics remain unresolved. |
| DLL VA10036AB0 / raw36AB0; table VA1013667C / raw13667C | Adapter maps blend enums to Direct3D states19/20. Enum6→SRC_ALPHA, enum1→ONE, enum7→INV_SRC_ALPHA. False global therefore means additive SrcAlpha/One; true means conventional SrcAlpha/OneMinusSrcAlpha. |
The DLL REA evidence is
`ev_f5a914ee9eae593b02a04149b6651b2d783151df046bbb417624bf94f23bb96c`,
closed/exported in `artifacts/shrink-ray/rea-blend/00.json`. The parent report
links retained EXE evidence and byte-guard utility. No originals were modified
or executed for this implementation.
## Implementation and explicit policies
`MeshDraw.Opacity` defaults to1; `MeshDraw.Blend` defaults to `MeshBlend.Opaque`.
The other modes are `Alpha` and `Additive`, using exactly the source/destination
factors above for both RGB and alpha. The caller chooses the mode; opacity alone
does not enable blending. The source effect should use opacity0.5 with its chosen
graphics branch. Texture alpha is not pre-halved.
The fragment shader retains the existing texture-alpha cutout test (<0.5) and
then multiplies texture alpha by material opacity. Keeping this test and threshold
is existing port behavior; source alpha-test interaction is still unverified.
The push constant is float opacity at byte64 after the existing64-byte transform;
the68-byte range covers vertex and fragment stages. The vertex shader is
unchanged. Opaque world and opaque UI blend/depth pipeline states are unchanged.
Blended world draws test opaque depth without writing depth. This is an explicit
modern implementation policy: original shrink-ray depth-write state has not been
recovered in this bounded investigation. Rendering order is opaque world,
blended world, then UI; each pass preserves mesh draw order. There is no distance
sorting. UI modes use the same blend factors with depth testing/writing disabled
and the existing identity transform. This supports opacity without disturbing
ordinary HUD composition; it is not a recovered universal original UI contract.
All explicit draw opacities must be finite within0..1 and blend modes must be
valid, including invisible draws. Scene creation/replacement and every render
validate these properties. Per-frame validation runs before swapchain acquisition
or command-buffer recording so a rejected mutable material leaves rendering
usable after correction. All six pipelines are destroyed before their layout.
## Verification
`scripts/compile-shaders.sh` compiled both shaders for Vulkan1.3 and validated
both SPIR-V modules. Vertex SPIR-V remained unchanged. The isolated source-linked
test project builds without compiling the main runtime:
```sh
source scripts/env.sh
dotnet restore tests/GamePort.BlendTests/GamePort.BlendTests.csproj --ignore-failed-sources --source .nuget/packages
dotnet build tests/GamePort.BlendTests/GamePort.BlendTests.csproj --no-restore
dotnet tests/GamePort.BlendTests/bin/Debug/net10.0/GamePort.BlendTests.dll artifacts/gadget-blending/final-frame.ppm
```
Build: zero warnings/errors. Linux headless Vulkan runtime: llvmpipe
(LLVM20.1.2,256bits), Khronos validation enabled, **17 checks passed, zero
validation errors**. GPU RGBA readback checks exercise default opaque color,
half-opacity alpha/additive RGB equations, opaque occlusion, disabled blended
depth writes, UI ordering and depth bypass for both blend modes, zero opacity,
unchanged texture cutout, invalid opacity/enum rejection, and successful rendering
after correction. Numeric color tolerance is2/255 for attachment quantization.
Logs and a final opaque reference frame remain in `artifacts/gadget-blending/`.
These are real port GPU checks, not original-game comparisons. Windows runtime,
the selected graphics-option branch, original depth-write behavior, mixed
transparent scene ordering, and original alpha-test policy remain unverified.
Main-runtime integration and gameplay visual comparison belong to the primary
agent's integration checks.
+143
View File
@@ -0,0 +1,143 @@
# Gadget selection and control contracts
2026-10-27. Original EXE SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Preferred VAs below have PE-mapped offsets in
artifacts/gadget-controls/source-contract.json. Tools guard the whole identity,
nine bounded source spans,40 instruction slices and10 virtual targets. Text
offsets equal VA−400000 for the supplied EXE. This is static recovery, not an
original gameplay capture or proof that every gadget is implemented in the port.
## REA evidence and limitations
Own generated-copy REA/Ghidra sessions are exported and closed in
artifacts/gadget-controls/rea-core/, rea-panel/ and rea-hit/.
| Procedure | Evidence |
|---|---|
|405FB0 display selection|ev_b740d70cfab21827d697151221a5cbcc0294c5d4b5742a2d3b94b10e62a08e1c|
|406590 selected HUD collapse|ev_c792af0532d5a11ecb3a602d31e3179a95b0c4b9e5242fbfe8390558b3a5c55a|
|406650 selected HUD expand|ev_dc23fb856bd21025fbfb4fb2389fae63431659f914d37475014d00dcc461fb6d|
|425870 menu-key dispatcher|ev_c2c664c7632af150fb70ecb3aaa13d8fb46c5493210a0c9af0b54a274f656ec2|
|403A20 menu group setter|ev_823efd8fa897c27a672c43a5e1859b0a4dbc8ba866593b6ab4e5db7d03b58944|
|404DE0 group/resource initialization|ev_bfded79da490ec9bc615e403ba00f4a006fe37d0f88b69fbf3a92ce433df17dc|
Queries404080,428D50,425B20,425EF0,403C50,403700,427370,403A30 and402F60
did not return pseudocode. Complete provider errors are retained; several say the
numeric input was interpreted as an unmapped file offset after no procedure
match. No successful pseudocode is attributed to those queries. Their contracts
below use reviewed instructions and fixed identity/span/virtual guards. No
unchanged failed calls were repeated. No original code was executed by this task.
## Owners and open/close transitions
Jimmy complete-object table4A3BDC maps184→425870 menu-key input,
1AC→427370 panel interaction,1F8→425EF0 open,1FC→425B20 close,
174→428D50 gadget selection.188 is429D00, **not** panel interaction.
Menu object is Jimmy complete+A18; global4F8181 is panel-open. Menu4D4 is group,
4C8 accepted item,4D8 selected HUD/display item. Global signed WORD4F0588 is a
different equipped movement/gadget mode. Menu display4D8 initializes3 at401F93;
Jimmy equipped mode initializes−1 at42225F.
425870 reads Tab at509841 and Space509858 (keyboard array509838+virtual-key),
plus controller509AC6. Shared edge latch Jimmy+1E00 suppresses repeats. With an
open panel,425AA6 calls close1FC. With panel closed and equipped mode!=-1,
425ABC calls cleanup178, writes mode−1, resets menu selection state and **returns**.
Only no-selection invokes open1F8(0) at425ADB..AF1. Thus equipped special gadget
requires one Tab to unequip and another to open; Tab is not a universal toggle.
The dispatcher also gates menu pointer, an elapsed/action field1E6C and competing
keys. Raw ownership/caller scheduling must remain distinct from this leaf branch.
Open425EF0 requires gameplay-enable4EC494 and closed panel. It collapses HUD,
sets group through menu4AC, invokes game168(1), marks panel-open, shows cursor
for groups except2 and disables Jimmy integration through interface214(false).
It also calls47D850 and clears sound-default gate4F8434. Close425B20 reverses
panel/game pause, cursor, integration and sound gate; root group0/previous-menu−1
Return simply closes. Source214 is body-enable, not raw controlled-pointer118.
Global control remains available to drive panel input while physics is disabled.
Full actor/fire/morph/music/software-clock pause ownership is not closed here;
pausing all port simulation is a broader declared policy, not this leaf proof.
Escape uses VK_ESCAPE509853 in425870 then complete1F0→42AB60. When panel is
open,42AB76 invokes close1FC and returns; it does not quit the application.
When closed it opens the separate main-menu group3, outside this gadget subset.
## Original group0 layout and rendering
404E97..404F8B constructs the eight gadget buttons in inventory-index order.
Their141×141 rectangles use strict interior comparisons in403A30:
| Item / original tile text | Top-left | Idle / hover canvases |
|---|---|---|
|0 BUBBLE|(12,182)|52 /11|
|1 ROCKET SHIP|(158,182)|46 /12|
|2 INVISIBLE|(12,327)|47 /13|
|3 SHRINK RAY|(157,327)|48 /14|
|4 SCOOTER|(342,182)|49 /15|
|5 REMOTE|(487,182)|50 /16|
|6 BASEBALL|(342,327)|51 /17|
|7 GRAPPLER|(487,327)|45 /18|
Canv20 is the640×480 base and already contains grey/unowned tiles. For current
route state1,402F60 creates both b/white and normal/green sprites.403A30 hides
green outside hover and shows it inside, leaving white idle. State0 and4 hide
both, exposing the base grey tile. Blue c assets are not bound by this group0
constructor; do not use them as an invented unavailable-state overlay.
Hit filtering skips state0/4 and missing green sprite, not every state!=1.
State3 can hit but forcibly hides green; state2/3 initial render visibility is
inherited (the initializer has no explicit show/hide branch for them). Do not
claim complete raw-state2/3 rendering from state1 behavior. Unknown states should
remain raw values, not be normalized into owned/available booleans.
403A30 scans29 entries in40-byte steps and returns the last overlapping eligible
hit. The state is menu-base+item*40+24; source sprite positions/dimensions determine
the hit rectangle. Boundaries x==left/right and y==top/bottom do not hit.
Return slot10 uses canvases182/181 at(12,95),141×78. Practice slot9 uses180/179
at(487,95),141×78. Jimmy construction4223BE..CD initializes both raw states1;
these runtime-only slots are outside the nine group0 entries serialized by TSK.
Slot8 is the separate backpack/inventory function, not a ninth ordinary gadget.
## Activation, practice and the combined default device
427370 samples the pointer and calls menu4A4→403A30. Primary activation includes
42A7A0 (left mouse, Enter, Ctrl, controller; a separate global suppressor can veto),
42A730 jump-input helper, and Enter polling46A3E0(13). It stores the accepted item
through menu478. Jimmy+1E25 is an action latch; releasing all accepted controls
clears it. This is source pointer selection; arrows/analog steer the OS pointer
in404080 using accumulated offsets±80*dt, not direct tile focus cycling.
For group0 gadget activation,4278D7 closes the panel, calls cleanup178, passes
menu4C8 to gadget174 and then re-enables body integration. Requested item3 and−1
share428DE0. That branch does **not** set global4F0588 to3: UI highlight becomes3,
while the normal equipped mode after cleanup remains−1. Ownership(0,3), HUD
highlight3, source mode−1 and the primary/jetpack action state are independent.
This agrees with the primary-fire investigation's default device path. The tile
name SHRINK RAY is authoritative art; its description113 includes both SHRINK
and JUMP/JETPACK actions. The old lab tag/internal-name explanation was too broad
if interpreted to mean no shrink-ray weapon exists.
Practice click427773..427802 toggles runtime group0/item9 between2(armed) and3,
rejecting SCENE>=500 and all VR01..08 levels. Item9 initially1 is also unarmed.
Choosing a gadget while armed invokes its direct tutorial LOAD, not Yes/No modal.
Bounded pushes/string offsets in the helper verify item0..7→vr01..08.gam. Item3
loads vr04.gam/PHONEBOOTH with authored return strings. The174 branch changes
item9 from2 to1 before loading; menu caller427903 subsequently writes3 when it
continues. The helper's default_device_selection models that174 branch, not the
entire caller's final state. Returning via slot10 also disarms practice to3.
Description records4F7EF0 stride24 map item0..7 to canvases
109,115,111,113,116,114,118,110.405FB0 and406590/6650 connect them to selected-gadget
HUD layout. No panel-hover description caller is proven; displaying BmenuL as
full-panel hover text would be a new policy. Viewport scaling/cursor placement in
the modern port remains separate from the original stretched640×480 coordinates.
## Verification and remaining scope
Seven Python groups pass in artifacts/gadget-controls/tests.log: original identity,
span/site/virtual guards; Tab states/latch; exact tile interiors and boundaries;
raw state filtering; highlight/equipped distinction; practice toggle gates; all
eight guarded tutorial destinations and initial runtime button states. The
functions are explicit source projections, not original execution or port UI
runtime verification. Primary owns integration, tests, widescreen policy and
unsupported gadget effects; this investigator changed only the three owned files.
+143
View File
@@ -0,0 +1,143 @@
# First playable gadget implementation
2026-10-27. User-directed gameplay continuation; collision checkpoint35a2a66/
0272f7b remains parked. This implements the original gadget screen and the combined
shrink-ray/jetpack device, with a bounded3SOL target consumer. It does not complete
the other seven special gadget modes, enemy combat/AI or original runtime comparison.
## Evidence and state ownership
The independent reports retain hashes, preferred VAs, mapped file offsets,
structures, callers, resource identities, REA Evidence and provider limitations:
- [Controls](gadget-controls.md):425870 keys/latch,425EF0/425B20 panel ownership,
427370 selection, exact rectangles/availability and eight practice destinations.
- [Assets](gadget-assets.md):54 exact screens.omt canvases; original tile labels,
models, morphs and sound resources. Blue c tiles are unused by recovered group0.
- [Primary fire](shrink-ray.md):426030/426E40 continuous scan, owned item3/raw
mode−1, energy−dt, strict target/obstruction gates,42AC10 callback and owned beam.
- [Heading](shrink-heading.md): original quantized heading;15 copied-DLL numeric
references and65,540 bin/quadrant cases match managed code, fingerprint24e64f91.
- [Targets](shrink-targets.md): actual3SOL constructor/load, radius90/factor1,
WALK/SHRINK clips, nonloop endpoint, authored/reset versus previous dynamic mode.
- [Blending](gadget-blending.md): source half opacity and blend enum conversion;
opaque/alpha/additive rendering implementation and explicit depth-write policy.
- [Review](gadgets-review.md): independent code/evidence review; missing ordinary
+10 callback corrected, eligibility defaults and remaining limits recorded.
Menu display item3 and equipped-mode word are separate. Selecting SHRINK RAY
closes the panel, cleans old special mode and leaves normal raw mode−1; item3
ownership also gates jetpack. SceneInventory.SelectedGadget remains the port's
display/request index; PlayerSceneBinding normalizes3 to raw mode−1. Existing
retained route state remains bounded to default device display−1/3.
## Implemented behavior
GadgetScreen/GadgetMenuOverlay use the original640×480 background, owned idle/
hover tiles and buttons, with uniform centered widescreen scale and inverse
pointer mapping. Tab/Space shares a held-key latch. First Tab unequips a special
mode, next opens. Escape/Return closes; mouse or Enter/Ctrl/jump buttons activates.
Arrows steer the pointer through the recovered accumulated80×dt offsets. Raw0/4
cannot hit; raw3 suppresses green hover. Current route0/1/4 rendering is recovered;
inherited raw2/3 idle visibility uses a declared owned-white port fallback.
Practice arm/choose loads the selected original tutorial directly, independently
of the pickup's Yes/No prompt. It rejects VR01..08 and SCENE>=500; runtime practice/
Return slots are not serialized in TSK. Selection observers see the panel closed.
Input capture clears held movement/jump/fire and preserves Space cutscene skip
when the panel cannot open. New SFX requests use the source panel gate; music
continues. Pausing all port gameplay/morph timers during the panel is broader than
the recovered body-enable/game168 leaves, and remains an explicit modern policy.
LabSimulation invokes gadget input in its existing fresh/retained input phase.
Grounded fire clears controller speed before movement apply and selects original
SHOOT. The ordinary FALL branch hides/stops the ray. Ray ownership requires
inventory(0,3)==1/raw mode−1; invalid ownership clicks117 once until release.
Held ordinary ray uses looping SFX0, spendsdt energy even without a hit and is
energy-exempt in VR01..08. Existing powered jump/fire remains independent.
ShrinkRay implements the continuous registry-order multi-target scan: body and
shrink-enable flags, not already shrunk, strict1500 distance, strict Y−150/+60,
strict quantized heading within yaw±5 with no added seam wrapping, and no accepted
source47C210 static-wall hit. The caller currently supplies only original3SOL
soldiers in LV1B/VR04/LEV1; only VR04 actually contains those actors.
Each ordinary hit requests SHRINK, sets mode5, timer30 and shrunk flag, awards10
through SceneInteractions and then writes the reaction marker. Score persists in
original-format snapshots. Already-shrunk targets do not receive repeated awards.
LIBBYPLANT/C3DDINO quest branches remain outside this3SOL consumer. Timer updates
preserve the source >0 decrement/<0 expiry edge, including exact-zero retention.
Expiry restores authored/reset AIState (VR04=2), not the pre-hit dynamic mode,
clears the marker and selects looping WALK/speed200.
Original soldier WALK/SHRINK geometry uses soldatak's matching original UV topology;
walk/shrink ASE files contain no UVs. Source SHRINK holds its last authored frame
(55.1186 high), without invented uniform scaling. The transition preserves frame
ordinal; exact within-frame clock preservation remains open. Source roots and
units are retained. Soldier body settling uses the existing provisional NPC
support/wall adapter with recovered90/1, not a claim of complete enemy physics.
The owned RAY mesh follows the captured player root/upright Euler without invented
muzzle offsets, lifetime or cooldown. Three source textures switch at the recovered
float-accumulator >double0.1 boundary, discarding overshoot. Source alpha0.5 is
applied once, not as geometric scale. Additive SrcAlpha/One is the chosen recovered
graphics branch; the source graphics-option predicate is still open. Generic alpha
SrcAlpha/OneMinusSrcAlpha is also implemented. Blended world depth-write disabled
and inherited cutout behavior are explicit rendering policies, not full legacy
material-state recovery. Opaque defaults and UI ordering are regression checked.
## Verification
Full scripts/test.sh passes157 Python checks,2 HUD tests, all managed suites,
29 game GPU completions and17 isolated Vulkan blend/readback checks with zero
enabled validation errors. Fifteen gadget groups cover menu/state/viewport,
source target gates, phase clock, held/release/energy/sound, authored morph hold,
score callback order and TSK persistence. Heading covers the65,540 original-DLL
references separately.539 original files remain unchanged.
Final source close-before-selection and authored-mode corrections pass the
complete final suite in integration-final.log; the latter distinguishes pre-hit
dynamic7 from restored authored2. No old numeric body/controller result changed.
Native Linux GTX1070/private Xvfb passes gadget-menu input at1920×1080 and ray
input at1280×720, with zero validation errors. Menu24 frames verify shared
Tab/Space edge, pause, Escape, select without leaking fire, Practice, Return and
stable root. Ray90 frames hits an actual VR04 yoke1 once, holds its authored small
pose, cycles all three textures and retains VR energy20.
Final source replay logs are native/menu-final.log and native/shrink-final.log.
The ray smoke explicitly moves the player near an actual authored soldier after
body settling. It does not invent/relocate targets or claim input navigation to
their high platforms, patrol/combat AI, or original visual parity. Saved mesh
height is a port animation observation; GPU readbacks verify rendered output and
material behavior. Logs/readbacks are in artifacts/gadget-implementation/ and
artifacts/gadget-blending/. Windows cross-publish/native runtime remain distinct.
Both distribution packages identify clean source7b5230c (source_dirty=no).
Publication succeeds for linux-x64 and win-x64; NU1900 records unavailable package
vulnerability metadata. Resource checks find54 menu canvases and soldier/VR
soldier/ray/SHOOT manifests in both packages. Standalone Linux from /tmp passes
the1920×1080 menu and90-frame VR04 ray fixtures in package-menu.log/package-ray.log;
release validation layers are unavailable. All539 original hashes verify again
after packaging. Preserved baseline packages remain untouched. Native Windows
gadget behavior is not agent-verified.
## Remaining work
| System | Recovered contract | Current port / remaining boundary |
| --- | --- | --- |
| Selection | Group0, eight cards, display3 versus raw−1, close before select | Implemented; inherited raw2/3 art visibility is a declared fallback |
| Practice | Selected item→VR01..08, disabled in tutorials/SCENE>=500 | Implemented through existing departure/RETURN state |
| Primary ray | Owned item3==1, continuous held scan, FALL interruption | Implemented in first-route scenes; full Euler/retained owned-effect lifecycle open |
| Energy/audio | Energy−dt, VR exemption, loop0, invalid117, warning80/182 | Scalar/loop/invalid implemented; warning latch and broader sound lifecycle open |
| Soldier hit | Strict target gates, SHRINK/mode5/timer30, +10 then marker | Actual VR04 3SOL implemented; later eligibility setters/AI and special quest classes open |
| Restore/animation | Strict-negative expiry, authored AI mode, WALK200, nonloop SHRINK | Implemented; exact fractional morph clock and full NPC physics remain provisional |
| Rendering | Original mesh/textures, opacity.5, two blend branches | Tested additive choice; graphics-option predicate/full material state open |
| Timing/ownership | Body enable and SFX gate on menu, original input phase | Existing phase bridge used; full-panel pause is modern policy, complete scheduler open |
Other gadget effects/equip cleanup, full soldier AI/reaction consumers and
dynamic collision; score popup and other quest targets; low/empty energy audio
latches; owned-ray retention across loads; exact full-Euler/render root and morph
phase; complete menu/music/software-clock lifecycle; original whole-game and
native Windows verification. These are bounded follow-ups, not reasons to replace
recovered source rules with invented cooldowns, damage, colliders or uniform shrink.
+117
View File
@@ -0,0 +1,117 @@
# First gadget integration review
Review of `SceneGadgets`, `ShrinkRay`, `LabSimulation`, `ShrinkRayVisuals`,
`ShrinkSoldierVisuals` and their `Program` wiring against
[shrink-ray.md](shrink-ray.md), [shrink-heading.md](shrink-heading.md) and
[shrink-targets.md](shrink-targets.md). This is a read-only source/evidence review,
not new gameplay runtime verification. It records the snapshot before the
primary's review fixes; subsequent implementation/tests must mark fixes verified.
Update during review: the primary added `ScoreAwarded`→`ChangeScore` wiring and
the source hit marker. Reading the updated code confirms ordinary +10 reaches
the score/save owner and the marker is set after the event; build/runtime checks
belong to the primary. The initial finding remains below as the reason for that fix.
## Directly evidenced callback omission
**Resolved: the initial implementation omitted the original +10 score callback.**
The initial `SceneGadgets.Input` applied `ShrinkSoldier.Shrink()` and incremented a diagnostic
hit counter without awarding persistent `SceneInteractions.Score`. Primary now
awards/persists10 and sets the reaction marker after the score event; its managed
test verifies ordering and the original-format save round-trip. Original
`42AC10..42ADB5` (raw `2AC10..2ADB5`, same guarded source identity as the ray
report) performs action/mode/timer/flag writes, then branches on the target's
ObjectTag at interface+3A0:
| Tag comparison / address | Recovered effect |
| --- | --- |
| `LIBBYPLANT`, 42AC84–42AC9B | Find `C3DLIBBY`; if found, award 100, mode 0, write 160 to complete6C4, set two action strings to WALK, and change SCENE 250→255 if currently 250. |
| `C3DDINO`, 42AD3F–42AD7E | If task DINO <10, set DINO=10 and award 300; otherwise return without those effects. |
| Every other tag, 42AD81–42ADA1 | Award 10 through42ADC0; write target complete94C/interface88C=1.0. |
`42ADC0..42ADF9` (raw `2ADC0..2ADF9`) adds with signed 32 arithmetic, clamps
negative total to 0, and for positive awards records the amount at 4F83C4 with
1.2s at 4F83C8. Existing score/save ownership belongs to `SceneInteractions`;
the shrink hit diagnostic is not a substitute. Preserve the reaction field as
an explicitly identified dependency of the still-unported enemy base/AI update;
its complete consumer semantics have not been recovered by this review.
Read-only GAM parsing confirms first-route scope:
- `level1b.gam` (lab): zero 3SOL actors.
- `VR04.gam`: three 3SOL, tags `yoke1`, `C3DYOKIANSOLDIER`, `yoke2`.
- `Level1.gam` (outside): zero 3SOL actors.
Thus all currently supported real target hits use the ordinary +10 branch,
including VR04. The callback has **no VR score exemption**. Do not apply the
energy exemption to score, invent a generic quest/objective update, or award
the special branches for every enemy of a matching class. Earlier vague
Humphrey descriptions do not identify this branch: the exact shipped string is
`C3DLIBBY` at4EF710. The apparent SE9 call at 42AC17 reaches `472970`, whose body
is `C3`/return; it is not evidence for another hit sound.
The primary's regression now checks the +10 save effect once per accepted
unshrunk target, simultaneous targets and later re-shrink after restoration,
while VR energy stays unchanged. The reaction-field consumers and unsupported
quest classes remain named limits rather than inferred combat behavior.
## Confirmed source alignment
- Owned item 3 must equal 1; equipped mode is −1 even when UI display item 3 is
highlighted. There is no positive-energy gate or projectile cadence in the scan.
- The scan is continuous while held. Current strict root height, distance<1500,
quantized original heading, no added heading seam wrap, geometry-query rejection
and multiple-hit behavior agree with the bounded source contract.
- The corrected FALL logic is sound: at 42692A an absent loop branches to426937;
`strcmp(FALL)==0` at 426948 skips the scan. With a loop present, equality at
42695F falls through stopping its handle, setting−1 and hiding the beam at
426963..426989. Other airborne actions can start/retain the loop and scan.
The port correctly blocks FALL, not all airborne poses, and reserves SHOOT for
grounded fire. Source speed608 is zeroed before this branch, including air.
- Beam position/yaw are captured when firing and rendered from that snapshot;
they should not be replaced with the player's later render-frame root. Source
copies root and full Euler at 426EF1/426F47, with no caller muzzle offset.
- Texture phases 0/1/2 use a float timer compared strictly with double0.1, advance
at most once and discard overshoot. Opacity .5 and additive drawing implement the
known global509A13=false branch. Conventional alpha is the other recovered
branch; the original settings/hardware choice is unresolved, so additive is
an explicit port policy, not a universally recovered default.
- Soldier geometry uses original WALK/SHRINK topology, actual GAM roots and an
authored nonlooping shrink morph. False selector preserves a clamped frame
ordinal; modern within-frame clock is explicitly approximate. There is no
invented uniform scale. Strict-negative expiry, WALK restart and restored
speed 200 follow the source. Radius 90/factor 1 are source defaults; reuse of the
existing scene-physics adapter remains provisional collision behavior.
## Material bounded differences and next checks
1. **Energy audio:** direct subtraction/clamp in `SceneGadgets.Input` matches the
scalar part of42A920, but omits its empty-crossing SFX80 and low-energy SFX182
latch/hysteresis (<19 to set, >20 to clear). VR04 masks this omission through
its energy exemption. Share the energy-adjust lifecycle before claiming source
fidelity outside VR04; do not add an unsupported energy>0 firing restriction.
2. **Full Euler:** the effect and wall endpoint use only yaw. Source copies all
Euler components. This is bounded by the present upright controlled-player
model; source pitch/roll behavior and generic Euler normalization remain a
dependency. Preserve full snapshots when that orientation model is implemented.
3. **Eligibility:** both source defaults are now confirmed. Generic constructor
46FDDF (raw 6FDDF) pushes 1, then46FDE3 calls471030. That setter writes authored
+16 at471037 and dispatches slot 214 at47103A; soldier game vtable4C19C4+214
contains471A00, whose471A04 writes live interface13E. Yokian constructor44A94F
(raw 4A94F) writes complete958/interface898=true;44A905 clears shrunk. Actual
soldier constructor44BF32 calls shared44A730; loader44C0B0 does not override
these flags. This agrees with the prior guarded body-composition finding
integration210/live13E=true. The current default-true candidates cover these
initialized actors under the no-AI boundary, but do not mirror later setters.
Actual VR04 GAM CanMove1 is the separate animated-object58C field; do not
equate it, generic `Actor.Active`, or visibility to the source body/shrink gates.
4. **Scope/ordering:** soldier AI, shared enemy reaction-field consumers, full
registry scheduling and hidden-owned-effect initialization remain outside this
first interaction. The modern step order is an implementation partial order;
standalone or rendered smoke success does not verify the original game's
complete update order. A native Windows walkthrough still needs hold/release,
jumping/FALL interruption, a wall-blocked target and 30s restoration checks.
No additional runtime changes were made by this review. Existing complete REA
Evidence/source guards are reused; unavailable source42AC10 decompilation was
not retried. Exact callback branches above were cross-checked against the guarded
original instruction range and source string bytes.
+148
View File
@@ -0,0 +1,148 @@
# Shrink-ray heading recovery
This closes the heading dependency of the held shrink-ray scan in
[shrink-ray.md](shrink-ray.md). Facts below come from immutable original bytes,
REA/Ghidra 12.1.4, and an isolated component call to a generated DLL copy.
The managed implementation is `src/GamePort/Game/OriginalHeading.cs`;
`OriginalHeading.Degrees(targetRoot - jimmyRoot)` returns the quantized source
heading. The caller must retain the original strict EulerY±5 comparison without
adding seam wrapping. Whole-game target selection remains a separate integration
and runtime check.
## Source identity and ownership
Original EXE SHA256:
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
OMT2.dll SHA256:
`3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
Generated targets were `artifacts/uncontrolled-phases/rea/Neutron.exe` and
`artifacts/asset-probe/game/OMT2.dll`. No original was modified or executed in
place. The focused helper checks both complete hashes, the import/export mapping,
13 instruction sites, six constants, and the regenerated lookup fingerprint.
| Owner/location | File offset | Recovered role |
| --- | --- | --- |
| EXE IAT0048D108 | `8D108` | OMT2 import `?angles@OMedia3DVector@@QAEXAAF0@Z` |
| EXE 00426FE4–00427011 | `26FE4` | Stores float32 target-root minus Jimmy-root vector |
| EXE 004270B1–004270C5 | `270B1` | Calls vector::angles with two signed-short references |
| EXE 004270D7–0042713B | `270D7` | Reads second output; strict heading-window comparisons |
| DLL 1001FDA0–1001FF6E | `1FDA0` | Export 278, `OMedia3DVector::angles(short&,short&)` |
| DLL 1001FDCB–1001FE3D | `1FDCB` | Computes horizontal lookup/quadrants; stores second output |
| DLL 100EDC00–100EDD2A | `EDC00` | `OMediaCosSinTable::init_table`; table generation |
| DLL 10104E04–10104E2B | `104E04` | Integer conversion explicitly switches x87 to truncation |
| DLL 10161E38 | runtime-initialized table | Half-acos unsigned-short table, global object+20008 |
Ranges above end exclusively. EXE addresses use base00400000, DLL addresses
base10000000; these source ranges have raw offset=RVA. Full range hashes and
checks are in generated `artifacts/shrink-ray/heading-source.json`.
## Recovered algorithm
Only vectorX and vectorZ affect the second output. It is always in 0..16383,
although the caller reads it with sign extension. One unit is exactly
`360/16384 = 0.02197265625` degrees (EXE float0048E5B4).
For finite float32 components, with extended intermediates in the original:
```text
if x == 0 and z == 0: return 0
i = trunc(16384 * z*z / (x*x + z*z))
a = halfAcos[i]
if z < 0:
a = (x < 0) ? 8192+a : 8192-a
else if x < 0:
a = 16384-a
return (-a) & 16383
```
The original actually truncates the negative ratio multiplied by−16384 and
subtracts that integer from the combined-table base index10004. The positive
index formulation above is equivalent on finite inputs. There is no atan2 call.
The table contains truncated integers:
```text
halfAcos[i] = trunc(acos(i * .0001220703125 - 1)
* 2607.5945876921437 * .5) # i=0..16383
halfAcos[16384] = 0 # explicit final endpoint
```
The stored constants and truncation are significant. The first 16384 words match
the previously observed copied-DLL FNV32 `4f800433`. The 16385-word little-endian
table SHA256 is `292eaae8707bcbc0e760280eca51ecb760914dbac81e943428219713e9065744`.
| Direction | Heading units | Degrees |
| --- | ---: | ---: |
| +Z | 0 | 0 |
| −X | 4096 | 90 |
| −Z | 8192 | 180 |
| +X | 12288 | 270 |
| X=−1,Z=+1 | 2048 | 45 |
| X=+1,Z=+1 | 14336 | 315 |
| X=+1,Z=1000 | 16364 | 359.560546875 |
| X=−1,Z=1000 | 20 | .439453125 |
| X=1000,Z=1 | 12288 | 270 |
This orientation matches the port's forward vector `(−sin(yaw),0,cos(yaw))`.
The coarse ratio table near cardinal axes is part of recovered behavior;
replacing it with rounded atan2 would change target acceptance near the 5° edge.
The scan calls this after its root-height and distance filters. The first
reference receives pitch and is unused here. For the zero vector the copied DLL
returns pitch 4096/yaw 0; this utility intentionally implements only yaw.
## Window and state interaction
At004270D7 the scan reads the second output from stack +16. It multiplies by the
stored degrees factor, compares strictly greater than JimmyEulerY−5, then at
00427112 compares strictly less than JimmyEulerY+5. The 5 is stored at0048D950.
Rejected targets branch to00427310, the next registry entry. These instructions
perform no modulo normalization, shortest-angle difference, nearest-target
selection, cooldown, or heading hysteresis.
Consequently a tiny positiveX target can yield359.56° and fail when JimmyY=0,
while its mirrored negativeX target yields .44° and passes. Do not repair this
asymmetry speculatively. Original Euler normalization outside this caller is a
separate system dependency.
## Evidence and verification
REA Evidence
`ev_944c7a8e63e2c332ecaabe01ddb6587f0c4b25ee087124e15394d617a94b2633`
is retained completely in `artifacts/shrink-ray/rea-heading/evidence.json` and
`analysis.snapshot.json`; extracted pseudocode is `heading.pseudo.c`.
The Ghidra call completed in 254.6s, beyond the existing batch client's 180s wait.
The client then closed its owned session successfully. The complete result was
recovered from that closed snapshot; no unchanged request was repeated. Ghidra's
x87 pseudocode omits portions of the ratio expression and misnames some stack
values; the instruction stream, not those temporary names, establishes the
formula above. `heading-source.json` records source offsets and range hashes.
`tools/binary/shrink_heading.py --emit-probe <generated.c>` emits a bounded probe
using only LoadLibrary/GetProcAddress on the generated OMT2 copy. It calls the
export with synthetic vectors; no game entry point is run. The existing
`tools/recon/reference_capture.py` harness isolates its filesystem/network and
does not mount Original/. Retained output is
`artifacts/shrink-ray/heading-probe/wine.log` and `capture.json` (exit 0). The first
six-second attempt ended during cold Wine initialization; its capture/log were
retained separately. The changed thirty-second run completed normally.
Observed: 15 explicit vector results and 65,540 generated bin/quadrant cases.
The sweep's word-wise FNV32 is `24e64f91`; both Python and managed implementations
match. This verifies the component under Wine, not full gameplay or native
Windows behavior. The source uses x87 extended intermediates; the managed/Python
projection uses double. Arbitrary float32 inputs exactly at ratio-bin boundaries
remain a precision risk beyond the observed sweep. Nonfinite vectors are rejected
explicitly by the modern utility; original invalid-input behavior is not claimed.
Reproduce from GamePort/:
```sh
python3 tools/binary/shrink_heading.py
python3 -m unittest discover -s tests -p test_shrink_heading.py -v
source scripts/env.sh
dotnet run --project tests/GamePort.HeadingTests
```
Remaining: integrate the utility with the scan's eligibility/raycast/callback
contract and compare actual target acceptance in gameplay. No unresolved heading
quadrant or table dependency blocks that integration.
+147
View File
@@ -0,0 +1,147 @@
# Shrink ray primary fire and owned effect
2026-10-27. Read-only static recovery from supplied EXE SHA256
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Preferred VAs below map to raw file offset VA−400000 for this image's text;
shrink_ray.py independently PE-maps all locations and guards eight bounded
function ranges plus44 source sites. No original code was executed by this task.
## Important identity correction
The inventory/menu highlight is not the raw equipped-mode word4F0588. The
[gadget control investigation](gadget-controls.md) proves selecting group0/item3
cleans current mode to−1, then calls equip174(3); cases3 and−1 leave that mode
unchanged.426E40's shrink scan requires owned item3==1 **and mode−1**. The same
item owns the recovered jetpack ability. Earlier jetpack-only descriptions that
treat SHRINKRAY as an unrelated internal label are superseded by this combined
source path and the original item's SHRINK/JUMP art. Do not implement selected
mode3 as a separate shrink-ray state merely because the menu highlights item3.
## Primary input and animation ownership
| VA / raw | Recovered contract |
|---|---|
|426030 /26030|Input callback first requires407060 false,475CA0 true, controlled5099E4 nonnull, global4F8430 false and interface1D2D false. Movement438A60 and gadget subhandlers run before the ordinary fire tail.|
|42A7A0 /2A7A0|Primary helper is false while4F83E0 is set; otherwise OR of509834,509845,509849,509AC4. Readme maps Enter/Ctrl/left mouse; pad input remains separate.|
|426566..42657F /26566|Held primary helper OR keyboard13 invokes the held-fire branch. Release stops the owned sound loop and hides the ray.|
|42668F..4266BD /2668F|Busy1D65 or modal4F8182 rejects; raw mode0 rejects; otherwise controller speed608 is set0.|
|4266C8..4266F1 /266C8|Grappler/energy subhandlers run; mode4 exits; ordinary mode−1 continues.|
|4266F7..42672B /266F7|Supported body requests SHOOT, then animation148. The caller's grounded shooting pose, not the collision support routine, owns this action.|
|4268BE..4268F7 /268BE|Owned item3 must equal1. If sound handle interface974==−1, start SFX0 looping and retain its handle. Invalid availability emits SFX117 and latches busy1D65 until release.|
|426902..42698C /26902|Airborne branch permits the ordinary fire path around the FALL action and owns its own loop interruption; do not force all airborne frames to grounded SHOOT.|
|4269BD /269BD|Complete virtual1B8 invokes426E40 after these gates. No one-shot cooldown or projectile spawn is present in426E40. It is a held, per-input-invocation scan.|
Raw primary callback physics/control predicates are separate from the modern F1,
inspection, focus and practice modal policies. New primary input must be cleared
at modern capture boundaries and must not leak into cutscene skip/menu selection.
## Target scan and hit order
426E40..427334:
1. Require403950(group0,item3)==1 and signed4F0588==−1.
2. Show Jimmy-owned complete object+A10 (interface+950) if present. Copy Jimmy's
current root exactly via318 and current Euler exactly via330. There is no
muzzle offset in this caller; the original ASE supplies the effect geometry.
3. Call42A920(−dt) once **before target traversal**, even if there is no hit.
There is no positive-energy test in this ordinary scan.42A920 exempts original
VR01..VR08, otherwise clamps energy0..100 and owns low/empty sounds/latches.
4. Traverse object registry50999C in linked order. Payload is the game interface.
Require interface13E nonzero, class-name check18(`C3DENEMY`), interface898
nonzero and interface8B0 false (already-shrunk flag).
5. Require enemy rootY strictly greater than JimmyY−150 and strictly less than
JimmyY+60. Full root-to-root Euclidean distance must be strictly below1500.
6. Call imported vector calculate_angles48D108; convert its signed-short heading
to degrees with stored float0.02197265625. Require heading strictly inside
JimmyEulerY−5 .. JimmyEulerY+5. These instructions add no seam wrapping; exact
angle production/convention and generic Euler normalization remain a separate
numeric contract. The helper projection accepts the recovered heading as input.
7. Build a source ray from Jimmy root+(0,150,0) to offset384(0,150,distance).
Call47C210 and reject on **any accepted wall-query hit**. This is the original
static grid/winding query, not nearest sphere sweep or a pixel/crosshair test.
8. For each accepted enemy invoke Jimmy complete1DC→42AC10(target interface).
There is no break/nearest-target reduction: multiple eligible enemies may be
hit in a single invocation. Registry order and source wall query are dependencies.
42AC10 requests exact action string `SHRINK` at4EF71C with argument0 through
enemy completeE0, sets enemy complete124(5), then complete974=30.0 and
complete970=true. Those fields are interface8B4 timer and8B0 flag. It also owns
class/tag-specific objective, score and Humphrey policy, so generic shrinking
must not invent a universal score or destruction event.
The independent [target investigation](shrink-targets.md) owns actual3SOL class,
SHRINK morph, timer expiry and restored action. Its source check corrects an
initial label:44AEC6 requests `WALK` (4ECA54), not STOP. Visual shrink is driven
by the original morph/action; do not substitute an invented uniform scale.
## Beam effect is an owned object, not a ballistic projectile
Jimmy constructor4222AB allocates6D0 bytes;4222C9 calls43FE20 and4222D9 stores
the resulting complete object at Jimmy+A10.43FE20 establishes C3DShrinkRay
interface table4B4350, invokes440000 Init and disables its physical collision
through220 setter4710C0. Phase complete6BC starts0 (interface5FC).
440000 Init binds `HIRAY`→`ray.ase` at440037, then texture slots0/1/2 to
ray0000.png/ray0001.png/ray0002.png. It sets action `RAY`, radius40 and source
factor0.3; these physical values do not imply a moving projectile. The caller
keeps the owned effect at Jimmy's root/Euler while held and hides it on release.
**Opacity, not scale:** C3DShrinkRay complete114 resolves40E4A0. Positive param
walks shape polygons and each nonnull material, writes RGB1 and alpha=param to
material+4C..58, source blend field+30=6, destination+34=7 when global509A13 is
true or1 otherwise, and ORs material flag38 with1. Init and every texture switch
call114(0.5). The earlier per-texture RGBA writes also set0.5; this setter
replaces the alpha rather than multiplying it again. No geometric half-scale is
justified.
The engine adapter10036AB0 (raw36AB0) uses table1013667C (raw13667C) to map both
material enums into D3D render states19/20. Selected entries are6→D3D5 SRC_ALPHA,
1→D3D2 ONE,7→D3D6 INV_SRC_ALPHA. Thus global509A13=false selects alpha-weighted
**additive** blending (SrcAlpha,One), while true selects conventional alpha
(SrcAlpha,OneMinusSrcAlpha). The flag is loaded from a graphics-setup option and
stored476BBE; its complete settings/hardware fallback semantics remain open.
Do not silently treat both branches as conventional alpha. The DLL SHA256 is
`3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
440180 interface3C4 update first invokes base40E050. On its first pass a flag
interface604 causes Init through1C; then float timer600 adds dt. When strictly
greater than **stored double0.1**, phase5FC increments, wraps after2 back0,
swaps the bound texture, reasserts opacity0.5, and resets timer0. It advances at
most once per invocation and discards overshoot. Since float0.1 is slightly above
double0.1, passing an exact float0.1 triggers the switch. No independent finite
beam lifetime is present; hold/release and object visibility own it.
## REA evidence, gaps and checks
The three owned EXE REA sessions used the generated hashed
artifacts/uncontrolled-phases/rea/Neutron.exe and closed/exported normally.
A fourth session used the generated artifacts/asset-probe/game/OMT2.dll copy for
the blend adapter, also closed/exported under artifacts/shrink-ray/rea-blend/.
| Retained path | Successful Evidence |
|---|---|
|artifacts/shrink-ray/rea-primary-followup/03.json|42A7A0 ev_3ff9cde0cab7a1e7ed456591becfcc4c4f4db3796aa6ab5e76a1dd124f9dac47|
|rea-primary-followup/04.json|42A920 ev_71897af12f4bfa1de946c6f17f3bbed34764fdc84258ce64516c8f1f904b465d|
|rea-effect/00.json|440000 ev_875816ebeb0d690c83518f14f36a13d646009d3530c0ad1f27efbd3a2342aeff|
|rea-effect/03.json|43FE20 ev_3ae9cf6456693b674f937b0e4c86392b88f0d80f8eb416e5b7585f08f790e7f9|
|rea-blend/00.json|10036AB0 ev_f5a914ee9eae593b02a04149b6651b2d783151df046bbb417624bf94f23bb96c|
426030/426E40/429D00 VA queries were unrecognized; corrected raw-offset selectors
were tried once and also failed.440180 and42AC10 likewise have no recognized
procedure in this profile. Errors/complete diagnostics remain beside successful
Evidence; their conclusions use fixed source instruction/body guards and the
matching class/vtable/asset chain, not invented successful decompilation.
`python3 -m unittest discover -s tests -p test_shrink_ray.py -v` passes seven groups:
source bodies/constants/assets/opacity anchors; owned3/mode−1; independent target
gates; strict range/height; strict quantized-heading/no-added-wrap; texture float/
double threshold, wrap and discarded overshoot; DLL body/table identity and
additive/conventional-alpha factor distinction. These are source projections,
not original execution or managed/native gameplay verification. Complete source
report can be generated with shrink_ray.py ../Original; originals remain read-only.
Remaining: exact imported heading production/Euler normalization, full airborne
SHOOT interruption, graphics-option/depth order, full enemy class/
script/score policies and original whole-game runtime comparison. The source
device's held geometry, textures, ownership gates and target callbacks support a
bounded first implementation; a synthetic projectile cadence is not supported.
+198
View File
@@ -0,0 +1,198 @@
# Original 3SOL shrink targets
Status: recovered static binary/asset contract for a bounded first shrink interaction.
Original runtime verification, full soldier AI, and exact collision integration remain open.
Originals were read only; REA inspected generated hashed copies, never executed originals.
Run `python3 tools/binary/shrink_targets.py ../Original` to produce the guarded contract,
including PE-mapped **file offsets** for every address below. Saved output:
`artifacts/shrink-targets/source-contract.json`. Addresses in this note are preferred-base VAs.
## Evidence ledger
REA results, complete evidence, snapshots, and closed-session records are retained under
`artifacts/shrink-targets/`. REA observations are static analysis, not runtime traces.
| Question | REA Evidence ID | Saved directory |
|---|---|---|
| Shared Yokian construction | `ev_19d3441021faa1f39087a8e65e3b04df57315de2ee53f75b2e70fce2dc8a432d` | `rea-soldier/` |
| Shared Yokian update | `ev_c7d9d0bd6ea80f021689545e79baca422ca5b526d69c89d7ccf54c4ea2142a18` | `rea-soldier/` |
| Actual soldier construction | `ev_64b0152bae4f3a51a80c70f6470212b5c5cb9036e449d5eefe6129b35ace70c2` | `rea-soldier-bindings/` |
| Soldier model/texture loading | `ev_4e46100718fc9d13d99409941d2494de216d281317a04fd9e56ad33e1aa3e6ec` | `rea-soldier-bindings/` |
| Generic load caller | `ev_efdc2d429180a0cd692326a261bc274ac5cb0daf45ab167c0627a858acabf041` | `rea-soldier-bindings/` |
| Engine sequence selection | `ev_67aff8ee9529fa39014ae438e22e3dc52ecd2ce71d0886974d0682d6eea58f8b` | `rea-sequence/` |
| Engine endpoint/loop handling | `ev_e0d4f2ee9131d62ea289ea1aeb0f24b7de4a2bd696149309e9dfb2e3d14614df` | `rea-loop/` |
| Dynamic mode setter | `ev_8286c3d9b13f47f1e6fbf211d85636b54fb5ccb7cc7e55dd1e0f0366a7170b84` | `rea-mode-local-ipc/` |
| AIState property registration | `ev_aa47a422ce39fc5bf5bbca319fe3c37e27526299abeb9f6cdb9d065d46de9f50` | `rea-mode-local-ipc/` |
| Generic load/reset state | `ev_c448bb4062e760eb4bf3b09d39e630b130a8eafd377a27625a25b69ab7679a27` | `rea-mode-local-ipc/` |
The first mode-closure attempt (`rea-mode/00.json`) failed because the sandbox
blocked Ghidra's local Unix-socket bind. The successful invocation above used
local IPC permission; no provider/client configuration was changed. Its complete
Evidence and close/snapshot records are retained. The failed call is not used
as evidence for source behavior.
`Neutron.exe` SHA-256: `f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
`OMT2.dll` SHA-256: `3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
The helper guards eight bounded code ranges, decisive byte sites, vtable targets,
resource strings, and all three ASE hashes; it fails on an unexpected identity.
## Class ownership and initialization — recovered
`44A730` constructs shared **C3DYokian**, not the final soldier. Actual soldier
constructor `44BEE0..44C028` calls it at `44BF32`, then registers FourCC `3SOL`
at `44BFF5`. Soldier complete-object vtable is `4C1E64`, game-interface vtable
`4C19C4` at complete object `+C0`, and embedded morph vtable `4C1E14` at `+90`.
The generic model loader `40E270` dispatches complete slot `10C` at `40E331`,
reaching soldier loader `44C0B0..44C1BB`. Derived update `44C1C0` calls shared
Yokian update `44AA00` at `44C1C9`.
| Complete slot / callsite | Recovered binding |
|---|---|
| `D8` / `40D4A0` | Register model animation definition |
| `E0` / `40DD90` | Select named action; chooses HI/LO family |
| `E4` / `40DA30` | Select underlying sequence and copy loop flag |
| `10C` / `44C0B0` | Soldier model load |
At `44C19D` the soldier pushes float **90** into game-interface slot `110`
(`471240`, authored radius setter; live setter slot `264`). At `44C1AC` it
pushes float **1** into game-interface slot `100` (`4711E0`, authored factor;
live setter slot `254`). Live read slots `260`/`250` reach `471B30`/`471AF0`.
These are soldier body defaults; they do not establish the full collision solver.
## Model, texture, and authored shrink geometry — recovered
| Registration site | Action | Original ASE |
|---|---|---|
| `44C0C3/44C0C8` | `HIWALK` | `ASE/soldwalk.ASE` |
| `44C0DC/44C0E1` | `HISHRINK` | `ASE/soldshrink.ASE` |
| `44C0F0/44C0F5` | `HITALK` | `ASE/soldatak.ASE` |
| `44C104/44C109` | `HISTOP` | `ASE/soldatak.ASE` |
The loader compares scene FourCC against `VR01..VR08` at `44C121/44C128`.
For those scenes both texture indices 0 and 1 use `vryoksoldier.png`
(`44C133/44C144`, string `4F1950`). Supplied filename is
`png/VRyoksoldier.png`; portable lookup must ignore case. Other scenes bind
index 0 to `png/yoksold.png` (`44C14F`) and index 1 to `png/yoksoldtalk.png`
(`44C160`). Loader selects `WALK` with second argument 1 at `44C184`.
All three ASE clips have 190 vertices and 377 faces. `soldwalk` and
`soldshrink` have five samples at ticks `0,960,1920,2880,3840` (5 fps,
960 ticks/frame); `soldatak` has two samples (10 fps, 480 ticks/frame).
In existing ASE→OMT coordinates, shrinking sample Y bounds are:
| Tick | Minimum Y | Maximum Y | Height |
|---|---:|---:|---:|
| 0 | -55.6508 | 260.1789 | 315.8297 |
| 960 | -19.5291 | 208.5813 | 228.1104 |
| 1920 | -28.4904 | 156.9837 | 185.4741 |
| 2880 | -4.0918 | 105.3861 | 109.4779 |
| 3840 | -1.3301 | 53.7885 | 55.1186 |
This is actual morph deformation. A uniform quarter-scale soldier would be an
unsupported replacement. No extra uniform render scale was established in the
inspected source. The visual can retain original vertex units and authored root.
## Shrink, animation ownership, and expiry — recovered
Jimmy callback `42AC10` (investigated separately in `shrink-ray.md`) receives an
enemy game interface and subtracts `C0` to obtain the complete object. It selects
`SHRINK` with argument 0 at `42AC33`, selects mode 5 at `42AC50`, writes timer
complete `974 = 30` at `42AC68`, and writes flag complete `970 = true` at
`42AC8A`. The shared constructor initializes that flag false at `44A905` and
timer zero at `44A7EA`. Game-interface-relative offsets are timer `8B4` and flag
`8B0`; authored/reset mode is interface `87C`, complete `93C`.
### Mode setter and restoration ownership — closure
Soldier complete vtable `4C1E64` slot `124` points to generic enemy setter
`4089B0`. At `4089E5..4089FE` it copies **current complete `6C8` into previous
`6CC`**, then stores the requested mode in `6C8`. Requested mode 5 takes jump
table entry `408BA8` directly to the return at `408B8E`; there is no further
mode-5 callback or copy into `93C`. Thus SHRINK selection does **not** snapshot
the dynamic prior mode into the expiry field.
Interface `87C` is registered as the GAM **AIState** property at
`407F67..407F77` (name string `4ECA90`). Shared Yokian construction initializes
both complete `6C8` and `93C` to 2 at `44A7D3/44A7F7/44A7FD`. Generic load/reset
`409480`, at `409503..40951E`, copies interface `608` back to `87C` and passes
it to complete slot `124`; the separate initialization path `409460` copies
`87C` into `608`. The expiry body reads `87C`, not previous dynamic mode `6CC`.
For the three authored VR04 soldiers this restores GAM AIState **2**. A port
which snapshots its dynamic current AI state when shrinking would diverge once
AI begins changing modes; preserve a separate authored/reset AIState field.
Its value is 2 by constructor default, rather than an uninitialized zero.
Named selector `40DD90` forwards the caller's second argument through slot `E4`
at `40DF4C..40DF5E`. Wrapper `40DA30` calls embedded engine sequence selection
at `40DA61`, then explicitly writes the argument byte to complete `AD` at
`40DA64`. Since the embedded animation starts at `90`, this is engine animation
offset `1D`. Engine `find_next_frame` (`OMT2.dll:10021000`) reads `+1D` at
`10021079`: false holds the current endpoint (`100210B4`), true wraps to first
frame (`10021080`). Therefore source `SHRINK(...,0)` **does not loop**; source
`WALK(...,1)` does loop.
The engine sequence-selection boolean also controls restart: `100209F0`,
especially `10020A3A..10020A78`, restarts at first frame when true; when false
and an old frame exists it walks old/new lists to preserve the frame ordinal.
Thus changing WALK→SHRINK need not begin at shrink frame 0. Both have five
samples. Exact within-frame clock preservation remains open; any time-zero
transition in the port is an explicit approximation until closed.
Shared update `44AA00` decrements timer only when it is **strictly positive**
(`44AE5E..44AE6F`), subtracting delta at `44AE75..44AE7F`. It expires only when
the resulting value is **strictly negative** (`44AE85..44AE90`). Exact zero does
not expire in this body and is skipped next tick: preserve/document this source
edge case instead of silently substituting `<= 0`.
Expiry zeros timer (`44AE96`), clears flag (`44AE9C`), clears interface `88C`,
reads authored/reset mode `87C` (`44AEA8`), invokes complete mode slot `124` (`44AEBD`),
and requests **WALK** with argument 1 (`44AEC6`). String `4ECA54` is `WALK`,
not STOP. It restores interface `604` speed 200 (`44AED3`). While shrunk the
inspected branch can move current mode 0 to mode 5, set interface-related value
1500, and speed 400 (`44AE42..44AE54`). Full AI meaning of those transitions is
not closed here.
Calls `43F870(40,15)` while shrunk and `(140,50)` on expiry operate on owned
effect interface `8EC`. They are **effect sizes**, not soldier body radius.
No body-radius setter was found in this bounded shrink/expiry branch; that
negative observation does not prove no other mode/base update changes physics.
## First real targets: VR04 — original level data
`gam/VR04.gam` contains three `3SOL` actors; all set `AIState=2`, `CanMove=1`,
and `HasCollision=1`. Values below come directly from the bounded GAM parser.
| GAM offset | ObjectTag | Position X,Y,Z | PatrolPoint | VisibleRange / FOV |
|---|---|---|---|---|
| `4431` | `yoke1` | `-2463.1035,6327.9810,-7001.6870` | `dyok1` | 1000 / 259 |
| `582C` | `C3DYOKIANSOLDIER` | `1677.5118,6422.5869,-4131.2129` | `eyok1` | 2500 / 259 |
| `67C5` | `yoke2` | `-529.4881,6378.4834,1319.0276` | `fyok1` | 1000 / 359 |
These are authored actors high in the scene, not entrance test dummies. A bounded
interaction test can move the player near one as an explicit test fixture; it
must not relocate original actors or claim their AI has been reconstructed.
## Implementation boundary and unresolved work
At investigation start the runtime's `SceneActorVisuals` supported Carl,
Goddard, and trophy families; it did not render `3SOL`. `MorphAnimation.Sample`
looped all clips. The supported next chunk is to export these real soldier
clips/textures, render authored actors, support a nonlooping last-frame hold,
and apply the recovered SHRINK/timer/WALK transition. Parent owns runtime work;
this report does not assert those changes have shipped or run.
Existing `OriginalScenePhysics` can provide provisional radius-90/factor-1
settling for that bounded interaction. Reusing it is an implementation choice,
not proof of original soldier physics. The following remain explicitly open:
- Full soldier patrol, targeting, attack, damage, death, shadow/effect and sound updates.
- Exact collision/support/root defaults and all dynamic radius changes through base/AI modes.
- Other script/load/reset callers that can modify authored AIState independently of dynamic mode.
- Exact sequence-switch subframe timing and special empty/mismatched sequence cases.
- Non-VR texture-index animation switching and low-detail action availability.
- Original runtime comparison of shrink geometry, 30-second restoration, targeting,
and actor placement; native Windows gameplay verification remains required.
Regression checks validate original identities/dispatch, clip topology and shrink
geometry, authored VR04 actors, and a bounded timer control-flow projection.
They do not execute original code or establish original runtime equivalence.
+202 -1
View File
@@ -1,4 +1,205 @@
# Progress — 2026-10-26 # Progress — 2026-10-27
## Gameplay gadgets — user-directed continuation
2026-10-27 UTC: user explicitly parked further collision recovery and chose
gameplay gadgets. Preserve35a2a66/0272f7b as the collision resume point; original
special/dynamic/shared-context and camera gates remain documented. The previous
feature-expansion pause is superseded for this work. Independent investigators
own gadget controls, resources and shrink-ray source reports/helpers/tests under
exclusive names; primary owns gameplay/UI/runtime integration and root docs.
The original gadget panel and combined shrink-ray/jetpack are now implemented.
Tab/Space opens the original art with owned/hover tiles, Return and direct
Practice selection, uniformly scaled for widescreen. Display item3 selects normal
raw mode−1; raw mode0 is Bubble, correcting older inferred Scooter labels.
Enter/Ctrl/left mouse fires the owned ray; jump remains the powered-jump control.
Actual VR04 soldiers use original WALK/SHRINK geometry, hold the small endpoint,
award10 once per hit and restore authored mode/WALK after the source timer expiry.
No uniform-scale substitute, invented targets or projectile cooldown is used.
Independent local REA reports retain exact source addresses/offsets, guards and
Evidence for controls, resources, targeting, heading, blend and target state.
Managed heading matches15 copied-original DLL references and65,540 sweep cases.
The first broad suite passes157 Python+2 HUD, all managed groups,29 game GPU
completions and17 isolated blend/readback checks, with zero enabled validation
errors and539 unchanged originals. The complete final rerun also passes after
the close-before-selection/authored-mode corrections, including15 gadget groups.
Native Linux/private Xvfb passes24-frame1920×1080 menu input/capture/pause and
90-frame1280×720 ray input against actual VR04 yoke1, all three texture phases,
authored55.119 mesh height, unchanged tutorial energy20 and zero validation errors.
These observations verify port behavior, not full original-game or native Windows
parity. Logs: artifacts/gadget-implementation/ and artifacts/gadget-blending/.
Final logs: integration-final.log, native/menu-final.log and native/shrink-final.log.
Scope, state owners, modern policies and remaining gates are in
[gadget implementation](gameplay/gadgets-implementation.md). Full enemy AI/combat,
other gadget effects, energy-warning audio and original lifecycle/visual comparison
remain open.
Source milestone7b5230c is committed locally. Both self-contained packages identify
that clean source (source_dirty=no); Linux and Windows publish succeeds despite
NU1900 unavailable vulnerability metadata. Both contain54 menu canvases and the
soldier/VR soldier/ray/SHOOT manifests. Standalone Linux launched from /tmp passes
the1920×1080 menu readback and90-frame VR04 ray/actual-target fixture, with authored
55.119 mesh height, all texture phases and energy20. Release validation layers are
unavailable, distinct from the enabled source/native checks. Windows remains
cross-built, not agent native-tested for gadgets. All539 original hashes verify
again after packaging. Logs: package.log, package-menu.log, package-ray.log in
artifacts/gadget-implementation/. Preserved baseline packages remain untouched.
## C4 ordinary body implementation — 2026-10-27 UTC
OriginalBodyPhysics composes the source static dispatcher, positive-Y versus
horizontal-first split, ordinary contact370/374, support/landing, published160
friction and suppression. All ten retained original-code body references match.
VR04 now uses this source static subset; lab/outside retain the capsule pending
special contacts and dynamic integration. The bridge uses actual radius60/100 for
both sphere response and support, with grounded restoration in the later wrapper.
Published body speed is separate from controller speed and survives script
preparation/control loss until a controlled publication; Init restores authored
speed (route default0). Ordinary callbacks cannot change root, so this subset
permits fixedW1 publication; full callback reentrancy remains a special-policy gate.
An independent investigator cross-checked source phase/flag branches, rootY clamp,
radius setter/getter and authored/live field chains with REA Evidence and guarded
instructions. The same investigator reviewed the implementation and independently
ran twenty body groups. No directly evidenced mismatch was found within the
declared zero-angular/ordinary/static subset. Other original VR04 dynamic classes,
generic rotations, initial/visual root and modern noclip capsule admission remain
explicit gaps. Reports: checkpoint/collision-body-composition-source.md,
collision-body-implementation.md and collision-body-implementation-review.md.
Full scripts/test.sh passes129 Python plus2 HUD tests, all managed groups including
20 body and11 dispatcher,27 GPU completions with zero enabled validation errors,
SDL dummy lifecycle and539 unchanged original hashes. Lab→tutorial→lab→outside,
RETURN/scalar/input ordering, control lock, objective/save and jetpack regressions
pass. Initial suite compile failed because two explicitly linked test projects
needed the new body dependencies; fixed and rerun successfully. Logs under
artifacts/body-composition/ retain both attempts.
After the final authored/live speed guards were added, the complete Python suite
passes130 tests in python-final.log (eight body-source groups,81 sites/12 targets).
The prior full integration run's129 count precedes that extra source regression;
no runtime implementation changed after its successful completion.
Native Linux GTX1070/private Xvfb at1920x1080 passes the300-frame VR04 SDL move/
brake/turn/jump replay and resize800x600, with zero Vulkan validation errors.
Native/headless source-body runs end grounded with travel403.88, one burst,
max rise418.93, energy20 and two support landings; radius-dependent support is
retained instead of flattening this diagnostic count. Final readback inspected;
modern sole bridge is consistent, not original pivot verification. No new native
Windows or whole-original-game comparison claimed. Baseline69d0187 remains intact.
Next: original dynamic actor/pair eligibility and shared reclip context, then
Player160/164/FENCE/LADDER for lab/outside; C5 shared eye/DEFAULT remains separate.
New package results will be recorded after the verified source milestone.
Both self-contained packages now identify clean35a2a66 (source_dirty=no). Standalone
Linux launches from /tmp pass the300-frame source-body tutorial flight and the
nondefault lab→tutorial→lab RETURN/root/scalar/companion fixture. Release validation
layers are unavailable; enabled source/native checks above remain separate.
Windows is cross-published only. Packaging emits NU1900 for unavailable vulnerability
metadata but both builds/publish succeed. All539 originals verify again afterward;
baseline package copies remain untouched. Logs: artifacts/body-composition/package.log,
package-tutorial.log and package-return.log.
## C4 static dispatcher, contacts and ordinary-body probe
Independent REA investigations and primary integration recover47B4B0's reachable
retry, source-order cell/FIFO duplicates, mutable nearest/last-polygon state and
terminal normal callback. OriginalStaticCollision implements this bounded grid
dispatcher and strict nearest support query as an isolated component. It remains
outside the playable body path. Seven copied-original dispatcher fixtures match
managed positions, pass/visit counts and callback polygon observations. Review
corrected initial nearest-distance gating and geometry-disabled publication with
retained callbacks. All investigator file ownership returned to primary.
Recovered370/374/37C, landing-before-velocity-clear, published160 versus controller608
and friction/suppression. The Player material discriminator is linked3DMa archive
ID, proven through OMT2.dll loader/database/chunk layout, not payload flags or a
render index. Scene preparation and Mesh now preserve signed IDs/completeness;
old metadata is rejected by the new source dispatcher. Actual LV1B/LEV1 contain
special climb/fence/ladder IDs; VR04 contains none. Special policies remain open.
Ten copied479D20/support fixtures completed in an isolated Wine32 harness with
synthetic ordinary-body virtual contracts. Results cover support/settling,
pending jump, falling/landing, friction versus published speed, stationary angular
motion, suppression and geometry disabled. They are numeric references for the
next adapter, not verification of a managed whole-body implementation. Corrected
C3's earlier support-hit inference:479DF7..479E54 cancels gravity/vertical velocity
when global geometry4F69E5 is disabled, not on ordinary grounded jumps. Prior
harness omissions/logs and temporary approval-review usage failure are retained;
after the stated reset, normal approval review succeeded and the probe completed.
Full scripts/test.sh passes:122 Python checks plus2 HUD checks, all managed groups,
27 GPU completions with zero enabled Vulkan validation errors, SDL dummy lifecycle
and539 unchanged originals. Eleven focused dispatcher groups pass, including actual
route material coverage, legacy metadata rejection, retained context and support
ties. Logs: artifacts/collision-integration/integration.log, dispatcher-tests.log,
dispatch/wine.log and body-probe/wine.log. No new native Windows or whole-original
game comparison is claimed. Existing baseline/release packages remain untouched.
Both self-contained RID builds succeed into separate artifacts/collision-integration/
build directories. Restore emitted NU1900 for unavailable vulnerability metadata;
compilation/publish succeeded. These are build artifacts, not a new package release
or native Windows runtime verification. Logs: build-linux.log/build-windows.log.
Reports: checkpoint/collision-grid-traversal.md, collision-contact-callbacks.md,
collision-body-probe.md and collision-integration-review.md. Next: ordinary body
composition against the ten references, then an explicit VR04 live subset with
root/input/ceiling/RETURN checks. Lab/outside replacement additionally requires
special callbacks and dynamic shared-context/reclip order. Shared camera eye,
audio clock/banks and remaining plan chunks follow their existing gates.
## C4 sphere response and ceiling continuation
REA investigated47BD80,479D20,47BBB0,47B4B0 and projection helpers on a generated
EXE copy. Complete Evidence/exports/closed snapshots are retained in
artifacts/collision-response/. Byte-guarded callgraph, nearest face/edge state,
one-sided ray, lower-edge mode and separate support phases are documented in
checkpoint/collision-response.md. An isolated copied-original kernel probe passes
ten synthetic cases under Wine32, including wall face/crossing/departure, edge
switches/lower-edge override and ceiling. Preferred-base mapping was unavailable;
the fixture rebases only explicit guarded in-memory operands. No original files
are patched or game entry point executed. Initial harness failures are retained.
Added OriginalSphereResponse as a bounded component with original numeric-reference
regressions. The live capsule remains until static-grid traversal, normal callbacks,
negative-Y split, support/friction and dynamic reclipping satisfy the C4 gate.
This supersedes the earlier recursive-sliding inference, not the whole solver.
Integrated directly evidenced Jimmy overhead behavior for LV1B/VR04/LEV1: root+150
one-sided47C210 query, min(−0.6*Vy,−85) response, mode1 jump/fire cancellation before
movement/fire. It runs without raw control. Fresh input still precedes Jimmy's
wrapper, retained input follows Jimmy/fire. Camera-only debug toggling does not
disable physical queries. Current capsule position response, other scenes and
full sound/gadget cleanup remain explicit approximations. See ceiling-wrapper.md.
Independent investigators supplied ceiling and camera byte guards plus REA batches;
primary completed reports and registration guards when investigator capacity ended.
All ownership is now primary. body-root-registration.md closes retained49E clearing,
physical-list rebuild and repeated Init before placement; it does not invent a
capsule height. camera-handoff.md proves resumed follow captures the shared scripted
eye and pre-update aiming; that C5 implementation remains next. Provider-unrecognized
entries/errors remain on disk beside successful Evidence and supplementary bytes.
Targeted movement25 groups, original lab ceiling/query fixture, five sphere groups,
camera query groups and source/projection tests pass. Both input-only lab/outside
and underground passages use the same geometry queries as Program and pass with
their score/task/contact assertions intact. Final scripts/test.sh passes:
104 Python checks plus separate HUD checks, all managed groups,27 GPU completions
with zero enabled Vulkan validation errors, SDL dummy lifecycle and539 unchanged
original hashes. Native Linux GTX1070 at1280x720 passes Carl/control,300-frame
jetpack SDL input/resize and F1/F3 checkpoint tools (four commands, five scene
renders), with zero validation errors. Logs: integration-final.log and native/.
Native Windows and original whole-game comparison remain open.
Both self-contained packages rebuilt from clean57dfcc6 (source_dirty=no).
Standalone Linux launches from /tmp pass the control/body/fire fixture and
nondefault tutorial/RETURN scalar/root/companion/availability assertions. Release
validation layers are unavailable; enabled source/native-window checks remain
separate. Logs: package.log, package-control.log and package-return.log under
artifacts/collision-response/. Preserved baseline packages remain untouched.
Windows is cross-published only. Next: complete C4 traversal/normal callbacks/
support/friction/dynamic reclipping, then shared viewport eye/aim ownership.
## Uncontrolled-player implementation and REA ## Uncontrolled-player implementation and REA
+22
View File
@@ -5,6 +5,15 @@ offsets, virtual addresses, API symbols or observed behavior. Decompiled output
evidence, not original source. Original gameplay has not yet been observed successfully; isolated original DLL evidence, not original source. Original gameplay has not yet been observed successfully; isolated original DLL
probes and modern runtime checks are recorded separately. probes and modern runtime checks are recorded separately.
- `gameplay/gadgets-implementation.md`: first playable gadget scope and evidence
map. `gadget-controls.md`/`gadget-assets.md` retain original group0 state, menu
rectangles and54 canvases. `shrink-ray.md` traces input/ownership/energy/target
scan and callback; `shrink-heading.md` records15 copied-DLL references plus
65,540 comparison cases. `shrink-targets.md` traces actual3SOL bodies, authored
morphs and authored/reset versus prior dynamic AI modes. `gadget-blending.md`
distinguishes recovered opacity/blend branches from Vulkan depth policy;
`gadgets-review.md` records independent review and resolved scoring omission.
- `checkpoint/control-phase-implementation.md`, `uncontrolled-player.md`, - `checkpoint/control-phase-implementation.md`, `uncontrolled-player.md`,
`uncontrolled-physics.md`, `cutscene-preparation.md`: frame/body versus identity `uncontrolled-physics.md`, `cutscene-preparation.md`: frame/body versus identity
gates, ordered CAM/MCA/AI preparation and bounded implementation. `rea.md` records gates, ordered CAM/MCA/AI preparation and bounded implementation. `rea.md` records
@@ -14,6 +23,19 @@ probes and modern runtime checks are recorded separately.
read chain, bounded ordinary-load scalar/body resets, full tutorial availability read chain, bounded ordinary-load scalar/body resets, full tutorial availability
tails and companion/shadow lifecycle. Source-byte checks and an isolated original tails and companion/shadow lifecycle. Source-byte checks and an isolated original
body-routine probe are separate from whole-game/runtime comparison. body-routine probe are separate from whole-game/runtime comparison.
- `checkpoint/collision-response.md`, `ceiling-wrapper.md`,
`body-root-registration.md`, `camera-handoff.md`: REA continuation into bounded
sphere kernel/original component probe, root-ray cancellation, retained physical
re-registration/repeated Init and shared scripted/follow eye. Source-byte guards,
port implementation and unresolved integration gates remain separate.
- `checkpoint/collision-grid-traversal.md`, `collision-contact-callbacks.md`,
`collision-body-probe.md`, `collision-integration-review.md`: REA/static grid,
contact material linkage/landing/friction and seven dispatcher/ten ordinary-body
component observations. Managed dispatcher is isolated; live capsule remains.
- `checkpoint/collision-body-composition-source.md`, `collision-body-implementation.md`,
`collision-body-implementation-review.md`: exact source phase/radius guards,
ordinary body composition matching ten original references, VR04 static subset
and retained dynamic/special/transform boundaries. Radius100 changes support too.
- `save-format.md`: full supplied TSK layout, task query/assignment and activation gates. - `save-format.md`: full supplied TSK layout, task query/assignment and activation gates.
- `analysis/lab-progression.md`: CAM/MCA/AI dispatch, original lab chain and skip/camera formulas. - `analysis/lab-progression.md`: CAM/MCA/AI dispatch, original lab chain and skip/camera formulas.
- `analysis/scene-entities.md`: exact entity-resource preparation and contact/sprite evidence. - `analysis/scene-entities.md`: exact entity-resource preparation and contact/sprite evidence.
+47 -3
View File
@@ -46,7 +46,34 @@ compile, runtime and original-fidelity verification are separate.
## Immediate continuation ## Immediate continuation
**Direction changed: pause feature expansion for the architecture checkpoint.** **Current direction: user-requested gameplay gadgets; collision work parked.**
Preserve35a2a66 body implementation,0272f7b release notes and baseline69d0187.
Recover/implement original gadget selection/use with local REA and original art;
extend the existing shrink-ray/jetpack device first where source contracts permit.
Current investigations own named files in docs/gameplay/, with runtime integration
owned by primary. Remaining special/dynamic collision and camera gates below are
the resume backlog, not prerequisites imposed on this user-directed gadget work.
- [x] Recover original gadget group0 selection, mode/display separation, ownership,
practice destinations and exact UI resources with local REA evidence.
- [x] Implement widescreen gadget screen, strict pointer regions, Tab/Space latch,
selection/input capture and direct Practice entry.
- [x] Implement owned default ray, original quantized target heading/obstruction,
texture phases, half opacity and tested alpha/additive Vulkan materials.
- [x] Render actual VR04 soldiers with original WALK/SHRINK morph, source timer,
authored-mode restoration and persistent ordinary10-point score callback.
- [x] Managed/source/GPU checks and native Linux menu/ray input fixtures.
- [x] Rebuild clean7b5230c Linux/Windows gadget packages, verify54 canvases/new
manifests in both, and run standalone Linux menu/ray fixtures from /tmp.
- [ ] Other special gadget effects and equip cleanup, energy-warning audio,
enemy AI/reaction consumers and original/native Windows comparison.
Details: [first gadget slice](gameplay/gadgets-implementation.md). Investigators
have returned all file ownership to primary. Complete final regression, native
Linux input and release checks pass; the remaining gadget effects are the next
gameplay backlog. Native Windows gadget verification remains open.
**Prior direction: architecture checkpoint and evidence-led implementation.**
Read `checkpoint/README.md`, `coverage.md` and `implementation-plan.md`. Preserved Read `checkpoint/README.md`, `coverage.md` and `implementation-plan.md`. Preserved
baseline69d0187 remains the testing tool. The loop/motion, script/state and baseline69d0187 remains the testing tool. The loop/motion, script/state and
camera/audio/UI investigations document the original lab→VR04→lab→outside route. camera/audio/UI investigations document the original lab→VR04→lab→outside route.
@@ -79,8 +106,25 @@ plan in verified chunks. Earlier priorities below are a backlog.
player-transform synchronization; managed/GPU/native Linux checks. player-transform synchronization; managed/GPU/native Linux checks.
- [x] Local REA6.8.0/Ghidra12.1.4/full JDK21 launcher, selected native pseudocode - [x] Local REA6.8.0/Ghidra12.1.4/full JDK21 launcher, selected native pseudocode
Evidence/snapshot export; client MCP configuration unchanged. See rea.md. Evidence/snapshot export; client MCP configuration unchanged. See rea.md.
- [ ] Next: full Jimmy/base wrapper and body registration/helper timing; C4 support/ - [x] C4 bounded sphere/triangle kernel recovered with REA and isolated original
response/root and shared viewport/DEFAULT handoff. C6 source channel allocation/ component references; explicit managed kernel and regressions added. Live adapter
replacement remains gated on traversal, callbacks, support and friction.
- [x] Root+150 upward query/bounce/mode1 cancellation traced and integrated for
the three route scenes, independently of raw control and camera debug switch.
- [x] Retained physical re-registration/repeated Init chain and shared camera-eye
handoff documented with byte guards and retained REA successes/provider gaps.
- [x] C4 static grid/retry dispatcher recovered and isolated managed component
compared against seven original fixtures; route material IDs and metadata gate.
- [x] Contact/landing/published-speed/friction contracts and actual special material
coverage recovered with REA. Ten isolated original body fixtures completed.
- [x] C4 ordinary body composition matches ten numeric references; VR04 uses the
recovered static subset with source radius/support/friction and published speed.
Twenty managed groups and native/headless powered-flight replays pass.
- [ ] Next: C4 original dynamic actor/pair eligibility and shared reclip context;
special160/164/FENCE/LADDER contact policies before lab/outside replacement;
full Jimmy/base wrapper/helper traversal and shared viewport/DEFAULT handoff.
Physical re-registration chain is recovered; full implementation/order remains.
C6 source channel allocation/
clock/banks remains separate. Fire's missing Ghidra procedure definition is an clock/banks remains separate. Fire's missing Ghidra procedure definition is an
analysis limitation; its immutable source-byte contract is already guarded. analysis limitation; its immutable source-byte contract is already guarded.
+11 -1
View File
@@ -13,6 +13,8 @@ for rid in linux-x64 win-x64; do
cp -a artifacts/extracted/animations/. "$out/scenes/animations/" cp -a artifacts/extracted/animations/. "$out/scenes/animations/"
cp -a artifacts/extracted/actors/. "$out/scenes/actors/" cp -a artifacts/extracted/actors/. "$out/scenes/actors/"
cp -a artifacts/extracted/ui/. "$out/scenes/ui/" cp -a artifacts/extracted/ui/. "$out/scenes/ui/"
mkdir -p "$out/scenes/gadgets"
cp -a artifacts/extracted/gadgets/. "$out/scenes/gadgets/"
mkdir -p "$out/scenes/effects" mkdir -p "$out/scenes/effects"
cp -a artifacts/extracted/effects/. "$out/scenes/effects/" cp -a artifacts/extracted/effects/. "$out/scenes/effects/"
cp artifacts/extracted/scene-catalog.json "$out/scenes/scene-catalog.json" cp artifacts/extracted/scene-catalog.json "$out/scenes/scene-catalog.json"
@@ -37,7 +39,7 @@ for rid in linux-x64 win-x64; do
printf 'packaged_utc=%s\n' "$(date -u +%FT%TZ)" printf 'packaged_utc=%s\n' "$(date -u +%FT%TZ)"
} > "$out/BUILD-INFO.txt" } > "$out/BUILD-INFO.txt"
cat > "$out/README.md" <<'NOTES' cat > "$out/README.md" <<'NOTES'
# Neutron lab story and jet pack checkpoint # Neutron lab story, gadgets and jet pack checkpoint
Linux: run ./launch-scene.sh. Windows: run launch-scene.cmd. Linux: run ./launch-scene.sh. Windows: run launch-scene.cmd.
Append --headless --frames 2 to render without a window, or --screenshot lab.ppm Append --headless --frames 2 to render without a window, or --screenshot lab.ppm
@@ -62,6 +64,12 @@ Level changes retain the window, fullscreen and size. HUD/debug UI scales unifor
on widescreen; --width 1920 --height 1080 sets initial window/offscreen dimensions. on widescreen; --width 1920 --height 1080 sets initial window/offscreen dimensions.
C pauses into inspection and resumes the chase camera. F11 fullscreen, Escape quit. C pauses into inspection and resumes the chase camera. F11 fullscreen, Escape quit.
Inspection: arrows/WASD orbit, +/- zoom, 1 idle, 2 run, 3 jump, 4 scratch preview. Inspection: arrows/WASD orbit, +/- zoom, 1 idle, 2 run, 3 jump, 4 scratch preview.
Tab/Space opens the original gadget screen (first unequips a special gadget).
Point with mouse/arrows; Enter/Ctrl or a mouse button selects; Escape/Return closes.
Practice Mode plus an owned gadget opens its tutorial. The combined shrink-ray/
jetpack pickup fires on Enter/Ctrl/left mouse and bursts on jump. Original Yokian
soldiers support the shrink morph,30-second restoration and10-point reward.
Other gadget effects and full enemy AI/combat remain incomplete.
Append --inspect to start directly in the old scene inspector. Append --inspect to start directly in the old scene inspector.
The default runs the recovered lab camera/speech sequence; Escape/Space skips The default runs the recovered lab camera/speech sequence; Escape/Space skips
its actions and restores control. --skip-intro starts with control; --mute disables its actions and restores control. --skip-intro starts with control; --mute disables
@@ -73,6 +81,8 @@ Tutorial RETURN restores the departure position and suppresses the lab intro.
Original actor/model/sprite props, common patrol, buttons/moving bars, lab task Original actor/model/sprite props, common patrol, buttons/moving bars, lab task
route, objectives, practice flow and checkpoint CLI are integrated. Collision, route, objectives, practice flow and checkpoint CLI are integrated. Collision,
60Hz cadence, pivots, rendering states and animation timing remain provisional. 60Hz cadence, pivots, rendering states and animation timing remain provisional.
VR04 now uses recovered static body response, support and friction. Lab/outside
retain the capsule pending special contact and dynamic collision recovery.
Full combat, AI, progression, menus and runtime saves remain incomplete. The user Full combat, AI, progression, menus and runtime saves remain incomplete. The user
confirms lab/tutorial/lab/outside and that their corrected Windows build works; confirms lab/tutorial/lab/outside and that their corrected Windows build works;
comprehensive native Windows input/physics/audio/driver validation remains pending. comprehensive native Windows input/physics/audio/driver validation remains pending.
+10
View File
@@ -9,6 +9,12 @@ dotnet run --project tests/GamePort.MovementTests -- ../Original
dotnet run --project tests/GamePort.DirectorTests -- ../Original dotnet run --project tests/GamePort.DirectorTests -- ../Original
dotnet run --project tests/GamePort.PatrolTests -- ../Original dotnet run --project tests/GamePort.PatrolTests -- ../Original
dotnet run --project tests/GamePort.SupportTests -- ../Original dotnet run --project tests/GamePort.SupportTests -- ../Original
dotnet run --project tests/GamePort.SphereResponseTests
dotnet run --project tests/GamePort.StaticCollisionTests
dotnet run --project tests/GamePort.BodyPhysicsTests
dotnet run --project tests/GamePort.GadgetTests
dotnet run --project tests/GamePort.HeadingTests
dotnet run --project tests/GamePort.BlendTests
dotnet run --project tests/GamePort.CameraRayTests dotnet run --project tests/GamePort.CameraRayTests
dotnet run --project tests/GamePort.InteractionTests -- ../Original dotnet run --project tests/GamePort.InteractionTests -- ../Original
dotnet run --project tests/GamePort.CheckpointTests -- ../Original dotnet run --project tests/GamePort.CheckpointTests -- ../Original
@@ -36,6 +42,7 @@ dotnet run --no-build -- --headless --story --smoke-practice-prompt --screenshot
dotnet run --no-build -- --headless --story --smoke-practice-transition dotnet run --no-build -- --headless --story --smoke-practice-transition
dotnet run --no-build -- --headless --smoke-practice-return --screenshot artifacts/test-practice-return.ppm dotnet run --no-build -- --headless --smoke-practice-return --screenshot artifacts/test-practice-return.ppm
dotnet run --no-build -- --headless --debug-menu --screenshot artifacts/test-debug-menu.ppm dotnet run --no-build -- --headless --debug-menu --screenshot artifacts/test-debug-menu.ppm
dotnet run --no-build -- --headless --skip-intro --gadget-menu --width 1920 --height 1080 --screenshot artifacts/test-gadget-menu.ppm
dotnet run --no-build -- --headless --debug-page player --noclip --width 1920 --height 1080 --screenshot artifacts/test-debug-player.ppm dotnet run --no-build -- --headless --debug-page player --noclip --width 1920 --height 1080 --screenshot artifacts/test-debug-player.ppm
dotnet run --no-build -- --headless --debug-page systems --width 2560 --height 1080 --screenshot artifacts/test-debug-systems.ppm dotnet run --no-build -- --headless --debug-page systems --width 2560 --height 1080 --screenshot artifacts/test-debug-systems.ppm
dotnet run --no-build -- --headless --debug-overlay --frames 2 --screenshot artifacts/test-debug-overlay.ppm dotnet run --no-build -- --headless --debug-overlay --frames 2 --screenshot artifacts/test-debug-overlay.ppm
@@ -45,6 +52,7 @@ dotnet run --no-build -- --headless --smoke-control-phases
dotnet run --no-build -- --headless --smoke-objective-panel --story-time 1 --screenshot artifacts/test-objective-visible.ppm dotnet run --no-build -- --headless --smoke-objective-panel --story-time 1 --screenshot artifacts/test-objective-visible.ppm
dotnet run --no-build -- --headless --smoke-objective-panel --story-time 9 --screenshot artifacts/test-objective-hidden.ppm dotnet run --no-build -- --headless --smoke-objective-panel --story-time 9 --screenshot artifacts/test-objective-hidden.ppm
dotnet run --no-build -- --headless --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-jetpack --screenshot artifacts/test-jetpack.ppm dotnet run --no-build -- --headless --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-jetpack --screenshot artifacts/test-jetpack.ppm
dotnet run --no-build -- --headless --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-shrink-ray --screenshot artifacts/test-shrink-ray.ppm
dotnet run --no-build -- --headless --skip-intro --write-save artifacts/test-checkpoint.tsk dotnet run --no-build -- --headless --skip-intro --write-save artifacts/test-checkpoint.tsk
dotnet run --no-build -- --headless --load-save artifacts/test-checkpoint.tsk --skip-intro dotnet run --no-build -- --headless --load-save artifacts/test-checkpoint.tsk --skip-intro
dotnet run --no-build -- --headless --story --scene artifacts/extracted/VR01/scene.json --level gam/VR01.gam --smoke-transition --skip-intro dotnet run --no-build -- --headless --story --scene artifacts/extracted/VR01/scene.json --level gam/VR01.gam --smoke-transition --skip-intro
@@ -61,6 +69,8 @@ SDL_AUDIODRIVER=dummy dotnet run --no-build -- --scene-audio-smoke artifacts/ext
SDL_AUDIODRIVER=dummy dotnet run --no-build -- --cutscene-audio-smoke artifacts/extracted/level1b/entities/entities.json SDL_AUDIODRIVER=dummy dotnet run --no-build -- --cutscene-audio-smoke artifacts/extracted/level1b/entities/entities.json
python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json
if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then
dotnet run --no-build -- --smoke-gadget-menu --width 1920 --height 1080 --screenshot artifacts/test-gadget-menu-window.ppm
dotnet run --no-build -- --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-shrink-ray --screenshot artifacts/test-shrink-ray-window.ppm
dotnet run --no-build -- --smoke-debug-tools dotnet run --no-build -- --smoke-debug-tools
dotnet run --no-build -- --smoke-window-transitions dotnet run --no-build -- --smoke-window-transitions
dotnet run --no-build -- --smoke-debug-overlay --screenshot artifacts/test-live-debug-window.ppm dotnet run --no-build -- --smoke-debug-overlay --screenshot artifacts/test-live-debug-window.ppm
@@ -0,0 +1,84 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Original screens.omt gadget art in the existing uniformly scaled UI viewport.</summary>
public sealed class GadgetMenuOverlay
{
private sealed record Quad(int Vertex, uint FirstIndex, uint Width, uint Height);
private readonly Dictionary<int, Quad> quads = [];
public Mesh Mesh { get; }
public GadgetMenuOverlay(Mesh combined, string manifest)
{
var full = Path.GetFullPath(manifest);
if (new FileInfo(full).Length > 128 * 1024) throw new InvalidDataException("Gadget manifest exceeds limit");
var directory = Path.GetDirectoryName(full)!;
using var document = JsonDocument.Parse(File.ReadAllBytes(full), new JsonDocumentOptions { MaxDepth = 12 });
var root = document.RootElement;
if (root.GetProperty("schema").GetInt32() != 1 || root.GetProperty("referenceWidth").GetInt32() != 640
|| root.GetProperty("referenceHeight").GetInt32() != 480)
throw new InvalidDataException("Unsupported gadget resource format");
var entries = root.GetProperty("textures");
if (entries.GetArrayLength() != 54) throw new InvalidDataException("Expected54 original gadget canvases");
var vertices = combined.Vertices.ToList();
var indices = combined.Indices.ToList();
var draws = combined.Draws.ToList();
if (!combined.HasExplicitDraws && draws.Count == 0 && indices.Count != 0)
draws.Add(new(0, (uint)indices.Count, -1));
var textures = new Dictionary<int, PngImage>(combined.Textures);
long total = 0;
foreach (var entry in entries.EnumerateArray())
{
var id = entry.GetProperty("id").GetInt32();
var width = entry.GetProperty("width").GetUInt32();
var height = entry.GetProperty("height").GetUInt32();
if (width is 0 or > 640 || height is 0 or > 480) throw new InvalidDataException("Invalid gadget canvas dimensions");
var path = Path.GetFullPath(Path.Combine(directory, entry.GetProperty("path").GetString()!));
if (!path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal))
throw new InvalidDataException("Gadget canvas escapes prepared directory");
var bytes = checked((long)width * height * 4);
total += bytes;
if (total > 16 * 1024 * 1024 || new FileInfo(path).Length != bytes)
throw new InvalidDataException("Invalid gadget canvas pixel count");
var texture = int.MinValue;
while (textures.ContainsKey(texture)) texture++;
textures.Add(texture, new(width, height, File.ReadAllBytes(path)));
if (!quads.TryAdd(id, new(vertices.Count, (uint)indices.Count, width, height)))
throw new InvalidDataException("Duplicate gadget canvas");
var first = (uint)vertices.Count;
vertices.AddRange([new(Vector3.Zero, new(0,0), Vector3.One), new(Vector3.Zero, new(1,0), Vector3.One),
new(Vector3.Zero, new(1,1), Vector3.One), new(Vector3.Zero, new(0,1), Vector3.One)]);
indices.AddRange([first, first + 1, first + 2, first, first + 2, first + 3]);
draws.Add(new((uint)indices.Count - 6, 6, texture) { ScreenSpace = true, Visible = false });
}
Mesh = new(vertices.ToArray(), indices.ToArray()) { Draws = draws.ToArray(), HasExplicitDraws = true,
Textures = textures, CollisionPolygons = combined.CollisionPolygons,
HasCollisionMaterialIds = combined.HasCollisionMaterialIds };
}
public void Update(Mesh destination, IReadOnlyList<GadgetCanvas> visible, uint width, uint height)
{
if (destination.Vertices.Length < Mesh.Vertices.Length || visible.Count > quads.Count)
throw new ArgumentException("Destination omits gadget overlay ranges");
foreach (var quad in quads.Values) Draw(quad).Visible = false;
var viewport = new UiViewport(width, height);
foreach (var canvas in visible)
{
if (!quads.TryGetValue(canvas.Id, out var quad)) throw new InvalidDataException("Unprepared gadget canvas");
var draw = Draw(quad);
if (draw.Visible) throw new ArgumentException("Gadget canvas occurs more than once");
draw.Visible = true;
var point = canvas.Position + viewport.CenterOffset;
destination.Vertices[quad.Vertex].Position = viewport.ToNdc(point);
destination.Vertices[quad.Vertex + 1].Position = viewport.ToNdc(point + new Vector2(quad.Width, 0));
destination.Vertices[quad.Vertex + 2].Position = viewport.ToNdc(point + new Vector2(quad.Width, quad.Height));
destination.Vertices[quad.Vertex + 3].Position = viewport.ToNdc(point + new Vector2(0, quad.Height));
}
MeshDraw Draw(Quad quad) => destination.Draws.FirstOrDefault(d => d.FirstIndex == quad.FirstIndex
&& d.IndexCount == 6 && d.ScreenSpace) ?? throw new ArgumentException("Destination omits gadget draws");
}
}
@@ -47,14 +47,14 @@ public sealed class PreviewAnimationLibrary
if (ReferenceEquals(clip, Current)) Name = label; if (ReferenceEquals(clip, Current)) Name = label;
} }
foreach (var (pose, folder) in new[] { (PlayerPose.Idle, "jimstop"), (PlayerPose.Run, "jimrun"), foreach (var (pose, folder) in new[] { (PlayerPose.Idle, "jimstop"), (PlayerPose.Run, "jimrun"),
(PlayerPose.Backpedal, "jimbackpedal"), (PlayerPose.Jump, "jimjump"), (PlayerPose.Fall, "jimfall"), (PlayerPose.Fly, "jimfly") }) (PlayerPose.Backpedal, "jimbackpedal"), (PlayerPose.Jump, "jimjump"), (PlayerPose.Fall, "jimfall"), (PlayerPose.Fly, "jimfly"), (PlayerPose.Shoot, "jimshoot") })
{ {
var path = Path.Combine(parent, folder, "animation.json"); var path = Path.Combine(parent, folder, "animation.json");
if (!File.Exists(path)) continue; if (!File.Exists(path)) continue;
movement[pose] = Load(path); movement[pose] = Load(path);
} }
foreach (var (action, folder) in new[] { ("STOP", "jimstop"), ("TALK", "jimtalk"), ("RUN", "jimrun"), foreach (var (action, folder) in new[] { ("STOP", "jimstop"), ("TALK", "jimtalk"), ("RUN", "jimrun"),
("JUMP", "jimjump"), ("FALL", "jimfall"), ("SCRATCH", "jimscratch"), ("FLY", "jimfly") }) ("JUMP", "jimjump"), ("FALL", "jimfall"), ("SCRATCH", "jimscratch"), ("FLY", "jimfly"), ("SHOOT", "jimshoot") })
{ {
var path = Path.Combine(parent, folder, "animation.json"); var path = Path.Combine(parent, folder, "animation.json");
if (File.Exists(path)) actions[action] = Load(path); if (File.Exists(path)) actions[action] = Load(path);
@@ -0,0 +1,40 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Owned original RAY mesh and three texture phases; material alpha0.5, additive default.</summary>
public sealed class ShrinkRayVisuals
{
private readonly MorphAnimation clip;
private readonly int offset;
private readonly MeshDraw[] phases;
public Mesh Mesh { get; }
public ShrinkRayVisuals(Mesh combined, string preparedRoot, string originalRoot)
{
clip = new(Path.Combine(preparedRoot,"actors/shrink-ray/ray/animation.json"));
offset = combined.Vertices.Length;
var id = int.MinValue + 12000;
while (combined.Textures.ContainsKey(id)) id++;
var mesh = clip.AppendTo(combined,id);
phases = new MeshDraw[3]; phases[0] = mesh.Draws[^1];
for (var phase = 1; phase < phases.Length; phase++)
{
do id++; while (mesh.Textures.ContainsKey(id));
mesh.Textures.Add(id,PngImage.Load(AssetPath.Resolve(originalRoot,$"png/ray000{phase}.png")));
phases[phase] = new(phases[0].FirstIndex,phases[0].IndexCount,id);
}
foreach (var draw in phases) { draw.Visible = false; draw.Opacity = .5f; draw.Blend = MeshBlend.Additive; }
Mesh = mesh with {Draws=[.. mesh.Draws,phases[1],phases[2]]};
}
public void Update(Mesh destination, ShrinkRay ray, double seconds)
{
for (var phase = 0; phase < phases.Length; phase++) phases[phase].Visible = ray.Visible && ray.TexturePhase == phase;
if (!ray.Visible) return;
var model = Matrix4x4.CreateRotationY(-ray.Yaw * MathF.PI / 180) * Matrix4x4.CreateTranslation(ray.Position);
clip.Sample(seconds,destination.Vertices.AsSpan(offset,clip.Base.Vertices.Length),model);
}
}
@@ -0,0 +1,73 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Original3SOL WALK/SHRINK morphs. No combat or patrol AI is inferred.</summary>
public sealed class ShrinkSoldierVisuals
{
private sealed class Visual(ShrinkSoldier soldier, int offset, MeshDraw draw)
{
public ShrinkSoldier Soldier = soldier;
public int Offset = offset;
public MeshDraw Draw = draw;
public bool Shrunk;
public double Time;
}
private readonly List<Visual> visuals = [];
private readonly MorphAnimation walk, shrink;
public Mesh Mesh { get; }
public ShrinkSoldierVisuals(Mesh combined, IReadOnlyList<ShrinkSoldier> soldiers, string preparedRoot, string level)
{
var vr = level.Length == 4 && level.StartsWith("VR0",StringComparison.Ordinal) && level[3] is >= '1' and <= '8';
var family = Path.Combine(preparedRoot,"actors",vr ? "soldier-vr" : "soldier");
walk = new(Path.Combine(family,"soldwalk/animation.json"));
shrink = new(Path.Combine(family,"soldshrink/animation.json"));
if (walk.Base.Vertices.Length != shrink.Base.Vertices.Length || !walk.Base.Indices.SequenceEqual(shrink.Base.Indices))
throw new InvalidDataException("Original soldier morph topology differs");
foreach (var soldier in soldiers)
{
var offset = combined.Vertices.Length;
var id = int.MinValue + 13000 + visuals.Count;
while (combined.Textures.ContainsKey(id)) id++;
combined = walk.AppendTo(combined,id);
visuals.Add(new(soldier,offset,combined.Draws[^1]));
}
Mesh = combined; Update(0,Mesh);
}
public void Update(double seconds, Mesh destination)
{
foreach (var visual in visuals)
{
if (visual.Shrunk != visual.Soldier.Shrunk)
{
//False selector preserves frame ordinal; within-frame clock is
//an explicit port approximation. WALK(true) restarts at frame0.
var ordinal = (int)Math.Floor(visual.Time / walk.SampleInterval) % walk.FrameCount;
visual.Time = visual.Soldier.Shrunk ? Math.Min(ordinal,shrink.FrameCount - 1) * shrink.SampleInterval : 0;
visual.Shrunk = visual.Soldier.Shrunk;
}
visual.Time += seconds;
var actor = visual.Soldier.Actor;
var rotation = Matrix4x4.CreateRotationX(actor.Rotation.X * MathF.PI / 180)
* Matrix4x4.CreateRotationY(-actor.Rotation.Y * MathF.PI / 180)
* Matrix4x4.CreateRotationZ(actor.Rotation.Z * MathF.PI / 180);
var clip = visual.Shrunk ? shrink : walk;
clip.Sample(visual.Time,destination.Vertices.AsSpan(visual.Offset,clip.Base.Vertices.Length),
rotation * Matrix4x4.CreateTranslation(actor.Position),!visual.Shrunk);
visual.Draw.Visible = actor.Visible;
}
}
public float RenderedHeight(string tag, Mesh destination)
{
var visual = visuals.Single(v => v.Soldier.Actor.Tag == tag);
var vertices = destination.Vertices.AsSpan(visual.Offset,walk.Base.Vertices.Length);
var low = float.PositiveInfinity; var high = float.NegativeInfinity;
foreach (var vertex in vertices) { low = MathF.Min(low,vertex.Position.Y); high = MathF.Max(high,vertex.Position.Y); }
return high - low;
}
}
+14 -3
View File
@@ -15,6 +15,7 @@ public struct MeshVertex(Vector3 position, Vector2 uv, Vector3 color)
public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices) public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
{ {
public MeshPolygonSource[] CollisionPolygons { get; init; } = []; public MeshPolygonSource[] CollisionPolygons { get; init; } = [];
public bool HasCollisionMaterialIds { get; init; }
public MeshDraw[] Draws { get; init; } = []; public MeshDraw[] Draws { get; init; } = [];
public bool HasExplicitDraws { get; init; } public bool HasExplicitDraws { get; init; }
public Dictionary<int,PngImage> Textures { get; init; } = []; public Dictionary<int,PngImage> Textures { get; init; } = [];
@@ -55,7 +56,9 @@ public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
? polygonList.EnumerateArray().Select(p => new MeshPolygonSource(p.GetProperty("shapeId").GetInt32(), ? polygonList.EnumerateArray().Select(p => new MeshPolygonSource(p.GetProperty("shapeId").GetInt32(),
p.GetProperty("polygonIndex").GetInt32(), p.GetProperty("polygonIndex").GetInt32(),
new Vector3(p.GetProperty("normal")[0].GetSingle(), p.GetProperty("normal")[1].GetSingle(), p.GetProperty("normal")[2].GetSingle()), new Vector3(p.GetProperty("normal")[0].GetSingle(), p.GetProperty("normal")[1].GetSingle(), p.GetProperty("normal")[2].GetSingle()),
p.GetProperty("materialName").GetString(), shapeNames.GetValueOrDefault(p.GetProperty("shapeId").GetInt32()))).ToArray() : []; p.GetProperty("materialName").GetString(), shapeNames.GetValueOrDefault(p.GetProperty("shapeId").GetInt32()),
p.TryGetProperty("materialId", out var materialId) && materialId.ValueKind == JsonValueKind.Number
? materialId.GetInt32() : null)).ToArray() : [];
if (collisionPolygons.Length != 0 && (collisionPolygons.Length != indices.Length / 3 if (collisionPolygons.Length != 0 && (collisionPolygons.Length != indices.Length / 3
|| collisionPolygons.Any(p => !float.IsFinite(p.Normal.X + p.Normal.Y + p.Normal.Z)))) || collisionPolygons.Any(p => !float.IsFinite(p.Normal.X + p.Normal.Y + p.Normal.Z))))
throw new InvalidDataException("Invalid source collision polygon metadata"); throw new InvalidDataException("Invalid source collision polygon metadata");
@@ -92,17 +95,25 @@ public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
for(var i=first;i<first+count;i++)vertices[indices[i]].Color=material.Item2; for(var i=first;i<first+count;i++)vertices[indices[i]].Color=material.Item2;
draws.Add(new MeshDraw(first,count,material.Item1)); draws.Add(new MeshDraw(first,count,material.Item1));
} }
return new Mesh(vertices, indices){Draws=draws.ToArray(),HasExplicitDraws=true,Textures=textures,CollisionPolygons=collisionPolygons}; return new Mesh(vertices, indices){Draws=draws.ToArray(),HasExplicitDraws=true,Textures=textures,CollisionPolygons=collisionPolygons,
HasCollisionMaterialIds=root.TryGetProperty("collisionPolygons", out var sourcePolygons)
&& sourcePolygons.EnumerateArray().All(p => p.TryGetProperty("materialId", out var id)
&& id.ValueKind is JsonValueKind.Number or JsonValueKind.Null)};
} }
} }
public readonly record struct MeshPolygonSource(int ShapeId, int PolygonIndex, Vector3 Normal, string? MaterialName, string? ShapeName = null) public readonly record struct MeshPolygonSource(int ShapeId, int PolygonIndex, Vector3 Normal, string? MaterialName,
string? ShapeName = null, int? MaterialId = null)
{ {
public bool TerrainCollision => ShapeName?.StartsWith("nc", StringComparison.OrdinalIgnoreCase) != true; public bool TerrainCollision => ShapeName?.StartsWith("nc", StringComparison.OrdinalIgnoreCase) != true;
} }
public enum MeshBlend { Opaque, Alpha, Additive }
public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId) public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId)
{ {
public bool Visible { get; set; } = true; public bool Visible { get; set; } = true;
public bool ScreenSpace { get; init; } public bool ScreenSpace { get; init; }
public float Opacity { get; set; } = 1;
public MeshBlend Blend { get; set; } = MeshBlend.Opaque;
} }
+4 -3
View File
@@ -10,6 +10,7 @@ public sealed class MorphAnimation
public PngImage Texture { get; } public PngImage Texture { get; }
public double SampleInterval { get; } public double SampleInterval { get; }
public bool HasVertexMotion { get; } public bool HasVertexMotion { get; }
public int FrameCount => frames.Length;
private readonly Mesh[] frames; private readonly Mesh[] frames;
public MorphAnimation(string manifestPath) public MorphAnimation(string manifestPath)
@@ -54,15 +55,15 @@ public sealed class MorphAnimation
Texture = new PngImage(width, height, rgba); Texture = new PngImage(width, height, rgba);
} }
public void Sample(double seconds, Span<MeshVertex> destination, Matrix4x4 model) public void Sample(double seconds, Span<MeshVertex> destination, Matrix4x4 model, bool loop = true)
{ {
if (!double.IsFinite(seconds) || seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds)); if (!double.IsFinite(seconds) || seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));
if (destination.Length != Base.Vertices.Length) throw new ArgumentException("Morph target size differs"); if (destination.Length != Base.Vertices.Length) throw new ArgumentException("Morph target size differs");
// Linear interpolation is recovered from DLL 0x10002F9A. Loop closure // Linear interpolation is recovered from DLL 0x10002F9A. Loop closure
// and gameplay-specific speed remain preview policies until recovered. // and gameplay-specific speed remain preview policies until recovered.
var frame = seconds / SampleInterval; var frame = seconds / SampleInterval;
var first = (int)(Math.Floor(frame) % frames.Length); var first = loop ? (int)(Math.Floor(frame) % frames.Length) : (int)Math.Min(Math.Floor(frame), frames.Length - 1);
var next = (first + 1) % frames.Length; var next = loop ? (first + 1) % frames.Length : Math.Min(first + 1, frames.Length - 1);
var t = (float)(frame - Math.Floor(frame)); var t = (float)(frame - Math.Floor(frame));
for (var i = 0; i < destination.Length; i++) for (var i = 0; i < destination.Length; i++)
{ {
+2
View File
@@ -14,6 +14,7 @@ public sealed class SceneAudio : IDisposable
public bool MusicMuted { get; private set; } public bool MusicMuted { get; private set; }
public bool SpeechMuted { get; private set; } public bool SpeechMuted { get; private set; }
public bool EffectsMuted { get; private set; } public bool EffectsMuted { get; private set; }
public bool GameplayEffectsEnabled { get; set; } = true;
public int EffectCount => effects.Count; public int EffectCount => effects.Count;
public int LoopCount => loops.Count; public int LoopCount => loops.Count;
public int QueuedEffectBytes => effects.Sum(effect => effect.QueuedBytes) + loops.Values.Sum(effect => effect.QueuedBytes); public int QueuedEffectBytes => effects.Sum(effect => effect.QueuedBytes) + loops.Values.Sum(effect => effect.QueuedBytes);
@@ -43,6 +44,7 @@ public sealed class SceneAudio : IDisposable
// and original channel/volume policy are separate unrecovered consumers. // and original channel/volume policy are separate unrecovered consumers.
public void Effect(int id, string? loopOwner = null) public void Effect(int id, string? loopOwner = null)
{ {
if (!GameplayEffectsEnabled) return;
var wave = resources.Wave("SoundEffects.omt", id) var wave = resources.Wave("SoundEffects.omt", id)
?? throw new FileNotFoundException($"Missing original default sound effect {id}"); ?? throw new FileNotFoundException($"Missing original default sound effect {id}");
if (loopOwner == null) effects.Add(new(wave.Path, paused: Paused, muted: EffectsMuted)); if (loopOwner == null) effects.Add(new(wave.Path, paused: Paused, muted: EffectsMuted));
+99
View File
@@ -0,0 +1,99 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct GadgetCanvas(int Id, Vector2 Position);
/// <summary>Bounded group0 gadget panel; source425870/425EF0/425B20/427370.</summary>
public sealed class GadgetScreen(SceneInventory inventory)
{
public static IReadOnlyList<Vector2> Positions { get; } = Array.AsReadOnly<Vector2>([new(12,182), new(158,182), new(12,327), new(157,327),
new(342,182), new(487,182), new(342,327), new(487,327)]);
private static readonly int[] idle = [52,46,47,48,49,50,51,45];
private Vector2 pointerOffset;
public bool Open { get; private set; }
public bool PracticeArmed { get; private set; }
public int Hovered { get; private set; } = -1;
public event Action<int>? PracticeRequested;
public event Action? Changed;
//UI display3 is the default shrink-ray/jetpack; source equipped word is-1.
public static int EquippedMode(int displaySelection) => displaySelection == 3 ? -1 : displaySelection;
public bool Toggle(bool permitted)
{
if (Open) { Close(); return true; }
if (!permitted) return false;
if (EquippedMode(inventory.SelectedGadget) != -1)
{
inventory.SelectGadget(-1); Changed?.Invoke(); return true;
}
Open = true; Hovered = -1; PracticeArmed = false; pointerOffset = Vector2.Zero; Changed?.Invoke(); return true;
}
public void Close()
{
if (!Open) return;
Open = false; Hovered = -1; PracticeArmed = false; pointerOffset = Vector2.Zero; Changed?.Invoke();
}
public Vector2 MovePointer(Vector2 point, Vector2 axis, float seconds)
{
if (!float.IsFinite(seconds) || seconds < 0 || seconds >= 1) throw new ArgumentOutOfRangeException(nameof(seconds));
if (!Open) return point;
//404080: accumulated source80*dt offsets; neutral clears each axis.
pointerOffset.X = axis.X > .5f ? pointerOffset.X + 80 * seconds
: axis.X < -.5f ? pointerOffset.X - 80 * seconds : 0;
pointerOffset.Y = axis.Y > .5f ? pointerOffset.Y + 80 * seconds
: axis.Y < -.5f ? pointerOffset.Y - 80 * seconds : 0;
return point + pointerOffset;
}
public bool PracticeAvailable(string level, int task) => task < 500
&& !(level.Length == 4 && level.StartsWith("VR0", StringComparison.Ordinal) && level[3] is >= '1' and <= '8');
public void Point(Vector2 point, string level, int task)
{
Hovered = -1;
if (!Open) return;
for (var i = 0; i < Positions.Count; i++)
if (inventory.State(0,i) is not (0 or 4) && Inside(point,Positions[i],141,141)) Hovered = i;
if (PracticeAvailable(level,task) && Inside(point,new(487,95),141,78)) Hovered = 9;
if (Inside(point,new(12,95),141,78)) Hovered = 10;
}
public bool Activate(string level, int task)
{
if (!Open) return false;
if (Hovered == 10) { Close(); return true; }
if (Hovered == 9 && PracticeAvailable(level,task))
{ PracticeArmed = !PracticeArmed; Changed?.Invoke(); return true; }
if (Hovered is < 0 or > 7 || inventory.State(0,Hovered) is 0 or 4) return false;
var item = Hovered;
var practice = PracticeArmed;
Close();
inventory.SelectGadget(item);
if (practice) PracticeRequested?.Invoke(item);
return true;
}
public GadgetCanvas[] Canvases(string level, int task)
{
if (!Open) return [];
List<GadgetCanvas> result = [new(20,Vector2.Zero)];
for (var i = 0; i < Positions.Count; i++)
{
//Known route states0/1/4. Other nonzero states retain an owned tile;
//their complete inherited visibility is not claimed recovered here.
if (inventory.State(0,i) is 0 or 4) continue;
result.Add(new(Hovered == i && inventory.State(0,i) != 3 ? 11+i : idle[i],Positions[i]));
}
result.Add(new(Hovered == 10 ? 181 : 182,new(12,95)));
if (PracticeAvailable(level,task))
result.Add(new(Hovered == 9 || PracticeArmed ? 179 : 180,new(487,95)));
return result.ToArray();
}
private static bool Inside(Vector2 point, Vector2 start, float width, float height) =>
point.X > start.X && point.X < start.X + width && point.Y > start.Y && point.Y < start.Y + height;
}
+76 -16
View File
@@ -4,12 +4,12 @@ using GamePort.Assets;
namespace GamePort.Game; namespace GamePort.Game;
public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump, public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump,
bool Rise = false, bool Descend = false, bool StrafeLeft = false, bool StrafeRight = false, bool Fast = false); bool Rise = false, bool Descend = false, bool StrafeLeft = false, bool StrafeRight = false, bool Fast = false, bool Fire = false);
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly } public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly, Shoot }
/// <summary> /// <summary>
/// Walking, airborne steering and jetpack checkpoint. Recovered arithmetic is described in /// Walking, airborne steering and jetpack checkpoint. Recovered arithmetic is described in
/// movement-checkpoint.md. Capsule, floor-derived pivot and 60Hz are port policies; /// movement-checkpoint.md. Legacy capsule, floor-derived pivot and60Hz are port policies;
/// original collision, intro, object interactions and animation timing remain open. /// original collision, intro, object interactions and animation timing remain open.
/// </summary> /// </summary>
public sealed class LabSimulation public sealed class LabSimulation
@@ -17,6 +17,8 @@ public sealed class LabSimulation
public const float BodyRadius = 24; // Provisional, not a recovered collider dimension. public const float BodyRadius = 24; // Provisional, not a recovered collider dimension.
private readonly SceneCollision collision; private readonly SceneCollision collision;
private readonly Func<Vector3, Vector3, SupportHit?>? cameraRay; private readonly Func<Vector3, Vector3, SupportHit?>? cameraRay;
private readonly Func<Vector3, Vector3, SupportHit?>? ceilingRay;
private readonly OriginalBodyPhysics? originalBody;
private readonly Vector3 sourceStart; private readonly Vector3 sourceStart;
private readonly float startYaw, modelMinimumY, rootHeight, startFloor; private readonly float startYaw, modelMinimumY, rootHeight, startFloor;
private float targetYaw, extraAirAcceleration, shadowDistance, lateralContribution; private float targetYaw, extraAirAcceleration, shadowDistance, lateralContribution;
@@ -33,8 +35,12 @@ public sealed class LabSimulation
public string LevelCode { get; set; } = "LV1B"; public string LevelCode { get; set; } = "LV1B";
public int GadgetMode { get; set; } = -1; public int GadgetMode { get; set; } = -1;
public float Energy { get; set; } = 20; public float Energy { get; set; } = 20;
//Source260/live15C serves both body collision and contact tests. The name
//predates source-body integration; burst100 is not an interaction-only size.
public float InteractionRadius { get; private set; } = 60; public float InteractionRadius { get; private set; } = 60;
public bool JetpackEffectVisible { get; private set; } public bool JetpackEffectVisible { get; private set; }
public Action<PlayerInput>? InputActions { get; set; }
public bool Shooting { get; private set; }
public float JetpackRemaining => jumpState.EffectRemaining; public float JetpackRemaining => jumpState.EffectRemaining;
public int JumpState => jumpState.JumpState; public int JumpState => jumpState.JumpState;
public float JumpHoldSeconds => jumpState.HoldSeconds; public float JumpHoldSeconds => jumpState.HoldSeconds;
@@ -49,17 +55,20 @@ public sealed class LabSimulation
public bool InputAfterPlayerUpdate { get; set; } public bool InputAfterPlayerUpdate { get; set; }
public float Yaw { get; private set; } public float Yaw { get; private set; }
public float Speed { get; private set; } public float Speed { get; private set; }
public float PublishedSpeed { get; private set; }
public bool UsesOriginalBody => originalBody != null;
public float TurnRate { get; private set; } public float TurnRate { get; private set; }
public bool Grounded { get; private set; } public bool Grounded { get; private set; }
public PlayerPose Pose => Noclip ? Velocity.LengthSquared() > 0 ? PlayerPose.Fly : PlayerPose.Idle public PlayerPose Pose => Noclip ? Velocity.LengthSquared() > 0 ? PlayerPose.Fly : PlayerPose.Idle
: pendingImpulse.Y > 0 ? PlayerPose.Jump : pendingImpulse.Y > 0 ? PlayerPose.Jump
: Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle : Grounded ? Shooting ? PlayerPose.Shoot : Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
: jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly : jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly
: !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall; : !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
public int Steps { get; private set; } public int Steps { get; private set; }
public int PhysicsSteps { get; private set; } public int PhysicsSteps { get; private set; }
public int ControllerSteps { get; private set; } public int ControllerSteps { get; private set; }
public int EffectSteps { get; private set; } public int EffectSteps { get; private set; }
public int CeilingHits { get; private set; }
public int Jumps { get; private set; } public int Jumps { get; private set; }
public int Landings { get; private set; } public int Landings { get; private set; }
public int WallHits { get; private set; } public int WallHits { get; private set; }
@@ -73,10 +82,14 @@ public sealed class LabSimulation
* Matrix4x4.CreateTranslation(Position - new Vector3(0, modelMinimumY, 0)); * Matrix4x4.CreateTranslation(Position - new Vector3(0, modelMinimumY, 0));
public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, float yaw, public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, float yaw,
Func<Vector3, Vector3, SupportHit?>? cameraRay = null) Func<Vector3, Vector3, SupportHit?>? cameraRay = null,
Func<Vector3, Vector3, SupportHit?>? ceilingRay = null,
OriginalStaticCollision? originalCollision = null)
{ {
this.collision = collision; this.collision = collision;
this.cameraRay = cameraRay; this.cameraRay = cameraRay;
this.ceilingRay = ceilingRay;
originalBody = originalCollision == null ? null : new OriginalBodyPhysics(originalCollision);
sourceStart = start; sourceStart = start;
startYaw = yaw; startYaw = yaw;
var bounds = standingPose.Bounds(); var bounds = standingPose.Bounds();
@@ -95,18 +108,19 @@ public sealed class LabSimulation
public void Reset() public void Reset()
{ {
var floor = collision.GroundHeight(sourceStart, 2500)!.Value; var floor = collision.GroundHeight(sourceStart, 2500)!.Value;
Position = new(sourceStart.X, floor + SceneCollision.Skin, sourceStart.Z); Position = new(sourceStart.X, floor + (UsesOriginalBody ? 0 : SceneCollision.Skin), sourceStart.Z);
Velocity = Vector3.Zero; Velocity = Vector3.Zero;
Yaw = targetYaw = startYaw; Yaw = targetYaw = startYaw;
Speed = TurnRate = extraAirAcceleration = shadowDistance = 0; Speed = PublishedSpeed = TurnRate = extraAirAcceleration = shadowDistance = 0;
lateralContribution = 0; pendingImpulse = Vector3.Zero; movementMode = 0; lateralContribution = 0; pendingImpulse = Vector3.Zero; movementMode = 0;
jumpState = default; jumpState = default;
forceFall = JetpackEffectVisible = false; forceFall = JetpackEffectVisible = false;
Shooting = false;
InteractionRadius = 60; Bursts = 0; InteractionRadius = 60; Bursts = 0;
Grounded = true; Grounded = true;
Noclip = HasNoclipEntry = false; Noclip = HasNoclipEntry = false;
Steps = Jumps = Landings = WallHits = 0; Steps = Jumps = Landings = WallHits = 0;
PhysicsSteps = ControllerSteps = EffectSteps = 0; PhysicsSteps = ControllerSteps = EffectSteps = CeilingHits = 0;
Travel = MaximumRise = 0; Travel = MaximumRise = 0;
CameraEye = DesiredEye().Eye; CameraEye = DesiredEye().Eye;
} }
@@ -155,10 +169,12 @@ public sealed class LabSimulation
// This reconstructs the player/input/fire partial order, not the full // This reconstructs the player/input/fire partial order, not the full
// scene registry, original cadence or original collision response. // scene registry, original cadence or original collision response.
StepPhysics(); StepPhysics();
//42469F..4246DC reasserts ordinary grounded radius before ownership
//checks. The scooter's separate radius160 policy remains unimplemented.
if (Grounded) InteractionRadius = 60;
if (controlled && !InputAfterPlayerUpdate) StepInput(input); if (controlled && !InputAfterPlayerUpdate) StepInput(input);
//42469F..4246DC reasserts ordinary grounded radius before ownership
//checks. Bubble mode0's separate radius160 policy remains unimplemented.
if (Grounded) InteractionRadius = 60;
//424BE0..424C34 runs this wrapper before437940's ownership gate.
StepCeiling();
if (controlled) StepPlayer(input); if (controlled) StepPlayer(input);
var effect = JetpackBurst.StepEffect(jumpState, Grounded, FixedStepClock.Step, Energy, LevelCode); var effect = JetpackBurst.StepEffect(jumpState, Grounded, FixedStepClock.Step, Energy, LevelCode);
jumpState = effect.State; Energy = effect.Energy; JetpackEffectVisible = effect.Visible; jumpState = effect.State; Energy = effect.Energy; JetpackEffectVisible = effect.Visible;
@@ -174,6 +190,22 @@ public sealed class LabSimulation
Speed = 0; Velocity = Vector3.Zero; Speed = 0; Velocity = Vector3.Zero;
} }
public void StopForPrimaryFire() => Speed = 0;
public void SetShooting(bool shooting) => Shooting = shooting;
private void StepCeiling()
{
if (Velocity.Y <= 0 || ceilingRay == null
|| ceilingRay(ActorRoot, ActorRoot + Vector3.UnitY * 150) == null) return;
Velocity = Velocity with { Y = (float)Math.Min(-Velocity.Y * .6, -85) };
CeilingHits++;
//425120 leaves hold, mode, pending impulse and acceleration intact.
//Full sound/selected-gadget cleanup callbacks remain a separate gap.
if (movementMode != 1) return;
jumpState = jumpState with { JumpState = 0, EffectRemaining = 0 };
forceFall = true;
}
/// <summary>Authored AI root/Euler writes. They do not reset body motion or /// <summary>Authored AI root/Euler writes. They do not reset body motion or
/// destination yaw61C; the full logical/render Euler model remains separate.</summary> /// destination yaw61C; the full logical/render Euler model remains separate.</summary>
public void ApplyAuthoredTransform(Vector3 root, float yaw) public void ApplyAuthoredTransform(Vector3 root, float yaw)
@@ -202,8 +234,9 @@ public sealed class LabSimulation
public void StopDebugMotion() public void StopDebugMotion()
{ {
Shooting = false;
Velocity = pendingImpulse = Vector3.Zero; Velocity = pendingImpulse = Vector3.Zero;
Speed = TurnRate = extraAirAcceleration = lateralContribution = 0; Speed = PublishedSpeed = TurnRate = extraAirAcceleration = lateralContribution = 0;
jumpState = default; movementMode = 0; forceFall = JetpackEffectVisible = false; jumpState = default; movementMode = 0; forceFall = JetpackEffectVisible = false;
targetYaw = Yaw; targetYaw = Yaw;
} }
@@ -259,6 +292,7 @@ public sealed class LabSimulation
targetYaw = Yaw; targetYaw = Yaw;
} }
StepCamera(); //438BC0/439900 input path owns follow; still provisional geometry/state. StepCamera(); //438BC0/439900 input path owns follow; still provisional geometry/state.
InputActions?.Invoke(input);
} }
private void StepPlayer(PlayerInput input) private void StepPlayer(PlayerInput input)
@@ -297,17 +331,24 @@ public sealed class LabSimulation
else if (air.Pose is JetpackPose.Jump or JetpackPose.Fly) forceFall = false; else if (air.Pose is JetpackPose.Jump or JetpackPose.Fly) forceFall = false;
if (air.StartGadget) Bursts++; if (air.StartGadget) Bursts++;
Velocity = velocity; // Produced body state is consumed by the next physics pass. Velocity = velocity; // Produced body state is consumed by the next physics pass.
PublishedSpeed = Speed; //437C22..437C2D: controller608 -> body160.
} }
private void StepPhysics() private void StepPhysics()
{ {
PhysicsSteps++; PhysicsSteps++;
const float dt = FixedStepClock.Step; const float dt = FixedStepClock.Step;
if (originalBody != null)
{
StepOriginalPhysics();
return;
}
var wasGrounded = Grounded; var wasGrounded = Grounded;
var velocity = Velocity; var velocity = Velocity;
// Keep the existing capsule/gravity adapter until C4 recovers Jimmy's // Keep the existing capsule/gravity adapter until C4 recovers Jimmy's
// pre-integration support/response. Source479DF7..479E54 can cancel // support/response. Source479DF7..479E54 cancels gravity and vertical
// gravity before a supported impulse; this adapter does not model that. // velocity when global geometry4F69E5 is disabled, not when grounded.
// This adapter does not model that separate source debug/global gate.
var displacement = RecoveredMotion.Integrate(ref velocity, ref pendingImpulse, var displacement = RecoveredMotion.Integrate(ref velocity, ref pendingImpulse,
Vector3.UnitY * extraAirAcceleration, RecoveredMotion.Gravity, dt); Vector3.UnitY * extraAirAcceleration, RecoveredMotion.Gravity, dt);
var before = Position; var before = Position;
@@ -326,7 +367,7 @@ public sealed class LabSimulation
} }
} }
Grounded = result.Grounded && velocity.Y <= 0; Grounded = result.Grounded && velocity.Y <= 0;
if (Grounded && velocity.Y < 0 || result.HitCeiling && velocity.Y > 0) velocity.Y = 0; if (Grounded && velocity.Y < 0 || result.HitCeiling && velocity.Y > 0 && ceilingRay == null) velocity.Y = 0;
if (Grounded) { extraAirAcceleration = 0; forceFall = false; } if (Grounded) { extraAirAcceleration = 0; forceFall = false; }
Velocity = velocity; Velocity = velocity;
if (!wasGrounded && Grounded) Landings++; if (!wasGrounded && Grounded) Landings++;
@@ -335,6 +376,25 @@ public sealed class LabSimulation
MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor); MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor);
} }
private void StepOriginalPhysics()
{
if (DynamicRootResolver != null)
throw new NotSupportedException("Original ordinary-body subset cannot use the provisional dynamic resolver");
var before = Position;
var result = originalBody!.Step(new(ActorRoot, Velocity, Vector3.UnitY * extraAirAcceleration,
pendingImpulse, Grounded, PublishedSpeed), FixedStepClock.Step, InteractionRadius);
Position = result.Body.Position - Vector3.UnitY * rootHeight;
Velocity = result.Body.Velocity;
pendingImpulse = result.Body.Impulse;
extraAirAcceleration = result.Body.Acceleration.Y;
Grounded = result.Body.Supported;
if (Grounded) forceFall = false;
if (result.Landing != null) Landings++;
if (result.Contact is { StoredNormal.Y: > -.7f }) WallHits++;
Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z));
MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor);
}
private void StepCamera() private void StepCamera()
{ {
const float dt = FixedStepClock.Step; const float dt = FixedStepClock.Step;
@@ -363,5 +423,5 @@ public sealed class LabSimulation
step is >= 80 and < 120, step is >= 60 and < 95, false, step < 180); step is >= 80 and < 120, step is >= 60 and < 95, false, step < 180);
public bool SmokePassed => Steps >= 240 && Travel > 50 && MaximumRise > 20 && Jumps > 0 && Landings > 0 && Grounded; public bool SmokePassed => Steps >= 240 && Travel > 50 && MaximumRise > 20 && Jumps > 0 && Landings > 0 && Grounded;
public string Report => $"Walk checkpoint: steps={Steps}, controller={ControllerSteps}, physics={PhysicsSteps}, effect={EffectSteps}, travel={Travel:F2}, jumps={Jumps}, landings={Landings}, max rise={MaximumRise:F2}, wall hits={WallHits}, grounded={Grounded}, feet={Position}."; public string Report => $"Walk checkpoint: steps={Steps}, controller={ControllerSteps}, physics={PhysicsSteps}, effect={EffectSteps}, travel={Travel:F2}, jumps={Jumps}, landings={Landings}, max rise={MaximumRise:F2}, wall hits={WallHits}, ceiling hits={CeilingHits}, grounded={Grounded}, feet={Position}, body={(UsesOriginalBody ? "source ordinary" : "provisional capsule")}.";
} }
+121
View File
@@ -0,0 +1,121 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct OrdinaryBodyState(Vector3 Position, Vector3 Velocity,
Vector3 Acceleration, Vector3 Impulse, bool Supported = false, float PublishedSpeed = 0,
Vector3 AngularVelocity = default, Vector3 Rotation = default);
public readonly record struct BodyLandingObservation(Vector3 Position, Vector3 Velocity,
Vector3 Acceleration, bool Supported);
public readonly record struct OrdinaryBodyStep(OrdinaryBodyState Body, Vector3 PreviousPosition,
Vector3 SupportAnchor, SupportHit? SupportHit, BodyLandingObservation? Landing,
CameraRayPolygon? Contact, int CollisionPasses, int TriangleTests);
/// <summary>
/// Bounded479D20 composition: enabled integration/support/pairs/static flags,
/// prevent-lowering true, ordinary Jimmy370/374/37C and no dynamic body pass.
/// Special Player374 policies are rejected at construction. This is independent
/// of controller ownership and published speed is distinct from input speed608.
/// Euler addition follows the probe's334 fixture contract; actual generic angle
/// wrapping is not recovered. The live player bridge supplies zero angular speed.
/// See collision-body-probe.md and collision-body-composition-source.md.
/// </summary>
public sealed class OriginalBodyPhysics
{
private readonly OriginalStaticCollision collision;
public OriginalBodyPhysics(OriginalStaticCollision collision)
{
ArgumentNullException.ThrowIfNull(collision);
if (collision.HasSpecialPlayerContacts)
throw new NotSupportedException("Ordinary body composition requires recovered special-contact policies for this scene");
this.collision = collision;
}
public OrdinaryBodyStep Step(OrdinaryBodyState body, float seconds,
float radius = OriginalBodySupport.JimmyRadius, float factor = OriginalBodySupport.JimmyFactor,
float friction = .8f, float suppressionScale = .5f, bool geometryEnabled = true)
{
Finite(body.Position); Finite(body.Velocity); Finite(body.Acceleration); Finite(body.Impulse);
Finite(body.AngularVelocity); Finite(body.Rotation);
if (!float.IsFinite(body.PublishedSpeed) || !float.IsFinite(friction) || !float.IsFinite(suppressionScale)
|| !float.IsFinite(factor)) throw new ArgumentOutOfRangeException(nameof(body));
if (!float.IsFinite(radius) || radius <= 0) throw new ArgumentOutOfRangeException(nameof(radius));
if (!float.IsFinite(seconds) || seconds <= 0 || seconds >= 1)
throw new ArgumentOutOfRangeException(nameof(seconds));
var previous = body.Position;
var wasSupported = body.Supported;
body = body with { Supported = false };
var anchor = new Vector3(0, -25000, 0);
if (!geometryEnabled)
{
//479DF7..479E5A: global geometry-off policy, not prior support.
anchor.Y = previous.Y;
body = body with { Supported = true, Acceleration = new(0, -RecoveredMotion.Gravity.Y, 0),
Velocity = body.Velocity with { Y = 0 } };
}
body = body with { Rotation = body.Rotation + body.AngularVelocity * seconds };
var velocity = body.Velocity;
var impulse = body.Impulse;
var delta = RecoveredMotion.Integrate(ref velocity, ref impulse, body.Acceleration,
RecoveredMotion.Gravity, seconds);
var context = new StaticCollisionContext(radius);
var horizontalFirst = delta.Y <= 0;
var move = collision.Move(previous, horizontalFirst ? delta with { Y = 0 } : delta,
radius, context, geometryEnabled: geometryEnabled);
var acceleration = body.Acceleration;
//47B80F/47B82E -> Jimmy ordinary374 or positive-Y-only370.
// Neither supported callback moves the actor root, so the source's
// post-callback previous/live-root equality test permits publication.
if (move.CallbackPolygon is { } contact && contact.StoredNormal.Y <= -.7f)
{
if (velocity.Y > 0) velocity.Y = 0;
if (acceleration.Y > 0) acceleration.Y = 0;
}
var position = move.Position;
if (horizontalFirst) position.Y += delta.Y;
position.Y = MathF.Max(position.Y, -25000);
body = body with { Position = position, Velocity = velocity, Acceleration = acceleration, Impulse = impulse };
SupportHit? supportHit = null;
BodyLandingObservation? landing = null;
if (geometryEnabled)
{
var support = OriginalBodySupport.Resolve(new(position, previous, velocity, acceleration, radius, factor),
wasSupported, (start, end, sides) => collision.TraceSupport(start, end, sides));
if (support.Supported)
{
//37C observes new root/zero acceleration but old velocity/support.
//Jimmy's inherited37C is a no-op; the observation is diagnostic.
if (support.Landed) landing = new(support.Body.Position, velocity, support.Body.Acceleration, false);
body = body with { Position = support.Body.Position, Velocity = support.Body.Velocity,
Acceleration = support.Body.Acceleration, Supported = true };
anchor = support.SupportAnchor;
supportHit = support.Hit;
}
}
if (body.PublishedSpeed == 0 && body.Supported && OriginalBodySupport.QuickMagnitude(body.Velocity) > 0)
{
var v = body.Velocity;
var w = body.AngularVelocity;
body = body with {
Velocity = v + new Vector3(-v.X * friction * seconds, 0, -v.Z * friction * seconds),
AngularVelocity = w + new Vector3(-w.X * friction * seconds, -w.Y * friction * seconds, -w.Z * friction * seconds)
};
}
if (OriginalBodySupport.QuickMagnitude(body.AngularVelocity) * suppressionScale <= .1f)
body = body with { AngularVelocity = Vector3.Zero };
if (body.PublishedSpeed == 0 && OriginalBodySupport.QuickMagnitude(body.Velocity) * suppressionScale <= .1f)
body = body with { Velocity = Vector3.Zero };
return new(body, previous, anchor, supportHit, landing, move.CallbackPolygon, context.Passes, context.TriangleTests);
}
private static void Finite(Vector3 value)
{
if (!float.IsFinite(value.X) || !float.IsFinite(value.Y) || !float.IsFinite(value.Z))
throw new ArgumentOutOfRangeException(nameof(value));
}
}
+17 -4
View File
@@ -4,7 +4,7 @@ using GamePort.Assets;
namespace GamePort.Game; namespace GamePort.Game;
public readonly record struct CameraRayPolygon(SupportTriangle Triangle, Vector3 StoredNormal, public readonly record struct CameraRayPolygon(SupportTriangle Triangle, Vector3 StoredNormal,
string? ShapeName = null, string? MaterialName = null); string? ShapeName = null, string? MaterialName = null, int? MaterialId = null);
public readonly record struct CameraRayResult(Vector3 Eye, float Gain, SupportHit? Hit); public readonly record struct CameraRayResult(Vector3 Eye, float Gain, SupportHit? Hit);
/// <summary> /// <summary>
@@ -20,7 +20,7 @@ public sealed class OriginalCameraRay
public const float CellOrigin = 130; //49B1FC. public const float CellOrigin = 130; //49B1FC.
private readonly Dictionary<int, List<SupportTriangle>> walls = []; private readonly Dictionary<int, List<SupportTriangle>> walls = [];
private readonly Dictionary<int, List<SupportTriangle>> all = []; private readonly Dictionary<int, List<SupportTriangle>> all = [];
public bool Enabled { get; set; } = true; //4F69E5. public bool Enabled { get; set; } = true; // Modern camera-only debug override.
public int PolygonCount { get; } public int PolygonCount { get; }
public int WallPolygonCount { get; } public int WallPolygonCount { get; }
/// <summary>Modern query diagnostic; repeated cells are intentionally counted.</summary> /// <summary>Modern query diagnostic; repeated cells are intentionally counted.</summary>
@@ -77,7 +77,7 @@ public sealed class OriginalCameraRay
if (a >= mesh.Vertices.Length || b >= mesh.Vertices.Length || c >= mesh.Vertices.Length) if (a >= mesh.Vertices.Length || b >= mesh.Vertices.Length || c >= mesh.Vertices.Length)
throw new InvalidDataException("Camera triangle index outside vertex table"); throw new InvalidDataException("Camera triangle index outside vertex table");
polygons[i] = new(new(mesh.Vertices[a].Position, mesh.Vertices[b].Position, mesh.Vertices[c].Position, polygons[i] = new(new(mesh.Vertices[a].Position, mesh.Vertices[b].Position, mesh.Vertices[c].Position,
source.ShapeId, source.PolygonIndex), source.Normal, source.ShapeName, source.MaterialName); source.ShapeId, source.PolygonIndex), source.Normal, source.ShapeName, source.MaterialName, source.MaterialId);
} }
return new(polygons); return new(polygons);
} }
@@ -88,12 +88,25 @@ public sealed class OriginalCameraRay
RequireFinite(start); RequireFinite(end); RequireFinite(start); RequireFinite(end);
LastTriangleTests = 0; LastTriangleTests = 0;
if (!Enabled) return null; if (!Enabled) return null;
return TraceCore(start, end, twoSided, diagnostic: true);
}
/// <summary>425170 also uses47C210. Camera-only debug controls must not
/// disable physical ceiling checks or overwrite camera-query diagnostics.</summary>
public SupportHit? TraceGeometry(Vector3 start, Vector3 end, bool twoSided = false)
{
RequireFinite(start); RequireFinite(end);
return TraceCore(start, end, twoSided, diagnostic: false);
}
private SupportHit? TraceCore(Vector3 start, Vector3 end, bool twoSided, bool diagnostic)
{
foreach (var grid in new[] { walls, all }) foreach (var grid in new[] { walls, all })
foreach (var cell in CellsBetween(start, end)) foreach (var cell in CellsBetween(start, end))
if (grid.TryGetValue(cell, out var triangles)) if (grid.TryGetValue(cell, out var triangles))
foreach (var triangle in triangles) foreach (var triangle in triangles)
{ {
LastTriangleTests++; if (diagnostic) LastTriangleTests++;
if (OriginalBodySupport.IntersectSegment(triangle, start, end, twoSided) is { } hit) if (OriginalBodySupport.IntersectSegment(triangle, start, end, twoSided) is { } hit)
return hit; return hit;
} }
+39
View File
@@ -0,0 +1,39 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>OMT2 vector::angles second output used by the original shrink ray.</summary>
public static class OriginalHeading
{
private static readonly ushort[] halfAcos = BuildHalfAcos();
public static float Degrees(Vector3 vector)
{
if (!float.IsFinite(vector.X) || !float.IsFinite(vector.Y) || !float.IsFinite(vector.Z))
throw new ArgumentOutOfRangeException(nameof(vector), "A finite direction is required.");
double x = vector.X, z = vector.Z;
if (x == 0 && z == 0) return 0;
// DLL1001FDCB..1001FE3D: truncate the squared ratio, table lookup,
// quadrant correction, negate and mask to the original 14-bit circle.
// Double intermediates approximate x87 extended precision; see findings.
int index = (int)(16384.0 * z * z / (x * x + z * z));
int angle = halfAcos[index];
if (z < 0)
angle = x < 0 ? 8192 + angle : 8192 - angle;
else if (x < 0)
angle = 16384 - angle;
return ((-angle) & 0x3fff) * 0.02197265625f;
}
private static ushort[] BuildHalfAcos()
{
var table = new ushort[16385];
// Stored DLL constants; final endpoint is explicitly zero at100EDD0D.
for (int i = 0; i < 16384; i++)
table[i] = (ushort)(Math.Acos(i * 0.0001220703125 - 1)
* 2607.5945876921437 * 0.5);
return table;
}
}
@@ -0,0 +1,81 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct SphereResponseState(float FaceDistance, float EdgeDistance, Vector3? Hit)
{
public static SphereResponseState Begin(float radius) => new(-1, radius, null);
}
public enum SphereContact { None, Face, Edge }
public readonly record struct SphereResponseResult(Vector3 Position, SphereResponseState State, SphereContact Contact);
/// <summary>
/// Bounded EXE47BD80 kernel over one supplied source triangle. Callers own grid
/// order, persistent nearest-hit state, callbacks and subsequent support. This
/// component does not replace the port's capsule or reconstruct the whole solver.
/// </summary>
public static class OriginalSphereResponse
{
public static SphereResponseResult Resolve(SupportTriangle triangle, Vector3 normal,
Vector3 previous, Vector3 position, float radius, SphereResponseState state,
bool edges = true, bool allowLowerEdges = false)
{
Finite(triangle.A); Finite(triangle.B); Finite(triangle.C);
Finite(normal); Finite(previous); Finite(position);
if (!float.IsFinite(radius) || radius <= 0 || !float.IsFinite(state.FaceDistance)
|| !float.IsFinite(state.EdgeDistance)) throw new ArgumentOutOfRangeException(nameof(radius));
var unchanged = new SphereResponseResult(position, state, SphereContact.None);
var offset = normal * radius;
var endpoint = position - offset;
endpoint.Y = MathF.Max(endpoint.Y, position.Y);
if (OriginalBodySupport.IntersectSegment(triangle, previous, endpoint) is { } face)
{
// A farther face returns immediately; it must not fall into edges.
if (state.FaceDistance != -1 && face.Distance >= state.FaceDistance) return unchanged;
var resolved = face.Position + offset;
if (normal.Y >= -.7f) resolved.Y = position.Y;
return new(resolved, state with { FaceDistance = face.Distance, Hit = face.Position }, SphereContact.Face);
}
if (!edges || normal.Y <= -.7f || normal.Y >= .7f) return unchanged;
//4695B0 considers only the three edges, including their endpoints.
var ab = NearestOnSegment(position, triangle.A, triangle.B);
var bc = NearestOnSegment(position, triangle.B, triangle.C);
var ca = NearestOnSegment(position, triangle.C, triangle.A);
var da = OriginalBodySupport.QuickMagnitude(position - ab);
var db = OriginalBodySupport.QuickMagnitude(position - bc);
var dc = OriginalBodySupport.QuickMagnitude(position - ca);
var nearest = db <= da ? db < dc ? bc : ca : da < dc ? ab : ca;
if (!allowLowerEdges && nearest.Y < position.Y) return unchanged;
var toEdge = nearest - position;
var distance = OriginalBodySupport.QuickMagnitude(toEdge);
// Exact overlap would normalize zero in the source. Keep that undefined
// arithmetic outside this bounded finite-input reconstruction.
if (distance == 0) return unchanged;
var direction = toEdge / distance;
if (Dot(direction, normal) >= 0 || state.EdgeDistance != -1 && distance >= state.EdgeDistance)
return unchanged;
var edgePosition = nearest - direction * radius;
edgePosition.Y = position.Y;
return new(edgePosition, state with { EdgeDistance = distance, Hit = nearest }, SphereContact.Edge);
}
private static Vector3 NearestOnSegment(Vector3 point, Vector3 a, Vector3 b)
{
var edge = b - a;
var length = OriginalBodySupport.QuickMagnitude(edge);
if (length == 0) return a;
var direction = edge / length;
var projection = Dot(point - a, direction);
return projection < 0 ? a : projection > length ? b : a + direction * projection;
}
private static float Dot(Vector3 a, Vector3 b) =>
(float)((double)a.X * b.X + (double)a.Y * b.Y + (double)a.Z * b.Z);
private static void Finite(Vector3 value)
{
if (!float.IsFinite(value.X) || !float.IsFinite(value.Y) || !float.IsFinite(value.Z))
throw new ArgumentOutOfRangeException(nameof(value));
}
}
@@ -0,0 +1,154 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
public sealed class StaticCollisionContext(float radius, float faceDistance = 130000)
{
public SphereResponseState Nearest { get; internal set; } = new(faceDistance, radius, null);
public CameraRayPolygon? LastPolygon { get; internal set; }
public int Passes { get; internal set; }
public int TriangleTests { get; internal set; }
}
public readonly record struct StaticCollisionMove(Vector3 Position, CameraRayPolygon? CallbackPolygon, bool Published);
public readonly record struct CollisionCells(int MinX, int MaxX, int MinZ, int MaxZ);
/// <summary>
/// Source47B4B0/47BBB0 static dispatcher. Preserves cell/FIFO duplicates, mutable
/// candidate, shared nearest state and retries. Callers own normal callbacks,
/// integration, support and scene-wide state. See collision-grid-traversal.md.
/// </summary>
public sealed class OriginalStaticCollision
{
private readonly Dictionary<int, List<CameraRayPolygon>> walls = [];
private readonly Dictionary<int, List<SupportTriangle>> all = [];
public int PolygonCount { get; }
public int WallPolygonCount { get; }
public bool HasSpecialPlayerContacts { get; }
public OriginalStaticCollision(IEnumerable<CameraRayPolygon> polygons)
{
var identities = new HashSet<(int, int)>();
foreach (var polygon in polygons.OrderBy(p => p.Triangle.ShapeId).ThenBy(p => p.Triangle.PolygonId))
{
if (polygon.ShapeName?.StartsWith("nc", StringComparison.OrdinalIgnoreCase) == true
|| Checkpoint(polygon.MaterialName)) continue;
var t = polygon.Triangle;
Finite(t.A); Finite(t.B); Finite(t.C); Finite(polygon.StoredNormal);
if (!identities.Add((t.ShapeId, t.PolygonId)))
throw new InvalidDataException("Source static collision needs one triangle per polygon");
var min = Vector3.Min(t.A, Vector3.Min(t.B, t.C));
var max = Vector3.Max(t.A, Vector3.Max(t.B, t.C));
foreach (var cell in Rectangle(new(Cell(min.X), Cell(max.X), Cell(min.Z), Cell(max.Z))))
{
if (!all.TryGetValue(cell, out var support)) all.Add(cell, support = []);
support.Add(t);
if (polygon.StoredNormal.Y >= .7f) continue;
if (!walls.TryGetValue(cell, out var list)) walls.Add(cell, list = []);
list.Add(polygon);
}
PolygonCount++;
if (polygon.StoredNormal.Y < .7f) WallPolygonCount++;
if (polygon.StoredNormal.Y > -.7f && polygon.StoredNormal.Y < .7f
&& polygon.MaterialId is >= 60 and <= 69 or >= 110 and <= 129 or 180)
HasSpecialPlayerContacts = true;
}
}
public static OriginalStaticCollision FromRouteScene(Mesh mesh, string level)
{
ArgumentNullException.ThrowIfNull(mesh);
if (level is not ("LV1B" or "VR04" or "LEV1"))
throw new NotSupportedException("Original static game-filter recovery covers only the three route scenes");
if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3)
throw new InvalidDataException("Source static collision requires original polygon metadata");
if (!mesh.HasCollisionMaterialIds)
throw new InvalidDataException("Source static collision requires material identities; prepare the scene again");
return new(Enumerable.Range(0, mesh.CollisionPolygons.Length).Select(i => {
var p = mesh.CollisionPolygons[i];
if (mesh.Indices[i * 3] >= mesh.Vertices.Length || mesh.Indices[i * 3 + 1] >= mesh.Vertices.Length
|| mesh.Indices[i * 3 + 2] >= mesh.Vertices.Length)
throw new InvalidDataException("Collision triangle index outside vertex table");
return new CameraRayPolygon(new(mesh.Vertices[mesh.Indices[i * 3]].Position,
mesh.Vertices[mesh.Indices[i * 3 + 1]].Position, mesh.Vertices[mesh.Indices[i * 3 + 2]].Position,
p.ShapeId, p.PolygonIndex), p.Normal, p.ShapeName, p.MaterialName, p.MaterialId);
}));
}
public StaticCollisionMove Move(Vector3 previous, Vector3 delta, float radius,
StaticCollisionContext context, bool edges = true, bool lowerEdges = false, bool geometryEnabled = true)
{
Finite(previous); Finite(delta);
if (!float.IsFinite(radius) || radius <= 0) throw new ArgumentOutOfRangeException(nameof(radius));
ArgumentNullException.ThrowIfNull(context);
// The source recurses with no explicit depth limit. This iterative form
// keeps the same state, and rejects paths outside the bounded contract
// instead of silently inventing a final collision position.
for (var retry = 0; retry < 256; retry++)
{
var length = OriginalBodySupport.QuickMagnitude(delta);
if (!lowerEdges && length < 1.1920928955078125e-7f) return new(previous, null, false);
context.Passes++;
var candidate = previous + delta;
var accepted = false;
foreach (var cell in Rectangle(Bounds(previous, candidate, radius + length)))
if (walls.TryGetValue(cell, out var polygons))
foreach (var polygon in polygons)
{
if (!geometryEnabled) continue;
context.TriangleTests++;
var result = OriginalSphereResponse.Resolve(polygon.Triangle, polygon.StoredNormal,
previous, candidate, radius, context.Nearest, edges, lowerEdges);
if (result.Contact == SphereContact.None) continue;
candidate = result.Position; context.Nearest = result.State;
context.LastPolygon = polygon; accepted = true;
}
if (!accepted) return new(candidate, context.LastPolygon, true);
delta = candidate - previous;
}
throw new InvalidOperationException("Source collision retry exceeds the verified finite-motion contract");
}
/// <summary>47C6E0 nearest reduction; equal hits retain cell/FIFO order.</summary>
public SupportHit? TraceSupport(Vector3 start, Vector3 end, bool twoSided = false)
{
Finite(start); Finite(end);
SupportHit? nearest = null;
var nearestDistance = OriginalBodySupport.QuickMagnitude(end - start);
foreach (var cell in Rectangle(new(Math.Min(Cell(start.X), Cell(end.X)), Math.Max(Cell(start.X), Cell(end.X)),
Math.Min(Cell(start.Z), Cell(end.Z)), Math.Max(Cell(start.Z), Cell(end.Z)))))
if (all.TryGetValue(cell, out var triangles))
foreach (var triangle in triangles)
if (OriginalBodySupport.IntersectSegment(triangle, start, end, twoSided) is { } hit
&& hit.Distance < nearestDistance)
{
nearest = hit;
nearestDistance = hit.Distance;
}
return nearest;
}
/// <summary>47B53A..47B62A: the Z upper bound intentionally uses MIN.</summary>
public static CollisionCells Bounds(Vector3 previous, Vector3 candidate, float expansion) => new(
Math.Min(Cell(previous.X - expansion), Cell(candidate.X - expansion)),
Math.Max(Cell(previous.X + expansion), Cell(candidate.X + expansion)),
Math.Min(Cell(previous.Z - expansion), Cell(candidate.Z - expansion)),
Math.Min(Cell(previous.Z + expansion), Cell(candidate.Z + expansion)));
private static int Cell(float value) => OriginalCameraRay.CellCoordinate(value);
private static IEnumerable<int> Rectangle(CollisionCells bounds)
{
for (var x = Math.Max(0, bounds.MinX); x <= Math.Min(259, bounds.MaxX); x++)
for (var z = Math.Max(0, bounds.MinZ); z <= Math.Min(259, bounds.MaxZ); z++) yield return 260 * x + z;
}
private static bool Checkpoint(string? value) => value != null
&& (value.Equals("cstart", StringComparison.OrdinalIgnoreCase)
|| value.Length == 7 && value.StartsWith("ccheck", StringComparison.OrdinalIgnoreCase)
&& value[6] is >= '1' and <= '9');
private static void Finite(Vector3 value)
{
if (!float.IsFinite(value.X) || !float.IsFinite(value.Y) || !float.IsFinite(value.Z))
throw new ArgumentOutOfRangeException(nameof(value));
}
}
+5
View File
@@ -17,6 +17,8 @@ public sealed class PlayerSceneBinding : IDisposable
this.director = director; this.player = player; this.inventory = inventory; this.tag = tag; this.director = director; this.player = player; this.inventory = inventory; this.tag = tag;
director.ActorPreparing += Prepare; director.ActorPreparing += Prepare;
director.AuthoredTransformChanged += Transform; director.AuthoredTransformChanged += Transform;
inventory.GadgetSelected += Selected;
Selected(inventory.SelectedGadget);
} }
public bool Step(PlayerInput input) public bool Step(PlayerInput input)
@@ -42,6 +44,8 @@ public sealed class PlayerSceneBinding : IDisposable
} }
} }
private void Selected(int item) => player.GadgetMode = GadgetScreen.EquippedMode(item);
private void Transform(DirectorActor actor) private void Transform(DirectorActor actor)
{ {
if (string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) if (string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase))
@@ -52,5 +56,6 @@ public sealed class PlayerSceneBinding : IDisposable
{ {
director.ActorPreparing -= Prepare; director.ActorPreparing -= Prepare;
director.AuthoredTransformChanged -= Transform; director.AuthoredTransformChanged -= Transform;
inventory.GadgetSelected -= Selected;
} }
} }
+88
View File
@@ -0,0 +1,88 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>First usable default shrink/jetpack device; special gadgets stay separate.</summary>
public sealed class SceneGadgets : IDisposable
{
private readonly LabSimulation player;
private readonly SceneInventory inventory;
private readonly OriginalScenePhysics physics;
private readonly OriginalCameraRay geometry;
private bool loop, busy;
public ShrinkRay Ray { get; } = new();
public IReadOnlyList<ShrinkSoldier> Soldiers { get; }
public int ShrinkHits { get; private set; }
public event Action<int, bool>? Sound;
public event Action? StopSound;
public event Action<int>? ScoreAwarded;
public SceneGadgets(SceneDirector director, SceneInventory inventory, LabSimulation player, Mesh world)
{
this.inventory = inventory; this.player = player;
//Static source registration game-filter is only recovered for the route.
geometry = OriginalCameraRay.FromRouteScene(world, player.LevelCode);
physics = new OriginalScenePhysics(world);
Soldiers = director.Actors.Where(a => a.Kind == "3SOL").Select(a => new ShrinkSoldier(a)).ToArray();
foreach (var soldier in Soldiers) soldier.Actor.Animation = "WALK";
player.InputActions += Input;
}
public void StepBodies(float seconds)
{
Ray.StepTexture(seconds);
foreach (var soldier in Soldiers) soldier.StepBody(physics, seconds);
}
public void StepTimers(float seconds)
{
foreach (var soldier in Soldiers) soldier.StepTimer(seconds);
}
private void Input(PlayerInput input)
{
if (!input.Fire) { busy = false; Stop(); return; }
if (busy || player.GadgetMode != -1) { Stop(); return; }
player.StopForPrimaryFire();
if (inventory.State(0,3) != 1)
{ Sound?.Invoke(117,false); busy = true; Stop(); return; }
//426937..426989: ordinary airborne FALL stops/hides the owned beam.
if (!player.Grounded && player.Pose == PlayerPose.Fall) { Stop(); return; }
player.SetShooting(player.Grounded);
if (!loop) { Sound?.Invoke(0,true); loop = true; }
const float dt = FixedStepClock.Step;
if (!(player.LevelCode.Length == 4 && player.LevelCode.StartsWith("VR0",StringComparison.Ordinal)
&& player.LevelCode[3] is >= '1' and <= '8')) player.Energy = Math.Clamp(player.Energy - dt,0,100);
//Bridge modern signed float yaw to the source's nonnegative Euler domain.
var yaw = (player.Yaw % 360 + 360) % 360;
var hits = Ray.Fire(player.ActorRoot,yaw,dt,
Soldiers.Select(s => new ShrinkCandidate(s.Actor.Tag,s.Actor.Position,Shrunk:s.Shrunk)),
(start,end) => geometry.TraceGeometry(start,end));
foreach (var tag in hits)
{
var soldier = Soldiers.First(s => s.Actor.Tag == tag);
soldier.Shrink(); ShrinkHits++;
//Ordinary3SOL callback42AD81 awards10, then publishes marker94C.
//Other enemy classes/special LIBBYPLANT/C3DDINO callbacks are separate.
if (!tag.Equals("LIBBYPLANT",StringComparison.OrdinalIgnoreCase)
&& !tag.Equals("C3DDINO",StringComparison.OrdinalIgnoreCase))
{ ScoreAwarded?.Invoke(10); soldier.MarkScoredHit(); }
}
}
public void Stop()
{
Ray.Hide(); player.SetShooting(false);
if (loop) StopSound?.Invoke();
loop = false;
}
public void Reset()
{
Stop(); busy = false; Ray.Reset(); ShrinkHits = 0;
foreach (var soldier in Soldiers) soldier.Reset();
}
public void Dispose() { player.InputActions -= Input; Stop(); }
}
+3 -2
View File
@@ -32,6 +32,7 @@ public sealed class SceneInteractions
public event Action<Vector3>? CheckpointCaptured; public event Action<Vector3>? CheckpointCaptured;
public event Action<DirectorActor, string>? ConversationStarted; public event Action<DirectorActor, string>? ConversationStarted;
public event Action<int>? ObjectiveChanged; public event Action<int>? ObjectiveChanged;
public void ChangeScore(int delta) => Score = Math.Max(0,unchecked(Score + delta));
public SceneInteractions(SceneDirector director, TaskStates tasks, OriginalSave save) public SceneInteractions(SceneDirector director, TaskStates tasks, OriginalSave save)
{ {
@@ -134,8 +135,8 @@ public sealed class SceneInteractions
private void CollectPickup(DirectorActor actor, GamEntity source, Vector3 playerRoot) private void CollectPickup(DirectorActor actor, GamEntity source, Vector3 playerRoot)
{ {
var id = source.Integer("PickupIndex", -1); var id = source.Integer("PickupIndex", -1);
// The source tag is SHRINKRAY; original objective art120 calls this //Group0/item3 is the combined shrink ray/jetpack. Objective120 names its
// pickup the jet pack, matching group0/item3 and powered-jump ownership. //jetpack action; original gadget tile14 and controls113 also name SHRINK.
var jetpack = Equal(source.Tag, "SHRINKRAY"); var jetpack = Equal(source.Tag, "SHRINKRAY");
var ordinaryStar = id is >= 3000 and < 4000 && source.Integer("PointValue") == 5; var ordinaryStar = id is >= 3000 and < 4000 && source.Integer("PointValue") == 5;
if (id is <= 0 or >= OriginalSave.ItemCount || !(ordinaryStar || jetpack && source.Integer("PointValue") == 50) if (id is <= 0 or >= OriginalSave.ItemCount || !(ordinaryStar || jetpack && source.Integer("PointValue") == 50)
+106
View File
@@ -0,0 +1,106 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct ShrinkCandidate(string Tag, Vector3 Position, bool BodyEnabled = true,
bool ShrinkEnabled = true, bool Shrunk = false);
/// <summary>Ordinary owned-item3/mode-1 continuous426E40 scan, not a projectile.</summary>
public sealed class ShrinkRay
{
private float textureTime;
public int TexturePhase { get; private set; }
public bool Visible { get; private set; }
public Vector3 Position { get; private set; }
public float Yaw { get; private set; }
public void StepTexture(float seconds)
{
Seconds(seconds);
textureTime += seconds;
//Float accumulation compared with the source stored double0.1.
if ((double)textureTime <= .1) return;
TexturePhase = (TexturePhase + 1) % 3;
textureTime = 0;
}
public void Hide() => Visible = false;
public void Reset() { Visible = false; TexturePhase = 0; textureTime = 0; }
public IReadOnlyList<string> Fire(Vector3 root, float yaw, float seconds,
IEnumerable<ShrinkCandidate> candidates, Func<Vector3, Vector3, SupportHit?> wallQuery)
{
Seconds(seconds);
if (!float.IsFinite(yaw)) throw new ArgumentOutOfRangeException(nameof(yaw));
Visible = true; Position = root; Yaw = yaw;
List<string> hits = [];
foreach (var target in candidates)
{
if (!target.BodyEnabled || !target.ShrinkEnabled || target.Shrunk
|| target.Position.Y <= root.Y - 150 || target.Position.Y >= root.Y + 60) continue;
var difference = target.Position - root;
var distance = difference.Length();
if (distance >= 1500) continue;
var heading = OriginalHeading.Degrees(difference);
//No added angle-seam wrapping in the recovered comparison.
if (heading <= yaw - 5 || heading >= yaw + 5) continue;
var (sin, cos) = LabSimulation.Trig(yaw);
var start = root + Vector3.UnitY * 150;
var end = start + new Vector3(-sin * distance, 0, cos * distance);
if (wallQuery(start, end) != null) continue;
hits.Add(target.Tag);
}
return hits;
}
private static void Seconds(float seconds)
{
if (!float.IsFinite(seconds) || seconds < 0 || seconds >= 1)
throw new ArgumentOutOfRangeException(nameof(seconds));
}
}
/// <summary>Bounded original3SOL body settling and shrink state; combat/path AI remain open.</summary>
public sealed class ShrinkSoldier(DirectorActor actor)
{
public DirectorActor Actor { get; } = actor;
public Vector3 Velocity { get; private set; }
public bool Grounded { get; private set; }
public bool Shrunk { get; private set; }
public float Remaining { get; private set; }
public int AuthoredMode { get; } = actor.SourceGam?.Integer("AIState",2) ?? 2;
public int PreviousMode { get; private set; }
public int ShrinkRevision { get; private set; }
public float HitMarker { get; private set; }
public void MarkScoredHit() => HitMarker = 1;
public void Reset()
{
Velocity = Vector3.Zero; Grounded = Shrunk = false; Remaining = 0;
ShrinkRevision = 0; HitMarker = 0; Actor.Animation = "WALK";
}
public void StepBody(OriginalScenePhysics physics, float seconds)
{
var result = physics.Step(Actor.Position, Velocity, 90, 1, Grounded, seconds);
Actor.Position = result.Body.Position; Velocity = result.Body.Velocity; Grounded = result.Supported;
}
public void Shrink()
{
if (Shrunk) return;
PreviousMode = Actor.AIstate; Actor.AIstate = 5;
Actor.Animation = "SHRINK"; Remaining = 30; Shrunk = true; ShrinkRevision++;
}
public void StepTimer(float seconds)
{
if (!float.IsFinite(seconds) || seconds < 0 || seconds >= 1) throw new ArgumentOutOfRangeException(nameof(seconds));
if (!Shrunk || Remaining <= 0) return;
Remaining -= seconds;
//Source44AE85: exact zero does not expire and is skipped next tick.
if (Remaining >= 0) return;
Remaining = 0; Shrunk = false; HitMarker = 0;
PreviousMode = Actor.AIstate;
Actor.AIstate = AuthoredMode; Actor.Animation = "WALK"; Actor.Speed = 200;
}
}
+218 -16
View File
@@ -85,6 +85,9 @@ internal static class Program
--smoke-practice-return Headless lab/VR04/RETURN root and intro-suppression check --smoke-practice-return Headless lab/VR04/RETURN root and intro-suppression check
--smoke-practice-window SDL practice pause/dismiss/resize check (12 frames) --smoke-practice-window SDL practice pause/dismiss/resize check (12 frames)
--smoke-jetpack 300-step powered steering/jump check in VR04 --smoke-jetpack 300-step powered steering/jump check in VR04
--smoke-shrink-ray Fire at an actual VR04 soldier; explicit player-placement fixture
--gadget-menu Render original gadget panel (--skip-intro); fixture owns item3
--smoke-gadget-menu SDL menu input/pause/selection/practice/Return check (24 frames)
--smoke-jump-key NAME Replay using shift/right-shift/insert/keypad0/right-mouse --smoke-jump-key NAME Replay using shift/right-shift/insert/keypad0/right-mouse
--smoke-carl-cutscene Verify input stays locked during the lab conversation --smoke-carl-cutscene Verify input stays locked during the lab conversation
--smoke-control-phases Airborne cutscene body/fire and restoration fixture --smoke-control-phases Airborne cutscene body/fire and restoration fixture
@@ -251,6 +254,7 @@ internal static class Program
var animationPath = Option(args, "--animation"); var animationPath = Option(args, "--animation");
var walkSmoke = args.Contains("--smoke-walk"); var walkSmoke = args.Contains("--smoke-walk");
var jetpackSmoke = args.Contains("--smoke-jetpack"); var jetpackSmoke = args.Contains("--smoke-jetpack");
var shrinkSmoke = args.Contains("--smoke-shrink-ray");
var carlSmoke = args.Contains("--smoke-carl-cutscene"); var carlSmoke = args.Contains("--smoke-carl-cutscene");
var controlPhaseSmoke = args.Contains("--smoke-control-phases"); var controlPhaseSmoke = args.Contains("--smoke-control-phases");
var objectiveWindowSmoke = args.Contains("--smoke-objective-window"); var objectiveWindowSmoke = args.Contains("--smoke-objective-window");
@@ -266,11 +270,12 @@ internal static class Program
var debugSmoke = args.Contains("--smoke-debug-menu"); var debugSmoke = args.Contains("--smoke-debug-menu");
var toolsSmoke = args.Contains("--smoke-debug-tools"); var toolsSmoke = args.Contains("--smoke-debug-tools");
var diagnosticsSmoke = args.Contains("--smoke-debug-overlay"); var diagnosticsSmoke = args.Contains("--smoke-debug-overlay");
var gadgetWindowSmoke = args.Contains("--smoke-gadget-menu");
if (walkSmoke && jetpackSmoke) throw new ArgumentException("Select one movement smoke check"); if (walkSmoke && jetpackSmoke) throw new ArgumentException("Select one movement smoke check");
var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window") var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window")
&& animationPath == null && !args.Contains("--time"); && animationPath == null && !args.Contains("--time");
var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time") var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time")
|| args.Contains("--skip-intro") || jetpackSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke; || args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke;
if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window"))) if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window")))
throw new ArgumentException("Story playback requires its own simulation mode."); throw new ArgumentException("Story playback requires its own simulation mode.");
if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode."); if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode.");
@@ -292,6 +297,11 @@ internal static class Program
SceneInteractions? interactions = null; SceneInteractions? interactions = null;
SceneMechanisms? mechanisms = null; SceneMechanisms? mechanisms = null;
SceneHud? hud = null; SceneHud? hud = null;
GadgetScreen? gadgetScreen = null;
GadgetMenuOverlay? gadgetOverlay = null;
SceneGadgets? gadgets = null;
ShrinkRayVisuals? rayVisuals = null;
ShrinkSoldierVisuals? soldierVisuals = null;
JetpackVisuals? jetpackVisuals = null; JetpackVisuals? jetpackVisuals = null;
var practice = new PracticePrompt(); var practice = new PracticePrompt();
ObjectivePanel? objectivePanel = null; ObjectivePanel? objectivePanel = null;
@@ -324,7 +334,9 @@ internal static class Program
? OriginalCameraRay.FromRouteScene(world, level.Code) : null; ? OriginalCameraRay.FromRouteScene(world, level.Code) : null;
debugCameraRay = cameraRay; debugCameraRay = cameraRay;
simulation = new LabSimulation(new SceneCollision(world), standingPose, originalStart.Position, originalStart.Rotation.Y, simulation = new LabSimulation(new SceneCollision(world), standingPose, originalStart.Position, originalStart.Rotation.Y,
cameraRay == null ? null : (look, eye) => cameraRay.Trace(look, eye)) cameraRay == null ? null : (look, eye) => cameraRay.Trace(look, eye),
cameraRay == null ? null : (start, end) => cameraRay.TraceGeometry(start, end),
level.Code == "VR04" ? OriginalStaticCollision.FromRouteScene(world,level.Code) : null)
{ LevelCode = level.Code, InputAfterPlayerUpdate = carriedSave != null }; { LevelCode = level.Code, InputAfterPlayerUpdate = carriedSave != null };
if (carriedPlayer != null) if (carriedPlayer != null)
{ {
@@ -342,7 +354,7 @@ internal static class Program
characterModel = placement.Model; characterModel = placement.Model;
mesh = animations.Current.AppendTo(mesh); mesh = animations.Current.AppendTo(mesh);
if (walking) if (walking)
Console.WriteLine("Controllable lab: arrows move/turn; Shift/Insert/right mouse jump; R reset; C pause/inspect; F11 fullscreen; Escape quit. Collision, pivot and timing remain provisional."); Console.WriteLine("Controllable lab: arrows move/turn; Shift/Insert/right mouse jump; Enter/Ctrl/left mouse fire; Tab/Space gadgets; R reset; C inspect; F11 fullscreen; Escape quit. Collision, pivot and timing remain provisional.");
else else
Console.WriteLine($"Preview floor correction: +{placement.VerticalCorrection:F3} Y. 1 idle, 2 run, 3 jump, 4 scratch."); Console.WriteLine($"Preview floor correction: +{placement.VerticalCorrection:F3} Y. 1 idle, 2 run, 3 jump, 4 scratch.");
} }
@@ -356,11 +368,17 @@ internal static class Program
storyTasks = tasks; storyTasks = tasks;
director = new SceneDirector(level!, tasks, resources.Duration); director = new SceneDirector(level!, tasks, resources.Duration);
interactions = new SceneInteractions(director, tasks, save); interactions = new SceneInteractions(director, tasks, save);
gadgetScreen = new GadgetScreen(interactions.Inventory);
interactions.Inventory.ApplyLevelAvailability(level!.Code); interactions.Inventory.ApplyLevelAvailability(level!.Code);
objectivePanel = new ObjectivePanel(interactions.CurrentObjective); objectivePanel = new ObjectivePanel(interactions.CurrentObjective);
interactions.ObjectiveChanged += objectivePanel.Select; interactions.ObjectiveChanged += objectivePanel.Select;
simulation!.Energy = interactions.Energy; simulation!.Energy = interactions.Energy;
simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3); simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3);
if (level.Code is "LV1B" or "VR04" or "LEV1")
{
gadgets = new SceneGadgets(director,interactions.Inventory,simulation,world);
gadgets.ScoreAwarded += interactions.ChangeScore;
}
mechanisms = new SceneMechanisms(director); mechanisms = new SceneMechanisms(director);
interactions.Transition += RequestTransition; interactions.Transition += RequestTransition;
interactions.PracticeRequested += practice.Show; interactions.PracticeRequested += practice.Show;
@@ -371,6 +389,11 @@ internal static class Program
interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!); interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!);
RequestTransition(new(PracticePrompt.Destination(mode), "PHONEBOOTH", 0, -1)); RequestTransition(new(PracticePrompt.Destination(mode), "PHONEBOOTH", 0, -1));
}; };
gadgetScreen.PracticeRequested += item =>
{
interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!);
RequestTransition(new($"VR0{item + 1}.gam", "PHONEBOOTH", 0, -1));
};
interactions.Collected += (entity, points) => Console.WriteLine($"Collected {entity.Tag}: +{points}; score={interactions.Score}."); interactions.Collected += (entity, points) => Console.WriteLine($"Collected {entity.Tag}: +{points}; score={interactions.Score}.");
foreach (var actor in director.Actors.Where(a => a.Kind is "3DOG" or "3CAR")) foreach (var actor in director.Actors.Where(a => a.Kind is "3DOG" or "3CAR"))
{ {
@@ -391,18 +414,37 @@ internal static class Program
actorVisuals = new SceneActorVisuals(mesh, world, director, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")), actorVisuals = new SceneActorVisuals(mesh, world, director, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),
actor => patrols.ContainsKey(actor.Tag)); actor => patrols.ContainsKey(actor.Tag));
mesh = actorVisuals.Mesh; mesh = actorVisuals.Mesh;
if (gadgets != null)
{
soldierVisuals = new ShrinkSoldierVisuals(mesh,gadgets.Soldiers,
Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),level!.Code);
mesh = soldierVisuals.Mesh;
}
spriteVisuals = new SceneSpriteVisuals(mesh, director, resources); spriteVisuals = new SceneSpriteVisuals(mesh, director, resources);
mesh = spriteVisuals.Mesh; mesh = spriteVisuals.Mesh;
staticVisuals = new StaticSceneVisuals(mesh, director, root, Path.Combine(Path.GetDirectoryName(scene!)!, "models")); staticVisuals = new StaticSceneVisuals(mesh, director, root, Path.Combine(Path.GetDirectoryName(scene!)!, "models"));
mesh = staticVisuals.Mesh; mesh = staticVisuals.Mesh;
simulation!.DynamicRootResolver = (previous, position, radius) => if (simulation!.UsesOriginalBody)
{
if (staticVisuals.DoorColliders().Any())
throw new NotSupportedException("Source ordinary-body scene has unsupported dynamic door colliders");
}
else simulation.DynamicRootResolver = (previous, position, radius) =>
DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius); DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius);
jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, ".."))); jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")));
mesh = jetpackVisuals.Mesh; mesh = jetpackVisuals.Mesh;
if (gadgets != null)
{
rayVisuals = new ShrinkRayVisuals(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),root);
mesh = rayVisuals.Mesh;
}
hud = new SceneHud(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../ui/ui.json")); hud = new SceneHud(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../ui/ui.json"));
mesh = hud.Mesh; mesh = hud.Mesh;
gadgetOverlay = new GadgetMenuOverlay(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../gadgets/gadgets.json"));
mesh = gadgetOverlay.Mesh;
Console.WriteLine($"Prepared source model actors: {staticVisuals.ActorCount}."); Console.WriteLine($"Prepared source model actors: {staticVisuals.ActorCount}.");
} }
using var gadgetLifetime = gadgets;
var debugMenu = new DebugMenu(scene != null && level != null var debugMenu = new DebugMenu(scene != null && level != null
? DebugMenu.AvailableScenes(root, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene)!, ".."))) : [], ? DebugMenu.AvailableScenes(root, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene)!, ".."))) : [],
Path.GetFileName(levelPath), originalStart?.Tag); Path.GetFileName(levelPath), originalStart?.Tag);
@@ -430,7 +472,11 @@ internal static class Program
var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture); var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture);
if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless) if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless)
throw new ArgumentException("Story time must be0..3600 seconds in headless mode."); throw new ArgumentException("Story time must be0..3600 seconds in headless mode.");
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0")); var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : shrinkSmoke ? "90" : gadgetWindowSmoke ? "24" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0"));
if (gadgetWindowSmoke && (headless || level?.Code != "LV1B" || loadedSave != null || frames < 24))
throw new ArgumentException("Gadget menu SDL fixture requires a fresh windowed lab and24 frames");
if (shrinkSmoke && (level?.Code != "VR04" || gadgets == null || frames < 60))
throw new ArgumentException("Shrink-ray smoke requires actual VR04 and at least60 frames");
if (controlPhaseSmoke && (level?.Code != "LV1B" || loadedSave != null || frames < 32 || director == null)) if (controlPhaseSmoke && (level?.Code != "LV1B" || loadedSave != null || frames < 32 || director == null))
throw new ArgumentException("Control-phase fixture needs a fresh lab and at least32 frames"); throw new ArgumentException("Control-phase fixture needs a fresh lab and at least32 frames");
if (toolsSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open)) if (toolsSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open))
@@ -460,12 +506,25 @@ internal static class Program
walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera", walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera",
width, height, !args.Contains("--no-validation")); width, height, !args.Contains("--no-validation"));
var window = presentation.Window; var window = presentation.Window;
ShrinkSoldier? shrinkVictim = null;
var shrinkPhaseMask = 0;
var sawShrinkKey = false;
Console.WriteLine($"Scene presentation: revision={renderer.SceneRevision}, windows={presentation.WindowCreationCount}, renderers={presentation.RendererCreationCount}, window ID={(window == 0 ? 0 : Sdl.SDL_GetWindowID(window))}, size={renderer.Width}x{renderer.Height}."); Console.WriteLine($"Scene presentation: revision={renderer.SceneRevision}, windows={presentation.WindowCreationCount}, renderers={presentation.RendererCreationCount}, window ID={(window == 0 ? 0 : Sdl.SDL_GetWindowID(window))}, size={renderer.Width}x{renderer.Height}.");
{ {
using var audio = Option(args, "--audio") is { } audioFile using var audio = Option(args, "--audio") is { } audioFile
? new SdlAudio(audioFile, args.Contains("--loop-audio"), debugMenu.Open) : null; ? new SdlAudio(audioFile, args.Contains("--loop-audio"), debugMenu.Open) : null;
using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null; using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null;
sceneAudio?.SetPaused(debugMenu.Open); sceneAudio?.SetPaused(debugMenu.Open);
if (gadgets != null)
{
gadgets.Sound += (id,loop) => sceneAudio?.Effect(id,loop ? "shrink-ray" : null);
gadgets.StopSound += () => sceneAudio?.StopLoop("shrink-ray");
}
if (gadgetScreen != null) gadgetScreen.Changed += () =>
{
gadgets?.Stop();
if (sceneAudio != null) sceneAudio.GameplayEffectsEnabled = !gadgetScreen.Open;
};
double initialPoseTime = 0; double initialPoseTime = 0;
if (director != null) if (director != null)
{ {
@@ -481,6 +540,7 @@ internal static class Program
sceneAudio.Music(originalStart!.Text("MusicDatabase") ?? "none", originalStart.Integer("MusicIndex", -1)); sceneAudio.Music(originalStart!.Text("MusicDatabase") ?? "none", originalStart.Integer("MusicIndex", -1));
} }
director.Begin(originalStart!, activateStartTrigger: !returning); director.Begin(originalStart!, activateStartTrigger: !returning);
gadgets?.Reset();
interactions!.Reset(); interactions!.Reset();
mechanisms!.Reset(); mechanisms!.Reset();
director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0)); director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0));
@@ -496,7 +556,8 @@ internal static class Program
Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}, retained player input order={simulation.InputAfterPlayerUpdate}, gadget availability={interactions.Inventory.State(0, 3)}."); Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}, retained player input order={simulation.InputAfterPlayerUpdate}, gadget availability={interactions.Inventory.State(0, 3)}.");
if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions"); if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions");
} }
if (args.Contains("--skip-intro") || jetpackSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); } if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (gadgetWindowSmoke) { interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3); }
if (controlPhaseSmoke) if (controlPhaseSmoke)
{ {
interactions.Inventory.SetState(0, 3, 1); interactions.Inventory.SelectGadget(3); interactions.Inventory.SetState(0, 3, 1); interactions.Inventory.SelectGadget(3);
@@ -554,7 +615,9 @@ internal static class Program
} }
for (var tick = 0; tick < (int)Math.Round(storyTime * 60) && !practice.Active && !debugMenu.Open; tick++) for (var tick = 0; tick < (int)Math.Round(storyTime * 60) && !practice.Active && !debugMenu.Open; tick++)
{ {
gadgets?.StepBodies(FixedStepClock.Step);
playerBinding!.Step(default); playerBinding!.Step(default);
gadgets?.StepTimers(FixedStepClock.Step);
interactions!.UpdateEnergy(simulation!.Energy); interactions!.UpdateEnergy(simulation!.Energy);
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step); foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
mechanisms!.Step(FixedStepClock.Step); mechanisms!.Step(FixedStepClock.Step);
@@ -563,10 +626,51 @@ internal static class Program
if (animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)) initialPoseTime = 0; if (animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)) initialPoseTime = 0;
initialPoseTime += FixedStepClock.Step; initialPoseTime += FixedStepClock.Step;
actorVisuals!.Update(FixedStepClock.Step, mesh); actorVisuals!.Update(FixedStepClock.Step, mesh);
soldierVisuals?.Update(FixedStepClock.Step,mesh);
spriteVisuals!.Step(FixedStepClock.Step); spriteVisuals!.Step(FixedStepClock.Step);
} }
if (args.Contains("--gadget-menu"))
{
interactions!.Inventory.SetState(0,3,1);
if (!gadgetScreen!.Toggle(director.Controlled && director.InventoryEnabled))
throw new InvalidOperationException("Gadget screen requires player control (--skip-intro)");
gadgetScreen.Point(new(200,380), level!.Code, storyTasks!.Get("SCENE"));
}
if (shrinkSmoke)
{
//Explicit test placement near an ACTUAL authored soldier.
//No invented targets or relocation of the soldier to entry.
for (var tick = 0; tick < 600; tick++) gadgets!.StepBodies(FixedStepClock.Step);
var floorQuery = new SceneCollision(world);
var sourceQuery = OriginalCameraRay.FromRouteScene(world,"VR04");
foreach (var soldier in gadgets!.Soldiers)
{
foreach (var direction in new[] {Vector3.UnitZ,-Vector3.UnitZ,Vector3.UnitX,-Vector3.UnitX})
{
var candidate = soldier.Actor.Position - direction * 500;
var floor = floorQuery.GroundHeight(candidate + Vector3.UnitY * 500,2500);
if (floor == null) continue;
candidate.Y = floor.Value + OriginalBodySupport.JimmyRadius * OriginalBodySupport.JimmyFactor;
if (soldier.Actor.Position.Y <= candidate.Y - 150 || soldier.Actor.Position.Y >= candidate.Y + 60
|| sourceQuery.TraceGeometry(candidate + Vector3.UnitY * 150,soldier.Actor.Position + Vector3.UnitY * 150) != null) continue;
var fixtureYaw = OriginalHeading.Degrees(soldier.Actor.Position - candidate);
var (viewSin,viewCos) = LabSimulation.Trig(fixtureYaw);
var fixtureEye = candidate + new Vector3(viewSin*350,180,-viewCos*350);
if (sourceQuery.TraceGeometry(fixtureEye,soldier.Actor.Position + Vector3.UnitY*25) != null) continue;
simulation!.ApplyAuthoredTransform(candidate,fixtureYaw);
simulation.RestoreReturnRoot(candidate); //Fixture camera snap at the explicitly moved player.
shrinkVictim = soldier; break;
}
if (shrinkVictim != null) break;
}
if (shrinkVictim == null) throw new InvalidOperationException("No supported source ray fixture near actual VR04 soldier");
interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3);
Console.WriteLine($"Shrink fixture: actual target={shrinkVictim.Actor.Tag}, target root={shrinkVictim.Actor.Position}, player root={simulation!.ActorRoot}.");
}
} }
var keys = new HashSet<uint>(); var keys = new HashSet<uint>();
var gadgetHeldKeys = new HashSet<uint>();
var gadgetArrows = new HashSet<uint>();
var debugCapturedKeys = new HashSet<uint>(); var debugCapturedKeys = new HashSet<uint>();
var running = true; var running = true;
var sawKey = false; var sawKey = false;
@@ -577,6 +681,7 @@ internal static class Program
var inspecting = !walking; var inspecting = !walking;
var active = presentation.HasInputFocus; var active = presentation.HasInputFocus;
var mouseJump = false; var mouseJump = false;
var mouseFire = false;
var stepClock = new FixedStepClock(); var stepClock = new FixedStepClock();
double poseTime = initialPoseTime; double poseTime = initialPoseTime;
var injectedInput = default(PlayerInput); var injectedInput = default(PlayerInput);
@@ -613,12 +718,16 @@ internal static class Program
var toolsEntry = simulation?.ActorRoot ?? Vector3.Zero; var toolsEntry = simulation?.ActorRoot ?? Vector3.Zero;
var controlEntry = simulation?.ActorRoot ?? Vector3.Zero; var controlEntry = simulation?.ActorRoot ?? Vector3.Zero;
var phasesLocked = false; var phasesResumed = false; var phasesLocked = false; var phasesResumed = false;
var gadgetChecks = new bool[7];
var gadgetEntry = simulation?.ActorRoot ?? Vector3.Zero;
var gadgetPausedSteps = 0;
void ResetScene() void ResetScene()
{ {
gadgetScreen?.Close();
if (simulation == null) { debugMenu.Message = "RESET REQUIRES PLAY MODE"; return; } if (simulation == null) { debugMenu.Message = "RESET REQUIRES PLAY MODE"; return; }
if (practice.Active) practice.Key(17, Vector2.Zero); if (practice.Active) practice.Key(17, Vector2.Zero);
simulation.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!); simulation.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!);
interactions?.Reset(); mechanisms?.Reset(); interactions?.Reset(); mechanisms?.Reset(); gadgets?.Reset(); mouseFire = false;
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0)); director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
} }
void ToggleCamera() void ToggleCamera()
@@ -632,6 +741,8 @@ internal static class Program
} }
void DebugInputBoundary() void DebugInputBoundary()
{ {
gadgetArrows.Clear();
gadgets?.Stop(); mouseFire = false;
debugCapturedKeys.UnionWith(keys); debugCapturedKeys.UnionWith(keys);
keys.Clear(); mouseJump = false; stepClock.Reset(); last = clock.Elapsed.TotalSeconds; keys.Clear(); mouseJump = false; stepClock.Reset(); last = clock.Elapsed.TotalSeconds;
audio?.SetPaused(debugMenu.Open); sceneAudio?.SetPaused(debugMenu.Open); audio?.SetPaused(debugMenu.Open); sceneAudio?.SetPaused(debugMenu.Open);
@@ -757,6 +868,33 @@ internal static class Program
} }
while (running) while (running)
{ {
if (gadgetWindowSmoke)
{
void Key(uint key,bool down) { var e=new Sdl.Event {Type=down?Sdl.KeyDown:Sdl.KeyUp,Scancode=key,Down=down?(byte)1:(byte)0};
if(!Sdl.SDL_PushEvent(ref e))throw new InvalidOperationException(Sdl.Error); }
void Click(bool down) { var e=new Sdl.Event {Type=down?Sdl.MouseButtonDown:Sdl.MouseButtonUp,MouseButton=1};
if(!Sdl.SDL_PushEvent(ref e))throw new InvalidOperationException(Sdl.Error); }
void Aim(Vector2 point) { Sdl.SDL_GetWindowSize(window,out var w,out var h);var v=new UiViewport(renderer.Width,renderer.Height);
var p=v.ToNdc(point+v.CenterOffset);Sdl.SDL_WarpMouseInWindow(window,(p.X+1)*w/2,(p.Y+1)*h/2); }
if(count==0)Key(43,true);
if(count==1){gadgetPausedSteps=simulation!.Steps;Key(44,true);}
if(count==2){gadgetChecks[0]=gadgetScreen!.Open&&simulation!.Steps==gadgetPausedSteps;Key(43,false);}
if(count==3){gadgetChecks[1]=gadgetScreen!.Open&&simulation!.Steps==gadgetPausedSteps;Key(41,true);}
if(count==4){gadgetChecks[2]=!gadgetScreen!.Open&&running;Key(41,false);Key(44,false);Key(43,true);}
if(count==5){Aim(new(200,380));Key(40,true);}
if(count==6){gadgetChecks[3]=!gadgetScreen!.Open&&interactions!.Inventory.SelectedGadget==3
&&simulation!.GadgetMode==-1&&gadgets?.Ray.Visible!=true;Key(40,false);Key(43,false);Key(43,true);}
if(count==7){Aim(new(520,120));Click(true);}
if(count==8){gadgetChecks[4]=gadgetScreen!.PracticeArmed;Click(false);Aim(new(50,120));Click(true);}
if(count==9){gadgetChecks[5]=!gadgetScreen!.Open&&!gadgetScreen.PracticeArmed&&transitionRequest==null;Key(43,false);Click(false);}
if(count==11){gadgetChecks[6]=simulation!.Jumps==0&&gadgets?.Ray.Visible!=true
&&Vector3.Distance(simulation.ActorRoot,gadgetEntry)<.1f;Key(43,true);Aim(new(200,380));}
}
if (shrinkSmoke && !headless && count == 0)
{
var fire = new Sdl.Event {Type=Sdl.KeyDown,Scancode=224,Down=1};
if (!Sdl.SDL_PushEvent(ref fire)) throw new InvalidOperationException(Sdl.Error);
}
if ((walkSmoke || jetpackSmoke) && !headless) if ((walkSmoke || jetpackSmoke) && !headless)
{ {
var requested = jetpackSmoke ? LabSimulation.JetpackSmokeInput(simulation!.Steps) var requested = jetpackSmoke ? LabSimulation.JetpackSmokeInput(simulation!.Steps)
@@ -779,9 +917,10 @@ internal static class Program
if (e.Type is Sdl.Quit or 0x210) running = false; if (e.Type is Sdl.Quit or 0x210) running = false;
if (e.Type is Sdl.WindowResized or Sdl.WindowPixelSizeChanged) renderer.Resize(); if (e.Type is Sdl.WindowResized or Sdl.WindowPixelSizeChanged) renderer.Resize();
if (e.Type is Sdl.WindowFocusLost or Sdl.WindowMinimized) if (e.Type is Sdl.WindowFocusLost or Sdl.WindowMinimized)
{ keys.Clear(); debugCapturedKeys.Clear(); mouseJump = false; active = false; stepClock.Reset(); } { keys.Clear(); debugCapturedKeys.Clear(); gadgetHeldKeys.Clear(); gadgetArrows.Clear(); mouseJump = mouseFire = false; gadgets?.Stop(); active = false; stepClock.Reset(); }
if (e.Type is Sdl.WindowFocusGained or Sdl.WindowRestored) if (e.Type is Sdl.WindowFocusGained or Sdl.WindowRestored)
{ active = true; stepClock.Reset(); last = clock.Elapsed.TotalSeconds; } { active = true; stepClock.Reset(); last = clock.Elapsed.TotalSeconds; }
if (e.Type == Sdl.KeyUp) { gadgetHeldKeys.Remove(e.Scancode); gadgetArrows.Remove(e.Scancode); }
if (e.Type == Sdl.KeyUp && debugCapturedKeys.Remove(e.Scancode)) continue; if (e.Type == Sdl.KeyUp && debugCapturedKeys.Remove(e.Scancode)) continue;
if (e.Type == Sdl.KeyDown && !debugMenu.Open && debugCapturedKeys.Contains(e.Scancode)) continue; if (e.Type == Sdl.KeyDown && !debugMenu.Open && debugCapturedKeys.Contains(e.Scancode)) continue;
if (e.Type == Sdl.KeyDown && e.Scancode == DebugDiagnostics.ToggleKey) if (e.Type == Sdl.KeyDown && e.Scancode == DebugDiagnostics.ToggleKey)
@@ -813,13 +952,36 @@ internal static class Program
continue; continue;
} }
if (practice.Active && e.Type == Sdl.MouseButtonDown) if (practice.Active && e.Type == Sdl.MouseButtonDown)
{ if (e.MouseButton == 1) practice.Click(Pointer()); keys.Clear(); mouseJump = false; stepClock.Reset(); continue; } { if (e.MouseButton == 1) practice.Click(Pointer()); keys.Clear(); mouseJump = mouseFire = false; stepClock.Reset(); continue; }
if (practice.Active && e.Type == Sdl.KeyDown) if (practice.Active && e.Type == Sdl.KeyDown)
{ {
if (e.Repeat == 0) practice.Key(e.Scancode, Pointer()); if (e.Repeat == 0) practice.Key(e.Scancode, Pointer());
if (practiceWindowSmoke && e.Scancode == 17 && !practice.Active) sawPracticeDismiss = true; if (practiceWindowSmoke && e.Scancode == 17 && !practice.Active) sawPracticeDismiss = true;
keys.Clear(); mouseJump = false; stepClock.Reset(); continue; keys.Clear(); mouseJump = mouseFire = false; stepClock.Reset(); continue;
} }
if (e.Type == Sdl.KeyDown && e.Scancode is 43 or 44
&& !inspecting && simulation?.Noclip != true && !practice.Active && gadgetScreen != null
&& (gadgetScreen.Open || director is { Controlled: true, InventoryEnabled: true }))
{
var first = gadgetHeldKeys.Count == 0;
gadgetHeldKeys.Add(e.Scancode);
if (first && e.Repeat == 0) gadgetScreen.Toggle(director is { Controlled: true, InventoryEnabled: true });
debugCapturedKeys.UnionWith(keys);
keys.Clear(); mouseJump = mouseFire = false; stepClock.Reset(); continue;
}
if (gadgetScreen?.Open == true)
{
if (e.Type == Sdl.KeyDown && e.Scancode is >= 79 and <= 82) gadgetArrows.Add(e.Scancode);
gadgetScreen.Point(Pointer(),level!.Code,storyTasks!.Get("SCENE"));
if (e.Type == Sdl.KeyDown) debugCapturedKeys.Add(e.Scancode);
if (e.Type == Sdl.KeyDown && e.Repeat == 0 && e.Scancode == 41) gadgetScreen.Close();
else if (e.Type == Sdl.MouseButtonDown && e.MouseButton is 1 or 3
|| e.Type == Sdl.KeyDown && e.Repeat == 0 && e.Scancode is 40 or 88 or 224 or 228 or 225 or 229 or 73 or 98)
gadgetScreen.Activate(level.Code,storyTasks.Get("SCENE"));
keys.Clear(); mouseJump = mouseFire = false; stepClock.Reset(); continue;
}
if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 1) mouseFire = true;
if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 1) mouseFire = false;
if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 3) if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 3)
{ {
mouseJump = true; mouseJump = true;
@@ -828,6 +990,7 @@ internal static class Program
if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 3) mouseJump = false; if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 3) mouseJump = false;
if (e.Type == Sdl.KeyDown) if (e.Type == Sdl.KeyDown)
{ {
if (shrinkSmoke && e.Scancode == 224) sawShrinkKey = true;
keys.Add(e.Scancode); keys.Add(e.Scancode);
if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == jumpScancode ? 4 : 0; if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == jumpScancode ? 4 : 0;
if (jetpackSmoke) sawJetpackKeys |= e.Scancode == 82 ? 1 : e.Scancode == 81 ? 2 : e.Scancode == 80 ? 4 : e.Scancode == jumpScancode ? 8 : 0; if (jetpackSmoke) sawJetpackKeys |= e.Scancode == 82 ? 1 : e.Scancode == 81 ? 2 : e.Scancode == 80 ? 4 : e.Scancode == jumpScancode ? 8 : 0;
@@ -861,24 +1024,41 @@ internal static class Program
var elapsed = now - last; var elapsed = now - last;
var dt = (float)Math.Min(elapsed, 0.1); var dt = (float)Math.Min(elapsed, 0.1);
last = now; last = now;
if (debugMenu.Open) animationStarted += elapsed; if (gadgetScreen?.Open == true && !headless && !debugMenu.Open)
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && (active || headless || walkSmoke || jetpackSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
{ {
var steps = headless || walkSmoke || jetpackSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed); var axis = new Vector2((gadgetArrows.Contains(79) ? 1 : 0) - (gadgetArrows.Contains(80) ? 1 : 0),
(gadgetArrows.Contains(81) ? 1 : 0) - (gadgetArrows.Contains(82) ? 1 : 0));
var point = Pointer();
var moved = gadgetScreen.MovePointer(point,axis,dt);
if (moved != point && Sdl.SDL_GetWindowSize(window,out var menuWidth,out var menuHeight))
{
var viewport = new UiViewport(renderer.Width,renderer.Height);
var ndc = viewport.ToNdc(moved + viewport.CenterOffset);
Sdl.SDL_WarpMouseInWindow(window,(ndc.X + 1) * menuWidth / 2,(ndc.Y + 1) * menuHeight / 2);
}
}
if (debugMenu.Open) animationStarted += elapsed;
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
{
var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed);
for (var step = 0; step < steps; step++) for (var step = 0; step < steps; step++)
{ {
var input = carlSmoke || controlPhaseSmoke ? new PlayerInput(true, false, true, false, true) var input = carlSmoke || controlPhaseSmoke ? new PlayerInput(true, false, true, false, true)
: shrinkSmoke && headless ? new PlayerInput(false,false,false,false,false,Fire:true)
: jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps) : jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps)
: walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput( : walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput(
keys.Contains(82) || simulation.Noclip && keys.Contains(26), keys.Contains(81) || simulation.Noclip && keys.Contains(22), keys.Contains(80), keys.Contains(79), keys.Contains(82) || simulation.Noclip && keys.Contains(26), keys.Contains(81) || simulation.Noclip && keys.Contains(22), keys.Contains(80), keys.Contains(79),
mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98), mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98),
keys.Contains(44) || keys.Contains(8), keys.Contains(224) || keys.Contains(228) || keys.Contains(20), keys.Contains(44) || keys.Contains(8), keys.Contains(224) || keys.Contains(228) || keys.Contains(20),
keys.Contains(4), keys.Contains(7), keys.Contains(225) || keys.Contains(229)); keys.Contains(4), keys.Contains(7), keys.Contains(225) || keys.Contains(229),
mouseFire || keys.Contains(40) || keys.Contains(88) || keys.Contains(224) || keys.Contains(228));
gadgets?.StepBodies(FixedStepClock.Step);
var before = simulation.Position; var before = simulation.Position;
var powered = simulation.JetpackEffectVisible && !simulation.Grounded; var powered = simulation.JetpackEffectVisible && !simulation.Grounded;
bool acceptsInput; bool acceptsInput;
if (playerBinding != null) acceptsInput = playerBinding.Step(input); if (playerBinding != null) acceptsInput = playerBinding.Step(input);
else { simulation.Step(input); acceptsInput = true; } else { simulation.Step(input); acceptsInput = true; }
gadgets?.StepTimers(FixedStepClock.Step);
if (jetpackSmoke && powered) if (jetpackSmoke && powered)
{ {
poweredAirTravel += Vector2.Distance(new(before.X, before.Z), new(simulation.Position.X, simulation.Position.Z)); poweredAirTravel += Vector2.Distance(new(before.X, before.Z), new(simulation.Position.X, simulation.Position.Z));
@@ -906,6 +1086,7 @@ internal static class Program
if (switched) poseTime = 0; if (switched) poseTime = 0;
poseTime += FixedStepClock.Step; poseTime += FixedStepClock.Step;
actorVisuals?.Update(FixedStepClock.Step, mesh); actorVisuals?.Update(FixedStepClock.Step, mesh);
soldierVisuals?.Update(FixedStepClock.Step,mesh);
spriteVisuals?.Step(FixedStepClock.Step); spriteVisuals?.Step(FixedStepClock.Step);
} }
characterModel = simulation.Model; characterModel = simulation.Model;
@@ -938,13 +1119,22 @@ internal static class Program
renderEye = storyEye; renderTarget = storyTarget; renderEye = storyEye; renderTarget = storyTarget;
} }
staticVisuals?.Update(mesh); staticVisuals?.Update(mesh);
if (debugMenu.Open || inspecting || practice.Active || director?.Controlled == false) gadgets?.Stop();
soldierVisuals?.Update(0,mesh);
if (gadgets != null) rayVisuals!.Update(mesh,gadgets.Ray,simulation!.Steps / 60d);
if (shrinkSmoke && gadgets!.Ray.Visible) shrinkPhaseMask |= 1 << gadgets.Ray.TexturePhase;
jetpackVisuals?.Update(mesh, simulation!); jetpackVisuals?.Update(mesh, simulation!);
spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh); spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh);
objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true
&& director is { Controlled: true, InventoryEnabled: true }); && director is { Controlled: true, InventoryEnabled: true });
objectivePanel?.Step(0, director?.ControlledTag != null, practice.Active); objectivePanel?.Step(0, director?.ControlledTag != null, practice.Active);
hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && objectivePanel!.PadVisible, hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && objectivePanel!.PadVisible && gadgetScreen?.Open != true,
practice.Active, objectivePanel!.YOffset, objectivePanel.ContentVisible, renderer.Width, renderer.Height); practice.Active, objectivePanel!.YOffset, objectivePanel.ContentVisible, renderer.Width, renderer.Height);
if (gadgetScreen != null)
{
if (!headless) gadgetScreen.Point(Pointer(),level!.Code,storyTasks!.Get("SCENE"));
gadgetOverlay!.Update(mesh,gadgetScreen.Canvases(level!.Code,storyTasks!.Get("SCENE")),renderer.Width,renderer.Height);
}
var gameplayProjection = originalCamera || simulation != null && !inspecting; var gameplayProjection = originalCamera || simulation != null && !inspecting;
var cameraMode = simulation?.Noclip == true && !inspecting ? "NOCLIP" : !inspecting && director?.CameraEye != null ? "CUTSCENE" var cameraMode = simulation?.Noclip == true && !inspecting ? "NOCLIP" : !inspecting && director?.CameraEye != null ? "CUTSCENE"
: simulation != null && !inspecting ? "GAMEPLAY" : originalCamera ? "STRT" : "ORBIT"; : simulation != null && !inspecting ? "GAMEPLAY" : originalCamera ? "STRT" : "ORBIT";
@@ -1253,6 +1443,18 @@ internal static class Program
if (simulation.Bursts == 0 || simulation.MaximumRise <= 137.62f || !simulation.Grounded if (simulation.Bursts == 0 || simulation.MaximumRise <= 137.62f || !simulation.Grounded
|| poweredAirTravel <= 20 || !poweredAirTurn || !headless && (sawJetpackKeys != 15 || !didResize)) return 2; || poweredAirTravel <= 20 || !poweredAirTurn || !headless && (sawJetpackKeys != 15 || !didResize)) return 2;
} }
if (shrinkSmoke)
{
var renderedHeight = soldierVisuals!.RenderedHeight(shrinkVictim!.Actor.Tag,mesh);
Console.WriteLine($"Shrink ray: target={shrinkVictim.Actor.Tag}, hits={gadgets!.ShrinkHits}, shrunk={shrinkVictim.Shrunk}, height={renderedHeight:F3}, remaining={shrinkVictim.Remaining:F3}, beam={gadgets.Ray.Visible}, phases={shrinkPhaseMask}, energy={simulation!.Energy:F3}, SDL fire={sawShrinkKey}.");
if (!shrinkVictim.Shrunk || gadgets.ShrinkHits < 1 || renderedHeight > 60 || !gadgets.Ray.Visible || shrinkPhaseMask != 7
|| simulation.Energy != 20 || !headless && !sawShrinkKey) return 2;
}
if (gadgetWindowSmoke)
{
Console.WriteLine($"Gadget menu SDL: shared-edge={gadgetChecks[0]}, pause={gadgetChecks[1]}, Escape={gadgetChecks[2]}, selection/fire-capture={gadgetChecks[3]}, practice={gadgetChecks[4]}, Return={gadgetChecks[5]}, stable-root={gadgetChecks[6]}.");
if (!gadgetChecks.All(c=>c)) return 2;
}
if (director != null) if (director != null)
{ {
Console.WriteLine($"Scene sequence: {director.CurrentTag ?? "none"}, shot={director.CurrentShot}, control={director.Controlled}, blocked={director.Blocked}, issues={director.Issues.Count}."); Console.WriteLine($"Scene sequence: {director.CurrentTag ?? "none"}, shot={director.CurrentShot}, control={director.Controlled}, blocked={director.Blocked}, issues={director.Issues.Count}.");
+4 -1
View File
@@ -2,9 +2,12 @@
layout(location=0) in vec2 texCoord; layout(location=0) in vec2 texCoord;
layout(location=1) in vec3 vertexColor; layout(location=1) in vec3 vertexColor;
layout(binding=0) uniform sampler2D diffuseMap; layout(binding=0) uniform sampler2D diffuseMap;
layout(push_constant) uniform Material {
layout(offset=64) float opacity;
} material;
layout(location=0) out vec4 outColor; layout(location=0) out vec4 outColor;
void main() { void main() {
vec4 diffuse = texture(diffuseMap, texCoord); vec4 diffuse = texture(diffuseMap, texCoord);
if (diffuse.a < 0.5) discard; if (diffuse.a < 0.5) discard;
outColor = vec4(diffuse.rgb * vertexColor, diffuse.a); outColor = vec4(diffuse.rgb * vertexColor, diffuse.a * material.opacity);
} }
Binary file not shown.
@@ -29,7 +29,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
private ImageView colorView,depthView; private ImageView colorView,depthView;
private RenderPass renderPass; private RenderPass renderPass;
private Framebuffer framebuffer; private Framebuffer framebuffer;
private Pipeline pipeline,overlayPipeline; private Pipeline pipeline,overlayPipeline,alphaPipeline,additivePipeline,overlayAlphaPipeline,overlayAdditivePipeline;
private PipelineLayout pipelineLayout; private PipelineLayout pipelineLayout;
private DescriptorSetLayout descriptorLayout; private DescriptorSetLayout descriptorLayout;
private DescriptorPool descriptorPool; private DescriptorPool descriptorPool;
@@ -130,6 +130,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
throw new ArgumentException("Scene requires nonempty, bounded triangle geometry.",nameof(mesh)); throw new ArgumentException("Scene requires nonempty, bounded triangle geometry.",nameof(mesh));
if(mesh.Draws.Any(d=>(ulong)d.FirstIndex+d.IndexCount>(ulong)mesh.Indices.Length)) if(mesh.Draws.Any(d=>(ulong)d.FirstIndex+d.IndexCount>(ulong)mesh.Indices.Length))
throw new ArgumentException("Scene draw exceeds index buffer.",nameof(mesh)); throw new ArgumentException("Scene draw exceeds index buffer.",nameof(mesh));
ValidateDrawMaterials(mesh.Draws);
ValidateTexture(fallback); ValidateTexture(fallback);
foreach(var image in mesh.Textures.Values)ValidateTexture(image); foreach(var image in mesh.Textures.Values)ValidateTexture(image);
@@ -142,6 +143,17 @@ public sealed unsafe class VulkanRenderer : IDisposable
} }
} }
private static void ValidateDrawMaterials(MeshDraw[] draws)
{
foreach(var draw in draws)
{
if(!float.IsFinite(draw.Opacity) || draw.Opacity<0 || draw.Opacity>1)
throw new ArgumentException("Draw opacity must be finite and between zero and one.",nameof(draws));
if(draw.Blend is not (MeshBlend.Opaque or MeshBlend.Alpha or MeshBlend.Additive))
throw new ArgumentException("Draw blend mode is invalid.",nameof(draws));
}
}
private SceneResources DetachScene() private SceneResources DetachScene()
{ {
var scene=new SceneResources(mesh,vertexBuffer,vertexMemory,indexBuffer,indexMemory, var scene=new SceneResources(mesh,vertexBuffer,vertexMemory,indexBuffer,indexMemory,
@@ -425,7 +437,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
var vertex=Shader("mesh.vert.spv");var fragment=Shader("mesh.frag.spv");var main=Marshal.StringToCoTaskMemUTF8("main"); var vertex=Shader("mesh.vert.spv");var fragment=Shader("mesh.frag.spv");var main=Marshal.StringToCoTaskMemUTF8("main");
try try
{ {
var push=new PushConstantRange(ShaderStageFlags.VertexBit,0,64);var dl=descriptorLayout; var push=new PushConstantRange(ShaderStageFlags.VertexBit|ShaderStageFlags.FragmentBit,0,68);var dl=descriptorLayout;
var layout=new PipelineLayoutCreateInfo{SType=StructureType.PipelineLayoutCreateInfo,SetLayoutCount=1,PSetLayouts=&dl,PushConstantRangeCount=1,PPushConstantRanges=&push}; var layout=new PipelineLayoutCreateInfo{SType=StructureType.PipelineLayoutCreateInfo,SetLayoutCount=1,PSetLayouts=&dl,PushConstantRangeCount=1,PPushConstantRanges=&push};
Check(vk.CreatePipelineLayout(device,&layout,null,out pipelineLayout),"CreatePipelineLayout"); Check(vk.CreatePipelineLayout(device,&layout,null,out pipelineLayout),"CreatePipelineLayout");
var stages=stackalloc PipelineShaderStageCreateInfo[2]; var stages=stackalloc PipelineShaderStageCreateInfo[2];
@@ -450,6 +462,23 @@ public sealed unsafe class VulkanRenderer : IDisposable
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out pipeline),"CreateGraphicsPipeline"); Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out pipeline),"CreateGraphicsPipeline");
ds.DepthTestEnable=false;ds.DepthWriteEnable=false; ds.DepthTestEnable=false;ds.DepthWriteEnable=false;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayPipeline),"CreateOverlayPipeline"); Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayPipeline),"CreateOverlayPipeline");
// Blended world geometry tests opaque depth but does not write it.
// Preserve draw order; general transparent-surface sorting is separate work.
blendAttachment.BlendEnable=true;
blendAttachment.SrcColorBlendFactor=BlendFactor.SrcAlpha;
blendAttachment.DstColorBlendFactor=BlendFactor.OneMinusSrcAlpha;
blendAttachment.ColorBlendOp=BlendOp.Add;
blendAttachment.SrcAlphaBlendFactor=BlendFactor.SrcAlpha;
blendAttachment.DstAlphaBlendFactor=BlendFactor.OneMinusSrcAlpha;
blendAttachment.AlphaBlendOp=BlendOp.Add;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayAlphaPipeline),"CreateOverlayAlphaPipeline");
ds.DepthTestEnable=true;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out alphaPipeline),"CreateAlphaPipeline");
blendAttachment.DstColorBlendFactor=BlendFactor.One;
blendAttachment.DstAlphaBlendFactor=BlendFactor.One;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out additivePipeline),"CreateAdditivePipeline");
ds.DepthTestEnable=false;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayAdditivePipeline),"CreateOverlayAdditivePipeline");
} }
finally{Marshal.FreeCoTaskMem(main);vk.DestroyShaderModule(device,vertex,null);vk.DestroyShaderModule(device,fragment,null);} finally{Marshal.FreeCoTaskMem(main);vk.DestroyShaderModule(device,vertex,null);vk.DestroyShaderModule(device,fragment,null);}
} }
@@ -502,6 +531,9 @@ public sealed unsafe class VulkanRenderer : IDisposable
} }
public void Render(Matrix4x4 mvp) public void Render(Matrix4x4 mvp)
{ {
// Draw materials are mutable between frames. Reject invalid state before
// acquiring an image or beginning a command buffer, even on hidden draws.
ValidateDrawMaterials(mesh.Draws);
uint imageIndex=0; uint imageIndex=0;
if(window!=0) if(window!=0)
{ {
@@ -517,14 +549,30 @@ public sealed unsafe class VulkanRenderer : IDisposable
vk.CmdSetViewport(command,0,1,&viewport);vk.CmdSetScissor(command,0,1,&scissor); vk.CmdSetViewport(command,0,1,&viewport);vk.CmdSetScissor(command,0,1,&scissor);
var vb=vertexBuffer;ulong offset=0;vk.CmdBindVertexBuffers(command,0,1,&vb,&offset);vk.CmdBindIndexBuffer(command,indexBuffer,0,IndexType.Uint32); var vb=vertexBuffer;ulong offset=0;vk.CmdBindVertexBuffers(command,0,1,&vb,&offset);vk.CmdBindIndexBuffer(command,indexBuffer,0,IndexType.Uint32);
var draws=mesh.HasExplicitDraws?mesh.Draws:[new MeshDraw(0,(uint)mesh.Indices.Length,-1)]; var draws=mesh.HasExplicitDraws?mesh.Draws:[new MeshDraw(0,(uint)mesh.Indices.Length,-1)];
foreach(var screenSpace in new[]{false,true}) // Opaque world first, blended world second, UI last. Within each pass,
// retain source order so existing UI composition remains unchanged.
for(var pass=0;pass<3;pass++)
{ {
vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,screenSpace?overlayPipeline:pipeline); var screenSpace=pass==2;
var transform=screenSpace?Matrix4x4.Identity:mvp; var transform=screenSpace?Matrix4x4.Identity:mvp;
vk.CmdPushConstants(command,pipelineLayout,ShaderStageFlags.VertexBit,0,64,&transform); var stages=ShaderStageFlags.VertexBit|ShaderStageFlags.FragmentBit;
vk.CmdPushConstants(command,pipelineLayout,stages,0,64,&transform);
foreach(var draw in draws) foreach(var draw in draws)
{ {
if (!draw.Visible || draw.ScreenSpace!=screenSpace) continue; if (!draw.Visible || draw.ScreenSpace!=screenSpace) continue;
if(!screenSpace && (draw.Blend==MeshBlend.Opaque)!=(pass==0))continue;
var selectedPipeline=(screenSpace,draw.Blend) switch
{
(false,MeshBlend.Alpha)=>alphaPipeline,
(false,MeshBlend.Additive)=>additivePipeline,
(true,MeshBlend.Alpha)=>overlayAlphaPipeline,
(true,MeshBlend.Additive)=>overlayAdditivePipeline,
(true,_)=>overlayPipeline,
_=>pipeline
};
vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,selectedPipeline);
var opacity=draw.Opacity;
vk.CmdPushConstants(command,pipelineLayout,stages,64,4,&opacity);
var descriptor=descriptors.GetValueOrDefault(draw.TextureId,descriptors[-1]); var descriptor=descriptors.GetValueOrDefault(draw.TextureId,descriptors[-1]);
vk.CmdBindDescriptorSets(command,PipelineBindPoint.Graphics,pipelineLayout,0,1,&descriptor,0,null); vk.CmdBindDescriptorSets(command,PipelineBindPoint.Graphics,pipelineLayout,0,1,&descriptor,0,null);
vk.CmdDrawIndexed(command,draw.IndexCount,1,draw.FirstIndex,0,0); vk.CmdDrawIndexed(command,draw.IndexCount,1,draw.FirstIndex,0,0);
@@ -565,6 +613,10 @@ public sealed unsafe class VulkanRenderer : IDisposable
DestroyTarget(); DestroyTarget();
if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null); if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null);
if(overlayPipeline.Handle!=0)vk.DestroyPipeline(device,overlayPipeline,null); if(overlayPipeline.Handle!=0)vk.DestroyPipeline(device,overlayPipeline,null);
if(alphaPipeline.Handle!=0)vk.DestroyPipeline(device,alphaPipeline,null);
if(additivePipeline.Handle!=0)vk.DestroyPipeline(device,additivePipeline,null);
if(overlayAlphaPipeline.Handle!=0)vk.DestroyPipeline(device,overlayAlphaPipeline,null);
if(overlayAdditivePipeline.Handle!=0)vk.DestroyPipeline(device,overlayAdditivePipeline,null);
if(pipelineLayout.Handle!=0)vk.DestroyPipelineLayout(device,pipelineLayout,null); if(pipelineLayout.Handle!=0)vk.DestroyPipelineLayout(device,pipelineLayout,null);
if(renderPass.Handle!=0)vk.DestroyRenderPass(device,renderPass,null); if(renderPass.Handle!=0)vk.DestroyRenderPass(device,renderPass,null);
DestroySceneResources(); DestroySceneResources();
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks><EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Assets/Mesh.cs" />
<Compile Include="../../src/GamePort/Assets/PngImage.cs" />
<Compile Include="../../src/GamePort/Platform/Sdl.cs" />
<Compile Include="../../src/GamePort/Rendering/Vulkan/VulkanRenderer.cs" />
<PackageReference Include="Silk.NET.Vulkan" Version="2.23.0" />
<PackageReference Include="Silk.NET.Vulkan.Extensions.KHR" Version="2.23.0" />
<PackageReference Include="Silk.NET.Vulkan.Extensions.EXT" Version="2.23.0" />
<Content Include="../../src/GamePort/Rendering/Shaders/*.spv" CopyToOutputDirectory="PreserveNewest" Link="Shaders/%(Filename)%(Extension)" />
</ItemGroup>
</Project>
+85
View File
@@ -0,0 +1,85 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Rendering.Vulkan;
// These tests read back actual Vulkan color attachments. No window or original
// executable is needed. The source-linked project avoids rebuilding GamePort.
var white=PngImage.White;
var count=0;
using var renderer=new VulkanRenderer(Scene(new Layer(Vector3.UnitZ,.8f)),white,64,64,validation:true);
Console.WriteLine($"Blend test GPU: {renderer.DeviceName}");
Check("opaque default",Scene(new Layer(Vector3.UnitX,.4f)),255,0,0);
Check("alpha half opacity",Scene(new(Vector3.UnitX,.4f,MeshBlend.Alpha,.5f),new(Vector3.UnitZ,.8f)),128,0,128);
Check("additive half opacity",Scene(new(Vector3.UnitX,.4f,MeshBlend.Additive,.5f),new(Vector3.UnitZ,.8f)),128,0,255);
Check("opaque depth occludes blend",Scene(new(Vector3.UnitX,.4f,MeshBlend.Alpha,.5f),new(Vector3.UnitZ,.2f)),0,0,255);
Check("blend does not write depth",Scene(new(Vector3.UnitX,.2f,MeshBlend.Alpha,.5f),new(Vector3.UnitY,.4f,MeshBlend.Alpha,.5f),new(Vector3.UnitZ,.8f)),64,128,64);
Check("UI follows blended world",Scene(new(Vector3.UnitY,.9f,Screen:true),new(Vector3.UnitX,.4f,MeshBlend.Additive,.5f),new(Vector3.UnitZ,.8f)),0,255,0);
Check("UI alpha ignores depth",Scene(new(Vector3.UnitX,.9f,MeshBlend.Alpha,.5f,true),new(Vector3.UnitZ,.2f)),128,0,128);
Check("UI additive ignores depth",Scene(new(Vector3.UnitX,.9f,MeshBlend.Additive,.5f,true),new(Vector3.UnitZ,.2f)),128,0,255);
Check("zero opacity",Scene(new(Vector3.UnitX,.4f,MeshBlend.Alpha,0),new(Vector3.UnitZ,.8f)),0,0,255);
// Texture coverage is tested before material opacity: a solid texture at .5
// opacity must draw, while a cutout remains absent even at full opacity.
var cutout=Scene(new(Vector3.UnitX,.4f,MeshBlend.Alpha,.5f),new(Vector3.UnitZ,.8f));
cutout.Draws[0]=cutout.Draws[0] with {TextureId=7};
cutout.Textures[7]=new PngImage(1,1,[255,255,255,0]);
Check("texture cutout unchanged",cutout,0,0,255);
var invalid=Scene(new Layer(Vector3.UnitX,.4f));
renderer.ReplaceScene(invalid,white);
foreach(var opacity in new[]{float.NaN,float.PositiveInfinity,-.01f,1.01f})
{
invalid.Draws[0].Opacity=opacity;
Throws("invalid mutable opacity",()=>renderer.Render(Matrix4x4.Identity));
}
invalid.Draws[0].Opacity=1;
invalid.Draws[0].Blend=(MeshBlend)99;
invalid.Draws[0].Visible=false;
Throws("invalid hidden blend",()=>renderer.Render(Matrix4x4.Identity));
Throws("replacement rejects invalid blend",()=>renderer.ReplaceScene(invalid,white));
invalid.Draws[0].Blend=MeshBlend.Opaque;
invalid.Draws[0].Visible=true;
renderer.Render(Matrix4x4.Identity);
AssertPixel("renderer usable after rejected state",255,0,0);
if(renderer.ValidationErrors!=0)throw new Exception($"Vulkan reported {renderer.ValidationErrors} validation errors.");
if(args.Length>0)renderer.SavePpm(args[0]);
Console.WriteLine($"PASS: {count} Vulkan material/readback checks; validation errors: {renderer.ValidationErrors}.");
void Check(string name,Mesh scene,int r,int g,int b)
{
renderer.ReplaceScene(scene,white);
renderer.Render(Matrix4x4.Identity);
AssertPixel(name,r,g,b);
}
void AssertPixel(string name,int r,int g,int b)
{
var pixels=renderer.ReadPixels();
var offset=(32*64+32)*4;
var expected=new[]{r,g,b};
for(var channel=0;channel<3;channel++)
if(Math.Abs(pixels[offset+channel]-expected[channel])>2)
throw new Exception($"{name}: expected ({r},{g},{b}), got ({pixels[offset]},{pixels[offset+1]},{pixels[offset+2]}).");
count++;
Console.WriteLine($"PASS: {name}");
}
void Throws(string name,Action action)
{
try {action();}
catch(ArgumentException){count++;Console.WriteLine($"PASS: {name}");return;}
throw new Exception($"{name}: expected ArgumentException.");
}
static Mesh Scene(params Layer[] layers)
{
var vertices=new List<MeshVertex>();var indices=new List<uint>();var draws=new List<MeshDraw>();
foreach(var layer in layers)
{
uint start=(uint)vertices.Count,first=(uint)indices.Count;
foreach(var xy in new[]{new Vector2(-1,-1),new Vector2(1,-1),new Vector2(1,1),new Vector2(-1,1)})
vertices.Add(new MeshVertex(new Vector3(xy,layer.Z),new Vector2(.5f),layer.Color));
indices.AddRange(new[]{start,start+1,start+2,start+2,start+3,start});
draws.Add(new MeshDraw(first,6,-1){Blend=layer.Blend,Opacity=layer.Opacity,ScreenSpace=layer.Screen});
}
return new Mesh(vertices.ToArray(),indices.ToArray()){HasExplicitDraws=true,Draws=draws.ToArray()};
}
readonly record struct Layer(Vector3 Color,float Z,MeshBlend Blend=MeshBlend.Opaque,float Opacity=1,bool Screen=false);
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
<ItemGroup><Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Assets/*.cs" />
<Compile Include="../../src/GamePort/Game/*.cs" />
</ItemGroup>
</Project>
+123
View File
@@ -0,0 +1,123 @@
using System.Numerics;
using GamePort.Game;
using GamePort.Assets;
void Check(bool value, string message) { if (!value) throw new Exception(message); }
void Near(Vector3 actual, Vector3 expected, string message) =>
Check(Vector3.Distance(actual,expected)<.002f,$"{message}: {actual} != {expected}");
var floor=new CameraRayPolygon(new(new(-1000,0,-1000),new(1000,0,-1000),new(0,0,1000)),Vector3.UnitY);
var physics=new OriginalBodyPhysics(new([floor]));
OrdinaryBodyState Initial() => new(new(0,75.9f,0),Vector3.Zero,Vector3.Zero,Vector3.Zero);
// References observed from copied479D20/support, body-probe/wine.log.
var cases=new (string Name,OrdinaryBodyState Input,Vector3 Position,Vector3 Velocity,float AngularY,bool Supported,float? LandingY,bool Geometry)[] {
("floor_support",Initial(),new(0,75.9000015f,0),Vector3.Zero,0,true,-13.333334f,true),
("spawn_settle",Initial() with {Position=new(0,26,0)},new(0,75.9000015f,0),Vector3.Zero,0,true,-13.333334f,true),
("pending_jump",Initial() with {Supported=true,Impulse=new(0,550,0),Acceleration=new(0,-264,0)},new(0,84.7711105f,0),new(0,532.266663f,0),0,false,null,true),
("fall_above_floor",Initial() with {Position=new(0,100,0),Velocity=new(0,-200,0)},new(0,96.4444427f,0),new(0,-213.333328f,0),0,false,null,true),
("fall_land",Initial() with {Position=new(0,76,0),Velocity=new(0,-200,0)},new(0,75.9000015f,0),Vector3.Zero,0,true,-213.333328f,true),
("ground_friction",Initial() with {Velocity=new(100,0,50),AngularVelocity=new(0,12,0)},new(1.66666675f,75.9000015f,.833333373f),new(98.6666641f,0,49.3333321f),11.8400002f,true,-13.333334f,true),
("published_speed",Initial() with {Velocity=new(100,0,50),AngularVelocity=new(0,12,0),PublishedSpeed=100},new(1.66666675f,75.9000015f,.833333373f),new(100,0,50),12,true,-13.333334f,true),
("stationary_angular",Initial() with {AngularVelocity=new(0,12,0)},new(0,75.9000015f,0),Vector3.Zero,12,true,-13.333334f,true),
("small_motion",Initial() with {Velocity=new(.125f,0,0)},new(.00208333344f,75.9000015f,0),Vector3.Zero,0,true,-13.333334f,true),
("geometry_disabled",Initial() with {Velocity=new(0,200,0),Acceleration=new(0,-264,0)},new(0,75.9000015f,0),Vector3.Zero,0,true,null,false)
};
foreach(var test in cases)
{
var result=physics.Step(test.Input,1f/60,geometryEnabled:test.Geometry);
Near(result.Body.Position,test.Position,$"{test.Name} root");
Near(result.Body.Velocity,test.Velocity,$"{test.Name} velocity");
Near(result.Body.AngularVelocity,new(0,test.AngularY,0),$"{test.Name} angular velocity");
Near(result.Body.Impulse,Vector3.Zero,$"{test.Name} consumes impulse");
var expectedAcceleration=test.Geometry ? test.Supported ? Vector3.Zero : test.Input.Acceleration : new Vector3(0,800,0);
Near(result.Body.Acceleration,expectedAcceleration,$"{test.Name} acceleration");
Check(result.Body.Supported==test.Supported && result.Landing.HasValue==test.LandingY.HasValue,$"{test.Name} support/landing");
if(test.LandingY is {} vy)
{
var observation=result.Landing!.Value;
Check(!observation.Supported && MathF.Abs(observation.Velocity.Y-vy)<.002f,$"{test.Name} callback sees old velocity/support");
Check(observation.Acceleration.Y==0 && observation.Position==result.Body.Position,$"{test.Name} callback sees new root/acceleration");
}
Console.WriteLine($"PASS original ordinary-body reference {test.Name}");
}
var resting=physics.Step(Initial() with {Supported=true},1f/60);
Check(resting.Body.Supported && resting.Landing==null,"already supported must not emit landing37C again");
Console.WriteLine("PASS prior support suppresses repeated landing callback");
var empty=new OriginalBodyPhysics(new([]));
var rotation=empty.Step(Initial() with {AngularVelocity=new(0,.1f,0)},.5f);
Near(rotation.Body.Rotation,new(0,.05f,0),"rotation is integrated before small angular motion is suppressed");
Check(rotation.Body.AngularVelocity==Vector3.Zero,"small angular suppression");
var moving=empty.Step(Initial() with {Velocity=new(.125f,0,0),PublishedSpeed=1},1f/60,geometryEnabled:false);
Check(moving.Body.Velocity.X!=0,"nonzero published speed suppresses friction and small linear cutoff");
Console.WriteLine("PASS angular integration and independent published speed cutoff");
try { new OriginalBodyPhysics(new([floor with {StoredNormal=Vector3.UnitZ,MaterialId=61}]));
throw new Exception("unsupported special contacts accepted"); }
catch(NotSupportedException) { }
Console.WriteLine("PASS unsupported special-contact scene rejected");
var falling=empty.Step(Initial(),1f/60);
var rising=empty.Step(Initial() with {Impulse=new(0,550,0)},1f/60);
Check(falling.CollisionPasses==0 && rising.CollisionPasses==1,
"falling vertical motion is added after horizontal dispatcher; rising motion is dispatched whole");
Console.WriteLine("PASS positive-Y versus horizontal-first split");
var ceiling=new CameraRayPolygon(new(new(-100,100,-100),new(100,100,100),new(100,100,-100)), -Vector3.UnitY);
var roof=new OriginalBodyPhysics(new([ceiling]));
var roofHit=roof.Step(new(new(0,80,0),new(0,920,0),new(0,100,0),Vector3.Zero),1f/60,10,1);
Near(roofHit.Body.Position,new(0,90,0),"ceiling candidate published after terminal callback370");
Check(roofHit.Contact==ceiling && roofHit.Body.Velocity.Y==0 && roofHit.Body.Acceleration.Y==0,
"370 clears positive vertical velocity and acceleration without landing");
Check(!roofHit.Body.Supported && roofHit.Landing==null,"ceiling does not invent floor support");
Console.WriteLine("PASS composed ceiling370 and support ownership");
var wide=physics.Step(Initial(),1f/60,100);
Near(wide.Body.Position,new(0,126.5f,0),"live radius100 changes support offset as well as collision");
var unclamped=empty.Step(Initial() with {Velocity=new(100,0,0)},.5f,friction:4,geometryEnabled:false);
Near(unclamped.Body.Velocity,new(-100,0,0),"source friction multiplier is not clamped");
Console.WriteLine("PASS radius-dependent support and unclamped friction");
var original=Path.GetFullPath(args.Length==1?args[0]:"../Original");
var world=Mesh.LoadSceneJson("artifacts/extracted/VR04/scene.json");
var level=GamLevel.Load(AssetPath.Resolve(original,"gam/VR04.gam"));
var start=level.FindStart()!;
var standing=AseMesh.Load(AssetPath.Resolve(original,"ASE/jimstop.ase"));
var geometry=OriginalCameraRay.FromRouteScene(world,"VR04");
LabSimulation Simulation(bool retained=false) => new(new(world),standing,start.Position,start.Rotation.Y,
(a,b)=>geometry.Trace(a,b),(a,b)=>geometry.TraceGeometry(a,b),OriginalStaticCollision.FromRouteScene(world,"VR04"))
{LevelCode="VR04",InputAfterPlayerUpdate=retained};
var player=Simulation();
Check(player.UsesOriginalBody && player.PublishedSpeed==0,"tutorial explicitly selects source body");
for(var i=0;i<120;i++)player.Step(default);
Check(player.Grounded && player.Landings==0,"steady source support must not chatter");
var sole=standing.Vertices.Min(v=>Vector3.Transform(v.Position,player.Model).Y);
Check(MathF.Abs(sole-player.Position.Y)<.001f,"modern sole/root render bridge remains explicit and stable");
var rootBefore=player.ActorRoot;
player.Step(new(false,false,false,false,true));
Check(player.PendingImpulse.Y==550 && player.Grounded,"controller queues takeoff after body");
player.Step(default,false);
Check(player.PendingImpulse==Vector3.Zero && !player.Grounded && player.ActorRoot.Y>rootBefore.Y
&& player.ControllerSteps==121 && player.PhysicsSteps==122,"body consumes jump without control ownership");
Console.WriteLine("PASS tutorial root/visual bridge and control-independent pending jump");
player=Simulation();
for(var i=0;i<8;i++)player.Step(new(true,false,false,false,false));
var published=player.PublishedSpeed;
Check(published>0 && published==player.Speed,"controlled tail publishes controller speed");
player.PrepareForScript();
Check(player.Speed==0 && player.PublishedSpeed==published,"preparation preserves previously published speed160");
player.Step(default,false);
Check(player.PublishedSpeed==published,"raw control gate prevents new publication");
player.Step(default);
Check(player.PublishedSpeed==player.Speed,"resumed controlled tail publishes again");
Console.WriteLine("PASS tutorial published speed/preparation/control boundaries");
player=Simulation(true);
Check(player.ApplyRetainedLevelState(new("LV1B",3,1,.6f,4)),"retained tutorial scalar state accepted");
Check(player.PublishedSpeed==0 && player.Velocity==Vector3.Zero,"scene Init resets published body/controller motion");
for(var i=0;i<300;i++)player.Step(LabSimulation.JetpackSmokeInput(i));
Check(player.Bursts>0 && player.Travel>50 && player.MaximumRise>100 && player.Energy==20,
"retained input ordering keeps powered steering and VR04 energy exemption");
Check(player.Grounded && player.Landings>0,"source tutorial powered flight returns to support");
Console.WriteLine("PASS retained tutorial jetpack/steering/landing phases");
player=Simulation();
player.SetNoclip(true);
player.Step(new(false,false,false,false,false,Rise:true));
var physicsSteps=player.PhysicsSteps;
player.SetNoclip(false);
player.Step(default,false);
Check(player.PhysicsSteps==physicsSteps+1 && player.PublishedSpeed==0,"modern noclip exits into source body with cleared motion");
Console.WriteLine("PASS tutorial noclip returns to source body");
Console.WriteLine("Ordinary body:20 groups passed; dynamic actors and special Player contacts remain separate.");
+2
View File
@@ -102,6 +102,8 @@ Test("source enable flag and unobstructed gain leave desired eye unchanged", ()
var result = ray.Constrain(high, low); var result = ray.Constrain(high, low);
Check(result.Eye == low && result.Gain == 1 && result.Hit == null && ray.LastTriangleTests == 0, Check(result.Eye == low && result.Gain == 1 && result.Hit == null && ray.LastTriangleTests == 0,
"disabled predicate queried geometry or moved eye"); "disabled predicate queried geometry or moved eye");
Check(ray.TraceGeometry(high, low)?.ShapeId == 1 && ray.LastTriangleTests == 0,
"camera-only debug switch disabled ceiling geometry or changed camera diagnostics");
ray.Enabled = true; ray.Enabled = true;
result = ray.Constrain(new(100, 100, 100), new(100, 0, 100)); result = ray.Constrain(new(100, 100, 100), new(100, 0, 100));
Check(result.Eye == new Vector3(100, 0, 100) && result.Gain == 1 && result.Hit == null, "miss changed eye or gain"); Check(result.Eye == new Vector3(100, 0, 100) && result.Gain == 1 && result.Hit == null, "miss changed eye or gain");
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
<ItemGroup><Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Assets/*.cs" />
<Compile Include="../../src/GamePort/Game/*.cs" />
<Compile Include="../../src/GamePort/Application/UiViewport.cs" />
<Compile Include="../../src/GamePort/Application/GadgetMenuOverlay.cs" />
<Compile Include="../../src/GamePort/Application/ShrinkRayVisuals.cs" />
<Compile Include="../../src/GamePort/Application/ShrinkSoldierVisuals.cs" />
</ItemGroup>
</Project>
+179
View File
@@ -0,0 +1,179 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
using GamePort.Application;
void Check(bool value,string message) { if(!value)throw new Exception(message); }
var count=0;
void Test(string name,Action action) {action();count++;Console.WriteLine($"PASS {name}");}
SceneInventory Inventory() {var values=new int[19];values[3]=1;return new(values);}
Test("source control gate and combined default device",()=>{
var inventory=Inventory();inventory.SelectGadget(3);
var screen=new GadgetScreen(inventory);
Check(GadgetScreen.EquippedMode(3)==-1,"display3 must not become equipped mode3");
Check(!screen.Toggle(false)&&!screen.Open,"script ownership prohibits opening");
Check(screen.Toggle(true)&&screen.Open,"owned default device opens on first Tab");
screen.Toggle(true);Check(!screen.Open,"open panel closes on Tab");
});
Test("strict original card bounds and raw ownership",()=>{
var inventory=Inventory();var screen=new GadgetScreen(inventory);screen.Toggle(true);
foreach(var p in new[]{new Vector2(157,380),new(298,380),new(200,327),new(200,468)})
{screen.Point(p,"LV1B",60);Check(screen.Hovered==-1,"exact tile boundary must miss");}
screen.Point(new(200,380),"LV1B",60);Check(screen.Hovered==3,"owned shrink/jetpack tile hits");
inventory.SetState(0,3,4);screen.Point(new(200,380),"LV1B",60);
Check(screen.Hovered==-1,"unavailable ownership must not select");
inventory.SetState(0,3,3);screen.Point(new(200,380),"LV1B",60);
Check(screen.Hovered==3&&!screen.Canvases("LV1B",60).Any(c=>c.Id==14),"raw3 hits without green hover");
});
Test("original background and white/green owned art",()=>{
var screen=new GadgetScreen(Inventory());screen.Toggle(true);
Check(screen.Canvases("LV1B",60).Select(c=>c.Id).SequenceEqual(new[]{20,48,182,180}),"unowned art remains base grey");
screen.Point(new(200,380),"LV1B",60);
Check(screen.Canvases("LV1B",60).Any(c=>c.Id==14)&&!screen.Canvases("LV1B",60).Any(c=>c.Id==48),"green selected by hover");
});
Test("Return closes without selecting or leaving practice armed",()=>{
var inventory=Inventory();var screen=new GadgetScreen(inventory);screen.Toggle(true);
screen.Point(new(520,120),"LV1B",60);screen.Activate("LV1B",60);
Check(screen.PracticeArmed,"Practice arms on click");
screen.Point(new(50,120),"LV1B",60);screen.Activate("LV1B",60);
Check(!screen.Open&&!screen.PracticeArmed&&inventory.SelectedGadget==-1,"Return closes/disarms only");
});
Test("armed gadget choice requests direct original tutorial",()=>{
var inventory=Inventory();var screen=new GadgetScreen(inventory);var chosen=-1;
var selectedAfterClose=false;inventory.GadgetSelected+=_=>selectedAfterClose=!screen.Open;
screen.PracticeRequested+=i=>chosen=i;screen.Toggle(true);
screen.Point(new(520,120),"LV1B",60);screen.Activate("LV1B",60);
screen.Point(new(200,380),"LV1B",60);screen.Activate("LV1B",60);
Check(chosen==3&&!screen.Open&&inventory.SelectedGadget==3&&selectedAfterClose,"source close-before-selection/direct item3→VR04");
screen.Toggle(true);screen.Point(new(520,120),"VR04",60);
Check(screen.Hovered==-1,"tutorial cannot recursively arm practice");
screen.Point(new(520,120),"LV1B",500);Check(screen.Hovered==-1,"scene500 blocks practice toggle");
});
Test("special equipped mode unequips before next Tab opens",()=>{
var inventory=Inventory();inventory.SetState(0,0,1);inventory.SelectGadget(0);
var screen=new GadgetScreen(inventory);screen.Toggle(true);
Check(!screen.Open&&inventory.SelectedGadget==-1,"first Tab unequips");
screen.Toggle(true);Check(screen.Open,"second Tab opens");
});
Test("real54-canvas overlay scales uniformly and preserves world",()=>{
var screen=new GadgetScreen(Inventory());screen.Toggle(true);screen.Point(new(200,380),"LV1B",60);
var world=new Mesh([new(new(1,2,3),Vector2.Zero,Vector3.One)],[0,0,0])
{Textures=new(){[int.MinValue]=PngImage.White},HasCollisionMaterialIds=true};
var overlay=new GadgetMenuOverlay(world,"artifacts/extracted/gadgets/gadgets.json");
Check(overlay.Mesh.Vertices.Length==217&&overlay.Mesh.Textures.Count==55,"bounded original resources and unique texture IDs");
var final=overlay.Mesh with {Vertices=overlay.Mesh.Vertices.ToArray(),Draws=overlay.Mesh.Draws.Select(d=>d with{}).ToArray()};
foreach(var (width,height) in new[]{(1920u,1080u),(3440u,1440u),(1280u,1024u)})
{
overlay.Update(final,screen.Canvases("LV1B",60),width,height);
Check(final.Vertices[0].Position==new Vector3(1,2,3),"world vertices unchanged");
var a=final.Vertices[1].Position;var b=final.Vertices[3].Position;
var pixelsX=(b.X-a.X)*width/2;var pixelsY=(b.Y-a.Y)*height/2;
Check(MathF.Abs(pixelsX/pixelsY-640f/480)<.00001f,"original panel aspect ratio");
Check(final.Draws.Count(d=>d.ScreenSpace&&d.Visible)==4,"only source menu ranges visible");
var view=new UiViewport(width,height);var reference=new Vector2(200,380);
var ndc=view.ToNdc(reference+view.CenterOffset);
var point=view.InverseModal(new((ndc.X+1)*width/2,(ndc.Y+1)*height/2));
screen.Point(point,"LV1B",60);Check(screen.Hovered==3,"render and hit mapping agree");
}
overlay.Update(final,[],1920,1080);Check(final.Draws.Skip(1).All(d=>!d.Visible),"closing hides all gadget art");
});
Test("original menu pointer accumulation and neutral reset",()=>{
var screen=new GadgetScreen(Inventory());screen.Toggle(true);
var p=screen.MovePointer(new(200,200),Vector2.UnitX,.25f);
Check(p==new Vector2(220,200),"source80*dt pointer offset");
p=screen.MovePointer(p,Vector2.UnitX,.25f);Check(p==new Vector2(260,200),"held axis accumulates offset");
Check(screen.MovePointer(p,Vector2.Zero,.25f)==p,"neutral discards accumulated axis");
});
Test("ray texture phase float/double boundary and discarded overshoot",()=>{
var ray=new ShrinkRay();ray.StepTexture(.1f);Check(ray.TexturePhase==1,"float.1 exceeds source double.1");
ray.StepTexture(.35f);Check(ray.TexturePhase==2,"one phase per invocation, no catchup");
ray.StepTexture(.1f);Check(ray.TexturePhase==0,"three source texture slots wrap");
ray.Reset();ray.StepTexture(.099f);Check(ray.TexturePhase==0,"below source boundary");
});
Test("continuous source target gates and no angle seam wrap",()=>{
var ray=new ShrinkRay();SupportHit? Clear(Vector3 a,Vector3 b)=>null;
var targets=new[]{new ShrinkCandidate("valid",new(0,0,1000)),new("body-off",new(0,0,800),false),
new("immune",new(0,0,800),ShrinkEnabled:false),new("already",new(0,0,800),Shrunk:true),
new("range",new(0,0,1500)),new("high",new(0,60,800)),new("low",new(0,-150,800)),
new("seam",new(1,0,1000)),new("near-zero",new(-1,0,1000)),new("last",new(0,0,900))};
Check(ray.Fire(Vector3.Zero,0,1f/60,targets,Clear).SequenceEqual(new[]{"valid","near-zero","last"}),
"source eligibility, strict range/height and input-order multi-hit");
Check(ray.Fire(Vector3.Zero,0,1f/60,targets,(a,b)=>new(Vector3.Zero,0,0,0)).Count==0,"any accepted static hit blocks");
var angle=OriginalHeading.Degrees(new(-1,0,1000));
Check(ray.Fire(Vector3.Zero,angle-5,1f/60,[new("edge",new(-1,0,1000))],Clear).Count==0,"exact yaw+5 is excluded");
});
var original=Path.GetFullPath("../Original");
var level=GamLevel.Load(AssetPath.Resolve(original,"gam/VR04.gam"));
var save=OriginalSave.Load(AssetPath.Resolve(original,"NewGame.tsk"));
Test("actual soldier shrink mode and strict timer expiry",()=>{
var director=new SceneDirector(level,new(save.Tasks),(_,_)=>0);
var actor=director.Actors.First(a=>a.Kind=="3SOL");var old=actor.AIstate;
var soldier=new ShrinkSoldier(actor);soldier.Shrink();
Check(actor.Animation=="SHRINK"&&actor.AIstate==5&&soldier.Remaining==30,"source target callback state");
for(var i=0;i<40;i++)soldier.StepTimer(.75f);
Check(soldier.Remaining==0&&soldier.Shrunk,"exact source timer0 does not expire");
soldier.StepTimer(.1f);Check(soldier.Shrunk,"timer0 skips future positive-only countdown");
soldier.Reset();actor.AIstate=7;soldier.Shrink();
Check(soldier.PreviousMode==7&&soldier.AuthoredMode==old,"authored AIState is distinct from previous dynamic mode");
for(var i=0;i<34;i++)soldier.StepTimer(.9f);
Check(!soldier.Shrunk&&actor.Animation=="WALK"&&actor.AIstate==old&&actor.Speed==200,"negative crossing restores authored mode/WALK");
});
Test("source shrink morph reaches and holds authored endpoint",()=>{
var director=new SceneDirector(level,new(save.Tasks),(_,_)=>0);
var soldier=new ShrinkSoldier(director.Actors.First(a=>a.Kind=="3SOL"));
var scene=new Mesh([],[]);var visuals=new ShrinkSoldierVisuals(scene,[soldier],"artifacts/extracted","VR04");
soldier.Shrink();visuals.Update(1,visuals.Mesh);
var height=visuals.RenderedHeight(soldier.Actor.Tag,visuals.Mesh);
Check(MathF.Abs(height-55.1186f)<.002f,"authored last shrink frame, no invented uniformscale");
visuals.Update(5,visuals.Mesh);Check(visuals.RenderedHeight(soldier.Actor.Tag,visuals.Mesh)==height,"nonloop endpoint stays small");
});
Test("ordinary primary fire, energy, sound transitions and release",()=>{
var lab=GamLevel.Load(AssetPath.Resolve(original,"gam/level1b.gam"));var start=lab.FindStart()!;
var world=Mesh.LoadSceneJson("artifacts/extracted/level1b/scene.json");
var player=new LabSimulation(new(world),AseMesh.Load(AssetPath.Resolve(original,"ASE/jimstop.ase")),start.Position,start.Rotation.Y);
var director=new SceneDirector(lab,new(save.Tasks),(_,_)=>0);
var inventory=Inventory();using var gadgets=new SceneGadgets(director,inventory,player,world);
var loops=0;var stops=0;var clicks=0;
gadgets.Sound+=(id,loop)=>{if(id==0&&loop)loops++;if(id==117)clicks++;};gadgets.StopSound+=()=>stops++;
player.Step(new(true,false,false,false,false,Fire:true));
Check(gadgets.Ray.Visible&&player.Shooting&&player.Speed==0&&player.Velocity.X==0&&player.Velocity.Z==0,"grounded fire stops controller movement before apply");
Check(MathF.Abs(player.Energy-(20-1f/60))<.0001f&&loops==1,"held beam charges once even without target");
player.Step(new(false,false,false,false,false,Fire:true));Check(loops==1,"owned loop is not restarted every tick");
player.Step(default);Check(!gadgets.Ray.Visible&&!player.Shooting&&stops==1,"release hides/stops effect");
inventory.SetState(0,3,0);player.Step(new(false,false,false,false,false,Fire:true));
player.Step(new(false,false,false,false,false,Fire:true));Check(clicks==1,"dry click latches until release");
});
Test("ray visual uses original geometry and single half-opacity additive material",()=>{
var visuals=new ShrinkRayVisuals(new Mesh([],[]),"artifacts/extracted",original);var ray=new ShrinkRay();
ray.Fire(Vector3.Zero,0,1f/60,[],(a,b)=>null);visuals.Update(visuals.Mesh,ray,0);
Check(visuals.Mesh.Vertices.Length==9&&visuals.Mesh.Indices.Length==9
&& visuals.Mesh.Vertices.Select(v=>v.Position).Distinct().Count()==5,"original five source vertices expanded by UV corners");
var beamDraws=visuals.Mesh.Draws.Where(d=>d.IndexCount!=0).ToArray();
Check(beamDraws.Count(d=>d.Visible)==1&&beamDraws.All(d=>d.Opacity==.5f&&d.Blend==MeshBlend.Additive),"source alpha replaces once and one texture phase renders");
ray.Hide();visuals.Update(visuals.Mesh,ray,0);Check(beamDraws.All(d=>!d.Visible),"release hides all phases");
});
Test("ordinary hit score order, repeated-hit guard and original save persistence",()=>{
//Explicit synthetic floor for deterministic actor settling; actual original
//VR04 soldier records are used, never substituted into the playable level.
var floor=new Mesh([new(new(-10000,0,-10000),Vector2.Zero,Vector3.One),
new(new(10000,0,-10000),Vector2.Zero,Vector3.One),new(new(0,0,10000),Vector2.Zero,Vector3.One)],[0,1,2])
{CollisionPolygons=[new(0,0,Vector3.UnitY,null)],HasCollisionMaterialIds=true};
var director=new SceneDirector(level,new(save.Tasks),(_,_)=>0);
var interactions=new SceneInteractions(director,new(save.Tasks),save);
interactions.Inventory.SetState(0,3,1);
var player=new LabSimulation(new(floor),AseMesh.Load(AssetPath.Resolve(original,"ASE/jimstop.ase")),Vector3.Zero,0,
originalCollision:OriginalStaticCollision.FromRouteScene(floor,"VR04")){LevelCode="VR04"};
using var gadgets=new SceneGadgets(director,interactions.Inventory,player,floor);
for(var i=0;i<600;i++)gadgets.StepBodies(1f/60);
var target=gadgets.Soldiers[0];
player.ApplyAuthoredTransform(new(target.Actor.Position.X,75.9f,target.Actor.Position.Z-500),0);
var observed=false;
gadgets.ScoreAwarded+=points=>{observed=points==10&&target.Shrunk&&target.Actor.AIstate==5&&target.HitMarker==0;interactions.ChangeScore(points);};
player.Step(new(false,false,false,false,false,Fire:true));
Check(observed&&target.HitMarker==1&&interactions.Score==save.Score+10,"source score callback follows shrink and precedes94C marker");
for(var i=0;i<10;i++)player.Step(new(false,false,false,false,false,Fire:true));
Check(interactions.Score==save.Score+10&&gadgets.ShrinkHits==1,"already-shrunk flag prevents repeated awards");
Check(OriginalSave.Parse(interactions.Snapshot().Encode()).Score==save.Score+10,"source-format save preserves gadget reward");
Check(player.Energy==20,"original VR energy exemption also applies to primary fire");
});
Console.WriteLine($"Gadgets:{count} groups passed; other gadget effects and complete enemy AI remain separate.");
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Game/OriginalHeading.cs" Link="OriginalHeading.cs" />
</ItemGroup>
</Project>
+47
View File
@@ -0,0 +1,47 @@
using System.Numerics;
using GamePort.Game;
// Source vector::angles cardinal/quadrant results, plus copied-DLL references.
var samples = new (Vector3 Direction, int Units)[]
{
(Vector3.Zero, 0), (Vector3.UnitZ, 0), (-Vector3.UnitX, 4096),
(-Vector3.UnitZ, 8192), (Vector3.UnitX, 12288),
(new(-1, 0, 1), 2048), (new(-1, 0, -1), 6144),
(new(1, 0, -1), 10240), (new(1, 0, 1), 14336),
(new(1, 100, 1000), 16364), (new(-1, -100, 1000), 20),
(new(1000, 0, 1), 12288), (new(-1000, 0, 1), 4096),
(new(.1234567f, 88, .7654321f), 15967), (new(-99.1f, -20, 15.7f), 3686),
};
foreach (var (direction, units) in samples)
{
float actual = OriginalHeading.Degrees(direction);
if (actual != units * 0.02197265625f)
throw new Exception($"Heading {direction}: expected {units} units, got {actual} degrees");
}
foreach (var bad in new[] { new Vector3(float.NaN, 0, 1), new Vector3(0, float.PositiveInfinity, 1) })
{
try { OriginalHeading.Degrees(bad); throw new Exception("Nonfinite vector accepted"); }
catch (ArgumentOutOfRangeException) { }
}
// A seam-crossing near-forward direction remains near360; the caller performs
// the original strict comparisons against Jimmy's EulerY without wrapping.
float seam = OriginalHeading.Degrees(new Vector3(1, 0, 1000));
if (seam is not (> 355 and < 360)) throw new Exception("Heading seam normalized away");
if (-5 < seam && seam < 5) throw new Exception("Source seam comparison changed");
uint hash = 2166136261;
int cases = 0;
for (int i = 0; i <= 16384; i++)
{
float a = (float)Math.Sqrt((i + .25) / 16384.5);
float b = (float)Math.Sqrt(1 - (i + .25) / 16384.5);
for (int quadrant = 0; quadrant < 4; quadrant++)
{
var direction = new Vector3((quadrant & 1) != 0 ? -b : b, 0, (quadrant & 2) != 0 ? -a : a);
ushort units = (ushort)(OriginalHeading.Degrees(direction) / .02197265625f);
hash = unchecked((hash ^ units) * 16777619);
cases++;
}
}
// Observed through the copied OMT2.dll export, heading-probe/wine.log.
if (hash != 0x24e64f91) throw new Exception($"Original-DLL sweep mismatch: {hash:x8}");
Console.WriteLine($"Heading: {samples.Length} copied-DLL references, {cases} sweep cases, finite guards and unwrapped seam passed.");
@@ -9,6 +9,10 @@
<Compile Include="../../src/GamePort/Game/TaskActivation.cs"/> <Compile Include="../../src/GamePort/Game/TaskActivation.cs"/>
<Compile Include="../../src/GamePort/Game/TaskStates.cs"/> <Compile Include="../../src/GamePort/Game/TaskStates.cs"/>
<Compile Include="../../src/GamePort/Game/LabSimulation.cs"/> <Compile Include="../../src/GamePort/Game/LabSimulation.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalBodyPhysics.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalStaticCollision.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalSphereResponse.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalCameraRay.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerLevelState.cs"/> <Compile Include="../../src/GamePort/Game/PlayerLevelState.cs"/>
<Compile Include="../../src/GamePort/Game/AirSteering.cs"/> <Compile Include="../../src/GamePort/Game/AirSteering.cs"/>
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/> <Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
+3 -1
View File
@@ -17,8 +17,10 @@ var director = new SceneDirector(level, tasks, resources.Duration);
var interactions = new SceneInteractions(director, tasks, save); var interactions = new SceneInteractions(director, tasks, save);
var mechanisms = new SceneMechanisms(director); var mechanisms = new SceneMechanisms(director);
var visuals = new StaticSceneVisuals(world, director, original, Path.Combine(prepared, "level1b/models")); var visuals = new StaticSceneVisuals(world, director, original, Path.Combine(prepared, "level1b/models"));
var geometry = OriginalCameraRay.FromRouteScene(world, level.Code);
var simulation = new LabSimulation(new SceneCollision(world), AseMesh.Load(AssetPath.Resolve(original, "ASE/jimstop.ase")), var simulation = new LabSimulation(new SceneCollision(world), AseMesh.Load(AssetPath.Resolve(original, "ASE/jimstop.ase")),
start.Position, start.Rotation.Y) { JetpackInventoryState = () => interactions.Inventory.State(0, 3) }; start.Position, start.Rotation.Y, (a,b) => geometry.Trace(a,b), (a,b) => geometry.TraceGeometry(a,b))
{ JetpackInventoryState = () => interactions.Inventory.State(0, 3) };
simulation.DynamicRootResolver = (before, after, radius) => DynamicBodyResponse.Resolve(visuals.DoorColliders(), before, after, radius); simulation.DynamicRootResolver = (before, after, radius) => DynamicBodyResponse.Resolve(visuals.DoorColliders(), before, after, radius);
var patrols = new List<ActorPatrol>(); var patrols = new List<ActorPatrol>();
foreach (var actor in director.Actors.Where(a => a.Kind is "3DOG" or "3CAR")) foreach (var actor in director.Actors.Where(a => a.Kind is "3DOG" or "3CAR"))
+69 -2
View File
@@ -12,6 +12,7 @@ var tests = new (string Name, Action Check)[]
("ordinary route load retains scalars independently of body/jump reset", RetainedLevelState), ("ordinary route load retains scalars independently of body/jump reset", RetainedLevelState),
("script preparation preserves queued work and uncontrolled physics consumes it", UncontrolledPhysics), ("script preparation preserves queued work and uncontrolled physics consumes it", UncontrolledPhysics),
("uncontrolled fire ticks while movement and grounded-release reset are gated", UncontrolledFire), ("uncontrolled fire ticks while movement and grounded-release reset are gated", UncontrolledFire),
("source root ceiling ray bounces and cancels before control ownership", CeilingWrapper),
("source camera query origin, hit adjustment, gain and one query per input", CameraQueryConsumer), ("source camera query origin, hit adjustment, gain and one query per input", CameraQueryConsumer),
("debug noclip bypasses walls/gravity/camera and exits without queued motion", Noclip), ("debug noclip bypasses walls/gravity/camera and exits without queued motion", Noclip),
("turn-only speed, forward acceleration/cap and release", SpeedLimits), ("turn-only speed, forward acceleration/cap and release", SpeedLimits),
@@ -191,6 +192,61 @@ static void RetainedLevelState()
Throws<ArgumentOutOfRangeException>(() => grounded.ApplyRetainedLevelState(state with { EffectRemaining = float.PositiveInfinity })); Throws<ArgumentOutOfRangeException>(() => grounded.ApplyRetainedLevelState(state with { EffectRemaining = float.PositiveInfinity }));
} }
static void CeilingWrapper()
{
var queries = 0;
var start = Vector3.Zero; var end = Vector3.Zero;
SupportHit? Ceiling(Vector3 a, Vector3 b)
{ queries++; start = a; end = b; return new((a + b) / 2, 1, 2, 75); }
var jump = new PlayerInput(false, false, false, false, true);
var simulation = FlatSimulation(ceilingRay: Ceiling);
simulation.Step(jump);
Check(queries == 0 && simulation.PendingImpulse.Y == 550, "Queued impulse is not upward velocity yet");
simulation.ApplyRetainedLevelState(new("LV1B", 3, 1, .625f, 6.125f));
var energy = simulation.Energy;
simulation.Step(jump, controlled: false);
NearVector(start, simulation.ActorRoot, .0001f, "Upward query uses post-physics actor root");
NearVector(end - start, Vector3.UnitY * 150, 0, "Upward ray uses authored150 span");
Check(simulation.Velocity.Y < -300 && simulation.CeilingHits == 1, "Original0.6 velocity reflection");
Check(simulation.ControllerSteps == 1 && simulation.MovementMode == 1 && simulation.JumpState == 0,
"Ceiling cancellation runs without controlled movement");
Near(simulation.JumpHoldSeconds, .625f, 0, "Cancellation preserves hold");
Near(simulation.JetpackRemaining, -FixedStepClock.Step, 0, "Fire ticks after cancellation zero");
Near(simulation.Energy, energy, 0, "Cancelled fire does not drain energy");
Check(simulation.Pose == PlayerPose.Fall && simulation.PendingImpulse == Vector3.Zero,
"FALL request and independent impulse consumption");
simulation.Step(default, controlled: false);
Check(queries == 1, "Non-upward velocity makes no ceiling query");
var otherMode = FlatSimulation(ceilingRay: Ceiling);
otherMode.Step(jump);
otherMode.ApplyRetainedLevelState(new("LV1B", 3, 0, .625f, 6.125f));
otherMode.Step(default, controlled: false);
Check(otherMode.Velocity.Y < 0 && otherMode.MovementMode == 0 && otherMode.JetpackRemaining > 6,
"Mode0 still reflects velocity but skips mode1 cancellation");
var hit = false;
var powered = FlatSimulation(ceilingRay: (a,b) => hit ? new SupportHit((a+b)/2, 1, 2, 75) : null);
powered.JetpackInventoryState = () => 1; powered.GadgetMode = 3;
for (var i = 0; i < 40; i++) powered.Step(jump);
Check(powered.JumpState == 3 && powered.JetpackRemaining > 0 && powered.Velocity.Y > 0,
"Powered ceiling fixture has active jump/fire");
hit = true; powered.Step(default, controlled: false);
Check(powered.Velocity.Y <= -85 && powered.JumpState == 0 && powered.JetpackRemaining < 0,
"Ceiling cancels an active powered burst while uncontrolled");
foreach (var retained in new[] { false, true })
{
var phases = new List<string>();
var ordered = FlatSimulation(cameraRay: (a,b) => { phases.Add("input"); return null; },
ceilingRay: (a,b) => { phases.Add("wrapper"); return null; });
ordered.InputAfterPlayerUpdate = retained;
ordered.Step(jump); phases.Clear(); ordered.Step(jump);
Check(phases.SequenceEqual(retained ? ["wrapper", "input"] : new[] { "input", "wrapper" }),
"Wrapper belongs to Jimmy callback between fresh/retained input boundaries");
}
}
static void CameraQueryConsumer() static void CameraQueryConsumer()
{ {
var enabled = false; var enabled = false;
@@ -584,9 +640,20 @@ static void OriginalLab(string project, string originals)
for (var i = 0; i < 120; i++) simulation.Step(default); for (var i = 0; i < 120; i++) simulation.Step(default);
Check(simulation.Jumps == 1 && simulation.Landings == 1 && simulation.Grounded, "stationary original-lab jump lands once"); Check(simulation.Jumps == 1 && simulation.Landings == 1 && simulation.Grounded, "stationary original-lab jump lands once");
Near(simulation.Position.Y, .5486332f + SceneCollision.Skin, .03f, "original lab jump returns to floor"); Near(simulation.Position.Y, .5486332f + SceneCollision.Skin, .03f, "original lab jump returns to floor");
var geometry = OriginalCameraRay.FromRouteScene(mesh, level.Code);
var overhead = new LabSimulation(collision, standing, start.Position, start.Rotation.Y,
(a,b) => geometry.Trace(a,b), (a,b) => geometry.TraceGeometry(a,b));
overhead.Step(new(false, false, false, false, true));
overhead.RestoreReturnRoot(overhead.ActorRoot + Vector3.UnitY * 300);
geometry.Enabled = false; // Modern camera-only switch must not suppress physical query.
overhead.Step(default, controlled: false);
Check(overhead.CeilingHits == 1 && overhead.Velocity.Y <= -85 && overhead.Pose == PlayerPose.Fall,
"Actual registered lab ceiling reverses upward motion with camera debug query disabled");
} }
static LabSimulation FlatSimulation(float yaw = 0, Func<Vector3, Vector3, SupportHit?>? cameraRay = null) static LabSimulation FlatSimulation(float yaw = 0, Func<Vector3, Vector3, SupportHit?>? cameraRay = null,
Func<Vector3, Vector3, SupportHit?>? ceilingRay = null)
{ {
var positions = new[] var positions = new[]
{ {
@@ -596,7 +663,7 @@ static LabSimulation FlatSimulation(float yaw = 0, Func<Vector3, Vector3, Suppor
var floor = new Mesh(positions.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(), [0, 1, 2, 3, 4, 5]); var floor = new Mesh(positions.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(), [0, 1, 2, 3, 4, 5]);
var standing = new Mesh([new(new(-20, -20, -20), Vector2.Zero, Vector3.One), var standing = new Mesh([new(new(-20, -20, -20), Vector2.Zero, Vector3.One),
new(new(20, 80, 20), Vector2.Zero, Vector3.One)], []); new(new(20, 80, 20), Vector2.Zero, Vector3.One)], []);
return new LabSimulation(new SceneCollision(floor), standing, new Vector3(0, 25, 0), yaw, cameraRay); return new LabSimulation(new SceneCollision(floor), standing, new Vector3(0, 25, 0), yaw, cameraRay, ceilingRay);
} }
static void SameState(LabSimulation actual, LabSimulation expected, string message) static void SameState(LabSimulation actual, LabSimulation expected, string message)
@@ -13,6 +13,10 @@
<Compile Include="../../src/GamePort/Game/TaskStates.cs"/> <Compile Include="../../src/GamePort/Game/TaskStates.cs"/>
<Compile Include="../../src/GamePort/Game/TaskActivation.cs"/> <Compile Include="../../src/GamePort/Game/TaskActivation.cs"/>
<Compile Include="../../src/GamePort/Game/LabSimulation.cs"/> <Compile Include="../../src/GamePort/Game/LabSimulation.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalBodyPhysics.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalStaticCollision.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalSphereResponse.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalCameraRay.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerLevelState.cs"/> <Compile Include="../../src/GamePort/Game/PlayerLevelState.cs"/>
<Compile Include="../../src/GamePort/Game/AirSteering.cs"/> <Compile Include="../../src/GamePort/Game/AirSteering.cs"/>
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/> <Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Game/OriginalBodySupport.cs" />
<Compile Include="../../src/GamePort/Game/OriginalSphereResponse.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,55 @@
using System.Numerics;
using GamePort.Game;
var wall = new SupportTriangle(new(-100, -100, 0), new(-100, 100, 0), new(100, 100, 0));
var normal = Vector3.UnitZ;
var initial = SphereResponseState.Begin(10);
SphereResponseResult Wall(Vector3 before, Vector3 after, bool edges = true, bool lower = true) =>
OriginalSphereResponse.Resolve(wall, normal, before, after, 10, initial, edges, lower);
void Near(Vector3 actual, Vector3 expected, string label)
{
if (Vector3.Distance(actual, expected) > .002f) throw new Exception($"{label}: {actual} != {expected}");
}
void Check(bool condition, string label) { if (!condition) throw new Exception(label); }
// Numeric references from the isolated copied original47BD80/OMT component.
var face = Wall(new(0, 20, 20), new(0, 20, 5));
Check(face.Contact == SphereContact.Face, "original face hit");
Near(face.Position, new(0, 20, 10), "original face response");
Check(face.State.FaceDistance == 20 && face.State.EdgeDistance == 10, "separate source nearest slots");
Near(Wall(new(0, 20, 20), new(0, 20, -20)).Position, face.Position, "through-plane response");
Check(Wall(new(0, 20, 5), new(0, 20, 20)).Contact == SphereContact.None, "departing source winding");
Console.WriteLine("PASS original face, crossing and departure references");
var edge = Wall(new(105, 100, 20), new(105, 100, 5));
Check(edge.Contact == SphereContact.Edge, "original edge hit");
Near(edge.Position, new(107.071068f, 100, 7.07106781f), "original edge response");
Near(edge.State.Hit!.Value, new(100, 100, 0), "original nearest vertex");
Check(Wall(new(105, 100, 20), new(105, 100, 5), edges: false).Contact == SphereContact.None,
"edge switch does not run face fallback");
Console.WriteLine("PASS original edge reference and disabled edge gate");
var upper = Wall(new(105, 105, 20), new(105, 105, 5));
Check(upper.Contact == SphereContact.Edge, "lower edge allowed");
Near(upper.Position, new(105.77375f, 105, 5.7737484f), "original lower-edge mode1 reference");
Check(Wall(new(105, 105, 20), new(105, 105, 5), lower: false).Contact == SphereContact.None,
"source lower-edge flag");
var ceiling = new SupportTriangle(new(-100, 100, -100), new(100, 100, 100), new(100, 100, -100));
var under = OriginalSphereResponse.Resolve(ceiling, -Vector3.UnitY, new(0, 80, 0), new(0, 95, 0), 10, initial);
Check(under.Contact == SphereContact.Face, "ceiling face");
Near(under.Position, new(0, 90, 0), "ceiling includes Y response");
Console.WriteLine("PASS lower-edge policy and ceiling face response");
var farther = OriginalSphereResponse.Resolve(wall, normal, new(0, 20, 20), new(0, 20, 5), 10,
initial with { FaceDistance = 19 });
Check(farther.Contact == SphereContact.None, "farther face suppressed without edge fallback");
var tied = OriginalSphereResponse.Resolve(wall, normal, new(0, 20, 20), new(0, 20, 5), 10, face.State);
Check(tied.Contact == SphereContact.None && tied.State == face.State, "equal face retains earlier state");
var edgeSuppressed = OriginalSphereResponse.Resolve(wall, normal, new(105, 100, 20), new(105, 100, 5),
10, initial with { EdgeDistance = 1 });
Check(edgeSuppressed.Contact == SphereContact.None, "edge nearest state persists across candidates");
Console.WriteLine("PASS shared nearest-hit and equal-distance boundaries");
try { Wall(new(float.NaN, 0, 0), Vector3.Zero); throw new Exception("NaN accepted"); }
catch (ArgumentOutOfRangeException) { }
Console.WriteLine("PASS bounded finite inputs; complete body solver and x87 boundary parity remain open");
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
<ItemGroup><Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Assets/*.cs" />
<Compile Include="../../src/GamePort/Game/*.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,103 @@
using System.Numerics;
using GamePort.Game;
using GamePort.Assets;
using System.Text.Json;
void Check(bool value, string message) { if (!value) throw new Exception(message); }
void Near(Vector3 actual, Vector3 expected, string message)
{ Check(Vector3.Distance(actual, expected) < .002f, $"{message}: {actual} != {expected}"); }
var wall = new CameraRayPolygon(new(new(-100,-100,0),new(-100,100,0),new(100,100,0),0,0),Vector3.UnitZ);
var world = new OriginalStaticCollision([wall]);
(StaticCollisionMove Move, StaticCollisionContext Context) Run(OriginalStaticCollision scene, Vector3 before, Vector3 delta,
bool edges=true, bool lower=false)
{
var context = new StaticCollisionContext(10);
return (scene.Move(before, delta, 10, context, edges, lower), context);
}
// References are copied-original dispatcher47B4B0 results, not just the kernel.
var face=Run(world,new(0,20,20),new(0,0,-15));
Near(face.Move.Position,new(0,20,10),"source face retry");
Check(face.Context.Passes==2 && face.Context.TriangleTests==4 && face.Move.CallbackPolygon==wall,
"source retry count, duplicate visits and final callback");
Console.WriteLine("PASS original face retry/publication and per-cell duplicate visits");
var edge=Run(world,new(105,100,20),new(0,0,-15));
Near(edge.Move.Position,new(107.071068f,100,7.07106781f),"source edge retry");
Check(edge.Context.Passes==2 && edge.Context.TriangleTests==2,"original edge retry statistics");
var disabled=Run(world,new(105,100,20),new(0,0,-15),edges:false);
Near(disabled.Move.Position,new(105,100,5),"source disabled edge");
Check(disabled.Context.Passes==1 && disabled.Context.TriangleTests==1 && disabled.Move.CallbackPolygon==null,
"disabled edges still scan and publish");
Console.WriteLine("PASS original edge and edge-disabled dispatcher references");
var zero=Run(world,new(0,20,20),Vector3.Zero);
Check(zero.Context.Passes==0 && !zero.Move.Published,"zero delta early exit");
var forced=Run(world,new(0,20,20),Vector3.Zero,lower:true);
Check(forced.Context.Passes==1 && forced.Context.TriangleTests==2 && forced.Move.Published,"source member42C forced zero");
Console.WriteLine("PASS zero-motion and forced-processing source boundaries");
var side=new CameraRayPolygon(new(new(0,-100,-100),new(0,-100,100),new(0,100,100),1,0),Vector3.UnitX);
var corner=Run(new([wall,side]),new(20,20,20),new(-30,0,-30));
Near(corner.Move.Position,new(5,20,10.000001f),"source corner/edge-below rejection");
Check(corner.Context.Passes==2 && corner.Context.TriangleTests==8 && corner.Move.CallbackPolygon==wall,
"terminal normal belongs to last accepted polygon, not last tested polygon");
Console.WriteLine("PASS original corner order and retained last polygon");
var ceiling=new CameraRayPolygon(new(new(-100,100,-100),new(100,100,100),new(100,100,-100)), -Vector3.UnitY);
var under=Run(new([ceiling]),new(0,80,0),new(0,15,0));
Near(under.Move.Position,new(0,90,0),"source ceiling retry");
Check(under.Context.Passes==2 && under.Context.TriangleTests==8 && under.Move.CallbackPolygon==ceiling,
"source ceiling terminal callback");
Console.WriteLine("PASS original ceiling dispatch reference");
Check(OriginalStaticCollision.Bounds(Vector3.Zero,new(1000,0,1000),1010)==new CollisionCells(127,134,127,132),
"source asymmetric Z upper bound");
var masked=new OriginalStaticCollision([wall with { ShapeName="ncwall" },side with { MaterialName="cstart" }]);
Check(masked.PolygonCount==0 && masked.TraceSupport(new(0,20,20),new(0,20,-20))==null,"source registration masks");
Console.WriteLine("PASS asymmetric source bounds and registration exclusions");
var floor=new CameraRayPolygon(new(new(-100,0,-100),new(100,0,-100),new(0,0,100),3,0),Vector3.UnitY);
var supported=new OriginalStaticCollision([floor]);
Check(supported.WallPolygonCount==0 && supported.TraceSupport(new(0,100,0),new(0,-100,0))?.ShapeId==3,
"general support grid remains separate from wall registration");
Console.WriteLine("PASS separate general-grid nearest support query");
var retained = new StaticCollisionContext(10);
world.Move(new(0,20,20),new(0,0,-15),10,retained);
var retainedNearest = retained.Nearest;
var withoutGeometry = world.Move(new(0,20,10),new(0,0,-15),10,retained,geometryEnabled:false);
Near(withoutGeometry.Position,new(0,20,-5),"disabled geometry publishes unclipped candidate");
Check(withoutGeometry.CallbackPolygon==wall && retained.TriangleTests==4 && retained.Nearest==retainedNearest,
"disabled geometry preserves retained last-polygon callback without testing triangles");
Console.WriteLine("PASS disabled geometry and retained callback state");
Check(new OriginalStaticCollision([wall with {MaterialId=61}]).HasSpecialPlayerContacts,
"fence material archive ID must require special callback handling");
Check(!new OriginalStaticCollision([wall with {MaterialId=17}]).HasSpecialPlayerContacts
&& !new OriginalStaticCollision([ceiling with {MaterialId=61}]).HasSpecialPlayerContacts
&& !new OriginalStaticCollision([wall with {MaterialId=61,ShapeName="ncwall"}]).HasSpecialPlayerContacts,
"ordinary material, ceiling370 and excluded shapes cannot trigger player374 special handling");
var fixture = Path.Combine(Path.GetTempPath(), $"neutron-material-{Guid.NewGuid():N}.json");
try
{
var source = new { vertices=new[] {new[]{0,0,0},new[]{1,0,0},new[]{0,1,0}},indices=new[]{0,1,2},
collisionPolygons=new[]{new{shapeId=0,polygonIndex=0,normal=new[]{0,0,1},materialName="fence",materialId=61}} };
File.WriteAllText(fixture,JsonSerializer.Serialize(source));
var loaded=Mesh.LoadSceneJson(fixture);
Check(loaded.HasCollisionMaterialIds && OriginalStaticCollision.FromRouteScene(loaded,"LV1B").HasSpecialPlayerContacts,
"prepared material identity must survive loader and source grid construction");
File.WriteAllText(fixture,File.ReadAllText(fixture).Replace(",\"materialId\":61", ""));
loaded=Mesh.LoadSceneJson(fixture);
Check(!loaded.HasCollisionMaterialIds,"legacy metadata must remain distinguishable from unresolved material");
try { OriginalStaticCollision.FromRouteScene(loaded,"LV1B"); throw new Exception("legacy metadata silently accepted"); }
catch(InvalidDataException) { }
}
finally { File.Delete(fixture); }
Console.WriteLine("PASS material policy IDs and legacy prepared-data rejection");
foreach(var (level,directory,special) in new[]{("LV1B","level1b",true),("VR04","VR04",false),("LEV1","level1",true)})
{
var scene=Mesh.LoadSceneJson(Path.Combine("artifacts/extracted",directory,"scene.json"));
Check(OriginalStaticCollision.FromRouteScene(scene,level).HasSpecialPlayerContacts==special,
$"actual {level} special-contact coverage differs from original archive inventory");
}
Console.WriteLine("PASS prepared lab/tutorial/outside contact coverage");
var tiedFloor = floor with {Triangle=floor.Triangle with {ShapeId=4}};
var supportTies = new OriginalStaticCollision([tiedFloor,floor]);
Check(supportTies.TraceSupport(new(0,100,0),new(0,-100,0))?.ShapeId==3,
"equal-distance support retains original shape/cell/FIFO order");
Check(supportTies.TraceSupport(Vector3.Zero,Vector3.Zero)==null,
"zero-length support has no strictly nearer hit");
Console.WriteLine("PASS support nearest ties and zero-length limit");
Console.WriteLine("Static dispatcher:11 groups passed; source whole-body/scene integration remains separate.");
@@ -19,8 +19,10 @@ var director = new SceneDirector(level, tasks, resources.Duration);
var interactions = new SceneInteractions(director, tasks, save); var interactions = new SceneInteractions(director, tasks, save);
var mechanisms = new SceneMechanisms(director); var mechanisms = new SceneMechanisms(director);
var visuals = new StaticSceneVisuals(world, director, original, Path.Combine(prepared, "level1b/models")); var visuals = new StaticSceneVisuals(world, director, original, Path.Combine(prepared, "level1b/models"));
var geometry = OriginalCameraRay.FromRouteScene(world, level.Code);
var simulation = new LabSimulation(new SceneCollision(world), AseMesh.Load(AssetPath.Resolve(original, "ASE/jimstop.ase")), var simulation = new LabSimulation(new SceneCollision(world), AseMesh.Load(AssetPath.Resolve(original, "ASE/jimstop.ase")),
start.Position, start.Rotation.Y) { JetpackInventoryState = () => interactions.Inventory.State(0, 3) }; start.Position, start.Rotation.Y, (a,b) => geometry.Trace(a,b), (a,b) => geometry.TraceGeometry(a,b))
{ JetpackInventoryState = () => interactions.Inventory.State(0, 3) };
var resolverCalls = 0; var resolverCalls = 0;
simulation.DynamicRootResolver = (before, after, radius) => simulation.DynamicRootResolver = (before, after, radius) =>
{ {
+93
View File
@@ -0,0 +1,93 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/binary'))
from body_composition_contract import can_publish, collect, phase_order
class BodyCompositionContractTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent/'Original')
def test_original_body_identity_and_decisive_sites(self):
self.assertEqual(self.report['body']['file_offset'], '0x79d20')
sites = {site['name']: site for site in self.report['sites']}
self.assertEqual(sites['clamp_candidate_y']['bytes'], 'd9442420d81d086a4d00')
self.assertEqual(sites['delta_y_nonpositive_branch']['bytes'], 'f6c441753d')
self.assertEqual(sites['root_compare_w']['file_offset'], '0x7a176')
self.assertEqual(len(sites), 81)
def test_disabled_integration_still_clears_support(self):
self.assertEqual(phase_order(integration_enabled=False),
['read_previous_support', 'clear_current_support', 'integration_gate'])
self.assertEqual(phase_order(support_enabled=False, integration_enabled=False),
['read_previous_support', 'integration_gate'])
def test_rotation_impulse_acceleration_gravity_and_suppression_order(self):
order = phase_order(upward=True)
names = ('rotate', 'impulse_add', 'impulse_clear', 'acceleration_add', 'gravity_add',
'velocity_to_delta', 'full_dispatch', 'support47b890',
'published_speed_zero_friction', 'angular_suppression',
'published_speed_zero_linear_suppression')
self.assertEqual(sorted(order.index(name) for name in names), [order.index(name) for name in names])
def test_nonpositive_vertical_motion_is_added_after_horizontal_response(self):
down = phase_order(upward=False)
up = phase_order(upward=True)
self.assertLess(down.index('horizontal_dispatch'), down.index('add_fall_y'))
self.assertLess(down.index('add_fall_y'), down.index('compare_previous_live_root_vec4'))
self.assertNotIn('add_fall_y', up)
self.assertNotIn('horizontal_dispatch', up)
def test_collision_world_and_global_geometry_are_separate_gates(self):
collision_off = phase_order(collision_enabled=False)
world_off = phase_order(world_enabled=False)
geometry_off = phase_order(geometry_enabled=False)
self.assertNotIn('support47b890', collision_off)
self.assertNotIn('published_speed_zero_friction', collision_off)
self.assertIn('translate31c', collision_off)
self.assertNotIn('translate31c', phase_order(collision_enabled=False, translation_locked=True))
self.assertIn('support47b890', world_off)
self.assertIn('published_speed_zero_friction', world_off)
self.assertNotIn('reset_static_context', world_off)
self.assertIn('reset_static_context', geometry_off)
self.assertIn('geometry_off_support_anchor_acceleration_velocity', geometry_off)
def test_publication_compares_fresh_previous_and_live_root_vec4(self):
root = (1.0, 2.0, 3.0, 1.0)
self.assertTrue(can_publish(root, root))
for component in range(4):
changed = list(root)
changed[component] += 1
self.assertFalse(can_publish(root, changed))
with self.assertRaises(ValueError):
can_publish(root[:3], root[:3])
def test_burst_and_support_share_live_radius_and_factor(self):
targets = {entry['slot']: entry['target'] for entry in self.report['tables']}
self.assertEqual(targets['0x110'], '0x471240')
self.assertEqual(targets['0x260'], '0x471b30')
self.assertEqual(targets['0x264'], '0x471b40')
self.assertEqual(targets['0x250'], '0x471af0')
self.assertEqual(targets['0x254'], '0x471b00')
self.assertAlmostEqual(self.report['constants']['factor'], 1.265, places=6)
def test_init_restores_authored_speed_separately_from_controller_publication(self):
targets = {entry['slot']: entry['target'] for entry in self.report['tables']}
self.assertEqual(targets['0x114'], '0x471260')
self.assertEqual(targets['0x118'], '0x471270')
self.assertEqual(targets['0x268'], '0x471b50')
self.assertEqual(targets['0x26c'], '0x471b60')
sites = {site['name']: site for site in self.report['sites']}
self.assertEqual(sites['init_authored_speed114']['file_offset'], '0x706cf')
self.assertEqual(sites['init_publish_speed26c']['file_offset'], '0x706db')
self.assertIn('894138', sites['authored_speed_setter118_to_live26c']['bytes'])
self.assertNotIn('894138', sites['published_speed_setter26c']['bytes'])
self.assertEqual(self.report['constants']['constructor_authored_speed'], 0)
if __name__ == '__main__':
unittest.main()
+19
View File
@@ -0,0 +1,19 @@
from pathlib import Path
import sys
import unittest
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tools/binary'))
from body_root_registration import collect
class BodyRootRegistrationTests(unittest.TestCase):
def test_registration_and_repeated_init_bytes(self):
result=collect(ROOT.parent/'Original')
self.assertEqual(len(result['sites']),14)
self.assertEqual(len(result['tables']),4)
targets={x['name']:x['target'] for x in result['tables']}
self.assertEqual(targets['Jimmy InitPhysics'],'0x42ab50')
self.assertEqual(targets['authored root'],'0x471630')
if __name__=='__main__':unittest.main()
+21
View File
@@ -0,0 +1,21 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/binary'))
from body_step_evidence import collect
class BodyStepEvidenceTests(unittest.TestCase):
def test_guarded_source_bodies_and_explicit_relocations(self):
report = collect(ROOT.parent/'Original')
self.assertEqual(len(report['bodies']), 15)
operands = report['probe_operands']
self.assertEqual(len({item['va'] for item in operands}), len(operands))
targets = {item['target'] for item in operands}
self.assertTrue({0x4f69e5, 0x5cfc7c, 0x695d54, 0x695d58}.issubset(targets))
if __name__ == '__main__':
unittest.main()
+60
View File
@@ -0,0 +1,60 @@
"""Shared-eye source anchors and phase-specific DEFAULT/follow boundaries."""
from pathlib import Path
import struct
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from camera_handoff import CameraProjection, collect, default_handoff, normal_follow
class CameraHandoffTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_original_shared_storage_and_callback_targets(self):
sites = {s['name']: s for s in self.report['sites']}
self.assertEqual(sites['walking_previous_x']['bytes'], 'd94044d99d14070000')
self.assertEqual(sites['airborne_previous_x']['bytes'], 'd94044d95c243c')
self.assertEqual(self.report['threshold']['value'], 1000)
targets = {t['name']: t['target'] for t in self.report['tables']}
self.assertEqual(targets['Jimmy walking input/follow'], '0x438bc0')
self.assertEqual(targets['Jimmy airborne input/follow'], '0x439900')
def test_default_below_equal_above_and_already_owned(self):
threshold_bits, = struct.unpack('<I', struct.pack('<f', 1000))
for offset, snapped in ((-1, False), (0, False), (1, True)):
distance, = struct.unpack('<f', struct.pack('<I', threshold_bits+offset))
view = CameraProjection((distance, 0, 0), (1, 2, 3))
result = default_handoff(view, (0, 0, 0), False)
self.assertEqual(result.eye, (0, 0, 0) if snapped else view.eye)
self.assertEqual(result.direction, view.direction, 'DEFAULT changes no orientation in this block')
owned = CameraProjection((5000, 0, 0), (1, 0, 0))
self.assertEqual(default_handoff(owned, (0, 0, 0), True), owned)
def test_first_resumed_follow_uses_scripted_shared_eye(self):
scripted = CameraProjection((600, 200, -200), (-600, -100, 200))
restored = default_handoff(scripted, (0, 500, -500), False)
self.assertEqual(restored, scripted, 'Within threshold retains scripted shared eye')
followed = normal_follow(restored, (0, 180, -350), (0, 99, 0), 1/60)
self.assertAlmostEqual(followed.eye[0], 584)
self.assertAlmostEqual(followed.eye[1], 199.6)
self.assertAlmostEqual(followed.eye[2], -204)
self.assertEqual(followed.direction, (-600, -101, 200), 'Aim derives from pre-update shared eye')
stale = CameraProjection((0, 180, -350), (0, 0, 1))
self.assertNotEqual(normal_follow(stale, (0, 180, -350), (0, 99, 0), 1/60).eye, followed.eye)
def test_snap_then_follow_preserves_phase_boundary(self):
scripted = CameraProjection((5000, 500, -500), (-1, 0, 0))
snapped = default_handoff(scripted, (0, 500, -500), False)
self.assertEqual(snapped.eye, (0, 500, -500))
self.assertEqual(snapped.direction, scripted.direction)
followed = normal_follow(snapped, (0, 180, -350), (0, 99, 0), 1/60, 1.5)
self.assertAlmostEqual(followed.eye[1], 490.4)
self.assertEqual(followed.direction, (0, -401, 500))
if __name__ == '__main__':
unittest.main()
+50
View File
@@ -0,0 +1,50 @@
"""Byte-guarded Jimmy ceiling query and cancellation boundaries."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from ceiling_wrapper import CeilingState, ceiling_projection, collect, upward_segment
class CeilingWrapperTests(unittest.TestCase):
def test_original_byte_constants_and_virtual_contracts(self):
report = collect(ROOT.parent / 'Original')
self.assertEqual(len(report['sites']), 37)
self.assertEqual(len(report['tables']), 8)
self.assertEqual(len(report['constants']), 6)
self.assertEqual(len(report['bodies']), 4)
def test_query_is_logical_root_to_plus150_not_capsule_top(self):
self.assertEqual(upward_segment((10, 75, 20)), ((10, 75, 20), (10, 225, 20)))
with self.assertRaises(ValueError):
upward_segment((0, float('nan'), 0))
def test_only_upward_hit_changes_velocity_with_minimum_downward_speed(self):
for vy in (0, -1, -200):
state = CeilingState((3, vy, 4), 1, 3, 8)
self.assertEqual(ceiling_projection(state, True), (state, ()))
slow = CeilingState((3, 10, 4), 1, 3, 8)
self.assertEqual(ceiling_projection(slow, False), (slow, ('query47C210',)))
self.assertEqual(ceiling_projection(slow, True)[0].velocity, (3, -85, 4))
fast = CeilingState((3, 200, 4), 1, 3, 8)
self.assertEqual(ceiling_projection(fast, True)[0].velocity, (3, -120, 4))
def test_cancel_is_mode1_only_and_preserves_other_motion_fields(self):
state = CeilingState((3, 10, 4), 1, 3, 8, .625, 264, 550)
result, events = ceiling_projection(state, True)
self.assertEqual((result.mode, result.jump, result.fire_remaining), (1, 0, 0))
self.assertEqual((result.hold, result.extra_acceleration, result.queued_impulse), (.625, 264, 550))
self.assertEqual(events, ('query47C210', 'velocity2C4', 'cancel1E0', 'FALL', 'cleanup140'))
for mode in (-1, 0, 2):
source = CeilingState((3, 10, 4), mode, 3, 8)
result, events = ceiling_projection(source, True)
self.assertEqual((result.mode, result.jump, result.fire_remaining), (mode, 3, 8))
self.assertEqual(events, ('query47C210', 'velocity2C4', 'cancel1E0'))
missing = CeilingState((3, 10, 4), 1, 3, None)
self.assertIsNone(ceiling_projection(missing, True)[0].fire_remaining)
if __name__ == '__main__':
unittest.main()
+110
View File
@@ -0,0 +1,110 @@
"""Bounded contact/friction source signatures and state boundary fixtures."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from collision_contact_callbacks import (
collect, normal_callback, NORMAL_Y_THRESHOLD, ceiling_projection,
player_material_actions, jimmy_contact_actions, friction_projection, landing_phases,
)
class CollisionContactCallbacksTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_exact_source_identity_targets_and_complete_callbacks(self):
self.assertEqual(len(self.report['sites']), 50)
self.assertEqual(len(self.report['tables']), 20)
self.assertEqual(len(self.report['bodies']), 6)
self.assertFalse(any(b['raw_control_reference'] for b in self.report['bodies']))
targets = {(t['owner'], t['slot']): t['target'] for t in self.report['tables']}
self.assertEqual(targets['Jimmy', '0x374'], '0x42a660')
self.assertEqual(targets['Object', '0x374'], '0x458890')
self.assertEqual(targets['Jimmy', '0x37c'], '0x472970')
def test_ceiling_callback_dispatch_has_strict_threshold(self):
self.assertEqual(normal_callback(NORMAL_Y_THRESHOLD), 0x370)
self.assertEqual(normal_callback(NORMAL_Y_THRESHOLD-.00001), 0x370)
self.assertEqual(normal_callback(NORMAL_Y_THRESHOLD+.00001), 0x374)
def test_ceiling_changes_only_independently_positive_y(self):
self.assertEqual(ceiling_projection((1, 5, 3, 7), (4, -2, 6, 8)),
((1, 0, 3, 7), (4, -2, 6, 8)))
self.assertEqual(ceiling_projection((1, -5, 3, 7), (4, 2, 6, 8)),
((1, -5, 3, 7), (4, 0, 6, 8)))
self.assertEqual(ceiling_projection((1, 0, 3, 7), (4, 0, 6, 8)),
((1, 0, 3, 7), (4, 0, 6, 8)))
def test_ordinary_material_is_not_generic_velocity_projection(self):
for elapsed in (0, 3, 4):
self.assertEqual(player_material_actions(17, elapsed, 0), ())
self.assertEqual(player_material_actions(120, 3, 0), ())
self.assertEqual(player_material_actions(120, 3.01, 1), ('complete160',))
self.assertEqual(player_material_actions(119, 4, 1), ('complete164',))
self.assertEqual(player_material_actions(60, 4, 0), ('fence_query',))
self.assertEqual(player_material_actions(69, 4, 1), ())
self.assertEqual(player_material_actions(180, 4, 0), ('ladder_query',))
for material in (-1, 59, 70, 109, 130, 179, 181):
self.assertEqual(player_material_actions(material, 4, 0), ())
def test_friction_is_gated_by_support_published_speed_and_linear_motion(self):
velocity, angular = (10, -5, 20, 7), (2, -4, 6, 8)
self.assertEqual(friction_projection(velocity, angular, .8, .25),
((8, -5, 16, 7), (1.6, -3.2, 4.8, 8)))
for options in ({'support': False}, {'published_speed': 2}, {'published_speed': -2}):
self.assertEqual(friction_projection(velocity, angular, .8, .25, **options),
(velocity, angular))
# No planar motion still damps angular velocity when vertical motion exists.
self.assertEqual(friction_projection((0, 5, 0), (2, 4, 6), .8, .25),
((0, 5, 0), (1.6, 3.2, 4.8)))
self.assertEqual(friction_projection((0, 0, 0), angular, .8, .25),
((0, 0, 0), angular))
# The source multiplier is not clamped to prevent reversal.
self.assertEqual(friction_projection((10, 5, 20), (2, 4, 6), 2, 1),
((-10, 5, -20), (-2, -4, -6)))
def test_no_selection_and_jetpack_bypass_extra_gadget_effects(self):
for selected in (-1, 3):
for mode in (0, 1):
self.assertEqual(jimmy_contact_actions(selected, 17, 4, mode), ())
self.assertEqual(jimmy_contact_actions(selected, 17, 4, mode,
gadget7_active=True), ())
self.assertEqual(jimmy_contact_actions(7, 17, 4, 0), ())
self.assertEqual(jimmy_contact_actions(7, 17, 4, 0, gadget7_active=True),
('gadget7_unresolved',))
def test_material_discriminator_is_linked_chunk_id_and_route_has_specials(self):
identity = self.report['material_identity']
self.assertEqual(len(identity['dll_sites']), 11)
expected = {
'level1b.omt': {61: 20, 62: 24, 63: 4, 120: 4, 121: 20, 122: 3, 180: 6},
'VR04.omt': {},
'level1.omt': {60: 62, 61: 38, 62: 26, 180: 20},
}
for archive in identity['archives']:
# Every used material payload has the same trailing value; the
# distinct source callback policy comes from its linked chunk ID.
self.assertEqual({m['payload_trailing'] for m in archive['materials']}, {3})
counts = {}
for polygon in archive['special_polygons']:
if polygon['potential374_wall']:
mid = polygon['material_id']
counts[mid] = counts.get(mid, 0) + 1
self.assertEqual(counts, expected[archive['name']])
material = next(m for m in archive['materials'] if m['id'] == 0)
self.assertNotEqual(material['table_id_offset'], material['payload_offset'])
def test_landing_callback_observes_old_velocity_and_support(self):
phases = landing_phases(False)
self.assertEqual(phases, ['root318', 'acceleration278_Y0',
'landing37C_noop_for_Jimmy', 'velocity2C4_Y0',
'support21C_true', 'shape34C', 'polygon33C'])
self.assertNotIn('landing37C_noop_for_Jimmy', landing_phases(True))
if __name__ == '__main__':
unittest.main()
+19
View File
@@ -0,0 +1,19 @@
from pathlib import Path
import sys
import unittest
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tools/binary'))
from collision_dispatch import collect
class DispatcherProbeTests(unittest.TestCase):
def test_source_callgraph_and_fixture_relocations(self):
report=collect(ROOT.parent/'Original')
self.assertEqual(len(report['bodies']),10)
operands=report['probe_operands']
self.assertEqual(len({p['va'] for p in operands}),len(operands))
self.assertTrue(any(p['target']==0x509B24 for p in operands))
self.assertTrue(any(p['target']==0x695D4C for p in operands))
if __name__=='__main__':unittest.main()
+79
View File
@@ -0,0 +1,79 @@
"""Static dispatcher source guards and independent ordering/state fixtures."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from collision_grid_traversal import (
EPSILON, NearestProjection, append_registration, cell, cells, collect,
scan_projection, traversal_bounds, visits,
)
class CollisionGridTraversalTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_source_retry_and_asymmetric_upper_bound_are_guarded(self):
sites = {s['name']: s for s in self.report['sites']}
self.assertEqual(sites['z_upper_uses_min']['bytes'], '663bf8897c2418ddd87c0489442418')
self.assertEqual(sites['retry_flag_branch']['bytes'], '8a44241384c00f8597000000')
self.assertEqual(sites['retry_call_same_dispatcher']['file_offset'], '0x7b877')
self.assertEqual(sites['wrapper_stores_last_polygon_and_retry']['bytes'], '89354c5d6900c60101')
bodies = {b['name']: b for b in self.report['bodies']}
self.assertEqual(bodies['static_dispatcher']['length'], 0x3D9)
self.assertEqual(self.report['constants']['0x4d5e40'], EPSILON)
self.assertAlmostEqual(self.report['constants']['0x4a3148'], -.7, places=7)
def test_extent_and_z_upper_min_are_distinct_from_x_upper_max(self):
self.assertEqual(cell(0), 130)
self.assertEqual(cell(-65001), 0, 'Truncate toward zero before signed-short storage')
self.assertEqual(traversal_bounds((0,0,0), (0,0,500), 50, 500), (128,131,128,131))
self.assertEqual(traversal_bounds((0,0,0), (500,0,0), 50, 500), (128,132,128,131))
self.assertEqual(traversal_bounds((0,0,0), (0,0,-500), 50, 500), (128,131,127,130))
def test_inclusive_x_outer_z_inner_and_skipped_outside_cells(self):
self.assertEqual(cells((1,2,4,5)), [(1,4),(1,5),(2,4),(2,5)])
self.assertEqual(cells((-1,1,258,260)), [(0,258),(0,259),(1,258),(1,259)])
self.assertEqual(cells((2,1,0,1)), [])
def test_polygon_only_per_cell_dedup_and_fifo_across_cells(self):
grid = {}
self.assertTrue(append_registration(grid, (1,2), 100, 20))
self.assertFalse(append_registration(grid, (1,2), 100, 99))
self.assertTrue(append_registration(grid, (1,2), 200, 20))
self.assertTrue(append_registration(grid, (1,3), 100, 20))
self.assertEqual(visits(grid, (1,1,2,3)), [
((1,2),(100,20)), ((1,2),(200,20)), ((1,3),(100,20)),
])
def test_mutable_candidate_and_nearest_survive_duplicate_visits_and_retry(self):
grid = {(1,2): [(100,20),(200,20)], (1,3): [(100,20)]}
nearest = NearestProjection(130000, 10)
observed = []
def first_pass(xy, polygon, candidate, state):
observed.append((xy, polygon[0], candidate, state.face, state.last_polygon))
self.assertIs(state, nearest)
if len(observed) == 1:
state.face = 3
return (8,9,10), True
return candidate, False
candidate, retry = scan_projection(grid, (1,1,2,3), (0,0,0), nearest, first_pass)
self.assertTrue(retry)
self.assertEqual(candidate, (8,9,10))
self.assertEqual(observed[1][2:], ((8,9,10),3,100))
self.assertEqual(observed[2][1], 100, 'A repeated cell visit is retained')
candidate, retry = scan_projection(
grid, (1,1,2,3), candidate, nearest,
lambda xy, polygon, current, state: (current, False))
self.assertFalse(retry)
self.assertEqual((nearest.face, nearest.edge, nearest.last_polygon), (3,10,100))
self.assertEqual(candidate, (8,9,10))
if __name__ == '__main__':
unittest.main()
+42
View File
@@ -0,0 +1,42 @@
from pathlib import Path
from types import SimpleNamespace
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/extractors'))
from omt import Entry, export_scene
class CollisionMaterialIdentityTests(unittest.TestCase):
def export(self, link, identity=61):
shape = dict(vertices=[(0, 0, 0), (1, 0, 0), (0, 1, 0)], normals=[],
polygons=[dict(corners=[dict(vertex=i, normal=0, uv=(0, 0)) for i in range(3)],
normal=(0, 0, 1), material=link)])
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
database = SimpleNamespace(path=root/'input'/'fixture.omt', data=b'fixture',
entries=[Entry('3DSh', 0, 0, 0, 'wall'), Entry('3DMa', identity, 0, 0, 'fence')],
payload=lambda entry: b'')
with patch('omt.read_shape', return_value=shape), patch('omt.read_material', return_value={}):
return export_scene(database, root/'output')['collisionPolygons'][0]
def test_archive_identity_is_preserved_independently_of_render_index(self):
polygon = self.export(dict(type='3DMa', id=61))
self.assertEqual((polygon['materialId'], polygon['materialName']), (61, 'fence'))
def test_null_missing_and_wrong_type_links_are_not_materials(self):
for link in (None, dict(type='3DMa', id=999), dict(type='3DSh', id=61)):
with self.subTest(link=link):
polygon = self.export(link)
self.assertIsNone(polygon['materialId'])
self.assertIsNone(polygon['materialName'])
def test_callback_identity_is_a_signed_long(self):
self.assertEqual(self.export(dict(type='3DMa', id=0xffffffff), 0xffffffff)['materialId'], -1)
if __name__ == '__main__':
unittest.main()
+27
View File
@@ -0,0 +1,27 @@
from pathlib import Path
import sys
import unittest
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tools/binary'))
from collision_response import collect, header, TARGETS
class CollisionResponseTests(unittest.TestCase):
def test_original_callgraph_bodies_and_constants(self):
report=collect(ROOT.parent/'Original')
self.assertEqual(len(report['bodies']),6)
self.assertAlmostEqual(report['constants']['0x48d974'],.7)
self.assertAlmostEqual(report['constants']['0x4a3148'],-.7)
self.assertEqual(report['constants']['0x49b1f8'],-1)
def test_probe_relocations_are_bounded_explicit_operands(self):
report=collect(ROOT.parent/'Original')
locations=[p['va'] for p in report['probe_operands']]
self.assertEqual(len(locations),len(set(locations)))
self.assertGreater(len(locations),40)
self.assertTrue(all(p['target'] in TARGETS for p in report['probe_operands']))
self.assertIn('{0x47c0c0, 0x48d104}',header(report))
if __name__=='__main__': unittest.main()
+69
View File
@@ -0,0 +1,69 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/binary'))
from gadget_controls import (collect, tab_action, hit_gadgets, practice_toggle,
default_device_selection, TILES)
class GadgetControlTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent/'Original')
def test_source_identity_spans_and_virtual_targets(self):
self.assertEqual(len(self.report['bodies']), 9)
self.assertEqual(len(self.report['sites']), 40)
self.assertEqual(len(self.report['vtables']), 10)
sites = {s['name']: s for s in self.report['sites']}
self.assertEqual(sites['tab_byte']['bytes'], 'a041985000')
self.assertEqual(sites['space_byte']['bytes'], 'a058985000')
self.assertEqual(sites['unequip_global']['file_offset'], '0x25ac2')
def test_tab_distinguishes_close_unequip_and_open_and_held_edge(self):
self.assertEqual(tab_action(True, -1), 'close')
self.assertEqual(tab_action(False, 5), 'unequip')
self.assertEqual(tab_action(False, -1), 'open_gadgets')
for opened in (True, False):
self.assertEqual(tab_action(opened, -1, latched=True), 'none')
def test_exact_tile_layout_and_strict_boundaries(self):
self.assertEqual(TILES[3], (157, 327))
for item, (x, y) in enumerate(TILES):
self.assertEqual(hit_gadgets([1]*8, x+70, y+70), item)
for a, b in ((x, y+70), (x+141, y+70), (x+70, y), (x+70, y+141)):
self.assertIsNone(hit_gadgets([1]*8, a, b))
def test_hit_filter_is_raw_state_not_owned_boolean(self):
x, y = TILES[3]
for state in (0, 4):
self.assertIsNone(hit_gadgets([state]*8, x+70, y+70))
for state in (1, 2, 3, -1):
self.assertEqual(hit_gadgets([state]*8, x+70, y+70), 3)
def test_display_highlight_three_is_not_equipped_mode_three(self):
table = self.report['selection_table']
self.assertEqual(table[0], table[4]) # Requested−1 and3 share branch428DE0.
state = default_device_selection(3)
self.assertEqual((state['highlight'], state['equipped_mode']), (3, -1))
self.assertIsNone(state['practice_level'])
def test_practice_toggles_only_outside_tutorial_and_before_scene500(self):
self.assertEqual(practice_toggle(3, 'LV1B', 60), 2)
self.assertEqual(practice_toggle(2, 'LV1B', 60), 3)
self.assertEqual(practice_toggle(3, 'LV1B', 500), 3)
for i in range(1, 9):
self.assertEqual(practice_toggle(3, f'VR0{i}', 60), 3)
state = default_device_selection(2)
self.assertEqual((state['practice_level'], state['practice_state']), ('VR04', 1))
def test_practice_destination_calls_match_all_eight_item_indices(self):
self.assertEqual([p['level'] for p in self.report['practice']], [f'vr0{i}.gam' for i in range(1,9)])
sites = {s['name']: s for s in self.report['sites']}
self.assertEqual(sites['initial_practice_return_state1']['bytes'], '6a016a0953e8f814feff6a016a0a53e8ee14feff')
if __name__ == '__main__':
unittest.main()
+57
View File
@@ -0,0 +1,57 @@
import hashlib
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent/'Original'
sys.path.insert(0, str(ROOT/'tools/extractors'))
from gadget_resources import CANVASES, export_gadget_resources
from omt import Database, FormatError
@unittest.skipUnless(ORIGINAL.exists(), 'Original assets are local integration fixtures')
class GadgetResourceTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.database = Database(ORIGINAL/'omt/screens.omt')
def test_exact_original_pixels_identities_and_dimensions_are_preserved(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'gadgets'
manifest = export_gadget_resources(self.database, output)
self.assertEqual(manifest['sourceSha256'], 'e8e95231f5d302b41f4fbf33df1c5a08ce4645370f9f519527ff1727b73b7a5e')
self.assertEqual((manifest['referenceWidth'], manifest['referenceHeight']), (640, 480))
self.assertEqual(len(manifest['textures']), 54)
self.assertEqual(len({texture['id'] for texture in manifest['textures']}), 54)
self.assertEqual(manifest, json.loads((output/'gadgets.json').read_text()))
by_id = {texture['id']: texture for texture in manifest['textures']}
self.assertEqual(by_id[14]['name'], 'item04')
self.assertEqual(manifest['tiles'][3]['label'], 'SHRINK RAY')
self.assertEqual(by_id[119]['name'], '9jetpack')
self.assertEqual((by_id[253]['width'], by_id[253]['height']), (15, 210))
for texture in manifest['textures']:
rgba = (output/texture['path']).read_bytes()
self.assertEqual(len(rgba), texture['width']*texture['height']*4)
self.assertEqual(hashlib.sha256(rgba).hexdigest(), texture['rgbaSha256'])
self.assertTrue((output/texture['png']).is_file())
def test_exports_cannot_overwrite_any_original_asset_subtree(self):
for output in (ORIGINAL, ORIGINAL/'omt/generated', ORIGINAL/'ASE/generated', ORIGINAL/'png/generated'):
with self.subTest(output=output), self.assertRaises(ValueError):
export_gadget_resources(self.database, output)
def test_changed_resource_contract_rejects_before_writing(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'gadgets'
with patch('gadget_resources.read_canvas', return_value=dict(width=1, height=1, rgba=b'\0'*4)):
with self.assertRaises(FormatError):
export_gadget_resources(self.database, output)
self.assertFalse(output.exists())
if __name__ == '__main__':
unittest.main()
+59
View File
@@ -0,0 +1,59 @@
import math
from pathlib import Path
import sys
import unittest
PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT / 'tools/binary'))
import shrink_heading as heading
class ShrinkHeadingTests(unittest.TestCase):
def test_quadrants(self):
for x, z, units in [(0, 0, 0), (0, 1, 0), (-1, 0, 4096),
(0, -1, 8192), (1, 0, 12288),
(-1, 1, 2048), (-1, -1, 6144),
(1, -1, 10240), (1, 1, 14336)]:
self.assertEqual(heading.heading_units(x, z), units)
def test_strict_window_and_no_seam_wrap(self):
self.assertTrue(heading.within_heading_window(0, 1, 0))
self.assertFalse(heading.within_heading_window(0, 1, 5))
self.assertFalse(heading.within_heading_window(0, 1, -5))
self.assertFalse(heading.within_heading_window(1, 1000, 0))
self.assertTrue(heading.within_heading_window(-1, 1000, 0))
def test_nonfinite(self):
for value in [math.nan, math.inf, -math.inf]:
with self.assertRaises(ValueError):
heading.heading_units(value, 1)
def test_copied_dll_samples(self):
for x, z, expected in [(1, 1000, 16364), (-1, 1000, 20),
(1000, 1, 12288), (-1000, 1, 4096),
(.1234567, .7654321, 15967), (-99.1, 15.7, 3686)]:
self.assertEqual(heading.heading_units(x, z), expected)
def test_copied_dll_full_bin_quadrant_sweep(self):
fingerprint = 2166136261
for i in range(16385):
a = heading.f32(math.sqrt((i + .25) / 16384.5))
b = heading.f32(math.sqrt(1 - (i + .25) / 16384.5))
for quadrant in range(4):
value = heading.heading_units(-b if quadrant & 1 else b,
-a if quadrant & 2 else a)
fingerprint = ((fingerprint ^ value) * 16777619) & 0xffffffff
self.assertEqual(fingerprint, 0x24e64f91)
def test_full_source_identity(self):
exe = PROJECT / 'artifacts/uncontrolled-phases/rea/Neutron.exe'
dll = PROJECT / 'artifacts/asset-probe/game/OMT2.dll'
if not exe.exists() or not dll.exists():
self.skipTest('generated original copies unavailable')
report = heading.evidence(exe, dll)
self.assertEqual(report['table_fnv32'], '4f800433')
self.assertEqual(report['exported']['ordinal'], 278)
if __name__ == '__main__':
unittest.main()
+67
View File
@@ -0,0 +1,67 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/binary'))
from shrink_ray import collect, target_eligible, texture_step, f32
class ShrinkRaySourceTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent/'Original')
def test_source_bodies_constants_assets_and_opacity(self):
self.assertEqual(len(self.report['bodies']), 8)
self.assertEqual(self.report['constants'], dict(lower_y=150, upper_y=60, range=1500,
yaw_half_angle=5, angle_unit_degrees=.02197265625, texture_period=.1))
self.assertEqual(self.report['strings']['0x4ef71c'], 'SHRINK')
self.assertEqual(self.report['strings']['0x4f0b78'], 'ray.ase')
names = {site['name'] for site in self.report['sites']}
self.assertTrue({'alpha_not_scale', 'blend_src6', 'ray_rotation_copy', 'target_callback'}.issubset(names))
def test_default_owned3_uses_mode_minus1_not_menu_highlight3(self):
p, t = (0, 0, 0), (0, 0, 100)
self.assertTrue(target_eligible(p, t, 0, 0))
for state in (0, 2, 3, 4):
self.assertFalse(target_eligible(p, t, 0, 0, owned_state=state))
for mode in range(8):
self.assertFalse(target_eligible(p, t, 0, 0, equipped_mode=mode))
def test_target_class_enabled_and_already_shrunk_gates_are_independent(self):
p, t = (0, 0, 0), (0, 0, 100)
for kw in (dict(integrates=False), dict(enemy=False), dict(enabled=False), dict(shrunk=True), dict(wall_hit=True)):
self.assertFalse(target_eligible(p, t, 0, 0, **kw))
def test_strict_range_and_height(self):
p = (0, 0, 0)
self.assertTrue(target_eligible(p, (0, 0, 1499.99), 0, 0))
self.assertFalse(target_eligible(p, (0, 0, 1500), 0, 0))
for y in (-150, 60):
self.assertFalse(target_eligible(p, (0, y, 100), 0, 0))
for y in (-149.999, 59.999):
self.assertTrue(target_eligible(p, (0, y, 100), 0, 0))
def test_strict_quantized_yaw_window_does_not_add_seam_wrapping(self):
p, t = (0, 0, 0), (0, 0, 100)
for angle in (-5, 5, 359):
self.assertFalse(target_eligible(p, t, 0, angle))
for angle in (-4.999, 0, 4.999):
self.assertTrue(target_eligible(p, t, 0, angle))
def test_texture_float_accumulator_double_threshold_and_single_advance(self):
self.assertEqual(texture_step(0, 0, .099999994), (0, f32(.099999994)))
self.assertEqual(texture_step(0, 0, f32(.1)), (1, 0))
self.assertEqual(texture_step(2, 0, .5), (0, 0))
self.assertEqual(texture_step(1, .09, .02), (2, 0))
def test_original_engine_blend_table_distinguishes_additive_and_alpha(self):
blend = self.report['blend']
self.assertEqual((blend['source_alpha'], blend['additive_destination'], blend['alpha_destination']), (5, 2, 6))
self.assertEqual(blend['body_file_offset'], '0x36ab0')
self.assertEqual(blend['table_file_offset'], '0x13667c')
if __name__ == '__main__':
unittest.main()
+65
View File
@@ -0,0 +1,65 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools' / 'binary'))
from shrink_targets import collect, timer_step
class ShrinkTargetSourceTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_original_byte_body_and_dispatch_identity(self):
self.assertTrue(self.report['known_binary'])
for group in ('bodies', 'sites', 'vtables', 'strings', 'clips'):
with self.subTest(group=group):
self.assertTrue(all(x['matches'] for x in self.report[group]))
self.assertEqual(len(self.report['bodies']), 8)
self.assertEqual((self.report['radius'], self.report['factor']), (90, 1))
modes = self.report['modes']
self.assertFalse(modes['shrink_snapshots_authored'])
self.assertEqual((modes['current_complete'], modes['previous_complete'], modes['authored_complete']),
('0x6c8', '0x6cc', '0x93c'))
self.assertEqual((modes['authored_property'], modes['initial_authored'], modes['expiry_restores']),
('AIState', 2, 'authored'))
def test_shrink_is_authored_geometry_with_compatible_topology(self):
clips = {c['name'].casefold(): c for c in self.report['clips']}
shrink = clips['soldshrink.ase']
self.assertEqual(shrink['times'], [0, 960, 1920, 2880, 3840])
self.assertEqual((shrink['frames_per_second'], shrink['ticks_per_frame']), (5, 960))
heights = [high-low for low, high in shrink['y_bounds']]
self.assertTrue(all(a > b for a, b in zip(heights, heights[1:])))
self.assertAlmostEqual(heights[0], 315.8297)
self.assertAlmostEqual(heights[-1], 55.1186)
for clip in clips.values():
self.assertEqual(set(clip['vertex_counts']), {190})
self.assertEqual(set(clip['face_counts']), {377})
self.assertEqual({t['name'].casefold() for t in self.report['textures']},
{'vryoksoldier.png', 'yoksold.png', 'yoksoldtalk.png'})
def test_timer_preserves_strict_original_expiry_boundary(self):
self.assertEqual(timer_step(30, 1), (29, True, False))
self.assertEqual(timer_step(.25, .5), (0, False, True))
self.assertEqual(timer_step(.25, .25), (0, True, False))
self.assertEqual(timer_step(0, 1), (0, True, False))
self.assertEqual(timer_step(0, 1, False), (0, False, False))
def test_original_vr04_has_three_authored_soldiers(self):
targets = self.report['vr04']['targets']
self.assertEqual([t['file_offset'] for t in targets], ['0x4431', '0x582c', '0x67c5'])
self.assertEqual([t['fields']['ObjectTag'] for t in targets],
['yoke1', 'C3DYOKIANSOLDIER', 'yoke2'])
for target in targets:
fields = target['fields']
self.assertEqual((fields['HasCollision'], fields['CanMove'], fields['AIState']), (1, 1, 2))
self.assertGreater(fields['PositionY'], 6300)
self.assertAlmostEqual(targets[0]['fields']['PositionX'], -2463.103515625)
self.assertAlmostEqual(targets[2]['fields']['PositionZ'], 1319.027587890625)
if __name__ == '__main__':
unittest.main()
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""Read-only479D20 composition guards, grounded in retained REA body evidence."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
BODY_START = 0x479D20
BODY_END = 0x47A32A
BODY_SHA256 = '5f4b05518bef5e5f0ecc3909ff0de0b43d2c7350c6beae0c4f797d3238a77fa1'
REA_BODY = 'ev_5439072b32ae9f9208795ad2b07bc524e2407b46da487072fb3dfd8c10e7c4b0'
SITES = (
('read_previous_support', 0x479D2E, 'ff9018020000'),
('cache_previous_support', 0x479D34, 'a2495d6900'),
('read_support_enabled_before_integration_gate', 0x479D3D, 'ff92c8010000'),
('clear_current_support', 0x479D4E, 'ff901c020000'),
('integration_gate', 0x479D58, 'ff9210020000'),
('disabled_integration_return', 0x479D60, '0f84bd050000'),
('geometry_global_gate', 0x479DDA, '381de5694f00'),
('geometry_enabled_anchor', 0x479DE4, '8b1653680050c3c6538bceff92f4020000'),
('geometry_disabled_support_true', 0x479DF9, '6a018bceff901c020000'),
('geometry_disabled_anchor_current_y', 0x479E03, '8b4424408b165350538bceff92f4020000'),
('geometry_disabled_inverse_gravity_y', 0x479E14, 'd90504fc5c00'),
('geometry_disabled_acceleration_xyz', 0x479E26, 'ff9278020000'),
('geometry_disabled_velocity_y_zero', 0x479E54, 'ff97c4020000'),
('read_angular_velocity', 0x479E63, 'ff92ac020000'),
('rotate_before_impulse', 0x479EAC, 'ff9034030000'),
('read_pending_impulse', 0x479EBB, 'ff9284020000'),
('add_pending_impulse', 0x479EE5, 'ff97cc020000'),
('consume_pending_impulse', 0x479EF2, 'ff928c020000'),
('read_acceleration', 0x479F01, 'ff9070020000'),
('add_acceleration', 0x479F4A, 'ff92cc020000'),
('add_gravity', 0x479F7E, 'ff90cc020000'),
('read_final_velocity', 0x479F8D, 'ff92bc020000'),
('collision220_gate', 0x479FD6, 'ff9020020000'),
('world1d0_gate', 0x479FE8, 'ff92d0010000'),
('reset_last_polygon', 0x47A038, '891d4c5d6900'),
('reset_nearest_face130000', 0x47A03E, 'c7055c5d690000e8fd47'),
('reset_nearest_edge_radius', 0x47A062, 'd91de0fb5c00'),
('capture_previous_root', 0x47A084, 'ff90fc020000'),
('delta_y_compare_zero', 0x47A08A, 'd90514d94800d9442430d8d9'),
('reset_auxiliary_collision_state', 0x47A096, '891d845d6900'),
('delta_y_nonpositive_branch', 0x47A09E, 'f6c441753d'),
('positive_full_dispatch', 0x47A0D6, 'e8d5130000'),
('nonpositive_horizontal_dispatch', 0x47A10F, 'e89c130000'),
('add_vertical_after_horizontal', 0x47A114, 'd944243cd844244c83c41cd95c2420'),
('read_previous_root_after_callback', 0x47A12C, 'ff92f8020000'),
('read_live_root_after_callback', 0x47A13D, 'ff9210030000'),
('root_compare_x', 0x47A143, 'd9078bc8d819'),
('root_compare_y', 0x47A154, 'd94704d85904'),
('root_compare_z', 0x47A165, 'd94708d85908'),
('root_compare_w', 0x47A176, 'd9470cd8590c'),
('clamp_candidate_y', 0x47A187, 'd9442420d81d086a4d00'),
('clamp_candidate_y_store', 0x47A198, 'c74424200050c3c6'),
('publish_candidate314', 0x47A1C4, 'ff9014030000'),
('world_disabled_capture_previous', 0x47A1FA, 'ff92fc020000'),
('world_disabled_translate', 0x47A220, 'ff921c030000'),
('post_motion_support_gate', 0x47A22A, 'ff90c8010000'),
('post_motion_support', 0x47A235, 'e856160000'),
('read_published_speed_for_friction', 0x47A241, 'ff9268020000'),
('friction', 0x47A25A, 'e8d1000000'),
('collision_disabled228_gate', 0x47A264, 'ff9228020000'),
('collision_disabled_translate', 0x47A28E, 'ff921c030000'),
('suppression_scale', 0x47A298, 'ff9030020000'),
('angular_suppression_inclusive', 0x47A2C5, 'f6c441740d'),
('angular_suppression_zero', 0x47A2D1, 'ff92b4020000'),
('linear_suppression_inclusive', 0x47A2FA, 'f6c4417424'),
('linear_suppression_published_speed', 0x47A303, 'ff9268020000'),
('linear_suppression_zero', 0x47A31D, 'ff90c4020000'),
('ctor_suppression_scale_half', 0x46FE01, '680000003f8bcde813130000'),
('player_friction_point8', 0x4373B0, '68cdcc4c3f'),
('player_friction_setter', 0x4373BD, 'e8ee9d0300'),
('friction_authored_to_live24c', 0x4711B0, '8b4424048b1150894128ff924c020000c20400'),
('jimmy_postload_radius60', 0x4236A3, '6800007042'),
('jimmy_postload_factor1265', 0x4236B3, '6885eba13f'),
('air_helper_complete_to_interface', 0x437FA3, '8dbec0000000'),
('burst_radius100', 0x4384E4, '680000c842'),
('burst_live_radius264', 0x4384F3, 'ff9264020000'),
('held_landing_radius60', 0x4386C1, '6800007042'),
('held_landing_live_radius264', 0x4386C8, 'ff9264020000'),
('authored_radius_to_live264', 0x471240, '8b4424048b1150894134ff9264020000c20400'),
('live_radius260', 0x471B30, 'd9815c010000c3'),
('live_radius264', 0x471B40, '8b44240489815c010000c20400'),
('live_support_factor250', 0x471AF0, 'd98154010000c3'),
('live_support_factor254', 0x471B00, '8b442404898154010000c20400'),
('ctor_zero_register', 0x46FC08, '33db'),
('ctor_authored_speed_zero', 0x46FE51, '538bcde817140000'),
('authored_speed_getter114', 0x471260, 'd94138c3'),
('authored_speed_setter118_to_live26c', 0x471270, '8b4424048b1150894138ff926c020000c20400'),
('init_authored_speed114', 0x4706CF, 'ff9714010000'),
('init_publish_speed26c', 0x4706DB, 'ff976c020000'),
('published_speed_getter268', 0x471B50, 'd98160010000c3'),
('published_speed_setter26c', 0x471B60, '8b442404898160010000c20400'),
)
TABLES = ((0x100, 0x4711E0), (0x110, 0x471240), (0x248, 0x471AD0),
(0x24C, 0x471AE0), (0x250, 0x471AF0), (0x254, 0x471B00),
(0x260, 0x471B30), (0x264, 0x471B40), (0x114, 0x471260),
(0x118, 0x471270), (0x268, 0x471B50), (0x26C, 0x471B60))
def phase_order(*, support_enabled=True, integration_enabled=True,
geometry_enabled=True, collision_enabled=True, world_enabled=True,
translation_locked=False, upward=False):
"""Control-flow projection only; no numeric/body or native execution claim."""
phases = ['read_previous_support']
if support_enabled:
phases.append('clear_current_support')
phases.append('integration_gate')
if not integration_enabled:
return phases
phases.append('anchor_far_below' if geometry_enabled else 'geometry_off_support_anchor_acceleration_velocity')
phases.extend(('rotate', 'impulse_add', 'impulse_clear', 'acceleration_add', 'gravity_add', 'velocity_to_delta'))
if collision_enabled:
if world_enabled:
phases.extend(('reset_static_context', 'capture_previous_root',
'full_dispatch' if upward else 'horizontal_dispatch'))
if not upward:
phases.append('add_fall_y')
phases.extend(('compare_previous_live_root_vec4', 'conditional_clamp_y_publish314'))
else:
phases.extend(('capture_previous_root', 'translate31c'))
if support_enabled:
phases.append('support47b890')
phases.append('published_speed_zero_friction')
elif not translation_locked:
phases.append('translate31c')
phases.extend(('angular_suppression', 'published_speed_zero_linear_suppression'))
return phases
def can_publish(previous_root, live_root):
"""Finite Vec4 equality predicate47A143..47A181, after contact callback."""
if len(previous_root) != 4 or len(live_root) != 4:
raise ValueError('Source publication comparison is Vec4')
return all(a == b for a, b in zip(previous_root, live_root, strict=True))
def collect(original):
pe = PE(find_case(Path(original), 'Neutron.exe'))
digest = hashlib.sha256(pe.data).hexdigest()
if digest != EXE_SHA256:
raise ValueError('Unexpected original executable identity')
body = read_va(pe, BODY_START, BODY_END-BODY_START)
if hashlib.sha256(body).hexdigest() != BODY_SHA256:
raise ValueError('Changed body integration instructions')
sites = []
for name, va, expected in SITES:
actual = read_va(pe, va, len(bytes.fromhex(expected)))
if actual.hex() != expected:
raise ValueError(f'Changed source site {name} at {va:x}')
sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), bytes=expected))
factor = struct.unpack('<f', read_va(pe, 0x4236B4, 4))[0]
if factor != struct.unpack('<f', struct.pack('<f', 1.265))[0]:
raise ValueError('Changed ordinary Jimmy support factor')
tables = []
for slot, expected in TABLES:
target = struct.unpack('<I', read_va(pe, 0x4A373C+slot, 4))[0]
if target != expected:
raise ValueError(f'Changed Jimmy interface slot {slot:x}')
tables.append(dict(slot=hex(slot), va=hex(0x4A373C+slot),
file_offset=hex(pe.offset(0x4A373C+slot-pe.base)), target=hex(target)))
return dict(sha256=digest, rea_body_evidence=REA_BODY,
body=dict(va=hex(BODY_START), file_offset=hex(pe.offset(BODY_START-pe.base)),
length=len(body), sha256=BODY_SHA256), sites=sites, tables=tables,
constants=dict(radius=60, factor=factor, friction=.8, suppression_scale=.5,
constructor_authored_speed=0),
limits=['finite-input control-flow projection', 'no original code execution',
'global dynamic state and special contacts remain separate'])
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
print(json.dumps(collect(parser.parse_args().original), indent=2))
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
"""Read-only retained physical registration and logical-root instruction guards."""
import argparse
import hashlib
import json
from pathlib import Path
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
SITES=(
('loader_clears_registration',0x46E131,'c6819e04000000'),
('jimmy_registration_guard',0x42AB50,'8a819e04000084c07505'),
('jimmy_registration_jump',0x42AB5A,'e971780300'),
('postload_registration_callback',0x4238B4,'ff502c'),
('registration_base_init',0x4623E7,'e82465ffff'),
('registration_authored_root',0x462405,'ff926c010000'),
('registration_authored_euler',0x462451,'ff9074010000'),
('registration_add_body',0x462464,'e8d7750100'),
('add_body_zero_authored_vector',0x479A5F,'6a006a006a00ff9250010000'),
('add_body_repeats_init',0x479A6F,'ff5028'),
('add_body_list',0x479A72,'8b3d3c5d6900'),
('add_body_node_bytes',0x479A78,'6a0c'),
('add_body_interface_payload',0x479AA9,'8930'),
('add_body_count',0x479AAB,'ff05405d6900'),
)
TABLES=(('Jimmy InitPhysics',0x2C,0x42AB50),
('authored root',0x16C,0x471630),
('authored Euler',0x174,0x4716D0),
('Jimmy Init',0x28,0x437890))
def collect(original):
pe=PE(find_case(Path(original),'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest()!=EXE_SHA256: raise ValueError('Unsupported EXE')
sites=[]
for name,va,expected in SITES:
actual=read_va(pe,va,len(bytes.fromhex(expected))).hex()
if actual!=expected: raise ValueError(f'{name} changed at {va:#x}: {actual}')
sites.append(dict(name=name,va=hex(va),file_offset=hex(pe.offset(va-pe.base)),bytes=actual))
tables=[]
for name,slot,expected in TABLES:
actual=struct.unpack('<I',read_va(pe,0x4A373C+slot,4))[0]
if actual!=expected: raise ValueError(f'{name} slot changed: {actual:#x}')
tables.append(dict(name=name,slot=hex(slot),target=hex(actual)))
return dict(sha256=EXE_SHA256,sites=sites,tables=tables,
scope='Static registration/reset chain; no original whole-loader execution or inferred collider height.')
if __name__=='__main__':
cli=argparse.ArgumentParser(description=__doc__);cli.add_argument('original',type=Path)
print(json.dumps(collect(cli.parse_args().original),indent=2))
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Read-only full body/support callgraph guards for the isolated component probe."""
import argparse
import hashlib
import json
from pathlib import Path
import struct
from collision_dispatch import collect as dispatch_collect, POINTERS
from collision_response import header
from checkpoint_script_state import find_case, read_va
from pe_inspect import PE
BODIES=(
('body_step',0x479D20,0x47A32A,'5f4b05518bef5e5f0ecc3909ff0de0b43d2c7350c6beae0c4f797d3238a77fa1'),
('friction',0x47A330,0x47A421,'3ac4d0268edb5fa4f5689a87fdc36759c12589caf76b2286b1817f2204a91155'),
('support',0x47B890,0x47BBB0,'5901c9475092af33db8015b58416475e9fa2c527b9e8860e36c0b4cc0ff3f25d'),
('support_query',0x47C6E0,0x47CA8B,'0f6127ef4e4bf7986ef195340002fbd97d3b6f1151377d053b1ad8d0c096cf57'),
('support_triangle',0x469A10,0x469B70,'6acde1608be611364a84ae8dadaa2f2675231f5ee9612445e7cb5e375e5d4e77'))
GLOBALS=sorted(set((*POINTERS,0x48D920,0x4D6A08,0x5CFC00,0x5CFC04,0x5CFC08,
0x695D49,0x695D5C,0x695D84,0x695D54,0x695D58,0x695D68,0x5CFC7C,
*range(0x5CFC40,0x5CFC70,4))))
def collect(original):
report=dispatch_collect(original);pe=PE(find_case(Path(original),'Neutron.exe'))
for name,start,end,digest in BODIES:
body=read_va(pe,start,end-start)
if hashlib.sha256(body).hexdigest()!=digest:raise ValueError(f'Changed body {name}')
report['bodies'].append(dict(name=name,va=hex(start),file_offset=hex(pe.offset(start-pe.base)),length=end-start,sha256=digest))
for target in GLOBALS:
value=struct.pack('<I',target)
for index in range(len(body)-3):
if body[index:index+4]==value:report['probe_operands'].append(dict(va=start+index,target=target))
report['probe_operands'].sort(key=lambda p:p['va'])
return report
if __name__=='__main__':
cli=argparse.ArgumentParser(description=__doc__);cli.add_argument('original',type=Path)
cli.add_argument('--probe-header',type=Path);cli.add_argument('--target-copy',type=Path)
args=cli.parse_args();report=collect(args.original)
if args.target_copy:
target=args.target_copy.resolve(strict=True)
if target.is_relative_to(args.original.resolve()):cli.error('Use a generated copy')
if hashlib.sha256(target.read_bytes()).hexdigest()!=report['sha256']:cli.error('Unexpected copy identity')
if args.probe_header:
output=args.probe_header.resolve()
if output.is_relative_to(args.original.resolve()):cli.error('Header must be outside originals')
output.write_text(header(report))
print(json.dumps(report,indent=2))
+106
View File
@@ -0,0 +1,106 @@
/* Original479D20 with copied code and synthetic ordinary-body virtual contracts.
* No game loader/entrypoint, script, audio or real actor instance is executed. */
#define main isolated_kernel_main
#include "collision_response_probe.c"
#undef main
#define TC __attribute__((thiscall))
typedef struct Node {struct Node *next,*previous;void *value;} Node;
typedef struct {
uintptr_t *table;Vec position,previous,velocity,acceleration,impulse,angular,rotation,anchor;
int supported,support,world,pairs,prevent;float speed,friction,factor,radius,scale;
unsigned landings;float landing_velocity;int landing_supported;
unsigned char reserved[0x500]; // Covers source dispatcher's direct member42C.
} Body;
typedef void (__cdecl *BodyStep)(Body*,float);
static int TC supported(Body*b){return b->supported;}
static int TC support(Body*b){return b->support;}
static int TC world(Body*b){return b->world;}
static int TC pairs(Body*b){return b->pairs;}
static int TC yes(Body*b){(void)b;return 1;}
static int TC no(Body*b){(void)b;return 0;}
static int TC prevent(Body*b){return b->prevent;}
static void TC set_supported(Body*b,int value){b->supported=value;}
static float TC radius(Body*b){return b->radius;}
static float TC factor(Body*b){return b->factor;}
static float TC speed(Body*b){return b->speed;}
static float TC friction(Body*b){return b->friction;}
static float TC scale(Body*b){return b->scale;}
#define GET(name,field) static Vec *TC name(Body*b,Vec*out){*out=b->field;return out;}
GET(position,position) GET(previous,previous) GET(velocity,velocity) GET(acceleration,acceleration)
GET(impulse,impulse) GET(angular,angular) GET(rotation,rotation)
#define SET(name,field) static void TC name(Body*b,Vec v){b->field=v;}
SET(set_position,position) SET(set_previous,previous) SET(set_velocity,velocity) SET(set_acceleration,acceleration)
#define XYZ(name,field) static void TC name(Body*b,float x,float y,float z){b->field.x=x;b->field.y=y;b->field.z=z;}
XYZ(position_xyz,position) XYZ(velocity_xyz,velocity) XYZ(acceleration_xyz,acceleration)
XYZ(impulse_xyz,impulse) XYZ(angular_xyz,angular) XYZ(anchor_xyz,anchor)
#define ADD(name,field) static void TC name(Body*b,float x,float y,float z){b->field.x+=x;b->field.y+=y;b->field.z+=z;}
ADD(add_velocity,velocity) ADD(add_angular,angular) ADD(rotate,rotation)
static void TC move(Body*b,Vec v){b->position.x+=v.x;b->position.y+=v.y;b->position.z+=v.z;}
static void TC landing(Body*b){b->landings++;b->landing_velocity=b->velocity.y;b->landing_supported=b->supported;}
static void TC pointer(Body*b,void*p){(void)b;(void)p;}
static void TC contact(Body*b,Vec normal,void*p){(void)b;(void)normal;(void)p;}
static uintptr_t table[0x500/4];
static void TC missing(Body*b) {
(void)b;uintptr_t call=(uintptr_t)__builtin_return_address(0);
fprintf(stderr,"MISSING fixture virtual after sourceVA %08lx\n",(unsigned long)(call-(uintptr_t)mapped+0x400000));
ExitProcess(2);
}
static Node sentinels[2][260*260];
static unsigned char polygon[0x30],shape[0x90],corners[60];
static Vec points[3]={{-1000,0,-1000,1},{1000,0,-1000,1},{0,0,1000,1}};
static void setup(void) {
for(unsigned i=0;i<sizeof(table)/sizeof(table[0]);i++)table[i]=(uintptr_t)missing;
#define SLOT(n,f) table[(n)/4]=(uintptr_t)(f)
SLOT(0x218,supported);SLOT(0x21c,set_supported);SLOT(0x1c8,support);SLOT(0x210,yes);
SLOT(0x220,pairs);SLOT(0x228,no);SLOT(0x1d0,world);SLOT(0x208,prevent);
SLOT(0x260,radius);SLOT(0x250,factor);SLOT(0x268,speed);SLOT(0x248,friction);SLOT(0x230,scale);
SLOT(0x310,position);SLOT(0x2f8,previous);SLOT(0x2bc,velocity);SLOT(0x270,acceleration);
SLOT(0x284,impulse);SLOT(0x2ac,angular);SLOT(0x314,set_position);SLOT(0x318,position_xyz);
SLOT(0x328,rotation);
SLOT(0x2fc,set_previous);SLOT(0x2c0,set_velocity);SLOT(0x274,set_acceleration);SLOT(0x31c,move);
SLOT(0x2c4,velocity_xyz);SLOT(0x278,acceleration_xyz);SLOT(0x28c,impulse_xyz);
SLOT(0x2b4,angular_xyz);SLOT(0x2f4,anchor_xyz);SLOT(0x334,rotate);
SLOT(0x2cc,add_velocity);SLOT(0x2b8,add_angular);SLOT(0x37c,landing);
SLOT(0x34c,pointer);SLOT(0x33c,pointer);SLOT(0x370,contact);SLOT(0x374,contact);
for(unsigned g=0;g<2;g++)for(unsigned i=0;i<260*260;i++) {
Node*s=&sentinels[g][i];s->next=s->previous=s;
*(Node**)AT((g?0x5cfc7c:0x509b24)+i*12)=s;
}
*(void**)(polygon+0x24)=corners;*(Vec*)(polygon+8)=(Vec){0,1,0,0};
*(void**)(shape+0x68)=points;
for(unsigned i=0;i<3;i++)*(unsigned*)(corners+i*20)=i;
for(int x=127;x<=132;x++)for(int z=127;z<=132;z++) {
Node*s=&sentinels[1][260*x+z],*n=calloc(1,sizeof(Node));void**r=calloc(1,0x1c);
require(n&&r,"support fixture allocation");r[0]=polygon;r[1]=shape;n->value=r;
n->next=s;n->previous=s->previous;s->previous->next=n;s->previous=n;
}
*(Vec*)AT(0x5cfc00)=(Vec){0,-800,0,0};
}
static Body initial(void) {
Body b={0};b.table=table;b.position=(Vec){0,75.9f,0,1};b.previous=b.position;
b.support=b.world=b.pairs=b.prevent=1;b.radius=60;b.factor=1.265f;b.friction=.8f;b.scale=.5f;
return b;
}
static void run(const char*name,Body b,int geometry) {
*(unsigned char*)AT(0x4f69e5)=geometry;
((BodyStep)AT(0x479d20))(&b,1.0f/60);
printf("CASE %s root=%.9g,%.9g,%.9g velocity=%.9g,%.9g,%.9g acceleration=%.9g,%.9g,%.9g impulseY=%.9g angularY=%.9g grounded=%d landings=%u observedVy=%.9g observedSupport=%d\n",
name,b.position.x,b.position.y,b.position.z,b.velocity.x,b.velocity.y,b.velocity.z,
b.acceleration.x,b.acceleration.y,b.acceleration.z,b.impulse.y,b.angular.y,b.supported,
b.landings,b.landing_velocity,b.landing_supported);
require(isfinite(b.position.y)&&isfinite(b.velocity.y),"finite source body output");
}
int main(void) {
setbuf(stdout,NULL);map_copy();setup();Body b=initial();
run("floor_support",b,1);
b=initial();b.position.y=26;b.previous=b.position;run("spawn_settle",b,1);
b=initial();b.supported=1;b.impulse.y=550;b.acceleration.y=-264;run("pending_jump",b,1);
b=initial();b.position.y=100;b.previous=b.position;b.velocity.y=-200;run("fall_above_floor",b,1);
b=initial();b.position.y=76;b.previous=b.position;b.velocity.y=-200;run("fall_land",b,1);
b=initial();b.velocity=(Vec){100,0,50,0};b.angular.y=12;run("ground_friction",b,1);
b=initial();b.velocity=(Vec){100,0,50,0};b.angular.y=12;b.speed=100;run("published_speed",b,1);
b=initial();b.angular.y=12;run("stationary_angular",b,1);
b=initial();b.velocity.x=.125f;run("small_motion",b,1);
b=initial();b.velocity.y=200;b.acceleration.y=-264;run("geometry_disabled",b,0);
puts("BODY_COMPONENT_COMPLETE: copied479D20/support with synthetic virtual contracts");return 0;
}
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Read-only shared viewport/default/follow camera handoff evidence."""
from __future__ import annotations
import argparse
from dataclasses import dataclass, replace
import hashlib
import json
import math
from pathlib import Path
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
SITES = (
('default_already_jimmy', 0x447D54, 'a1e499500083c40c3bc6753f'),
('default_restore_raw_control', 0x447E27, 'ff9018010000'),
('default_local_snap', 0x447E2F, '680000fac3680000fa43'),
('default_transform_local', 0x447E42, 'ff9284030000'),
('default_current_viewport', 0x447E54, '8b0d509a5000'),
('default_current_eye_x', 0x447E5E, 'd94144'),
('default_current_eye_y', 0x447E61, 'd94148'),
('default_distance_sqrt', 0x447E95, 'd9fa'),
('default_strict_threshold', 0x447E9D, 'd81dace54800dfe0f6c441751e'),
('default_snap_x', 0x447EAA, 'd95944'),
('default_snap_y', 0x447EB6, 'd95848'),
('default_snap_z', 0x447EC3, 'd9594c'),
('walking_capture_shared_viewport', 0x438EF7, 'a1509a5000'),
('walking_previous_x', 0x438F03, 'd94044d99d14070000'),
('walking_previous_y', 0x438F17, 'd94148d99d18070000'),
('walking_previous_z', 0x438F26, 'd9424cd99d1c070000'),
('walking_ray_callback', 0x439714, 'ff966c010000'),
('walking_delta_previous_x', 0x439722, 'd8a514070000'),
('walking_delta_previous_y', 0x43972C, 'd8a518070000'),
('walking_delta_previous_z', 0x439742, 'd8a51c070000'),
('walking_normal_x_gain', 0x4397B1, 'd88d54080000'),
('walking_normal_y_gain', 0x4397C2, 'd98558080000dc05d02a4a00'),
('walking_normal_z_gain', 0x4397E7, 'd88d5c080000'),
('walking_add_shared_x', 0x439811, 'd800'),
('walking_add_shared_y', 0x43981D, 'd84004d95804'),
('walking_add_shared_z', 0x43982A, 'd84008d95808'),
('walking_aim_from_previous_x', 0x439834, 'd8a514070000'),
('walking_aim_from_previous_y', 0x43984D, 'd8a518070000'),
('walking_aim_from_previous_z', 0x43985B, 'd8a51c070000'),
('walking_angles_from_vector', 0x439865, 'ff1508d14800'),
('walking_angle_wrap', 0x4398A3, '25ff3f0000'),
('airborne_capture_shared_viewport', 0x439E33, 'a1509a5000'),
('airborne_previous_x', 0x439E40, 'd94044d95c243c'),
('airborne_previous_y', 0x439E47, 'd94048d95c2440'),
('airborne_previous_z', 0x439E4E, 'd9404c'),
('airborne_delta_previous_x', 0x439EF1, 'd864243c'),
('airborne_delta_previous_y', 0x439EF9, 'd8642440'),
('airborne_delta_previous_z', 0x439F0B, 'd8642444'),
('airborne_add_shared_x', 0x43A07D, 'd84044'),
('airborne_add_shared_y', 0x43A08F, 'd84004d95804'),
('airborne_add_shared_z', 0x43A099, 'd84008d95808'),
('airborne_aim_previous_x', 0x43A0A3, 'd8642444'),
('airborne_aim_previous_y', 0x43A0BA, 'd8642448'),
('airborne_aim_previous_z', 0x43A0C6, 'd864244c'),
('airborne_angles_from_vector', 0x43A0CE, 'ff1508d14800'),
('mca_shared_eye_x', 0x431677, 'a1509a5000d95844'),
('mca_shared_eye_y', 0x431683, '8b0d509a5000'),
('mca_shared_eye_z', 0x431694, '8b15509a5000'),
('camera_setup_eye_y', 0x437742, 'c781cc07000000004843'),
('camera_setup_eye_z', 0x437763, 'c781d00700000000afc3'),
)
TABLES = (
('Jimmy walking input/follow', 0x4A3BDC, 0x124, 0x438BC0),
('Jimmy airborne input/follow', 0x4A3BDC, 0x128, 0x439900),
('Jimmy camera setup', 0x4A3BDC, 0x170, 0x437740),
('Jimmy static ray callback', 0x4A3BDC, 0x16C, 0x43B820),
)
@dataclass(frozen=True)
class CameraProjection:
eye: tuple[float, float, float]
direction: tuple[float, float, float]
def default_handoff(view: CameraProjection, local_snap_world, already_jimmy: bool):
"""Bounded route projection of DEFAULT; orientation is not rewritten here."""
distance = math.sqrt(sum((a-b)**2 for a, b in zip(view.eye, local_snap_world, strict=True)))
if not already_jimmy and distance > 1000:
return replace(view, eye=tuple(local_snap_world))
return view
def normal_follow(view: CameraProjection, desired_eye, look_point, dt, ray_gain=1):
"""Walking normal-branch interpretation only, not source/x87 execution.
Desired-eye construction/special fields are intentionally supplied by caller;
static ray behavior is separately recovered. Aim uses the pre-update eye.
"""
gains = (1.6, 1.2, 1.6)
eye = tuple(old+(desired-old)*gain*ray_gain*dt
for old, desired, gain in zip(view.eye, desired_eye, gains, strict=True))
direction = tuple(look-old for look, old in zip(look_point, view.eye, strict=True))
return CameraProjection(eye, direction)
def collect(root):
pe = PE(find_case(Path(root), 'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256:
raise ValueError('Unsupported original EXE identity')
sites = []
for name, va, expected in SITES:
actual = read_va(pe, va, len(bytes.fromhex(expected))).hex()
if actual != expected:
raise ValueError(f'{name} changed at {va:#x}: {actual}')
sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), bytes=actual))
tables = []
for name, table, slot, expected in TABLES:
target, = struct.unpack('<I', read_va(pe, table+slot, 4))
if target != expected:
raise ValueError(f'{name} callback changed')
tables.append(dict(name=name, table=hex(table), slot=hex(slot), target=hex(target),
file_offset=hex(pe.offset(table+slot-pe.base))))
threshold, = struct.unpack('<f', read_va(pe, 0x48E5AC, 4))
if threshold != 1000:
raise ValueError('DEFAULT threshold changed')
return dict(sha256=EXE_SHA256, sites=sites, tables=tables,
threshold=dict(va='0x48e5ac', file_offset=hex(pe.offset(0x48E5AC-pe.base)), value=threshold),
scope='Source-byte evidence plus bounded state projection; no original runtime execution.')
if __name__ == '__main__':
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('original', type=Path)
print(json.dumps(collect(cli.parse_args().original), indent=2))
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""Read-only Jimmy ceiling-wrapper evidence and bounded state projection."""
from __future__ import annotations
import argparse
from dataclasses import dataclass, replace
import hashlib
import json
import math
from pathlib import Path
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
SITES = (
('wrapper_velocity_before_ceiling', 0x424BE0, 'ff92bc020000d94004d81d14d94800'),
('wrapper_only_strictly_upward', 0x424BF1, 'f6c441750c'),
('wrapper_ceiling_virtual', 0x424BFC, 'ff92a4010000'),
('wrapper_distance_virtual', 0x424C08, 'ff90a8010000'),
('wrapper_movement_after_queries', 0x424C34, 'e8072d0100'),
('ceiling_logical_root', 0x42519B, 'ff9010030000'),
('ceiling_one_sided', 0x4251A3, '6a0083ec10'),
('ceiling_root_y_plus150', 0x4251B8, 'd9442438d805343e4a00'),
('ceiling_ray_dispatch', 0x4251FC, 'e80f700500'),
('ceiling_hit_required', 0x425204, '84c00f84c7000000'),
('ceiling_live_velocity_recheck', 0x425215, 'ff92bc020000d94004d81d14d94800'),
('ceiling_recheck_strictly_upward', 0x425226, 'f6c4410f85a4000000'),
('ceiling_negative_velocity_times_double06', 0x42523E, 'd94004d9e0dc0df8e54800'),
('ceiling_minimum_downward85_compare', 0x42524D, 'd81df0e54800'),
('ceiling_minimum_downward85_write', 0x425255, 'f6c4417508c744240c0000aac2'),
('ceiling_write_velocity_xyz', 0x42528E, 'ff93c4020000'),
('ceiling_optional_sound_gate', 0x425294, '66833d88054f0000742b'),
('ceiling_sound_elapsed_compare', 0x42529E, 'd9875c1e0000d81d50d94800'),
('ceiling_sound47', 0x4252B1, '6a006a2f6affe8c4360300'),
('ceiling_sound_elapsed_reset', 0x4252BF, 'c7875c1e000000000000'),
('ceiling_cancellation_virtual', 0x4252CD, 'ff92e0010000'),
('cancellation_only_mode1', 0x425123, 'b801000000663986c4070000753c'),
('cancellation_jump_zero_mode1', 0x425139, '66c786e80700000000668986c4070000'),
('cancellation_fall_request', 0x425134, '68e8f34e00'),
('cancellation_owned_effect', 0x42514F, '8b86f807000085c0740a'),
('cancellation_effect_zero', 0x425159, 'c780c006000000000000'),
('cancellation_cleanup_virtual', 0x425167, 'ff9040010000'),
('cleanup_base_noop', 0x429913, 'e858900400'),
('cleanup_class_flags', 0x429918, 'c686641e000000c786681e000000000000'),
('cleanup_saved_sound', 0x429941, '8b863c0a000083f8ff7415'),
('cleanup_saved_sound_stop', 0x42994C, '6a0050e8acf00200'),
('cleanup_saved_sound_invalid', 0x429957, 'c7863c0a0000ffffffff'),
('distance_global_bypass', 0x4252E3, 'a010824f00'),
('distance_root_minus2500', 0x425335, 'd9442438d825e80c4a00'),
('distance_nearest_ray', 0x425379, 'e862730500'),
('distance_shadow_pointer_required', 0x4253AC, '8b8f2c0a000085c9'),
('distance_cache_store', 0x42547C, 'd99f6c080000'),
)
TABLES = (
('complete_ceiling_query', 0x4A3BDC, 0x1A4, 0x425170),
('complete_distance_query', 0x4A3BDC, 0x1A8, 0x4252E0),
('complete_ceiling_cancel', 0x4A3BDC, 0x1E0, 0x425120),
('complete_animation_request', 0x4A3BDC, 0xE0, 0x40DD90),
('complete_gadget_stop', 0x4A3BDC, 0x140, 0x429910),
('interface_velocity_get', 0x4A373C, 0x2BC, 0x471F10),
('interface_velocity_set', 0x4A373C, 0x2C4, 0x471F40),
('interface_root_get', 0x4A373C, 0x310, 0x472300),
)
CONSTANTS = (
('root_upward_span', 0x4A3E34, 'f', 150.0),
('bounce_coefficient', 0x48E5F8, 'd', 0.6),
('maximum_vertical_response', 0x48E5F0, 'f', -85.0),
('upward_threshold', 0x48D914, 'f', 0.0),
('sound_elapsed_threshold', 0x48D950, 'f', 5.0),
('shadow_downward_span', 0x4A0CE8, 'f', 2500.0),
)
BODY_HASHES = (
('ceiling_cancellation', 0x425120, 0x4F,
'170f31c1f88d09d9f9d4a5cfa69c2d34a77a477ca63bcbf5efe4d0409f6c61d2'),
('ceiling_query_response', 0x425170, 0x16C,
'8a2555793945f3b0eacecfefd8ffcd838c9820250b109d6120bf0a86ad32c153'),
('shadow_distance_refresh', 0x4252E0, 0x1AB,
'28482ee15afc15af43f344656b7262b1d61d68c667ebf5125bfb20b20328dc7d'),
('derived_cleanup', 0x429910, 0x53,
'eca3f8629cdc54c87fe4cb4e7b1f272099d10009a230711d2c1cbcf5fc37d382'),
)
@dataclass(frozen=True)
class CeilingState:
velocity: tuple[float, float, float]
mode: int
jump: int
fire_remaining: float | None
hold: float = 0
extra_acceleration: float = 0
queued_impulse: float = 0
def upward_segment(root):
"""425170 root to root+150Y, not a radius/capsule-top segment."""
if len(root) != 3 or not all(math.isfinite(v) for v in root):
raise ValueError('Finite XYZ root required')
return tuple(root), (root[0], root[1] + 150, root[2])
def ceiling_projection(state, hit):
"""Bounded response/cancel projection, not original execution or full wrapper.
hit is supplied by the separately recovered 47C210 static predicate. No
ownership input exists. Class sound/gadget cleanup callbacks are events only;
Python is not an x87 arithmetic oracle.
"""
if len(state.velocity) != 3 or not all(math.isfinite(v) for v in state.velocity):
raise ValueError('Finite velocity required')
if state.velocity[1] <= 0:
return state, ()
if not hit:
return state, ('query47C210',)
# Final store is float32; coefficient is the original stored double.
reflected = struct.unpack('<f', struct.pack('<f', min(-state.velocity[1] * 0.6, -85.0)))[0]
state = replace(state, velocity=(state.velocity[0], reflected, state.velocity[2]))
events = ('query47C210', 'velocity2C4', 'cancel1E0')
if state.mode == 1:
state = replace(state, jump=0,
fire_remaining=0 if state.fire_remaining is not None else None)
events += ('FALL', 'cleanup140')
return state, events
def collect(root):
pe = PE(find_case(Path(root), 'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256:
raise ValueError('Unsupported original EXE')
sites = []
for name, va, expected in SITES:
actual = read_va(pe, va, len(bytes.fromhex(expected))).hex()
if actual != expected:
raise ValueError(f'Changed instruction {name} at {va:#x}: {actual}')
sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), bytes=actual))
tables = []
for name, table, slot, target in TABLES:
if struct.unpack('<I', read_va(pe, table+slot, 4))[0] != target:
raise ValueError(f'Changed virtual target {name}')
tables.append(dict(name=name, table=hex(table), slot=hex(slot), target=hex(target),
file_offset=hex(pe.offset(table+slot-pe.base))))
constants = []
for name, va, fmt, expected in CONSTANTS:
value = struct.unpack('<'+fmt, read_va(pe, va, struct.calcsize(fmt)))[0]
if value != expected:
raise ValueError(f'Changed constant {name}')
constants.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)),
format=fmt, value=value))
bodies = []
for name, va, length, expected in BODY_HASHES:
actual = hashlib.sha256(read_va(pe, va, length)).hexdigest()
if actual != expected:
raise ValueError(f'Changed body {name}')
bodies.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)),
length=length, sha256=actual))
if read_va(pe, 0x4EF3E8, 5) != b'FALL\0':
raise ValueError('Changed FALL animation identity')
return dict(sha256=EXE_SHA256, sites=sites, tables=tables, constants=constants, bodies=bodies,
scope='Static source bytes and explicit projection; no original runtime or complete solver.')
if __name__ == '__main__':
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('original', type=Path)
print(json.dumps(collect(cli.parse_args().original), indent=2))
+275
View File
@@ -0,0 +1,275 @@
#!/usr/bin/env python3
"""Read-only contact callback, friction and publication evidence; bounded projections."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import struct
import sys
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'extractors'))
from omt import Database, Reader, read_material, read_shape
DLL_SHA256 = '3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943'
DLL_SITES = (
('db_link_chunk', 0x10030070, '8b4424048b54240c89411c8b44240889410c89511089480c8b410c668b502066895122c20c00'),
('header_id_offset_size', 0x1004659f, '8b4b288d54245852e8f4d302008b4b288d44245050e837d402008d4c2454518b4b28e82ad40200'),
('header_record_insert', 0x10046635, '8b4e148d542450528b4104508d44243450e865190000'),
('chunk_id_lookup', 0x10045b98, '8b4c24108b500c3bca7c068d44240ceb08897424048d4424048b003bc65e740a8b401083c00859'),
('object_lookup_chunk', 0x1002df43, '55538bceff50488b3e55538bceff576c508bceff5774538be8'),
('object_db_link_call', 0x1002e0a5, '8b4c24108b075355518bcfff5018'),
('link_reads_fourcc_id', 0x100302ac, '8d4c2410518bcee8383704008d5424148bce52e8dc3604008b5c24108b6c2414'),
('link_get_object', 0x100302e8, '8b0755538bcfff50148b4c2418894104'),
('polygon_link_read', 0x10003f4f, '8d4424388bce50e8a5fe06008b4c243c51e910030000'),
('polygon_material_set', 0x10004275, '8bcbe874010000'),
('material_pointer_publish', 0x10004402, '8b44240485c08941047403ff4014c20400'),
)
# Fixed signatures from independently reviewed original instructions.
SITES = (
('root_before_normal', 0x47b7b1, '89038b442440894b048953088943'),
('normal_threshold', 0x47b7e3, 'd81d48314a00'),
('normal_strict_positive_side', 0x47b7f9, 'f6c441751f'),
('wall374', 0x47b80f, 'ff9774030000'),
('ceiling370', 0x47b82e, 'ff9770030000'),
('ceiling_velocity_read', 0x47269f, 'ff90bc020000'),
('ceiling_velocity_strict', 0x4726c0, 'f6c4417526'),
('ceiling_velocity_write', 0x4726e3, 'ff90c0020000'),
('ceiling_accel_read', 0x4726f6, 'ff9270020000'),
('ceiling_accel_strict', 0x472717, 'f6c4417525'),
('ceiling_accel_write', 0x472734, 'ff9074020000'),
('jimmy_gadget', 0x42a660, '66833d88054f0007'),
('jimmy_common_player_forward', 0x42a70b, 'e830030100'),
('base_guard', 0x458895, 'ff90d801000084c0742a8b4c'),
('base378', 0x4588c3, 'ff9078030000'),
('player_elapsed', 0x43aa4a, 'd98674070000d81da0e54800'),
('player_metadata', 0x43aa69, '8b400485c074658b400c85c00f84520200008b'),
('player_mode', 0x43aad5, '6683be04070000000f85f8040000'),
('landing_root', 0x47bb32, 'ff9018030000'),
('landing_acceleration', 0x47bb4b, 'ff9078020000'),
('landing_previous_ground', 0x47bb51, 'a0495d690084c0750a'),
('landing37c', 0x47bb5e, 'ff907c030000'),
('landing_velocity', 0x47bb74, 'ff92c4020000'),
('landing_support', 0x47bb7c, '6a018bceff921c020000'),
('landing_shape', 0x47bb91, 'ff904c030000'),
('landing_polygon', 0x47bba1, 'ff923c030000'),
('friction_speed_read', 0x47a241, 'ff9268020000'),
('friction_equal_zero', 0x47a24f, 'f6c4407440'),
('friction_call', 0x47a25a, 'e8d1000000'),
('friction_support', 0x47a344, 'ff901802000084c00f84ca000000'),
('friction_coefficient', 0x47a356, 'ff9248020000'),
('friction_magnitude', 0x47a38e, 'ff1504d14800d81d14d94800dfe0f6c441757b'),
('friction_linear_add', 0x47a3cb, 'ff92cc020000'),
('friction_angular_add', 0x47a416, 'ff92b8020000'),
('speed_getter', 0x471b50, 'd98160010000c3'),
('speed_setter', 0x471b60, '8b442404898160010000c20400'),
('speed_publication', 0x437c22, '8b86080600008b16508bceff926c020000'),
('small_motion_scale', 0x471a70, 'd98144010000c3'),
('threshold_minus07', 0x4a3148, '333333bf'),
('threshold_zero', 0x48d914, '00000000'),
('threshold_point1', 0x48d920, 'cdcccc3d'),
('threshold_3', 0x48e5a0, '00004040'),
('ctor_ebx_zero', 0x46fc08, '33db'),
('ctor208_false', 0x46fdbc, '538bcde8ac110000'),
('ctor1c8_true', 0x46fdc4, '6a018bcde8d3110000'),
('ctor1d0_true', 0x46fdcd, '6a018bcde8fa110000'),
('ctor220_true', 0x46fdf0, '6a018bcde8c7120000'),
('ctor228_false', 0x46fdf9, '538bcde8ef120000'),
('ctor42c_false', 0x46ffb1, '889d2c040000'),
('player208_true', 0x43740a, '578bcee85e9b0300'),
)
BODY_HASHES = (
('ceiling370', 0x472690, 0xba, 'febfe9381b19074c41b229b314307c85f95710a35c7907935f76519052d4b50c'),
('jimmy374', 0x42a660, 0xb4, 'd52831057c35afbdb73babff81857a6a3cfb2466f639b8be0a80e6300d386b0c'),
('player374', 0x43aa40, 0x5a3, '2acd114eb62fe67490d9301bc8e68f196830be74eb9076f52f79111467344a78'),
('base374', 0x458890, 0x3d, '250d34ac046749aa9e6d6e22968b1139a98be46d8f31cb2dda287ddc5c2c4b6f'),
('friction', 0x47a330, 0xf1, '3ac4d0268edb5fa4f5689a87fdc36759c12589caf76b2286b1817f2204a91155'),
('landing37c', 0x472970, 0x1, 'ae3f4619b0413d70d3004b9131c3752153074e45725be13b9a148978895e359e'),
)
TABLES = (
('Object', 0x4d3154, 0x370, 0x472690),
('Object', 0x4d3154, 0x374, 0x458890),
('Object', 0x4d3154, 0x378, 0x472750),
('Object', 0x4d3154, 0x37c, 0x472970),
('Object', 0x4d3154, 0x230, 0x471a70),
('Animated', 0x48fe1c, 0x370, 0x472690),
('Animated', 0x48fe1c, 0x374, 0x458890),
('Animated', 0x48fe1c, 0x378, 0x472750),
('Animated', 0x48fe1c, 0x37c, 0x472970),
('Animated', 0x48fe1c, 0x230, 0x471a70),
('Player', 0x4af6c4, 0x370, 0x472690),
('Player', 0x4af6c4, 0x374, 0x43aa40),
('Player', 0x4af6c4, 0x378, 0x472750),
('Player', 0x4af6c4, 0x37c, 0x472970),
('Player', 0x4af6c4, 0x230, 0x471a70),
('Jimmy', 0x4a373c, 0x370, 0x472690),
('Jimmy', 0x4a373c, 0x374, 0x42a660),
('Jimmy', 0x4a373c, 0x378, 0x472750),
('Jimmy', 0x4a373c, 0x37c, 0x472970),
('Jimmy', 0x4a373c, 0x230, 0x471a70),
)
NORMAL_Y_THRESHOLD = struct.unpack('<f', bytes.fromhex('333333bf'))[0]
def normal_callback(normal_y):
"""Finite-input dispatch only; caller already publishes candidate root."""
return 0x374 if normal_y > NORMAL_Y_THRESHOLD else 0x370
def ceiling_projection(velocity, acceleration):
"""472690 changes strictly positive Y only, retaining fourth components."""
def clear_positive_y(v):
return (v[0], 0 if v[1] > 0 else v[1], *v[2:])
return clear_positive_y(velocity), clear_positive_y(acceleration)
def player_material_actions(material_id, elapsed, mode):
"""Classify bounded branches, without inventing unresolved class callbacks."""
if elapsed <= 3:
return ()
actions = []
if 120 <= material_id <= 129:
actions.append('complete160')
if 110 <= material_id <= 119:
actions.append('complete164')
if mode == 0:
if 60 <= material_id <= 69:
actions.append('fence_query')
if material_id == 180:
actions.append('ladder_query')
return tuple(actions)
def jimmy_contact_actions(selected, material_id, elapsed, mode, *, gadget7_active=False):
"""42A660 branch contract; selected -1/3 have no extra gadget behavior."""
actions = player_material_actions(material_id, elapsed, mode)
if selected == 7 and gadget7_active:
actions += ('gadget7_unresolved',)
return actions
def friction_projection(velocity, angular, coefficient, delta, *,
support=True, published_speed=0):
"""47A330 with caller's268 gate; excludes later small-motion suppression.
Finite vectors only. Nonzero quick_magnitude gate is represented by any
nonzero component, not a substitute implementation of imported magnitude.
Python arithmetic is not an x87 bit-identity oracle. No clamp is added.
"""
if published_speed != 0 or not support or not any(velocity[:3]):
return tuple(velocity), tuple(angular)
k = coefficient * delta
return ((velocity[0] - velocity[0]*k, velocity[1],
velocity[2] - velocity[2]*k, *velocity[3:]),
tuple(x-x*k for x in angular[:3]) + tuple(angular[3:]))
def landing_phases(previous_support):
phases = ['root318', 'acceleration278_Y0']
if not previous_support:
phases.append('landing37C_noop_for_Jimmy')
return phases + ['velocity2C4_Y0', 'support21C_true', 'shape34C', 'polygon33C']
def material_identity_report(root):
"""Original table IDs linked by source chunk metadata, not payload flags.
Eligibility is registration+normal only, not evidence a gameplay trajectory
actually contacts a polygon. Preserve explicit source shape/polygon identity.
"""
root = Path(root)
dll = PE(find_case(root, 'OMT2.dll'))
if hashlib.sha256(dll.data).hexdigest() != DLL_SHA256:
raise ValueError('Unsupported original OMT2.dll')
anchors = []
for name, va, expected in DLL_SITES:
if read_va(dll, va, len(bytes.fromhex(expected))).hex() != expected:
raise ValueError(f'Changed DLL instruction {name}')
anchors.append(dict(name=name, va=hex(va), file_offset=hex(dll.offset(va-dll.base)), bytes=expected))
archives = []
for filename in ('level1b.omt', 'VR04.omt', 'level1.omt'):
db = Database(find_case(root, 'omt/' + filename))
# Record the identity's actual table byte offset, separate from payload.
r = Reader(db.data, db.table_offset)
id_offsets = {}
for _ in range(r.count(8)):
kind = r.take(4).decode('latin1')
for _ in range(r.count(13)):
offset = r.position
identity = r.u32()
r.take(8)
r.string()
id_offsets[kind, identity] = offset
materials = {e.id: e for e in db.entries if e.type == '3DMa'}
summaries = {}
special = []
for entry in db.entries:
if entry.type != '3DSh':
continue
shape = read_shape(db.payload(entry))
registered = not entry.name.lower().startswith('nc')
for index, polygon in enumerate(shape['polygons']):
link = polygon['material']
if link is None or link['type'] != '3DMa' or link['id'] not in materials:
continue
identity = link['id']
material = materials[identity]
item = summaries.setdefault(identity, dict(id=identity, name=material.name,
table_id_offset=id_offsets['3DMa', identity], payload_offset=material.offset,
payload_size=material.size, payload_sha256=hashlib.sha256(db.payload(material)).hexdigest(),
payload_trailing=read_material(db.payload(material))['trailing'],
polygons=0, registered_polygons=0, potential374_wall_polygons=0))
item['polygons'] += 1
item['registered_polygons'] += int(registered)
wall374 = registered and NORMAL_Y_THRESHOLD < polygon['normal'][1] < -NORMAL_Y_THRESHOLD
item['potential374_wall_polygons'] += int(wall374)
if player_material_actions(identity, 4, 0):
special.append(dict(shape_id=entry.id, shape_name=entry.name,
shape_payload_offset=entry.offset, polygon_index=index,
material_id=identity, normal=polygon['normal'], registered=registered,
potential374_wall=wall374))
archives.append(dict(name=filename, sha256=hashlib.sha256(db.data).hexdigest(),
materials=list(summaries.values()), special_polygons=special))
return dict(dll_sha256=DLL_SHA256, dll_sites=anchors, archives=archives,
discriminator='signed 3DMa database chunk ID at material+0C->chunk+8; not payload trailing')
def collect(root):
pe = PE(find_case(Path(root), 'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256:
raise ValueError('Unsupported original EXE')
sites = []
for name, va, expected in SITES:
actual = read_va(pe, va, len(bytes.fromhex(expected))).hex()
if actual != expected:
raise ValueError(f'Changed instruction {name} at {va:#x}')
sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), bytes=actual))
tables = []
for owner, table, slot, target in TABLES:
if struct.unpack('<I', read_va(pe, table+slot, 4))[0] != target:
raise ValueError(f'Changed {owner} slot{slot:x}')
tables.append(dict(owner=owner, table=hex(table), slot=hex(slot), target=hex(target),
file_offset=hex(pe.offset(table+slot-pe.base))))
bodies = []
for name, va, length, expected in BODY_HASHES:
raw = read_va(pe, va, length)
if hashlib.sha256(raw).hexdigest() != expected:
raise ValueError(f'Changed callback {name}')
bodies.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)),
length=length, sha256=expected,
raw_control_reference=struct.pack('<I', 0x5099E4) in raw))
return dict(sha256=EXE_SHA256, sites=sites, tables=tables, bodies=bodies,
material_identity=material_identity_report(root),
scope='Static guarded source and bounded state fixtures; no original execution.')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
print(json.dumps(collect(parser.parse_args().original), indent=2))
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""Guard the expanded original dispatcher probe callgraph; never execute originals."""
import argparse
import hashlib
import json
from pathlib import Path
import struct
from collision_response import collect as kernel_collect, header, TARGETS
from checkpoint_script_state import find_case, read_va
from pe_inspect import PE
EXTRA=(
('static_dispatch',0x47B4B0,0x47B889,'da4ca56149636d5fc5059403a0ef81a0007c96972e3c12f2a8dedfa7568dd160'),
('polygon_dispatch',0x47BBB0,0x47BD73,'b583bb88a97bef45961ad64a6b21533e9149d3dcb4a292d5dbe27db98d4dd325'),
('polygon_vertex',0x477F10,0x477F5F,'b5460f170b2315a462700d585b0626321186977a7bc192ede831a1e1ba60677c'),
('truncate',0x47F940,0x47F96A,'b1c1cecad44192fa8b32676658fcfea569fa1810741a5a5321c77f488c90b0b7'))
POINTERS=(*TARGETS,0x509B24,0x49B1FC,0x4D6A04,0x4F69E5,0x695D46,0x695D4C,0x695D70,0x695D78)
def collect(original):
report=kernel_collect(original);pe=PE(find_case(Path(original),'Neutron.exe'))
for name,start,end,digest in EXTRA:
body=read_va(pe,start,end-start)
if hashlib.sha256(body).hexdigest()!=digest:raise ValueError(f'Changed body {name}')
report['bodies'].append(dict(name=name,va=hex(start),file_offset=hex(pe.offset(start-pe.base)),length=end-start,sha256=digest))
for target in POINTERS:
value=struct.pack('<I',target)
for index in range(len(body)-3):
if body[index:index+4]==value:report['probe_operands'].append(dict(va=start+index,target=target))
report['probe_operands'].sort(key=lambda p:p['va'])
return report
if __name__=='__main__':
cli=argparse.ArgumentParser(description=__doc__);cli.add_argument('original',type=Path)
cli.add_argument('--probe-header',type=Path);cli.add_argument('--target-copy',type=Path)
args=cli.parse_args();report=collect(args.original)
if args.target_copy:
target=args.target_copy.resolve(strict=True)
if target.is_relative_to(args.original.resolve()):cli.error('Use a generated target copy')
if hashlib.sha256(target.read_bytes()).hexdigest()!=report['sha256']:cli.error('Unexpected target copy hash')
if args.probe_header:
output=args.probe_header.resolve()
if output.is_relative_to(args.original.resolve()):cli.error('Header must be outside originals')
output.write_text(header(report))
print(json.dumps(report,indent=2))
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more