Recover sphere response and correct Jimmy ceiling cancellation

This commit is contained in:
UnixNight committed 2026-10-26 16:09:19 -04:00
1 parent 6a7a53c90d
commit 57dfcc64bb
37 files changed
+1324 -18

No files matched your search

+2
View File
@@ -102,6 +102,8 @@ Test("source enable flag and unobstructed gain leave desired eye unchanged", ()
var result = ray.Constrain(high, low);
Check(result.Eye == low && result.Gain == 1 && result.Hit == null && ray.LastTriangleTests == 0,
"disabled predicate queried geometry or moved eye");
Check(ray.TraceGeometry(high, low)?.ShapeId == 1 && ray.LastTriangleTests == 0,
"camera-only debug switch disabled ceiling geometry or changed camera diagnostics");
ray.Enabled = true;
result = ray.Constrain(new(100, 100, 100), new(100, 0, 100));
Check(result.Eye == new Vector3(100, 0, 100) && result.Gain == 1 && result.Hit == null, "miss changed eye or gain");
+3 -1
View File
@@ -17,8 +17,10 @@ var director = new SceneDirector(level, tasks, resources.Duration);
var interactions = new SceneInteractions(director, tasks, save);
var mechanisms = new SceneMechanisms(director);
var visuals = new StaticSceneVisuals(world, director, original, Path.Combine(prepared, "level1b/models"));
var geometry = OriginalCameraRay.FromRouteScene(world, level.Code);
var simulation = new LabSimulation(new SceneCollision(world), AseMesh.Load(AssetPath.Resolve(original, "ASE/jimstop.ase")),
start.Position, start.Rotation.Y) { JetpackInventoryState = () => interactions.Inventory.State(0, 3) };
start.Position, start.Rotation.Y, (a,b) => geometry.Trace(a,b), (a,b) => geometry.TraceGeometry(a,b))
{ JetpackInventoryState = () => interactions.Inventory.State(0, 3) };
simulation.DynamicRootResolver = (before, after, radius) => DynamicBodyResponse.Resolve(visuals.DoorColliders(), before, after, radius);
var patrols = new List<ActorPatrol>();
foreach (var actor in director.Actors.Where(a => a.Kind is "3DOG" or "3CAR"))
+69 -2
View File
@@ -12,6 +12,7 @@ var tests = new (string Name, Action Check)[]
("ordinary route load retains scalars independently of body/jump reset", RetainedLevelState),
("script preparation preserves queued work and uncontrolled physics consumes it", UncontrolledPhysics),
("uncontrolled fire ticks while movement and grounded-release reset are gated", UncontrolledFire),
("source root ceiling ray bounces and cancels before control ownership", CeilingWrapper),
("source camera query origin, hit adjustment, gain and one query per input", CameraQueryConsumer),
("debug noclip bypasses walls/gravity/camera and exits without queued motion", Noclip),
("turn-only speed, forward acceleration/cap and release", SpeedLimits),
@@ -191,6 +192,61 @@ static void RetainedLevelState()
Throws<ArgumentOutOfRangeException>(() => grounded.ApplyRetainedLevelState(state with { EffectRemaining = float.PositiveInfinity }));
}
static void CeilingWrapper()
{
var queries = 0;
var start = Vector3.Zero; var end = Vector3.Zero;
SupportHit? Ceiling(Vector3 a, Vector3 b)
{ queries++; start = a; end = b; return new((a + b) / 2, 1, 2, 75); }
var jump = new PlayerInput(false, false, false, false, true);
var simulation = FlatSimulation(ceilingRay: Ceiling);
simulation.Step(jump);
Check(queries == 0 && simulation.PendingImpulse.Y == 550, "Queued impulse is not upward velocity yet");
simulation.ApplyRetainedLevelState(new("LV1B", 3, 1, .625f, 6.125f));
var energy = simulation.Energy;
simulation.Step(jump, controlled: false);
NearVector(start, simulation.ActorRoot, .0001f, "Upward query uses post-physics actor root");
NearVector(end - start, Vector3.UnitY * 150, 0, "Upward ray uses authored150 span");
Check(simulation.Velocity.Y < -300 && simulation.CeilingHits == 1, "Original0.6 velocity reflection");
Check(simulation.ControllerSteps == 1 && simulation.MovementMode == 1 && simulation.JumpState == 0,
"Ceiling cancellation runs without controlled movement");
Near(simulation.JumpHoldSeconds, .625f, 0, "Cancellation preserves hold");
Near(simulation.JetpackRemaining, -FixedStepClock.Step, 0, "Fire ticks after cancellation zero");
Near(simulation.Energy, energy, 0, "Cancelled fire does not drain energy");
Check(simulation.Pose == PlayerPose.Fall && simulation.PendingImpulse == Vector3.Zero,
"FALL request and independent impulse consumption");
simulation.Step(default, controlled: false);
Check(queries == 1, "Non-upward velocity makes no ceiling query");
var otherMode = FlatSimulation(ceilingRay: Ceiling);
otherMode.Step(jump);
otherMode.ApplyRetainedLevelState(new("LV1B", 3, 0, .625f, 6.125f));
otherMode.Step(default, controlled: false);
Check(otherMode.Velocity.Y < 0 && otherMode.MovementMode == 0 && otherMode.JetpackRemaining > 6,
"Mode0 still reflects velocity but skips mode1 cancellation");
var hit = false;
var powered = FlatSimulation(ceilingRay: (a,b) => hit ? new SupportHit((a+b)/2, 1, 2, 75) : null);
powered.JetpackInventoryState = () => 1; powered.GadgetMode = 3;
for (var i = 0; i < 40; i++) powered.Step(jump);
Check(powered.JumpState == 3 && powered.JetpackRemaining > 0 && powered.Velocity.Y > 0,
"Powered ceiling fixture has active jump/fire");
hit = true; powered.Step(default, controlled: false);
Check(powered.Velocity.Y <= -85 && powered.JumpState == 0 && powered.JetpackRemaining < 0,
"Ceiling cancels an active powered burst while uncontrolled");
foreach (var retained in new[] { false, true })
{
var phases = new List<string>();
var ordered = FlatSimulation(cameraRay: (a,b) => { phases.Add("input"); return null; },
ceilingRay: (a,b) => { phases.Add("wrapper"); return null; });
ordered.InputAfterPlayerUpdate = retained;
ordered.Step(jump); phases.Clear(); ordered.Step(jump);
Check(phases.SequenceEqual(retained ? ["wrapper", "input"] : new[] { "input", "wrapper" }),
"Wrapper belongs to Jimmy callback between fresh/retained input boundaries");
}
}
static void CameraQueryConsumer()
{
var enabled = false;
@@ -584,9 +640,20 @@ static void OriginalLab(string project, string originals)
for (var i = 0; i < 120; i++) simulation.Step(default);
Check(simulation.Jumps == 1 && simulation.Landings == 1 && simulation.Grounded, "stationary original-lab jump lands once");
Near(simulation.Position.Y, .5486332f + SceneCollision.Skin, .03f, "original lab jump returns to floor");
var geometry = OriginalCameraRay.FromRouteScene(mesh, level.Code);
var overhead = new LabSimulation(collision, standing, start.Position, start.Rotation.Y,
(a,b) => geometry.Trace(a,b), (a,b) => geometry.TraceGeometry(a,b));
overhead.Step(new(false, false, false, false, true));
overhead.RestoreReturnRoot(overhead.ActorRoot + Vector3.UnitY * 300);
geometry.Enabled = false; // Modern camera-only switch must not suppress physical query.
overhead.Step(default, controlled: false);
Check(overhead.CeilingHits == 1 && overhead.Velocity.Y <= -85 && overhead.Pose == PlayerPose.Fall,
"Actual registered lab ceiling reverses upward motion with camera debug query disabled");
}
static LabSimulation FlatSimulation(float yaw = 0, Func<Vector3, Vector3, SupportHit?>? cameraRay = null)
static LabSimulation FlatSimulation(float yaw = 0, Func<Vector3, Vector3, SupportHit?>? cameraRay = null,
Func<Vector3, Vector3, SupportHit?>? ceilingRay = null)
{
var positions = new[]
{
@@ -596,7 +663,7 @@ static LabSimulation FlatSimulation(float yaw = 0, Func<Vector3, Vector3, Suppor
var floor = new Mesh(positions.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(), [0, 1, 2, 3, 4, 5]);
var standing = new Mesh([new(new(-20, -20, -20), Vector2.Zero, Vector3.One),
new(new(20, 80, 20), Vector2.Zero, Vector3.One)], []);
return new LabSimulation(new SceneCollision(floor), standing, new Vector3(0, 25, 0), yaw, cameraRay);
return new LabSimulation(new SceneCollision(floor), standing, new Vector3(0, 25, 0), yaw, cameraRay, ceilingRay);
}
static void SameState(LabSimulation actual, LabSimulation expected, string message)
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Game/OriginalBodySupport.cs" />
<Compile Include="../../src/GamePort/Game/OriginalSphereResponse.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,55 @@
using System.Numerics;
using GamePort.Game;
var wall = new SupportTriangle(new(-100, -100, 0), new(-100, 100, 0), new(100, 100, 0));
var normal = Vector3.UnitZ;
var initial = SphereResponseState.Begin(10);
SphereResponseResult Wall(Vector3 before, Vector3 after, bool edges = true, bool lower = true) =>
OriginalSphereResponse.Resolve(wall, normal, before, after, 10, initial, edges, lower);
void Near(Vector3 actual, Vector3 expected, string label)
{
if (Vector3.Distance(actual, expected) > .002f) throw new Exception($"{label}: {actual} != {expected}");
}
void Check(bool condition, string label) { if (!condition) throw new Exception(label); }
// Numeric references from the isolated copied original47BD80/OMT component.
var face = Wall(new(0, 20, 20), new(0, 20, 5));
Check(face.Contact == SphereContact.Face, "original face hit");
Near(face.Position, new(0, 20, 10), "original face response");
Check(face.State.FaceDistance == 20 && face.State.EdgeDistance == 10, "separate source nearest slots");
Near(Wall(new(0, 20, 20), new(0, 20, -20)).Position, face.Position, "through-plane response");
Check(Wall(new(0, 20, 5), new(0, 20, 20)).Contact == SphereContact.None, "departing source winding");
Console.WriteLine("PASS original face, crossing and departure references");
var edge = Wall(new(105, 100, 20), new(105, 100, 5));
Check(edge.Contact == SphereContact.Edge, "original edge hit");
Near(edge.Position, new(107.071068f, 100, 7.07106781f), "original edge response");
Near(edge.State.Hit!.Value, new(100, 100, 0), "original nearest vertex");
Check(Wall(new(105, 100, 20), new(105, 100, 5), edges: false).Contact == SphereContact.None,
"edge switch does not run face fallback");
Console.WriteLine("PASS original edge reference and disabled edge gate");
var upper = Wall(new(105, 105, 20), new(105, 105, 5));
Check(upper.Contact == SphereContact.Edge, "lower edge allowed");
Near(upper.Position, new(105.77375f, 105, 5.7737484f), "original lower-edge mode1 reference");
Check(Wall(new(105, 105, 20), new(105, 105, 5), lower: false).Contact == SphereContact.None,
"source lower-edge flag");
var ceiling = new SupportTriangle(new(-100, 100, -100), new(100, 100, 100), new(100, 100, -100));
var under = OriginalSphereResponse.Resolve(ceiling, -Vector3.UnitY, new(0, 80, 0), new(0, 95, 0), 10, initial);
Check(under.Contact == SphereContact.Face, "ceiling face");
Near(under.Position, new(0, 90, 0), "ceiling includes Y response");
Console.WriteLine("PASS lower-edge policy and ceiling face response");
var farther = OriginalSphereResponse.Resolve(wall, normal, new(0, 20, 20), new(0, 20, 5), 10,
initial with { FaceDistance = 19 });
Check(farther.Contact == SphereContact.None, "farther face suppressed without edge fallback");
var tied = OriginalSphereResponse.Resolve(wall, normal, new(0, 20, 20), new(0, 20, 5), 10, face.State);
Check(tied.Contact == SphereContact.None && tied.State == face.State, "equal face retains earlier state");
var edgeSuppressed = OriginalSphereResponse.Resolve(wall, normal, new(105, 100, 20), new(105, 100, 5),
10, initial with { EdgeDistance = 1 });
Check(edgeSuppressed.Contact == SphereContact.None, "edge nearest state persists across candidates");
Console.WriteLine("PASS shared nearest-hit and equal-distance boundaries");
try { Wall(new(float.NaN, 0, 0), Vector3.Zero); throw new Exception("NaN accepted"); }
catch (ArgumentOutOfRangeException) { }
Console.WriteLine("PASS bounded finite inputs; complete body solver and x87 boundary parity remain open");
@@ -19,8 +19,10 @@ var director = new SceneDirector(level, tasks, resources.Duration);
var interactions = new SceneInteractions(director, tasks, save);
var mechanisms = new SceneMechanisms(director);
var visuals = new StaticSceneVisuals(world, director, original, Path.Combine(prepared, "level1b/models"));
var geometry = OriginalCameraRay.FromRouteScene(world, level.Code);
var simulation = new LabSimulation(new SceneCollision(world), AseMesh.Load(AssetPath.Resolve(original, "ASE/jimstop.ase")),
start.Position, start.Rotation.Y) { JetpackInventoryState = () => interactions.Inventory.State(0, 3) };
start.Position, start.Rotation.Y, (a,b) => geometry.Trace(a,b), (a,b) => geometry.TraceGeometry(a,b))
{ JetpackInventoryState = () => interactions.Inventory.State(0, 3) };
var resolverCalls = 0;
simulation.DynamicRootResolver = (before, after, radius) =>
{
+19
View File
@@ -0,0 +1,19 @@
from pathlib import Path
import sys
import unittest
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tools/binary'))
from body_root_registration import collect
class BodyRootRegistrationTests(unittest.TestCase):
def test_registration_and_repeated_init_bytes(self):
result=collect(ROOT.parent/'Original')
self.assertEqual(len(result['sites']),14)
self.assertEqual(len(result['tables']),4)
targets={x['name']:x['target'] for x in result['tables']}
self.assertEqual(targets['Jimmy InitPhysics'],'0x42ab50')
self.assertEqual(targets['authored root'],'0x471630')
if __name__=='__main__':unittest.main()
+60
View File
@@ -0,0 +1,60 @@
"""Shared-eye source anchors and phase-specific DEFAULT/follow boundaries."""
from pathlib import Path
import struct
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from camera_handoff import CameraProjection, collect, default_handoff, normal_follow
class CameraHandoffTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent / 'Original')
def test_original_shared_storage_and_callback_targets(self):
sites = {s['name']: s for s in self.report['sites']}
self.assertEqual(sites['walking_previous_x']['bytes'], 'd94044d99d14070000')
self.assertEqual(sites['airborne_previous_x']['bytes'], 'd94044d95c243c')
self.assertEqual(self.report['threshold']['value'], 1000)
targets = {t['name']: t['target'] for t in self.report['tables']}
self.assertEqual(targets['Jimmy walking input/follow'], '0x438bc0')
self.assertEqual(targets['Jimmy airborne input/follow'], '0x439900')
def test_default_below_equal_above_and_already_owned(self):
threshold_bits, = struct.unpack('<I', struct.pack('<f', 1000))
for offset, snapped in ((-1, False), (0, False), (1, True)):
distance, = struct.unpack('<f', struct.pack('<I', threshold_bits+offset))
view = CameraProjection((distance, 0, 0), (1, 2, 3))
result = default_handoff(view, (0, 0, 0), False)
self.assertEqual(result.eye, (0, 0, 0) if snapped else view.eye)
self.assertEqual(result.direction, view.direction, 'DEFAULT changes no orientation in this block')
owned = CameraProjection((5000, 0, 0), (1, 0, 0))
self.assertEqual(default_handoff(owned, (0, 0, 0), True), owned)
def test_first_resumed_follow_uses_scripted_shared_eye(self):
scripted = CameraProjection((600, 200, -200), (-600, -100, 200))
restored = default_handoff(scripted, (0, 500, -500), False)
self.assertEqual(restored, scripted, 'Within threshold retains scripted shared eye')
followed = normal_follow(restored, (0, 180, -350), (0, 99, 0), 1/60)
self.assertAlmostEqual(followed.eye[0], 584)
self.assertAlmostEqual(followed.eye[1], 199.6)
self.assertAlmostEqual(followed.eye[2], -204)
self.assertEqual(followed.direction, (-600, -101, 200), 'Aim derives from pre-update shared eye')
stale = CameraProjection((0, 180, -350), (0, 0, 1))
self.assertNotEqual(normal_follow(stale, (0, 180, -350), (0, 99, 0), 1/60).eye, followed.eye)
def test_snap_then_follow_preserves_phase_boundary(self):
scripted = CameraProjection((5000, 500, -500), (-1, 0, 0))
snapped = default_handoff(scripted, (0, 500, -500), False)
self.assertEqual(snapped.eye, (0, 500, -500))
self.assertEqual(snapped.direction, scripted.direction)
followed = normal_follow(snapped, (0, 180, -350), (0, 99, 0), 1/60, 1.5)
self.assertAlmostEqual(followed.eye[1], 490.4)
self.assertEqual(followed.direction, (0, -401, 500))
if __name__ == '__main__':
unittest.main()
+50
View File
@@ -0,0 +1,50 @@
"""Byte-guarded Jimmy ceiling query and cancellation boundaries."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from ceiling_wrapper import CeilingState, ceiling_projection, collect, upward_segment
class CeilingWrapperTests(unittest.TestCase):
def test_original_byte_constants_and_virtual_contracts(self):
report = collect(ROOT.parent / 'Original')
self.assertEqual(len(report['sites']), 37)
self.assertEqual(len(report['tables']), 8)
self.assertEqual(len(report['constants']), 6)
self.assertEqual(len(report['bodies']), 4)
def test_query_is_logical_root_to_plus150_not_capsule_top(self):
self.assertEqual(upward_segment((10, 75, 20)), ((10, 75, 20), (10, 225, 20)))
with self.assertRaises(ValueError):
upward_segment((0, float('nan'), 0))
def test_only_upward_hit_changes_velocity_with_minimum_downward_speed(self):
for vy in (0, -1, -200):
state = CeilingState((3, vy, 4), 1, 3, 8)
self.assertEqual(ceiling_projection(state, True), (state, ()))
slow = CeilingState((3, 10, 4), 1, 3, 8)
self.assertEqual(ceiling_projection(slow, False), (slow, ('query47C210',)))
self.assertEqual(ceiling_projection(slow, True)[0].velocity, (3, -85, 4))
fast = CeilingState((3, 200, 4), 1, 3, 8)
self.assertEqual(ceiling_projection(fast, True)[0].velocity, (3, -120, 4))
def test_cancel_is_mode1_only_and_preserves_other_motion_fields(self):
state = CeilingState((3, 10, 4), 1, 3, 8, .625, 264, 550)
result, events = ceiling_projection(state, True)
self.assertEqual((result.mode, result.jump, result.fire_remaining), (1, 0, 0))
self.assertEqual((result.hold, result.extra_acceleration, result.queued_impulse), (.625, 264, 550))
self.assertEqual(events, ('query47C210', 'velocity2C4', 'cancel1E0', 'FALL', 'cleanup140'))
for mode in (-1, 0, 2):
source = CeilingState((3, 10, 4), mode, 3, 8)
result, events = ceiling_projection(source, True)
self.assertEqual((result.mode, result.jump, result.fire_remaining), (mode, 3, 8))
self.assertEqual(events, ('query47C210', 'velocity2C4', 'cancel1E0'))
missing = CeilingState((3, 10, 4), 1, 3, None)
self.assertIsNone(ceiling_projection(missing, True)[0].fire_remaining)
if __name__ == '__main__':
unittest.main()
+27
View File
@@ -0,0 +1,27 @@
from pathlib import Path
import sys
import unittest
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tools/binary'))
from collision_response import collect, header, TARGETS
class CollisionResponseTests(unittest.TestCase):
def test_original_callgraph_bodies_and_constants(self):
report=collect(ROOT.parent/'Original')
self.assertEqual(len(report['bodies']),6)
self.assertAlmostEqual(report['constants']['0x48d974'],.7)
self.assertAlmostEqual(report['constants']['0x4a3148'],-.7)
self.assertEqual(report['constants']['0x49b1f8'],-1)
def test_probe_relocations_are_bounded_explicit_operands(self):
report=collect(ROOT.parent/'Original')
locations=[p['va'] for p in report['probe_operands']]
self.assertEqual(len(locations),len(set(locations)))
self.assertGreater(len(locations),40)
self.assertTrue(all(p['target'] in TARGETS for p in report['probe_operands']))
self.assertIn('{0x47c0c0, 0x48d104}',header(report))
if __name__=='__main__': unittest.main()