Implement source-backed Scooter vehicle in tutorial and outside
This commit is contained in:
1 parent
8df5e81070
commit
62c07a3d59
44 files changed
+3135
-174
No files matched your search
@@ -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
|
||||
|
||||
@@ -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).
|
||||
@@ -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`
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.**
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
@@ -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).
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+8
-2
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Numerics;
|
||||
using GamePort.Game;
|
||||
namespace GamePort.Application;
|
||||
/// <summary>Ordinary input replay at the authored tutorial/outside start. Extra
|
||||
/// body/input/frame ticks reuse received input; no root, speed or timer seeding.</summary>
|
||||
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<uint,bool> 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;i<ticks;i++)
|
||||
{
|
||||
binding.Step(last);
|
||||
interactions.Update(player.ActorRoot,player.InteractionRadius,scooter.Mounted?scooter.Actor:null);
|
||||
interactions.UpdateEnergy(player.Energy);director.Step(FixedStepClock.Step);extra++;
|
||||
}
|
||||
}
|
||||
public void AfterFrame(int frame)
|
||||
{
|
||||
Console.WriteLine($"Scooter {StageName(frame)}: root={scooter.Root}, rotation={scooter.Rotation}, velocity={scooter.Velocity}, scalar={scooter.Steering.Speed}, supported={scooter.Supported}, wheels={scooter.FrontSupports}/{scooter.RearSupports}, impact={scooter.ImpactActive}, contacts={scooter.Contacts}, jumps={scooter.Jumps}.");
|
||||
if(frame==0)checks[0]=scooter.Spawned&&!scooter.Mounted&&player.GadgetMode==4;
|
||||
if(frame==1)checks[1]=scooter.Mounted&&binding.InventoryControlled&&director.AuthoredControlledTag==scooter.Actor.Tag;
|
||||
if(frame==2)checks[2]=scooter.Mounted&&Vector3.Distance(scooter.Root,mountedRoot)>100&&scooter.Steering.Speed>100;
|
||||
if(frame==3)checks[3]=scooter.Rotation.Y!=yaw&&scooter.Steering.Angle>0;
|
||||
if(frame==4)checks[4]=scooter.Steering.Speed<speed&&scooter.Jumps>0;
|
||||
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};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.Numerics;
|
||||
using System.Text.Json;
|
||||
using GamePort.Assets;
|
||||
using GamePort.Game;
|
||||
namespace GamePort.Application;
|
||||
|
||||
/// <summary>Original scooter.omt shape0 and four shape1 wheels, plus exact
|
||||
/// HISCOOT/HISCOOTSTOP source-pivot morphs. Null-material faces stay undrawn.</summary>
|
||||
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<int,PngImage>(combined.Textures);var ids=new Dictionary<int,int>();
|
||||
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<visual.Source.Vertices.Length;i++)
|
||||
{var v=visual.Source.Vertices[i];v.Position=Vector3.Transform(v.Position,model);destination.Vertices[visual.Offset+i]=v;}
|
||||
}
|
||||
void Pose(Clip clip,bool visible)
|
||||
{
|
||||
clip.Draw.Visible=visible;if(!visible)return;
|
||||
clip.Source.Sample(time,destination.Vertices.AsSpan(clip.Offset,clip.Source.Base.Vertices.Length),
|
||||
RocketOrientation.Model(vehicle.RiderRotation,vehicle.Root,Vector3.One));
|
||||
PlayerGadgetMaterial.Apply(clip.Draw,appearance);var color=appearance.Color;
|
||||
for(int i=0;i<clip.Source.Base.Vertices.Length;i++)destination.Vertices[clip.Offset+i].Color*=new Vector3(color.X,color.Y,color.Z);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,8 @@ public sealed class SceneAudio : IDisposable
|
||||
loops.Add(loopOwner, new(wave.Path, true, Paused, EffectsMuted));
|
||||
}
|
||||
}
|
||||
public void TuneLoop(string owner,Func<int,int> 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();
|
||||
|
||||
@@ -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<length)Queue();}
|
||||
public void Dispose()
|
||||
|
||||
@@ -37,7 +37,8 @@ public sealed class ActorPatrol
|
||||
public float WaitRemaining { get; private set; }
|
||||
public string? CurrentWaypoint => 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<string, DirectorActor?> findActor,
|
||||
Func<PatrolBodyState, float, PatrolBodyState> 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(DestinationDistance<ArrivalDistance)Arrived=true;
|
||||
else if(DestinationDistance>ArrivalDistance*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");
|
||||
|
||||
@@ -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<bool>? 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();
|
||||
|
||||
@@ -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<OrdinaryBodyState,CameraRayPolygon,OrdinaryBodyState>? 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 };
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
using System.Numerics;
|
||||
using GamePort.Assets;
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>Jimmy's owned C3DJEEP, summoned at Goddard and mounted by contact.
|
||||
/// Ordinary source vehicle/wheel profile is admitted in VR05 and outsideLEV1.</summary>
|
||||
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<Vector3> WheelRoots=>wheels.Roots;
|
||||
public IReadOnlyList<Vector3> 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<Vector3,Vector3,float,Vector3>? DynamicRootResolver{get;set;}
|
||||
public event Action? EngineStarted;
|
||||
public event Action? EngineStopped;
|
||||
public event Action<float>? 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();
|
||||
}
|
||||
@@ -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);
|
||||
/// <summary>4130A0 default mode1. Clipping follows smoothing and uses a sphere,
|
||||
/// then look minus NEW eye determines source signed14-bit aim.</summary>
|
||||
public static class ScooterCamera
|
||||
{
|
||||
public static ScooterCameraResult Follow(Vector3 root,Vector3 rotation,Vector3 oldEye,float dt,Func<Vector3,Vector3,Vector3>? 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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
/// <summary>465830 keyboard prefix and465220 ordinary non-AI/non-sprint drive.
|
||||
/// Wheel/body support is observed independently; never fabricated here.</summary>
|
||||
public static class ScooterMotion
|
||||
{
|
||||
public const float Maximum=1485;
|
||||
/// <summary>421910 with the constructor's disabled bounce flag.</summary>
|
||||
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);
|
||||
}
|
||||
/// <summary>4669F0 ordinary enabled-body impact suffix.</summary>
|
||||
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(speed<Maximum)speed=MathF.Min(Maximum,speed+700*dt);reverse=false;}
|
||||
if(rear>0&&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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.Numerics;
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>412A90 four-child setup and467080 post-normal wheel positioning.
|
||||
/// Child support is queried manually; children have no independent integrator.</summary>
|
||||
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<Vector3> Roots=>roots;
|
||||
public IReadOnlyList<Vector3> 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)<gain?desired:current+step;
|
||||
}
|
||||
return new(Axis(rotation.X,target.X),Axis(rotation.Y,target.Y),Axis(rotation.Z,target.Z));
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,7 @@ internal static unsafe class Sdl
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_PutAudioStreamData(nint stream,nint buffer,int length);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern int SDL_GetAudioStreamQueued(nint stream);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetAudioStreamGain(nint stream,float gain);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetAudioStreamFrequencyRatio(nint stream,float ratio);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_DestroyAudioStream(nint stream);
|
||||
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern void SDL_Delay(uint ms);
|
||||
}
|
||||
+83
-10
@@ -33,6 +33,8 @@ internal static class Program
|
||||
catch (Exception error) { Console.Error.WriteLine(error); return 1; }
|
||||
}
|
||||
|
||||
private static int ScooterEngineFrequency(int baseFrequency,float speed)=>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<animations!.Current.Base.Vertices.Length;i++)
|
||||
@@ -1374,6 +1435,12 @@ internal static class Program
|
||||
}
|
||||
renderer.UpdateVertices(mesh.Vertices);
|
||||
renderer.Render(view * projection);
|
||||
if(scooterFixture!=null)
|
||||
{
|
||||
scooterFixture.AfterFrame(count);
|
||||
if(ScooterSmoke.StageName(count) is{} stage&&Option(args,"--screenshot") is{} capture)
|
||||
renderer.SavePpm(Path.ChangeExtension(capture,$".{stage}.ppm"));
|
||||
}
|
||||
if(grapplerFixture!=null)
|
||||
{
|
||||
grapplerFixture.AfterFrame(count);
|
||||
@@ -1678,6 +1745,12 @@ internal static class Program
|
||||
if(!headless)Console.WriteLine($"Baseball SDL keys received: {sawBaseballKeys==15}.");
|
||||
if(!baseballFixture.Passed || !headless && sawBaseballKeys!=15)return 2;
|
||||
}
|
||||
if(scooterFixture!=null)
|
||||
{
|
||||
Console.WriteLine(scooterFixture.Report);
|
||||
if(!headless)Console.WriteLine($"Scooter SDL keys received: {sawScooterKeys==127}.");
|
||||
if(!scooterFixture.Passed||!headless&&sawScooterKeys!=127)return 2;
|
||||
}
|
||||
if(grapplerFixture!=null)
|
||||
{
|
||||
Console.WriteLine(grapplerFixture.Report);
|
||||
|
||||
@@ -85,7 +85,8 @@ Require(allGadgetsView.Lines.Length<=32 && allGadgetsView.Lines[allGadgetsView.S
|
||||
"Last player action remains visible within the widescreen overlay capacity");
|
||||
menu.Key(81);Require(menu.Key(40)==DebugAction.GiveRocketship,"Player tools expose Rocketship after Give All Gadgets");
|
||||
menu.Key(81); Require(menu.Key(40)==DebugAction.GiveGrappler,"Player tools expose Grappler after Rocketship");
|
||||
menu.Key(81); Require(menu.Selected==0,"Player navigation wraps after Grappler");
|
||||
menu.Key(81); Require(menu.Key(40)==DebugAction.GiveScooter,"Player tools grant Scooter for tutorial/outside");
|
||||
menu.Key(81); Require(menu.Selected==0,"Player navigation wraps after Scooter");
|
||||
Console.WriteLine("PASS Give All Gadgets navigation, repeat handling and overlay bounds");
|
||||
|
||||
var original = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original");
|
||||
|
||||
@@ -38,5 +38,9 @@
|
||||
<Compile Include="../../src/GamePort/Game/GrapplerRay.cs" />
|
||||
<Compile Include="../../src/GamePort/Game/RocketOrientation.cs" />
|
||||
<Compile Include="../../src/GamePort/Game/OriginalHeading.cs" />
|
||||
<Compile Include="../../src/GamePort/Game/Scooter.cs"/>
|
||||
<Compile Include="../../src/GamePort/Game/ScooterCamera.cs"/>
|
||||
<Compile Include="../../src/GamePort/Game/ScooterMotion.cs"/>
|
||||
<Compile Include="../../src/GamePort/Game/ScooterWheels.cs"/>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
|
||||
<ItemGroup><Compile Include="Program.cs"/><Compile Include="../../src/GamePort/Assets/*.cs"/>
|
||||
<Compile Include="../../src/GamePort/Game/*.cs"/>
|
||||
<Compile Include="../../src/GamePort/Application/PlayerGadgetMaterial.cs"/>
|
||||
<Compile Include="../../src/GamePort/Application/ScooterVisuals.cs"/>
|
||||
<None Include="original-motion-reference.json" CopyToOutputDirectory="PreserveNewest"/>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -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<speed,"brake");
|
||||
for(int i=0;i<120&&!f.S.Supported;i++)f.Frame(default);
|
||||
if(f.S.Supported){int jumps=f.S.Jumps;f.Frame(new(false,false,false,false,true));Check(f.S.Jumps==jumps+1&&f.S.PendingImpulse.Y==700,"supported jump queues impulse");}
|
||||
Check(f.P.Energy==20,"no invented gadget energy debit");
|
||||
}
|
||||
static void Wheels(){using var f=new Fixture("VR05");f.Summon();for(int i=0;i<100;i++)f.Frame(default);Check(f.S.FrontSupports+f.S.RearSupports>=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();}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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()
|
||||
+103
-70
@@ -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<len(source['normals']) else poly['normal']))
|
||||
self.assertEqual(actual['vertices'],expected_vertices)
|
||||
self.assertEqual(actual['uvs'],expected_uvs)
|
||||
self.assertEqual(actual['normals'],expected_normals)
|
||||
self.assertEqual(actual['indices'],list(range(len(expected_vertices))))
|
||||
wheel=json.loads((out/m['wheelMesh']).read_text())
|
||||
self.assertEqual(sum(d['indexCount'] for d in wheel['meshes'] if d['material']==-1),28*3)
|
||||
|
||||
def test_unbound_morphs_retain_source_161_ticks_and_no_guessed_uvs(self):
|
||||
def test_stored_source_spheres_are_not_actor_radius_or_visual_scale(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory)/'scooter'
|
||||
manifest = export_scooter(ORIGINAL, output)
|
||||
for entry in manifest['unboundMorphs']:
|
||||
morph = json.loads((output/entry['path']).read_text())
|
||||
self.assertEqual((morph['framesPerSecond'], morph['ticksPerFrame']), (30, 160))
|
||||
samples = morph['objects'][0]['samples']
|
||||
self.assertEqual([s['time'] for s in samples], [0, 161])
|
||||
self.assertEqual([len(s['vertices']) for s in samples], [195, 195])
|
||||
self.assertTrue(all(not s['uvs'] and not s['textureFaces'] for s in samples))
|
||||
self.assertEqual(morph['sha256'], hashlib.sha256(
|
||||
resolve_asset(ORIGINAL, 'ASE/'+entry['source']).read_bytes()).hexdigest())
|
||||
m=export_scooter(ORIGINAL,Path(directory)/'scooter')
|
||||
body,wheel=m['shapes']
|
||||
self.assertEqual(body['storedSphere']['radius'],91.31170654296875)
|
||||
self.assertEqual(wheel['storedSphere']['radius'],23.769514083862305)
|
||||
self.assertEqual(body['storedSphere']['sourceRadiusOffset'],124)
|
||||
self.assertEqual(wheel['storedSphere']['sourceRadiusOffset'],92324)
|
||||
self.assertNotIn('actorScale',m['bindings'])
|
||||
self.assertEqual(m['bindings']['bodyDatabaseShape'],0)
|
||||
self.assertEqual(m['bindings']['wheelDatabaseShape'],1)
|
||||
|
||||
def test_original_subtrees_ancestors_and_symlinks_rejected(self):
|
||||
for output in (ORIGINAL, ORIGINAL/'png/generated-scooter', ORIGINAL.parent):
|
||||
with self.subTest(output=output), self.assertRaises(ValueError):
|
||||
export_scooter(ORIGINAL, output)
|
||||
def test_two_rider_morphs_keep_exact_samples_topology_and_opaque_atlas(self):
|
||||
base=read_ase(resolve_asset(ORIGINAL,'ASE/jimstop.ASE'))['objects'][0]['samples'][0]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory)/'scooter'
|
||||
output.mkdir()
|
||||
outside = Path(directory)/'unchanged'
|
||||
outside.write_text('unchanged')
|
||||
for relative in ('scooter.json', 'shape_0', 'jimscooter', 'jimycarl.rgba'):
|
||||
(output/relative).symlink_to(outside)
|
||||
with self.subTest(relative=relative), self.assertRaises(ValueError):
|
||||
export_scooter(ORIGINAL, output)
|
||||
self.assertEqual(outside.read_text(), 'unchanged')
|
||||
(output/relative).unlink()
|
||||
out=Path(directory)/'scooter';m=export_scooter(ORIGINAL,out)
|
||||
self.assertEqual(hashlib.sha256((out/'jimycarl.rgba').read_bytes()).hexdigest(),JIMMY_RGBA_SHA256)
|
||||
for stem in CLIPS:
|
||||
animation=json.loads((out/stem/'animation.json').read_text())
|
||||
self.assertEqual([f['time'] for f in animation['frames']],[0,480])
|
||||
self.assertEqual(animation['texture']['path'],'../jimycarl.rgba')
|
||||
source=read_ase(resolve_asset(ORIGINAL,f'ASE/{stem}.ASE'))['objects'][0]['samples']
|
||||
for sample,frame in zip(source,animation['frames'],strict=True):
|
||||
expected=expand_mesh({**sample,'faces':base['faces'],'textureFaces':base['textureFaces'],'uvs':base['uvs']})
|
||||
actual=json.loads((out/stem/frame['path']).read_text())
|
||||
self.assertEqual(actual['vertices'],[list(p) for p in expected['vertices']])
|
||||
self.assertEqual(actual['uvs'],[list(p) for p in expected['uvs']])
|
||||
self.assertEqual(actual['indices'],expected['indices'])
|
||||
self.assertEqual((len(m['levels'][0]['entities']),len(m['levels'][1]['entities'])),(18,322))
|
||||
self.assertEqual(m['goddardTransformation']['indexedVertices'],195)
|
||||
self.assertEqual(m['goddardTransformation']['sourceTimes'],[0,161])
|
||||
|
||||
def test_changed_source_identity_rejected_before_writes(self):
|
||||
def test_original_binding_spans_and_alias_string_operands(self):
|
||||
pe=PE(resolve_asset(ORIGINAL,'Neutron.exe'))
|
||||
expected=[(0x4214f0,37,'3aa8cb83c0e81fa70622d540015517ecd60549945ace69b6cfe9357641dbd19b'),
|
||||
(0x422c58,40,'92f233fbba67cc7eb63d29614f6d8a04da703169b91b86e53b36ee5d722b2929'),
|
||||
(0x41cdf0,20,'1a0e33a555990de9d997d9fe5dc33af242c3994681e511b3b6f5134857659b82'),
|
||||
(0x468270,42,'cacdf3e512e808601f753b22504a553da79de578b0a792a322ee43966119a838')]
|
||||
for va,length,digest in expected:
|
||||
self.assertEqual(hashlib.sha256(read_va(pe,va,length)).hexdigest(),digest)
|
||||
self.assertEqual(pe.offset(va-pe.base),va-0x400000)
|
||||
for va,string in [(0x4ef104,b'jimscooter.ase\0'),(0x4ef0f0,b'Jimscooterstop.ase\0'),
|
||||
(0x4ee9ec,b'HISCOOT\0'),(0x4ef0e4,b'HISCOOTSTOP\0'),(0x4ee9f4,b'godscooter.ASE\0')]:
|
||||
self.assertEqual(read_va(pe,va,len(string)),string)
|
||||
|
||||
def test_changed_original_or_contract_rejects_before_output(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory)/'scooter'
|
||||
with patch.dict(SOURCES, {'omt/scooter.omt': '0'*64}), self.assertRaises(FormatError):
|
||||
export_scooter(ORIGINAL, output)
|
||||
self.assertFalse(output.exists())
|
||||
out=Path(directory)/'scooter'
|
||||
with patch.dict(SOURCES,{'omt/scooter.omt':'0'*64}):
|
||||
with self.assertRaises(FormatError):export_scooter(ORIGINAL,out)
|
||||
self.assertFalse(out.exists())
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
out=Path(directory)/'scooter'
|
||||
with patch('scooter_resources.CANVASES',((0,'changed',22568,3966,32,32,'0'*64),)):
|
||||
with self.assertRaises(FormatError):export_scooter(ORIGINAL,out)
|
||||
self.assertFalse(out.exists())
|
||||
|
||||
def test_original_and_generated_symlink_paths_rejected(self):
|
||||
for destination in (ORIGINAL, ORIGINAL/'ASE/generated', ORIGINAL.parent):
|
||||
with self.assertRaises(ValueError):export_scooter(ORIGINAL,destination)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
out=Path(directory)/'scooter';out.mkdir();(out/'linked').symlink_to(ORIGINAL,target_is_directory=True)
|
||||
with self.assertRaises(ValueError):export_scooter(ORIGINAL,out)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
def test_export_is_deterministic(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root=Path(directory);export_scooter(ORIGINAL,root/'a');export_scooter(ORIGINAL,root/'b')
|
||||
a={str(p.relative_to(root/'a')):p.read_bytes() for p in (root/'a').rglob('*') if p.is_file()}
|
||||
b={str(p.relative_to(root/'b')):p.read_bytes() for p in (root/'b').rglob('*') if p.is_file()}
|
||||
self.assertEqual(a,b)
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Guarded Scooter drive/input source and copied-code probe preparation."""
|
||||
import argparse,hashlib,json,re,struct,subprocess
|
||||
from pathlib import Path
|
||||
from scooter import collect as scooter_collect
|
||||
from checkpoint_script_state import find_case,read_va
|
||||
from pe_inspect import PE
|
||||
|
||||
RANGES=((0x421910,0x421ba4),(0x467000,0x467045),(0x4669f0,0x466aea),(0x458890,0x458a00),(0x473320,0x47353a),(0x465220,0x46582d),(0x465830,0x465dfe),(0x421c10,0x421cf7),
|
||||
(0x476ff0,0x477490),(0x4723f0,0x472420),(0x472480,0x472570),(0x472b10,0x472c10))
|
||||
EVIDENCE_RANGES=RANGES+((0x467080,0x4679c0),(0x468020,0x468300),
|
||||
(0x412f90,0x413030),(0x466af0,0x466b30),(0x425120,0x425170),
|
||||
(0x41e0f9,0x41e1f8),(0x41e2f0,0x41e3a0),(0x408e40,0x409010))
|
||||
def collect(original):
|
||||
report=scooter_collect(original);pe=PE(find_case(Path(original),'Neutron.exe'))
|
||||
# Only absolute data/IAT references found in decoded disassembly are eligible.
|
||||
targets=set()
|
||||
for start,end in RANGES:
|
||||
result=subprocess.run(['objdump','-d','-Mintel',f'--start-address={start}',f'--stop-address={end}',str(pe.path)],capture_output=True,text=True,check=True)
|
||||
targets.update(int(v,16) for v in re.findall(r'ds:0x([0-9a-f]+)',result.stdout))
|
||||
targets.update((0x48d104,0x48d10c))
|
||||
report['motion_ranges']=[dict(va=hex(start),file_offset=hex(pe.offset(start-pe.base)),length=end-start,
|
||||
sha256=hashlib.sha256(read_va(pe,start,end-start)).hexdigest()) for start,end in EVIDENCE_RANGES]
|
||||
report['motion_relocations']=[]
|
||||
for start,end in RANGES:
|
||||
data=read_va(pe,start,end-start)
|
||||
for target in sorted(targets):
|
||||
for match in re.finditer(re.escape(struct.pack('<I',target)),data):
|
||||
report['motion_relocations'].append(dict(va=start+match.start(),target=target))
|
||||
report['motion_constants']={hex(va):struct.unpack('<d' if wide else '<f',read_va(pe,va,8 if wide else 4))[0]
|
||||
for va,wide in [(0x4d5888,False),(0x48d948,False),(0x49b1f8,False),(0x49fac0,False),(0x4d5880,True),
|
||||
(0x4d5878,False),(0x4d5870,True),(0x4a3144,False)]}
|
||||
return report
|
||||
|
||||
def generate(original,output):
|
||||
output=Path(output).resolve();original=Path(original).resolve()
|
||||
if output.is_relative_to(original) or original.is_relative_to(output):raise ValueError('Separate output required')
|
||||
output.mkdir(parents=True,exist_ok=True);report=collect(original)
|
||||
body=(Path(__file__).with_name('scooter_motion_probe.c')).read_text()
|
||||
body=body.replace('/* RELOCATIONS */',','.join('{0x%x,0x%x}'%(r['va'],r['target']) for r in report['motion_relocations']))
|
||||
(output/'scooter_motion_probe.c').write_text(body)
|
||||
(output/'source.json').write_text(json.dumps(report,indent=2)+'\n');return report
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('original',type=Path);p.add_argument('--generate-probe',type=Path);a=p.parse_args()
|
||||
r=generate(a.original,a.generate_probe) if a.generate_probe else collect(a.original)
|
||||
print(json.dumps(r,indent=2))
|
||||
@@ -0,0 +1,143 @@
|
||||
/* Copied465220 full arithmetic and465830 keyboard input. Synthetic base actor,
|
||||
body properties, wheel support, camera/audio/input; original OMT vector/trig. */
|
||||
#define main unused_grappler_main
|
||||
#include "grappler_scalar_probe.c"
|
||||
#undef main
|
||||
typedef struct{float x,y,z,w;}Vec;
|
||||
static uintptr_t game_table[0x440/4],outer_table[0x180/4],wheel_table[0x220/4];
|
||||
static unsigned char wheels[4][0x200];
|
||||
static Vec velocity,acceleration,angular;static float scalar,friction;static int supported,missing_slot;
|
||||
#define GF(g,o) (*(float*)((g)+(o)))
|
||||
static void TC missing(void*self){fprintf(stderr,"MISSING caller=%x self=%x\n",(unsigned)((unsigned char*)__builtin_return_address(0)-mapped+0x400000),(unsigned)self);require(0,"unexpected virtual call");}
|
||||
static int TC zero(void*self){(void)self;return 0;}
|
||||
static int TC enabled(void*self){(void)self;return 1;}
|
||||
static int TC support(void*self){(void)self;return supported;}
|
||||
static int TC wheel_support(void*self){return ((unsigned char*)self)[4];}
|
||||
static float TC speed(void*self){(void)self;return scalar;}
|
||||
static float TC get_friction(void*self){(void)self;return friction;}
|
||||
static void TC set_speed(void*self,float v){(void)self;scalar=v;}
|
||||
static Vec*TC get_velocity(void*self,Vec*out){(void)self;*out=velocity;return out;}
|
||||
static void TC set_velocity(void*self,float x,float y,float z){(void)self;velocity=(Vec){x,y,z,0};}
|
||||
static void TC set_accel(void*self,float x,float y,float z){(void)self;acceleration=(Vec){x,y,z,0};}
|
||||
static Vec*TC get_angular(void*self,Vec*out){(void)self;*out=angular;return out;}
|
||||
static void TC set_angular(void*self,float x,float y,float z){(void)self;angular=(Vec){x,y,z,0};}
|
||||
static void TC add_angular(void*self,float x,float y,float z){(void)self;angular.x+=x;angular.y+=y;angular.z+=z;}
|
||||
static void TC add_velocity(void*self,float x,float y,float z){(void)self;velocity.x+=x;velocity.y+=y;velocity.z+=z;}
|
||||
static void TC noop_dt(void*self,float dt){(void)self;(void)dt;}
|
||||
static void TC noop(void*self){(void)self;}
|
||||
static void TC mouse(void*self,short*x,short*y){(void)self;*x=*y=0;}
|
||||
static void setup(void){
|
||||
map_source();
|
||||
const struct{uint32_t va,target;} reloc[]={/* RELOCATIONS */};
|
||||
for(unsigned i=0;i<sizeof(reloc)/sizeof(reloc[0]);i++){
|
||||
uint32_t value;memcpy(&value,AT(reloc[i].va),4);require(value==reloc[i].target,"absolute operand");
|
||||
value=(uintptr_t)AT(value);memcpy(AT(reloc[i].va),&value,4);
|
||||
}
|
||||
HMODULE dll=LoadLibraryA("Z:\\work\\game\\OMT2.dll");require(dll!=NULL,"copied OMT2");
|
||||
*(void**)AT(0x48d104)=GetProcAddress(dll,"?quick_magnitude@OMedia3DVector@@QBEMXZ");
|
||||
*(void**)AT(0x48d10c)=GetProcAddress(dll,"?global@OMediaCosSinTable@@2V1@A");
|
||||
require(*(void**)AT(0x48d104)&&*(void**)AT(0x48d10c),"OMT vector exports");
|
||||
float*trig=*(void**)AT(0x48d10c);printf("TABLE quarter sin=%.9g cos=%.9g\n",trig[4096],trig[16385+4096]);
|
||||
const unsigned char ready[]={0xb0,1,0xc3},base[]={0xc2,4,0};
|
||||
memcpy(AT(0x475ca0),ready,3);memcpy(AT(0x462520),base,3);
|
||||
for(unsigned i=0;i<sizeof(game_table)/4;i++)game_table[i]=(uintptr_t)missing;
|
||||
for(unsigned i=0;i<sizeof(outer_table)/4;i++)outer_table[i]=(uintptr_t)missing;
|
||||
outer_table[0x140/4]=(uintptr_t)AT(0x467000);game_table[0x278/4]=(uintptr_t)set_accel;
|
||||
game_table[0x2ac/4]=(uintptr_t)get_angular;game_table[0x2b4/4]=(uintptr_t)set_angular;game_table[0x2b8/4]=(uintptr_t)add_angular;
|
||||
game_table[0x220/4]=(uintptr_t)enabled;
|
||||
game_table[0x210/4]=(uintptr_t)enabled;game_table[0x218/4]=(uintptr_t)support;
|
||||
game_table[0x248/4]=(uintptr_t)get_friction;game_table[0x268/4]=(uintptr_t)speed;game_table[0x26c/4]=(uintptr_t)set_speed;
|
||||
game_table[0x2bc/4]=(uintptr_t)get_velocity;game_table[0x2c4/4]=(uintptr_t)set_velocity;game_table[0x2cc/4]=(uintptr_t)add_velocity;
|
||||
game_table[0x328/4]=(uintptr_t)AT(0x4723f0);game_table[0x334/4]=(uintptr_t)AT(0x472480);game_table[0x38c/4]=(uintptr_t)AT(0x472b10);
|
||||
outer_table[0x160/4]=(uintptr_t)noop;
|
||||
outer_table[0xf8/4]=(uintptr_t)mouse;outer_table[0xec/4]=(uintptr_t)noop_dt;outer_table[0x164/4]=(uintptr_t)noop;
|
||||
outer_table[0x120/4]=(uintptr_t)AT(0x421c10);outer_table[0x124/4]=(uintptr_t)AT(0x421c40);
|
||||
outer_table[0x128/4]=(uintptr_t)AT(0x421c70);outer_table[0x12c/4]=(uintptr_t)AT(0x421cb0);outer_table[0x130/4]=(uintptr_t)AT(0x413a60);
|
||||
for(int offset=0xfc;offset<=0x11c;offset+=4)outer_table[offset/4]=(uintptr_t)zero;
|
||||
for(int offset=0x134;offset<=0x150;offset+=4)outer_table[offset/4]=(uintptr_t)zero;
|
||||
outer_table[0x140/4]=(uintptr_t)AT(0x467000);game_table[0x1d8/4]=(uintptr_t)zero;
|
||||
wheel_table[0x218/4]=(uintptr_t)wheel_support;
|
||||
}
|
||||
static unsigned char*reset(float speed_in,float vx,float vy,float vz,float pitch,float yaw,float turn,int front,int rear,int ground){
|
||||
memset(object,0,sizeof(object));unsigned char*g=object+0xc0;*(void**)object=outer_table;*(void**)g=game_table;
|
||||
memset(AT(0x509830),0,0x1d0);acceleration=(Vec){3,4,5,0};angular=(Vec){10,20,30,0};scalar=speed_in;velocity=(Vec){vx,vy,vz,0};friction=.8f;supported=ground;
|
||||
GF(g,0x224)=pitch;GF(g,0x228)=yaw;GF(g,0x22c)=0;GF(g,0x57c)=turn;GF(g,0x560)=2250;
|
||||
*(int*)(g+0x590)=*(int*)(g+0x594)=1;GF(g,0x550)=700;GF(g,0x558)=1200;GF(g,0x568)=1485;*(short*)(g+0x540)=front;*(short*)(g+0x542)=rear;
|
||||
for(int i=0;i<4;i++){
|
||||
memset(wheels[i],0,sizeof(wheels[i]));*(void**)(wheels[i]+0xc0)=wheel_table;
|
||||
wheels[i][0xc4]=i<2?i<front:i-2<rear;*(void**)(g+0x4b8+i*4)=wheels[i];
|
||||
}
|
||||
return g;
|
||||
}
|
||||
static void drive(const char*name,float s,float vx,float vy,float vz,float p,float y,float t,int front,int rear,int ground,int throttle,int brake,int reverse,float timer,float dt){
|
||||
unsigned char*g=reset(s,vx,vy,vz,p,y,t,front,rear,ground);g[0x598]=throttle;g[0x599]=brake;g[0x59f]=reverse;GF(g,0x588)=timer;
|
||||
((void(TC*)(void*,float))AT(0x465220))(g,dt);
|
||||
printf("DRIVE %s in=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%d,%d,%d,%d,%d,%d,%.9g,%.9g out=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g\n",name,s,vx,vy,vz,p,y,t,front,rear,ground,throttle,brake,reverse,timer,dt,scalar,velocity.x,velocity.y,velocity.z,GF(g,0x228),GF(g,0x580),GF(g,0x578),GF(g,0x588));
|
||||
}
|
||||
static void wall_case(const char*name,float s,Vec v,Vec n,int active,int up,float dt){
|
||||
unsigned char*g=reset(s,v.x,v.y,v.z,0,0,0,2,2,1);g[0x59b]=1;g[0x59c]=active;*AT(0x50985e)=up;F(0x696030)=dt;
|
||||
((void(TC*)(void*,Vec,void*))AT(0x421910))(g,n,NULL);
|
||||
printf("WALL %s in=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%d,%d,%.9g out=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%u\n",name,s,v.x,v.y,v.z,n.x,n.y,n.z,active,up,dt,scalar,velocity.x,velocity.y,velocity.z,acceleration.x,acceleration.y,acceleration.z,g[0x59c]);
|
||||
}
|
||||
static void crash_case(const char*name,float timer,float dt){
|
||||
unsigned char*g=reset(0,120,100,-60,0,0,0,2,2,1);g[0x59c]=1;GF(g,0x58c)=timer;
|
||||
((void(TC*)(void*,float))AT(0x4669f0))(object,dt);
|
||||
printf("CRASH %s in=%.9g,%.9g out=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%u\n",name,timer,dt,velocity.x,velocity.y,velocity.z,angular.x,angular.y,angular.z,GF(g,0x58c),g[0x59c]);
|
||||
}
|
||||
static void face_case(const char*name,float p,float y,float r,float dp,float dy,float dr,float rate,float dt){
|
||||
unsigned char*g=reset(0,0,0,0,p,y,0,2,2,1);GF(g,0x22c)=r;GF(g,0x274)=dp;GF(g,0x278)=dy;GF(g,0x27c)=dr;GF(g,0x29c)=rate;g[5]=g[10]=1;
|
||||
((void(TC*)(void*,float))AT(0x473320))(g,dt);
|
||||
printf("FACE %s in=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g out=%.9g,%.9g,%.9g\n",name,p,y,r,dp,dy,dr,rate,dt,GF(g,0x224),GF(g,0x228),GF(g,0x22c));
|
||||
}
|
||||
static void normal(const char*name,Vec n,float y){float initial=y,p=0,r=0;((void(*)(Vec*,float*,float*,float*))AT(0x476ff0))(&n,&p,&y,&r);printf("NORMAL %s in=%.9g,%.9g,%.9g,%.9g out=%.9g,%.9g,%.9g\n",name,n.x,n.y,n.z,initial,p,y,r);}
|
||||
static void input(const char*name,float s,float t,int keyturn,int rev,int brake,int up,int down,int left,int right,int rear,float dt){
|
||||
unsigned char*g=reset(s,0,0,0,0,0,t,2,rear,1);g[0x59d]=keyturn;g[0x59f]=rev;g[0x599]=brake;
|
||||
*AT(0x50985e)=up;*AT(0x509860)=down;*AT(0x50985d)=left;*AT(0x50985f)=right;
|
||||
((void(TC*)(void*,float))AT(0x465830))(g,dt);
|
||||
printf("INPUT %s in=%.9g,%.9g,%d,%d,%d,%d,%d,%d,%d,%d,%.9g out=%.9g,%.9g,%u,%u,%u,%u\n",name,s,t,keyturn,rev,brake,up,down,left,right,rear,dt,scalar,GF(g,0x57c),g[0x59d],g[0x59f],g[0x599],g[0x598]);
|
||||
}
|
||||
int main(void){
|
||||
setbuf(stdout,NULL);setup();
|
||||
drive("rest",0,0,0,0,0,0,0,2,2,1,0,0,0,0,.1f);
|
||||
drive("launch",100,0,0,0,0,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("forward",300,0,0,300,0,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("coast",300,0,0,300,0,0,0,2,2,1,0,0,0,0,.1f);
|
||||
drive("turn",300,0,0,300,0,0,30,2,2,1,1,0,0,0,.1f);
|
||||
drive("slowturn",80,0,0,80,0,0,-30,1,2,1,1,0,0,0,.1f);
|
||||
drive("drift",400,150,10,300,0,35,25,2,2,1,1,0,0,0,.1f);
|
||||
drive("falling",300,0,-100,300,0,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("rising",300,0,100,300,0,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("uphill",300,0,0,300,20,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("downhill",300,0,0,300,-20,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("reverse",-300,0,0,-300,0,0,30,2,2,1,0,1,1,0,.1f);
|
||||
drive("reverse_allowed",-300,0,0,-300,0,0,30,2,2,1,0,1,1,1.1f,.1f);
|
||||
drive("unsupported",300,0,0,300,0,0,30,2,2,0,1,0,0,0,.1f);
|
||||
drive("frontnone",300,0,0,300,0,0,30,0,2,1,1,0,0,0,.1f);
|
||||
drive("onewheel",300,0,0,300,0,0,30,1,0,1,1,0,0,0,.1f);
|
||||
drive("nowheels",300,0,0,300,0,0,30,0,0,1,1,0,0,0,.1f);
|
||||
drive("brakestill",0,0,0,0,0,0,0,2,2,1,0,1,1,0,.1f);
|
||||
drive("braketimer",0,0,0,0,0,0,0,2,2,1,0,1,1,1,.1f);
|
||||
drive("negativecoast",-30,0,0,-30,0,0,0,2,2,1,0,0,0,0,.1f);
|
||||
drive("tinycoast",.1f,0,0,.1f,0,0,0,2,2,1,0,0,0,0,.1f);
|
||||
drive("tick",1400,120,-13,1200,5,179,40,2,2,1,1,0,0,0,1.f/60);
|
||||
normal("flat",(Vec){0,1,0,0},0);normal("slopeZ",(Vec){0,.9396926f,.3420201f,0},0);normal("slopeX",(Vec){.3420201f,.9396926f,0,0},90);normal("slopeXZ",(Vec){.2f,.95f,.2f,0},45);
|
||||
for(int i=0;i<4;i++){
|
||||
char name[32];sprintf(name,"input%d",i);input(name,300,10,1,0,0,i==0,i==1,i==2,i==3,2,.1f);
|
||||
}
|
||||
input("nosupport",300,10,1,0,0,1,0,1,0,0,.1f);
|
||||
input("reverseheld",0,0,0,1,1,0,1,0,0,2,.1f);
|
||||
input("brakenegative",-300,0,0,0,0,0,1,0,0,2,.1f);
|
||||
input("both",300,44,0,1,1,1,1,1,1,2,.1f);
|
||||
input("cap",1490,-44,0,0,0,1,0,0,1,2,.1f);
|
||||
wall_case("head_on",600,(Vec){0,13,600,0},(Vec){0,0,-1,0},0,1,.1f);
|
||||
wall_case("side",600,(Vec){600,13,0,0},(Vec){-1,0,0,0},0,1,.1f);
|
||||
wall_case("side_no_throttle",600,(Vec){600,13,0,0},(Vec){-1,0,0,0},0,0,.1f);
|
||||
wall_case("glance",600,(Vec){400,-20,300,0},(Vec){-.8f,0,-.6f,0},0,1,.1f);
|
||||
wall_case("slow20",10,(Vec){0,13,20,0},(Vec){0,0,-1,0},0,1,.1f);
|
||||
wall_case("reverse",-300,(Vec){0,-13,-300,0},(Vec){0,0,1,0},0,0,.1f);
|
||||
wall_case("already_crash",0,(Vec){0,100,300,0},(Vec){0,0,-1,0},1,1,.1f);
|
||||
crash_case("begin",0,.1f);crash_case("before_end",3.8f,.1f);crash_case("equal_end",3.9f,.1f);crash_case("after_end",4,.1f);
|
||||
face_case("ordinary",10,20,30,0,30,0,5,.1f);face_case("seam",359,359,359,1,1,1,2,.1f);face_case("small",.1f,.1f,.1f,0,0,0,2,.1f);
|
||||
for(int i=0;i<4;i++){char name[32];sprintf(name,"slopeYaw%d",i);normal(name,(Vec){.2f,.95f,.2f,0},i*90);}
|
||||
puts("SCOOTER_MOTION_COMPLETE: copied465220/465830, synthetic dependencies");return 0;
|
||||
}
|
||||
@@ -16,6 +16,7 @@ from bubble_resources import export_bubble
|
||||
from baseball_resources import export_baseball
|
||||
from rocketship_resources import export_rocketship
|
||||
from grappler_resources import export_grappler
|
||||
from scooter_resources import export_scooter
|
||||
from sound_bank import export_sound_bank
|
||||
|
||||
|
||||
@@ -90,6 +91,7 @@ def main():
|
||||
export_baseball(args.original,args.output/'baseball')
|
||||
export_rocketship(args.original,args.output/'rocketship')
|
||||
export_grappler(args.original,args.output/'grappler')
|
||||
export_scooter(args.original,args.output/'scooter')
|
||||
effects = export_sound_bank(args.original, args.output / 'effects')
|
||||
print(f"SoundEffects.omt: {len(effects['resources'])} original sound identities")
|
||||
for name in args.audio:
|
||||
|
||||
@@ -1,100 +1,203 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Export original Scooter resource data; do not assign attachments or playback.
|
||||
"""Export exact Scooter OMT body/wheel and Jimmy rider resources.
|
||||
|
||||
The two Scooter ASE morphs have 195 indexed positions, whereas scooter.omt's
|
||||
body has 98. Keep these samples unbound rather than inventing UVs or a base.
|
||||
Mesh pivots, vertices, UVs, materials, texture pixels and morph samples are
|
||||
unchanged. Runtime owns source vehicle/wheel transforms and action selection.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections import Counter
|
||||
from dataclasses import asdict
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from ase import export_ase, read_ase
|
||||
from entities import resolve_asset
|
||||
from models import export_omt_model
|
||||
from omt import Database, FormatError, read_shape
|
||||
from gam import parse
|
||||
from omt import Database, FormatError, read_canvas, read_material, read_shape, write_png
|
||||
from png import read_png
|
||||
|
||||
SOURCES = {
|
||||
'Neutron.exe': 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8',
|
||||
'omt/scooter.omt': '8d4ffdafee5fd819c5220ee4f608c901a5988fe6b8b13316e15618f5eec75e81',
|
||||
'ASE/jimstop.ASE': 'b294d090ac5c4ec449d845db6d837f2cbedf5f7b812f5b6ed2bb70f85246f1d0',
|
||||
'ASE/jimscooter.ASE': 'b27c8cb80811eb70e391fc061dab99c7d5f0b4d884c109b34c673a1815508299',
|
||||
'ASE/jimscooterstop.ASE': 'edcdcc879a28757994525f815c88cd6dd46dc788b69ba2f902323d6de48cb873',
|
||||
'ASE/jimstop.ASE': 'b294d090ac5c4ec449d845db6d837f2cbedf5f7b812f5b6ed2bb70f85246f1d0',
|
||||
'ASE/godscooter.ASE': 'c18f1414ec2b397e0c8f8320f63830ab88630ea05a354bb99af34ce7fea79bd1',
|
||||
'ASE/godscooter2.ASE': 'fcf9ca5e8298efa7b4d551d9d09878c04f1f2647b6a30edfa2297617a7d63189',
|
||||
'png/jimycarl.png': '55ed165aaffe177cb62558a08d13fc3b2210da6e353065b108849d46df9dacb6',
|
||||
'gam/VR05.gam': 'f8a14585116bbf0f339b22f634a3fa66b5e7c967bdd19a21e98a18aea2c73a02',
|
||||
'gam/level1.gam': '40b809d007671e082c07c2766e487f30115a85ef3a067d5c15ff374b32cdb3f2',
|
||||
}
|
||||
CLIPS = ('jimscooter', 'jimscooterstop')
|
||||
JIMMY_RGBA_SHA256 = '5e54ccb99e9e060843cd7f80fd93ff8bf47f8779666e41d4240398354a278a3f'
|
||||
CANVASES = ((0, 'scooterwheel2', 22568, 3966, 32, 32,
|
||||
'92dfef71def8079db70ba4eaa47e973d45a0b3987418e87dbf65cc3cf0bf823b'),
|
||||
(1, 'goddard128', 26534, 65770, 128, 128,
|
||||
'b22651171a7b9f2c99831a1ff4fd8d01d11ccabfc276d71dd91bacd710cd1cba'))
|
||||
SHAPES = ((0, 'goddard01', 'body', 104, 19342, 98, 176),
|
||||
(1, 'wheel', 'wheel', 92304, 5814, 32, 56))
|
||||
# Mapped source spans: Init binds database0, Jimmy aliases, Goddard alias,
|
||||
# wheel's inherited visual binder. Values are guarded below before output.
|
||||
BINDINGS = (
|
||||
(0x4214f0, 0x421515, 'body database entry0'),
|
||||
(0x422c58, 0x422c80, 'Jimmy HISCOOT/HISCOOTSTOP'),
|
||||
(0x41cdf0, 0x41ce04, 'Goddard HISCOOT'),
|
||||
(0x468270, 0x46829a, 'wheel database visual binder'),
|
||||
(0x477550, 0x4775e2, 'MakeShapeUnLit material consumer'),
|
||||
)
|
||||
|
||||
|
||||
def digest(data: bytes) -> 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()
|
||||
Reference in new issue
Block a user