From bf876e9c3ca921f3bbdb0de3ce8880e5b2b7a115 Mon Sep 17 00:00:00 2001 From: Cristian Cerroni Date: Sat, 7 Nov 2026 08:26:17 -0500 Subject: [PATCH] Match original collision rounding through populated dynamic reclip --- AGENTS.md | 8 + docs/analysis/dynamic-collision.md | 6 + docs/architecture.md | 7 + docs/checkpoint/coverage.md | 7 + docs/checkpoint/dynamic-context.md | 5 + docs/checkpoint/dynamic-reclip.md | 153 ++++++++++++++++++ docs/checkpoint/next-work-plan.md | 6 + docs/compatibility.md | 16 ++ docs/decisions.md | 10 ++ docs/progress.md | 25 +++ docs/reverse-engineering.md | 5 + docs/tasks.md | 10 +- scripts/test.sh | 1 + src/GamePort/Game/OriginalBodySupport.cs | 29 ++-- src/GamePort/Game/OriginalSphereResponse.cs | 13 +- src/GamePort/Game/OriginalStaticCollision.cs | 3 + .../GamePort.DynamicReclipTests.csproj | 13 ++ tests/GamePort.DynamicReclipTests/Program.cs | 153 ++++++++++++++++++ .../GamePort.DynamicReclipTests/expected.json | 32 ++++ tests/test_dynamic_reclip.py | 48 ++++++ tools/binary/dynamic_reclip.py | 82 ++++++++++ tools/binary/dynamic_reclip_probe.c | 83 ++++++++++ 22 files changed, 701 insertions(+), 14 deletions(-) create mode 100644 docs/checkpoint/dynamic-reclip.md create mode 100644 tests/GamePort.DynamicReclipTests/GamePort.DynamicReclipTests.csproj create mode 100644 tests/GamePort.DynamicReclipTests/Program.cs create mode 100644 tests/GamePort.DynamicReclipTests/expected.json create mode 100644 tests/test_dynamic_reclip.py create mode 100644 tools/binary/dynamic_reclip.py create mode 100644 tools/binary/dynamic_reclip_probe.c diff --git a/AGENTS.md b/AGENTS.md index 03be2c1..b843a4e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,6 +68,14 @@ relative to construction; preserve retained hit/last polygon and final local-roo publication. Jeep default deletion eligibility is guarded, full cleanup remains open. Next nonempty shared static reclip/ordered bodies and real callbacks; no live pair admission or package change.345 Python checks and539 originals pass. +Populated continuation: docs/checkpoint/dynamic-reclip.md matches14 full original/ +C# observations and12 kernel steps. Shared edge/ray math now retains evidenced +float-store boundaries; NodeVisits precedes the geometry gate. No broad x87 or +new actor admission claim. Next real Jimmy/VR04 callback mutations/live getter +timing and retained helper cleanup/order; consult current verification receipts. +The populated correction passes348 Python+2 HUD, all managed projects and36 GPU +checks, plus native Linux Carl/VR04 SDL replays and Windows x64 cross-publish. +All539 originals and924ad2f packages are unchanged; no new Windows execution. 2026-11-06 continuation: the earlier292 original component cases plus50 derived- caller cases and body/visual-sync audit supply no extra reset. Startup diagnostics diff --git a/docs/analysis/dynamic-collision.md b/docs/analysis/dynamic-collision.md index d8afb24..cce1d14 100644 --- a/docs/analysis/dynamic-collision.md +++ b/docs/analysis/dynamic-collision.md @@ -143,3 +143,9 @@ Empty-grid tests close that finite ownership contract, not nonempty shared-world behavior, real actor responses or broad live admission. The source kernel itself has since been recovered in collision-response/body reports; the older unresolved wording above describes this report's original implementation checkpoint. + +The [populated follow-up](../checkpoint/dynamic-reclip.md) adds14 exact full +observations and12 kernel-step matches, with source-store corrections in shared +edge/ray arithmetic. This closes the populated synthetic reclip contract without +replacing the live injected adapter. Real callbacks, live getter timing and +retained physical/helper order remain the admission boundary. diff --git a/docs/architecture.md b/docs/architecture.md index edaf409..f7a2559 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,6 +5,13 @@ SDL3 for platform windowing, input and audio. Linux x64 and Windows x64 are equally required. Source is `src/GamePort/`; root executable csproj allows `dotnet build` and `dotnet run` from GamePort. No runtime network dependencies. +Shared collision kernels retain recovered float-store boundaries in edge +projection and ray normalization/hit publication. `StaticCollisionContext` keeps +nearest/last polygon, passes, pre-geometry node visits and actual primitive tests +separate. Dynamic pair/reclip composition remains a test fixture until real +actor callbacks and retained physical order are recovered. See +checkpoint/dynamic-reclip.md; no generic live box solver is implied. + `Scooter` is a separate registered C3DJEEP in VR05/LEV1, owning body, wheels, steering/impact/jump clocks and camera state. Selection summons at the companion; strict contact transfers raw control. PlayerSceneBinding runs body, player/input, diff --git a/docs/checkpoint/coverage.md b/docs/checkpoint/coverage.md index faa6da9..cf0118b 100644 --- a/docs/checkpoint/coverage.md +++ b/docs/checkpoint/coverage.md @@ -1,5 +1,12 @@ # Core architecture coverage map +2026-11-07 populated follow-up: [dynamic reclip](dynamic-reclip.md) adds14 full +original/C# comparisons and12 kernel-step matches (S/P/M). Real synthetic static +walls/ceiling now exercise shared nearest, retries,370/374 order and primitive +mode. Kernel arithmetic corrections follow captured divergences and original +float-store boundaries; no numerical tolerance was added. Actual actor callbacks, +post-callback flag/radius ownership and retained helper order still gate live pairs. + 2026-11-07: [dynamic/shared context](dynamic-context.md) adds17 complete original/ C# test-composition cases and12 captured kernel argument matches (S/P/M). Hit/last-polygon retention, old static callback and final local-root publication diff --git a/docs/checkpoint/dynamic-context.md b/docs/checkpoint/dynamic-context.md index 3f677d9..45d318b 100644 --- a/docs/checkpoint/dynamic-context.md +++ b/docs/checkpoint/dynamic-context.md @@ -137,6 +137,11 @@ cleanup, child deletion, sweep execution or final retained registry order. ## Remaining admission gates and next chunk +Follow-up: [populated reclip](dynamic-reclip.md) now executes real synthetic static +walls/ceiling and matches14 full observations/12 kernel steps after directly +evidenced rounding corrections. The first gate below is closed for that bounded +composition; real actors, ordered-body provenance and reentrancy remain separate. + 1. Exercise static geometry after a dynamic hit, rather than only empty-grid reclip. Compare shared nearest/last ownership across two real primitive candidates and ordered bodies, including face/edge ties and flag transitions. diff --git a/docs/checkpoint/dynamic-reclip.md b/docs/checkpoint/dynamic-reclip.md new file mode 100644 index 0000000..3c15989 --- /dev/null +++ b/docs/checkpoint/dynamic-reclip.md @@ -0,0 +1,153 @@ +# Populated dynamic reclip and recovered rounding boundaries + +2026-11-07. Continues [dynamic context](dynamic-context.md). The complete original +box query now runs against a populated synthetic static grid. Fourteen full +observations and12 diagnostic kernel steps match the C# composition exactly as +parsed float32 values. This checkpoint corrects directly evidenced shared math; +it does not admit dynamic pairs or new actors to live gameplay. + +## Evidence and runtime boundary + +Canonical EXE SHA-256: +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +The generator reuses the prior11 guarded bodies/102 relocations, including +47A5E0,47B4B0,47BBB0,47BD80,469880 and469B70. Body hashes, PE offsets and copied +OMT2.dll identity are retained in `artifacts/dynamic-reclip/native/source.json`. + +REA evidence is reused, not regenerated for an unchanged question: + +| Evidence | Source | +|---|---| +|`ev_0d64cc58fa8f5573fc8e61e0f2c20e36288099212bd2257d3a3121361fd6c904`|Complete original instruction listing; decisive float stores/call order.| +|`ev_76827fca086933b7c48a9036a5a4a0a0f86d714935de6373eca4a3530fd231c5`|47A5E0 mode2 pseudocode, retained under dynamic-context/rea.| +|`ev_f39128dafc2a3a20b5768613ce22b3c3168fe8653908837d92ad9a69ef5f2ad8`|47B4B0 static traversal/retry; see collision-grid-traversal.md.| +|`ev_5e39f2668d04b1fdd2c91b298a28413327dc3879e6b8bbffe0a14bc1dcbc1128`|4695B0 nearest-edge pseudocode; assembly resolves intermediate stores.| + +`tools/binary/dynamic_reclip.py` generates a bounded harness containing copies of +the existing probe sources without their mains. The new executable calls copied +source bodies with synthetic box/sphere getters, point transforms, callbacks and +grid nodes. It never invokes the original entry point. An instrumented private +mapped47BD80 counts primitive mode and captures12 steps only for the skew case; +the hook restores original entry bytes for each real kernel invocation. Original +files and on-disk copied EXE remain unpatched. This is Wine32 component execution, +not full original gameplay, live actor callbacks or native Windows verification. + +Final execution is under `artifacts/dynamic-reclip/probe-verified/`, with no +network or Original-directory mount. An earlier overlapping prefix preparation +produced no observations; a separate completed prefix then exceeded the12-second +startup bound while still running. The45-second bound completed successfully. +Incomplete attempts and intermediate comparisons are preserved separately and +are not counted as source observations. One initial ceiling triangle missed the +intended path; the final fixture covers it and proves a real370 callback. + +## Shared state through populated static geometry + +The box is identity-oriented with cube(−50,−50,−10)..(50,50,10), radius40; +sphere radius10, previous(0,0,50), current(0,0,15). The dynamic face query normally +gives rootZ20, face40, edge10 and hitZ10. A separate old polygon99 is seeded. + +| Fixture | Original result / dependency | +|---|---| +|Static wallZ35|Nearer static face wins: rootZ45, face15, hitZ35, last0;2 passes/4 cell-list visits.| +|WallZ10 at equal dynamic face|No replacement: rootZ20, face40, old polygon99 survives.| +|Far wallZ0|No replacement; old polygon99 still supplies the terminal callback.| +|Walls35→30 and30→35|Both end atZ45/face15; winning polygon is0 or1 according to its identity.2 passes/8 visits.| +|Root-mutating callbacks|Final local root still overwrites the mutation, now toZ45.| +|Box response inhibited|Only dynamic callback; no static visits, passes or setter.| +|Static geometry disabled|2 node visits, no static kernel calls; retained old-polygon callback still occurs.| +|Sphere42C enabled|12 dynamic kernel calls in mode0,4 static kernel calls in mode1, terminal callbacks/setter in mode0.| +|Old ceiling polygon|No accepted static face, but retained normal−Y invokes370 rather than374.| +|Real ceilingY35|Root(0,25,23.7499962), face43.7501259, last1;370 follows dynamic374, then314;2 passes/12 visits.| +|Repeated query without context reset|Nearest limits reset per dynamic query; last polygon and all callback/pass/visit/kernel counters persist across calls.| + +The real ceiling fixture starts currentY30 and uses a triangle covering positiveZ. +The skew fixture instead starts previousY−30/currentY0 and registers the original +wall/ceiling triangles without claiming that the ceiling accepts. Its dynamic +edge→face sequence is the numerical diagnostic below. + +The callback event string records virtual slot, polygon identity and global mode. +Dynamic callbacks use374/null. Static callback370/374 selects from the **retained +last polygon's normal**, and final314 follows callbacks. Every observation compares +contact, rootXYZW, face/edge/hitXYZW, last identity, callback/setter/pass/visit counts, +global mode, mode0/1 kernel counts and complete event order. Sequential queries use +the same synthetic actor; they do not prove registry order across real actors. + +## First divergences and supported corrections + +Text offsets are VA−400000; the source tools check actual PE mapping. + +1. **Visited nodes and primitive tests have different owners.** At47B6A8..47B6B9 + (file7B6A8),695D70 increments before4F69E5 is checked. The first managed + comparison reported0 visits versus original2 with geometry disabled. + `StaticCollisionContext.NodeVisits` now counts before that gate, while + `TriangleTests` continues counting only dispatched primitives. This is a + diagnostic-state correction, not a new collision response. +2. **Segment projection X retains its product.** The skew case's first differing + kernel is zero-based6: input(0,0,15,1) matches, but source hitX is + `8.68490133e-7` and managed hitX was0.4699A0..4699DE (file699A0) retains + directionX×projection until adding originX; Y/Z products have intermediate + float stores. `OriginalSphereResponse.NearestOnSegment` now follows those + separate boundaries.47C194..47C1D0 likewise retains X/Z products through the + final edge-root subtraction. This makes the complete step6 output match. +3. **Ray normalization and hit publication retain intermediates.** The next + mismatch is step7's face hit.469BE5..469C09 (file69BE5) uses OMT's returned + quick-magnitude quotient directly for reciprocal normalization; a float return + inserted an extra rounding.469DF0..469E13 (file69DF0) stores hit coordinates + after multiply+add. `OriginalBodySupport` now retains the magnitude intermediate + as double for these ray callers, and delays coordinate rounding until that + final store. Its public float QuickMagnitude result and caller-owned nearest + reduction remain float. All14 final observations and12 kernel steps now match. + +Intermediate failure logs and experiment snapshots remain local, including +`managed-initial.log`, `managed-after-visits.log`, `projection-experiment.log`, +`ray-experiment.log` and `wide-experiment.log`. No epsilon or near-zero clamp was +added. The comparator parses native9-digit and managed shortest decimal spellings +back to float32; distinct values remain failures. Double intermediates reproduce +these fixtures, not every x87 extended-precision or table-boundary case. + +## Implementation and validation + +Runtime changes are confined to the shared support/ray and sphere kernels plus +the additional static visit counter. `tests/GamePort.DynamicReclipTests` keeps +fixed numeric references and all12 kernel steps for artifact-free normal runs; +`--native` checks the complete generated observation file, and `--dump` supports +future differential tracing. Python tests guard instruction boundaries, safe +generation and exact-float comparison semantics. Both probe source and expected +data are test fixtures, not new actor implementations. + +`scripts/test.sh` exits0 with348 Python+2 HUD Python checks, all managed projects, +36 Vulkan/render checks with zero validation errors, audio lifecycle and539 +original hashes. Debug build has zero warnings/errors. Native Linux SDL Carl +control (first neutral input/300 idle ticks) and VR04 jetpack steering/resize +also pass with zero validation errors. Windows x64 self-contained cross-publish +succeeds to a separate artifact directory. Existing packaged DLLs and BUILD-INFO +remain identical to924ad2f; no new package or Windows execution is claimed. + +Reproduction after **waiting for disposable prefix preparation to complete**: + +```sh +python3 tools/binary/dynamic_reclip.py ../Original --output artifacts/dynamic-reclip/native +i686-w64-mingw32-gcc -O0 -Wall -Wextra -Wno-unused-function -o artifacts/dynamic-reclip/native/probe.exe artifacts/dynamic-reclip/native/dynamic_reclip_probe.c +python3 tools/recon/reference_capture.py --asset-probe --probe-executable artifacts/dynamic-reclip/native/probe.exe --probe-success DYNAMIC_RECLIP_COMPLETE --seconds 45 --output artifacts/dynamic-reclip/probe-verified +python3 tools/binary/dynamic_reclip.py ../Original --output artifacts/dynamic-reclip/native --capture artifacts/dynamic-reclip/probe-verified +source scripts/env.sh +dotnet run --project tests/GamePort.DynamicReclipTests -- --native artifacts/dynamic-reclip/native/observations.json +``` + +For a complete field/step difference report, run `--dump` to a local file, then +pass that file as `dynamic_reclip.py --managed ` with the same output path. +The generated comparison explicitly records every mismatch; it does not turn +nearby values into parity. Final platform/suite receipts are in progress.md and +compatibility.md; local identities/results are in artifacts/dynamic-reclip/. + +## Remaining gate and next chunk + +Populated-grid composition now supports a bounded shared-context response. Before +live admission, recover actual Jimmy/VR04 actor callback mutations, live flag/ +radius reads after callbacks, constructor-only helper re-entry/cleanup and real +physical registration order across LOAD/RETURN. Reentrant global-mode and grid +mutation, extreme coordinates/degenerate inputs and general x87 boundary behavior +remain open. Preserve lab/outside capsule and the existing VR04 static-only actor +set. Next focus on real actor callback ownership, then implement the bounded +response adapter against those interfaces. No movement tuning, angle reset, +gadget feature or unsupported dynamic actor is introduced here. diff --git a/docs/checkpoint/next-work-plan.md b/docs/checkpoint/next-work-plan.md index da466be..c69eb14 100644 --- a/docs/checkpoint/next-work-plan.md +++ b/docs/checkpoint/next-work-plan.md @@ -43,6 +43,12 @@ mutations/children/order remain open. Next extend to nonempty static reclip and ordered-body context, then real actor callbacks and retained helper cleanup. Keep the current live solver and924ad2f packages while those gates remain. +Populated follow-up: [dynamic reclip](dynamic-reclip.md) now matches14 complete +observations and12 kernel steps. Direct source-store corrections remove two +rounding divergences without admitting new actors. Next prioritize real Jimmy/ +VR04 callback mutations and live getter timing, then constructor-only helper +cleanup/order across LOAD/RETURN; integrate the bounded response only afterward. + ## Objective Establish the original ownership and timing of player state across gameplay, diff --git a/docs/compatibility.md b/docs/compatibility.md index d01efec..1bc0906 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -1,5 +1,21 @@ # Compatibility and validation +2026-11-07 populated-reclip correction:14 complete original/C# observations and12 +kernel steps match exact float32 values after source-store arithmetic corrections. +Initial node-visit, edge-projection and ray-hit failures are retained. No epsilon +or near-zero reset is added. `scripts/test.sh` exits0:348 Python checks,2 HUD +Python checks, all managed projects,36 Vulkan/render checks with zero validation +errors, dummy-device audio lifecycle and539 unchanged original files. Debug build +has zero warnings/errors. Native Linux1920×1080 SDL Carl-control and VR04 jetpack/ +resize replays also pass with zero validation errors; first neutral input and300 +idle ticks stay upright. Windows x64 self-contained cross-publish succeeds to a +separate artifact directory; no new Windows execution is claimed. Existing Linux/ +Windows packaged DLLs and BUILD-INFO remain the verified924ad2f baseline. +Dynamic composition still uses synthetic actors/callbacks/grid and is not live +pair admission. Double intermediates reproduce these cases, not all x87 inputs. +See [populated reclip](checkpoint/dynamic-reclip.md), with final logs/identities +under artifacts/dynamic-reclip/validation.json and its referenced artifacts. + 2026-11-07 dynamic-context checkpoint:17 copied-original mode2/static reclip observations match the C# test composition in full, including XYZW, shared nearest/hit/old polygon, callback/setter/pass counts and mode. All12 instrumented diff --git a/docs/decisions.md b/docs/decisions.md index 5f94610..d26af71 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -412,3 +412,13 @@ assets and generated packages stay excluded. Keep source topology and kernel boundary distinct. Empty-grid/synthetic actor results do not admit live scene collision. Guard default Jeep deletion while leaving cleanup-mutated active lifetime open. See checkpoint/dynamic-context.md. +58. **Follow evidenced float-store boundaries instead of accepting nearby roots.** + Populated reclip exposed an edge projection mismatch at triangle6, then a ray + hit mismatch at7. Delayed X projection/edge-root products, retained quick- + magnitude normalization and delayed hit-coordinate stores close14 complete + float32 comparisons and12 kernel steps without epsilon or near-zero clamps. + Keep public float magnitude/caller nearest state and source per-coordinate + stores distinct; double intermediates do not establish general x87 identity. + Count static node visits before the geometry gate, separately from actual + primitive tests. Real actor callbacks/lifetime still gate live integration. + See checkpoint/dynamic-reclip.md. diff --git a/docs/progress.md b/docs/progress.md index c53d03a..7cc649c 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -7,6 +7,31 @@ Next-work plan: [recover interactions, then implement verified changes](checkpoi It defines the Carl source/differential gate, the bounded implementation step, movement/contact/animation recovery and the end-to-end platform checkpoint. +## Populated reclip and source rounding + +[Populated dynamic reclip](checkpoint/dynamic-reclip.md) extends the copied +original query to14 cases with actual synthetic static triangles and12 captured +kernel steps. All fields match exactly as float32, including wall/ceiling retry, +old-polygon callbacks, disabled-geometry visits and per-primitive lower-edge mode. +A skew edge first diverged at triangle6; original instruction stores support +delayed X projection/edge publication and ray normalization/hit-point rounding. +Those shared kernels now follow the evidenced boundaries. The public float +quick-magnitude result is preserved; double intermediates are not a universal +x87 oracle. Node visits are now counted separately from primitive tests. + +No new dynamic actor or scene admission is enabled. Actual Jimmy/VR04 callback +mutations, post-callback live flag/radius reads and retained helper cleanup/order +remain next. Native source execution uses synthetic actors/grid under Wine32; +whole-original and native Windows gameplay remain separate. Detailed verification +receipts and limits are recorded in compatibility.md and the linked report. + +Verification complete: scripts/test.sh exits0 with348 Python+2 HUD checks, all +managed projects and36 Vulkan/render checks with zero validation errors; audio +lifecycle and539 original hashes pass. Native Linux Carl neutral/300-idle and +VR04 SDL steering/resize pass with zero validation errors. Windows x64 cross- +publish succeeds; no new Windows runtime claim. Existing924ad2f packages remain +unchanged while the verified source correction is committed separately. + ## Dynamic response and shared context [Dynamic context](checkpoint/dynamic-context.md) adds17 complete original/C# diff --git a/docs/reverse-engineering.md b/docs/reverse-engineering.md index a5e0001..eddcedf 100644 --- a/docs/reverse-engineering.md +++ b/docs/reverse-engineering.md @@ -5,6 +5,11 @@ 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 probes and modern runtime checks are recorded separately. +- [Populated dynamic reclip](checkpoint/dynamic-reclip.md):14 full observations + and12 captured kernel steps. Original instruction stores explain delayed edge + projection, ray normalization and hit-coordinate rounding. Shared kernels now + reproduce those cases exactly; node visits are distinct from primitive tests. + Actor callbacks/live getter timing and retained helper order remain open. - [Dynamic box/shared context](checkpoint/dynamic-context.md): full47A5E0 plus static reclip/kernel execution,17 complete C# composition comparisons and12 captured kernel triangle/normal arguments. Nearest reset, retained hit/last diff --git a/docs/tasks.md b/docs/tasks.md index 5564097..772e5e5 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -86,8 +86,14 @@ Execution order and acceptance criteria: [next work plan](checkpoint/next-work-p Preserve old polygon/hit, post-callback publication and kernel winding. Guard Jeep default teardown eligibility separately from full cleanup. See checkpoint/dynamic-context.md; no live pair admission is enabled. -- [ ] Extend dynamic reclip to nonempty static geometry/ordered bodies, real - actor callbacks and cleanup-mutated helper lifetime before live integration. +- [ ] Recover ordered-body context provenance, real actor callbacks and cleanup- + mutated helper lifetime before live integration. The populated fixtures below + close the bounded nonempty reclip contract. +- [x] Match populated static reclip in14 complete original/C# cases and12 kernel + steps. Correct directly evidenced projection, ray normalization and coordinate + float stores; separate pre-gate node visits from primitive tests. See + checkpoint/dynamic-reclip.md. Sequential same-actor queries do not establish + real physical ordering, callback mutation contracts or helper lifetime. - [x] Expand original lifecycle coverage:96 Carl contact,8 composed input/ controller/skip-prefix,48 task/objective and140 base/STOP cases; recover complete diff --git a/scripts/test.sh b/scripts/test.sh index 35bdb42..ed07037 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -20,6 +20,7 @@ dotnet run --project tests/GamePort.BodyPhysicsTests dotnet run --project tests/GamePort.BodyOwnershipTests dotnet run --project tests/GamePort.PairLifecycleTests dotnet run --project tests/GamePort.DynamicContextTests +dotnet run --project tests/GamePort.DynamicReclipTests dotnet run --project tests/GamePort.GadgetTests dotnet run --project tests/GamePort.InvisibleTests dotnet run --project tests/GamePort.BubbleMotionTests diff --git a/src/GamePort/Game/OriginalBodySupport.cs b/src/GamePort/Game/OriginalBodySupport.cs index 9c16ad5..f21e724 100644 --- a/src/GamePort/Game/OriginalBodySupport.cs +++ b/src/GamePort/Game/OriginalBodySupport.cs @@ -30,7 +30,11 @@ public static class OriginalBodySupport private static readonly ushort[] halfAcos = BuildHalfAcos(); /// OMT1001FF70: largest component divided by a quantized sine lookup. - public static float QuickMagnitude(Vector3 vector) + public static float QuickMagnitude(Vector3 vector) => (float)QuickMagnitudeIntermediate(vector); + + // OMT returns its quotient in an x87 register. Callers with no intervening + // float store must retain that intermediate; this is not general x87 emulation. + internal static double QuickMagnitudeIntermediate(Vector3 vector) { RequireFinite(vector); var x = (double)MathF.Abs(vector.X); @@ -43,7 +47,7 @@ public static class OriginalBodySupport if (z == 0) return 0; var otherSquared = x * x + y * y; var index = (int)(otherSquared * 16384 / (otherSquared + z * z)) & 0x3fff; - return (float)(z / sine[halfAcos[index] & 0x3fff]); + return z / sine[halfAcos[index] & 0x3fff]; } /// @@ -100,11 +104,13 @@ public static class OriginalBodySupport ArgumentNullException.ThrowIfNull(triangles); RequireFinite(start); RequireFinite(end); var direction = end - start; - var length = QuickMagnitude(direction); + var length = QuickMagnitudeIntermediate(direction); if (length == 0) return null; - direction /= length; + var reciprocal = 1 / length; + direction = new((float)(direction.X*reciprocal),(float)(direction.Y*reciprocal), + (float)(direction.Z*reciprocal)); SupportHit? nearest = null; - var nearestDistance = length; + var nearestDistance = (float)length; foreach (var triangle in triangles) { var hit = IntersectSegment(triangle, start, direction, length, twoSided); @@ -124,13 +130,15 @@ public static class OriginalBodySupport { RequireFinite(start); RequireFinite(end); var direction = end - start; - var length = QuickMagnitude(direction); + var length = QuickMagnitudeIntermediate(direction); if (length == 0) return null; - return IntersectSegment(triangle, start, direction / length, length, twoSided); + var reciprocal = 1 / length; + return IntersectSegment(triangle, start,new((float)(direction.X*reciprocal), + (float)(direction.Y*reciprocal),(float)(direction.Z*reciprocal)),length,twoSided); } private static SupportHit? IntersectSegment(SupportTriangle triangle, - Vector3 start, Vector3 direction, float length, bool twoSided) + Vector3 start, Vector3 direction, double length, bool twoSided) { RequireFinite(triangle.A); RequireFinite(triangle.B); RequireFinite(triangle.C); var edge1 = triangle.B - triangle.A; @@ -150,7 +158,10 @@ public static class OriginalBodySupport var distance = Dot(q, edge2) * inverse; // Beginning accepted, endpoint rejected; no invented camera radius/skin. if (distance < 0 || distance >= length) return null; - var position = start + direction * distance; + //469DF0..469E13 stores each hit coordinate only after multiply+add. + //Keep the product until that store, including near-cancelling inputs. + var position = new Vector3((float)(start.X+(double)direction.X*distance), + (float)(start.Y+(double)direction.Y*distance),(float)(start.Z+(double)direction.Z*distance)); return new SupportHit(position, triangle.ShapeId, triangle.PolygonId, QuickMagnitude(position - start)); } diff --git a/src/GamePort/Game/OriginalSphereResponse.cs b/src/GamePort/Game/OriginalSphereResponse.cs index 1488e2d..f86c124 100644 --- a/src/GamePort/Game/OriginalSphereResponse.cs +++ b/src/GamePort/Game/OriginalSphereResponse.cs @@ -55,8 +55,10 @@ public static class OriginalSphereResponse 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; + //47C194..47C1D0 keeps each X/Z product through the subtraction before + //the final float store; Vector3 multiplication would round it early. + var edgePosition = new Vector3((float)(nearest.X-(double)direction.X*radius),position.Y, + (float)(nearest.Z-(double)direction.Z*radius)); return new(edgePosition, state with { EdgeDistance = distance, Hit = nearest }, SphereContact.Edge); } @@ -67,7 +69,12 @@ public static class OriginalSphereResponse 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; + if (projection < 0) return a; + if (projection > length) return b; + //4699A0..4699DE retains X's product until adding the segment origin; + //Y/Z products have explicit intervening float stores in the source. + return new((float)(a.X+(double)direction.X*projection), + a.Y+direction.Y*projection,a.Z+direction.Z*projection); } private static float Dot(Vector3 a, Vector3 b) => diff --git a/src/GamePort/Game/OriginalStaticCollision.cs b/src/GamePort/Game/OriginalStaticCollision.cs index 88319b3..1671c23 100644 --- a/src/GamePort/Game/OriginalStaticCollision.cs +++ b/src/GamePort/Game/OriginalStaticCollision.cs @@ -8,6 +8,8 @@ public sealed class StaticCollisionContext(float radius, float faceDistance = 13 public SphereResponseState Nearest { get; internal set; } = new(faceDistance, radius, null); public CameraRayPolygon? LastPolygon { get; internal set; } public int Passes { get; internal set; } + //47B6A8..47B6B9 counts list visits before the geometry-enable gate. + public int NodeVisits { get; internal set; } public int TriangleTests { get; internal set; } } @@ -100,6 +102,7 @@ public sealed class OriginalStaticCollision if (walls.TryGetValue(cell, out var polygons)) foreach (var polygon in polygons) { + context.NodeVisits++; if (!geometryEnabled) continue; context.TriangleTests++; var result = OriginalSphereResponse.Resolve(polygon.Triangle, polygon.StoredNormal, diff --git a/tests/GamePort.DynamicReclipTests/GamePort.DynamicReclipTests.csproj b/tests/GamePort.DynamicReclipTests/GamePort.DynamicReclipTests.csproj new file mode 100644 index 0000000..0ba66f1 --- /dev/null +++ b/tests/GamePort.DynamicReclipTests/GamePort.DynamicReclipTests.csproj @@ -0,0 +1,13 @@ + + + Exenet10.0 + enableenable + false + + + + + + + + diff --git a/tests/GamePort.DynamicReclipTests/Program.cs b/tests/GamePort.DynamicReclipTests/Program.cs new file mode 100644 index 0000000..4b5ff98 --- /dev/null +++ b/tests/GamePort.DynamicReclipTests/Program.cs @@ -0,0 +1,153 @@ +using System.Numerics; +using System.Text.Json; +using GamePort.Game; + +// Synthetic actor composition, not live scene admission. All roots are points; +// callbacks mutate roots only, primitive flags remain constant during each query. +var fixture = new Fixture(); +var actual = new List(); +void Query(string name) => actual.Add(fixture.Query(name)); +fixture.Reset(); fixture.Wall(0,35); Query("nearer_wall"); +fixture.Reset(); fixture.Wall(0,10); Query("equal_dynamic_face"); +fixture.Reset(); fixture.Wall(0,0); Query("far_wall"); +fixture.Reset(); fixture.Wall(0,35); fixture.Wall(1,30); Query("two_near_first"); +fixture.Reset(); fixture.Wall(0,30); fixture.Wall(1,35); Query("two_far_first"); +fixture.Reset(); fixture.Wall(0,35); fixture.Mutate = true; Query("nearer_callback_root"); +fixture.Reset(); fixture.Wall(0,35); fixture.Inhibit = true; Query("inhibit_static_visit"); +fixture.Reset(); fixture.Wall(0,35); fixture.Geometry = false; Query("geometry_off_visits"); +fixture.Reset(); fixture.Wall(0,35); fixture.Force = true; Query("forced_primitive_mode"); +fixture.Reset(); fixture.Wall(0,0); fixture.CeilingSeed = true; Query("stale_ceiling_callback"); +fixture.Reset(); fixture.Wall(0,0); fixture.Root.Y = 30; +fixture.Ceiling(35,true); Query("ceiling_response"); +fixture.Reset(); fixture.Wall(0,35); fixture.Previous.Y = -30; +fixture.Ceiling(); Query("wall_and_ceiling"); +fixture.Reset(); fixture.Wall(0,35); Query("retained_first"); +fixture.Previous = new(0,0,50); fixture.Root = new(0,0,15,1); Query("retained_second"); + +if(args is ["--dump"]) +{ + Console.WriteLine(JsonSerializer.Serialize(new {cases = actual,diagnostic_steps = fixture.DiagnosticSteps})); + return; +} +var native = args is ["--native", _]; +if(args.Length != 0 && !native) throw new ArgumentException("Use --native "); +using var expected = JsonDocument.Parse(File.ReadAllText(native ? args[1] + : Path.Combine(AppContext.BaseDirectory,"expected.json"))); +var cases = expected.RootElement.GetProperty("cases").EnumerateArray().ToArray(); +if(cases.Length != actual.Count) throw new Exception("Case count differs"); +for(var i = 0; i < actual.Count; i++) Compare(cases[i],actual[i],cases[i].GetProperty("name").GetString()!); +Compare(expected.RootElement.GetProperty("diagnostic_steps"), + JsonSerializer.SerializeToElement(fixture.DiagnosticSteps),"diagnostic_steps"); +Console.WriteLine($"PASS {actual.Count} populated-grid dynamic/static comparisons and 12 kernel steps; exact float32, callback order and primitive mode."); + +static void Compare(JsonElement expected,JsonElement actual,string path) +{ + if(expected.ValueKind != actual.ValueKind) throw new Exception($"{path}: value kind differs"); + if(expected.ValueKind == JsonValueKind.Object) + { + if(expected.EnumerateObject().Count() != actual.EnumerateObject().Count()) throw new Exception($"{path}: fields differ"); + foreach(var p in expected.EnumerateObject()) Compare(p.Value,actual.GetProperty(p.Name),path+"."+p.Name); + } + else if(expected.ValueKind == JsonValueKind.Array) + { + if(expected.GetArrayLength() != actual.GetArrayLength()) throw new Exception($"{path}: array length differs"); + for(var i = 0; i < expected.GetArrayLength(); i++) Compare(expected[i],actual[i],$"{path}[{i}]"); + } + // Native %.9g and managed shortest-roundtrip text can spell the same float + // differently. Compare exact parsed Single values, without an epsilon. + else if(expected.ValueKind == JsonValueKind.Number) + { + if(expected.GetSingle() != actual.GetSingle()) throw new Exception($"{path}: {actual} != original {expected}"); + } + else if(!JsonElement.DeepEquals(expected,actual)) throw new Exception($"{path}: {actual} != original {expected}"); +} + +sealed class Fixture +{ + public Vector3 Previous; + public Vector4 Root; + public bool Mutate,Inhibit,Geometry,Force,CeilingSeed; + private StaticCollisionContext context = null!; + private readonly List polygons = []; + private readonly List events = []; + private int dynamicCallbacks,staticCallbacks,setters,kernelCalls; + private CameraRayPolygon seed; + public List DiagnosticSteps { get; } = []; + + public void Reset() + { + Previous = new(0,0,50); Root = new(0,0,15,1); + Mutate = Inhibit = Force = CeilingSeed = false; Geometry = true; + context = new(88,77){Nearest = new(77,88,new(111,222,333))}; + seed = new(new(new(-100,-100,0),new(-100,100,0),new(100,100,0),99,0),Vector3.UnitZ); + context.LastPolygon = seed; + polygons.Clear(); events.Clear(); + dynamicCallbacks = staticCallbacks = setters = kernelCalls = 0; + } + public void Wall(int id,float z) => polygons.Add(new(new(new(-100,-100,z),new(-100,100,z), + new(100,100,z),0,id),Vector3.UnitZ)); + public void Ceiling(float y = 5,bool positiveZ = false) => polygons.Add(new(new(new(-100,y,-100), + positiveZ ? new(-100,y,100) : new(100,y,100), + positiveZ ? new(100,y,100) : new(100,y,-100),0,1),-Vector3.UnitY)); + private int PolygonId(CameraRayPolygon? p) => p is null ? -1 : p == seed ? 99 : p.Value.Triangle.PolygonId; + private void Notify(Vector3 normal,CameraRayPolygon? polygon,int slot) + { + events.Add($"{slot:x}:{PolygonId(polygon)}:0"); + if(polygon is null) dynamicCallbacks++; else staticCallbacks++; + if(Mutate) Root = new(777,888,999,2); + } + public JsonElement Query(string name) + { + if(CeilingSeed) + { + seed = seed with { StoredNormal = -Vector3.UnitY }; + context.LastPolygon = seed; + } + var current = new Vector3(Root.X,Root.Y,Root.Z); + var candidate = current; + context.Nearest = context.Nearest with {FaceDistance = -1,EdgeDistance = 10}; + var box = new DynamicBoxCollider(1,Vector3.Zero,new(-50,-50,-10),new(50,50,10),Matrix4x4.Identity,40); + foreach(var triangle in DynamicSceneCollision.Triangles(box)) + { + var cross = Vector3.Cross(triangle.B-triangle.A,triangle.C-triangle.A); + var normal = cross/OriginalBodySupport.QuickMagnitude(cross); + kernelCalls++; + var input = candidate; + var hit = OriginalSphereResponse.Resolve(new(triangle.A,triangle.C,triangle.B),normal, + Previous,candidate,10,context.Nearest); + if(name == "wall_and_ceiling") + { + var h = hit.State.Hit!.Value; + DiagnosticSteps.Add(JsonSerializer.SerializeToElement(new { + index = DiagnosticSteps.Count,input = new[]{input.X,input.Y,input.Z,1}, + output = new[]{hit.Position.X,hit.Position.Y,hit.Position.Z,1}, + contact = hit.Contact == SphereContact.None ? 0 : 1,face = hit.State.FaceDistance, + edge = hit.State.EdgeDistance,hit = new[]{h.X,h.Y,h.Z,1} + })); + } + if(hit.Contact == SphereContact.None) continue; + candidate = hit.Position; context.Nearest = hit.State; + Notify(normal,null,0x374); + } + var contact = context.Nearest.FaceDistance != -1 || context.Nearest.EdgeDistance < 10; + if(contact && !Inhibit) + { + var world = new OriginalStaticCollision(polygons); + var clipped = world.Move(Previous,candidate-Previous,10,context,edges:false, + lowerEdges:Force,geometryEnabled:Geometry); + if(clipped.CallbackPolygon is {} polygon) + Notify(polygon.StoredNormal,polygon,polygon.StoredNormal.Y > -.7f ? 0x374 : 0x370); + events.Add("314:-1:0"); Root = new(clipped.Position,1); setters++; + } + var p = context.Nearest.Hit!.Value; + return JsonSerializer.SerializeToElement(new { + name,contact = contact ? 1 : 0,root = new[]{Root.X,Root.Y,Root.Z,Root.W}, + face = context.Nearest.FaceDistance,edge = context.Nearest.EdgeDistance, + hit = new[]{p.X,p.Y,p.Z,1},last = PolygonId(context.LastPolygon), + dynamicCallbacks,staticCallbacks,setters,passes = context.Passes, + visits = context.NodeVisits,mode = 0, + kernelZero = kernelCalls+(Force ? 0 : context.TriangleTests), + kernelLower = Force ? context.TriangleTests : 0,events = string.Join(',',events) + }); + } +} diff --git a/tests/GamePort.DynamicReclipTests/expected.json b/tests/GamePort.DynamicReclipTests/expected.json new file mode 100644 index 0000000..e5c0832 --- /dev/null +++ b/tests/GamePort.DynamicReclipTests/expected.json @@ -0,0 +1,32 @@ +{ + "cases": [ + {"name":"nearer_wall","contact":1,"root":[0,0,45,1],"face":15,"edge":10,"hit":[0,0,35,1],"last":0,"dynamicCallbacks":1,"staticCallbacks":1,"setters":1,"passes":2,"visits":4,"mode":0,"kernelZero":16,"kernelLower":0,"events":"374:-1:0,374:0:0,314:-1:0"}, + {"name":"equal_dynamic_face","contact":1,"root":[0,0,20,1],"face":40,"edge":10,"hit":[0,0,10,1],"last":99,"dynamicCallbacks":1,"staticCallbacks":1,"setters":1,"passes":1,"visits":2,"mode":0,"kernelZero":14,"kernelLower":0,"events":"374:-1:0,374:99:0,314:-1:0"}, + {"name":"far_wall","contact":1,"root":[0,0,20,1],"face":40,"edge":10,"hit":[0,0,10,1],"last":99,"dynamicCallbacks":1,"staticCallbacks":1,"setters":1,"passes":1,"visits":2,"mode":0,"kernelZero":14,"kernelLower":0,"events":"374:-1:0,374:99:0,314:-1:0"}, + {"name":"two_near_first","contact":1,"root":[0,0,45,1],"face":15,"edge":10,"hit":[0,0,35,1],"last":0,"dynamicCallbacks":1,"staticCallbacks":1,"setters":1,"passes":2,"visits":8,"mode":0,"kernelZero":20,"kernelLower":0,"events":"374:-1:0,374:0:0,314:-1:0"}, + {"name":"two_far_first","contact":1,"root":[0,0,45,1],"face":15,"edge":10,"hit":[0,0,35,1],"last":1,"dynamicCallbacks":1,"staticCallbacks":1,"setters":1,"passes":2,"visits":8,"mode":0,"kernelZero":20,"kernelLower":0,"events":"374:-1:0,374:1:0,314:-1:0"}, + {"name":"nearer_callback_root","contact":1,"root":[0,0,45,1],"face":15,"edge":10,"hit":[0,0,35,1],"last":0,"dynamicCallbacks":1,"staticCallbacks":1,"setters":1,"passes":2,"visits":4,"mode":0,"kernelZero":16,"kernelLower":0,"events":"374:-1:0,374:0:0,314:-1:0"}, + {"name":"inhibit_static_visit","contact":1,"root":[0,0,15,1],"face":40,"edge":10,"hit":[0,0,10,1],"last":99,"dynamicCallbacks":1,"staticCallbacks":0,"setters":0,"passes":0,"visits":0,"mode":0,"kernelZero":12,"kernelLower":0,"events":"374:-1:0"}, + {"name":"geometry_off_visits","contact":1,"root":[0,0,20,1],"face":40,"edge":10,"hit":[0,0,10,1],"last":99,"dynamicCallbacks":1,"staticCallbacks":1,"setters":1,"passes":1,"visits":2,"mode":0,"kernelZero":12,"kernelLower":0,"events":"374:-1:0,374:99:0,314:-1:0"}, + {"name":"forced_primitive_mode","contact":1,"root":[0,0,45,1],"face":15,"edge":10,"hit":[0,0,35,1],"last":0,"dynamicCallbacks":1,"staticCallbacks":1,"setters":1,"passes":2,"visits":4,"mode":0,"kernelZero":12,"kernelLower":4,"events":"374:-1:0,374:0:0,314:-1:0"}, + {"name":"stale_ceiling_callback","contact":1,"root":[0,0,20,1],"face":40,"edge":10,"hit":[0,0,10,1],"last":99,"dynamicCallbacks":1,"staticCallbacks":1,"setters":1,"passes":1,"visits":2,"mode":0,"kernelZero":14,"kernelLower":0,"events":"374:-1:0,370:99:0,314:-1:0"}, + {"name":"ceiling_response","contact":1,"root":[0,25,23.7499962,1],"face":43.7501259,"edge":10,"hit":[0,35,23.7499962,1],"last":1,"dynamicCallbacks":1,"staticCallbacks":1,"setters":1,"passes":2,"visits":12,"mode":0,"kernelZero":24,"kernelLower":0,"events":"374:-1:0,370:1:0,314:-1:0"}, + {"name":"wall_and_ceiling","contact":1,"root":[-8.68490019e-07,0,20.0000038,1],"face":50.0001411,"edge":5,"hit":[-8.68490019e-07,-5.48603339e-07,10.0000029,1],"last":99,"dynamicCallbacks":2,"staticCallbacks":1,"setters":1,"passes":1,"visits":6,"mode":0,"kernelZero":18,"kernelLower":0,"events":"374:-1:0,374:-1:0,374:99:0,314:-1:0"}, + {"name":"retained_first","contact":1,"root":[0,0,45,1],"face":15,"edge":10,"hit":[0,0,35,1],"last":0,"dynamicCallbacks":1,"staticCallbacks":1,"setters":1,"passes":2,"visits":4,"mode":0,"kernelZero":16,"kernelLower":0,"events":"374:-1:0,374:0:0,314:-1:0"}, + {"name":"retained_second","contact":1,"root":[0,0,45,1],"face":15,"edge":10,"hit":[0,0,35,1],"last":0,"dynamicCallbacks":2,"staticCallbacks":2,"setters":2,"passes":4,"visits":8,"mode":0,"kernelZero":32,"kernelLower":0,"events":"374:-1:0,374:0:0,314:-1:0,374:-1:0,374:0:0,314:-1:0"} + ], + "diagnostic_steps": [ + {"index":0,"input":[0,0,15,1],"output":[0,0,15,1],"contact":0,"face":-1,"edge":10,"hit":[111,222,333,1]}, + {"index":1,"input":[0,0,15,1],"output":[0,0,15,1],"contact":0,"face":-1,"edge":10,"hit":[111,222,333,1]}, + {"index":2,"input":[0,0,15,1],"output":[0,0,15,1],"contact":0,"face":-1,"edge":10,"hit":[111,222,333,1]}, + {"index":3,"input":[0,0,15,1],"output":[0,0,15,1],"contact":0,"face":-1,"edge":10,"hit":[111,222,333,1]}, + {"index":4,"input":[0,0,15,1],"output":[0,0,15,1],"contact":0,"face":-1,"edge":10,"hit":[111,222,333,1]}, + {"index":5,"input":[0,0,15,1],"output":[0,0,15,1],"contact":0,"face":-1,"edge":10,"hit":[111,222,333,1]}, + {"index":6,"input":[0,0,15,1],"output":[-8.68490133e-07,0,20,1],"contact":1,"face":-1,"edge":5,"hit":[8.68490133e-07,0,10,1]}, + {"index":7,"input":[-8.68490133e-07,0,20,1],"output":[-8.68490019e-07,0,20.0000038,1],"contact":1,"face":50.0001411,"edge":5,"hit":[-8.68490019e-07,-5.48603339e-07,10.0000029,1]}, + {"index":8,"input":[-8.68490019e-07,0,20.0000038,1],"output":[-8.68490019e-07,0,20.0000038,1],"contact":0,"face":50.0001411,"edge":5,"hit":[-8.68490019e-07,-5.48603339e-07,10.0000029,1]}, + {"index":9,"input":[-8.68490019e-07,0,20.0000038,1],"output":[-8.68490019e-07,0,20.0000038,1],"contact":0,"face":50.0001411,"edge":5,"hit":[-8.68490019e-07,-5.48603339e-07,10.0000029,1]}, + {"index":10,"input":[-8.68490019e-07,0,20.0000038,1],"output":[-8.68490019e-07,0,20.0000038,1],"contact":0,"face":50.0001411,"edge":5,"hit":[-8.68490019e-07,-5.48603339e-07,10.0000029,1]}, + {"index":11,"input":[-8.68490019e-07,0,20.0000038,1],"output":[-8.68490019e-07,0,20.0000038,1],"contact":0,"face":50.0001411,"edge":5,"hit":[-8.68490019e-07,-5.48603339e-07,10.0000029,1]} + ] +} diff --git a/tests/test_dynamic_reclip.py b/tests/test_dynamic_reclip.py new file mode 100644 index 0000000..8eb7dc0 --- /dev/null +++ b/tests/test_dynamic_reclip.py @@ -0,0 +1,48 @@ +from pathlib import Path +import json +import sys +import tempfile +import unittest + +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'tools/binary')) +from dynamic_reclip import CASES,prepare,differences +from checkpoint_script_state import find_case,read_va,EXE_SHA256 +from pe_inspect import PE + + +class DynamicReclipTests(unittest.TestCase): + def test_comparison_uses_exact_float32_and_requires_complete_fields(self): + self.assertEqual(differences({'p':[20.0000038]},{'p':[20.000004]}),[]) + self.assertEqual(differences({'p':[0]},{'p':[-8.68490133e-7]})[0]['path'],'.p[0]') + self.assertEqual(differences({'a':1},{'a':1,'extra':2})[0]['reason'],'fields differ') + self.assertEqual(differences([1],[1,2])[0]['reason'],'length differs') + + def test_original_counts_node_before_geometry_and_clears_primitive_mode(self): + pe=PE(find_case(ROOT.parent/'Original','Neutron.exe')) + for va,expected in [(0x47b6a8,'8b3d705d6900'),(0x47b6b1,'47'), + (0x47b6b2,'803de5694f0000'),(0x47b6b9,'893d705d6900'), + (0x47b742,'c705745d690000000000'), + (0x4699a0,'d9442404d84c244c'), + (0x4699c0,'d944242cd8c1d95c242c'), + (0x469be5,'ff1504d14800d83d24d94800'), + (0x469df0,'d9442454d80b')]: + self.assertEqual(read_va(pe,va,len(bytes.fromhex(expected))).hex(),expected) + + def test_generated_probe_is_bounded_and_original_output_is_rejected(self): + original=ROOT.parent/'Original' + with tempfile.TemporaryDirectory() as temporary: + output=Path(temporary) + result=prepare(original,output) + self.assertEqual(result,dict(guarded_bodies=11,relocations=102)) + source=json.loads((output/'source.json').read_text()) + self.assertEqual(source['sha256'],EXE_SHA256) + self.assertNotIn('int main(void)',(output/'dynamic_context_probe.c').read_text()) + harness=(output/'dynamic_reclip_probe.c').read_text() + self.assertEqual(len(CASES),14) + for name in CASES:self.assertIn('result("'+name+'")',harness) + with self.assertRaisesRegex(ValueError,'Separate output'): + prepare(original,original/'forbidden-generated-probe') + + +if __name__=='__main__':unittest.main() diff --git a/tools/binary/dynamic_reclip.py b/tools/binary/dynamic_reclip.py new file mode 100644 index 0000000..91d84da --- /dev/null +++ b/tools/binary/dynamic_reclip.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Capture populated-grid dynamic/static component state from copied originals.""" +import argparse +import hashlib +import json +import struct +from pathlib import Path +from dynamic_context import generate +from checkpoint_script_state import find_case + +CASES=('nearer_wall','equal_dynamic_face','far_wall','two_near_first','two_far_first', + 'nearer_callback_root','inhibit_static_visit','geometry_off_visits','forced_primitive_mode', + 'stale_ceiling_callback','ceiling_response','wall_and_ceiling','retained_first','retained_second') + + +def differences(expected,actual,path=''): + """Exact float32 comparison; report missing/extra fields, never use epsilon.""" + if isinstance(expected,dict) and isinstance(actual,dict): + if expected.keys()!=actual.keys():return [dict(path=path,reason='fields differ')] + return [d for key in expected for d in differences(expected[key],actual[key],path+'.'+key)] + if isinstance(expected,list) and isinstance(actual,list): + if len(expected)!=len(actual):return [dict(path=path,reason='length differs')] + return [d for i,(a,b) in enumerate(zip(expected,actual)) for d in differences(a,b,path+f'[{i}]')] + if isinstance(expected,(int,float)) and isinstance(actual,(int,float)): + same=struct.pack('0&&event_length+(unsigned)count