From 62c07a3d59ca6d71a7456957d8586c268d27c439 Mon Sep 17 00:00:00 2001 From: Cristian Cerroni Date: Wed, 4 Nov 2026 18:06:09 -0500 Subject: [PATCH] Implement source-backed Scooter vehicle in tutorial and outside --- AGENTS.md | 25 +- README.md | 6 + docs/architecture.md | 10 + docs/checkpoint/coverage.md | 1 + docs/compatibility.md | 12 + docs/debug-menu.md | 7 + docs/decisions.md | 9 + docs/gameplay/gadget-assets.md | 9 + docs/gameplay/scooter-live.md | 169 ++ docs/gameplay/scooter.md | 5 +- docs/progress.md | 21 + docs/tasks.md | 10 +- scripts/package.sh | 7 + scripts/test.sh | 5 + src/GamePort/Application/DebugMenu.cs | 13 +- src/GamePort/Application/ScooterSmoke.cs | 75 + src/GamePort/Application/ScooterVisuals.cs | 73 + src/GamePort/Audio/SceneAudio.cs | 2 + src/GamePort/Audio/SdlAudio.cs | 7 + src/GamePort/Game/ActorPatrol.cs | 26 +- src/GamePort/Game/LabSimulation.cs | 16 +- src/GamePort/Game/OriginalBodyPhysics.cs | 8 +- src/GamePort/Game/OriginalCameraRay.cs | 2 +- src/GamePort/Game/OriginalStaticCollision.cs | 2 +- src/GamePort/Game/PlayerSceneBinding.cs | 63 +- src/GamePort/Game/SceneDirector.cs | 12 + src/GamePort/Game/SceneInteractions.cs | 6 +- src/GamePort/Game/Scooter.cs | 155 ++ src/GamePort/Game/ScooterCamera.cs | 25 + src/GamePort/Game/ScooterMotion.cs | 102 ++ src/GamePort/Game/ScooterWheels.cs | 65 + src/GamePort/Platform/Sdl.cs | 1 + src/GamePort/Program.cs | 93 +- tests/GamePort.DebugMenuTests/Program.cs | 3 +- .../GamePort.PatrolTests.csproj | 4 + .../GamePort.ScooterTests.csproj | 10 + tests/GamePort.ScooterTests/Program.cs | 155 ++ .../original-motion-reference.json | 1477 +++++++++++++++++ tests/test_scooter_motion.py | 45 + tests/test_scooter_resources.py | 173 +- tools/binary/scooter_motion.py | 46 + tools/binary/scooter_motion_probe.c | 143 ++ tools/extractors/prepare.py | 2 + tools/extractors/scooter_resources.py | 209 ++- 44 files changed, 3135 insertions(+), 174 deletions(-) create mode 100644 docs/gameplay/scooter-live.md create mode 100644 src/GamePort/Application/ScooterSmoke.cs create mode 100644 src/GamePort/Application/ScooterVisuals.cs create mode 100644 src/GamePort/Game/Scooter.cs create mode 100644 src/GamePort/Game/ScooterCamera.cs create mode 100644 src/GamePort/Game/ScooterMotion.cs create mode 100644 src/GamePort/Game/ScooterWheels.cs create mode 100644 tests/GamePort.ScooterTests/GamePort.ScooterTests.csproj create mode 100644 tests/GamePort.ScooterTests/Program.cs create mode 100644 tests/GamePort.ScooterTests/original-motion-reference.json create mode 100644 tests/test_scooter_motion.py create mode 100644 tools/binary/scooter_motion.py create mode 100644 tools/binary/scooter_motion_probe.c diff --git a/AGENTS.md b/AGENTS.md index fdccfca..4c3b5e1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,16 +46,19 @@ changes. Current gadget controls/resources/primary-fire findings belong in docs/gameplay/. Distinguish static recovery, implementation, port tests and original runtime evidence. Main owns integration/runtime; gadget investigators have exclusive named files, not shared directories. -Latest gadget continuation: docs/gameplay/grappler-live.md. BoundedVR08 is now -live: source body/shared sphere context, camera, exact rope/SWING/cursor/audio, -selection/companion/control cleanup, explicit RETURN and retained scalar memory. -113 original-component observations,13 managed live groups,40 Python checks and -9-phase native Linux SDL replay support it; validation enabled, zero errors. -Whole-original/native Windows comparison, general dynamic pairs, other levels -and arbitrary ordinary attached LOAD continuity remain open. Source/REA evidence -is under artifacts/grappler-{body,camera,assets}-live; all ownership is primary. -Next gadget candidate is Scooter; close source support/wheel/contact contracts -in scooter.md before vehicle implementation. Preserve parked collision gates. +Latest gadget continuation: docs/gameplay/scooter-live.md. Scooter is live in +VR05 and outsideLEV1 through normal owned tile/F1. Separate C3DJEEP body and four +real wheel supports, source drive/input/impact/default camera, exact source-pivot +art, pitch-controlled engine and summon/contact mount/cleanup/RETURN are integrated. +53 copied-original observations match managed formulas;10-phase headless/native +Linux replays pass in both scenes, zero validation errors. The32-row debug Player +page fits ultrawide. Whole-original/native Windows comparison, modes2..20, +mouse/analog, dynamic pairs and arbitrary retained LOAD/save remain open. Goddard +follow is an opt-in bounded adapter in these scenes. Source/REA artifacts are under +artifacts/scooter-*-live; all ownership is primary. Package evidence is in the live +report. Preserve parked Jimmy collision; Scooter's source callback is independent. +Grappler remains live boundedVR08; see docs/gameplay/grappler-live.md for113 +original-component observations,13 managed/40 Python checks and9-phase SDL replay. The user clarified orbit's remaining issue was inverted Left/Right; Left/A and Right/D azimuth mappings are corrected, Up/Down unchanged. Playable packages identify clean70cba65; native input/resize/validation passes. See docs/orbit-camera.md. @@ -74,7 +77,7 @@ package provenance and validation are recorded in the live report. Baseball continuation: docs/gameplay/baseball-implementation.md. Its20-slot pool, hold/release aiming, original TIME art and boundedVR07 moving targets are implemented; original dynamic pair discovery/other enemy consumers remain open. -Scooter recovery is saved in docs/gameplay/scooter.md; do not invent wheel supports. +Scooter historical recovery is docs/gameplay/scooter.md; live coverage is scooter-live.md. Bubble's mode2, original sprite and boundedVR01 source body/floor state are implemented and tested; Invisible, ray/jetpack and shared energy state remain integrated. Other gadgets diff --git a/README.md b/README.md index 9fc2ad9..0067780 100644 --- a/README.md +++ b/README.md @@ -248,3 +248,9 @@ The collision continuation adds a probed [source sphere kernel](docs/checkpoint/collision-response.md) and integrates the [overhead response](docs/checkpoint/ceiling-wrapper.md); full capsule replacement and [shared camera handoff](docs/checkpoint/camera-handoff.md) remain open. + +Scooter is implemented in VR05 and outside LEV1. Select its owned tile with +Tab/Space (or F1 → Player → Give/Select Scooter), then walk into the summoned +vehicle at Goddard. Up/primary fire accelerates, Left/Right steers, Down brakes +then reverses, jump jumps, Tab/Space unequips. F1 Give All Gadgets also grants +its normal tile. Source, verification and remaining limits: [Scooter](docs/gameplay/scooter-live.md). diff --git a/docs/architecture.md b/docs/architecture.md index acc2404..2661455 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,6 +5,16 @@ 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. +`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, +vehicle frame/passenger-copy, then wheel phase. OrdinaryBodyPhysics exposes the +wall callback before floor/friction so contact speed writes affect the same pass. +ScooterVisuals uses exact unit-scale body/wheels/rider morphs; SceneAudio maps +source engine frequency to SDL stream ratio. Goddard follow is opt-in for these +scenes. Scene-local lifetime, provisional moving doors and fixed cadence remain +explicit boundaries. See gameplay/scooter-live.md. + `BaseballGadget` keeps pending/saved/displayed aim, camera adjustments and20 owned `BaseballProjectile` entries distinct from equipped raw mode. Cleanup hides its UI/restores the companion but retains the latch and flying balls. `SceneBaseballs` diff --git a/docs/checkpoint/coverage.md b/docs/checkpoint/coverage.md index 8ec6e08..bc98b58 100644 --- a/docs/checkpoint/coverage.md +++ b/docs/checkpoint/coverage.md @@ -27,6 +27,7 @@ runtime comparison. Coverage does not mean implementation completeness. | INVENTORY | PostLoad common prefix enables eight owned gadgets4→1, then VR01..08 disables1→4; full tail re-enables the practice gadget. LV1B disables1/7; other wire values preserved. | Availability pass now applied at level entry and verified across TSK tutorial/return; snapshots preserve raw values. | S/M/R. Full selected-gadget/UI and other level tails remain incomplete; bounded route mode/hold/fire carry is implemented. | Keep availability separate from ownership, task changes and arbitrary state carry. | | SAVE | TSK45FEE0 writer /4603F0 reader; records, arrays, return strings, stored departure root; queued460E70→460EA0. | Original-format round-trip and CLI save, scene snapshots; no full source save UI/load lifecycle. | S/M. Source reader duplicates matching task callback then all-entity420 post-task hook; this is distinct from Jimmy placement PostLoad423A90. Current fresh-director path differs. | C7 after C1/C2; test repeated callbacks before adopting loader behavior. | | CHECKPOINT | Pickup42AF00 stores+1E38 root/+1E48 level separately from+9A8 RETURN root. | Capture exposed, not used for return; source capture consumers unknown. | S/M. Do not interpret as death/respawn until read consumer found. | Track unresolved consumer; no speculative gameplay. | +| SCOOTER |4211A0/412A90 owned vehicle/4 children;465220/465830 drive/input;467080 post-normal wheel support;421910 impact;4130A0 camera;4281B3 cleanup. | Now live VR05 and outsideLEV1, normal tile plus F1. Body→input/frame→rider-copy→wheel phases, exact unscaled resources, source camera/audio and RETURN. | S/P/M/R:53 isolated original observations, actual-level managed tests,10-phase native/headless replays. No complete original-game comparison. | Whole-original/native Windows comparison; shared global/pair state, retained LOAD/helper/save lifecycle and other levels remain bounded. See gameplay/scooter-live.md. | ## Interaction and ownership map diff --git a/docs/compatibility.md b/docs/compatibility.md index 5846cec..2a5bbc0 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -1,5 +1,17 @@ # Compatibility and validation +Scooter (2026-11-04): live in VR05 and outside LEV1 through normal owned gadget +selection and F1 grant.53 copied-original component observations match managed +math; actual-level tests cover mount, wheel/body phases, drive/jump, head-on +recovery, camera and cleanup/RETURN. Native Linux GTX1070/private Xvfb1920×1080 +passes both10-phase SDL input replays with zero enabled Vulkan validation errors. +A2560×1080 Player-page capture shows all32 rows including Scooter; inspected. +Headless replay passes both scenes. Source and final validation/package provenance +are in gameplay/scooter-live.md. Fixed cadence, Jimmy's outside capsule, provisional +NPC/dynamic door body, other levels and original/native Windows comparison remain +explicit limits. Historical gadget-only status below is retained chronologically. + + Compilation, native runtime, original behavior and full feature completion are separate evidence categories. **The game is not fully reconstructed/playable yet.** diff --git a/docs/debug-menu.md b/docs/debug-menu.md index dc9c75a..85620d6 100644 --- a/docs/debug-menu.md +++ b/docs/debug-menu.md @@ -26,6 +26,13 @@ by themselves. Debug tools do not imply reconstructed progression or full gamepl ## Player and Systems pages +**Give/Select Scooter** grants item4 and summons the live vehicle at Goddard in +VR05 or outside LEV1. Walk into it to mount; selecting alone leaves Jimmy free. +The normal owned gadget tile works outside too. Header diagnostics report +OFF/PARK/RIDE, speed and front/rear supported wheel counts. Tab/Space unequips; +F3/reset releases vehicle control and sound. The Player page remains32 rows. + + Player includes **Give All Gadgets**, which sets all eight gadget tiles to owned and available in the current scene. It preserves the equipped gadget and other inventory entries. Normal level-load availability rules still apply afterward. diff --git a/docs/decisions.md b/docs/decisions.md index dea5bca..313a7c9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -292,3 +292,12 @@ boundary. Preserve first geometry scale across reattach/reequip/load. Camera offsets are locals consumed by separate ground/air branches, not world poses. Exact SWING uses its own source-pivot draw. See gameplay/grappler-live.md. + +46. **Scooter owns a vehicle body and real wheel supports.** Normal item4 selection + summons at Goddard; strict later contact mounts. Keep scalar/live velocity/ + pending impulse and body/input/frame/wheel phases distinct. Enable bounded + VR05 and outsideLEV1 from the normal owned tile. Use source body150/.2, + four narrow wheel offsets, explicit prevent-lowering/bounce overrides, + face-only camera clip and exact unscaled art. Preserve parked Jimmy collision. + Native component comparison, managed integration and port rendering establish + separate coverage; no complete original/Windows parity is inferred. diff --git a/docs/gameplay/gadget-assets.md b/docs/gameplay/gadget-assets.md index 640fab6..0cf816f 100644 --- a/docs/gameplay/gadget-assets.md +++ b/docs/gameplay/gadget-assets.md @@ -133,3 +133,12 @@ range, timing, energy and interruption policy. The selection3 naming overlap is an explicit reason to implement the combined shrink/jetpack controls coherently. Other gadget assets are candidates for later behavior recovery, not evidence that all eight gadget behaviors are currently implemented. + +2026-11-04 Scooter continuation: export_scooter now prepares exact OMT shape0/1, +Canv0/1 pixels and HISCOOT/HISCOOTSTOP rider morphs, with source aliases and PE +spans in its manifest. Runtime body/wheels/rider preserve source pivots/unit scale; +null-material wheel faces remain undrawn. The Goddard HISCOOT alias is separately +recovered and is not substituted for the active Jeep mesh. Eight resource groups +check exact geometry/UVs/normals/materials/radii/pixels, morph samples/topology, +binding instructions, determinism, identity and output isolation. Live status and +remaining render/lifetime limits: [scooter-live.md](scooter-live.md). diff --git a/docs/gameplay/scooter-live.md b/docs/gameplay/scooter-live.md new file mode 100644 index 0000000..543c0f5 --- /dev/null +++ b/docs/gameplay/scooter-live.md @@ -0,0 +1,169 @@ +# Live Scooter: VR05 and outside LEV1 + +2026-11-04. Supersedes the deferred status in [scooter.md](scooter.md). +The user requested normal outside use after the vehicle implementation. Item4 +now summons an independent C3DJEEP at Goddard; walking into it mounts Jimmy. +An owned tile in the normal Tab/Space gadget panel works in both scenes. F1 → +Player → Give/Select Scooter supplies the same selection path. Up/primary fire +accelerates, Left/Right steers, Down brakes then reverses, jump queues a supported +jump, and Tab/Space unequips. There is no invented equip-energy requirement. +Other scenes retain the tile/Practice flow without enabling an unsupported body. + +## Source and evidence + +Authoritative EXE SHA256: +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +Original files remain untouched. The friend's source supplied leads; binary and +resource checks against this project's originals determine the contracts. +`scooter.py` retains17 spans/13 virtual bindings/10 constants; `scooter_motion.py` +adds20 bounded ranges, PE offsets, hashes and relocation operands. The committed +`tests/GamePort.ScooterTests/original-motion-reference.json` identifies source, +probe generator, generated executable and Wine log, with53 observations. Code +addresses below have file offset VA−400000, independently checked by PE mapping. + +| Original VA / file offset | Caller, owner and recovered contract | +|---|---| +|4211A0 /211A0;464B90 /64B90|Jimmy Init423CE8 lazily constructs6AC-byte Jeep, stored Jimmy+A30. Complete vtable4A2F8C, game+C0 vtable4A2AEC. Radius150, support factor.2, friction.9, suppression1. Explicit464C75 sets prevent-lowering true;464C7D disables bounce.| +|4290B7 /290B7|Selection requires enabled Goddard, copies his root/Euler into vehicle, enables/shows vehicle, disables/hides companion. Selecting alone does not mount.| +|47B3E0 /7B3E0;47A430 /7A430;422F13 /22F13|Strict quick-magnitude sphere contact invokes Jimmy's interaction dispatcher422D30, identifies C3DJEEP, calls complete1E0→425120, transfers raw owner5099E4, sets rider69C, selects SCOOT.425120 only cancels mode1 jump/effect when eligible.| +|412A90 /12A90;468020 /68020|Construct four wheel children, first4 of6 pointer slots578..58C. Local positions (−3,1,73),(3,1,73),(−3,1,−30),(3,1,−30). Mutual wheel/vehicle/passenger exclusions. Wheels have no independent integration/gravity; support queries are manual.| +|465830 /65830;421C10 /21C10|Keyboard steering±200dt, cap45, Left precedence; return-to-zero latch. Rear support required for throttle/reverse. Accel700, brake1200, maximum1485, reverse−594. Down's first edge brakes; held reverse additionally waits through the source one-second timer branch. No sprint predicate.| +|465220 /65220|Counts prior child supports, applies yaw only with front contacts/horizontal motion, coasting/steer/slope terms, then full-velocity/forward mixing only with parent support and≥2 child supports. Direction sum is intentionally not renormalized. Scalar, velocity and pending impulse are distinct state.| +|421910 /21910;467000 /67000;4669F0 /669F0|Head-on contact with horizontal quick speed>20 and abs(forward·normal)≥.9 starts impact: speed/acceleration0. No bounce reflection. Four-second enabled-body state damps horizontal velocity/angular velocity, then clears them. Glancing positive-speed throttle applies source minimum230, even if it raises a slow scalar.| +|473770 /73770;412F90 /12F90;467080 /67080|Post-normal registry phase sets roll=−steering/2, manually queries each wheel's real support, clamps local suspension±15, spins from horizontal travel/radius, then synchronizes visuals. Radius23.769514 from OMT shape1 header. Wheels do not fabricate support from the parent.| +|476FF0 /76FF0;466AF0 /66AF0;473320 /73320|Stored support normal→signed14-bit angle components→yaw-rotated pitch/roll. The target yaw is overwritten with live yaw. Source full AddEuler normalizes all axes during drive. Facing uses shortest delta, rate*dt and strict small-step snap. No contacts selects pitch340/rate2; unmounted sets rate10.| +|421580 /21580|Mounted jump latch queues Y700; float pose clock strictly exceeds double.3 before selecting SCOOTSTOP for signed speed<10, otherwise SCOOT. Jimmy copies root/Euler before the later wheel/lean phase.| +|4130A0 /130A0|Default mode1 eye uses rotated(−30,0,−200)+worldY50, quick-distance gains1/1.7/2.8, smoothing before clipping, new-eye quantized aim toward rotated(0,50,100). Impact retains eyeY, approaches rootXZ at.3dt and aims at root.413870 explicitly passes edges=false.| +|413852 /13852;47B4B0 /7B4B0|Camera resets nearest face distance130000 only, inherits edge/contact state, clips from vehicle root with cube75's sphere radius64.9519043. Ordinary body initializes its own sphere context; no invented camera sweep.| +|412ED0 /12ED0|Enabled/visible vehicle starts loop SFX46 and retains base sample frequency. Pitch=max(7000,trunc(base+signedSpeed*(1/1.9)*51)). Parked vehicle also sounds; cleanup stops it.| +|4281B3 /281B3;457FF7 /57FF7|Selected cleanup restores eligible Goddard at vehicle root/Euler, disables/hides vehicle, stops engine. Mounted branch restores Jimmy raw control, raises root40, clears acceleration/live velocity, preserves movement mode/pending impulse. RETURN explicitly invokes cleanup before requesting transition.| + +Vehicle complete offsets:600/602/604 front/rear/total support WORDs;610/618/620/ +628 acceleration/brake/base/current maximum;61C prior scalar;63C angle;640 yaw +rate;648 brake timer;64C impact timer;650/654 camera modes;658/659 throttle/brake; +65C impact;65D/65F keyboard/reverse latch;690/694 engine channel/base frequency; +698 jump latch;69C rider;6A0 pose clock. Full source structures remain partial. + +REA/Ghidra12.1.4 evidence is retained under artifacts/scooter-{wheels,assets, +lifecycle,motion}-live, including complete replies, exports and closed snapshots. +Important Evidence IDs: + +-465220 `ev_09ecf350c8705d5f9c1da5b444eb8cd027f64f4859713b29c9d04bc4c55c2bc8`; + 465830 `ev_dbb6ac283387e14f08d527a750c14af44c52ed80c612c40393a5434a16589916`. +-467080 `ev_3e6bc2c29886888f3d70087b38b7a8b933d70394908f0328e1a3032a39cd9077`; + 468020 `ev_2bbed17bcf63926b0ed8202ebf6d7320bf49ddb5bc4427a541c2bff4e448e84b`; + 4682A0 `ev_f083ee63317f9d4d999b16da31c770e0f5c0517caebf73ba53e8769bc4ee7699`. +-4213F0 `ev_4ef0cec31d2f339f8e10213acabaa71f0fee3f7c6c96f278f691947616dbaa22`; + 422AC0 `ev_a689f8970de2072f0e2b18babfa9f20c9aa9824a37acdb76c158218d4b85d992`; + 477550 `ev_d44b004b6fe8045d4f9592712cda51bcb3cfb331d58980493bd7ced707d68150`. +-476FF0 `ev_9d38be2acca1063e7d91783adc0e928f9f9128cfb9031e258eaa51e94f0adfa1`; + 467990 `ev_c4db605fd549572edcee03e01e5c0026ba856ad5ad0016678fd1ca2902e5610b`. + +Some selectors, including4130A0/422D30/466AF0, were not recognized as complete +procedures. Saved instructions and callers fill those bounded gaps; no successful +decompilation is attributed to them. x87 aliases in465220/476FF0 are unreliable; +assembly plus copied-original numeric execution resolves arithmetic. No unchanged +failed selector was retried. Profile identity and exact metadata remain in the +saved REA bundles. + +## Implementation and ownership + +`Scooter` owns vehicle body, previous wheel contacts, input latches, impact/pose +clocks and shared-camera history. `ScooterMotion`, `ScooterWheels` and +`ScooterCamera` isolate the recovered formulas. `PlayerSceneBinding` steps body +before input, tests contact after Jimmy's independent physics, transfers ownership, +steps vehicle frame, copies passenger transform, then steps wheel phase. Fresh/ +retained input order follows the existing player registration-order switch. +Raw control loss alone does not teardown; named-Jimmy CAM/MCA/RETURN cleanup does. +`SceneInteractions` accepts vehicle-owned pickups and coincident Jimmy LOAD, with +separate radii150/60. Excluded wheel/passenger pair callbacks are not dispatched. +General dynamic pair discovery remains unimplemented. Provisional moving-door +response is an explicitly inherited modern adapter. + +Source PostLoad41E0F9 places active-follow Goddard250 behind Jimmy when a ray is +clear; retained STRT placement4239EC and RETURN423AE3 remain separate source paths. +The port creates the owned companion in VR05/LEV1 before runtime bindings and uses +behind250 or STRT fallback. Its opt-in state4 follow subset uses408E40/408BC0 +velocity/arrival hysteresis and41E303 speed450/600 plus far warp1500→behind800. +It retains the existing provisional NPC body and heading/animation bridge; this +is not full Goddard AI. Lab patrol behavior is unchanged. Modern R reset releases +selection, clears vehicle state and restores the companion near the start. F3 +releases it before noclip. Modern scene teardown disposes the engine before audio. +Vehicle/wheel allocation is scene-local; arbitrary non-RETURN persistence and +full retained-source reconstruction are unresolved, not silently claimed exact. + +`ScooterVisuals` uses source-pivot, unit-scale scooter.omt shape0 and four shape1 +wheels. Null-material faces remain undrawn (DLL1003756C), rather than invented +white caps. Exact original canvases are exported. HISCOOT and HISCOOTSTOP bind +jimscooter/Jimscooterstop morphs, with jimstop topology and original opaque Jimmy +atlas; the rider uses the Euler copied before wheel lean. godscooter.ASE is a +separate Goddard transformation resource, not the active vehicle shape.421535→ +477550 makes the source shape unlit; there is no impact scale change. + +## Verification and unresolved questions + +-53 copied-original Wine32 component observations match managed formulas:22 drive, + 9 input,8 normal→Euler (unused output yaw excluded),3 facing,7 wall and4 impact. + Harness supplies synthetic base actor/camera/audio/wheel support and original + OMT vector/trig. It never runs the original game entrypoint. Source quarter-turn + table sin=1/cos=0 is observed, explaining exact cardinal terrain endpoints. +-11 managed integration groups use real VR05/LEV1 data: ordinary outside tile, + summon/contact mount, body/wheels, drive/steer/brake/jump/no energy debit, + actual front-door wall and four-second recovery, default/impact camera math, + dismount40/companion/audio, named cleanup/noclip/reset, actual RETURN and visual + repeat/hide, plus follow/freeze/warp/reset of the companion. Front-door +Z driving hits the house steps, correctly entering impact. +-The original OMT cube probe observed75→bounds±37.5/radius64.9519043 with false + flag before a later unrelated true-flag call faulted. That diagnostic run was + not a clean complete camera probe; full camera execution is not claimed. +-Source guards and exact-resource exporter checks run through scripts/test.sh. + Runtime replay/build/package results are recorded below after verification. + +Remaining: original whole-game comparison and native Windows play; mouse/analog +input and camera modes2..20; special cutscene camera helpers; scene-wide shared +collision globals including Jimmy/vehicle/other body ordering; general dynamic +pairs, mission/hazard callbacks and other levels; exact Goddard body/animation; +full retained vehicle/wheel/helper lifetime and save/load; render/cadence/pivot +parity. Jimmy's lab/outside capsule remains parked; Scooter uses its independent +source static body and does not bypass special Jimmy policies. Fixed60Hz and +modern wide UI are explicit port policies. Dummy audio verifies transport and +lifecycle, not speakers or audible pitch quality. + +## Port replay evidence + +Headless llvmpipe1280×720 and native Linux GTX1070/private Xvfb1920×1080 +pass10 render phases in both VR05 and LEV1: summon, contact mount, drive, steer, +brake/jump, dismount, remount, named cleanup, noclip and reset. All seven injected +SDL keys are received; Vulkan validation is enabled with zero errors. The outside +replay explicitly uses authored school1 and turns away from obstacles; front-door +head-on behavior is covered separately by the actual-geometry managed test. +248 extra player/vehicle/interactions/director ticks reuse received input, without +root/speed/timer seeding. Companion/patrol and HUD clocks are not included in those +extra fixture ticks; this is not a source cadence or manual tutorial-completion +claim. Final native R exercises the real reset command; the headless fixture calls +the bounded reset helpers directly. Logs: artifacts/scooter-{vr05,outside}{,-window}.log; +stage captures share those prefixes. Images were inspected, including source +rider/body/wheels and the full32-row2560×1080 Player page. + +From GamePort, `source scripts/env.sh`, then: + +``` +dotnet run --project tests/GamePort.ScooterTests +dotnet run -- --scene artifacts/extracted/VR05/scene.json --level gam/VR05.gam \ + --smoke-scooter --headless --screenshot artifacts/scooter-check.ppm +dotnet run --no-build -- --scene artifacts/extracted/level1/scene.json \ + --level gam/level1.gam --start school1 --smoke-scooter --headless +``` + +For native SDL replay omit --headless and add `--width 1920 --height 1080`. Set SDL_AUDIODRIVER=dummy only when hardware output is +unavailable. The audio replay executes SDL frequency-ratio calls and cleanup; +audible behavior and native Windows playback remain unverified. + +Final regression: scripts/test.sh exits0 (artifacts/scooter-final-tests.log):303 +Python tests plus2 separate HUD checks, all managed suites,36 main GPU completions +with zero enabled Vulkan validation errors,17 material readback checks, route/ +checkpoint/transition/animation and SDL dummy audio checks. All539 originals +verify unchanged. The later companion-active guard and first-engine-frame frequency +ordering were verified by the final11-group Scooter and10-group Patrol runs; +source guards and final .NET10 build pass. The build retains the existing NU1900 +unavailable vulnerability-metadata warning; there are no compilation errors. +Native Windows runtime and original whole-game comparison are still pending. diff --git a/docs/gameplay/scooter.md b/docs/gameplay/scooter.md index 8a1eefa..8562fd4 100644 --- a/docs/gameplay/scooter.md +++ b/docs/gameplay/scooter.md @@ -1,4 +1,7 @@ -# Scooter: separate vehicle and deferred implementation +# Scooter: original static checkpoint (historical) + +Current implementation and corrected contracts: [scooter-live.md](scooter-live.md). +The following records the earlier evidence boundary. 2026-11-02. Static source recovery only; **no live Scooter implementation or original gameplay verification**. User parked broad collision. Scooter cannot diff --git a/docs/progress.md b/docs/progress.md index 9279859..7315821 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -1,5 +1,26 @@ # Progress — 2026-11-04 +## Live Scooter in VR05 and outside LEV1 + +Implemented independent vehicle/wheel bodies, summon-at-Goddard and strict contact +mount, normal owned-tile outside selection, drive/steer/brake/reverse/jump, +impact/recovery, rider poses, default/impact camera, engine pitch and atomic +cleanup/RETURN. Exact body/wheels/rider resources use source pivots and unit scale. +F1 grants/selects Scooter and shows mount/speed/wheel state; the32-row Player page +fits native2560×1080. Goddard has an opt-in bounded follow subset in these scenes. + +53 copied-original component observations match managed formulas. Both headless +and native Linux1920×1080 replays pass10 phases with real SDL input and zero +Vulkan validation errors. Actual front-door head-on contact/recovery is a separate +managed test: it correctly blocks throttle for four seconds. Camera source413870 +passes edges=false, correcting an initial mismatch. Source/REA ledger, coverage, +port boundaries and remaining work: [scooter-live.md](gameplay/scooter-live.md). +Full scripts/test.sh passes303 Python+2 HUD/all managed suites and36 main GPU +completions, with zero validation errors. Final11 Scooter/10 Patrol groups and +539 original hashes pass. Package provenance follows in the live report. +Original whole-game and native Windows comparison remain pending; Jimmy's +lab/outside capsule and parked broad collision work are preserved. + ## Live VR08 Grappler Integrated shared body/sphere contact state, full bounded base callbacks, recovered diff --git a/docs/tasks.md b/docs/tasks.md index dcc05fa..4d6a72b 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -52,8 +52,14 @@ compile, runtime and original-fidelity verification are separate. Linux SDL replay pass. See gameplay/grappler-live.md for evidence and limits. - [ ] Native Windows and whole-originalVR08 comparison; shared dynamic pairs, special policies/other levels and non-RETURN attachment continuity remain open. -- [ ] Next gadget: Scooter source wheel/support/contact contracts before live - implementation. Preserve parked general collision continuation. +- [x] Scooter source wheel/support/contact recovery and bounded live VR05/LEV1: + separate vehicle, real4-wheel supports, normal owned-tile outside use, source + drive/impact/camera/pose/audio, summon/contact mount/cleanup and RETURN.53 native + component observations, managed integration and10-phase Linux SDL replays pass. + See gameplay/scooter-live.md; preserve parked general collision continuation. +- [ ] Scooter whole-original/native Windows comparison; mouse/analog/camera + modes2..20, special mission helpers, general dynamic pairs and retained LOAD/ + save lifecycle remain open. Other levels require evidence before enabling. Historical Grappler gates below were closed for boundedVR08 by this checkpoint; component reports remain evidence, not current live status. diff --git a/scripts/package.sh b/scripts/package.sh index 249704a..89e2bb0 100755 --- a/scripts/package.sh +++ b/scripts/package.sh @@ -25,6 +25,8 @@ for rid in linux-x64 win-x64; do cp -a artifacts/extracted/rocketship/. "$out/scenes/rocketship/" mkdir -p "$out/scenes/grappler" cp -a artifacts/extracted/grappler/. "$out/scenes/grappler/" + mkdir -p "$out/scenes/scooter" + cp -a artifacts/extracted/scooter/. "$out/scenes/scooter/" mkdir -p "$out/scenes/effects" cp -a artifacts/extracted/effects/. "$out/scenes/effects/" cp artifacts/extracted/scene-catalog.json "$out/scenes/scene-catalog.json" @@ -66,6 +68,11 @@ F1 -> Player -> Give/Select Grappler equips it in VR08. Its Practice tile opens that tutorial. Aim at a surface until the target appears; hold Enter/Ctrl/left mouse to attach/reel, arrows steer, release fire and jump to detach. Tab/Space unequips. Grappler is currently limited to VR08. +Scooter works normally in VR05 and outside: select its owned gadget tile or +F1/Player Give/Select Scooter, then walk into it at Goddard to mount. Up/primary +fire accelerates, Left/Right steers, Down brakes then reverses, jump jumps. +Tab/Space unequips, restores Goddard and stops the engine. Give All Gadgets grants +the normal tile too. See docs/gameplay/scooter-live.md for source and limits. Player/Systems add input ordering, jetpack availability, objective/practice, camera obstruction, audio category mutes and debug checkpoint save/load. Checkpoints save level/start/progression, not live position; see docs/debug-menu.md. diff --git a/scripts/test.sh b/scripts/test.sh index dd7e2c6..aeb7278 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -22,6 +22,7 @@ dotnet run --project tests/GamePort.BaseballVisualTests dotnet run --project tests/GamePort.RocketFlightTests dotnet run --project tests/GamePort.RocketshipTests dotnet run --project tests/GamePort.GrapplerLiveTests +dotnet run --project tests/GamePort.ScooterTests dotnet run --project tests/GamePort.GrapplerTests dotnet run --project tests/GamePort.HeadingTests dotnet run --project tests/GamePort.BlendTests @@ -68,6 +69,8 @@ dotnet run --no-build -- --headless --scene artifacts/extracted/VR01/scene.json dotnet run --no-build -- --headless --scene artifacts/extracted/VR07/scene.json --level gam/VR07.gam --smoke-baseball --screenshot artifacts/test-baseball.ppm dotnet run --no-build -- --headless --scene artifacts/extracted/VR08/scene.json --level gam/VR08.gam --smoke-grappler --screenshot artifacts/test-grappler.ppm dotnet run --no-build -- --headless --scene artifacts/extracted/VR02/scene.json --level gam/VR02.gam --smoke-rocketship --screenshot artifacts/test-rocketship.ppm +dotnet run --no-build -- --headless --scene artifacts/extracted/VR05/scene.json --level gam/VR05.gam --smoke-scooter --screenshot artifacts/test-scooter-vr05.ppm +dotnet run --no-build -- --headless --scene artifacts/extracted/level1/scene.json --level gam/level1.gam --start school1 --smoke-scooter --screenshot artifacts/test-scooter-outside.ppm dotnet run --no-build -- --headless --skip-intro --write-save artifacts/test-checkpoint.tsk dotnet run --no-build -- --headless --load-save artifacts/test-checkpoint.tsk --skip-intro dotnet run --no-build -- --headless --story --scene artifacts/extracted/VR01/scene.json --level gam/VR01.gam --smoke-transition --skip-intro @@ -84,6 +87,8 @@ 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/VR05/scene.json --level gam/VR05.gam --smoke-scooter --width 1920 --height 1080 --screenshot artifacts/test-scooter-vr05-window.ppm + dotnet run --no-build -- --scene artifacts/extracted/level1/scene.json --level gam/level1.gam --start school1 --smoke-scooter --width 1920 --height 1080 --screenshot artifacts/test-scooter-outside-window.ppm dotnet run --no-build -- --scene artifacts/extracted/VR08/scene.json --level gam/VR08.gam --smoke-grappler --width 1920 --height 1080 --screenshot artifacts/test-grappler-window.ppm dotnet run --no-build -- --scene artifacts/extracted/VR02/scene.json --level gam/VR02.gam --smoke-rocketship --width 1920 --height 1080 --screenshot artifacts/test-rocketship-window.ppm dotnet run --no-build -- --scene artifacts/extracted/VR07/scene.json --level gam/VR07.gam --smoke-baseball --width 1920 --height 1080 --screenshot artifacts/test-baseball-window.ppm diff --git a/src/GamePort/Application/DebugMenu.cs b/src/GamePort/Application/DebugMenu.cs index 03abcfd..5f7a164 100644 --- a/src/GamePort/Application/DebugMenu.cs +++ b/src/GamePort/Application/DebugMenu.cs @@ -8,7 +8,7 @@ public sealed record DebugScene(string LevelFile, string Code, string[] Starts); public enum DebugAction { None, Resume, Camera, SkipCutscene, RefillEnergy, GiveJetpack, ApplySceneTask, LoadScene, Reset, ForceControl, ToggleOverlay, Noclip, NoclipSpeed, StopMotion, ShowObjective, ReturnNoclipEntry, LevelAvailability, InputOrder, ApplyJetpackState, CameraObstruction, MuteMusic, MuteSpeech, MuteEffects, RestartMusic, StopEffects, SaveCheckpoint, LoadCheckpoint, Practice, - GiveInvisible, UnequipGadget, GiveBubble, GiveBaseball, GiveAllGadgets, GiveRocketship, GiveGrappler } + GiveInvisible, UnequipGadget, GiveBubble, GiveBaseball, GiveAllGadgets, GiveRocketship, GiveGrappler, GiveScooter } public sealed record DebugMenuView(string[] Lines, int SelectedLine); public sealed record DebugStatus(string Level, string Start, Vector3 Root, float Yaw, float Speed, bool Grounded, float Energy, int Score, int SceneTask, string Cutscene, bool Controlled, @@ -31,6 +31,7 @@ public sealed record DebugSystems public bool Targetable { get; init; } = true; public string BubblePhase { get; init; } = "OFF"; public string BaseballState { get; init; } = "OFF"; + public string? ScooterState { get; init; } public string? GrapplerState { get; init; } public string? RocketshipState { get; init; } public float BodyRadius { get; init; } = 60; @@ -58,7 +59,7 @@ public sealed class DebugMenu public const int ItemCount = 12; public const int PageCount = 3; public int Page { get; private set; } - public int PageItems => Page switch { 1 => 17, 2 => 9, _ => ItemCount }; + public int PageItems => Page switch { 1 => 18, 2 => 9, _ => ItemCount }; private static readonly float[] FlySpeeds = [300, 600, 1200, 2400]; private int flySpeedIndex = 1, jetpackStateIndex = 1; private static readonly int[] JetpackStates = [0, 1, 4]; @@ -122,7 +123,7 @@ public sealed class DebugMenu 5 => DebugAction.LevelAvailability, 6 => DebugAction.InputOrder, 8 => DebugAction.ApplyJetpackState, 9 => DebugAction.RefillEnergy, 10 => DebugAction.GiveInvisible, 11 => DebugAction.UnequipGadget, 12 => DebugAction.GiveBubble, - 13 => DebugAction.GiveBaseball, 14 => DebugAction.GiveAllGadgets,15=>DebugAction.GiveRocketship,16=>DebugAction.GiveGrappler, _ => DebugAction.None + 13 => DebugAction.GiveBaseball, 14 => DebugAction.GiveAllGadgets,15=>DebugAction.GiveRocketship,16=>DebugAction.GiveGrappler,17=>DebugAction.GiveScooter, _ => DebugAction.None }; if (Page == 2) return Selected switch { @@ -162,7 +163,7 @@ public sealed class DebugMenu $"OBJECTIVE {system.Objective} TIME {F(system.ObjectiveTime)} GADGET STATE {system.JetpackAvailability}", $"INVISIBLE {F(system.InvisibleRemaining)} RECHARGE {F(system.InvisibleRecharge)}/7 TARGETABLE {system.Targetable}", $"BUBBLE {system.BubblePhase} BODY R {F(system.BodyRadius)} FACTOR {system.BodyFactor.ToString("0.000",c)}", - system.GrapplerState is{} grapple?$"GRAPPLER {grapple}":system.RocketshipState is{} rocket?$"ROCKET {rocket}":$"BASEBALL {system.BaseballState}"]; + system.ScooterState is{} scooter?$"SCOOTER {scooter}":system.GrapplerState is{} grapple?$"GRAPPLER {grapple}":system.RocketshipState is{} rocket?$"ROCKET {rocket}":$"BASEBALL {system.BaseballState}"]; string[] items = Page == 1 ? [ $"NOCLIP (F3): {system.Noclip} (ENTER TOGGLE)", $"FLY SPEED: {F(FlySpeed)} LIVE {F(system.NoclipSpeed)} (ENTER APPLIES)", "STOP MOTION / CLEAR QUEUED JUMP", "SHOW CURRENT OBJECTIVE", @@ -170,13 +171,13 @@ public sealed class DebugMenu $"INPUT AFTER PLAYER: {system.InputAfterPlayer} (TOGGLE)", $"JET PACK STATE: {JetpackState} (0 NONE / 1 OWNED / 4 DISABLED)", "APPLY JET PACK STATE", "REFILL ENERGY TO 100", "GIVE / SELECT INVISIBLE", "UNEQUIP CURRENT GADGET", "GIVE / SELECT BUBBLE", "GIVE / SELECT BASEBALL", - "GIVE ALL GADGETS", "GIVE / SELECT ROCKETSHIP (VR02)", "GIVE / SELECT GRAPPLER (VR08)"] : [ + "GIVE ALL GADGETS", "GIVE / SELECT ROCKETSHIP (VR02)", "GIVE / SELECT GRAPPLER (VR08)", "GIVE / SELECT SCOOTER (VR05 / OUTSIDE)"] : [ $"STATIC CAMERA OBSTRUCTION: {(system.CameraObstruction?.ToString() ?? "UNAVAILABLE")}", $"MUTE MUSIC: {system.MusicMuted}", $"MUTE SPEECH: {system.SpeechMuted}", $"MUTE EFFECTS: {system.EffectsMuted}", "RESTART SELECTED MUSIC", "STOP ALL EFFECTS / LOOPS", "SAVE DEBUG CHECKPOINT", "LOAD DEBUG CHECKPOINT", "SHOW JET PACK PRACTICE PROMPT"]; return new([.. header, .. items, "TAB NEXT PAGE UP/DOWN SELECT ENTER APPLY", Page == 1 ? "FLY: WASD/ARROWS SPACE/E UP CTRL/Q DOWN SHIFT FAST" : "CHECKPOINT: DEBUG-CHECKPOINT.TSK BESIDE EXECUTABLE", - "F1 / ESC CLOSE - ACTIONS USE EXISTING SYSTEMS", Message], header.Length + Selected); + Message], header.Length + Selected); } return new([ "NEUTRON DEBUG MENU - F1", diff --git a/src/GamePort/Application/ScooterSmoke.cs b/src/GamePort/Application/ScooterSmoke.cs new file mode 100644 index 0000000..4cc0890 --- /dev/null +++ b/src/GamePort/Application/ScooterSmoke.cs @@ -0,0 +1,75 @@ +using System.Numerics; +using GamePort.Game; +namespace GamePort.Application; +/// Ordinary input replay at the authored tutorial/outside start. Extra +/// body/input/frame ticks reuse received input; no root, speed or timer seeding. +public sealed class ScooterSmoke +{ + private readonly LabSimulation player; + private readonly PlayerSceneBinding binding; + private readonly SceneDirector director; + private readonly SceneInteractions interactions; + private readonly Scooter scooter; + private readonly string level; + private readonly bool[] checks=new bool[10]; + private PlayerInput last;private Vector3 mountedRoot;private float yaw,speed;private int extra; + public ScooterSmoke(LabSimulation p,PlayerSceneBinding b,SceneDirector d,SceneInteractions i,string level) + {player=p;binding=b;director=d;interactions=i;scooter=b.Scooter!;this.level=level;i.Inventory.SetState(0,4,1);i.Inventory.SelectGadget(4);} + public void BeforeFrame(int frame,Action key,bool headless) + { + if(frame==0&&!headless)key(81,true); + if(frame==1) + { + for(int i=0;i<120&&!scooter.Mounted;i++)Advance(1); + if(!headless){key(81,false);key(82,true);if(level=="LEV1")key(80,true);}mountedRoot=scooter.Root; + } + if(frame==2){Advance(90);yaw=scooter.Rotation.Y;if(!headless)key(80,true);} + if(frame==3){Advance(15);speed=scooter.Steering.Speed;if(!headless){key(82,false);key(80,false);key(81,true);}} + if(frame==4) + { + Advance(12);for(int i=0;i<120&&!scooter.Supported;i++)Advance(1); + if(!headless){key(81,false);key(225,true);} + } + if(frame==5){Advance(120);if(headless)interactions.Inventory.SelectGadget(-1);else{key(225,false);key(43,true);}} + if(frame==6){if(!headless)key(43,false);interactions.Inventory.SelectGadget(4);} + if(frame==7){if(level=="VR05")director.Trigger("scooter");else director.ReleasePlayerGadget();} + if(frame==8) + { + director.Skip();interactions.Inventory.SelectGadget(4); + if(headless)player.SetNoclip(true);else key(60,true); + } + if(frame==9) + { + if(headless){binding.ResetVehicle();player.Reset();} + else {key(60,false);key(21,true);} + } + } + public void Received(PlayerInput input)=>last=input; + private void Advance(int ticks) + { + for(int i=0;i100&&scooter.Steering.Speed>100; + if(frame==3)checks[3]=scooter.Rotation.Y!=yaw&&scooter.Steering.Angle>0; + if(frame==4)checks[4]=scooter.Steering.Speed0; + if(frame==5)checks[5]=!scooter.Spawned&&!scooter.Mounted&&!scooter.EnginePlaying&&director.Controlled; + if(frame==6)checks[6]=scooter.Mounted&&player.GadgetMode==4; + if(frame==7)checks[7]=!scooter.Spawned&&!scooter.EnginePlaying&&player.GadgetMode==-1; + if(frame==8)checks[8]=player.Noclip&&!scooter.Spawned&&interactions.Inventory.SelectedGadget==-1; + if(frame==9)checks[9]=!player.Noclip&&!scooter.Spawned&&scooter.BodySteps==0; + } + public bool Passed=>checks.All(v=>v); + public string Report=>$"Scooter {level}: summon={checks[0]}, contact mount={checks[1]}, drive={checks[2]}, steer={checks[3]}, brake/jump={checks[4]}, dismount={checks[5]}, remount={checks[6]}, authored cleanup={checks[7]}, noclip={checks[8]}, reset={checks[9]}, extra ordinary ticks={extra}."; + public static PlayerInput Input(int frame,string level)=>new(frame is 1 or 2,frame is 0 or 3,frame==2||frame==1&&level=="LEV1",false,frame==4); + public static string? StageName(int frame)=>frame switch{0=>"summoned",1=>"mounted",2=>"driving",3=>"steer",4=>"jump",5=>"dismounted",6=>"remounted",7=>"cleanup",8=>"noclip",9=>"reset",_=>null}; +} diff --git a/src/GamePort/Application/ScooterVisuals.cs b/src/GamePort/Application/ScooterVisuals.cs new file mode 100644 index 0000000..48e55ca --- /dev/null +++ b/src/GamePort/Application/ScooterVisuals.cs @@ -0,0 +1,73 @@ +using System.Numerics; +using System.Text.Json; +using GamePort.Assets; +using GamePort.Game; +namespace GamePort.Application; + +/// Original scooter.omt shape0 and four shape1 wheels, plus exact +/// HISCOOT/HISCOOTSTOP source-pivot morphs. Null-material faces stay undrawn. +public sealed class ScooterVisuals +{ + private sealed record Static(Mesh Source,int Offset,MeshDraw[] Draws); + private sealed record Clip(MorphAnimation Source,int Offset,MeshDraw Draw); + private readonly Static body; + private readonly Static[] wheels; + private readonly Clip scoot,stop; + public Mesh Mesh{get;} + public ScooterVisuals(Mesh combined,string preparedRoot) + { + var root=Path.GetFullPath(Path.Combine(preparedRoot,"scooter")); + using var document=JsonDocument.Parse(File.ReadAllBytes(Path.Combine(root,"scooter.json"))); + var data=document.RootElement; + if(data.GetProperty("schema").GetInt32()!=1)throw new InvalidDataException("Unknown Scooter schema"); + string Resource(string key) + { + var path=Path.GetFullPath(Path.Combine(root,data.GetProperty(key).GetString()!)); + if(!path.StartsWith(root+Path.DirectorySeparatorChar,StringComparison.Ordinal))throw new InvalidDataException("Scooter path escapes resources"); + return path; + } + Static Append(Mesh source) + { + var textures=new Dictionary(combined.Textures);var ids=new Dictionary(); + int next=int.MinValue;foreach(var pair in source.Textures) + {while(textures.ContainsKey(next))next++;ids[pair.Key]=next;textures.Add(next++,pair.Value);} + int offset=combined.Vertices.Length;uint indexOffset=(uint)combined.Indices.Length; + var draws=source.Draws.Select(d=>new MeshDraw(d.FirstIndex+indexOffset,d.IndexCount,d.TextureId==-1?-1:ids[d.TextureId]) + {Visible=false,Blend=d.Blend,Opacity=d.Opacity}).ToArray(); + combined=new([..combined.Vertices,..source.Vertices],[..combined.Indices,..source.Indices.Select(i=>i+(uint)offset)]) + {HasExplicitDraws=true,Textures=textures,Draws=[..combined.Draws,..draws],CollisionPolygons=combined.CollisionPolygons, + HasCollisionMaterialIds=combined.HasCollisionMaterialIds}; + return new(source,offset,draws); + } + Clip Load(string key) + { + var source=new MorphAnimation(Resource(key));int offset=combined.Vertices.Length,id=int.MinValue; + while(combined.Textures.ContainsKey(id))id++;combined=source.AppendTo(combined,id); + var draw=combined.Draws[^1];draw.Visible=false;return new(source,offset,draw); + } + body=Append(Mesh.LoadSceneJson(Resource("bodyMesh"))); + var wheel=Mesh.LoadSceneJson(Resource("wheelMesh"));wheels=Enumerable.Range(0,4).Select(_=>Append(wheel)).ToArray(); + scoot=Load("scootAnimation");stop=Load("stopAnimation");Mesh=combined; + } + public void Update(Mesh destination,Scooter vehicle,double time,PlayerAppearance appearance) + { + Draw(body,vehicle.Root,vehicle.Rotation,vehicle.Spawned); + for(int i=0;i<4;i++)Draw(wheels[i],vehicle.WheelRoots[i],vehicle.WheelRotations[i],vehicle.Spawned); + Pose(scoot,vehicle.Mounted&&!vehicle.RiderStopped);Pose(stop,vehicle.Mounted&&vehicle.RiderStopped); + void Draw(Static visual,Vector3 root,Vector3 angles,bool visible) + { + foreach(var draw in visual.Draws)draw.Visible=visible; + if(!visible)return;var model=RocketOrientation.Model(angles,root,Vector3.One); + for(int i=0;i frequency) + {if(loops.TryGetValue(owner,out var stream))stream.SetFrequency(frequency(stream.SourceFrequency));} public void StopLoop(string owner) { if (loops.Remove(owner, out var stream)) stream.Dispose(); diff --git a/src/GamePort/Audio/SdlAudio.cs b/src/GamePort/Audio/SdlAudio.cs index c2c564c..2b1bcaa 100644 --- a/src/GamePort/Audio/SdlAudio.cs +++ b/src/GamePort/Audio/SdlAudio.cs @@ -10,6 +10,7 @@ public sealed class SdlAudio : IDisposable private int length; private readonly bool loop; private bool audioInitialized; + public int SourceFrequency {get;private set;} public bool Paused { get; private set; } public bool Muted { get; private set; } public int QueuedBytes @@ -28,6 +29,7 @@ public sealed class SdlAudio : IDisposable try { if(!Sdl.SDL_LoadWAV(Path.GetFullPath(path),out var spec,out data,out var size))throw new InvalidOperationException(Sdl.Error); + SourceFrequency=spec.Frequency; length=checked((int)size); stream=Sdl.SDL_OpenAudioDeviceStream(uint.MaxValue,ref spec,0,0); if(stream==0)throw new InvalidOperationException(Sdl.Error); @@ -55,6 +57,11 @@ public sealed class SdlAudio : IDisposable if (!Sdl.SDL_SetAudioStreamGain(stream, muted ? 0 : 1)) throw new InvalidOperationException(Sdl.Error); Muted = muted; } + public void SetFrequency(int frequency) + { + ObjectDisposedException.ThrowIf(stream==0,this); + if(frequency<=0||!Sdl.SDL_SetAudioStreamFrequencyRatio(stream,(float)frequency/SourceFrequency))throw new InvalidOperationException(Sdl.Error); + } private void Queue(){if(!Sdl.SDL_PutAudioStreamData(stream,data,length))throw new InvalidOperationException(Sdl.Error);} public void Pump(){if(!Paused && loop && QueuedBytes waypoint?.Tag; public string? PreviousWaypoint => previousWaypoint?.Tag; - public bool SupportedState => actor.AIstate is 1 or 3 or 7 or 9 || actor.Kind == "3CAR" && actor.AIstate == 6; + public bool FollowPlayer {get;set;} + public bool SupportedState => actor.AIstate is 1 or 3 or 7 or 9 || actor.Kind == "3CAR" && actor.AIstate == 6 || FollowPlayer&&actor.Kind=="3DOG"&&actor.AIstate==4; public ActorPatrol(DirectorActor actor, Func findActor, Func integrateBody, @@ -86,7 +87,7 @@ public sealed class ActorPatrol if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt)); SynchronizeAuthoredState(); if (!SupportedState) return false; - if (!actor.Active) return true; + if (!actor.Active||!actor.MovementEnabled) return true; if (!float.IsFinite(actor.Speed)) throw new InvalidOperationException("Nonfinite Goddard speed"); // EXE408023->40E050: the body consumes the *previous* velocity first. @@ -104,6 +105,7 @@ public sealed class ActorPatrol { case 1: Velocity = Vector3.Zero; break; // EXE40835D, after body integration. case 3: StepPatrol(); break; + case 4: StepFollow(); break; case 7: StepWait(dt); break; // State9 jumps directly to the common finisher408911. State6 calls // sensing409CC0 first; source player-contact dispatch is implemented @@ -112,12 +114,30 @@ public sealed class ActorPatrol } // States1/6/7 return before selecting a destination angle (409186..19B). // Retain the old destination on a waypoint change, as the source does. - if (actor.AIstate == 3 && DestinationDelta.X * DestinationDelta.X + DestinationDelta.Z * DestinationDelta.Z > 0) + if (actor.AIstate is 3 or 4 && DestinationDelta.X * DestinationDelta.X + DestinationDelta.Z * DestinationDelta.Z > 0) desiredYaw = MathF.Atan2(-DestinationDelta.X, DestinationDelta.Z) * (180 / MathF.PI); Publish(); return true; } + private void StepFollow() + { + var target=findActor("JIM1");if(target==null||!target.Active)return; + DestinationDelta=target.Position-actor.Position;DestinationDistance=DestinationDelta.Length(); + var length=magnitude(DestinationDelta); + float multiplier=DestinationDistance>=2000?3:DestinationDistance>=1000?1.7f:1; + Velocity=Arrived||length==0?Vector3.Zero:DestinationDelta/length*(actor.Speed*multiplier); + if(DestinationDistanceArrivalDistance*1.5f)Arrived=false; + actor.Speed=DestinationDistance>440?600:450; + if(DestinationDistance>1500) + { + actor.Position=target.Position+RocketOrientation.Rotate(new(0,0,-800),target.Rotation); + Velocity=Vector3.Zero; + } + actor.Animation=magnitude(Velocity)>20?"RUN":"WAG"; + } + private void StepPatrol() { waypoint ??= findActor(actor.Patrol ?? "none"); diff --git a/src/GamePort/Game/LabSimulation.cs b/src/GamePort/Game/LabSimulation.cs index d199cd3..7681348 100644 --- a/src/GamePort/Game/LabSimulation.cs +++ b/src/GamePort/Game/LabSimulation.cs @@ -238,7 +238,7 @@ public sealed class LabSimulation return ((float)Math.Sin(radians), (float)Math.Cos(radians)); } - public void Step(PlayerInput input, bool controlled = true, bool? anyControlled = null, Action? afterPhysics = null) + public void Step(PlayerInput input, bool controlled = true, bool? anyControlled = null, Action? afterPhysics = null,Func? controlledAfterPhysics=null) { if (Noclip) { @@ -251,6 +251,7 @@ public sealed class LabSimulation // scene registry, original cadence or original collision response. StepPhysics(); afterPhysics?.Invoke(); + if(controlledAfterPhysics!=null)controlled=controlledAfterPhysics(); if (controlled && !InputAfterPlayerUpdate) StepInput(input); //42469F..4246DC runs independently of raw ownership. if (Grounded) @@ -288,6 +289,19 @@ public sealed class LabSimulation forceFall=true;CameraEye=sharedEye; } + public void EnterScooter() + { + CancelPoweredFlight(); //425120 only cancels mode1 jump/effect. + TracksBubbleOrientation=true; + } + public void ApplyScooterTransform(Vector3 root,Vector3 rotation) + {ApplyAuthoredTransform(root,rotation.Y);Pitch=rotation.X;Roll=rotation.Z;targetPitch=Pitch;targetRoll=Roll;targetYaw=Yaw;} + public void LeaveScooter(Vector3 root,Vector3 rotation,Vector3 eye) + { + ApplyScooterTransform(root+Vector3.UnitY*40,rotation); + Velocity=Vector3.Zero;extraAirAcceleration=0;CameraEye=eye; + } + public void RocketImpact() { AdjustEnergy(-1);ScoreChanged?.Invoke(-1);CancelPoweredFlight(); diff --git a/src/GamePort/Game/OriginalBodyPhysics.cs b/src/GamePort/Game/OriginalBodyPhysics.cs index a79dab7..28de2e3 100644 --- a/src/GamePort/Game/OriginalBodyPhysics.cs +++ b/src/GamePort/Game/OriginalBodyPhysics.cs @@ -50,7 +50,8 @@ public sealed class OriginalBodyPhysics public OrdinaryBodyStep Step(OrdinaryBodyState body, float seconds, float radius = OriginalBodySupport.JimmyRadius, float factor = OriginalBodySupport.JimmyFactor, float friction = .8f, float suppressionScale = .5f, bool geometryEnabled = true, - BodyResponseProfile profile = BodyResponseProfile.Jimmy) + BodyResponseProfile profile = BodyResponseProfile.Jimmy, + Func? wallContact = null) { Finite(body.Position); Finite(body.Velocity); Finite(body.Acceleration); Finite(body.Impulse); Finite(body.AngularVelocity); Finite(body.Rotation); @@ -111,6 +112,11 @@ public sealed class OriginalBodyPhysics } } var position = move.Position; + if(wallContact!=null&&move.CallbackPolygon is{StoredNormal.Y:>-.7f}terminal) + { + body=wallContact(body with{Position=position,Velocity=velocity,Acceleration=acceleration,Impulse=impulse},terminal); + position=body.Position;velocity=body.Velocity;acceleration=body.Acceleration;impulse=body.Impulse; + } if (horizontalFirst) position.Y += delta.Y; position.Y = MathF.Max(position.Y, -25000); body = body with { Position = position, Velocity = velocity, Acceleration = acceleration, Impulse = impulse }; diff --git a/src/GamePort/Game/OriginalCameraRay.cs b/src/GamePort/Game/OriginalCameraRay.cs index 94d8091..1a7090e 100644 --- a/src/GamePort/Game/OriginalCameraRay.cs +++ b/src/GamePort/Game/OriginalCameraRay.cs @@ -69,7 +69,7 @@ public sealed class OriginalCameraRay public static OriginalCameraRay FromRouteScene(Mesh mesh, string levelCode) { ArgumentNullException.ThrowIfNull(mesh); - if (levelCode is not ("LV1B" or "VR01" or "VR02" or "VR04" or "VR07" or "VR08" or "LEV1")) + if (levelCode is not ("LV1B" or "VR01" or "VR02" or "VR04" or "VR05" or "VR07" or "VR08" or "LEV1")) throw new NotSupportedException("Static camera game-filter recovery covers only selected route/tutorial scenes"); if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3) throw new InvalidDataException("Original camera query requires source polygon metadata"); diff --git a/src/GamePort/Game/OriginalStaticCollision.cs b/src/GamePort/Game/OriginalStaticCollision.cs index 381b7c4..88319b3 100644 --- a/src/GamePort/Game/OriginalStaticCollision.cs +++ b/src/GamePort/Game/OriginalStaticCollision.cs @@ -61,7 +61,7 @@ public sealed class OriginalStaticCollision public static OriginalStaticCollision FromRouteScene(Mesh mesh, string level) { ArgumentNullException.ThrowIfNull(mesh); - if (level is not ("LV1B" or "VR01" or "VR02" or "VR04" or "VR07" or "VR08" or "LEV1")) + if (level is not ("LV1B" or "VR01" or "VR02" or "VR04" or "VR05" or "VR07" or "VR08" or "LEV1")) throw new NotSupportedException("Original static game-filter recovery covers the route and VR01"); if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3) throw new InvalidDataException("Source static collision requires original polygon metadata"); diff --git a/src/GamePort/Game/PlayerSceneBinding.cs b/src/GamePort/Game/PlayerSceneBinding.cs index 6f888a2..3592281 100644 --- a/src/GamePort/Game/PlayerSceneBinding.cs +++ b/src/GamePort/Game/PlayerSceneBinding.cs @@ -10,16 +10,18 @@ public sealed class PlayerSceneBinding : IDisposable private readonly LabSimulation player; private readonly SceneInventory inventory; private readonly string tag; + public Scooter? Scooter {get;} public Rocketship? Rocketship { get; } public bool InventoryControlled=>director.InventoryEnabled&&(director.Controlled|| - Rocketship is{Mounted:true} rocket&&director.ControlledTag==rocket.Actor.Tag); + Rocketship is{Mounted:true} rocket&&director.ControlledTag==rocket.Actor.Tag|| + Scooter is{Mounted:true} scooter&&director.ControlledTag==scooter.Actor.Tag); public int UnsupportedGadgetCleanups { get; private set; } public PlayerSceneBinding(SceneDirector director, LabSimulation player, SceneInventory inventory, string tag, - Rocketship? rocketship=null) + Rocketship? rocketship=null,Scooter? scooter=null) { this.director = director; this.player = player; this.inventory = inventory; this.tag = tag; - Rocketship=rocketship; + Rocketship=rocketship;Scooter=scooter; if(rocketship!=null)rocketship.RiderHit+=player.RocketImpact; director.ActorPreparing += Prepare; director.AuthoredTransformChanged += Transform; @@ -34,12 +36,31 @@ public sealed class PlayerSceneBinding : IDisposable public bool Step(PlayerInput input) { - if(player.Noclip&&Rocketship?.Mounted==true)inventory.SelectGadget(-1); + if(player.Noclip&&(Rocketship?.Mounted==true||Scooter?.Spawned==true))inventory.SelectGadget(-1); bool VehicleControl()=>Rocketship is{Mounted:true} r&&(director.AuthoredControlledTag==r.Actor.Tag||director.DebugForceControl); - var acceptsInput = director.Controlled || player.Noclip || VehicleControl(); + bool ScooterControl()=>Scooter is{Mounted:true}s&&(director.AuthoredControlledTag==s.Actor.Tag||director.DebugForceControl); + var acceptsInput = director.Controlled || player.Noclip || VehicleControl()||ScooterControl(); + Scooter?.StepBody(FixedStepClock.Step,input); Rocketship?.StepBody(FixedStepClock.Step); - player.Step(input,(director.Controlled&&Rocketship?.Mounted!=true)||player.Noclip,director.ControlledTag!=null, - ()=>{if(!player.InputAfterPlayerUpdate&&VehicleControl())Rocketship!.StepInput(input,FixedStepClock.Step);}); + bool JimmyControl()=>(director.Controlled&&Rocketship?.Mounted!=true&&Scooter?.Mounted!=true)||player.Noclip; + player.Step(input,JimmyControl(),director.ControlledTag!=null,()=> + { + if(Scooter is{Spawned:true,Mounted:false}s&&!player.Noclip&&s.TryMount(player.ActorRoot,player.InteractionRadius)) + {player.EnterScooter();director.TransferControl(s.Actor);} + if(!player.InputAfterPlayerUpdate) + { + if(VehicleControl())Rocketship!.StepInput(input,FixedStepClock.Step); + if(ScooterControl())Scooter!.StepInput(input,FixedStepClock.Step); + } + },JimmyControl); + Scooter?.StepFrame(input,FixedStepClock.Step); + if(Scooter is{Mounted:true}scooter) + { + player.ApplyScooterTransform(scooter.Root,scooter.Rotation); + director.TransferControl(scooter.Actor); + if(player.InputAfterPlayerUpdate&&ScooterControl())scooter.StepInput(input,FixedStepClock.Step); + } + Scooter?.StepWheels(); Rocketship?.StepFrame(input,FixedStepClock.Step); if(Rocketship is{Mounted:true} rocket) { @@ -69,13 +90,25 @@ public sealed class PlayerSceneBinding : IDisposable if (!string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) return; //427FF0 switches raw mode, not display selection. A rejected Invisible //equip can leave display2 with raw mode-1; cleanup does not equip it. - if (player.GadgetMode is 0 or 1 or 2 or 6 or 7 || inventory.SelectedGadget is -1 or 3) + if (player.GadgetMode is 0 or 1 or 2 or 4 or 6 or 7 || inventory.SelectedGadget is -1 or 3) { inventory.SelectGadget(-1); player.GadgetMode = -1; } else if (player.GadgetMode != -1) UnsupportedGadgetCleanups++; } private void Selected(int item) { + if(Scooter is{Spawned:true}scooter) + { + bool mounted=scooter.Mounted; + if(director.FindActor("C3DGODDARD") is{} dog) + {dog.Position=scooter.Root;dog.Rotation=scooter.Rotation;dog.Visible=dog.BodyEnabled=dog.MovementEnabled=true;} + scooter.Release(); + if(mounted) + { + player.LeaveScooter(scooter.Root,scooter.Rotation,scooter.CameraEye); + if(director.FindActor(tag) is{} rider){rider.Animation="RUN";director.TransferControl(rider);} + } + } if(Rocketship?.Mounted==true) { Rocketship.Release(); @@ -85,7 +118,16 @@ public sealed class PlayerSceneBinding : IDisposable if (item==0 && director.FindActor(tag) is{} actor) player.SeedBubbleTilt(actor.Rotation); //The display tile remains available for Practice outside the bounded //live scene; unsupported selection must not invent a Jimmy flight mode. - player.GadgetMode=item==1&&Rocketship==null?-1:GadgetScreen.EquippedMode(item); + player.GadgetMode=item==1&&Rocketship==null||item==4&&Scooter==null?-1:GadgetScreen.EquippedMode(item); + if(item==4&&Scooter!=null) + { + if(director.FindActor("C3DGODDARD") is{} dog&&dog.BodyEnabled) + { + Scooter.Summon(dog.Position,dog.Rotation,player.CameraEye); + dog.Visible=dog.BodyEnabled=dog.MovementEnabled=false; + } + else player.GadgetMode=-1; + } if(item==1&&Rocketship!=null) { var rider=director.FindActor(tag)!; @@ -97,8 +139,9 @@ public sealed class PlayerSceneBinding : IDisposable public void ResetVehicle() { - if(Rocketship?.Mounted==true)inventory.SelectGadget(-1); + if(Rocketship?.Mounted==true||Scooter?.Spawned==true)inventory.SelectGadget(-1); Rocketship?.Reset(); + Scooter?.Reset(); } private void DefaultGadget() => inventory.SelectGadget(-1); diff --git a/src/GamePort/Game/SceneDirector.cs b/src/GamePort/Game/SceneDirector.cs index 2f7646b..5ac8a0e 100644 --- a/src/GamePort/Game/SceneDirector.cs +++ b/src/GamePort/Game/SceneDirector.cs @@ -183,6 +183,18 @@ public sealed class SceneDirector public DirectorActor? FindActor(string tag) => actors.GetValueOrDefault(tag); + internal DirectorActor AddOwnedActor(string tag,string kind,Vector3 root) + { + if(actors.TryGetValue(tag,out var existing))return existing; + var actor=new DirectorActor(null,tag,kind,root);Actors.Add(actor);actors.Add(tag,actor);return actor; + } + + public DirectorActor EnsureCompanion(Vector3 root,Vector3 rotation) + { + var actor=AddOwnedActor("C3DGODDARD","3DOG",root); + actor.Position=root;actor.Rotation=rotation;actor.AIstate=4;actor.Speed=450;return actor; + } + internal void TransferControl(DirectorActor actor) { if(!Actors.Contains(actor))throw new ArgumentException("Control requires a registered actor",nameof(actor)); diff --git a/src/GamePort/Game/SceneInteractions.cs b/src/GamePort/Game/SceneInteractions.cs index c8d248d..a7d632c 100644 --- a/src/GamePort/Game/SceneInteractions.cs +++ b/src/GamePort/Game/SceneInteractions.cs @@ -81,7 +81,7 @@ public sealed class SceneInteractions { if (!float.IsFinite(activePlayerRoot.X + activePlayerRoot.Y + activePlayerRoot.Z) || !float.IsFinite(playerRadius) || playerRadius < 0) throw new ArgumentOutOfRangeException(nameof(activePlayerRoot)); - bool VehicleControlled()=>vehicle is{Kind:"3ROC"}&&director.AuthoredControlledTag==vehicle.Tag; + bool VehicleControlled()=>vehicle is{Kind:"3ROC" or "3JEE"}&&director.AuthoredControlledTag==vehicle.Tag; bool Controlled()=>director.Controlled||VehicleControlled(); if (!Controlled()) return; HideCollected(); @@ -97,9 +97,9 @@ public sealed class SceneInteractions if (!director.Controlled) break; } // Carl InitObject413E2F..45 sets radius100 and support factor0.75. - //435D08 pickups require the raw controlled ship.457EE6 LOAD requires + //435D08 pickups require the raw controlled actor.457EE6 LOAD requires //the real Jimmy passenger; the coincident actors keep distinct radii. - var contactRadius=source.Kind=="3PIC"&&VehicleControlled()?50:playerRadius; + var contactRadius=source.Kind=="3PIC"&&VehicleControlled()?(vehicle!.Kind=="3JEE"?150:50):playerRadius; var radius = contactRadius + (source.Kind == "3TRO" ? 20 : source.Kind == "3CAR" ? 100 : source.Number("Radius")); var overlaps = actor.Active && (source.Kind!="3TRO" || actor.BodyEnabled) && OriginalBodySupport.QuickMagnitude(activePlayerRoot - actor.Position) < radius; diff --git a/src/GamePort/Game/Scooter.cs b/src/GamePort/Game/Scooter.cs new file mode 100644 index 0000000..b828684 --- /dev/null +++ b/src/GamePort/Game/Scooter.cs @@ -0,0 +1,155 @@ +using System.Numerics; +using GamePort.Assets; +namespace GamePort.Game; + +/// Jimmy's owned C3DJEEP, summoned at Goddard and mounted by contact. +/// Ordinary source vehicle/wheel profile is admitted in VR05 and outsideLEV1. +public sealed class Scooter : IDisposable +{ + private readonly OriginalStaticCollision world; + private readonly OriginalBodyPhysics physics; + private readonly Dictionary<(int,int),Vector3> normals; + private readonly ScooterWheels wheels=new(); + private OrdinaryBodyState body; + private Vector3 destination; + private float poseClock,faceRate=5,impactTime; + private bool jumpLatch; + private Vector3? supportNormal; + public DirectorActor Actor{get;} + public bool Spawned{get;private set;} + public bool Mounted{get;private set;} + public bool ImpactActive{get;private set;} + public bool RiderStopped{get;private set;} + public bool EnginePlaying{get;private set;} + public Vector3 Root=>body.Position; + public Vector3 Rotation{get;private set;} + public Vector3 RiderRotation{get;private set;} + public Vector3 Velocity=>body.Velocity; + public Vector3 PendingImpulse=>body.Impulse; + public bool Supported=>body.Supported; + public ScooterSteering Steering{get;private set;} + public IReadOnlyList WheelRoots=>wheels.Roots; + public IReadOnlyList WheelRotations=>wheels.Rotations; + public int FrontSupports=>wheels.Front; + public int RearSupports=>wheels.Rear; + public int BodySteps{get;private set;} + public int InputSteps{get;private set;} + public int FrameSteps{get;private set;} + public int Contacts{get;private set;} + public int Jumps{get;private set;} + public Vector3 CameraEye{get;private set;} + public Vector3 CameraTarget{get;private set;} + public Func? DynamicRootResolver{get;set;} + public event Action? EngineStarted; + public event Action? EngineStopped; + public event Action? EngineSpeedChanged; + public event Action? MountedChanged; + + public Scooter(DirectorActor actor,Mesh mesh,string level) + { + if(level is not("VR05" or "LEV1"))throw new NotSupportedException("Scooter body profile covers VR05 and outsideLEV1"); + Actor=actor;world=OriginalStaticCollision.FromRouteScene(mesh,level); + //421910 ordinary callback is independent of Jimmy's special materials. + physics=new(world,allowSpecialMaterials:true); + normals=mesh.CollisionPolygons.ToDictionary(p=>(p.ShapeId,p.PolygonIndex),p=>p.Normal); + Reset(); + } + public void Reset() + { + Release();body=default;Steering=default;RiderRotation=Rotation=destination=Vector3.Zero; + faceRate=5;poseClock=impactTime=0;ImpactActive=jumpLatch=RiderStopped=false;wheels.Reset(); + BodySteps=InputSteps=FrameSteps=Contacts=Jumps=0; + } + public void Summon(Vector3 root,Vector3 rotation,Vector3 eye) + { + body=body with{Position=root};RiderRotation=Rotation=destination=rotation;CameraEye=eye;CameraTarget=eye+Vector3.UnitZ*200; + Spawned=true;Actor.Visible=Actor.BodyEnabled=Actor.MovementEnabled=true;Sync(); + } + public bool TryMount(Vector3 jimmyRoot,float radius) + { + if(!Spawned||Mounted||OriginalBodySupport.QuickMagnitude(Root-jimmyRoot)>=150+radius)return false; + Mounted=true;RiderStopped=false;poseClock=0;MountedChanged?.Invoke();return true; + } + public void Release() + { + Spawned=Mounted=false;Actor.Visible=Actor.BodyEnabled=Actor.MovementEnabled=false; + if(EnginePlaying){EnginePlaying=false;EngineStopped?.Invoke();} + } + public void StepBody(float dt,PlayerInput input) + { + if(!Spawned)return; + var result=physics.Step(body,dt,150,.2f,friction:.9f,suppressionScale:1,wallContact:(current,wall)=> + {body=current;Contact(wall.StoredNormal,input,dt);return body with{PublishedSpeed=Steering.Speed};}); + body=result.Body;BodySteps++; + if(DynamicRootResolver!=null)body=body with{Position=DynamicRootResolver(result.PreviousPosition,Root,150)}; + if(result.SupportHit is{} hit&&normals.TryGetValue((hit.ShapeId,hit.PolygonId),out var normal)) + supportNormal=normal; + Sync(); + } + public void StepInput(PlayerInput input,float dt) + { + if(!Mounted)return;InputSteps++; + var next=ScooterMotion.Input(Steering,input,RearSupports,dt); + Steering=ImpactActive?Steering with{Angle=next.Angle,KeyboardTurn=next.KeyboardTurn}:next; + var camera=ScooterCamera.Follow(Root,Rotation,CameraEye,dt,(start,end)=> + { + var context=physics.LastStaticContext??new(64.9519043f); + context.Nearest=context.Nearest with{FaceDistance=130000}; + //413870 pushes false: camera reclip tests faces, not wheel/body edges. + return world.Move(start,end-start,64.9519043f,context,edges:false).Position; + },impact:ImpactActive); + CameraEye=camera.Eye;CameraTarget=camera.Target; + } + public void StepFrame(PlayerInput input,float dt) + { + if(!Spawned)return; + Rotation=ScooterWheels.Face(Rotation,destination,faceRate,dt); + if(ImpactActive) + { + var impact=ScooterMotion.Impact(Velocity,body.AngularVelocity,impactTime,dt); + impactTime=impact.Time;ImpactActive=impact.Active; + body=body with{Velocity=impact.Velocity,AngularVelocity=impact.AngularVelocity}; + if(!ImpactActive)Steering=Steering with{Speed=0}; + } + else + { + var drive=ScooterMotion.Apply(Steering,Velocity,Rotation,Supported,FrontSupports,RearSupports,dt,.9f); + Steering=drive.Steering;Rotation=drive.Rotation;body=body with{Velocity=drive.Velocity}; + } + FrameSteps++; + if(Mounted) + { + if(!input.Jump)jumpLatch=false; + else if(!jumpLatch&&Supported){body=body with{Impulse=new(0,700,0)};jumpLatch=true;Jumps++;} + poseClock+=dt; + if((double)poseClock>.3){RiderStopped=Steering.Speed<10;poseClock=0;} + } + else {Steering=Steering with{Speed=0};faceRate=10;} + body=body with{PublishedSpeed=Steering.Speed}; + //Jimmy copies the parent's Euler before the later wheel/lean phase. + RiderRotation=Rotation; + if(!EnginePlaying){EnginePlaying=true;EngineStarted?.Invoke();} + else EngineSpeedChanged?.Invoke(Steering.Speed); + Sync(); + } + public void StepWheels() + { + if(!Spawned)return; + Rotation=Rotation with{Z=Steering.Angle*-.5f}; + //Counts used by465220 are from the preceding wheel pass. + var oldFront=FrontSupports;var oldRear=RearSupports; + wheels.Update(Root,Rotation,Steering.Angle,Steering.Speed,Steering.Braking,ImpactActive,world); + if(oldFront+oldRear==0){destination=new(340,Rotation.Y,0);faceRate=2;} + else if(supportNormal is{} normal)destination=ScooterWheels.TerrainTarget(normal,Rotation.Y); + Sync(); + } + private void Contact(Vector3 normal,PlayerInput input,float dt) + { + Contacts++; + var result=ScooterMotion.Contact(Steering.Speed,Velocity,Rotation,normal,body.Acceleration,ImpactActive,input.Forward||input.Fire,dt); + if(!ImpactActive&&result.Impact)impactTime=0; + ImpactActive=result.Impact;Steering=Steering with{Speed=result.Speed};body=body with{Acceleration=result.Acceleration}; + } + private void Sync(){Actor.Position=Root;Actor.Rotation=Rotation;Actor.Speed=Steering.Speed;} + public void Dispose()=>Release(); +} diff --git a/src/GamePort/Game/ScooterCamera.cs b/src/GamePort/Game/ScooterCamera.cs new file mode 100644 index 0000000..9994efc --- /dev/null +++ b/src/GamePort/Game/ScooterCamera.cs @@ -0,0 +1,25 @@ +using System.Numerics; +namespace GamePort.Game; +public readonly record struct ScooterCameraResult(Vector3 Eye,Vector3 Target,Vector3 DesiredEye,Vector3 Look,float Gain); +/// 4130A0 default mode1. Clipping follows smoothing and uses a sphere, +/// then look minus NEW eye determines source signed14-bit aim. +public static class ScooterCamera +{ + public static ScooterCameraResult Follow(Vector3 root,Vector3 rotation,Vector3 oldEye,float dt,Func? clip=null,bool impact=false) + { + var desired=root+RocketOrientation.Rotate(new(-30,0,-200),rotation)+Vector3.UnitY*50; + var delta=desired-oldEye;var distance=OriginalBodySupport.QuickMagnitude(delta); + float gain=distance>400?2.8f:distance>200?1.7f:1; + var eye=oldEye+delta*dt*gain; + if(impact) + { + //413157..4131C0: approach root X/Z at .3; leave eye Y unchanged. + desired=new(root.X,oldEye.Y,root.Z);gain=.3f;eye=oldEye+(desired-oldEye)*dt*gain; + } + if(clip!=null)eye=clip(root,eye); + var look=impact?root:root+RocketOrientation.Rotate(new(0,50,100),rotation); + var(p,y)=OriginalHeading.Angles(look-eye); + var direction=RocketOrientation.Rotate(Vector3.UnitZ,new(p*.02197265625f,y*.02197265625f,0)); + return new(eye,eye+direction*200,desired,look,gain); + } +} diff --git a/src/GamePort/Game/ScooterMotion.cs b/src/GamePort/Game/ScooterMotion.cs new file mode 100644 index 0000000..3088519 --- /dev/null +++ b/src/GamePort/Game/ScooterMotion.cs @@ -0,0 +1,102 @@ +using System.Numerics; +namespace GamePort.Game; + +public readonly record struct ScooterSteering(float Speed=0,float Angle=0,bool KeyboardTurn=false,bool Reverse=false, + bool Braking=false,bool Throttle=false,float BrakeTime=0,float YawRate=0,float Blend=0); +public readonly record struct ScooterDrive(ScooterSteering Steering,Vector3 Velocity,Vector3 Rotation); +public readonly record struct ScooterContact(float Speed,Vector3 Acceleration,bool Impact); +public readonly record struct ScooterImpact(Vector3 Velocity,Vector3 AngularVelocity,float Time,bool Active); + +/// 465830 keyboard prefix and465220 ordinary non-AI/non-sprint drive. +/// Wheel/body support is observed independently; never fabricated here. +public static class ScooterMotion +{ + public const float Maximum=1485; + /// 421910 with the constructor's disabled bounce flag. + public static ScooterContact Contact(float speed,Vector3 velocity,Vector3 rotation,Vector3 normal, + Vector3 acceleration,bool impact,bool throttle,float dt) + { + float length=OriginalBodySupport.QuickMagnitude(velocity with{Y=0}); + var forward=RocketOrientation.Rotate(Vector3.UnitZ,rotation); + if(!impact&&length>20&&MathF.Abs(Vector3.Dot(forward,normal))>=.9f) + return new(0,Vector3.Zero,true); + if(impact||speed<=0||length==0)return new(speed,acceleration,impact); + float dot=Vector3.Dot(velocity/OriginalBodySupport.QuickMagnitude(velocity),normal); + dot*=dot<-.85f?3.5f:1.5f; + if(dot<0&&throttle)speed=MathF.Max(230,speed-MathF.Abs(dot)*1200*dt); + return new(speed,acceleration,impact); + } + /// 4669F0 ordinary enabled-body impact suffix. + public static ScooterImpact Impact(Vector3 velocity,Vector3 angular,float time,float dt) + { + time+=dt; + return time>=4?new(Vector3.Zero,Vector3.Zero,time,false): + new(velocity+new Vector3(-velocity.X*dt,0,-velocity.Z*dt),angular-angular*dt,time,true); + } + public static ScooterSteering Input(ScooterSteering state,PlayerInput input,int rear,float dt) + { + var angle=state.Angle;var keyboard=state.KeyboardTurn; + if(input.Left){angle+=200*dt;keyboard=true;} + else if(input.Right){angle-=200*dt;keyboard=true;} + else if(keyboard)angle=angle>0?MathF.Max(0,angle-200*dt):MathF.Min(0,angle+200*dt); + angle=Math.Clamp(angle,-45,45);float speed=state.Speed;bool reverse=state.Reverse,brake=state.Braking; + bool throttle=rear>0&&(input.Forward||input.Fire); + if(throttle){if(speed0&&input.Backward) + { + if(!reverse) + { + reverse=true; + if(speed>0){speed=MathF.Max(0,speed-1200*dt);brake=true;} + else if(speed<0){speed=MathF.Min(0,speed+1200*dt);brake=true;} + } + else speed=MathF.Max(-Maximum*.4f,speed-1200*dt); + } + else {brake=false;reverse=false;} + return state with{Speed=speed,Angle=angle,KeyboardTurn=keyboard,Reverse=reverse,Braking=brake,Throttle=throttle}; + } + public static ScooterDrive Apply(ScooterSteering state,Vector3 velocity,Vector3 rotation,bool supported,int front,int rear,float dt,float friction=.9f) + { + float speed=state.Speed,rate=state.YawRate,blend=state.Blend,timer=state.BrakeTime; + var horizontal=velocity with{Y=0};var magnitude=OriginalBodySupport.QuickMagnitude(horizontal); + if(magnitude>0) + { + if(front>0) + { + rate=front*state.Angle*MathF.Min(magnitude*.005f,1); + var direction=horizontal/magnitude;var forward=RocketOrientation.Rotate(Vector3.UnitZ,rotation); + var delta=rate*dt*(Vector3.Dot(direction,forward)<0?-1:1); + rotation=RocketOrientation.Add(rotation,new(0,delta,0)); + } + if(front+rear!=0) + { + if(!state.Throttle&&!state.Reverse) + {speed=(float)(speed-speed*.5f*dt);if(speed>=-1&&speed<=1)speed=0;} + if(!state.Braking)speed=(float)(speed-Math.Abs(state.Angle)*(1.0/45)*(speed*.8f)*dt); + speed=(float)(speed-Math.Sin(rotation.X*.01745329238474369f)*500*dt); + } + } + if(supported&&front+rear>=2) + { + var forward=RocketOrientation.Rotate(Vector3.UnitZ,rotation);var direction=forward; + var liveMagnitude=OriginalBodySupport.QuickMagnitude(velocity); + if(speed>0&&liveMagnitude!=0) + { + direction=velocity/liveMagnitude; + if(Vector3.Dot(direction,forward)<0)direction=forward; + if(!state.Braking) + { + var factor=(float)(2250*.6600000262260437f*.20000000298023224f/speed); + blend=MathF.Min(friction,friction*factor); + direction=new(direction.X+forward.X*blend,forward.Y,direction.Z+forward.Z*blend); + } + timer=0; + } + else if(state.Braking){timer+=dt;if(timer<1)speed=0;} + var next=direction*speed; + if(velocity.Y<0)next.Y+=velocity.Y; + velocity=next; + } + return new(state with{Speed=speed,YawRate=rate,Blend=blend,BrakeTime=timer},velocity,rotation); + } +} diff --git a/src/GamePort/Game/ScooterWheels.cs b/src/GamePort/Game/ScooterWheels.cs new file mode 100644 index 0000000..e7c1eba --- /dev/null +++ b/src/GamePort/Game/ScooterWheels.cs @@ -0,0 +1,65 @@ +using System.Numerics; +namespace GamePort.Game; + +/// 412A90 four-child setup and467080 post-normal wheel positioning. +/// Child support is queried manually; children have no independent integrator. +public sealed class ScooterWheels +{ + public const float Radius=23.769514083862305f; + public static readonly Vector3[] Offsets=[new(-3,1,73),new(3,1,73),new(-3,1,-30),new(3,1,-30)]; + private readonly Vector3[] roots=new Vector3[4],angles=new Vector3[4]; + private readonly float[] spins=new float[4]; + private readonly bool[] supported=new bool[4]; + public IReadOnlyList Roots=>roots; + public IReadOnlyList Rotations=>angles; + public int Front=>supported.Take(2).Count(v=>v); + public int Rear=>supported.Skip(2).Count(v=>v); + public void Reset(){Array.Clear(roots);Array.Clear(angles);Array.Clear(spins);Array.Clear(supported);} + public void Update(Vector3 root,Vector3 rotation,float steering,float speed,bool braking,bool crash,OriginalStaticCollision world) + { + var forward=RocketOrientation.Rotate(Vector3.UnitZ,rotation); + for(int i=0;i<4;i++) + { + var before=roots[i];var local=Offsets[i];var desired=root+RocketOrientation.Rotate(local,rotation); + if(!crash) + { + var result=OriginalBodySupport.Resolve(new(desired,before,Vector3.Zero,Vector3.Zero,Radius,1,PreventLowering:false), + supported[i],(a,b,s)=>world.TraceSupport(a,b,s)); + supported[i]=result.Supported; + var anchor=result.Supported?result.SupportAnchor.Y:-25000; + local.Y=Math.Clamp(local.Y+anchor-desired.Y,Offsets[i].Y-15,Offsets[i].Y+15); + } + roots[i]=root+RocketOrientation.Rotate(local,rotation); + var delta=(roots[i]-before) with{Y=0};var distance=OriginalBodySupport.QuickMagnitude(delta); + if(distance!=0&&(speed<0||!braking)) + spins[i]=RocketOrientation.AddAxis(spins[i],(float)(distance/Radius*57.295776f)*(Vector3.Dot(delta,forward)>0?1:-1)); + angles[i]=i%2==0 + ?new(rotation.Z,RocketOrientation.AddAxis(rotation.Y,90),RocketOrientation.AddAxis(rotation.X,-spins[i])) + :new(RocketOrientation.AddAxis(0,-rotation.Z),RocketOrientation.AddAxis(rotation.Y,-90),RocketOrientation.AddAxis(rotation.X,spins[i])); + if(i<2)angles[i]=RocketOrientation.Add(angles[i],RocketOrientation.Rotate(new(0,steering,0),rotation)); + } + } + public static Vector3 TerrainTarget(Vector3 normal,float yaw) + { + var(_,x)=OriginalHeading.Angles(new(normal.X,0,normal.Y)); + var(_,z)=OriginalHeading.Angles(new(normal.Z,0,normal.Y)); + var index=(int)((double)yaw*45.511112213134766)&16383; + var(sine,cosine)=RocketOrientation.Units(index); + //Source table cardinal endpoints are exact, rather than Math.Cos(pi/2)'s residue. + if((index&4095)==0){sine=index switch{4096=>1,12288=>-1,_=>0};cosine=index switch{0=>1,8192=>-1,_=>0};} + var components=new Vector3((float)(-x*(double)cosine-z*(double)sine),0, + (float)(-z*(double)cosine+x*(double)sine))*.02197265625f; + return new(RocketOrientation.AddAxis(0,-components.Z),yaw,RocketOrientation.AddAxis(0,components.X)); + } + public static Vector3 Face(Vector3 rotation,Vector3 target,float rate,float dt) + { + float Axis(float current,float desired) + { + float delta=desired-current; + if(delta>=180)delta-=360;else if(delta< -180)delta+=360; + float gain=dt*rate;float step=delta*gain; + return MathF.Abs(step)Math.Max(7000,(int)(baseFrequency+(double)speed*(1/1.9)*51)); + private static string? Option(string[] args, string name) { var i = Array.IndexOf(args, name); @@ -90,6 +92,7 @@ internal static class Program --smoke-shrink-ray Fire at an actual VR04 soldier; explicit player-placement fixture --smoke-invisible Accelerated recharge/activation/flash/expiry/unequip fixture in VR03 --smoke-baseball VR07 aim/release/flight/target/respawn fixture + --smoke-scooter VR05 / outside summon-drive-cleanup replay --smoke-grappler VR08 attach/reel/swing/cleanup fixture --smoke-rocketship VR02 flight/turn/roll/control fixture --smoke-bubble VR01 expand/throttle/bounce/cleanup/fade input fixture @@ -265,6 +268,7 @@ internal static class Program var invisibleSmoke = args.Contains("--smoke-invisible"); var bubbleSmoke = args.Contains("--smoke-bubble"); var baseballSmoke = args.Contains("--smoke-baseball"); + var scooterSmoke=args.Contains("--smoke-scooter"); var grapplerSmoke = args.Contains("--smoke-grappler"); var rocketSmoke = args.Contains("--smoke-rocketship"); var carlSmoke = args.Contains("--smoke-carl-cutscene"); @@ -287,7 +291,7 @@ internal static class Program var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window") && animationPath == null && !args.Contains("--time"); var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time") - || args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke || grapplerSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke; + || args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke || grapplerSmoke || scooterSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke; if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window"))) throw new ArgumentException("Story playback requires its own simulation mode."); if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode."); @@ -320,6 +324,8 @@ internal static class Program SceneBaseballs? baseballs = null; BaseballVisuals? baseballVisuals = null; BaseballAimOverlay? baseballAim = null; + Scooter? scooter=null; + ScooterVisuals? scooterVisuals=null; Rocketship? rocketship = null; RocketshipVisuals? rocketshipVisuals = null; GrapplerVisuals? grapplerVisuals = null; @@ -351,7 +357,7 @@ internal static class Program var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase")); if (walking) { - var cameraRay = level!.Code is "LV1B" or "VR01" or "VR02" or "VR04" or "VR07" or "VR08" or "LEV1" + var cameraRay = level!.Code is "LV1B" or "VR01" or "VR02" or "VR04" or "VR05" or "VR07" or "VR08" or "LEV1" ? OriginalCameraRay.FromRouteScene(world, level.Code) : null; debugCameraRay = cameraRay; simulation = new LabSimulation(new SceneCollision(world), standingPose, originalStart.Position, originalStart.Rotation.Y, @@ -398,13 +404,23 @@ internal static class Program simulation!.Energy = interactions.Energy; simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3); simulation.ScoreChanged += interactions.ChangeScore; + if(level.Code is "VR05" or "LEV1") + { + if(director.FindActor("C3DGODDARD")==null) + { + var behind=simulation.ActorRoot+RocketOrientation.Rotate(new(0,0,-250),new(0,simulation.Yaw,0)); + var ray=OriginalCameraRay.FromRouteScene(world,level.Code); + director.EnsureCompanion(ray.TraceGeometry(simulation.ActorRoot,behind)==null?behind:originalStart!.Position,Vector3.Zero); + } + scooter=new(director.AddOwnedActor("C3DJEEP","3JEE",Vector3.Zero),world,level.Code); + } if(level.Code=="VR02")rocketship=new(director.Actors.Single(a=>a.Kind=="3ROC"),world,level.Code); if (level.Code is "LV1B" or "VR04" or "LEV1") { gadgets = new SceneGadgets(director,interactions.Inventory,simulation,world); gadgets.ScoreAwarded += interactions.ChangeScore; } - if(level.Code is "LV1B" or "VR01" or "VR04" or "VR07" or "VR08" or "LEV1") + if(level.Code is "LV1B" or "VR01" or "VR04" or "VR05" or "VR07" or "VR08" or "LEV1") { baseballs=new(director,simulation,world); baseballs.ScoreAwarded+=interactions.ChangeScore; @@ -437,6 +453,7 @@ internal static class Program grounded = resolved.Supported; return new(resolved.Body.Position, resolved.Body.Velocity); }); + patrol.FollowPlayer=actor.Kind=="3DOG"&&level!.Code is "VR05" or "LEV1"; patrols.Add(actor.Tag, patrol); director.RegisterPatrolConsumer(actor.Tag); director.ActorChanged += changed => { if (ReferenceEquals(changed, actor)) patrol.SynchronizeAuthoredState(); }; @@ -461,6 +478,11 @@ internal static class Program } else simulation.DynamicRootResolver = (previous, position, radius) => DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius); + if(scooter!=null) + { + scooter.DynamicRootResolver=(a,b,r)=>DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(),a,b,r); + scooterVisuals=new(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!,"..")));mesh=scooterVisuals.Mesh; + } jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, ".."))); mesh = jetpackVisuals.Mesh; bubbleVisuals = new(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!,".."))); @@ -520,7 +542,7 @@ internal static class Program var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture); 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") ?? (grapplerSmoke ? "9" : rocketSmoke ? "10" : walkSmoke ? "240" : jetpackSmoke ? "300" : shrinkSmoke ? "90" : invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke ? "8" : gadgetWindowSmoke ? "24" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0")); + var frames = int.Parse(Option(args, "--frames") ?? (scooterSmoke ? "10" : grapplerSmoke ? "9" : rocketSmoke ? "10" : walkSmoke ? "240" : jetpackSmoke ? "300" : shrinkSmoke ? "90" : invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke ? "8" : gadgetWindowSmoke ? "24" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0")); if (gadgetWindowSmoke && (headless || level?.Code != "LV1B" || loadedSave != null || frames < 24)) throw new ArgumentException("Gadget menu SDL fixture requires a fresh windowed lab and24 frames"); if (shrinkSmoke && (level?.Code != "VR04" || gadgets == null || frames < 60)) @@ -531,6 +553,8 @@ internal static class Program throw new ArgumentException("Bubble smoke requires a fresh VR01 and at least8 frames"); if(baseballSmoke && (level?.Code!="VR07" || frames<8 || loadedSave!=null)) throw new ArgumentException("Baseball fixture requires a fresh VR07 and at least8 frames"); + if(scooterSmoke&&(scooter==null||frames<10||loadedSave!=null)) + throw new ArgumentException("Scooter replay requires fresh VR05 or outsideLEV1 and10 frames"); if(grapplerSmoke&&(level?.Code!="VR08"||frames<9||loadedSave!=null)) throw new ArgumentException("Grappler fixture requires fresh VR08 and at least9 frames"); if(rocketSmoke&&(level?.Code!="VR02"||frames<10||loadedSave!=null)) @@ -559,7 +583,7 @@ internal static class Program var height = uint.Parse(Option(args, "--height") ?? "720"); if (width is < 64 or > 8192 || height is < 64 or > 8192) throw new ArgumentException("Viewport dimensions must be64..8192"); using var playerBinding = director == null ? null - : new PlayerSceneBinding(director, simulation!, interactions!.Inventory, level!.Player!.Tag!,rocketship); + : new PlayerSceneBinding(director, simulation!, interactions!.Inventory, level!.Player!.Tag!,rocketship,scooter); var renderer = presentation.LoadScene(mesh, texture, headless, walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera", width, height, !args.Contains("--no-validation")); @@ -570,6 +594,8 @@ internal static class Program InvisibleSmoke? invisibleFixture = null; BubbleSmoke? bubbleFixture = null; BaseballSmoke? baseballFixture = null; + ScooterSmoke? scooterFixture=null; + var sawScooterKeys=0; GrapplerSmoke? grapplerFixture=null; RocketshipSmoke? rocketFixture=null; var sawRocketKeys=0; @@ -581,6 +607,7 @@ internal static class Program using var audio = Option(args, "--audio") is { } audioFile ? new SdlAudio(audioFile, args.Contains("--loop-audio"), debugMenu.Open) : null; using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null; + using var scooterLifetime=scooter; using var grapplerLifetime = simulation?.Grappler; if(simulation?.Grappler is{} grapplerAudio) { @@ -593,6 +620,12 @@ internal static class Program simulation.GadgetSound += (id,loop) => sceneAudio?.Effect(id,loop?"bubble":null); simulation.BubbleSoundStopped += () => sceneAudio?.StopLoop("bubble"); } + if(scooter!=null) + { + scooter.EngineStarted+=()=>sceneAudio?.Effect(46,"scooter"); + scooter.EngineStopped+=()=>sceneAudio?.StopLoop("scooter"); + scooter.EngineSpeedChanged+=speed=>sceneAudio?.TuneLoop("scooter",baseFrequency=>ScooterEngineFrequency(baseFrequency,speed)); + } if(baseballs!=null)baseballs.Sound+=id=>sceneAudio?.Effect(id); if(rocketship!=null) { @@ -643,7 +676,7 @@ internal static class Program Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}, retained player input order={simulation.InputAfterPlayerUpdate}, gadget availability={interactions.Inventory.State(0, 3)}."); if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions"); } - if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke || grapplerSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); } + if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke || grapplerSmoke || scooterSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); } if (gadgetWindowSmoke) { interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3); } if (controlPhaseSmoke) { @@ -725,6 +758,7 @@ internal static class Program } if (invisibleSmoke) invisibleFixture = new(simulation!,interactions!.Inventory); if(baseballSmoke)baseballFixture=new(simulation!,playerBinding!,interactions!.Inventory,baseballs!,director); + if(scooterSmoke)scooterFixture=new(simulation!,playerBinding!,director,interactions!,level!.Code); if(grapplerSmoke)grapplerFixture=new(simulation!,playerBinding!,director,interactions!); if(rocketSmoke)rocketFixture=new(simulation!,playerBinding!,director,interactions!); if (bubbleSmoke) bubbleFixture = new(simulation!,interactions!.Inventory); @@ -820,6 +854,12 @@ internal static class Program if (practice.Active) practice.Key(17, Vector2.Zero); playerBinding?.ResetVehicle();simulation.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!); rocketship?.Reset(); + if(scooter!=null) + { + var behind=simulation.ActorRoot+RocketOrientation.Rotate(new(0,0,-250),new(0,simulation.Yaw,0)); + var ray=OriginalCameraRay.FromRouteScene(world,level!.Code); + director!.EnsureCompanion(ray.TraceGeometry(simulation.ActorRoot,behind)==null?behind:originalStart!.Position,Vector3.Zero); + } interactions?.Reset(); mechanisms?.Reset(); gadgets?.Reset(); baseballs?.Reset(); mouseFire = false; director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0)); } @@ -920,6 +960,11 @@ internal static class Program debugMenu.Message=rocketship?.Mounted==true?"ROCKETSHIP EQUIPPED - ARROWS FLY, ENTER/T TURN, R ROLL": "ROCKETSHIP GIVEN - SELECT ITS PRACTICE TILE TO FLY IN VR02"; break; + case DebugAction.GiveScooter when interactions != null: + interactions.Inventory.SetState(0,4,1);interactions.Inventory.SelectGadget(4); + debugMenu.Message=scooter?.Spawned==true?"SCOOTER SUMMONED AT GODDARD - WALK INTO IT TO MOUNT": + "SCOOTER GIVEN - AVAILABLE IN VR05 AND OUTSIDE"; + break; case DebugAction.GiveGrappler when interactions != null: interactions.Inventory.SetState(0,7,1);interactions.Inventory.SelectGadget(7); debugMenu.Message=simulation?.GadgetMode==7?"GRAPPLER EQUIPPED - FIRE ATTACH/REEL, JUMP DETACH": @@ -990,6 +1035,11 @@ internal static class Program } while (running) { + scooterFixture?.BeforeFrame(count,(key,down)=> + { + var e=new Sdl.Event{Type=down?Sdl.KeyDown:Sdl.KeyUp,Scancode=key,Down=down?(byte)1:(byte)0}; + if(!Sdl.SDL_PushEvent(ref e))throw new InvalidOperationException(Sdl.Error); + },headless); grapplerFixture?.BeforeFrame(count,(key,down)=> { var e=new Sdl.Event{Type=down?Sdl.KeyDown:Sdl.KeyUp,Scancode=key,Down=down?(byte)1:(byte)0}; @@ -1061,6 +1111,8 @@ internal static class Program } while (!headless && Sdl.SDL_PollEvent(out var e)) { + if(scooterSmoke&&e.Type==Sdl.KeyDown) + sawScooterKeys|=e.Scancode switch{81=>1,82=>2,80=>4,225=>8,43=>16,60=>32,21=>64,_=>0}; if(grapplerSmoke&&e.Type==Sdl.KeyDown) sawGrapplerKeys|=e.Scancode switch{80=>1,224=>2,82=>4,225=>8,60=>16,_=>0}; if(rocketSmoke&&e.Type==Sdl.KeyDown) @@ -1193,12 +1245,13 @@ internal static class Program } } if (debugMenu.Open) animationStarted += elapsed; - if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke || grapplerSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke)) + if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke || grapplerSmoke || scooterSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke)) { - var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke || grapplerSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed); + var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || baseballSmoke || rocketSmoke || grapplerSmoke || scooterSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed); for (var step = 0; step < steps; step++) { var input = carlSmoke || controlPhaseSmoke ? new PlayerInput(true, false, true, false, true) + : scooterSmoke && headless ? ScooterSmoke.Input(count,level!.Code) : grapplerSmoke && headless ? GrapplerSmoke.Input(count) : rocketSmoke && headless ? RocketshipSmoke.Input(count) : baseballSmoke && headless ? BaseballSmoke.Input(count) @@ -1220,6 +1273,7 @@ internal static class Program bool acceptsInput; if (playerBinding != null) acceptsInput = playerBinding.Step(input); else { simulation.Step(input); acceptsInput = true; } + scooterFixture?.Received(input); grapplerFixture?.Received(input); rocketFixture?.Received(input); gadgets?.StepTimers(FixedStepClock.Step); @@ -1235,7 +1289,7 @@ internal static class Program if (!simulation.Noclip) { director?.Touch(level!.Player!.Tag!, simulation.ActorRoot); - interactions?.Update(simulation.ActorRoot, simulation.InteractionRadius,rocketship is{Mounted:true}?rocketship.Actor:null); + interactions?.Update(simulation.ActorRoot, simulation.InteractionRadius,rocketship is{Mounted:true}?rocketship.Actor:scooter is{Mounted:true}?scooter.Actor:null); } if (practice.Active) { keys.Clear(); mouseJump = false; stepClock.Reset(); break; } if (!simulation.Noclip) mechanisms?.Update(simulation.ActorRoot, simulation.InteractionRadius); @@ -1278,6 +1332,11 @@ internal static class Program view = Matrix4x4.CreateLookAtLeftHanded(simulation.CameraEye, simulation.CameraTarget, Vector3.UnitY); renderEye = simulation.CameraEye; renderTarget = simulation.CameraTarget; } + if(!inspecting&&scooter is{Mounted:true}) + { + renderEye=scooter.CameraEye;renderTarget=scooter.CameraTarget; + view=Matrix4x4.CreateLookAtLeftHanded(renderEye,renderTarget,Vector3.UnitY); + } if(!inspecting&&rocketship is{Mounted:true}) { renderEye=rocketship.CameraEye;renderTarget=rocketship.CameraTarget; @@ -1300,6 +1359,7 @@ internal static class Program if(rocketship!=null)rocketshipVisuals?.Update(mesh,rocketship,rocketship.FrameSteps/60d,simulation!.Appearance); if(simulation?.Grappler is{} grapplerRender)grapplerVisuals?.Update(mesh,grapplerRender,simulation.ActorRoot, new(simulation.Pitch,simulation.Yaw,simulation.Roll),poseTime,simulation.Appearance,renderEye,renderTarget); + if(scooter!=null)scooterVisuals?.Update(mesh,scooter,scooter.FrameSteps/60d,simulation!.Appearance); spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh); objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && director is { Controlled: true, InventoryEnabled: true }); @@ -1334,6 +1394,7 @@ internal static class Program : simulation?.Bubble.Collapsing==true ? "FADE" : "OFF", BaseballState=simulation==null?"OFF":$"{(simulation.Baseball.Equipped?"ON":"OFF")} AIM {simulation.Baseball.SavedPitch:F1} PENDING {simulation.Baseball.PendingThrow} THROWS {simulation.Baseball.Throws}", GrapplerState=simulation?.Grappler is{} g?$"{(g.Attached?"ON":"OFF")} LEN {g.Memory.Length:F1} FIRST {g.Memory.FirstLength:F1} HIT {g.Contacts}":null, + ScooterState=scooter==null?null:$"{(scooter.Mounted?"RIDE":scooter.Spawned?"PARK":"OFF")} SPEED {scooter.Steering.Speed:F1} WHEELS {scooter.FrontSupports}/{scooter.RearSupports}", RocketshipState=rocketship==null?null:$"{(rocketship.Mounted?"ON":"OFF")} SPEED {rocketship.Steering.Speed:F1} VY {rocketship.Velocity.Y:F1} HIT {rocketship.Contacts}", BodyRadius = simulation?.InteractionRadius ?? 60, BodyFactor=simulation?.BodyFactor ?? 1.265f, Objective = interactions?.CurrentObjective ?? 0, ObjectiveTime = objectivePanel?.Elapsed ?? 0, @@ -1366,7 +1427,7 @@ internal static class Program } if (simulation != null && characterDraw != null) { - characterDraw.Visible=rocketship?.Mounted!=true && simulation.Grappler?.SwingPose!=true; + characterDraw.Visible=rocketship?.Mounted!=true && scooter?.Mounted!=true && simulation.Grappler?.SwingPose!=true; PlayerGadgetMaterial.Apply(characterDraw,simulation.Appearance); var color=simulation.Appearance.Color; for(var i=0;i + + + + diff --git a/tests/GamePort.ScooterTests/GamePort.ScooterTests.csproj b/tests/GamePort.ScooterTests/GamePort.ScooterTests.csproj new file mode 100644 index 0000000..a2f5869 --- /dev/null +++ b/tests/GamePort.ScooterTests/GamePort.ScooterTests.csproj @@ -0,0 +1,10 @@ + + Exenet10.0 + enableenablefalse + + + + + + + diff --git a/tests/GamePort.ScooterTests/Program.cs b/tests/GamePort.ScooterTests/Program.cs new file mode 100644 index 0000000..a06aad9 --- /dev/null +++ b/tests/GamePort.ScooterTests/Program.cs @@ -0,0 +1,155 @@ +using System.Numerics; +using System.Text.Json; +using GamePort.Assets; +using GamePort.Game; +using GamePort.Application; + +var tests=new(string,Action)[]{("copied-original drive/input/facing/terrain observations",Original), + ("selection summons at Goddard, strict contact mounts",Mount), + ("outside normal tile drives, steers, brakes and jumps",Outside), + ("actual wheel supports and source offsets",Wheels), + ("front-door impact owns throttle for four seconds then recovers",Wall), + ("unmount raises40, restores Goddard and stops engine",Release), + ("camera uses new-eye aim, distance gains and sphere delegate",Camera), + ("cutscene/noclip/reset release control and sound",Lifecycle), + ("actual tutorial RETURN accepts the passenger and cleans vehicle",Return), + ("original vehicle/wheel/rider geometry stays unit scale",Visuals), + ("outside companion follows, freezes while summoned, and returns near Jimmy",Companion), +}; +foreach(var(name,test)in tests){test();Console.WriteLine("PASS "+name);}Console.WriteLine($"Scooter integration: {tests.Length} groups passed."); +static void Original() +{ + using var doc=JsonDocument.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory,"original-motion-reference.json"))); + int count=0; + foreach(var c in doc.RootElement.GetProperty("cases").EnumerateArray()) + { + var p=c.GetProperty("input").EnumerateArray().Select(v=>v.GetSingle()).ToArray(); + var o=c.GetProperty("observed").EnumerateArray().Select(v=>v.GetSingle()).ToArray();var name=c.GetProperty("name").GetString()!; + switch(c.GetProperty("kind").GetString()) + { + case "DRIVE": + var d=ScooterMotion.Apply(new(p[0],p[6],Reverse:p[12]!=0,Braking:p[11]!=0,Throttle:p[10]!=0,BrakeTime:p[13]),new(p[1],p[2],p[3]),new(p[4],p[5],0),p[9]!=0,(int)p[7],(int)p[8],p[14],.8f); + Near(d.Steering.Speed,o[0],name+" scalar");NearV(d.Velocity,new(o[1],o[2],o[3]),name+" velocity"); + Near(d.Rotation.Y,o[4],name+" yaw");Near(d.Steering.YawRate,o[5],name+" rate");Near(d.Steering.Blend,o[6],name+" blend");Near(d.Steering.BrakeTime,o[7],name+" timer");break; + case "INPUT": + var s=ScooterMotion.Input(new(p[0],p[1],p[2]!=0,p[3]!=0,p[4]!=0),new(p[5]!=0,p[6]!=0,p[7]!=0,p[8]!=0,false),(int)p[9],p[10]); + Near(s.Speed,o[0],name);Near(s.Angle,o[1],name);Check(s.KeyboardTurn==(o[2]!=0)&&s.Reverse==(o[3]!=0)&&s.Braking==(o[4]!=0)&&s.Throttle==(o[5]!=0),name+" flags");break; + case "NORMAL": + var normal=ScooterWheels.TerrainTarget(new(p[0],p[1],p[2]),p[3]);Near(normal.X,o[0],name+" pitch");Near(normal.Z,o[2],name+" roll");break; + case "FACE":NearV(ScooterWheels.Face(new(p[0],p[1],p[2]),new(p[3],p[4],p[5]),p[6],p[7]),new(o[0],o[1],o[2]),name);break; + case "WALL": + var contact=ScooterMotion.Contact(p[0],new(p[1],p[2],p[3]),Vector3.Zero,new(p[4],p[5],p[6]),new(3,4,5),p[7]!=0,p[8]!=0,p[9]); + Near(contact.Speed,o[0],name+" speed");NearV(new(p[1],p[2],p[3]),new(o[1],o[2],o[3]),name+" no bounce"); + NearV(contact.Acceleration,new(o[4],o[5],o[6]),name+" acceleration");Check(contact.Impact==(o[7]!=0),name+" impact");break; + case "CRASH": + var impact=ScooterMotion.Impact(new(120,100,-60),new(10,20,30),p[0],p[1]); + NearV(impact.Velocity,new(o[0],o[1],o[2]),name+" velocity");NearV(impact.AngularVelocity,new(o[3],o[4],o[5]),name+" angular"); + Near(impact.Time,o[6],name+" timer");Check(impact.Active==(o[7]!=0),name+" expiry");break; + }count++; + } + Check(count==53,"native numeric coverage");Console.WriteLine($"Compared {count} original numeric observations."); +} +static void Mount(){using var f=new Fixture("VR05");f.Summon();Check(f.S.Spawned&&!f.S.Mounted&&f.P.GadgetMode==4,"summon does not mount");f.Mount();Check(f.S.Mounted&&f.D.AuthoredControlledTag==f.S.Actor.Tag&&f.Binding.InventoryControlled,"contact owns control/menu");} +static void Outside() +{ + using var f=new Fixture("LEV1");f.I.Inventory.SetState(0,4,1); + var menu=new GadgetScreen(f.I.Inventory,()=>f.P.GadgetMode); + Check(menu.Toggle(f.Binding.InventoryControlled),"outside gadget panel opens"); + menu.Point(GadgetScreen.Positions[4]+new Vector2(50),"LEV1",0); + Check(menu.Hovered==4&&menu.Activate("LEV1",0)&&f.S.Spawned&&!menu.Open,"ordinary owned tile summons outside"); + f.Mount();var root=f.S.Root; + for(int i=0;i<100;i++)f.Frame(new(true,false,false,false,false)); + Check(f.S.Steering.Speed>200&&Vector3.Distance(root,f.S.Root)>100,"outside ordinary driving"); + float yaw=f.S.Rotation.Y;for(int i=0;i<20;i++)f.Frame(new(true,false,true,false,false)); + Check(f.S.Rotation.Y!=yaw&&f.S.Steering.Angle>0,"outside steering"); + float speed=f.S.Steering.Speed;for(int i=0;i<10;i++)f.Frame(new(false,true,false,false,false)); + Check(f.S.Steering.Speed=2,"real support query accepts wheels");Check(ScooterWheels.Offsets.SequenceEqual(new Vector3[]{new(-3,1,73),new(3,1,73),new(-3,1,-30),new(3,1,-30)}),"four exact narrow offsets");} +static void Wall() +{ + using var f=new Fixture("LEV1","frontdoor");f.Summon();f.Mount(); + for(int i=0;i<180&&!f.S.ImpactActive;i++)f.Frame(new(true,false,false,false,false)); + Check(f.S.Contacts>0&&f.S.ImpactActive&&f.S.Steering.Speed==0,"actual porch wall enters impact"); + for(int i=0;i<240&&f.S.ImpactActive;i++)f.Frame(default); + Check(!f.S.ImpactActive&&f.S.Velocity==Vector3.Zero,"four-second impact recovers"); + for(int i=0;i<20;i++)f.Frame(new(true,false,false,false,false)); + Check(f.S.Steering.Speed>0||f.S.ImpactActive,"throttle resumes after expiry"); +} +static void Release() +{ + using var f=new Fixture("VR05");int starts=0,stops=0,pitches=0;f.S.EngineStarted+=()=>starts++;f.S.EngineStopped+=()=>stops++; + f.S.EngineSpeedChanged+=_=>pitches++;f.Summon();f.Frame(default); + Check(starts==1&&pitches==0,"first engine frame captures base frequency without tuning"); + f.Mount();var root=f.S.Root;var dog=f.D.FindActor("C3DGODDARD")!; + f.I.Inventory.SelectGadget(-1);NearV(f.P.ActorRoot,root+Vector3.UnitY*40,"dismount elevation"); + Check(!f.S.Spawned&&!f.S.Mounted&&f.D.Controlled&&f.P.Velocity==Vector3.Zero&&dog.Visible&&dog.BodyEnabled,"owners restored"); + NearV(dog.Position,root,"Goddard returns at scooter root");Check(starts==1&&stops==1&&!f.S.EnginePlaying,"engine cleanup once"); +} +static void Camera() +{ + var c=ScooterCamera.Follow(Vector3.Zero,Vector3.Zero,new(0,50,-300),.1f); + NearV(c.DesiredEye,new(-30,50,-200),"defaultlocal");NearV(c.Eye,new(-3,50,-290),"near smoothing"); + int calls=0;var clipped=ScooterCamera.Follow(Vector3.Zero,Vector3.Zero,new(0,50,-1000),.1f,(a,b)=>{calls++;Check(a==Vector3.Zero,"sphere starts at root");return b*.8f;}); + Check(calls==1&&clipped.Gain==2.8f,"far gain/clip");var(p,y)=OriginalHeading.Angles(clipped.Look-clipped.Eye); + NearV(Vector3.Normalize(clipped.Target-clipped.Eye),RocketOrientation.Rotate(Vector3.UnitZ,new(p*.02197265625f,y*.02197265625f,0)),"new eye heading"); + var impact=ScooterCamera.Follow(new(100,100,100),Vector3.Zero,new(0,50,-300),.1f,impact:true); + NearV(impact.Eye,new(3,50,-288),"impact XZ-only smoothing");Check(impact.Look==new Vector3(100),"impact aims at root"); +} +static void Lifecycle() +{ + using var f=new Fixture("VR05");f.Summon();f.Mount();f.D.ReleasePlayerGadget();Check(!f.S.Spawned&&!f.S.EnginePlaying&&f.P.GadgetMode==-1,"namedJimmy cleanup"); + f.Summon();f.Mount();f.P.SetNoclip(true);f.Binding.Step(default);Check(!f.S.Spawned&&f.D.Controlled,"noclip releases"); + f.Binding.ResetVehicle();Check(f.S.BodySteps==0&&!f.S.Spawned,"reset"); +} +static void Return() +{ + using var f=new Fixture("VR05");f.I.SetReturnContext("level1b.gam","STARTEXP");f.Summon();f.Mount(); + var portal=f.Level.Entities.First(e=>e.Kind=="LOAD"&&e.Text("LevelName")=="RETURN");LevelTransition? request=null;f.I.Transition+=t=>request=t; + f.P.ApplyAuthoredTransform(portal.Position,f.P.Yaw);f.I.Update(f.P.ActorRoot,60,f.S.Actor); + Check(request is{Returning:true}&&!f.S.Spawned&&f.D.Controlled,"passenger RETURN releases vehicle"); +} +static void Visuals() +{ + using var f=new Fixture("VR05");var visuals=new ScooterVisuals(f.World,"artifacts/extracted");f.Summon();f.Mount(); + visuals.Update(visuals.Mesh,f.S,.1,f.P.Appearance);var vertices=visuals.Mesh.Vertices.Skip(f.World.Vertices.Length).ToArray(); + visuals.Update(visuals.Mesh,f.S,.1,f.P.Appearance);Check(vertices.SequenceEqual(visuals.Mesh.Vertices.Skip(f.World.Vertices.Length)),"repeated render does not accumulate transforms"); + Check(visuals.Mesh.Draws.Count(d=>d.Visible)>f.World.Draws.Count(d=>d.Visible),"body/wheel/rider visible"); + f.I.Inventory.SelectGadget(-1);visuals.Update(visuals.Mesh,f.S,.1,f.P.Appearance);Check(visuals.Mesh.Draws.Skip(f.World.Draws.Length).All(d=>!d.Visible),"helpers hide"); +} +static void Companion() +{ + using var f=new Fixture("LEV1");var jimmy=f.D.FindActor("JIM1")!;var dog=f.D.FindActor("C3DGODDARD")!; + var patrol=new ActorPatrol(dog,f.D.FindActor,(b,dt)=>b with{Position=b.Position+b.Velocity*dt}){FollowPlayer=true}; + patrol.Step(FixedStepClock.Step);Check(patrol.Velocity.Length()>400,"state4 chooses follow velocity"); + var before=dog.Position;patrol.Step(FixedStepClock.Step);Check(dog.Position!=before,"prior velocity moves next body phase"); + f.Summon();before=dog.Position;patrol.Step(FixedStepClock.Step);Check(dog.Position==before,"disabled companion does not drift"); + f.I.Inventory.SelectGadget(-1);Check(dog.MovementEnabled,"unequip resumes companion"); + dog.Position=jimmy.Position+new Vector3(3000,0,0);patrol.Step(FixedStepClock.Step); + NearV(dog.Position,jimmy.Position+RocketOrientation.Rotate(new(0,0,-800),jimmy.Rotation),"far follow warp"); + f.D.EnsureCompanion(jimmy.Position,Vector3.Zero);NearV(dog.Position,jimmy.Position,"explicit reset placement updates existing actor"); +} +static void Check(bool ok,string name){if(!ok)throw new Exception(name);} +static void Near(float a,float b,string name)=>Check(float.IsFinite(a)&&Math.Abs(a-b)<.02f,$"{name}: {a} != {b}"); +static void NearV(Vector3 a,Vector3 b,string name)=>Check(Vector3.Distance(a,b)<.04f,$"{name}: {a} != {b}"); +sealed class Fixture:IDisposable +{ + public GamLevel Level{get;}public Mesh World{get;}public LabSimulation P{get;}public SceneDirector D{get;}public SceneInteractions I{get;}public Scooter S{get;}public PlayerSceneBinding Binding{get;} + public Fixture(string code,string? startTag=null) + { + string name=code=="LEV1"?"level1":"VR05";World=Mesh.LoadSceneJson(AssetPath.Resolve("artifacts/extracted",name+"/scene.json"));Level=GamLevel.Load(AssetPath.Resolve("../Original","gam/"+name+".gam")); + var save=OriginalSave.Load("../Original/NewGame.tsk");var tasks=new TaskStates(save.Tasks);var start=Level.FindStart(startTag)!;D=new(Level,tasks,(_,_)=>0);I=new(D,tasks,save);D.Begin(start,false); + var ray=OriginalCameraRay.FromRouteScene(World,code); + P=new(new(World),new MorphAnimation("artifacts/extracted/animations/jimstop/animation.json").Base,start.Position,start.Rotation.Y, + (a,b)=>ray.Trace(a,b),(a,b)=>ray.TraceGeometry(a,b),code=="VR05"?OriginalStaticCollision.FromRouteScene(World,code):null){LevelCode=code}; + D.SyncActor("JIM1",P.ActorRoot,new(0,P.Yaw,0));D.EnsureCompanion(P.ActorRoot+RocketOrientation.Rotate(new(0,0,-250),new(0,P.Yaw,0)),startTag=="frontdoor"?Vector3.Zero:new(0,P.Yaw,0)); + S=new(D.AddOwnedActor("C3DJEEP","3JEE",Vector3.Zero),World,code);Binding=new(D,P,I.Inventory,"JIM1",scooter:S); + } + public void Summon(){I.Inventory.SetState(0,4,1);I.Inventory.SelectGadget(4);} + public void Frame(PlayerInput input){Binding.Step(input);D.Step(FixedStepClock.Step);} + public void Mount(){for(int i=0;i<120&&!S.Mounted;i++)Frame(new(false,true,false,false,false));if(!S.Mounted)throw new Exception($"Contact mount failed: Jimmy{P.ActorRoot}, Scooter{S.Root}");for(int i=0;i<60;i++)Frame(default);} + public void Dispose(){S.Release();Binding.Dispose();} +} diff --git a/tests/GamePort.ScooterTests/original-motion-reference.json b/tests/GamePort.ScooterTests/original-motion-reference.json new file mode 100644 index 0000000..1a49719 --- /dev/null +++ b/tests/GamePort.ScooterTests/original-motion-reference.json @@ -0,0 +1,1477 @@ +{ + "scope": "Copied original465220/465830/421910/4669F0/473320/476FF0 with synthetic actor/base/wheels/camera/audio and original OMT vector/trig; no original game entrypoint.", + "files": { + "tools/binary/scooter_motion.py": "92247de22b0bb87490fd0e4bc8606780b1662e4d468a329465b034a9d6657f57", + "tools/binary/scooter_motion_probe.c": "8e8f6b1931a0044383dab1313a5635d2d885be96e4381908d2722dc1d27d8149", + "artifacts/scooter-motion-live/scooter_motion_probe.exe": "fc6301e5e381c5236b3c4507a43bbc4653729e797ee25b4679413e6dd159005e", + "artifacts/scooter-motion-live/probe/wine.log": "bc26ec9300aa9ee1b764e9b0400df696bf34dcb0179e747e10dc3bd0d287718b", + "tools/binary/grappler_scalar_probe.c": "c51cc1ecefaf7a90e69a40624fd0e8cd7e01500359c4e67aee6213bb36f4a810" + }, + "cases": [ + { + "kind": "DRIVE", + "name": "rest", + "input": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "launch", + "input": [ + 100.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 100.0, + 0.0, + 0.0, + 100.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "forward", + "input": [ + 300.0, + 0.0, + 0.0, + 300.0, + 0.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 300.0, + 0.0, + 0.0, + 537.600037, + 0.0, + 0.0, + 0.792000055, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "coast", + "input": [ + 300.0, + 0.0, + 0.0, + 300.0, + 0.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 285.0, + 0.0, + 0.0, + 513.0, + 0.0, + 0.0, + 0.800000012, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "turn", + "input": [ + 300.0, + 0.0, + 0.0, + 300.0, + 0.0, + 0.0, + 30.0, + 2.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 284.0, + -23.7430897, + 0.0, + 509.955963, + 6.0, + 60.0, + 0.800000012, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "slowturn", + "input": [ + 80.0, + 0.0, + 0.0, + 80.0, + 0.0, + 0.0, + -30.0, + 1.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 75.7333298, + 1.06874049, + 0.0, + 136.310562, + 359.0, + -12.0, + 0.800000012, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "drift", + "input": [ + 400.0, + 150.0, + 10.0, + 300.0, + 0.0, + 35.0, + 25.0, + 2.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 382.222229, + 18.1413746, + 0.0, + 523.711609, + 40.0, + 50.0, + 0.621627986, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "falling", + "input": [ + 300.0, + 0.0, + -100.0, + 300.0, + 0.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 300.0, + 0.0, + -100.0, + 522.204834, + 0.0, + 0.0, + 0.792000055, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "rising", + "input": [ + 300.0, + 0.0, + 100.0, + 300.0, + 0.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 300.0, + 0.0, + 0.0, + 522.204834, + 0.0, + 0.0, + 0.792000055, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "uphill", + "input": [ + 300.0, + 0.0, + 0.0, + 300.0, + 20.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 282.898987, + 0.0, + 96.7344971, + 495.57605, + 0.0, + 0.0, + 0.800000012, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "downhill", + "input": [ + 300.0, + 0.0, + 0.0, + 300.0, + -20.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 317.101013, + 0.0, + -108.543808, + 540.347778, + 0.0, + 0.0, + 0.749288082, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "reverse", + "input": [ + -300.0, + 0.0, + 0.0, + -300.0, + 0.0, + 0.0, + 30.0, + 2.0, + 2.0, + 1.0, + 0.0, + 1.0, + 1.0, + 0.0, + 0.100000001 + ], + "observed": [ + 0.0, + 0.0, + 0.0, + 0.0, + 354.0, + 60.0, + 0.0, + 0.100000001 + ] + }, + { + "kind": "DRIVE", + "name": "reverse_allowed", + "input": [ + -300.0, + 0.0, + 0.0, + -300.0, + 0.0, + 0.0, + 30.0, + 2.0, + 2.0, + 1.0, + 0.0, + 1.0, + 1.0, + 1.10000002, + 0.100000001 + ], + "observed": [ + -300.0, + -31.4653263, + -0.0, + -298.345337, + 354.0, + 60.0, + 0.0, + 1.20000005 + ] + }, + { + "kind": "DRIVE", + "name": "unsupported", + "input": [ + 300.0, + 0.0, + 0.0, + 300.0, + 0.0, + 0.0, + 30.0, + 2.0, + 2.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 284.0, + 0.0, + 0.0, + 300.0, + 6.0, + 60.0, + 0.0, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "frontnone", + "input": [ + 300.0, + 0.0, + 0.0, + 300.0, + 0.0, + 0.0, + 30.0, + 0.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 284.0, + 0.0, + 0.0, + 511.199982, + 0.0, + 0.0, + 0.800000012, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "onewheel", + "input": [ + 300.0, + 0.0, + 0.0, + 300.0, + 0.0, + 0.0, + 30.0, + 1.0, + 0.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 284.0, + 0.0, + 0.0, + 300.0, + 3.0, + 30.0, + 0.0, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "nowheels", + "input": [ + 300.0, + 0.0, + 0.0, + 300.0, + 0.0, + 0.0, + 30.0, + 0.0, + 0.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 300.0, + 0.0, + 0.0, + 300.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "brakestill", + "input": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 0.0, + 1.0, + 1.0, + 0.0, + 0.100000001 + ], + "observed": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ] + }, + { + "kind": "DRIVE", + "name": "braketimer", + "input": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 0.0, + 1.0, + 1.0, + 1.0, + 0.100000001 + ], + "observed": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.10000002 + ] + }, + { + "kind": "DRIVE", + "name": "negativecoast", + "input": [ + -30.0, + 0.0, + 0.0, + -30.0, + 0.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + -28.5, + -0.0, + -0.0, + -28.5, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "tinycoast", + "input": [ + 0.100000001, + 0.0, + 0.0, + 0.100000001, + 0.0, + 0.0, + 0.0, + 2.0, + 2.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "kind": "DRIVE", + "name": "tick", + "input": [ + 1400.0, + 120.0, + -13.0, + 1200.0, + 5.0, + 179.0, + 40.0, + 2.0, + 2.0, + 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0166666675 + ], + "observed": [ + 1382.68103, + -66.2162399, + 107.215126, + -1612.78662, + 177.666672, + 80.0, + 0.171840072, + 0.0 + ] + }, + { + "kind": "NORMAL", + "name": "flat", + "input": [ + 0.0, + 1.0, + 0.0, + 0.0 + ], + "observed": [ + -0.0, + 345.0, + 0.0 + ] + }, + { + "kind": "NORMAL", + "name": "slopeZ", + "input": [ + 0.0, + 0.939692616, + 0.342020094, + 0.0 + ], + "observed": [ + 341.0, + 0.0, + 0.0 + ] + }, + { + "kind": "NORMAL", + "name": "slopeX", + "input": [ + 0.342020094, + 0.939692616, + 0.0, + 90.0 + ], + "observed": [ + 19.9951172, + 345.0, + 0.0 + ] + }, + { + "kind": "NORMAL", + "name": "slopeXZ", + "input": [ + 0.200000003, + 0.949999988, + 0.200000003, + 45.0 + ], + "observed": [ + -0.0, + 45.0, + 16.8110485 + ] + }, + { + "kind": "INPUT", + "name": "input0", + "input": [ + 300.0, + 10.0, + 1.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 2.0, + 0.100000001 + ], + "observed": [ + 370.0, + 0.0, + 1.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "kind": "INPUT", + "name": "input1", + "input": [ + 300.0, + 10.0, + 1.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 2.0, + 0.100000001 + ], + "observed": [ + 180.0, + 0.0, + 1.0, + 1.0, + 1.0, + 0.0 + ] + }, + { + "kind": "INPUT", + "name": "input2", + "input": [ + 300.0, + 10.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 2.0, + 0.100000001 + ], + "observed": [ + 300.0, + 30.0, + 1.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "kind": "INPUT", + "name": "input3", + "input": [ + 300.0, + 10.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 2.0, + 0.100000001 + ], + "observed": [ + 300.0, + -10.0, + 1.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "kind": "INPUT", + "name": "nosupport", + "input": [ + 300.0, + 10.0, + 1.0, + 0.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 300.0, + 30.0, + 1.0, + 0.0, + 0.0, + 0.0 + ] + }, + { + "kind": "INPUT", + "name": "reverseheld", + "input": [ + 0.0, + 0.0, + 0.0, + 1.0, + 1.0, + 0.0, + 1.0, + 0.0, + 0.0, + 2.0, + 0.100000001 + ], + "observed": [ + -120.0, + 0.0, + 0.0, + 1.0, + 1.0, + 0.0 + ] + }, + { + "kind": "INPUT", + "name": "brakenegative", + "input": [ + -300.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 2.0, + 0.100000001 + ], + "observed": [ + -180.0, + 0.0, + 0.0, + 1.0, + 1.0, + 0.0 + ] + }, + { + "kind": "INPUT", + "name": "both", + "input": [ + 300.0, + 44.0, + 0.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 2.0, + 0.100000001 + ], + "observed": [ + 250.0, + 45.0, + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + { + "kind": "INPUT", + "name": "cap", + "input": [ + 1490.0, + -44.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 1.0, + 2.0, + 0.100000001 + ], + "observed": [ + 1490.0, + -45.0, + 1.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "kind": "WALL", + "name": "head_on", + "input": [ + 600.0, + 0.0, + 13.0, + 600.0, + 0.0, + 0.0, + -1.0, + 0.0, + 1.0, + 0.100000001 + ], + "observed": [ + 0.0, + 0.0, + 13.0, + 600.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "kind": "WALL", + "name": "side", + "input": [ + 600.0, + 600.0, + 13.0, + 0.0, + -1.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.100000001 + ], + "observed": [ + 230.0, + 600.0, + 13.0, + 0.0, + 3.0, + 4.0, + 5.0, + 0.0 + ] + }, + { + "kind": "WALL", + "name": "side_no_throttle", + "input": [ + 600.0, + 600.0, + 13.0, + 0.0, + -1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 600.0, + 600.0, + 13.0, + 0.0, + 3.0, + 4.0, + 5.0, + 0.0 + ] + }, + { + "kind": "WALL", + "name": "glance", + "input": [ + 600.0, + 400.0, + -20.0, + 300.0, + -0.800000012, + 0.0, + -0.600000024, + 0.0, + 1.0, + 0.100000001 + ], + "observed": [ + 230.0, + 400.0, + -20.0, + 300.0, + 3.0, + 4.0, + 5.0, + 0.0 + ] + }, + { + "kind": "WALL", + "name": "slow20", + "input": [ + 10.0, + 0.0, + 13.0, + 20.0, + 0.0, + 0.0, + -1.0, + 0.0, + 1.0, + 0.100000001 + ], + "observed": [ + 230.0, + 0.0, + 13.0, + 20.0, + 3.0, + 4.0, + 5.0, + 0.0 + ] + }, + { + "kind": "WALL", + "name": "reverse", + "input": [ + -300.0, + 0.0, + -13.0, + -300.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.100000001 + ], + "observed": [ + 0.0, + 0.0, + -13.0, + -300.0, + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + { + "kind": "WALL", + "name": "already_crash", + "input": [ + 0.0, + 0.0, + 100.0, + 300.0, + 0.0, + 0.0, + -1.0, + 1.0, + 1.0, + 0.100000001 + ], + "observed": [ + 0.0, + 0.0, + 100.0, + 300.0, + 3.0, + 4.0, + 5.0, + 1.0 + ] + }, + { + "kind": "CRASH", + "name": "begin", + "input": [ + 0.0, + 0.100000001 + ], + "observed": [ + 108.0, + 100.0, + -54.0, + 9.0, + 18.0, + 27.0, + 0.100000001, + 1.0 + ] + }, + { + "kind": "CRASH", + "name": "before_end", + "input": [ + 3.79999995, + 0.100000001 + ], + "observed": [ + 108.0, + 100.0, + -54.0, + 9.0, + 18.0, + 27.0, + 3.89999986, + 1.0 + ] + }, + { + "kind": "CRASH", + "name": "equal_end", + "input": [ + 3.9000001, + 0.100000001 + ], + "observed": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 4.0, + 0.0 + ] + }, + { + "kind": "CRASH", + "name": "after_end", + "input": [ + 4.0, + 0.100000001 + ], + "observed": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 4.0999999, + 0.0 + ] + }, + { + "kind": "FACE", + "name": "ordinary", + "input": [ + 10.0, + 20.0, + 30.0, + 0.0, + 30.0, + 0.0, + 5.0, + 0.100000001 + ], + "observed": [ + 5.0, + 25.0, + 15.0 + ] + }, + { + "kind": "FACE", + "name": "seam", + "input": [ + 359.0, + 359.0, + 359.0, + 1.0, + 1.0, + 1.0, + 2.0, + 0.100000001 + ], + "observed": [ + 359.399994, + 359.399994, + 359.399994 + ] + }, + { + "kind": "FACE", + "name": "small", + "input": [ + 0.100000001, + 0.100000001, + 0.100000001, + 0.0, + 0.0, + 0.0, + 2.0, + 0.100000001 + ], + "observed": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "kind": "NORMAL", + "name": "slopeYaw0", + "input": [ + 0.200000003, + 0.949999988, + 0.200000003, + 0.0 + ], + "observed": [ + 349.0, + 45.0, + 11.887207 + ] + }, + { + "kind": "NORMAL", + "name": "slopeYaw1", + "input": [ + 0.200000003, + 0.949999988, + 0.200000003, + 90.0 + ], + "observed": [ + 11.887207, + 45.0, + 11.887207 + ] + }, + { + "kind": "NORMAL", + "name": "slopeYaw2", + "input": [ + 0.200000003, + 0.949999988, + 0.200000003, + 180.0 + ], + "observed": [ + 11.887207, + 45.0, + 349.0 + ] + }, + { + "kind": "NORMAL", + "name": "slopeYaw3", + "input": [ + 0.200000003, + 0.949999988, + 0.200000003, + 270.0 + ], + "observed": [ + 349.0, + 45.0, + 349.0 + ] + } + ], + "source_sha256": "f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8", + "ranges": [ + { + "va": "0x421910", + "file_offset": "0x21910", + "length": 660, + "sha256": "a5a0cd543bf833aa87a896c33144c4d374bb55aae7d7726619011ce6b3611ebc" + }, + { + "va": "0x467000", + "file_offset": "0x67000", + "length": 69, + "sha256": "d4201c88903b9b9a2537775af68150432e67d63a6a31b65c19fd78851163f96a" + }, + { + "va": "0x4669f0", + "file_offset": "0x669f0", + "length": 250, + "sha256": "47fa3391722f640dd7dbf2aa128e23abeefc5bc43fbeca01aa663fd397f31231" + }, + { + "va": "0x458890", + "file_offset": "0x58890", + "length": 368, + "sha256": "a271523b34f868e827b5ebc0c46557f4052db8d1d9972361c6a559fd97f220cd" + }, + { + "va": "0x473320", + "file_offset": "0x73320", + "length": 538, + "sha256": "abe0858601f076cc8024abd935efaaf595a1a2232640837e628fe8b92eb33cb1" + }, + { + "va": "0x465220", + "file_offset": "0x65220", + "length": 1549, + "sha256": "22a766ca5ccd38bcb524d75b1620dfd4718b2ddef2997dedae3f6f84d0984ec8" + }, + { + "va": "0x465830", + "file_offset": "0x65830", + "length": 1486, + "sha256": "62cb4e87ab784d45a13fc763cb79b00d23942a95776568209cbd2b0b625f191f" + }, + { + "va": "0x421c10", + "file_offset": "0x21c10", + "length": 231, + "sha256": "7461aaff87634a270874304ad4a4618fdc020c3643cc21d605d5cf3b4581820e" + }, + { + "va": "0x476ff0", + "file_offset": "0x76ff0", + "length": 1184, + "sha256": "fb184f561d9aace113da3a8bff9dd2d2effceb9233507aeb1018b5cbde82cb94" + }, + { + "va": "0x4723f0", + "file_offset": "0x723f0", + "length": 48, + "sha256": "ae10074b5ae2ff3d2d2ce8c16358476acdba2f2a166be8ad5c9f05e3f55ffc23" + }, + { + "va": "0x472480", + "file_offset": "0x72480", + "length": 240, + "sha256": "406c3904538abe07d88ca440e39ca56c00765d0871943991ba7b792da4803c16" + }, + { + "va": "0x472b10", + "file_offset": "0x72b10", + "length": 256, + "sha256": "ee9516aef07738fcf7da370af74185f7522686759218ad1bf4d93be46f0c28b2" + }, + { + "va": "0x467080", + "file_offset": "0x67080", + "length": 2368, + "sha256": "20d60b584557eb5e741f6d3193a26f4daae0c54b5071263603ff67d9ac4dd74a" + }, + { + "va": "0x468020", + "file_offset": "0x68020", + "length": 736, + "sha256": "1b78c5c5f65c52f47b1f4b1f6ae4989be939a70f6aa0e64c6a19be591f4a766b" + }, + { + "va": "0x412f90", + "file_offset": "0x12f90", + "length": 160, + "sha256": "2a23a8162fe05d579aadc9adf68f44b391537dd33bdd63903fdf3988b9159979" + }, + { + "va": "0x466af0", + "file_offset": "0x66af0", + "length": 64, + "sha256": "22b691c52bd1e17ee95cf264386fef3f8da3f8e662b0cc89c80c6c170bbff73e" + }, + { + "va": "0x425120", + "file_offset": "0x25120", + "length": 80, + "sha256": "c73a4c15f300f13f85919667faac12fe83763864d6a1e9e94117b7ce9d231091" + }, + { + "va": "0x41e0f9", + "file_offset": "0x1e0f9", + "length": 255, + "sha256": "81f21789bcac96e27c148a30f23bbd0d743a91f3e4c1c9b14ff266719dbb0aee" + }, + { + "va": "0x41e2f0", + "file_offset": "0x1e2f0", + "length": 176, + "sha256": "5d30469dcfd03cab530a9389d3854fa3d6b1aebfe9a042cf14b807cd9b2e1d94" + }, + { + "va": "0x408e40", + "file_offset": "0x8e40", + "length": 464, + "sha256": "a2e979550104a2a9615c28b8b187fe9c33e840d043d7d52a1774763ee9398ee8" + } + ], + "table_quarter": { + "sin": 1, + "cos": 0 + } +} diff --git a/tests/test_scooter_motion.py b/tests/test_scooter_motion.py new file mode 100644 index 0000000..d26bebd --- /dev/null +++ b/tests/test_scooter_motion.py @@ -0,0 +1,45 @@ +"""Identity and provenance for copied-original Scooter numeric observations.""" +from pathlib import Path +import collections +import hashlib +import json +import math +import sys +import unittest +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'tools/binary')) +from scooter_motion import collect +from checkpoint_script_state import read_va +from pe_inspect import PE + +class ScooterMotionEvidence(unittest.TestCase): + def test_source_identity_ranges_and_offsets(self): + source=collect(ROOT.parent/'Original') + fixture=json.loads((ROOT/'tests/GamePort.ScooterTests/original-motion-reference.json').read_text()) + self.assertEqual(source['sha256'],fixture['source_sha256']) + self.assertEqual(source['motion_ranges'],fixture['ranges']) + self.assertEqual(len(source['motion_ranges']),20) + for span in fixture['ranges']: + self.assertEqual(int(span['file_offset'],16),int(span['va'],16)-0x400000) + + def test_generator_provenance_and_complete_native_cases(self): + fixture=json.loads((ROOT/'tests/GamePort.ScooterTests/original-motion-reference.json').read_text()) + for name,digest in fixture['files'].items(): + # Generated binaries/logs are identified, but not required in a fresh checkout. + if name.startswith('tools/'): + self.assertEqual(hashlib.sha256((ROOT/name).read_bytes()).hexdigest(),digest) + self.assertEqual(len(digest),64) + self.assertEqual(collections.Counter(c['kind'] for c in fixture['cases']), + dict(DRIVE=22,INPUT=9,NORMAL=8,FACE=3,WALL=7,CRASH=4)) + self.assertEqual(len({(c['kind'],c['name']) for c in fixture['cases']}),53) + self.assertTrue(all(math.isfinite(v) for c in fixture['cases'] for k in ('input','observed') for v in c[k])) + self.assertEqual(fixture['table_quarter'],dict(sin=1,cos=0)) + + def test_camera_face_only_flag_and_vehicle_body_overrides(self): + pe=PE(ROOT.parent/'Original/Neutron.exe') + self.assertEqual(read_va(pe,0x413870,2),bytes.fromhex('6a00')) + # Explicit prevent-lowering true, bounce false; neither comes from Jimmy. + self.assertEqual(read_va(pe,0x464c75,5),bytes.fromhex('e8f6c20000')) + self.assertEqual(read_va(pe,0x464c7d,5),bytes.fromhex('e80ec40000')) + +if __name__=='__main__':unittest.main() diff --git a/tests/test_scooter_resources.py b/tests/test_scooter_resources.py index 85369dd..5c429c8 100644 --- a/tests/test_scooter_resources.py +++ b/tests/test_scooter_resources.py @@ -1,3 +1,4 @@ +"""Exact original Scooter resources, material links and source-pivot expansion.""" from pathlib import Path import hashlib import json @@ -9,90 +10,122 @@ from unittest.mock import patch ROOT = Path(__file__).resolve().parents[1] ORIGINAL = ROOT.parent/'Original' sys.path.insert(0, str(ROOT/'tools/extractors')) +sys.path.insert(0, str(ROOT/'tools/binary')) +from scooter_resources import (CANVASES, CLIPS, JIMMY_RGBA_SHA256, SOURCES, export_scooter) from ase import expand_mesh, read_ase from entities import resolve_asset -from omt import FormatError -from png import read_png -from scooter_resources import SOURCES, export_scooter +from omt import Database, FormatError, read_canvas, read_shape +from pe_inspect import PE +from checkpoint_script_state import read_va -@unittest.skipUnless(ORIGINAL.exists(), 'Original assets are local integration fixtures') +@unittest.skipUnless(ORIGINAL.exists(), 'Original resources are local fixtures') class ScooterResourceTests(unittest.TestCase): - def test_original_shape_material_links_and_pixels(self): + def test_exact_omt_shapes_canvas_pixels_and_material_links(self): with tempfile.TemporaryDirectory() as directory: - output = Path(directory)/'scooter' - manifest = export_scooter(ORIGINAL, output) - self.assertEqual(manifest, json.loads((output/'scooter.json').read_text())) + out = Path(directory)/'scooter'; manifest = export_scooter(ORIGINAL, out) + self.assertEqual(manifest, json.loads((out/'scooter.json').read_text())) self.assertEqual(manifest['sources'], SOURCES) - self.assertEqual([s['triangles'] for s in manifest['shapes']], [176, 56]) - for identity, expected_canvas in ((0, 1), (1, 0)): - scene = json.loads((output/f'shape_{identity}/scene.json').read_text()) - self.assertEqual(len(scene['materials']), 1) - self.assertEqual(scene['materials'][0]['texture'], dict(type='Canv', id=expected_canvas)) - texture = scene['textures'][0] - self.assertEqual(texture['id'], expected_canvas) - image = read_png(output/f'shape_{identity}'/texture['png']) - self.assertEqual(image['rgba'], (output/f'shape_{identity}'/texture['path']).read_bytes()) - wheel = json.loads((output/'shape_1/scene.json').read_text()) - self.assertIn(-1, [m['material'] for m in wheel['meshes']]) - self.assertEqual((output/'jimycarl.rgba').read_bytes(), - read_png(resolve_asset(ORIGINAL, 'png/jimycarl.png'))['rgba']) + for id_, name, offset, size, width, height, digest in CANVASES: + self.assertEqual(hashlib.sha256((out/f'canvas_{id_}.rgba').read_bytes()).hexdigest(), digest) + self.assertEqual((out/f'canvas_{id_}.rgba').stat().st_size, width*height*4) + body = json.loads((out/manifest['bodyMesh']).read_text()) + wheel = json.loads((out/manifest['wheelMesh']).read_text()) + self.assertEqual((len(body['vertices']), len(body['indices'])), (176*3, 176*3)) + self.assertEqual((len(wheel['vertices']), len(wheel['indices'])), (56*3, 56*3)) + for mesh in (body, wheel): + self.assertEqual({m['id']:m['texture']['id'] for m in mesh['materials']}, {0:1,1:0}) + self.assertTrue(all((out/Path(manifest['bodyMesh']).parent/t['path']).is_file() for t in mesh['textures'])) + self.assertEqual([s['materialPolygons'] for s in manifest['shapes']], [{'0':176},{'1':28,'null':28}]) + self.assertEqual(sum(p['materialId'] is None for p in wheel['collisionPolygons']),28) - def test_jimmy_exact_base_topology_and_morph_positions(self): + def test_original_mesh_pivots_vertices_uvs_normals_and_null_draws_preserved(self): + database = Database(resolve_asset(ORIGINAL, 'omt/scooter.omt')) with tempfile.TemporaryDirectory() as directory: - output = Path(directory)/'scooter' - export_scooter(ORIGINAL, output) - base = read_ase(resolve_asset(ORIGINAL, 'ASE/jimstop.ASE'))['objects'][0]['samples'][0] - for stem in ('jimscooter', 'jimscooterstop'): - source = read_ase(resolve_asset(ORIGINAL, f'ASE/{stem}.ASE')) - animation = json.loads((output/stem/'animation.json').read_text()) - self.assertEqual((animation['framesPerSecond'], animation['ticksPerFrame']), (10, 480)) - self.assertEqual([f['time'] for f in animation['frames']], [0, 480]) - self.assertEqual(animation['sha256'], source['sha256']) - for index, sample in enumerate(source['objects'][0]['samples']): - expected = expand_mesh(dict(sample, faces=base['faces'], uvs=base['uvs'], - textureFaces=base['textureFaces'])) - actual = json.loads((output/stem/animation['frames'][index]['path']).read_text()) - self.assertEqual(actual['vertices'], [list(v) for v in expected['vertices']]) - self.assertEqual(actual['uvs'], [list(v) for v in expected['uvs']]) + out=Path(directory)/'scooter';m=export_scooter(ORIGINAL,out) + for metadata in m['shapes']: + entry=next(e for e in database.entries if e.type=='3DSh' and e.id==metadata['shapeId']) + source=read_shape(database.payload(entry));actual=json.loads((out/metadata['path']).read_text()) + expected_vertices=[];expected_uvs=[];expected_normals=[] + for poly in source['polygons']: + for corner in poly['corners']: + expected_vertices.append(list(source['vertices'][corner['vertex']])) + expected_uvs.append(list(corner['uv'])) + ni=corner['normal'];expected_normals.append(list(source['normals'][ni] if ni str: + return hashlib.sha256(data).hexdigest() def _json(path: Path, value): path.write_text(json.dumps(value, separators=(',', ':'), allow_nan=False)+'\n', encoding='utf-8') +def _shape_scene(shape: dict, entry, materials: list, textures: list) -> dict: + """Same source corner/triangle-fan expansion as omt.export_scene, one shape.""" + scene = dict(source='scooter.omt', sha256=SOURCES['omt/scooter.omt'], + coordinates='Original OMT coordinates and pivot, unchanged', vertices=[], uvs=[], normals=[], + indices=[], meshes=[], materials=materials, textures=textures, collisionPolygons=[], warnings=[]) + names = {m['id']: m['name'] for m in materials} + for polygon_index, poly in enumerate(shape['polygons']): + first = len(scene['vertices']); first_index = len(scene['indices']) + link = poly['material']; material = link['id'] if link else -1 + for corner in poly['corners']: + scene['vertices'].append(shape['vertices'][corner['vertex']]) + scene['uvs'].append(corner['uv']) + normal = corner['normal'] + scene['normals'].append(shape['normals'][normal] if normal < len(shape['normals']) else poly['normal']) + for i in range(1, len(poly['corners'])-1): + scene['indices'].extend((first, first+i, first+i+1)) + scene['collisionPolygons'].append(dict(shapeId=entry.id, polygonIndex=polygon_index, + normal=poly['normal'], materialName=names.get(material), materialId=material if link else None)) + if scene['meshes'] and scene['meshes'][-1]['material'] == material: + scene['meshes'][-1]['indexCount'] += len(scene['indices'])-first_index + else: + scene['meshes'].append(dict(name=entry.name, shapeId=entry.id, + firstIndex=first_index, indexCount=len(scene['indices'])-first_index, material=material)) + if len(poly['corners']) != 3: + raise FormatError('Scooter source topology unexpectedly needs fan triangulation') + return scene + + def export_scooter(original: Path, output: Path) -> dict: original, output = original.resolve(), output.resolve() if output.is_relative_to(original) or original.is_relative_to(output): raise ValueError('Output must be separate from the original installation') - # Existing descendants are checked before any helper writes into them. if output.exists() and any(p.is_symlink() for p in output.rglob('*')): raise ValueError('Generated Scooter paths must not contain symlinks') paths = {name: resolve_asset(original, name) for name in SOURCES} for name, path in paths.items(): - if hashlib.sha256(path.read_bytes()).hexdigest() != SOURCES[name]: + if digest(path.read_bytes()) != SOURCES[name]: raise FormatError(f'Unexpected original Scooter source identity: {name}') + clips = {name: read_ase(paths[f'ASE/{name}.ASE']) for name in (*CLIPS, 'jimstop')} + base = clips['jimstop']['objects'][0]['samples'][0] + if len(base['vertices']) != 426 or len(base['faces']) != 814 or not base['textureFaces']: + raise FormatError('Jimmy source base lacks exact compatible textured topology') + for stem in CLIPS: + clip = clips[stem] + if len(clip['objects']) != 1: + raise FormatError('Unexpected Scooter rider object count') + samples = clip['objects'][0]['samples'] + if tuple(s['time'] for s in samples) != (0, 480) or any( + (len(s['vertices']), len(s['faces']), len(s['uvs']), len(s['textureFaces'])) != (426, 814, 0, 0) for s in samples): + raise FormatError('Unexpected Scooter rider source samples/topology') + jimmy = read_png(paths['png/jimycarl.png']) + if (jimmy['width'], jimmy['height'], digest(jimmy['rgba'])) != (256, 256, JIMMY_RGBA_SHA256): + raise FormatError('Unexpected Jimmy atlas pixels') database = Database(paths['omt/scooter.omt']) - shapes = {} - for identity, expected in ((0, ('goddard01', 98, 176)), (1, ('wheel', 32, 56))): - entry = next(e for e in database.entries if e.type == '3DSh' and e.id == identity) - shape = read_shape(database.payload(entry)) - if (entry.name, len(shape['vertices']), len(shape['polygons'])) != expected: - raise FormatError('Unexpected original Scooter shape metadata') - shapes[identity] = shape - animations = {name: read_ase(path) for name, path in paths.items() if name.startswith('ASE/')} - for name, animation in animations.items(): - expected_count = 195 if 'godscooter' in name else 426 - if len(animation['objects']) != 1 or len(animation['objects'][0]['samples']) != 2: - raise FormatError('Unexpected original Scooter animation objects/samples') - if any(len(s['vertices']) != expected_count for s in animation['objects'][0]['samples']): - raise FormatError('Unexpected original Scooter morph vertex count') - texture_path = resolve_asset(original, 'png/jimycarl.png') - texture = read_png(texture_path) - rgba = texture.pop('rgba') - texture.update(source=texture_path.name, sourceSha256=hashlib.sha256(texture_path.read_bytes()).hexdigest(), - rgbaSha256=hashlib.sha256(rgba).hexdigest(), path='../jimycarl.rgba') - manifest = dict(schema=1, sources=SOURCES.copy(), shapes=[], animations=[], unboundMorphs=[], - bindingPolicy='Resource-only export; caller owns original attachment, transforms and timing') + shapes, textures, materials, pixels = {}, [], [], {} + for entry in database.entries: + payload = database.payload(entry) + if entry.type == '3DSh': + shapes[entry.id] = (entry, read_shape(payload)) + elif entry.type == '3DMa': + materials.append(dict(id=entry.id, name=entry.name, **read_material(payload))) + if set(shapes) != {0, 1} or len(materials) != 2: + raise FormatError('Unexpected Scooter shape/material count') + for id_, name, source_offset, source_bytes, width, height, rgba_sha in CANVASES: + entries = [e for e in database.entries if e.type == 'Canv' and e.id == id_] + if len(entries) != 1: + raise FormatError('Unexpected Scooter texture identity') + entry = entries[0]; canvas = read_canvas(database.payload(entry)) + if (entry.name, entry.offset, entry.size, canvas['width'], canvas['height'], digest(canvas['rgba'])) != ( + name, source_offset, source_bytes, width, height, rgba_sha): + raise FormatError('Unexpected Scooter canvas metadata/pixels') + pixels[id_] = canvas['rgba'] + textures.append(dict(id=id_, name=name, path=f'../canvas_{id_}.rgba', png=f'../canvas_{id_}.png', + width=width, height=height, sourceOffset=source_offset, sourceBytes=source_bytes, + sourceSha256=digest(database.payload(entry)), rgbaSha256=rgba_sha)) + if {m['id']: m['texture']['id'] for m in materials} != {0: 1, 1: 0}: + raise FormatError('Scooter material-to-canvas links changed') + scenes, shape_meta = {}, [] + for id_, name, folder, offset, size, vertices, polygons in SHAPES: + entry, shape = shapes[id_] + if (entry.name, entry.offset, entry.size, len(shape['vertices']), len(shape['polygons'])) != ( + name, offset, size, vertices, polygons): + raise FormatError('Unexpected Scooter source shape metadata') + counts = Counter(str(p['material']['id']) if p['material'] else 'null' for p in shape['polygons']) + if counts != ({'0': 176} if id_ == 0 else {'1': 28, 'null': 28}): + raise FormatError('Scooter source material assignment changed') + scenes[folder] = _shape_scene(shape, entry, materials, textures) + shape_meta.append(dict(shapeId=id_, name=name, path=f'{folder}/scene.json', sourceOffset=offset, + sourceBytes=size, sourceSha256=digest(database.payload(entry)), indexedVertices=vertices, + polygons=polygons, materialPolygons=dict(sorted(counts.items())), + storedSphere=dict(center=list(shape['bounds'][:3]), radius=shape['bounds'][3], + sourceCenterOffset=offset+8, sourceRadiusOffset=offset+20), + bounds=[[min(v[i] for v in shape['vertices']) for i in range(3)], + [max(v[i] for v in shape['vertices']) for i in range(3)]])) + levels = [] + for name in ('gam/VR05.gam', 'gam/level1.gam'): + level = parse(paths[name].read_bytes()) + levels.append(dict(source=paths[name].name, sha256=SOURCES[name], + entities=[dict(ordinal=i, **asdict(e)) for i, e in enumerate(level.entities)])) + # Import the established PE reader only after resource validation; no target execution. + import sys + sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'binary')) + from pe_inspect import PE + from checkpoint_script_state import read_va + pe = PE(paths['Neutron.exe']) + spans = [dict(va=hex(start), fileOffset=hex(pe.offset(start-pe.base)), length=end-start, + purpose=purpose, sha256=digest(read_va(pe, start, end-start))) for start, end, purpose in BINDINGS] + manifest = dict(schema=1, sources=SOURCES.copy(), bodyMesh='body/scene.json', wheelMesh='wheel/scene.json', + scootAnimation='jimscooter/animation.json', stopAnimation='jimscooterstop/animation.json', + shapes=shape_meta, textures=textures, animations=[], levels=levels, + bindings=dict(bodyDatabaseShape=0, wheelDatabaseShape=1, scootAlias='HISCOOT', stopAlias='HISCOOTSTOP', + scootAction='SCOOT', stopAction='SCOOTSTOP', bodyUnlit=True, sourceSpans=spans), + goddardTransformation=dict(source='godscooter.ASE', alias='HISCOOT', indexedVertices=195, polygons=370, + sourceTimes=[0, 161], alternateSource='godscooter2.ASE', + status='Source binding/inventory only; no compatible textured195-vertex base supplied; not active vehicle body'), + bindingPolicy='Exact resources/source pivots. Runtime owns parent/child transforms, wheel spin/support, mounted root, action timing and lifecycle.') output.mkdir(parents=True, exist_ok=True) - for identity in shapes: - folder = f'shape_{identity}' - details = export_omt_model(database, identity, output/folder) - manifest['shapes'].append(dict(id=identity, path=folder+'/scene.json', **details)) - (output/'jimycarl.rgba').write_bytes(rgba) - for stem in ('jimscooter', 'jimscooterstop'): + (output/'jimycarl.rgba').write_bytes(jimmy['rgba']) + for id_, rgba in pixels.items(): + (output/f'canvas_{id_}.rgba').write_bytes(rgba) + entry = next(e for e in textures if e['id'] == id_) + write_png(output/f'canvas_{id_}.png', entry['width'], entry['height'], rgba) + for folder, scene in scenes.items(): + (output/folder).mkdir(parents=True, exist_ok=True) + _json(output/folder/'scene.json', scene) + for stem in CLIPS: animation = export_ase(paths[f'ASE/{stem}.ASE'], output/stem, paths['ASE/jimstop.ASE']) - animation['texture'] = texture + animation['texture'] = dict(path='../jimycarl.rgba', width=256, height=256, + source=paths['png/jimycarl.png'].name, sourceSha256=SOURCES['png/jimycarl.png'], rgbaSha256=JIMMY_RGBA_SHA256) _json(output/stem/'animation.json', animation) - manifest['animations'].append(dict(source=stem+'.ASE', path=stem+'/animation.json')) - for stem in ('godscooter', 'godscooter2'): - animation = animations[f'ASE/{stem}.ASE'] - filename = stem+'-unbound.json' - _json(output/filename, animation) - manifest['unboundMorphs'].append(dict(source=stem+'.ASE', path=filename, - vertices=195, sourceTimes=[s['time'] for s in animation['objects'][0]['samples']], - reason='No matching textured base recovered; OMT body 98 and existing Goddard base 222 differ')) + manifest['animations'].append(dict(source=paths[f'ASE/{stem}.ASE'].name, path=f'{stem}/animation.json', + indexedVertices=426, polygons=814, sourceTimes=[0, 480])) _json(output/'scooter.json', manifest) return manifest -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('original', type=Path) - parser.add_argument('--output', type=Path, required=True) - args = parser.parse_args() +if __name__ == '__main__': + cli = argparse.ArgumentParser(description=__doc__) + cli.add_argument('original', type=Path) + cli.add_argument('--output', type=Path, required=True) + args = cli.parse_args() export_scooter(args.original, args.output) print(f'Original Scooter resources exported: {args.output}/scooter.json') - - -if __name__ == '__main__': - main()