From 976e677019bcb640d5b8c8fc9a46eb19b11d0e18 Mon Sep 17 00:00:00 2001 From: Cristian Cerroni Date: Sat, 24 Oct 2026 20:57:39 -0400 Subject: [PATCH] Restore original airborne steering for jumps and jetpack bursts --- README.md | 2 +- docs/analysis/air-steering.md | 85 +++++++++++++++++++++ docs/analysis/jetpack.md | 9 +++ docs/analysis/movement-checkpoint.md | 14 ++-- docs/architecture.md | 7 ++ docs/compatibility.md | 11 +-- docs/progress.md | 25 +++++-- docs/reverse-engineering.md | 1 + docs/tasks.md | 2 + scripts/test.sh | 1 + src/GamePort/Game/AirSteering.cs | 36 +++++++++ src/GamePort/Game/LabSimulation.cs | 24 +++++- src/GamePort/Program.cs | 38 +++++++--- tests/GamePort.MovementTests/Program.cs | 98 +++++++++++++++++++++---- tests/test_air_steering.py | 40 ++++++++++ tools/recon/reference_capture.py | 18 +++-- 16 files changed, 357 insertions(+), 54 deletions(-) create mode 100644 docs/analysis/air-steering.md create mode 100644 src/GamePort/Game/AirSteering.cs create mode 100644 tests/test_air_steering.py diff --git a/README.md b/README.md index c761b1f..658042c 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ art identifies it as the **jet pack**. Its practice prompt accepts **Y** or a cl on Yes to enter VR04, and **N** or a click on No to resume. Enter selects the hovered Yes region, otherwise No. The original practice return uses the saved lab start tag. Runtime checkpoint-position restoration is still unrecovered. -Normal midair arrows do not steer. Source patrol/door logic is integrated, while +In the air, Up accelerates, Left/Right turn, and Down brakes horizontal motion. Source patrol/door logic is integrated, while sensing, full collision response, alpha/lighting and audio effects remain incomplete. `--load-save PATH` reads original TSK task/items/score/checkpoint state; diff --git a/docs/analysis/air-steering.md b/docs/analysis/air-steering.md new file mode 100644 index 0000000..3e29f80 --- /dev/null +++ b/docs/analysis/air-steering.md @@ -0,0 +1,85 @@ +# Corrected airborne keyboard input + +User testing exposed an error in the earlier reconstruction: Jimmy could rise +with the jet pack but could not begin moving/turning in the air. This report +supersedes the no-air-steering claim in the original movement checkpoint. +Read-only Neutron.exe addresses are VAs; text file offsets are VA-0x400000. + +## Dispatch error and recovered handler + +The signed mode at interface+704 (complete+7C4) selects jump table438BA4: +mode0->438B31, mode1->438B60, mode2->438B6D, mode3->438B82. Mode1 logs at +438B60, removes its printf argument at438B6A, then **falls through** to438B6D. +438B76 calls complete-object virtual128, whose Jimmy vtable4A3BDC entry is439900. +It does not return after logging. The earlier report incorrectly read that +control flow and a regression test encoded the error. Both have been corrected. + +Normal jump/jetpack movement uses mode1 and the following keyboard subset of +439900. Special movement mode2 (distinct from gadget selection) shares the input +handler but has extra turn/pose/camera behavior; that full mode is not implemented. + +| Input/rule | Source | Implemented arithmetic | +| --- | --- | --- | +| Left before Right |439943/439966|Left precedence; adjust turn rate by+100*dt or-100*dt| +| Release keyboard turn |439989..439A19|Move prior turn rate toward0 by100*dt, clamp crossing| +| Normal air turn limit |439D81..439DB7|Clamp rate to[-30,+30] degrees/sec| +| Up |439AE6..439B69|Add source30 speed per call, cap600| +| Coast |439B69..439BA2|If speed>600*0.909090936, subtract35*.5; otherwise retain| +| Down with positive speed |439C1D..439C78|Subtract35*.5, clamp at0| +| Down with negative speed |439C7A..439CB2|Add35 toward0, clamp crossing| + +Forward acceleration precedes braking when Up/Down are both held. Turn alone +does not use ground acceleration. At normal maximum600, release coasts down +600->582.5->565->547.5->530 and retains530 until another input/ground phase. +Down brakes, rather than starting reverse air movement. These are source rules, +not a replacement walking controller enabled wholesale in the air. + +## Velocity and integration + +Air apply437F90 preserves vertical velocity, adds turnRate*dt to current yaw +at438011..43802B, and calculates lateral velocity at43803B..438062 as: + +``` +sideSpeed = turnRate * (1-friction) * speed * float(1/55) +velocityXZ = forward(yaw)*speed + right(yaw)*sideSpeed +``` + +Source friction is0.8. Air sideSpeed lacks the additional ground dt factor; +ground437CDx uses (turnRate*(1-friction)*speed/45+keyboardSide)*dt instead. +The port now preserves the shared turn-rate field through landing and clears it +on scene reset. Air input's destination yaw is current yaw (439E2B), so the ground +keyboard target offset does not override its direct yaw update. + +AirSteering.cs translates this keyboard subset. LabSimulation calls it while +airborne, including before burst activation and after release. The +existing jetpack vertical state/effect/energy behavior remains a separate phase. +Full original input/update/rotation phase order, mouse/analog, pitch/roll/lean, +special flight mode2, collision response and camera are still incomplete. Current +integration is yaw-only at fixed60Hz with the provisional collision capsule. + +## Verification + +-2 Python source tests guard all four dispatch-table entries, mode1 fall-through, + vtable128 and decisive keyboard/constants/air-lateral instruction sites. +-16 movement groups pass, replacing the invalid no-air-steering fixture with + ordinary-jump response, exact keyboard arithmetic, powered takeoff-from-rest + steering/braking, left/right paths and60/120/144Hz equivalent replay. +-14 vertical jetpack groups remain passing. Input-only lab navigation still + reachesSCENE60, score150, owned jet pack and the original outside LOAD. +-The upgraded VR04 smoke starts vertically, presses Up/Left/Down during active + flight, releases the burst and lands. Headless llvmpipe renders300 frames: + powered horizontal travel403.88, one burst/landing, maximum rise418.98, + zero Vulkan validation errors. It requires actual powered horizontal travel + and nonzero turn rate, so the previous frozen-air implementation fails it. +-Window mode injects all four Up/Left/Down/Shift keys through SDL, runs300 frames + and resizes800x600. Package/runtime results are recorded in compatibility.md. + +These are static and port runtime regressions; original gameplay comparison and +native Windows verification remain distinct. Original assets remain unchanged. + +Final package checks: Linux self-contained GTX1070 and Windows self-contained +under isolated Wine64 both receive the full SDL input sequence, resize and finish +with identical403.88 powered travel and grounded position. Linux reports zero +validation errors; Wine validation is disabled. Logs: artifacts/package-jetpack-steering.log +and artifacts/windows-jetpack-steering-package/wine.log. Native Windows remains +unverified by the agent. All539 original hashes still match. diff --git a/docs/analysis/jetpack.md b/docs/analysis/jetpack.md index b6dd060..d0cbbe0 100644 --- a/docs/analysis/jetpack.md +++ b/docs/analysis/jetpack.md @@ -97,3 +97,12 @@ timer, energy clamp/VR immunity, depletion, explicit phase differences, absent effect and bounded malformed input. The existing13 movement groups still pass. These are static/data/port algorithm checks. Original gameplay/native Windows comparison remains required before a fidelity claim. + + +## Airborne steering correction + +User testing found frozen horizontal control during powered flight. The original +mode1 dispatcher falls through to439900; the earlier no-input interpretation was +wrong. AirSteering now supplies the separate source airborne keyboard path for +both jumps and bursts. Up accelerates, Left/Right ramp turn rate, Down brakes. +See air-steering.md for dispatch proof, exact arithmetic and new movement/GPU tests. diff --git a/docs/analysis/movement-checkpoint.md b/docs/analysis/movement-checkpoint.md index 27532fc..f51a199 100644 --- a/docs/analysis/movement-checkpoint.md +++ b/docs/analysis/movement-checkpoint.md @@ -44,14 +44,12 @@ support can receive the full 550 impulse with no net gravity that step, before airborne acceleration begins. A port's immediate grounded-to-airborne transition can differ by one tick; do not claim an exact original jump apex. -Movement dispatcher mode 1 (`0x438B60`) logs and returns without running -walking input. Ordinary arrow acceleration/turn input is therefore absent -while that air mode is active. Air apply reuses takeoff speed and rotation, -preserving vertical velocity; with the default extra turn rate zero, it has -no new keyboard steering. Its nonzero extra-turn lateral calculation uses -`turnRate*(1-friction)*speed/55`, without the ground branch's additional `dt` -on lateral magnitude, and omits the keyboard side contribution. A port that -allows normal walking input in the air should identify that as an approximation. +**Correction from user testing:** mode1 (`0x438B60`) logs and falls through +`0x438B6D` to complete virtual128=`0x439900`, the separate airborne input handler. +The earlier claim that it returned without input was wrong. Normal jumps and +jet pack flight allow Up acceleration, Down braking and Left/Right turn-rate +control. The corrected source arithmetic, regressions and remaining integration +limits are in [air-steering.md](air-steering.md). Ground input remains separate. ## Normal keyboard walking diff --git a/docs/architecture.md b/docs/architecture.md index c57aeaa..5bf6c4f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -115,3 +115,10 @@ SceneAudio. Stopping disposes the loop and retains its selected resource identit return starts the selected track again. Standalone speech streams do not decide music policy. Tests distinguish source CAM lifecycle from generic music/speech mixing and cover natural completion, reset and skip. + + +AirSteering provides439900's normal airborne keyboard subset independently of +walking input. Mode1 logs then falls through to its real handler; it is not a +no-input state. LabSimulation preserves the turn-rate field, uses recovered air +coasting/braking and applies the distinct ground/air lateral formulas. Mouse, +analog, full lean/camera and original global phase order remain incomplete. diff --git a/docs/compatibility.md b/docs/compatibility.md index b18411f..7d36a38 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -27,11 +27,11 @@ separate evidence categories. **The game is not fully reconstructed/playable yet | Mouse/relative input/controller | Incomplete | SDL entry point declaration alone is not behavior | | Audio stream | Linux dummy device | Original11025Hz mono WAV consumed10752bytes/500ms; speakers untested | | Physics fragments/RNG | Standalone C# tests | Recovered arithmetic; controller/jump/collision state incomplete | -| No-gadget walking/jump controller | Linux tests and GPU replay pass | Recovered speed/yaw/ballistic formulas; transient jump state/order approximated | +| Walking/jump/air controller |16 movement groups + GPU replay pass |Corrected mode1 fall-through to source air handler: acceleration/braking/turning during jumps and bursts; phase/collision/lean remain provisional | | Static source collision | 11 deterministic groups pass | Capsule sweep/slide, walls/ceilings/slopes/ledges; all2869 lab triangles retained; masks/dimensions provisional | -| Simulation cadence | 13 movement groups pass | Fixed60Hz independent of60/120/144Hz rendering, ten-minute finite run; original cadence unresolved | +| Simulation cadence |16 movement groups pass | Fixed60Hz independent of60/120/144Hz rendering, ten-minute finite run; original cadence unresolved | | Walking camera and animation | Linux headless/window pass | Original five motion clips, recovered eye180/target99; pivot, timing and obstruction solver provisional | -| Walk SDL input/resize | GTX1070/Xvfb240-step pass | Arrows/Shift injected through SDL; travel1250.12,jump/landing; resize800x600; zero validation errors | +| Walk SDL input/resize | Earlier GTX1070/Xvfb240-step pass |Historical pre-air-fix travel1250.12; current corrected managed/headless replay1264.55. Current powered SDL check is below | | TSK saves/task gates | All12 originals byte-round-trip | Bounded parse/write, task/items/score/checkpoint CLI resume; full game-state/menu save incomplete | | Lab CAM/MCA/AI interpreter | Source sequence tests + Linux GPU pass |16 speech cues, recovered camera formulas, skip/actions/control restoration; no original comparison | | Dynamic actors/sprites/models | Linux GPU pass |Carl/Goddard/Jimmy morphs, source Canv timing and9 original lab props; billboard/alpha, pivots and playback timing remain provisional | @@ -39,12 +39,13 @@ separate evidence categories. **The game is not fully reconstructed/playable yet | VR01 star/trophy contacts | Source-data tests pass |5-point stars,300 trophy, acquired flags and contact-enter semantics; distance/exclusions/box approximation | | RETURN / renderer recreation | Linux headless pass |Original VR01 RETURN dispatch renders VR01 thenLV1B, zero validation errors; fades/window transition unverified | | Supplied scene availability |All35 GAMs supplied;33 have OMT geometry |Level3B/E GAMs are duplicate four-entity records apart from level code; registered OMT archives absent, normal gameplay use unverified; no substitution or established blocker | -| Lab task/contact route | Managed input replay + headless GPU pass |888 input-only movement steps with live contacts/NPC updates reachSCENE60, score150, jetpack andlevel1; separate direct-contact GPU rebuild check | +| Lab task/contact route | Managed input replay + headless GPU pass |914 input-only movement steps with live contacts/NPC updates reachSCENE60, score150, jetpack andlevel1; separate direct-contact GPU rebuild check | | Patrol/support |10 patrol +13 support groups pass |Source phases/profiles and8 DLL magnitude refs; Carl sensing, Goddard follow and full wall response incomplete | | Buttons/doors | Source state tests and GPU props pass |Cooldown, hold/reversal, original model transforms; source broadphase/box order with modern narrowphase | | Dynamic collision |10 managed groups pass |Includes actual closed/open lab bars; full source solver/activation exclusions incomplete | | Lab objectives/practice | Art/data/managed/headless + native Linux window pass |Exact source coordinates, modal pause, Y/N/pointer rules; N resumes and resize800x600 onGTX1070, zero errors; slide/highlight incomplete | -| Jetpack tutorial |14 state groups +300-step VR04 GPU pass |FLY/fire effect, radius/timer/energy/VR rules; maxrise418.98/landing, zero validation errors; phase/shadow/collision approximations | +| Jetpack tutorial |14 vertical groups +16 movement groups +300-step VR04 GPU pass |Powered horizontal travel403.88, turn/brake/release and landing; rise418.98, zero validation errors; phase/shadow/collision/lean approximations | +| Powered SDL/package steering |Linux GTX1070 and preliminary Wine64 window pass |300 frames, Up/Left/Down/Shift received, resize800x600, travel403.88/landing; Linux zero validation errors, Wine validation disabled; native Windows pending | | Default effects bank |251 exact RIFF exports, SDL dummy pass |Pickup/button/door sounds and owner-loop stop; positional/volume/channel policy incomplete; MPEG-in-RIFF bird1/id162 unsupported by SDL WAV | | Complete scene/gameplay loop | Incomplete |Lab navigation, exact collision/pivot/cadence and original reference comparison still required | | Menus/AI/combat/progression/saves | Incomplete | Required future work | diff --git a/docs/progress.md b/docs/progress.md index c88d625..5b8a7df 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -4,6 +4,19 @@ user-verified Windows rendering checkpoint into an interactive original lab and jet pack tutorial flow. This is not a verified faithful complete scene or release. +## Jetpack steering correction + +User testing exposed frozen airborne steering. The earlier recovery incorrectly +read mode1's log branch as an early return; it actually falls through to439900. +The port now uses the original airborne Up acceleration, Down braking and +Left/Right turn-rate rules for jumps and jet pack bursts. Source byte checks, +16 movement groups,14 vertical burst groups and the full input-only lab route pass. +VR04 GPU replay travels403.88 horizontally during powered flight, turns and lands +with zero validation errors. The rebuilt Linux package and Windows package under isolated Wine64 pass300 +SDL-input frames with Up/Left/Down/Shift and resize800x600, matching403.88 travel. +Linux GTX1070 validation reports zero errors; Wine validation is disabled. +Native Windows retesting remains unverified by the agent. Details and remaining fidelity limits: analysis/air-steering.md. + ## Latest user-tested correction User testing found background music continuing during cutscenes. Recovered CAM @@ -19,8 +32,8 @@ report and exact static rules support this fix. An additional managed replay now walks through explanation, jet pack, Carl and outside LOAD using only movement inputs, source live contacts and NPC patrol/body -updates. It reachesSCENE60/score150 with jet pack owned after888 movement steps -and7100.55 travel; the player is never repositioned. This strengthens port lab +updates. It reachesSCENE60/score150 with jet pack owned after914 movement steps +and7038.29 travel with corrected airborne input; the player is never repositioned. This strengthens port lab navigation coverage without proving original collision/cadence fidelity. ## Current integrated behavior @@ -76,16 +89,16 @@ confidence and approximation boundaries are retained there. Managed checks cover source data, director/actions/cameras, task/interactions, patrol, recovered support, moving-box collision, jetpack states and HUD composition. -Python currently has36 top-level regression tests plus2 targeted UI extraction tests. -Existing11 collision and13 movement groups pass;14 jetpack groups pass. Eight +Python currently has38 top-level regression tests plus2 targeted UI extraction tests. +Existing11 collision and16 movement groups pass;14 jetpack groups pass. Eight quick-magnitude float results are checked against an isolated original DLL probe. Original mode2 standing/jump animation probes confirm zero dynamic-point offsets for the tested clips. This is DLL evidence, not observed original game behavior. Headless llvmpipe runs render the story, model actors, practice prompt, lab exit and VR04 entry with zero Vulkan validation errors. The300-step VR04 powered replay -jumps once, rises418.98 units and lands; VR immunity retains20 energy. The ordinary -240-step replay travels1250.12 and rises137.62; port landing-count telemetry changed +jumps once, rises418.98 units and lands; VR immunity retains20 energy. The corrected ordinary +240-step replay travels1264.55 and rises137.62; port landing-count telemetry changed with the explicit state table. These measurements verify port behavior only. See artifacts/full-integration-test.log and practice/jetpack logs for current checks. diff --git a/docs/reverse-engineering.md b/docs/reverse-engineering.md index 477e41b..e89f212 100644 --- a/docs/reverse-engineering.md +++ b/docs/reverse-engineering.md @@ -16,6 +16,7 @@ probes and modern runtime checks are recorded separately. - `analysis/dynamic-collision.md`: source3DUD broadphase/triangle order and modern response boundary. - `analysis/buttons-doors.md`: button contact/cooldown and moving-bar state machine. - `analysis/ui.md`: original objective/practice canvases, coordinates, input and return strings. +- `analysis/air-steering.md`: corrected mode1 fall-through, airborne keyboard handler and source regression evidence. - `analysis/jetpack.md`: corrected lab pickup identity, powered-jump/effect/energy phases. - `analysis/sound-effects.md`: default bank identity, preserved wave payloads and loop lifecycle. - `original-manifest.json`: complete original SHA-256 baseline. diff --git a/docs/tasks.md b/docs/tasks.md index 6919c3e..fe28dcd 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -21,6 +21,8 @@ compile, runtime and original-fidelity verification are separate. - [x] Shared Goddard/Carl patrol subset and recovered body support with DLL checks. - [x] Button/vertical-door behavior and source dynamic broadphase/box triangle rules. - [x] Powered-jump state/effect/energy arithmetic, original FLY/fire morphs and GPU replay. +- [x] Correct mode1 input dispatch and source airborne steering for jumps/bursts; + Up acceleration, Down braking, Left/Right turn and powered travel regressions. ## Immediate continuation diff --git a/scripts/test.sh b/scripts/test.sh index b28d1ce..67a21cc 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -42,6 +42,7 @@ SDL_AUDIODRIVER=dummy dotnet run --no-build -- --scene-audio-smoke artifacts/ext SDL_AUDIODRIVER=dummy dotnet run --no-build -- --cutscene-audio-smoke artifacts/extracted/level1b/entities/entities.json python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then + dotnet run --no-build -- --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-jetpack --screenshot artifacts/test-jetpack-window.ppm dotnet run --no-build -- --smoke-practice-window --frames 12 --screenshot artifacts/test-practice-window.ppm dotnet run --no-build -- --scene artifacts/extracted/level1b/scene.json --smoke-window --frames 6 --screenshot artifacts/test-window.ppm dotnet run --no-build -- --smoke-walk --screenshot artifacts/test-walk-window.ppm diff --git a/src/GamePort/Game/AirSteering.cs b/src/GamePort/Game/AirSteering.cs new file mode 100644 index 0000000..18c96f6 --- /dev/null +++ b/src/GamePort/Game/AirSteering.cs @@ -0,0 +1,36 @@ +namespace GamePort.Game; + +public readonly record struct AirSteeringResult(float Speed, float TurnRate); + +/// Keyboard subset of normal airborne input439900 (mode1). +/// Modes1/2 share the handler; special flight mode2 and mouse/analog are separate. +/// +public static class AirSteering +{ + public const float TurnAcceleration = 100; //48D96C, applied with dt. + public const float TurnLimit = 30; //439D81..439DB7, ordinary mode1. + public const float CoastThreshold = 0.9090909361839294f; //49D5DC. + + public static AirSteeringResult Step(float speed, float turnRate, PlayerInput input, float seconds) + { + if (!float.IsFinite(speed) || !float.IsFinite(turnRate) || !float.IsFinite(seconds) || seconds < 0 || seconds >= 1) + throw new ArgumentOutOfRangeException(nameof(seconds)); + var turnStep = TurnAcceleration * seconds; + if (input.Left) turnRate += turnStep; + else if (input.Right) turnRate -= turnStep; + else if (turnRate < 0) turnRate = MathF.Min(0, turnRate + turnStep); + else if (turnRate > 0) turnRate = MathF.Max(0, turnRate - turnStep); + turnRate = Math.Clamp(turnRate, -TurnLimit, TurnLimit); + + if (input.Forward) speed = RecoveredMotion.AddSpeed(speed); + else if (speed > RecoveredMotion.MaximumSpeed * CoastThreshold) + speed -= RecoveredMotion.SpeedDecay * .5f; + //439C1D..439CB2 brakes to0, without starting reverse flight. + if (input.Backward) + { + if (speed > 0) speed = MathF.Max(0, speed - RecoveredMotion.SpeedDecay * .5f); + else if (speed < 0) speed = MathF.Min(0, speed + RecoveredMotion.SpeedDecay); + } + return new(speed, turnRate); + } +} diff --git a/src/GamePort/Game/LabSimulation.cs b/src/GamePort/Game/LabSimulation.cs index b5a842e..2046e1f 100644 --- a/src/GamePort/Game/LabSimulation.cs +++ b/src/GamePort/Game/LabSimulation.cs @@ -7,7 +7,7 @@ public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly } /// -/// No-gadget walking checkpoint. Recovered input/arithmetic is described in +/// Walking, airborne steering and jetpack checkpoint. Recovered arithmetic is described in /// movement-checkpoint.md. Capsule, floor-derived pivot and 60Hz are port policies; /// original collision, intro, object interactions and animation timing remain open. /// @@ -33,6 +33,7 @@ public sealed class LabSimulation public Vector3 Velocity { get; private set; } public float Yaw { get; private set; } public float Speed { get; private set; } + public float TurnRate { get; private set; } public bool Grounded { get; private set; } public PlayerPose Pose => Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle : jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly @@ -74,7 +75,7 @@ public sealed class LabSimulation Position = new(sourceStart.X, floor + SceneCollision.Skin, sourceStart.Z); Velocity = Vector3.Zero; Yaw = targetYaw = startYaw; - Speed = extraAirAcceleration = shadowDistance = 0; + Speed = TurnRate = extraAirAcceleration = shadowDistance = 0; jumpState = default; forceFall = JetpackEffectVisible = false; InteractionRadius = 60; Bursts = 0; @@ -109,11 +110,25 @@ public sealed class LabSimulation if (input.Backward) Speed = MathF.Max(Speed - 52.5f, -300); else if (!input.Forward) Speed = RecoveredMotion.ReleaseSpeed(Speed); } + else + { + var steering = AirSteering.Step(Speed, TurnRate, input, dt); + Speed = steering.Speed; TurnRate = steering.TurnRate; + //439E2B preserves current yaw as the destination; air apply then + //438011..43802B adds the independent turn rate directly to yaw. + targetYaw = Yaw; + } var yawError = MathF.IEEERemainder(targetYaw - Yaw, 360); Yaw = (Yaw + yawError * dt * 3.7f) % 360; + if (Velocity.LengthSquared() != 0 || Grounded && lateral != 0) + Yaw = (Yaw + TurnRate * dt) % 360; var (sin, cos) = Trig(Yaw); var velocity = new Vector3(-sin * Speed, Velocity.Y, cos * Speed); - if (Grounded) velocity += new Vector3(cos, 0, sin) * (lateral * dt); + //437CDx ground uses /45 then dt;43803B air uses /55 without dt. + const float friction = .8f; + var sideSpeed = Grounded ? (TurnRate * (1 - friction) * Speed / 45 + lateral) * dt + : TurnRate * (1 - friction) * Speed * .0181818176060915f; + velocity += new Vector3(cos, 0, sin) * sideSpeed; if (collision.GroundHeight(ActorRoot, 2500) is { } shadowFloor) shadowDistance = MathF.Abs(ActorRoot.Y - shadowFloor - 13); var air = JetpackBurst.Step(jumpState, new(Grounded, input.Jump, velocity.Y, shadowDistance, @@ -170,6 +185,9 @@ public sealed class LabSimulation public static PlayerInput SmokeInput(int step) => new(step < 120, false, false, step >= 120 && step < 180, step >= 72 && step < 84); + public static PlayerInput JetpackSmokeInput(int step) => new(step is >= 45 and < 80, + step is >= 80 and < 120, step is >= 60 and < 95, false, step < 180); + public bool SmokePassed => Steps >= 240 && Travel > 50 && MaximumRise > 20 && Jumps > 0 && Landings > 0 && Grounded; public string Report => $"Walk checkpoint: steps={Steps}, travel={Travel:F2}, jumps={Jumps}, landings={Landings}, max rise={MaximumRise:F2}, wall hits={WallHits}, grounded={Grounded}, feet={Position}."; } diff --git a/src/GamePort/Program.cs b/src/GamePort/Program.cs index b09489d..87b0809 100644 --- a/src/GamePort/Program.cs +++ b/src/GamePort/Program.cs @@ -76,7 +76,7 @@ internal static class Program --smoke-practice-prompt Headless original jet pack practice prompt --smoke-practice-transition Headless lab-to-VR04 practice transition --smoke-practice-window SDL practice pause/dismiss/resize check (12 frames) - --smoke-jetpack Headless 300-step powered-jump/release check in VR04 + --smoke-jetpack 300-step powered steering/jump check in VR04 --verify-assets Decode all original PNG/ASE files --smoke-window Test keyboard event/resize (requires --frames 6 or more) --no-validation Disable development validation @@ -325,8 +325,8 @@ internal static class Program if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless) throw new ArgumentException("Story time must be0..3600 seconds in headless mode."); var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : headless ? "1" : "0")); - if (jetpackSmoke && (!headless || level?.Code != "VR04" || frames < 300)) - throw new ArgumentException("Jetpack smoke requires headless VR04 and at least300 frames"); + if (jetpackSmoke && (level?.Code != "VR04" || frames < 300)) + throw new ArgumentException("Jetpack smoke requires VR04 and at least300 frames"); if (walkSmoke && frames < 240) throw new ArgumentException("Walk smoke requires at least 240 frames."); var smoke = args.Contains("--smoke-window"); if (frames < 0 || (smoke && (headless || frames < 6))) @@ -413,6 +413,9 @@ internal static class Program double poseTime = initialPoseTime; var injectedInput = default(PlayerInput); var sawWalkKeys = 0; + var sawJetpackKeys = 0; + float poweredAirTravel = 0; + var poweredAirTurn = false; var sawPracticeDismiss = false; var sawPracticePause = false; double last = clock.Elapsed.TotalSeconds; @@ -426,11 +429,13 @@ internal static class Program } while (running) { - if (walkSmoke && !headless) + if ((walkSmoke || jetpackSmoke) && !headless) { - var requested = LabSimulation.SmokeInput(simulation!.Steps); + var requested = jetpackSmoke ? LabSimulation.JetpackSmokeInput(simulation!.Steps) + : LabSimulation.SmokeInput(simulation!.Steps); foreach (var (scancode, down, previous) in new[] { (82u, requested.Forward, injectedInput.Forward), + (81u, requested.Backward, injectedInput.Backward), (80u, requested.Left, injectedInput.Left), (79u, requested.Right, injectedInput.Right), (225u, requested.Jump, injectedInput.Jump) }) { if (down == previous) continue; @@ -461,6 +466,7 @@ internal static class Program { keys.Add(e.Scancode); if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == 225 ? 4 : 0; + if (jetpackSmoke) sawJetpackKeys |= e.Scancode == 82 ? 1 : e.Scancode == 81 ? 2 : e.Scancode == 80 ? 4 : e.Scancode == 225 ? 8 : 0; if (smoke && e.Scancode == 79) sawKey = true; if (e.Scancode is 41 or 44 && e.Repeat == 0 && director is { Controlled: false }) { sceneAudio?.StopSpeech(); director.Skip(); keys.Clear(); mouseJump = false; } @@ -504,18 +510,25 @@ internal static class Program var elapsed = now - last; var dt = (float)Math.Min(elapsed, 0.1); last = now; - if (simulation != null && !inspecting && !practice.Active && (active || headless || walkSmoke)) + if (simulation != null && !inspecting && !practice.Active && (active || headless || walkSmoke || jetpackSmoke)) { - var steps = headless || walkSmoke || practiceWindowSmoke ? 1 : stepClock.Advance(elapsed); + var steps = headless || walkSmoke || jetpackSmoke || practiceWindowSmoke ? 1 : stepClock.Advance(elapsed); for (var step = 0; step < steps; step++) { - var input = jetpackSmoke ? new PlayerInput(false, false, false, false, simulation.Steps < 180) + var input = jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps) : walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput( keys.Contains(82), keys.Contains(81), keys.Contains(80), keys.Contains(79), mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98)); if (director?.Controlled != false) { + var before = simulation.Position; + var powered = simulation.JetpackEffectVisible && !simulation.Grounded; simulation.Step(input); + if (jetpackSmoke && powered) + { + poweredAirTravel += Vector2.Distance(new(before.X, before.Z), new(simulation.Position.X, simulation.Position.Z)); + poweredAirTurn |= MathF.Abs(simulation.TurnRate) > 1; + } interactions?.UpdateEnergy(simulation.Energy); director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0)); director?.Touch(level!.Player!.Tag!, simulation.ActorRoot); @@ -590,7 +603,7 @@ internal static class Program if (!Sdl.SDL_PushEvent(ref key) || !Sdl.SDL_SetWindowSize(window, 800, 600)) throw new InvalidOperationException(Sdl.Error); } - if (walkSmoke && !headless && count == 1 && !Sdl.SDL_SetWindowSize(window, 800, 600)) + if ((walkSmoke || jetpackSmoke) && !headless && count == 1 && !Sdl.SDL_SetWindowSize(window, 800, 600)) throw new InvalidOperationException(Sdl.Error); if (smoke && count == 1) { @@ -603,7 +616,7 @@ internal static class Program if (!Sdl.SDL_PushEvent(ref cycle)) throw new InvalidOperationException(Sdl.Error); } } - if ((smoke || walkSmoke || practiceWindowSmoke) && renderer.Width == 800 && renderer.Height == 600) didResize = true; + if ((smoke || walkSmoke || jetpackSmoke || practiceWindowSmoke) && renderer.Width == 800 && renderer.Height == 600) didResize = true; if (frames > 0 && count >= frames) break; if (transitionRequest != null) break; } @@ -621,7 +634,10 @@ internal static class Program if (jetpackSmoke) { Console.WriteLine($"Powered jump: bursts={simulation!.Bursts}, remaining={simulation.JetpackRemaining:F3}, energy={simulation.Energy:F3}, grounded={simulation.Grounded}."); - if (simulation.Bursts == 0 || simulation.MaximumRise <= 137.62f || !simulation.Grounded) return 2; + Console.WriteLine($"Powered air steering: travel={poweredAirTravel:F2}, turned={poweredAirTurn}."); + if (!headless) Console.WriteLine($"Jetpack SDL keys received={sawJetpackKeys == 15}, resize800x600={didResize}."); + if (simulation.Bursts == 0 || simulation.MaximumRise <= 137.62f || !simulation.Grounded + || poweredAirTravel <= 20 || !poweredAirTurn || !headless && (sawJetpackKeys != 15 || !didResize)) return 2; } if (director != null) { diff --git a/tests/GamePort.MovementTests/Program.cs b/tests/GamePort.MovementTests/Program.cs index e2ba030..bb2c69c 100644 --- a/tests/GamePort.MovementTests/Program.cs +++ b/tests/GamePort.MovementTests/Program.cs @@ -15,7 +15,10 @@ var tests = new (string Name, Action Check)[] ("jump rises, falls and returns to support", JumpLanding), ("held zero-burn jump repeats and release stops repetition", HeldJump), ("airborne jump re-press rearms landing without a double jump", JumpRepress), - ("air mode ignores arrow steering", AirControl), + ("air input accelerates, brakes, turns and coasts at source limits", AirArithmetic), + ("ordinary jump responds to airborne arrows", AirControl), + ("powered jetpack starts moving and turns from stationary takeoff", JetpackControl), + ("powered steering remains independent of presentation rate", JetpackReplayRates), ("reset restores spawn, camera and counters", Reset), ("ten-minute simulation remains finite and supported", LongRun), ("original lab placement, floor, walking and jump checkpoint", () => OriginalLab(project, originals)), @@ -162,25 +165,93 @@ static void HeldJump() Check(simulation.Jumps == jumpCount + 1 && !simulation.Grounded, "new grounded press starts another jump"); } +static void AirArithmetic() +{ + var input = new PlayerInput(true, false, true, false, true); + var first = AirSteering.Step(0, 0, input, 1f / 60); + Near(first.Speed, 30, 0, "air forward adds source30 per invocation"); + Near(first.TurnRate, 100f / 60, .00001f, "air turn ramps by100*dt"); + var both = AirSteering.Step(0, 0, input with { Right = true }, 1f / 60); + Check(both == first, "Left wins over Right in air"); + var turn = 0f; + for (var i = 0; i < 90; i++) turn = AirSteering.Step(0, turn, input, 1f / 60).TurnRate; + Near(turn, 30, 0, "normal airborne turn limit30"); + for (var i = 0; i < 30; i++) turn = AirSteering.Step(0, turn, default, 1f / 60).TurnRate; + Near(turn, 0, 0, "released turn decays to0 without crossing"); + var coast = 600f; + for (var i = 0; i < 10; i++) coast = AirSteering.Step(coast, 0, default, 1f / 60).Speed; + Near(coast, 530, 0, "unpowered input coasts after half-decay crosses max*10/11"); + var braking = new PlayerInput(false, true, false, false, false); + for (var i = 0; i < 40; i++) coast = AirSteering.Step(coast, 0, braking, 1f / 60).Speed; + Near(coast, 0, 0, "Down brakes to0 without reversing"); + Near(AirSteering.Step(100, 0, input with { Backward = true }, 1f / 60).Speed, 112.5f, 0, + "air forward increment precedes Down braking"); + Near(AirSteering.Step(-10, 0, braking, 1f / 60).Speed, 0, 0, "negative takeoff speed brakes toward0"); + Throws(() => AirSteering.Step(0, 0, default, float.NaN)); +} + static void AirControl() { - var idleInput = FlatSimulation(); - var arrowInput = FlatSimulation(); + var simulation = FlatSimulation(); + simulation.Step(new(false, false, false, false, true)); + var origin = simulation.Position; for (var i = 0; i < 20; i++) { - idleInput.Step(new(true, false, false, false, false)); - arrowInput.Step(new(true, false, false, false, false)); + Check(!simulation.Grounded, "ordinary jump steering fixture stays in air"); + simulation.Step(new(true, false, true, false, false)); } - idleInput.Step(new(true, false, false, false, true)); - arrowInput.Step(new(true, false, false, false, true)); - for (var i = 0; i < 24; i++) + Check(simulation.Speed == 600 && simulation.Yaw > 5 && Vector2.Distance( + new(origin.X, origin.Z), new(simulation.Position.X, simulation.Position.Z)) > 75, + "airborne arrows must accelerate and turn an initially stationary jump"); +} + +static void JetpackControl() +{ + var straight = FlatSimulation(); + var left = FlatSimulation(); + var right = FlatSimulation(); + foreach (var simulation in new[] { straight, left, right }) { - Check(!idleInput.Grounded && !arrowInput.Grounded, "comparison remains airborne"); - idleInput.Step(default); - arrowInput.Step(new(true, true, true, true, false)); - SameState(arrowInput, idleInput, "ordinary arrows ignored while airborne"); + simulation.JetpackInventoryState = () => 1; + for (var i = 0; i < 40; i++) simulation.Step(new(false, false, false, false, true)); + Check(simulation.JetpackEffectVisible && !simulation.Grounded && simulation.Bursts == 1, + "stationary takeoff reaches an active powered burst before directional input"); + } + var initialHeight = left.Position.Y; + for (var i = 0; i < 60; i++) + { + straight.Step(new(true, false, false, false, true)); + left.Step(new(true, false, true, false, true)); + right.Step(new(true, false, false, true, true)); + Check(!left.Grounded && left.JetpackEffectVisible, "steering occurs during powered flight"); + } + Check(straight.Position.Z > 400 && left.Yaw > 20 && right.Yaw < -20, + "powered Up moves from rest and Left/Right turn while airborne"); + Check(left.Position.X < -50 && right.Position.X > 50 && left.Position.Y > initialHeight, + "powered paths change direction and retain vertical lift"); + var beforeBrake = left.Speed; + for (var i = 0; i < 40; i++) left.Step(new(false, true, false, false, true)); + Check(beforeBrake > 0 && left.Speed == 0 && left.TurnRate == 0 && !left.Grounded, + "Down brakes during active burst and released turn settles"); + left.Reset(); + Near(left.TurnRate, 0, 0, "reset clears accumulated airborne turn"); +} + +static void JetpackReplayRates() +{ + LabSimulation? reference = null; + foreach (var rate in new[] { 60, 120, 144 }) + { + var simulation = FlatSimulation(); + simulation.LevelCode = "VR04"; + var clock = new FixedStepClock(); + for (var frame = 0; frame < rate * 3; frame++) + for (var step = clock.Advance(1.0 / rate); step > 0; step--) + simulation.Step(new(simulation.Steps >= 40, false, simulation.Steps >= 80, false, true)); + Check(simulation.Bursts == 1 && simulation.Travel > 500, "render-rate replay exercises powered steering"); + if (reference != null) SameState(simulation, reference, "powered steering presentation rate"); + reference = simulation; } - Near(arrowInput.Speed, 600, 0, "takeoff speed retained in air"); } static void JumpRepress() @@ -287,6 +358,7 @@ static void SameState(LabSimulation actual, LabSimulation expected, string messa NearVector(actual.CameraEye, expected.CameraEye, .0001f, $"{message}: camera"); Near(actual.Yaw, expected.Yaw, .0001f, $"{message}: yaw"); Near(actual.Speed, expected.Speed, 0, $"{message}: speed"); + Near(actual.TurnRate, expected.TurnRate, 0, $"{message}: turn rate"); Check(actual.Grounded == expected.Grounded && actual.Pose == expected.Pose && actual.Jumps == expected.Jumps && actual.Landings == expected.Landings, $"{message}: movement state/counters"); } diff --git a/tests/test_air_steering.py b/tests/test_air_steering.py new file mode 100644 index 0000000..4bb078c --- /dev/null +++ b/tests/test_air_steering.py @@ -0,0 +1,40 @@ +"""Guard the actual original airborne dispatcher and keyboard arithmetic sites.""" +from pathlib import Path +import struct +import unittest + +EXE = Path(__file__).resolve().parents[2]/'Original/Neutron.exe' + + +class AirSteeringEvidence(unittest.TestCase): + def test_air_mode_falls_through_to_real_input_handler(self): + raw = EXE.read_bytes() + self.assertEqual(struct.unpack_from('<4I', raw, 0x38ba4), + (0x438b31, 0x438b60, 0x438b6d, 0x438b82)) + # Mode1 logs then continues at mode2's call site. It does not return. + self.assertEqual(raw[0x38b6a:0x38b76], bytes.fromhex('83c4048b4424108b17508bcf')) + self.assertEqual(raw[0x38b76:0x38b7c], bytes.fromhex('ff9228010000')) + self.assertEqual(struct.unpack_from('