Match original collision rounding through populated dynamic reclip
This commit is contained in:
1 parent
135ff3642a
commit
bf876e9c3c
22 files changed
+701
-14
No files matched your search
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 <file>` 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.
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -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#
|
||||
|
||||
@@ -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
|
||||
|
||||
+8
-2
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -30,7 +30,11 @@ public static class OriginalBodySupport
|
||||
private static readonly ushort[] halfAcos = BuildHalfAcos();
|
||||
|
||||
/// <summary>OMT1001FF70: largest component divided by a quantized sine lookup.</summary>
|
||||
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];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="../../src/GamePort/Assets/*.cs" />
|
||||
<Compile Include="../../src/GamePort/Game/*.cs" />
|
||||
<None Include="expected.json" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -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<JsonElement>();
|
||||
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 <observations.json>");
|
||||
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<CameraRayPolygon> polygons = [];
|
||||
private readonly List<string> events = [];
|
||||
private int dynamicCallbacks,staticCallbacks,setters,kernelCalls;
|
||||
private CameraRayPolygon seed;
|
||||
public List<JsonElement> 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)
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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]}
|
||||
]
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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('<f',expected)==struct.pack('<f',actual)
|
||||
else:same=expected==actual
|
||||
return [] if same else [dict(path=path,original=expected,managed=actual)]
|
||||
|
||||
|
||||
def compare(output,managed):
|
||||
native=json.loads((output/'observations.json').read_text());actual=json.loads(managed.read_text())
|
||||
if any(tuple(c['name'] for c in data['cases'])!=CASES for data in (native,actual)):
|
||||
raise ValueError('Case sequence changed')
|
||||
cases=[dict(name=a['name'],differences=differences(a,b)) for a,b in zip(native['cases'],actual['cases'])]
|
||||
if any([s['index'] for s in data['diagnostic_steps']]!=list(range(12)) for data in (native,actual)):
|
||||
raise ValueError('Kernel trace incomplete')
|
||||
steps=[dict(index=a['index'],differences=differences(a,b)) for a,b in zip(native['diagnostic_steps'],actual['diagnostic_steps'])]
|
||||
result=dict(exact_cases=sum(not c['differences'] for c in cases),total_cases=len(cases),
|
||||
cases=cases,diagnostic_steps=steps,scope='Exact parsed float32 comparisons, no tolerance. Differences are unresolved, not accepted source parity.')
|
||||
(output/'comparison.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
return result
|
||||
|
||||
|
||||
def prepare(original,output):
|
||||
result=generate(original,output)
|
||||
source=output/'dynamic_context_probe.c'
|
||||
source.write_text(source.read_text().split('int main(void)')[0])
|
||||
(output/'dynamic_reclip_probe.c').write_text(Path(__file__).with_name('dynamic_reclip_probe.c').read_text())
|
||||
return result
|
||||
|
||||
|
||||
def capture(output,directory):
|
||||
sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
source=json.loads((output/'source.json').read_text())
|
||||
metadata=json.loads((directory/'capture.json').read_text())
|
||||
log=(directory/'wine.log').read_text()
|
||||
if metadata['captures'][-1]['wineExit']!=0 or 'DYNAMIC_RECLIP_COMPLETE' not in log:
|
||||
raise ValueError('Incomplete component execution')
|
||||
for filename,key in [('Neutron.exe','sha256'),('OMT2.dll','omt_sha256')]:
|
||||
if sha(find_case(directory/'game',filename))!=source[key]:raise ValueError('Copied source mismatch')
|
||||
if json.loads((directory/'probe-identity.json').read_text())['sha256']!=sha(output/'probe.exe'):
|
||||
raise ValueError('Probe identity mismatch')
|
||||
cases=[json.loads(line[7:]) for line in log.splitlines() if line.startswith('RECLIP ')]
|
||||
if tuple(c['name'] for c in cases)!=CASES:raise ValueError('Case sequence changed')
|
||||
files=[directory/'wine.log',directory/'capture.json',directory/'probe-identity.json',output/'source.json',
|
||||
*(output/name for name in ('dynamic_reclip_probe.c','dynamic_context_probe.c','collision_dispatch_probe.c',
|
||||
'collision_response_probe.c','collision_response_relocations.h','probe.exe'))]
|
||||
steps=[json.loads(line[12:]) for line in log.splitlines() if line.startswith('KERNEL_STEP ')]
|
||||
if [s['index'] for s in steps]!=list(range(12)):raise ValueError('Incomplete diagnostic kernel trace')
|
||||
result=dict(cases=cases,diagnostic_steps=steps,provenance={str(p):sha(p) for p in files},
|
||||
scope='Complete copied dynamic query/static dispatcher/kernel; synthetic actors/callbacks/transforms and populated grid. Not full scene or real actor execution.')
|
||||
(output/'observations.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
return dict(cases=len(cases),scope=result['scope'])
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
cli=argparse.ArgumentParser(description=__doc__)
|
||||
cli.add_argument('original',type=Path);cli.add_argument('--output',type=Path,required=True)
|
||||
mode=cli.add_mutually_exclusive_group()
|
||||
mode.add_argument('--capture',type=Path);mode.add_argument('--managed',type=Path);args=cli.parse_args()
|
||||
print(json.dumps(compare(args.output,args.managed) if args.managed else
|
||||
capture(args.output,args.capture) if args.capture else prepare(args.original,args.output),indent=2))
|
||||
@@ -0,0 +1,83 @@
|
||||
/* Complete original dynamic box + populated static grid; bounded actor fixtures.
|
||||
* Included source is generated without its standalone main. Originals untouched. */
|
||||
#include "dynamic_context_probe.c"
|
||||
static unsigned char stale_polygon[0x30];
|
||||
static char events[4096];
|
||||
static unsigned event_length,kernel_zero,kernel_lower;
|
||||
static int tracing;
|
||||
static unsigned trace_steps;
|
||||
static void vector_json(Vec p){printf("[%.9g,%.9g,%.9g,%.9g]",p.x,p.y,p.z,p.w);}
|
||||
|
||||
static int polygon_id(void *p) {
|
||||
if(!p)return -1;
|
||||
if(p==stale_polygon)return 99;
|
||||
if(p==polygon[0])return 0;
|
||||
if(p==polygon[1])return 1;
|
||||
require(0,"unknown fixture polygon");return -2;
|
||||
}
|
||||
static void event(unsigned slot,void*p) {
|
||||
int count=snprintf(events+event_length,sizeof(events)-event_length,
|
||||
"%s%x:%d:%u",event_length?",":"",slot,polygon_id(p),*(unsigned*)AT(0x695d74));
|
||||
require(count>0&&event_length+(unsigned)count<sizeof(events),"event bound");
|
||||
event_length+=(unsigned)count;
|
||||
}
|
||||
static void TC response370(void*self,Vec n,void*p){event(0x370,p);on_contact(self,n,p);}
|
||||
static void TC response374(void*self,Vec n,void*p){event(0x374,p);on_contact(self,n,p);}
|
||||
static void TC publish(void*self,Vec p){event(0x314,NULL);set_root(self,p);}
|
||||
static unsigned observe_kernel(Vec a,Vec b,Vec c,Vec n,Vec previous,Vec*current,float radius,int edges) {
|
||||
Vec input=*current;
|
||||
if(*(unsigned*)AT(0x695d74))kernel_lower++;else kernel_zero++;
|
||||
memcpy(AT(0x47bd80),kernel_prefix,5);
|
||||
unsigned result=((Kernel)AT(0x47bd80))(a,b,c,n,previous,current,radius,edges);
|
||||
if(tracing&&trace_steps<12){
|
||||
printf("KERNEL_STEP {\"index\":%u,\"input\":",trace_steps++);vector_json(input);
|
||||
printf(",\"output\":");vector_json(*current);
|
||||
printf(",\"contact\":%u,\"face\":%.9g,\"edge\":%.9g,\"hit\":",result&255,
|
||||
*(float*)AT(0x695d5c),*(float*)AT(0x5cfbe0));vector_json(*(Vec*)AT(0x5cfbe8));puts("}");
|
||||
}
|
||||
hook_jump(AT(0x47bd80),observe_kernel);return result;
|
||||
}
|
||||
static void setup(void) {
|
||||
reset();event_length=kernel_zero=kernel_lower=trace_steps=0;events[0]=0;tracing=0;
|
||||
memset(stale_polygon,0,sizeof(stale_polygon));
|
||||
*(Vec*)(stale_polygon+8)=(Vec){0,0,1,0};*(void**)AT(0x695d4c)=stale_polygon;
|
||||
sphere_table[0x370/4]=(uintptr_t)response370;sphere_table[0x374/4]=(uintptr_t)response374;
|
||||
sphere_table[0x314/4]=(uintptr_t)publish;
|
||||
}
|
||||
static void z_wall(unsigned id,float z) {
|
||||
add_triangle(id,(Vec){-100,-100,z,1},(Vec){-100,100,z,1},
|
||||
(Vec){100,100,z,1},(Vec){0,0,1,0});
|
||||
}
|
||||
static void result(const char*name) {
|
||||
int hit=((int(__cdecl*)(void*,void*))AT(0x47a5e0))(box_object,sphere_object)&255;
|
||||
Vec h=*(Vec*)AT(0x5cfbe8);
|
||||
printf("RECLIP {\"name\":\"%s\",\"contact\":%d,\"root\":[%.9g,%.9g,%.9g,%.9g],\"face\":%.9g,\"edge\":%.9g,\"hit\":[%.9g,%.9g,%.9g,%.9g],\"last\":%d,\"dynamicCallbacks\":%u,\"staticCallbacks\":%u,\"setters\":%u,\"passes\":%u,\"visits\":%u,\"mode\":%u,\"kernelZero\":%u,\"kernelLower\":%u,\"events\":\"%s\"}\n",
|
||||
name,hit,sphere_root.x,sphere_root.y,sphere_root.z,sphere_root.w,
|
||||
*(float*)AT(0x695d5c),*(float*)AT(0x5cfbe0),h.x,h.y,h.z,h.w,
|
||||
polygon_id(*(void**)AT(0x695d4c)),dynamic_callbacks,static_callbacks,setters,
|
||||
*(unsigned*)AT(0x695d78),*(unsigned*)AT(0x695d70),*(unsigned*)AT(0x695d74),
|
||||
kernel_zero,kernel_lower,events);
|
||||
}
|
||||
int main(void) {
|
||||
setbuf(stdout,NULL);map_copy();
|
||||
memcpy(kernel_prefix,AT(0x47bd80),5);hook_jump(AT(0x47bd80),observe_kernel);
|
||||
setup();z_wall(0,35);result("nearer_wall");
|
||||
setup();z_wall(0,10);result("equal_dynamic_face");
|
||||
setup();z_wall(0,0);result("far_wall");
|
||||
setup();z_wall(0,35);z_wall(1,30);result("two_near_first");
|
||||
setup();z_wall(0,30);z_wall(1,35);result("two_far_first");
|
||||
setup();z_wall(0,35);mutate=1;result("nearer_callback_root");
|
||||
setup();z_wall(0,35);inhibit=1;result("inhibit_static_visit");
|
||||
setup();z_wall(0,35);*(unsigned char*)AT(0x4f69e5)=0;result("geometry_off_visits");
|
||||
setup();z_wall(0,35);sphere_object[0x42c]=1;result("forced_primitive_mode");
|
||||
setup();z_wall(0,0);*(Vec*)(stale_polygon+8)=(Vec){0,-1,0,0};result("stale_ceiling_callback");
|
||||
setup();z_wall(0,0);sphere_root.y=30;
|
||||
add_triangle(1,(Vec){-100,35,-100,1},(Vec){-100,35,100,1},(Vec){100,35,100,1},(Vec){0,-1,0,0});
|
||||
result("ceiling_response");
|
||||
setup();z_wall(0,35);sphere_previous.y=-30;
|
||||
add_triangle(1,(Vec){-100,5,-100,1},(Vec){100,5,100,1},(Vec){100,5,-100,1},(Vec){0,-1,0,0});
|
||||
tracing=1;result("wall_and_ceiling");
|
||||
setup();z_wall(0,35);result("retained_first");
|
||||
sphere_previous=(Vec){0,0,50,1};sphere_root=(Vec){0,0,15,1};result("retained_second");
|
||||
puts("DYNAMIC_RECLIP_COMPLETE");return 0;
|
||||
}
|
||||
Reference in new issue
Block a user