From 57dfcc64bb98e899a0152d2c715baff10fd4e7d8 Mon Sep 17 00:00:00 2001 From: Cristian Cerroni Date: Mon, 26 Oct 2026 16:09:19 -0400 Subject: [PATCH] Recover sphere response and correct Jimmy ceiling cancellation --- AGENTS.md | 4 + README.md | 4 + docs/analysis/original-collision.md | 5 + docs/architecture.md | 8 + docs/checkpoint/README.md | 5 + docs/checkpoint/body-root-registration.md | 46 +++++ docs/checkpoint/camera-handoff.md | 40 +++++ docs/checkpoint/ceiling-wrapper.md | 52 ++++++ docs/checkpoint/collision-response.md | 109 +++++++++++ docs/checkpoint/coverage.md | 8 +- docs/checkpoint/implementation-plan.md | 21 +++ docs/checkpoint/review.md | 7 + docs/compatibility.md | 18 ++ docs/decisions.md | 8 + docs/progress.md | 43 +++++ docs/reverse-engineering.md | 5 + docs/tasks.md | 13 +- scripts/test.sh | 1 + src/GamePort/Game/LabSimulation.cs | 29 ++- src/GamePort/Game/OriginalCameraRay.cs | 17 +- src/GamePort/Game/OriginalSphereResponse.cs | 81 +++++++++ src/GamePort/Program.cs | 3 +- tests/GamePort.CameraRayTests/Program.cs | 2 + tests/GamePort.LabRouteTests/Program.cs | 4 +- tests/GamePort.MovementTests/Program.cs | 71 +++++++- .../GamePort.SphereResponseTests.csproj | 12 ++ tests/GamePort.SphereResponseTests/Program.cs | 55 ++++++ .../GamePort.UndergroundRouteTests/Program.cs | 4 +- tests/test_body_root_registration.py | 19 ++ tests/test_camera_handoff.py | 60 +++++++ tests/test_ceiling_wrapper.py | 50 ++++++ tests/test_collision_response.py | 27 +++ tools/binary/body_root_registration.py | 52 ++++++ tools/binary/camera_handoff.py | 132 ++++++++++++++ tools/binary/ceiling_wrapper.py | 170 ++++++++++++++++++ tools/binary/collision_response.py | 77 ++++++++ tools/binary/collision_response_probe.c | 80 +++++++++ 37 files changed, 1324 insertions(+), 18 deletions(-) create mode 100644 docs/checkpoint/body-root-registration.md create mode 100644 docs/checkpoint/camera-handoff.md create mode 100644 docs/checkpoint/ceiling-wrapper.md create mode 100644 docs/checkpoint/collision-response.md create mode 100644 src/GamePort/Game/OriginalSphereResponse.cs create mode 100644 tests/GamePort.SphereResponseTests/GamePort.SphereResponseTests.csproj create mode 100644 tests/GamePort.SphereResponseTests/Program.cs create mode 100644 tests/test_body_root_registration.py create mode 100644 tests/test_camera_handoff.py create mode 100644 tests/test_ceiling_wrapper.py create mode 100644 tests/test_collision_response.py create mode 100644 tools/binary/body_root_registration.py create mode 100644 tools/binary/camera_handoff.py create mode 100644 tools/binary/ceiling_wrapper.py create mode 100644 tools/binary/collision_response.py create mode 100644 tools/binary/collision_response_probe.c diff --git a/AGENTS.md b/AGENTS.md index f5572f9..7c6e193 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,3 +52,7 @@ not changed. Use generated copies, preserve complete Evidence/snapshots, and kee static decompilation distinct from source execution. Current C3 continuation: docs/checkpoint/control-phase-implementation.md; remaining body/wrapper/camera gates 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 +gates are grid/normal callbacks/support/friction and shared camera state. diff --git a/README.md b/README.md index 3232f31..8f51e29 100644 --- a/README.md +++ b/README.md @@ -180,3 +180,7 @@ Native reverse engineering uses the local REA/Ghidra launcher separately from runtime builds; see [local analysis setup](docs/rea.md). Current source-backed cutscene control/body phase findings are in [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. diff --git a/docs/analysis/original-collision.md b/docs/analysis/original-collision.md index 580378a..28c05bb 100644 --- a/docs/analysis/original-collision.md +++ b/docs/analysis/original-collision.md @@ -1,5 +1,10 @@ # 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 OriginalBodySupport module now translates the vertical support/segment path. This does not supersede the complete provisional SceneCollision solver or prove diff --git a/docs/architecture.md b/docs/architecture.md index b59574b..fe472d0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -23,6 +23,14 @@ verification possible without a desktop; this is distinct from SDL presentation. Simulation implementation must follow recovered algorithms and timing. A generic 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; source grid/callback/support integration remains gated. +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 offscreen and SDL surface presentation, an independent SDL WAV stream, bounded GAM/PNG/scene readers, and a retained-topology morph sampler. Prepared scene JSON diff --git a/docs/checkpoint/README.md b/docs/checkpoint/README.md index ea5e150..6d2907f 100644 --- a/docs/checkpoint/README.md +++ b/docs/checkpoint/README.md @@ -29,6 +29,11 @@ backed by [uncontrolled player](uncontrolled-player.md), [cutscene preparation](cutscene-preparation.md). [REA setup](../rea.md) records 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. + Evidence labels used throughout: - **Recovered:** static instructions, serialized original data, or a specifically diff --git a/docs/checkpoint/body-root-registration.md b/docs/checkpoint/body-root-registration.md new file mode 100644 index 0000000..d21a894 --- /dev/null +++ b/docs/checkpoint/body-root-registration.md @@ -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. diff --git a/docs/checkpoint/camera-handoff.md b/docs/checkpoint/camera-handoff.md new file mode 100644 index 0000000..1d773f3 --- /dev/null +++ b/docs/checkpoint/camera-handoff.md @@ -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. diff --git a/docs/checkpoint/ceiling-wrapper.md b/docs/checkpoint/ceiling-wrapper.md new file mode 100644 index 0000000..c208ba5 --- /dev/null +++ b/docs/checkpoint/ceiling-wrapper.md @@ -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. diff --git a/docs/checkpoint/collision-response.md b/docs/checkpoint/collision-response.md new file mode 100644 index 0000000..84be2c1 --- /dev/null +++ b/docs/checkpoint/collision-response.md @@ -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.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 response; face/edge nearest state and helpers; root+150 overhead bounce/cancel; support and quick magnitude; dynamic boxes; NC exclusion. | Isolated source sphere kernel with original component references; route overhead wrapper integrated. Live swept24-unit capsule/feet and dynamic response remain provisional. | S/P/M/R. Ten isolated original kernel cases; byte/managed checks. Grid/normal callbacks/support/friction, masks/stairs/root render remain open; radius60 is not capsule24. | C4: integrate traversal/callback/support order before replacing live adapter; doorway/corner is first route case. | | 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. | | 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. | | 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. | | 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. | diff --git a/docs/checkpoint/implementation-plan.md b/docs/checkpoint/implementation-plan.md index 7c7e83c..4b8f941 100644 --- a/docs/checkpoint/implementation-plan.md +++ b/docs/checkpoint/implementation-plan.md @@ -129,3 +129,24 @@ allowed where it resolves a core-system question, without waiting for every leve checks above remain separate. Baseline untouched; Windows cross-published only. Logs: artifacts/uncontrolled-phases/package*.log. Next work is full wrapper/base 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. diff --git a/docs/checkpoint/review.md b/docs/checkpoint/review.md index c63ef87..67f55f2 100644 --- a/docs/checkpoint/review.md +++ b/docs/checkpoint/review.md @@ -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 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 source anchors, state owners/lifetimes, route interactions, baseline comparison, explicit unknowns and bounded implementation actions. Feature expansion remains diff --git a/docs/compatibility.md b/docs/compatibility.md index 952162b..1c8ffbb 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -3,6 +3,24 @@ Compilation, native runtime, original behavior and full feature completion are separate evidence categories. **The game is not fully reconstructed/playable yet.** +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. + Control-phase continuation (2026-10-26): body/fire eligibility and ordered raw preparations are source-byte guarded separately from port behavior. Targeted24 movement groups, coupled director/preparation tests and the airborne control diff --git a/docs/decisions.md b/docs/decisions.md index 272661e..f28ecc4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -165,3 +165,11 @@ Evidence/profile/hash/snapshots and close owned sessions. CLI avoids changing the existing MCP registration. Unknown procedure definitions remain unknown; 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. diff --git a/docs/progress.md b/docs/progress.md index 0afaf71..bd0feeb 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -1,5 +1,48 @@ # Progress — 2026-10-26 +## 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. + ## Uncontrolled-player implementation and REA Continued C3 into source control/body/fire boundaries. Original475CA0/frame/body diff --git a/docs/reverse-engineering.md b/docs/reverse-engineering.md index 3fea4b3..bed1121 100644 --- a/docs/reverse-engineering.md +++ b/docs/reverse-engineering.md @@ -14,6 +14,11 @@ probes and modern runtime checks are recorded separately. read chain, bounded ordinary-load scalar/body resets, full tutorial availability tails and companion/shadow lifecycle. Source-byte checks and an isolated original 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. - `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/scene-entities.md`: exact entity-resource preparation and contact/sprite evidence. diff --git a/docs/tasks.md b/docs/tasks.md index 2052a44..e76337d 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -79,8 +79,17 @@ plan in verified chunks. Earlier priorities below are a backlog. player-transform synchronization; managed/GPU/native Linux checks. - [x] Local REA6.8.0/Ghidra12.1.4/full JDK21 launcher, selected native pseudocode Evidence/snapshot export; client MCP configuration unchanged. See rea.md. -- [ ] Next: full Jimmy/base wrapper and body registration/helper timing; C4 support/ - response/root and shared viewport/DEFAULT handoff. C6 source channel allocation/ +- [x] C4 bounded sphere/triangle kernel recovered with REA and isolated original + 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. +- [ ] Next: C4 grid/normal-callback/support/friction and dynamic response integration; + 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 analysis limitation; its immutable source-byte contract is already guarded. diff --git a/scripts/test.sh b/scripts/test.sh index 870270e..7c034e6 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -9,6 +9,7 @@ dotnet run --project tests/GamePort.MovementTests -- ../Original dotnet run --project tests/GamePort.DirectorTests -- ../Original dotnet run --project tests/GamePort.PatrolTests -- ../Original dotnet run --project tests/GamePort.SupportTests -- ../Original +dotnet run --project tests/GamePort.SphereResponseTests dotnet run --project tests/GamePort.CameraRayTests dotnet run --project tests/GamePort.InteractionTests -- ../Original dotnet run --project tests/GamePort.CheckpointTests -- ../Original diff --git a/src/GamePort/Game/LabSimulation.cs b/src/GamePort/Game/LabSimulation.cs index 2270357..bb5acbc 100644 --- a/src/GamePort/Game/LabSimulation.cs +++ b/src/GamePort/Game/LabSimulation.cs @@ -17,6 +17,7 @@ public sealed class LabSimulation public const float BodyRadius = 24; // Provisional, not a recovered collider dimension. private readonly SceneCollision collision; private readonly Func? cameraRay; + private readonly Func? ceilingRay; private readonly Vector3 sourceStart; private readonly float startYaw, modelMinimumY, rootHeight, startFloor; private float targetYaw, extraAirAcceleration, shadowDistance, lateralContribution; @@ -60,6 +61,7 @@ public sealed class LabSimulation public int PhysicsSteps { get; private set; } public int ControllerSteps { get; private set; } public int EffectSteps { get; private set; } + public int CeilingHits { get; private set; } public int Jumps { get; private set; } public int Landings { get; private set; } public int WallHits { get; private set; } @@ -73,10 +75,12 @@ public sealed class LabSimulation * Matrix4x4.CreateTranslation(Position - new Vector3(0, modelMinimumY, 0)); public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, float yaw, - Func? cameraRay = null) + Func? cameraRay = null, + Func? ceilingRay = null) { this.collision = collision; this.cameraRay = cameraRay; + this.ceilingRay = ceilingRay; sourceStart = start; startYaw = yaw; var bounds = standingPose.Bounds(); @@ -106,7 +110,7 @@ public sealed class LabSimulation Grounded = true; Noclip = HasNoclipEntry = false; Steps = Jumps = Landings = WallHits = 0; - PhysicsSteps = ControllerSteps = EffectSteps = 0; + PhysicsSteps = ControllerSteps = EffectSteps = CeilingHits = 0; Travel = MaximumRise = 0; CameraEye = DesiredEye().Eye; } @@ -155,10 +159,12 @@ public sealed class LabSimulation // This reconstructs the player/input/fire partial order, not the full // scene registry, original cadence or original collision response. StepPhysics(); + if (controlled && !InputAfterPlayerUpdate) StepInput(input); //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); + //424BE0..424C34 runs this wrapper before437940's ownership gate. + StepCeiling(); if (controlled) StepPlayer(input); var effect = JetpackBurst.StepEffect(jumpState, Grounded, FixedStepClock.Step, Energy, LevelCode); jumpState = effect.State; Energy = effect.Energy; JetpackEffectVisible = effect.Visible; @@ -174,6 +180,19 @@ public sealed class LabSimulation Speed = 0; Velocity = Vector3.Zero; } + 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; + } + /// Authored AI root/Euler writes. They do not reset body motion or /// destination yaw61C; the full logical/render Euler model remains separate. public void ApplyAuthoredTransform(Vector3 root, float yaw) @@ -326,7 +345,7 @@ public sealed class LabSimulation } } 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; } Velocity = velocity; if (!wasGrounded && Grounded) Landings++; @@ -363,5 +382,5 @@ public sealed class LabSimulation 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 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}."; } diff --git a/src/GamePort/Game/OriginalCameraRay.cs b/src/GamePort/Game/OriginalCameraRay.cs index 834193d..c9ac38d 100644 --- a/src/GamePort/Game/OriginalCameraRay.cs +++ b/src/GamePort/Game/OriginalCameraRay.cs @@ -20,7 +20,7 @@ public sealed class OriginalCameraRay public const float CellOrigin = 130; //49B1FC. private readonly Dictionary> walls = []; private readonly Dictionary> 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 WallPolygonCount { get; } /// Modern query diagnostic; repeated cells are intentionally counted. @@ -88,12 +88,25 @@ public sealed class OriginalCameraRay RequireFinite(start); RequireFinite(end); LastTriangleTests = 0; if (!Enabled) return null; + return TraceCore(start, end, twoSided, diagnostic: true); + } + + /// 425170 also uses47C210. Camera-only debug controls must not + /// disable physical ceiling checks or overwrite camera-query diagnostics. + 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 cell in CellsBetween(start, end)) if (grid.TryGetValue(cell, out var triangles)) foreach (var triangle in triangles) { - LastTriangleTests++; + if (diagnostic) LastTriangleTests++; if (OriginalBodySupport.IntersectSegment(triangle, start, end, twoSided) is { } hit) return hit; } diff --git a/src/GamePort/Game/OriginalSphereResponse.cs b/src/GamePort/Game/OriginalSphereResponse.cs new file mode 100644 index 0000000..1488e2d --- /dev/null +++ b/src/GamePort/Game/OriginalSphereResponse.cs @@ -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); + +/// +/// 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. +/// +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)); + } +} diff --git a/src/GamePort/Program.cs b/src/GamePort/Program.cs index 8a9cc24..b22923d 100644 --- a/src/GamePort/Program.cs +++ b/src/GamePort/Program.cs @@ -324,7 +324,8 @@ internal static class Program ? OriginalCameraRay.FromRouteScene(world, level.Code) : null; debugCameraRay = cameraRay; 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)) { LevelCode = level.Code, InputAfterPlayerUpdate = carriedSave != null }; if (carriedPlayer != null) { diff --git a/tests/GamePort.CameraRayTests/Program.cs b/tests/GamePort.CameraRayTests/Program.cs index 99f200f..03787cd 100644 --- a/tests/GamePort.CameraRayTests/Program.cs +++ b/tests/GamePort.CameraRayTests/Program.cs @@ -102,6 +102,8 @@ Test("source enable flag and unobstructed gain leave desired eye unchanged", () var result = ray.Constrain(high, low); Check(result.Eye == low && result.Gain == 1 && result.Hit == null && ray.LastTriangleTests == 0, "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; 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"); diff --git a/tests/GamePort.LabRouteTests/Program.cs b/tests/GamePort.LabRouteTests/Program.cs index ecf8c84..3d0b2d5 100644 --- a/tests/GamePort.LabRouteTests/Program.cs +++ b/tests/GamePort.LabRouteTests/Program.cs @@ -17,8 +17,10 @@ var director = new SceneDirector(level, tasks, resources.Duration); var interactions = new SceneInteractions(director, tasks, save); var mechanisms = new SceneMechanisms(director); 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")), - 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); var patrols = new List(); foreach (var actor in director.Actors.Where(a => a.Kind is "3DOG" or "3CAR")) diff --git a/tests/GamePort.MovementTests/Program.cs b/tests/GamePort.MovementTests/Program.cs index 2b794c5..94741c1 100644 --- a/tests/GamePort.MovementTests/Program.cs +++ b/tests/GamePort.MovementTests/Program.cs @@ -12,6 +12,7 @@ var tests = new (string Name, Action Check)[] ("ordinary route load retains scalars independently of body/jump reset", RetainedLevelState), ("script preparation preserves queued work and uncontrolled physics consumes it", UncontrolledPhysics), ("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), ("debug noclip bypasses walls/gravity/camera and exits without queued motion", Noclip), ("turn-only speed, forward acceleration/cap and release", SpeedLimits), @@ -191,6 +192,61 @@ static void RetainedLevelState() Throws(() => 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(); + 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() { var enabled = false; @@ -584,9 +640,20 @@ static void OriginalLab(string project, string originals) 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"); 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? cameraRay = null) +static LabSimulation FlatSimulation(float yaw = 0, Func? cameraRay = null, + Func? ceilingRay = null) { var positions = new[] { @@ -596,7 +663,7 @@ static LabSimulation FlatSimulation(float yaw = 0, Func 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), 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) diff --git a/tests/GamePort.SphereResponseTests/GamePort.SphereResponseTests.csproj b/tests/GamePort.SphereResponseTests/GamePort.SphereResponseTests.csproj new file mode 100644 index 0000000..a9fe575 --- /dev/null +++ b/tests/GamePort.SphereResponseTests/GamePort.SphereResponseTests.csproj @@ -0,0 +1,12 @@ + + + Exenet10.0 + enableenable + false + + + + + + + diff --git a/tests/GamePort.SphereResponseTests/Program.cs b/tests/GamePort.SphereResponseTests/Program.cs new file mode 100644 index 0000000..3a9b3cf --- /dev/null +++ b/tests/GamePort.SphereResponseTests/Program.cs @@ -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"); diff --git a/tests/GamePort.UndergroundRouteTests/Program.cs b/tests/GamePort.UndergroundRouteTests/Program.cs index 6804ae7..fe4f7be 100644 --- a/tests/GamePort.UndergroundRouteTests/Program.cs +++ b/tests/GamePort.UndergroundRouteTests/Program.cs @@ -19,8 +19,10 @@ var director = new SceneDirector(level, tasks, resources.Duration); var interactions = new SceneInteractions(director, tasks, save); var mechanisms = new SceneMechanisms(director); 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")), - 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; simulation.DynamicRootResolver = (before, after, radius) => { diff --git a/tests/test_body_root_registration.py b/tests/test_body_root_registration.py new file mode 100644 index 0000000..ba2f5b7 --- /dev/null +++ b/tests/test_body_root_registration.py @@ -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() diff --git a/tests/test_camera_handoff.py b/tests/test_camera_handoff.py new file mode 100644 index 0000000..dc4e00d --- /dev/null +++ b/tests/test_camera_handoff.py @@ -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(' 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(' +#include +#include +#include +#include +#include +typedef struct { float x,y,z,w; } Vec; +typedef unsigned (__cdecl *Kernel)(Vec,Vec,Vec,Vec,Vec,Vec*,float,int); +static unsigned char *mapped; +#define AT(va) (mapped+(va)-0x400000) +#include "collision_response_relocations.h" +static void require(int ok,const char *message) { + if(!ok){fprintf(stderr,"FAIL %s\n",message);exit(2);} +} +static void map_copy(void) { + unsigned char *image=VirtualAlloc(NULL,0x299000, + MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE); + require(image!=NULL,"component map");mapped=image; + FILE *f=fopen("Neutron.exe","rb");require(f!=NULL,"copied EXE"); + fseek(f,0,SEEK_END);long size=ftell(f);rewind(f); + require(size>64&&size<16000000,"bounded EXE"); + unsigned char *data=malloc(size);require(data!=NULL,"file allocation"); + require(fread(data,1,size,f)==(size_t)size,"read EXE");fclose(f); + require(*(uint16_t*)data==IMAGE_DOS_SIGNATURE,"DOS header"); + uint32_t offset=*(uint32_t*)(data+0x3c); + require(offset<(uint32_t)size-sizeof(IMAGE_NT_HEADERS32),"NT header bounds"); + IMAGE_NT_HEADERS32 *nt=(void*)(data+offset); + require(nt->Signature==IMAGE_NT_SIGNATURE&&nt->FileHeader.Machine==IMAGE_FILE_MACHINE_I386 + &&nt->OptionalHeader.ImageBase==0x400000&&nt->OptionalHeader.SizeOfImage==0x299000,"PE32 layout"); + IMAGE_SECTION_HEADER *sections=IMAGE_FIRST_SECTION(nt); + require((unsigned char*)(sections+nt->FileHeader.NumberOfSections)<=data+size,"section table bounds"); + for(unsigned i=0;iFileHeader.NumberOfSections;i++) { + IMAGE_SECTION_HEADER *s=§ions[i]; + require((uint64_t)s->PointerToRawData+s->SizeOfRawData<=(uint64_t)size + &&(uint64_t)s->VirtualAddress+s->SizeOfRawData<=nt->OptionalHeader.SizeOfImage,"section bounds"); + memcpy(image+s->VirtualAddress,data+s->PointerToRawData,s->SizeOfRawData); + } + free(data); + for(unsigned i=0;i