diff --git a/README.md b/README.md index d97d287..26ebcfa 100644 --- a/README.md +++ b/README.md @@ -4,11 +4,12 @@ Local reconstruction of the supplied **Jimmy Neutron: Boy Genius** installation using C#/.NET 10, Silk.NET.Vulkan (Vulkan 1.3), and SDL3. Original files remain untouched in `../Original`. There are no Git remotes or runtime online services. -**Current milestone: controllable original lab with walking, jumping, collision, -chase camera and original animation clips.** Recovered controller arithmetic is -integrated; collision/pivot/cadence and animation timing remain provisional. -Introductory cutscenes, interactions, progression and saves remain incomplete. -See [progress](docs/progress.md) and [compatibility](docs/compatibility.md). +**Current milestone: original lab story, interactions and jet pack practice flow.** +The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard +patrol logic, pickups, objectives, the practice prompt, VR04 powered jumping and +checkpoint transitions. Collision response, timing and visual fidelity remain +provisional. The full game is incomplete; see [progress](docs/progress.md) and +[compatibility](docs/compatibility.md) for tested scope and remaining work. ## Build and run locally @@ -21,12 +22,34 @@ python3 tools/extractors/prepare.py --audio sounds musicsecretlab dotnet run ``` -The default is the original secret lab (LV1B), starting at the GAM location after -settling onto source floor geometry. **Arrows** walk/backpedal/turn; **Shift, -Insert, numpad 0 or right mouse** jump. **R** resets, **C** pauses into inspection -and resumes the chase camera, **F11** toggles fullscreen, **Escape** quits. -No-gadget held jump can repeat on landing; normal midair arrows do not steer. -The original STARTEXP/LABEXP intro is skipped for this checkpoint. +The default starts the original secret lab (LV1B), including the recovered intro +camera/speech sequence. **Escape or Space** skips the current sequence and restores +control. **Arrows** walk/backpedal/turn; **Shift, Insert, numpad 0 or right mouse** +jump, and holding jump uses the jet pack after obtaining it. **O** raises/lowers +the objective panel. **R** resets the scene placement with current progression; +**C** pauses into inspection, **F11** toggles fullscreen, **Escape** quits during +ordinary play. Use `--skip-intro` to begin with control or `--mute` for silent play. + +The original lab pickup is internally tagged `shrinkray`; the original objective +art identifies it as the **jet pack**. Its practice prompt accepts **Y** or a click +on Yes to enter VR04, and **N** or a click on No to resume. Enter selects the +hovered Yes region, otherwise No. The original practice return uses the saved +lab start tag. Runtime checkpoint-position restoration is still unrecovered. +Normal midair arrows do not steer. Source patrol/door logic is integrated, while +sensing, full collision response, alpha/lighting and audio effects remain incomplete. + +`--load-save PATH` reads original TSK task/items/score/checkpoint state; +`--write-save PATH` writes that state outside the asset directory. This resumes the +saved STRT checkpoint; arbitrary current-position/complete game-state saving is +not implemented. `--start TAG` selects an original checkpoint for investigation. +Prepare all available scenes for other save files with +`python3 tools/extractors/prepare.py --all-scenes --audio sounds musicsecretlab`. +All35 GAM entity files are supplied;33 have matching OMT geometry archives. +Level3B.gam and Level3E.gam each contain the same four entities apart from their +level identifier. Their registered OMT archives are absent, but no incoming GAM +transition or supplied save selects them. Their use in normal gameplay remains +unverified; this is not an established blocker. The manifest records the absent +geometry without substitution. See [level resource evidence](docs/analysis/level-resource-mapping.md). Use `--inspect` for the previous inspector: arrows/WASD orbit, plus/minus zoom; 1 idle, 2 run, 3 jump, 4 scratch preview. With no simulation, C toggles stored/orbit @@ -39,6 +62,8 @@ Headless verification on a machine with Vulkan 1.3 (Mesa lavapipe works): ```bash dotnet run -- --headless --with-player --time 0.05 --screenshot artifacts/lab.ppm dotnet run -- --headless --smoke-walk --screenshot artifacts/walk.ppm +dotnet run -- --headless --story --story-time 12 --screenshot artifacts/story.ppm +dotnet run -- --headless --skip-intro --write-save artifacts/checkpoint.tsk dotnet run -- --headless --model ASE/jimstop.ase --texture png/jimycarl.png dotnet run -- --audio artifacts/extracted/musicsecretlab/Wave_00000000_HuntingBuildupVar2_11k.wav --loop-audio dotnet run -- --help @@ -77,14 +102,16 @@ dotnet publish -c Release -r win-x64 --self-contained true Packages are local directories `dist/linux-x64` and `dist/win-x64`. Run `launch-scene.sh` or `launch-scene.cmd`; append `--headless --frames 1` for a render smoke test. They include the .NET runtime, SDL3 native library, SPIR-V, -original asset copies, prepared lab/Jimmy resources, audio and limitations. +original asset copies, all33 available prepared scenes, actor/UI resources, audio +and limitations. Windows cross-publishing and preliminary headless Wine64 rendering are verified. -A user confirmed native Windows loading/rendering; this movement update still -needs native Windows input/physics testing. Full native Windows functionality is unverified. +A user confirmed native Windows loading/rendering of the earlier checkpoint; +this story/tutorial update still needs native Windows input/physics testing. Full native Windows functionality is unverified. These are investigation packages, not a finished game release. `scripts/test.sh` runs Python regressions, native C# data/collision/movement checks, -all PNG/ASE decoders, actual Vulkan GPU readback, dummy-device SDL3 audio, and +all PNG/ASE decoders, source-backed interaction/AI/support/jetpack/UI checks, +actual Vulkan GPU readback, dummy-device SDL3 audio, and original SHA-256 verification. Set `NEUTRON_WINDOW_TEST=1` with a working DISPLAY to include injected keyboard and swapchain-resize verification. Full OMT audit: diff --git a/docs/analysis/buttons-doors.md b/docs/analysis/buttons-doors.md new file mode 100644 index 0000000..c34b4fe --- /dev/null +++ b/docs/analysis/buttons-doors.md @@ -0,0 +1,75 @@ +# Player-contact buttons and vertical doors + +Static recovery and managed integration, 2026-10-24. Original executable SHA-256: +f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8. +EXE text file offsets are VA minus0x400000. Originals were only read. + +## Button contact + +C3DButton interface+C0 vtable493B60, enter slot40=411BB0, update slot3C4=411DE0, +activation slot28=4118B0, PostLoad slot404=411EF0. InitObject411B82 sets radius300; +PostLoad411EF8/411F09 sets authored/current radius300 again. Activation4119A7 +sets150; runtime resizing after subsequent task reactivation remains to be matched. +The current player contact subset uses normal PostLoad radius300 plus Jimmy60, +strict overlap and source offsets to distinguish duplicate C3DBUTTON tags. + +Enter411BC1 accepts the active player or a C3DBASEBALL. The port currently handles +only player contact. Availability at interface608 must be nonzero, cooldown7B0 +must be<=0. Current definition HIUP (literal4ED9C0) selects the press branch: +set cooldown4.0 at411C35, optionally play AvailSound at411C92..A2, select DOWN +at411CAE..B5 and set material RGB(.2,.2,.2) at411CBB..FC. Existing DOWN selects +UP and original authored RGB at411D59..B1. Material pulse/tint is not yet ported. + +Resolve ActivateButton through first case-insensitive tag lookup474070. If found, +call its interface428 with source Toggle (411D18..23). A button target additionally +becomes available while the caller becomes unavailable (411D29..47). Complete +generic button-to-button toggle activation is still unresolved by this consumer; +the lab targets bars, a vertical door. NewTaskState/NASound are serialized but the +traced ordinary contact path does not consume them. No task award was invented. +The special LV4B branch411C3F..8F is outside this lab implementation. + +Update411E24 subtracts dt only for positive cooldown and reactivates/resets at +<=0, then stores0. Continuous contact does not generate another enter callback. +SceneMechanisms retains contact membership across cooldown reset. + +## Vertical door state + +C3DDoorUpDown interface+C0 vtable4993AC: activation417760, contact4178C0, +update417930, toggle428=417AC0. Source fields are ItemClosed at5FC, current +closed flag600, Next604, remaining668, DoorSpeed66C, OpenTime670, elapsed674, +OpenAmount680. DoorSpeed is used as the movement **duration**, not units/second. +Initial open state adds OpenAmount to the stored source origin at41777B..AE. +Origin getter interface164=471600 returns the saved vector atEC..F8. + +Toggle ignores requests equal to current closed state. During movement it replaces +remaining with duration-minus-remaining (417AE9..F5); from rest it copies duration +and starts loop sound59 when no movement sound is active (417B11..43). Next is +dispatched before assigning closed state (417B49..C01). The current consumer +handles Next targeting3AIT; other original subclasses remain explicit unsupported. +Requested0 opens,1 closes; other values toggle (417C01..34). + +Update first consumes positive remaining by dt and clamps to0. Completion stops +the movement loop and emits sound58 (417974..AE). Set vertical root to: + +```text +fraction = remaining / DoorSpeed +closed: sourceY + OpenAmount*fraction +open: sourceY + OpenAmount*(1-fraction), reset open elapsed0 +``` + +There is no leftover-dt integration. Once stationary/open, add dt to elapsed and +close only when elapsed is **strictly greater** than OpenTime (417A77..AA). +Lab bars: originY-1076.0883, duration5sec, distance500, open hold3sec, touch-disabled. +Its two authored buttons use Toggle-1. TouchActivated doors' own contact and +baseball contact paths remain outside the player-button subset. + +## Runtime verification and limits + +Game/SceneMechanisms runs in the same fixed-step scene loop as the director. +Application/StaticSceneVisuals displays UP/DOWN variants and door root movement. +Two source-data regression groups cover strict360 contact, four-second reset, +duplicate tags, contact persistence, five-second opening, continuous reversal, +sound-loop lifetime, exact endpoints and strict three-second hold expiration. +These checks establish port behavior from static evidence. Moving-object physics, +material pulse, sound-bank resolution, full task/reactivation behavior and original +runtime comparison are not established by these tests. diff --git a/docs/analysis/dynamic-collision.md b/docs/analysis/dynamic-collision.md new file mode 100644 index 0000000..5656b64 --- /dev/null +++ b/docs/analysis/dynamic-collision.md @@ -0,0 +1,130 @@ +# Moving vertical-door collision + +Read-only static recovery and bounded managed component,2026-10-24. Original +Neutron.exe SHA-256 f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8. +EXE text file offsets below are VA minus0x400000. No original code was executed +for this investigation. Source geometry/defaults are recovered; full response is +still injected and must not be called the original collision solver. + +## Door defaults and activation + +C3DDoorUpDown complete constructor4174F0 installs interface+C0 vtable4993AC. + +| Evidence | Result | +| --- | --- | +|4175B0 ->4710C0 ->iface224/471A40|Entity pair collision enabled; current byte+140=true| +|4175C6/4175CA ->471730|Collision mode178/field124=2| +|4175CF/4175D2 ->471030 ->iface214/471A00|Own physics integration disabled; byte13E=false| +|417CAB/417CB2 ->iface110|PostLoad radius40, overriding automatically copied shape radius| +|40E410/40E413|HasCollision-1 retains constructor flags| +|40E427/40E433|Explicit HasCollision nonzero enables pairs and own integration| +|40E44B/40E457|Explicit HasCollision0 disables pairs and own integration| + +Do not interpret own integration=false as a noncolliding door. Its entity pairs +remain enabled. Render visibility, current pair permission, world geometry checks, +own integration and authored CanMove are different flags. On HasCollision-1, +task visibility changes do not themselves execute the explicit pair-disable path; +the caller must track source activation flags without equating visible and solid. + +CanMove is read at base40E0F0. After physical update462520, zero restores the +serialized origin through position/Euler setters40E103..40E15C. Nonzero permits +the current position to remain, allowing the door state machine's vertical motion. +It does not replace collision mode2 with a static world mesh. + +## What the box actually uses + +Shape-change hook462270 reads the current OMT shape's find_cube method through +complete slot44 at4622D4. This is the min/max of its local source vertex positions, +not a world-aligned bound of an already transformed rendered model. It forwards +min to iface2E8 at4622FB (storage1D4..1E0), max to iface2E0 at462325 +(storage1C4..1D0). OMT find_cube1000AA80 computes all six values from shape vectors. +This justifies original local shape bounds; unrelated editor icons or a guessed +full-model world AABB are not substitutes. + +47A776/47A7A5 retrieve these bounds.47A7EC..47A99B transforms all eight corners +through iface384=472980, using current Euler angles and root position. The point +method quantizes angles through the original trigonometric table. The bounded +component accepts a supplied local-to-world matrix; correctness of that matrix +for every nonzero authored Euler rotation remains the caller's responsibility. +The actual lab bars have zero rotation, so translation is unambiguous. + +Corner bits:4 selects maxX,2 maxY,1 maxZ. The switch at47B3AC then emits these +twelve triangles, with the original diagonal choice/order preserved: + +```text +0,1,2 1,3,2 0,2,4 2,6,4 +4,6,5 6,7,5 5,7,3 5,3,1 +0,4,1 4,5,1 2,3,7 7,6,2 +``` + +The pure component rebuilds these triangles from the current door transform. +There is no persistent collider left at its closed root and no invented relative +door-motion sweep. Original47A5E0 similarly constructs the box at its current +pose, then obtains the other body's previous/current roots47AAD4/47AB0D. + +## Dispatch, gates and response boundary + +Global entity-pair loop47A430 requires both slot220 flags and mutual slot3A0 +class/permission gates. At47A4CF/47A4E7 it checks collision mode178. If either +actor has mode2, it calls47A5E0 with that actor first; otherwise it calls the +ordinary root-sphere path47B3E0. Exclusions/class gates are inputs to the bounded +component; their complete class-specific behavior is not silently invented. + +47A5F5 additionally requires the **other** actor's world-geometry flag1D0. +Root broadphase then uses quick_magnitude and these inclusive comparisons: + +- Other actor mode2: distance<=boxRadius+otherRadius, then return contact directly + at47A712..47A72C/47B39F without the twelve-triangle response. +- Other modes: distance<=2*boxRadius+otherRadius, at47A73F..47A75B. Only candidates + passing this gate construct/sweep the oriented cube. + +The second rule is a source quirk. Normal Jimmy radius60 and door radius40 give +**140 units**, despite the bars' much larger shape bounds. Do not enlarge it to +the graphic cube's bounding sphere while calling the result recovered behavior. + +For every cube triangle,47B277 invokes shared sphere/triangle kernel47BD80 and +can invoke the other actor's normal response callback374 at47B29B. After all +twelve, box iface1E0 inhibits ordinary position response when true47B2EF..47B2F7. +Otherwise the candidate displacement is clipped against static world through +47B4B0 at47B364 before assigning the sphere root via314 at47B399. Thus a generic +sphere-vs-AABB overlap/push is not an exact translation of the original response. + +## Implemented interface and tests + +Game/DynamicSceneCollision.cs is deliberately bounded: source defaults and +HasCollision sentinel handling; pair/world-geometry gates; exact broadphase; +current oriented corners; exact twelve-triangle order; injected narrowphase; +contact-preserving response inhibition and second-mode2 shortcut. + +DynamicBoxCollider takes identity, source root, local min/max, local-to-world +matrix, current radius, pair flag and response-inhibition flag. DynamicSphereMotion +takes previous/current root, radius and the relevant flags/mode. Resolve invokes +a supplied Func, or returns unchanged +when a recovered gate rejects it. The sweep contains all twelve SupportTriangles. +The callback must provide the still-unrecovered47BD80/static clipping response. + +Source lab fixture: bars GAM offsetA29C, root(3810.1970,-1076.0883,-1180.4956), +HasCollision-1,CanMove1,OpenAmount500,rotation0. Its42 ASE source points convert +to local min(-223.8069,-18.7273,-16.8051),max(228.7926,391.2706,16.8051). +All raw points, including any nonvisible faces, contribute to these shape bounds. + +Run from GamePort: + +```sh +python3 tools/binary/dynamic_collision_evidence.py +source scripts/env.sh +dotnet run --project tests/GamePort.DynamicCollisionTests +``` + +The script checks26 original instruction sequences, all12 jump targets and all36 +corner indices extracted directly from the bounded switch-case machine bytes. +It verifies the source class table, lab entity flags and ASE bound facts. +JSON evidence is artifacts/binary/dynamic-collision-evidence.json. + +All10 managed groups pass: defaults/sentinel; inclusive140 broadphase and its +large-cube quirk; permission/geometry gates; oriented corners; source cube topology; +injected response/inhibition; mode2 shortcut; moving geometry; invalid inputs; +actual lab bars closed/open passage using the existing provisional swept-sphere +SceneCollision adapter. The latter verifies port integration, not original47BD80 +or original runtime behavior. Full edge/vertex sphere response, static reclipping, +door pushing/crushing and native original comparison remain unresolved. diff --git a/docs/analysis/jetpack.md b/docs/analysis/jetpack.md new file mode 100644 index 0000000..b6dd060 --- /dev/null +++ b/docs/analysis/jetpack.md @@ -0,0 +1,99 @@ +# Laboratory jet pack and powered jump + +Read-only static recovery plus managed implementation,2026-10-24. EXE text file +offsets are VA minus0x400000. Neutron.exe SHA-256 is +f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8. +Original DLL/frame and original game comparisons are separate evidence categories. + +## Identity + +The lab pickup's GAM tag SHRINKRAY/PickupIndex301 is a prototype/internal name. +Original screens.omt Canv120 says GET JET PACK; its effect grants inventory +group0/item3. That exact inventory slot gates the powered-jump code43848E/4385C9. +It must not be presented as a shrink-ray weapon. The original readme describes +Shift/Insert/right mouse as Jump - Jet Pack Burst. The actual C3DShrinkRay class +has separate ray.ase/ray0000..2.png bindings440035..A6, outside this implementation. + +## Controller and state order + +Game/JetpackBurst.cs translates the vertical state/action subset of437F90. +Grounded/released outer update437B9E resets jump state0 before air application. +States below3 set extra acceleration to gravity*1.33f-gravity at438148..18D. +With gravity-800 this yields-264 extra/-1064 net. The initial jump queues550 +at4383B3 and clears the effect timer; the hold timer starts0. + +State1 adds dt and starts a burst only after hold is strictly>.4f +(4383FD..418). State2 renewed hold attempts immediately (438559). Both enter +state3 even when disabled. Allowed start sets effect time8 (field884, ctor437640), +current radius100 when the effect exists (4384DE..F3), requests FLY and sets +vertical velocity10 (4384F9..546). Slot138(2) invokes a gadget/sound callback; +it is not a proven movement-mode assignment and the component does not invent one. + +Start is disallowed in LEV6,LV4B,LV6A,LEV3,LV3A/B/C/D; gadget modes2/6/7; +nonpositive global4F83D4; or inventory item3 state0/4. VR04 bypasses those guards +(43841E..4384D4,438559..633). Other nonzero inventory states remain accepted. + +Before state dispatch, states>=3 inspect the effect timer. An existing effect +with time<=0 resets states3/4 to0, requests FALL, stops the gadget and returns +before replacing acceleration (438192..20D). The previous extra acceleration +therefore survives that invocation. This is also why unavailable gadgets can +repeat ordinary jumps on landing while jump remains held. + +With positive burn time, distance-controlled extra acceleration is: + +| Condition | Extra Y | Net Y including gravity | +| --- | --- | --- | +| Shadow distance<500, velocityY>=-1 |880|80| +| Shadow distance<500, velocityY<-1 |1040|240| +| Shadow distance>=500 |720|-80| + +Near-branch .1/.3 are stored doubles; far .1 is float (438210..30D). +Source distance86C comes from Jimmy to his shadow425450..47C. Shadow query +4252E0 uses a vertical segment2500 downward and places its root hitY+13 for +default height30. Current integration approximates this query with the port's +walkable floor query; failed queries retain prior distance. + +Held state3 landing stops the effect, restores radius60 and enters4 +(438693..6EF). Airborne release stops the timer, requests FALL and enters4 +without a radius restore (438745..780). Jimmy's next ordinary grounded update +42469B restores60. Source released table state4 goes directly to reset43879A; +state5 checks grounding. The component's tests preserve these distinct branches. + +## Effect, energy and visual assets + +C3DJetpackFire update421FB0 obtains its owner. Grounded owner sets remaining0; +then it subtracts dt, including when inactive (421FDD..422009). A nonpositive +result hides it. A positive result shows it and adjusts global4F83D4 by-dt*.5 +(42202B..3B). Timer values are not clamped to0. Empty owner/effect leaves fields +unchanged. Running burn is not cancelled merely because energy reaches0. + +Energy helper42A920 skips adjustments for numeric FourCC VR01..VR08, otherwise +adds the requested amount and clamps0..100 (42A975..9C1). Low/empty-energy sounds +and other energy/damage consumers are not yet mapped. The original TSK float +PlayerValue retains this global. SceneInteractions now preserves live energy +when producing a checkpoint snapshot. + +Effect bindings421F30..96 are DEFAULT fire.ase, HINONE fire2.ase and fire.png. +The active effect follows owner root/Euler directly at42204C..B6. Preparation +exports the original two-triangle morph; JetpackVisuals samples it into the final +combined GPU buffer and controls its draw from the effect phase. Exact effect +translucency and global morph cadence remain open. Jimmy HIFLY->jimfly.ase is +registered at422B1A..26; its426 point vectors reuse the original Jimmy base UVs. + +## Integration and verification boundary + +LabSimulation uses controller -> movement/static/dynamic collision -> effect +update at fixed60Hz. Original global object iteration/phase order is unresolved; +the pure APIs expose controller and effect phases separately rather than hiding +that choice. Normal logical actor-root clearance is now75.9 from recovered +PostLoad/support constants; player capsule radius24, full wall solver and sole +placement remain provisional. Burst100/landing60 radius changes currently affect +contacts and moving-door broadphase; they do not make the modern capsule exact. + +Fourteen JetpackTests groups pass: takeoff/release/refire, strict .4 threshold, +disabled repeat, all source start gates/VR04 exception, acceleration thresholds, +transition acceleration/radius semantics, timer/energy order, negative inactive +timer, energy clamp/VR immunity, depletion, explicit phase differences, absent +effect and bounded malformed input. The existing13 movement groups still pass. +These are static/data/port algorithm checks. Original gameplay/native Windows +comparison remains required before a fidelity claim. diff --git a/docs/analysis/lab-progression.md b/docs/analysis/lab-progression.md new file mode 100644 index 0000000..60a9bef --- /dev/null +++ b/docs/analysis/lab-progression.md @@ -0,0 +1,216 @@ +# Original lab trigger and camera sequence + +Static executable/GAM investigation, 2026-10-24. VAs are preferred-base +Neutron.exe addresses (these text offsets are VA-0x400000). Port runtime +verification is separate; no original gameplay comparison has succeeded. + +## Recovered sequence + +LV1B STRT STARTEXP at GAM0x5B0E starts LABEXP. AITrigger labexp at0x18FAD +selects labexp1 when SCENE30; original NewGame starts with SCENE30. Chain: +LABEXP1 -> SITGODDARD -> LABEXP2a -> LABEXP2 -> labexp2b -> LABEXP3A -> +LABEXP3 -> labexp3b -> GOCARL -> GOGODDARD -> WATCHGODDARD -> TELGODDARD -> +GODDARDDIS -> TELFX1OFF -> TELGODDARD2 -> end -> jimend -> default. +CAM/MCA nodes supply16 speech cues in this sequence. Speech end, not a guessed +fixed cutscene duration, advances the nodes. + +STRT deferred dispatch0x4426A7 validates a C3DTriggerType target, then clears +player control through game slot0x118 before dispatch0x4426B7..C1. CAM activation +0x4165E2 PlayerControlled='none' preserves control, 'NULL' clears it, named existing +objects receive control. DEFAULT0x447CF0 restores Jimmy, enables inventory, and +clears the global skip flag at0x447F89. SCENE30 calls Jimmy help/inventory callback +0x42AB60; it does not unlock the exit or simply advance the task to60. + +AI trigger actions0x40C300 execute synchronously: actor animation/state/speed, +patrol, hide/show, named-marker teleport, yaw; then conditional child selection +0x40C230 exact-matches current TaskName state to ActivateStateN and selects first +existing ActivateObjectN. 0x40C9BF/0x40CA26/58 dispatch child or NextTrigger. +SITGODDARD does not wait for SIT animation. GOGODDARD sets actor state3/speed260/ +patrolGODDARDPAT1 and starts WATCHGODDARD immediately. Patrol movement is concurrent +and is now consumed by ActorPatrol with recovered support and provisional wall response. + +## Camera formulas and timing + +CAM0x415FC2 checks sound handle through0x47D890; finished sound deactivates target +animation then dispatches NextTrigger0x4160A4..E2. MCA0x430DD2 waits similarly, +advances to next non-none target, then finisher0x4311F0 dispatches NextTrigger. +Port uses exact prepared PCM sample duration for deterministic stepping; actual +hardware playback latency/end state is not yet matched to the original handle. + +CAM0x4161CD..585: CameraType2 eye=authored camera position, look=target root. +Otherwise D=clamp(InitialDist-ZoomSpeed*t,MinDist,MaxDist). ViewFromCamera0 uses +eye=targetLocalToWorld(TargOffsetX,TargOffsetY,D), look=root+(0,LookVoffset,0). +Nonzero ViewFromCamera (including1/3) uses A=targetLocalToWorld(TargOffsetXYZ), +eye=A+normalize(cameraPosition-A)*D, look=A; LookVoffset unused in that branch. + +MCA0x431027..11C1 resets per-shot elapsed time0x43190F. Local eyes: + +|Type|Local eye| +|---|---| +|0|(0,40,200)| +|1|(0,140,max(100,300-15t))| +|2|(0,240,max(100,500-35t))| +|3|(200,240,max(100,700-55t))| +|4|(-200,190,max(100,700-55t))| + +Transform eye by target Euler/root; look=root+(0,LookatVOffsetN-60,0), constant60 +at0x49D5B4/handler0x43116A. Both handlers write exact eye/look via0x431670. +Port uses quantized modern trigonometry; x87 table/rotation-bit identity unverified. + +CAM skip0x4160F1 and MCA0x430EED accept Escape/Space/controller/global flag, set +0x4F83E4, stop speech, preserve deactivation/actions and fast-forward the remaining +chain until DEFAULT. Port suppresses newly queued speech while skipping. + +## Progression after intro + +Teleport explanation AI special0x40CB43..6B changes SCENE30/31->35. Pickup special +0x4365D0..639 changes SCENE35->50 for shrinkray, with additional inventory effects. +Carl callback0x413E50..9D changes50->60,65->70,270->280 after base0x41B810. +The follow-up below recovers and implements the actual contact/talk dispatcher +and the internally named shrinkray jet pack checkpoint/inventory/practice/gadget effects. General AI sensing, +weapon behavior and all special pickups remain incomplete. + +LOAD LABTONEIGH GAM0xA43 goes tolevel1.gam/startlevel1, SCENE60/radius200. +Underground LOAD0x8360 requires scene65, start riverlab. Binary0x457F32..7F5F: +none requiredtask bypasses; taskvalue-1 bypasses; otherwise >=RequiredLevel and +ExactLevel!=-1 additionally requires equality to that numeric ExactLevel. +Original LOAD contact uses the independent RequiredTask gate. Its interface+C8 +vtable0x4D025C has task callback+0x424=0x458880, which only stores the supplied +TaskState at interface+0x494; it does not apply animated-entity activation rules. +Applying generic Animated.RequiredLevel to LABTONEIGH incorrectly disables it +because its TaskName is none while its RequiredTask is SCENE. The director now +leaves LOAD activation alone and SceneInteractions checks its real task gate. + +## Implementation and remaining limits + +Game/SceneDirector is bounded synchronous dispatch plus stateful CAM/MCA timing. +It preserves original GAM values, task gates, skip actions and reports unknown +classes/cycles/missing targets. Source-authored actor states are mutable copies. +Jimmy creates Goddard at0x423C98->0x41C810 (tag at0x41C88C); initial port position +uses gstart as a placement inference, then the authored SITGODDARD action positions +him before his first shot. Source visibility/collision masks are not fully ported. + +Carl/Goddard rendering, speech/music and camera integration run in default lab play; +--story-time N gives a headless comparison point, --skip-intro executes skip actions. +Sprite/OMT props, common patrol, lab interactions and the practice modal are integrated. +Fades, complete collision/sensing, animation timing and full inventory remain incomplete. Model pivot/grounding remains provisional. Tests exercise original +sequence/control restoration, all five MCA formulas, CAM modes, task gates, +bounded cycles and actual decoded sound durations; GPU story12s render is verified +under Linux llvmpipe with zero validation errors. This does not prove original fidelity. + +## Lab jet pack (internal tag SHRINKRAY) and Carl interaction follow-up + +Read-only static source investigation plus managed regression execution. Original +source EXE SHA-256 is f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8. +Source GAM level1b SHA remains recorded in original-manifest.json. No original +binary was executed for this follow-up. + +### Lab jet pack: ordinary collection and the exact special gate + +GAM0x1799 is3PIC tagshrinkray, PickupIndex301, PointValue50, Radius125, +SoundIndex116, noPIC_NUMBER/RequiredPicNum/PickedUpIndex. Its generic contact +0x435CE0 accepts the active player, rejects an already acquired index, runs the +prerequisite virtual complete+0xD8, marks ordinary acquired state1 at0x435E11, +hides and disables contact. It invokes special hook0x4365D0 at0x435FCB before +positive score0x435FED. + +The special hook compares ObjectTag to SHRINKRAY at0x4365D7..E7 (literal0x4F050C) +and SCENE exactly35 at0x4365ED..FD. Only that gate performs: + +1. Active Jimmy complete+0x1E8 at0x43662C, resolved through complete vtable + 0x4A3BDC to0x42AF00: capture current level code and physics root at complete + +0x1E48/+0x1E38. The port emits CheckpointCaptured(root); it does not guess + that this is the unidentified TSK StoredVector or change a STRT checkpoint. +2. SCENE50 assignment0x436632..639. +3. Inventory setter0x4038C0(group0,item3,state1) at0x43663E..644. +4. Help/item-information page0 via0x406F90(0), call0x43664B. +5. Jimmy complete+0x174(3) at0x43667C..67E, resolved to0x428D50 gadget selection. + +Collecting this tag outside SCENE35 still performs ordinary acquired/score behavior, +but does not receive these special side effects. The port preserves this boundary +rather than adding a minimum-level restriction. It emits HelpRequested(0) and +Inventory.GadgetSelected(3); presentation, modal pause and the jetpack motion/effect +consumer are separate integration work. + +### Carl: entering talk precedes dialogue, rather than following its end + +Carl interface is complete+0xC0, vtable0x495364; complete vtable0x495804. +InitObject0x413D60 sets radius100 through interface+0x110 at0x413E2F..36 and +support factor0.75 via+0x100 at0x413E3E..45. This supports a100-unit root +contact radius, not a model-sized capsule assumption. + +Inherited contact-enter0x40A3C0 first handles base collision.0x40A44C..45C checks +that the contacted entity is the actor's resolved TargetName (complete+0x6C0, +interface+0x600; resolved at0x40948B..49A). If actor AIState6, +0x40A676..68D calls complete+0x124(0). C3DFriend update0x41B950 runs general +AI0x408000 first and, whenever resulting AIState0, calls complete+0x140 at +0x41B972..988. Carl's complete+0x140 is0x41B7B0. + +That dispatcher obtains complete+0x17C=0x41BB20. This searches five TalkTriggerN +names in source order, requiring an existing target, TalkState!=-1 and either +exact actor TaskState or wildcard-2. It retains the selected object before any +task mutation. With a match, it invokes complete+0x180=0x413E50 FIRST, then +dispatches the chosen object's interface+0x5C with that object itself as caller +at0x41B7D3..D8. It increments the conversation counter, sets AIState9 at +0x41B7F0..F7, and invokes desired-facing hook+0x148=0x4093E0. Without a match, +it leaves state0 and retries on later updates without awarding points. + +Carl0x413E50 calls base0x41B810 (+100 score, zero velocity through interface+0x410) +and then maps SCENE50->60,65->70 or270->280. Thus the normal lab route changes +to60 BEFORE starting neutron1a, and the exit may pass its gate while the dialogue +is running. The port does not award or advance on conversation end. General +state6 visibility/FOV sensing0x409CC0 and desired-facing smoothing are not yet +implemented by this contact subset; entering the recovered100+60 root-sphere +contact path is supported. Other friend classes do not reuse Carl's derived hook. + +Carl TaskState override0x413F30 invokes generic activation, then LV1B branch +0x414068..118: SCENE outside0..60 deactivates;31..60 resolves CARLESC3 and sets +state6/position; states below60 activate;60 leaves generic activation unchanged. +This runs on every assignment, including repeated values. On scene initialization +or reset, call SceneInteractions.Reset AFTER SceneDirector.Begin to restore the +class callback and acquired-item visibility after actor reset. + +### Inventory and objective persistence + +SceneInventory preserves the19 signed TSK inventory values (9 group0,10 group1) +with owned arrays and bounded indices. Source0x4038C0 writes an item state at +group pointer0x4F8164[group]+40*item+0x24;0x403950 reads a signed short from +the same location. Unknown existing wire values remain unchanged unless the port +performs a recovered assignment. The separate29-item consumable group/counts are +not silently conflated with these two groups. + +The TSK OtherCounter global0x4F8194 is now identified as the current objective +selector. SCENE setter0x45F990 uses byte/target jump tables0x45FC48/0x45FBF0 and +0x45FD98/0x45FD40 to call0x406F50(objective,1). That helper clears44 transient +flags at0x4F7D00, stores the selector0x4F8194 and sets flag[objective]=1. Relevant +lab milestones35/50/60 select1/2/3;65 does not replace the selector. The port +maps all44 supplied milestone states (including140/141 selecting8), exposes +CurrentObjective/ObjectiveChanged, and saves the selector in OtherCounter. +The lab stationary objective panel and practice modal are integrated; timed UI +slides/highlights and remaining objective consumers are separate work. + +### Verification and boundaries + +Run source scripts/env.sh, then dotnet run --project tests/GamePort.InteractionTests +-- ../Original. Managed checks cover the actual authored intro/skip/explanation, +task35->50 shrinkray with exact event order and+50, Carl task-position/contact/ +talk with pre-dialogue60/+100, original LABTONEIGH destination, TSK write/reload, +no repeated acquisition or talk, outside35 behavior, first-existing/wildcard talk +selection, no-match/no-award, strict160 contact threshold, controlled-player gate, +inventory bounds/array ownership and every objective mapping against the original +EXE dispatch tables. Eleven exact instruction sequences support the decisive +call sites/constants. These are implementation/data checks, not original gameplay +comparison or native Windows validation. + +Contacts now call OriginalBodySupport.QuickMagnitude, which translates the original +lookup algorithm with generated sine/acos tables; eight float-bit outputs now +match isolated original DLL probes. Full table bit identity, exclusion lists, +specialized contacts, body resolution and general AI sensing remain incomplete. Other special pickups remain reported unsupported. + +## Corrected pickup identity and modal + +The source tag SHRINKRAY is a prototype name. screens.omt Canv120 explicitly +says GET JET PACK; inventorygroup0/item3 also gates powered jumping. User-facing +notes must call this the lab jetpack.406F90(0) opens PracticeYesNo169 and pauses +the game; it is not a generic help page. Yes enters VR04/PHONEBOOTH with current +level/current STRT return context, while No resumes. See ui.md and jetpack.md. diff --git a/docs/analysis/level-resource-mapping.md b/docs/analysis/level-resource-mapping.md new file mode 100644 index 0000000..04e2c57 --- /dev/null +++ b/docs/analysis/level-resource-mapping.md @@ -0,0 +1,97 @@ +# Level3B / Level3E resource evidence + +Static investigation, 2026-10-24. Source: unmodified `Original/Neutron.exe`, SHA-256 +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +Addresses are preferred-base EXE virtual addresses. File offsets for the addresses +below equal VA minus `0x400000` in this PE. No original code was executed. + +## Findings and scope + +The user is correct that **`gam/Level3B.gam` and `gam/Level3E.gam` exist**. +Both parse successfully as 1,777-byte entity files with four entities: +`3JIM`, `STRT`, `LOAD`, `3SBU`. Their bytes after the four-byte level header +are identical; headers are `LV3B` and `LV3E`. GAMs contain entity properties, +not replacement scene mesh/material/texture payloads. + +The original executable also has explicit, separate archive-opening paths for +**`omt/level3B.omt` and `omt/level3E.omt`**. Those files are absent from the +supplied original tree. This is verified loader behavior, rather than an inferred +same-stem pairing or merely an unused string reference. No shared-map alias is +present on the traced initialization paths. + +However, whether these scenes occur in normal shipped gameplay is **unverified**. +Small identical entity bodies suggest possible stubs/development leftovers; that +is an inference, not established intent. The primary's corpus check found no +serialized GAM string references to either scene name/code and no source TSK +starting in `LV3B`/`LV3E`. This does not exclude hardcoded transitions or other +entry routes. Do not describe the archives as confirmed required files for the +normal game, or tell the user their GAM files are missing. + +## Class and archive dispatch + +| Evidence | Level3B | Level3E | +|---|---|---| +| Complete class | `CLevel03BGame` | `CLevel03EGame` | +| Constructor | `0x451AF0` | `0x452690` | +| Constructor sets level code | `0x451BA8`: push `LV3B` | `0x452748`: push `LV3E` | +| Factory calls constructor for code | `0x45D635` | `0x45D78B` | +| Complete vtable | `0x4C7830` | `0x4C8A00` | +| Initialization slot `+0xB4` | `0x451C50` | `0x4527F0` | +| Literal archive string | `0x4F1F24`: `level3B.omt` | `0x4F1FFC`: `level3E.omt` | +| Archive string length/copy | `0x451C99` / `0x451CC5` | `0x452839` / `0x452865` | +| Dispatch archive loader slot `+0xE4` | `0x451CE8` | `0x452888` | + +Both vtable `+0xE4` entries are `0x44E7B0`. This function copies the supplied +archive filename, invokes slot `+0x16C` with the directory string `omt` at +`0x4F1B1C` (`0x44E7FF..0x44E81E`), builds the string argument, calls the file +stream helper `0x476170` at `0x44E8B4`, then calls database helper `0x476000` +at `0x44E8CE`. It stores the file stream/database in globals +`0x5099D8` / `0x5099C0`. There is no fallback archive name in this routine. + +File helper `0x476170` imports `OMediaFilePath` and `OMediaFileStream` +constructors (`0x48D188`, `0x48D184`). Database helper `0x476000` imports +`OMediaDataBase(OMediaStream*)` at `0x48D19C`. This confirms the archive string +goes to the real file/database path rather than to a debug label. + +The level-code-to-GAM path is separate: the switch at `0x4607F1` selects +`level3b.gam` (`0x4F49C4`) at `0x46083E`; the `LV3E` branch selects +`level3e.gam` (`0x4F49A0`) at `0x46088E`. The level registry also contains +code/GAM records at `0x4F3BE0` and `0x4F3C4C`. Existence in the factory and +registries proves registration, not a normal-gameplay route. + +## Missing-file handling + +The traced archive-opening path does **not** directly abort, choose a shared map, +or produce procedural replacement geometry when the map archive cannot open: + +- `0x476000` initializes its result to null, checks the stream pointer and its + open byte `+0x24` (`0x47602A..0x476033`), and returns null without constructing + a database when either condition fails. +- `0x44E7B0` retains the resulting null database and returns. It does not itself + throw or dispatch an explicit missing-map error in the examined path. +- Base geometry/entity-resource enumeration `0x44D4F0` checks `0x5099C0` at + `0x44D513`; null skips enumeration to `0x44D7F2`. +- The child initialization then continues and separately constructs `3SKY` through + the factory `0x459CB0`. Its sky resource is `omt\nightsky.omt` at `0x4F1DA4`, + passed at `0x451D35` / `0x4528D5`. + +Thus these archives' absence means the port has no recovered scene geometry for +the registered entries. It does **not** prove an original startup crash, and this +static trace cannot establish whether the shipped game ever tries to enter them. + +## Reproducible checks + +Run from `GamePort`: + +```sh +python3 tools/binary/level_resource_evidence.py +``` + +The read-only script passes **13 decisive instruction byte assertions**, resolves +both class vtables, verifies the archive directory/names, parses both GAMs, reports +their SHA-256 hashes, confirms their identical bodies and checks archive presence +case-insensitively. It reports normal-gameplay reachability as unverified. + +Confidence: high for supplied-file presence, original loader mapping and null-map +enumeration handling; unverified for gameplay reachability, intended stub status, +and original runtime outcome. diff --git a/docs/analysis/original-collision.md b/docs/analysis/original-collision.md new file mode 100644 index 0000000..e998792 --- /dev/null +++ b/docs/analysis/original-collision.md @@ -0,0 +1,309 @@ +# Follow-up original collision evidence + +Static investigation and isolated copied-DLL probes,2026-10-24. The bounded +OriginalBodySupport module now translates the vertical support/segment path. +This does not supersede the complete provisional SceneCollision solver or prove +original gameplay fidelity; full body collision/pivot/cadence remain unresolved. + +HasCollision is serialized type6 at EXE40D423 into interface+584. LV1B includes +-1defaults, explicit1Carl, explicit0plant/teleport/OMT props. Per-object collision +exclusions DisableCollisionID4730F0/EnableCollisionID473170 maintain separate lists; +visibility/material alone cannot choose collision masks. + +Jimmy grounded update42469B..4246E3 sets physical-radius slot264 to60 when WORD +4F0588!=0, versus160 otherwise. Shape/animation reset42369A..4236AA sets authored +radius60 through interface slot110, forwarding the radius. Gate semantics/root and +vertical support differ from the preview feet capsule: do not blindly replace its +radius24 with60 and call that original collision. Static resolver47B4B0 ->47BBB0 -> +47BD80 reads interface+15C radius; recovered vertical support47B890 is below. + +ASE mode2 conversion of standing Jimmy was executed against a copied DLL in the +isolated harness: its raw bounds remain unchanged and both frame offsets are zero. +No hidden scale/pivot correction was found. The remaining sole/root discrepancy +must not be replaced with a guessed scale or translation. + +## Reproducible source evidence + +All addresses below are preferred virtual addresses. Neutron `.text` addresses +map to file offsets VA minus `0x400000`; OMT2 addresses should be mapped through +their PE section table. Original files are only read, never executed or modified +by this investigation. Bounded `objdump -d -M intel --start-address=... +--stop-address=...` reads were used for instruction interpretation. + +Run `python3 tools/binary/collision_evidence.py` from GamePort. This read-only +script checks27 decisive EXE/DLL instruction-byte sequences, resolves interface and +game vtable slots from original PE bytes, and derives source mesh/GAM facts. It +uses the existing bounded PE, OMT and GAM readers and adds no dependencies. +Neutron.exe SHA-256 is +`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`. +The script does not execute original instructions; its calculated values are +static consequences, not observed original gameplay. + +## Jimmy PostLoad: radius and vertical clearance + +Jimmy's game interface is complete object plus `0xC0`, vtable `0x4A373C`. +The **interface** slots below must not be looked up in the complete-object OMT +vtable `0x4A3BDC`. + +| Interface slot | Implementation | Field/behavior | +| --- | --- | --- | +| `0x100` | `0x4711E0` | Authored support factor at interface `+0x2C`; forwards to slot `0x254` | +| `0x110` | `0x471240` | Authored radius at `+0x34`; forwards to slot `0x264` | +| `0x250` | `0x471AF0` | Current support factor getter, `+0x154` | +| `0x254` | `0x471B00` | Current support factor setter, `+0x154` | +| `0x260` | `0x471B30` | Current radius getter, `+0x15C` | +| `0x264` | `0x471B40` | Current radius setter, `+0x15C` | +| `0x310` | `0x472300` | Current physics position, `+0x214..+0x220` | +| `0x318` | `0x472330` | Physics position setter and changed hook | +| `0x40C` | `0x423610` | Jimmy PostLoad | + +`0x423631` passes the string `Calling PostLoad for C3DJimmy()` (VA `0x4EF3B4`). +After restoring the base shape through complete-object slot `0xAC`, PostLoad +pushes `0x42700000 = 60.0f` at `0x4236A3` and calls interface slot `0x110` at +`0x4236AA`. It then pushes `0x3FA1EB85 = 1.2649999856948853f` at `0x4236B3` +and calls interface slot `0x100` at `0x4236BA`. + +The earlier player constructor factor `0.7` at `0x4373C2..0x4373C9` is therefore +superseded by Jimmy PostLoad. It is not friction: constructor friction `0.8` +goes through `0x4711B0` and interface slot `0x24C`. The factor's original source +name is not recovered; "support factor" describes its verified use below. + +Grounded update `0x42469B..0x4246E9` sets the current radius again. It uses 160 +when WORD current gadget selector `0x4F0588` equals zero and 60 otherwise. The +selector is initialized to `-1` by Jimmy constructor `0x42225F`, so no-gadget +grounded behavior takes the 60 branch. Grounded gadget-specific changes are +distinct from a uniform player body dimension and must remain state-dependent. + +This establishes original radius 60 for the ordinary path; it does **not** +establish a vertical capsule of height 209.4361. The current provisional capsule +radius 24 cannot be described as recovered, and simply replacing that radius +without recovering root/solver conventions would mix two different models. + +## Vertical support handler `0x47B890` + +This handler queries source geometry separately from the horizontal/ceiling +triangle resolver. It exits immediately if geometry collision byte `0x4F69E5` +is zero. Its active path reads radius through slot `0x260` and support factor +through `0x250` at `0x47B8B0` / `0x47B8BE`. The multiplication at `0x47B8C8` +stores `radius * factor` (the subsequent `push` means the store at `0x47B8D5` +is local offset `+0x08`, not `+0x0C`; tracking that stack shift matters). + +Recovered active-path outline, omitting callback bookkeeping: + +```text +r = currentRadius +h = currentSupportFactor +clearance = (h == 1 or h < 0.1) ? r : r*h +P = currentPhysicsPosition +Q = previous/resolverPosition (slot 0x2F8) +top = max(P.y, Q.y) +if segmentQuery(Q, P, 0) hits H: + top += length(P-Q) - length(H-Q) +start = (P.x, top + clearance, P.z) +end = (P.x, P.y - 2*r, P.z) +if segmentQuery(start, end, 0) hits F: + resolvedY = F.y + r*h + if preventLowering(slot0x208) and P.y > resolvedY: return + setPosition(P.x, resolvedY, P.z) + zero acceleration.Y and velocity.Y, preserving X/Z + setGrounded(true) + preserve hit polygon and shape for callbacks +``` + +The ray span uses the conditional `clearance`; the final support height adds +the stored product `r*h`. The distinction matters for factors below0.1, although +ordinary Jimmy's1.265 branch uses the same product in both places. Ray assembly +is `0x47BA33..0x47BAD1`, hit Y plus product `0x47BAE1..0x47BAEF`, position write +`0x47BB23..0x47BB32`, grounded write `0x47BB7C..0x47BB80`. The handler invokes +an optional interface landing hook only when prior grounded byte `0x695D49` +was false (`0x47BB51..0x47BB5E`). + +For radius60 and PostLoad factor1.265, float32 clearance is **75.9000015** world +units. At the actual lab spawn XZ, the only source polygon below GAM root26.6619 +is Box06/shape71/polygon497/material17 at Y=0.5486332333; its stored normal is +approximately `(−0.00002292,1,−0.00002965)`. The next vertical hits are overhead +surfaces at473.6309 and491.0861. Thus the ordinary successful flat support branch +predicts physics root Y about **76.448635**, not a permanent root-to-floor offset +of26.1133 inferred from serialized GAM placement. + +That is a conditional static prediction, not an original frame capture. Initial +GAM placement can be corrected by physics after loading. With raw standing +minimum local Y=-64.6165, the predicted root would put its lowest raw vertex +11.2835 units above that floor. This remaining discrepancy must not be turned +into an invented scale factor. The port's present sole-based render transform +and floor-derived actor offset remain separate approximations. + +## Shape bounds and render transform + +Complete-object shape-change hook `0x462270` reads current shape pointer `+0x8C`, +copies shape bounding-sphere radius `shape+0x4C` into interface slot `0x110`, +then asks shape virtual `0x44` for six cube bounds. It forwards two four-float +records through interface slots `0x2E8` / `0x2E0`, stored at `+0x1D4` / +`+0x1C4` by `0x472120` / `0x4720C0`. These are bound records, not a recovered +capsule radius/height constructor. Jimmy's explicit PostLoad radius60 follows +the base-shape restore and therefore overrides the automatically copied radius. + +OMT shape `prepare` at DLL `0x100062A0` computes sphere center and maximum +vertex distance (`0x100062EE..0x10006389`) using the bounding-box center finder +`0x10005470`. This computes bounds and does not itself move the vertices. + +Physics-to-render position hook `0x4624B0` reads interface slot `0x310` and copies +XYZ directly to complete-object offsets `+0x44,+0x48,+0x4C` (interface-relative +`-0x7C,-0x78,-0x74`) at `0x4624CA..0x4624E8`. No extra vertical translation +or scalar multiplier occurs in this hook. + +Jimmy complete-object slot `0x7C` targets import thunk `0x47EDB4`, which jumps +through IAT `0x48D36C` to OMT `get_dynamic_offset@OMedia3DMorphAnim`, DLL +`0x100033F0`. It reads current animation frame `+0x98` and returns that frame's +XYZ offsets `+0x08,+0x0C,+0x10`; without a frame it returns zero. Base frame +constructor DLL `0x10021180` initializes those offsets to zero. Therefore this +hook has no hardcoded Jimmy floor/pivot adjustment. Full converter/frame writes +still need controlled probing before asserting every relevant offset stays zero. + +## ASE object mode2 does not imply a scale correction + +The DLL object-mode global `0x1013D6CC` has five absolute-address references in +the inspected binary (the script lists their operand addresses). ASE-specific +reads at `0x1001396E` and `0x10013CBF` control GROUP/GEOMOBJECT separation. ASE +constructor `0x10012DF1` sets its "first object" flag1 and `0x10012DF7` sets +group depth0. In object mode2, the first ungrouped GEOMOBJECT clears that flag +and does not request a new shape (`0x10013CD2..0x10013D15`). + +`jimstop.ase` contains one GEOMOBJECT, no GROUP and no TM_ANIMATION. Its ordinary +vertex-list handler `0x10014EE0` parses each XYZ, swaps Y/Z and appends the +four-float vector to either base-shape vectors or the current morph frame +(`0x10014F59..0x10014FA8`). There is no multiplication by NODE_TM scale or a +constant0.4 in that handler. NODE_TM parsing `0x10014130` stores matrix rows +and an inverse matrix in converter state; this is not evidence that the baked +mesh vertices should be transformed a second time. + +The earlier mode0 probe matched raw standing bounds (rendering.md). The follow-up +mode2 animated probe now also matches them; its two jimstop frames both have +offset(0,0,0). Do not apply an unproven0.4 scale or call the actor pivot solved. + +## Static scene inclusion versus entity activation + +Static grid registration is `0x479140`, called by scene-object InitPhysics +`0x464B00`. It visits every shape polygon and makes these exclusions: + +1. `0x4794C0` handles checkpoint materials named exactly `cstart` or + `ccheck1`..`ccheck9`, marking their polygon word at `+0x1C` as4 and calling + the game checkpoint hook. +2. `0x4797A0` asks game virtual slot `0x134` whether to consume a polygon. + For CJimmyGame and CLevel01BGame this slot is `0x475CD0`, which returns false. +3. Otherwise it computes polygon centroid/radius and XZ bounds, then registers + it in a260×260 grid with cell index `trunc(world*0.002+130)`. + +The checkpoint filter immediately returns false when polygon material is null +(`0x4794E8..0x4794ED`). **Null material is therefore retained for static collision**, +even though it is skipped by drawing. This directly supports retaining the lab's +325 unresolved-material triangles. The actual LV1B materials contain no +`cstart`/`ccheck*` names, so all2,869 source triangles reach this registration +path. No general "decorative" name filter was found in it. + +Two grids are populated: all polygons at base `0x5CFC7C` and a wall/ceiling grid +at `0x509B24` when stored polygon normal.Y is strictly below0.7 +(`0x47987D` captures normal.Y; `0x4798B3..0x4798CF` performs the comparison). +The vertical segment query `0x47C6E0` uses the all-polygon grid, retaining the +nearest hit along the input segment. The static sweep `0x47B4B0` uses the +wall/ceiling grid. Its radius comes from interface slot `0x260`; closest-hit +state feeds recursive sliding and callbacks. Its full narrow-phase behavior +`0x47BBB0 ->0x47BD80` remains incompletely translated, so the current port's +two-sided capsule and0.65 slope threshold are still provisional. + +Entity collision is a different layer. HasCollision registration at `0x40D423` +binds a type6 property to interface `+0x584` (complete object `+0x644`). During +activation, `0x40E40A..0x40E45D` treats-1 as "retain default", zero as disable +(slot `0x3A4` plus slot `0x214=false`), and nonzero as enable (slot `0x3AC` plus +`0x214=true`). This is separate from visibility and the all-polygon static grid. +Actual LV1B values are nine default-1, one explicit1 and seven explicit0. +Carl is explicitly enabled; plant/teleport/OMT props provide explicit exclusions. + +`DisableCollisionID` `0x4730F0` searches global entities by ObjectID at interface +`+0x404` and adds matches to the caller's exclusion list `+0x254` if absent; +`EnableCollisionID` `0x473170` removes matching entries. Parent/entity analysis +also recovered the ordinary pair test at `0x47B3E0`: strict actor-root Euclidean +distance less than the sum of current radii, followed by exclusions. Mode2 pair +geometry follows another path and must not be replaced with that metric blindly. + +## Recovered guard, ray kernel and frame phase + +Support slot208 is4719D0, reading interface+13A. Guard47BAFD..47BB0A rejects +currentRoot.Y strictly greater than hitY+r*h. It does not inspect velocity; it +prevents lowering a body above support even while that body is descending. +C3DAI constructor407B4D..51 enables the authored flag through470F70, which +forwards to current flag setter4719E0. The earlier label "upward guard" was +imprecise. Clearance comparison48D920 is float0.10000000149, not0.5. + +Goddard inherits support factor0.30000001192 at407B2B/407B30; PostLoad41E64A/ +41E651 overrides radius to130, so ordinary flat clearance is39.0. No corresponding +factor override was found in the traced Goddard constructor/PostLoad path. + +EXE469B70 is a Moller-Trumbore-style segment test. It normalizes direction using +quick_magnitude, retains source winding, and accepts determinant<=-epsilon when +twoSided=false, or absolute determinant>=epsilon when true. Epsilon4D5E40/44 is +±1.1920928955078125e-7. Barycentric u/v boundaries are inclusive; t>=0 is accepted +but t>=segmentLength is rejected (469DDD/469DEE). Hit XYZ is correct: the pop edi +at469DF6 shifts subsequent stack operands, so apparently repeated offsets do not +mean repeated direction components.47C6E0 retains strictly nearer hits; equal ties +follow original grid traversal. No slope-normal cutoff is applied by this query. + +Physics479D20 captures prior grounded via218 at479D2E, saves695D49, and clears +current grounded through21C at479D4E when geometry-support flag1C8 is set. +Impulse/acceleration/gravity integration precedes wall/ceiling resolution47B4B0; +support47B890 is called at47A235 after the resulting position is assigned, then +friction47A330 and small-velocity clearing follow. The new support module preserves +this phase boundary; it is not the entire479D20 implementation. + +## quick_magnitude lookup recovery and actual DLL comparison + +OMT1001FF70 keeps largest absolute component m and other components a,b, computes +index=trunc((a²+b²)*16384/(a²+b²+m²))&16383, then returns m/sine[halfAcos[index]]. +Initializer100EDC00 uses these stored doubles: + +- sine[i]=float(sin(i*0.0003834951969604492)), with exact quadrant overrides; +- halfAcos[i]=trunc(acos(i/8192.0-1)*2607.5945876921437*0.5). + +This is a sine table, not the cosine table initially suspected. The isolated +copied-DLL probe observed FNV1a32 fingerprints431383b5 for all16384 sine floats +and4f800433 for all16384 half-acos words. Modern Python regeneration matches both +whole-table fingerprints. The C# function also matches eight actual original-DLL +float-bit outputs, including3/4/0 ->40a0001e,1/1/1 ->3fddb16e and500/100/300 -> +4413eb31. Zero is handled directly in the port; the observed DLL also returns0. +This verifies these math references on the tested environment; it is not a full +x87 arithmetic or native Windows gameplay equivalence claim. + +## Implemented boundary and validation + +src/GamePort/Game/OriginalBodySupport.cs provides QuickMagnitude, a source-winding +Trace over supplied SupportTriangle records, and Resolve for SupportBody input. +Resolve returns root/velocity/acceleration, supported/landing flags, source hit +identity and the support anchor written via2F4. The caller owns prior/current +grounded phase, geometry-registration masks, landing callback and hit bookkeeping. +Trace scans linearly instead of260x260 grid traversal; tie identities can differ. +Double/single arithmetic does not reproduce every x87 temporary rounding boundary. +This is a separate root-support component, not a replacement feet capsule. + +Run source scripts/env.sh then dotnet run --project tests/GamePort.SupportTests. +All13 groups pass: original-DLL math bit references; source winding/two-sided +override; strict endpoint/start; nearest/tie identity; root/velocity/acceleration; +height guard independent of velocity;0.1 factor boundary; crossed-geometry query +lift; disabled geometry; invalid input; ten-second gravity stability/jump; actual +2869 lab triangles including invisible proxies and predicted root76.448635. + +tools/binary/collision_mode2_probe.c builds with local i686-w64-mingw32-gcc and +runs only via tools/recon/reference_capture.py --asset-probe --probe-executable +artifacts/binary/collision_mode2_probe.exe in a copied installation. Original and +network paths are absent from that namespace. Artifacts/binary/mode2-jimstop.log +records successful conversion:426 points, matching raw bounds, one sequence/two +frames and zero offsets. An initial probe-reader error treated sequence pointers +as frames; the corrected bounded vector-of-sequences/list-of-frames traversal +was verified against100203C0/10020870. No original assets were written. +The follow-up jimjump animation-only conversion also succeeds after allowing its +legitimate empty base shape: one sequence, three frames of426 points, all offsets +zero. See artifacts/binary/mode2-jimjump.log. Empty base center/bounds are not +initialized geometry and must not be interpreted as a transform. The final probe +suppresses that center output when the base is empty. + +Full horizontal/ceiling narrow-phase sliding, dynamic collider activation/boxes, +exact body/render pivot and original gameplay/native Windows comparison remain. diff --git a/docs/analysis/patrol.md b/docs/analysis/patrol.md new file mode 100644 index 0000000..a354bbf --- /dev/null +++ b/docs/analysis/patrol.md @@ -0,0 +1,252 @@ +# Original patrol and Goddard lab route + +Static evidence from the immutable `Original/Neutron.exe`, `OMT2.dll` and +`gam/level1b.gam`, investigated 2026-10-24. Addresses below are preferred-base VAs; +the executable text file offsets are VA minus `0x400000`. No successful original +runtime comparison verifies the resulting motion. The follow-up at the end records +the bounded runtime AI implementation and its separate test/physics limits. + +## Relevant dispatch and fields + +Goddard's interface pointer is complete object plus `0xC0`. His interface vtable +is `0x49F480`, complete-object vtable `0x49F920`. His update `0x41DEE0` reaches +the general AI update `0x408000` at `0x41E520` for the ordinary patrol state, +after clearing interface `+0x8A8` (complete `+0x968`, animation override). + +|Complete offset|Interface offset|Meaning/evidence| +|---|---|---| +|`0x6C4`|`0x604`|Movement speed, float; AI trigger integer AISpeed converted to float| +|`0x6C8`|`0x608`|Current AI state; `3` is patrol, `1` is waiting, `7` is timed waypoint wait| +|`0x6CC`|`0x60C`|Previous AI state, assigned by setter `0x4089B0`| +|`0x6E4..6EC`|`0x624..62C`|Destination minus current root position| +|`0x6F4`|`0x634`|Within arrival distance flag| +|`0x6FC`|`0x63C`|Exact square-root 3D destination distance| +|`0x708`|`0x648`|Initial PatrolPoint tag| +|`0x820`|`0x760`|Patrol/run animation alias| +|`0x870`|`0x7B0`|Waiting animation alias| +|`0x8C0`|`0x800`|Current waypoint interface pointer, initially null| +|`0x8C8`|`0x808`|Previous waypoint pointer| +|`0x8D0/8D4/8D8`|`0x810/814/818`|Euler smoothing factors X/Y/Z| +|`0x8E8..8F0`|`0x828..830`|Current destination root position| +|`0x90C`|`0x84C`|Timed waypoint wait remaining seconds| +|`0x944`|`0x884`|Arrival threshold, default `110.0f` at `0x407D9A`| +|`0x948`|`0x888`|Alternate movement mode flag, default zero; nonzero uses facing vector and threshold440| +|`0x968`|`0x8A8`|Suppress automatic animation selection while nonzero| + +The normal lab Goddard path uses default arrival threshold110 and mode flag0; +the inspected Goddard constructor does not replace those defaults. His Euler +smoothing factors are explicitly overridden to `(0.3,3.2,0.3)` at +`0x41C8DB..0x41C90C`. + +## State3 movement, arrival and update order + +The general AI state dispatch table at `0x408980` maps state3 to `0x408518`. +Before that dispatch, `0x408000` calls animated/base update `0x40E050(dt)`. +That calls shared physical integration `0x462520`, which reaches game physics +through slot `0x130`, and then `0x458930 -> 0x473240`. The latter calls the +AI interface slot `0x3D8 -> 0x4096E0` for orientation smoothing. Thus previous +velocity and previous desired Euler angles are consumed before this update +computes the next patrol velocity and angle target. A port that immediately +integrates the newly selected velocity differs by one simulation tick. + +Patrol performs the following operations in source order: + +1. Complete slot `0x12C -> 0x408C90`: when current waypoint pointer is null, + resolve PatrolPoint tag (`complete+0x708`) with first case-insensitive tag + lookup `0x474070`. If still missing, set state1 and clear horizontal velocity, + preserving its Y component. Otherwise call complete slot `0x130`. +2. Slot `0x130 -> 0x408D40`: normally copy waypoint root to destination and compute + `delta = waypoint.Position - actor.Position`. Store full 3D Euclidean distance + (`sqrt(dx*dx + dy*dy + dz*dz)`) at complete `+0x6FC`. A separate movement + special flag can retain a previous destination; its nonordinary behavior is + outside this lab route. +3. Ensure the patrol/run animation is active (`0x408549..0x40856A`), looping, + unless animation override is nonzero. +4. Unless an independent temporary-target timer is positive, complete slot + `0x134 -> 0x408E40` computes `velocity = delta / quick_magnitude(delta) * speed`. + State3 has multiplier1. Full XYZ velocity is assigned, rather than retaining + old vertical velocity. If already marked arrived, assign zero XYZ instead. +5. Complete slot `0x128 -> 0x408BC0` compares exact stored distance with threshold. + **Strictly less than110** sets arrived true and calls an arrival virtual + method. Distance greater than110 clears an existing arrival flag for state3; + exactly110 leaves it unchanged. The arrival method is `0x41E580 -> 0x409890` + for Goddard and does nothing in state3 (its special branch is state10). +6. If arrived and the current pointer is a PAT, process wait/next below. +7. At `0x408958..0x40896C`, complete slot `0x138 -> 0x409140(dt)` computes new + destination Euler angles from the final destination-minus-root vector. + +The velocity assignment therefore precedes the arrival comparison: on the first +update entering the arrival radius, it may retain a nonzero newly selected +velocity for the next physical step while already selecting the next waypoint. +There is no normal exact-position snapping, remaining-distance speed clamp, or +multiple-waypoint traversal loop in this branch. +When a new waypoint is selected, arrival is not immediately cleared or distance +recomputed. On the next update the old arrived flag can therefore select zero +velocity/WAG before the newly computed distance clears that flag; subsequent +update selects RUN and movement again. Avoid replacing this order with a +smooth continuous multi-segment walker while describing it as recovered. + +`quick_magnitude` is the OMT export at `OMT2.dll:0x1001FF70`, imported through +`0x48D104`. It uses absolute components, largest-component selection and lookup +tables rather than a direct sqrt. The follow-up `OriginalBodySupport.QuickMagnitude` +now reconstructs those tables from their recovered initializer constants; modern +trig versus original x87 table equality remains unverified. Arrival itself uses +sqrt, not this helper. Zero delta is handled defensively by the port instead of +depending on the original invalid float-to-integer conversion behavior. + +## WaitTime and NextPatrolPoint + +PAT property loader `0x434DE0` operates on the PAT interface (complete plus +`0xC8`): + +|Property|PAT interface offset|PAT complete offset| +|---|---|---| +|CallObjectTag|`0x520`|`0x5E8`| +|ActivateAnim|`0x584`|`0x64C`| +|SoundDatabase|`0x64C`|`0x714`| +|SoundIndex|`0x714`|`0x7DC`| +|NextPatrolPoint|`0x5E8`|`0x6B0`| +|WaitAnim|`0x6B0`|`0x778`| +|WaitTime|`0x718`|`0x7E0`| + +At `0x40861F..0x408698`, **WaitTime>0** enters state7, starts PAT.WaitAnim loop1 +unless animation override is active, copies WaitTime to actor wait timer and +sets XYZ velocity zero. State7 `0x408370..0x408414` subtracts dt only while the +timer was positive at entry; if the result is **less than or equal to zero** it +restores the previous state, clears arrival and resolves this waypoint's +NextPatrolPoint. It does not consume leftover time to move through the next +segment in the same update. The exact-zero case corrects an earlier report +reading: `0x40838C` uses `test ah,0x41 / jne` to skip an initially nonpositive +timer, whereas `0x4083B0` uses `test ah,0x41 / je` to keep waiting only after a +positive result. On equality x87 C3 makes `ah&0x41=0x40`, so expiry occurs. +The comparison constant at `0x48D914` is float0. A timer already zero at entry +remains in state7. The timed-wait next-point lookup at `0x408406` does not +interpret missing `WAIT`/`SCAN` names specially; the immediate branch below does. + +For WaitTime<=0, `0x40869D..0x408757` immediately saves the current pointer as +previous and resolves NextPatrolPoint. If the lookup fails, the literal `WAIT` +sets state1 and literal `SCAN` sets state6. A nonexistent ordinary name, including +`none`, compares unequal to both special literals and leaves state3 until the +next `0x408C90` lookup of initial PatrolPoint; this detail is easy to miss. + +`none` is not equal to `WAIT`. Consequently this path can restart a route on the +next update instead of necessarily becoming idle. Any port choosing to stop at +`NextPatrolPoint=none` is making a terminal-route policy approximation, not an +exact translation of these instructions. For the lab cutscene, a later authored +GODDARDDIS action interrupts patrol and explicitly sets state1/SIT/phone2. + +CallObjectTag/ActivateAnim/SoundIndex are serialized and loaded, but their generic +execution is **not** recovered from this normal Goddard branch. PAT touch handler +`0x434EA0` calls base touch then only logs when a C3DAI is in state2. All lab PATs +have CallObjectTag=`none`; no invented callback is necessary for Goddard's route. + +## Goddard animation and authored route + +Goddard constructor (`0x41C9A3..0x41CA79`) sets aliases: +complete `+0x7F8=WAG`, `+0x820=RUN`, `+0x848=FLY`, `+0x870=WAG`, +`+0x7D0=WAG`, `+0x898=RUN`. Literal RUN is at `0x4ECA64`; WAG at `0x4ECA68`. +State3 update therefore replaces the trigger's AIAnim=`walk` with RUN on the +next update, without requiring an invented WALK-to-RUN asset alias. State1 +setter starts WAG unless animation override is nonzero; state1's steady update +does not itself force a new alias. A trigger can therefore preserve an explicit +SIT in state1 when its animation override suppresses the setter default. + +|Tag / GAM offset|Position|Next / wait| +|---|---|---| +|gstart / `0x960A`|`(4801.444336,38.160038,669.824158)`|none, wait0, WaitAnim sit| +|GODDARDPAT1 / `0x3D5F`|`(5011.098633,16.988688,716.637146)`|GODDARDPAT2, wait0| +|GODDARDPAT2 / `0x3F69`|`(5244.313477,26.268572,-249.976944)`|none, wait-1, WaitAnim sit| + +GOGODDARD AIT at GAM`0x3918` sets target C3DGODDARD, AIState3, AISpeed260, +AIPatrol GODDARDPAT1 and AIAnim walk, then immediately begins WATCHGODDARD. +SITGODDARD previously positions Goddard at gstart with yaw180. GODDARDDIS at +GAM`0x48D4` later interrupts by setting AIState1, AIAnim sit, AINewPos phone2, +AINewRotY10. None of these AI triggers waits for patrol completion. + +## Heading smoothing and remaining limits + +Desired orientation `0x409140` calls OMT vector.angles through `0x48D108` +(`OMT2.dll:0x1001FDA0`), scales the returned integer angular units by +`360/16384 = 0.02197265625f` (`0x48E5B4`) and writes destination Euler angles +through `0x472660`. In the ordinary flat yaw case, the equivalent heading is +`atan2(-delta.X, delta.Z)` in degrees. This mathematical atan2 equivalence is an +approximation to the original table quantization. + +The following frame's `0x4096E0` wraps each destination-minus-current Euler delta +at180 degrees, then adds `wrappedDelta * axisFactor * dt`; Goddard Y factor3.2 +is recovered above. Factor clamping is absent in this routine. The routine first +checks enabled/dirty flags; collision/arrival conditions can skip updating desired +heading. Full pitch/table equality and actor-floor contact matching remain open. + +Shared world gravity/collision also applies during the base update; replacing +the full body solver by direct waypoint interpolation or floor clamping must be +recorded as a port approximation. General stuck recovery `0x40A250`, temporary +targets and AI states other than the normal state3/7 path are not covered here. + +Read-only verification checked 17 executable dispatcher/vtable/string and GAM +route assertions: state3 dispatch, patrol virtual targets, WAIT/SCAN/RUN/WAG +literals, both route links, speed260, final WaitTime-1, and absence of actors +named none/WAIT/SCAN. This establishes consistency of the static evidence, not +runtime or visual fidelity. No original files or C# source were changed. + +## Runtime follow-up + +`Game/ActorPatrol.cs` implements ordinary states1/3/7 plus the common base phase +for state9. Carl state6 also receives that phase; its general FOV/visibility +sensor409CC0 remains unimplemented, while SceneInteractions handles source contact +dispatch. Other states are outside the supported subset. It exchanges root position/velocity +through the injected `PatrolBodyState -> PatrolBodyState` body step. Its own +algorithm does not invent a body radius, support factor, collision solver or +floor clamp. It consumes the prior velocity, smooths the prior yaw target by3.2, +selects RUN, computes the next fullXYZ velocity, compares exact distance and then +processes one waypoint/wait transition. The recovered table magnitude helper is +the default normalizer; a separate injected metric remains available for tests. + +Follow-up disassembly also verifies ordinary state1 zeroes XYZ at`0x40835D` +**after** the base physics update. The missing-initial-point transition preserves +Y at`0x408D1E..26`; its enclosing state3 branch still passes through RUN selection +after the resolver returns. States1/6/7 skip new destination-angle selection at +`0x409186..19B`. The port keeps their authored animations rather than forcing +WAG every idle tick. The subsequent TELGODDARD2 camera explicitly requests TALK +after GODDARDDIS requests SIT;40DF18..22 proves this unregistered TALK request +leaves the selected SIT clip/name unchanged. SceneActorVisuals retains that no-op. + +The runtime's authored teleport synchronization resets its velocity/route cache +and preserves the authored yaw/animation. This is an explicit port reset policy; +full original teleport bookkeeping is not recovered. Camera-only animation +events do not reset the route. Heading currently changes yaw only using atan2; +full pitch, original angle quantization, dirty flags, temporary targets and stuck +recovery are not implemented here. Physics and original runtime comparison remain +separate integration/validation work. + +Verification from `GamePort`: + +```sh +source scripts/env.sh +dotnet run --project tests/GamePort.PatrolTests/GamePort.PatrolTests.csproj +``` + +All9 deterministic groups pass: prior velocity/yaw phase; velocity-before-arrival +and waypoint pause; strict110/equality behavior; wait expiry at exact zero and +discarded remainder; WAIT/SCAN/none and lookup precedence; missing initial Y +preservation and fullXYZ velocity; authored teleport/cache handling; injectable +normalization separate from sqrt arrival; and the actual GAM Goddard route plus +GODDARDDIS interruption. Free-body/held-body fixtures validate AI ordering, not +original body physics, rendering or original gameplay fidelity. + +## Carl profile and live integration + +Carl constructor413BCB sets speed200. It installs WALK at complete820/898 through +413BFC..1D (literal4ECA54), STOP at7F8/870 through413C22..43 (literal4ED040). +Its yaw smoothing factor remains inherited3.0 from407CF8; Goddard overrides3.2. +The shared state3/7 code is therefore reused with class-specific aliases/factors. +State9 dispatch table408980 jumps directly to408911, adding no new velocity or +animation command. State6 calls the still-unported sensor409CC0 before this +common finisher. No arbitrary proximity-to-dialogue-end task rule was added. + +Live runtime bodies now use recovered Goddard130/.3 and Carl100/.75 root support, +source-winding floor queries and the exact source normal.Y<.7 wall-grid mask. +The wall response is still the port's swept sphere, not the original47BD80 solver. +Visuals use those actor roots without an additional sole-based correction. +The remaining raw-sole/root clearance difference is documented in collision notes. +Primary added a tenth test group for Carl's profile, speed, yaw factor and state9. diff --git a/docs/analysis/scene-entities.md b/docs/analysis/scene-entities.md new file mode 100644 index 0000000..6274dad --- /dev/null +++ b/docs/analysis/scene-entities.md @@ -0,0 +1,104 @@ +# Source entity resources and contact investigation + +Read-only 2026-10-24. tools/extractors/entities.py prepares exact GAM typed fields, +sourceSHA/offsets/raw bytes, transforms, duplicate tags, object-link candidate +ordinals, and explicit database/type/id references. It does not decide gameplay +visibility or turn editor SpriteDatabase icons into game actors. --decode preserves +referenced PCM WAV, Canv RGBA/PNG and3DSh decoded JSON. Tests check preservation, +case lookup/ambiguity, path boundaries and actual lab/VR01 resources. + +LV1B has129 entities:19 PIC,20AIT,13CAM,12MCA,16PAT,4OMT,2LOAD,2buttons and a bars +object, plus actors/effects. Its62 explicit resources resolve. VR01 has16 entities, +4star pickups IDs3001..3004 (sprites.omt Canv135 star, PointValue5,radius100), +2RETURN gates,2phone booths, trophy and a3-shot voicepractice intro24/23/22; +10 unique explicit resources resolve. Static level geometry omits dynamic actors. + +## Verified visual mappings + +- Carl STOP carlstop.ase0x4EDBC0 registered413DDC; texturecarl.png0x4EDBB4 at413DF2. + TALK/WALK/INHALE/CHEER/TELE registrations413D8C..413DE8; actual strings have HI + quality prefixes. Raw morph animation timing/quality dispatch remains incomplete. +- Goddard godsit.ASE0x4EEA0C registered41CDDE, goddard02.png0x4EE980 at41CE58. + HI-prefixed registrations41CDA0..41CE5F include FLY/EAT/RUN/SIT/SCOOT/WAG/GROWL/ + ROCK/POINT. Godpoint has complete UVs; godsit/run/growl have none. Current actor + preparation retains godpoint UVs for the common222-point/411-face topology; + this base choice is an inference. Godwag has30 different expanded corner UVs. + Follow-up40DF18..22 proves unregistered STOP/TALK/WALK requests preserve the + current clip/name. The consumer retains that source no-op; it invents no aliases. +- Trophy trophy.ase0x4F16E4 at448E1F; trophy.png0x4F16D8 at448E3A. Update448EC0 spins + Y90deg/sec (constant0x4A7388). Contact448F20 accepts active player, hides, adds300 + score, plays effect230, disables contact. No task/level completion in that callback. +- Phone class43579D opens phone.omt0x4F0314, shape3DSh0 via477BA0 at4357C9. Do not + substitute similarly named phone.ASE/phone.png without evidence. +- Buttons explicit down/up ASEbuttondown/buttonup and switch.png bind411695/ + 4116C3/411722. Bars explicit GAM ASEFilebars.ase/PNGFilechain.png. +- SpriteSize is actual world width/height: EXE4645F0 sets complete+AC/B0, C4 bit1; + OMTget_canv_wordsize10029930 reads them. Align values3/3 center offsets by half + size via10029890. Exact billboard flag248 handling remains under investigation. + +## Contact and pickup rules + +PIC interface+C8 vtable4AE548 contactslot40->435CE0. LOAD interface+C8 vtable4D025C +contactslot40->457EC0. Shared0x47A430 uses sphere path0x47B3E0 unless collisionmode +slot178 returns2, which uses specialized box path47A5E0. Sphere overlap obtains +roots via slot310, quick_magnitude, compares STRICT distance =ReqPicNumAmount, then consumes that amount and clears +inventory if depleted. This is a consuming prerequisite, not only a check. +PointValue>0 adds global score through42ADC0, lower-clamped0; repeat count gates it. +Normal collected flag1 hides/disables; PickedUpIndex!=-1 path uses flag2/effect. +Inventory/special pickup effects remain to be completed before broad collection. + +These data/executable findings are not full runtime entity or interaction support. +Only Carl/Goddard and Jimmy morph consumers are currently integrated into --story; +source sprites/OMT props/phones/trophy/buttons/bars still require runtime consumers. + +## Implemented sprite/contact subset (primary follow-up) + +Source3ANI update40ED40 adds dt to a float timer and advances only when timer is +strictly greater than1/FPS; resets timer0, advances one frame per invocation, +discarding remainder. Loop0 stops on last visible frame,1 repeats,2 hides/stops +(40EF02..41). Toggle40F160 resets index/timer and shows/starts on1, hides/stops +on0, -1 toggles subject to its one-second debounce. Port implements explicit0/1 +from the director; debounced-1 sprite toggles remain pending. Task activation is +separate from the AnimatedSprite Activated field: a visible apple can be idle. + +SourceSprite1..9 resources are now exported, and source-sized centered quads +render3PIC/3ANI from their explicit Canv resources. Camera-facing orientation is +still an approximation. Color modulation is retained; translucent alpha/blending +and all billboard flags remain to be recovered. Editor icons are not rendered. + +SceneInteractions currently accepts the ordinary3000..3999,PointValue5, no-inventory +star subset and trophy; broader pickup inventory/special effects report unsupported. +Normal acquired flag1 at435E11 hides/disables; score path435FC3..436002 adds positive +PointValue under repeat gating. Special tags4365D0..436829 are intentionally not +silently treated as plain score pickups. Original VR01 fixture tests collect4stars +for20, trophy for300, prevent repeat, serialize/reload acquired flags, and emit a +single stored RETURN request per contact entry. Original quick_magnitude and +exclusion/box contact rules remain unresolved; modern root-sphere distance is used. + +The executable's RETURN branch457F92..4580BE reads Jimmy complete+88C (saved third +string) and+8F0 (fourth string), supporting stored ReturnLevel/ReturnStart semantics. +Headless VR01->LV1B renderer/window-lifetime integration passes. Fades are not yet +implemented. Acquisition is serialized in TSK; full game-state/UI saving remains +unfinished. Trophy disable is per scene; no invented permanent trophy flag is added. + +All35 GAM files are present, including Level3B.gam and Level3E.gam. Their matching +OMT geometry archives are absent and named by the executable at4F1F24/4F1FFC. +Both1777-byte GAMs have identical bytes after the level identifier and four entities; +no serialized incoming GAM transition or supplied save selects them. Original +class registration/loading paths do not establish use in normal progression. +Their absence is not a proven required-content blocker.33 available pairs are +generated; scene-catalog.json records unavailable geometry without substitution. +See level-resource-mapping.md for loader and corpus evidence. +Additional unresolved explicit references: LEV1 icons.omt Canv45 (editor icon), +LV5A musicrocketmaze.omt Wave2, LV2A musicschool.omt Wave2. No substitutions. diff --git a/docs/analysis/scene-models.md b/docs/analysis/scene-models.md new file mode 100644 index 0000000..a35339f --- /dev/null +++ b/docs/analysis/scene-models.md @@ -0,0 +1,120 @@ +# Source-backed static scene models + +Implemented 2026-10-24 in `tools/extractors/models.py` and +`Application/StaticSceneVisuals.cs`. This adds the original model consumers for +OMT props, phone booths and explicit ASE/PNG entities. It does not establish +complete interaction, door collision, animation playback or visual fidelity. + +## Evidence and prepared fixtures + +LV1B has nine relevant model instances, sharing six source models: + +| Source entities | Original model | Triangles per instance | Texture binding | +|---|---|---:|---| +| PHONE1 / PHONE2 | `phone.omt`, `3DSh:0` | 90 | Three original material/canvas links | +| bars | GAM `ASEFile=bars.ase` | 54 | GAM `PNGFile=chain.png` | +| Two `C3DBUTTON` records | GAM `Up.ase` / `Down.ase` | 16 each variant | GAM `UpDown.Png=switch.png` | +| dino | GAM `objects.omt`, `3DSh:27` | 256 | Original material27 -> canvas26 | +| plant1 / plant2 / plant3 | GAM `objects.omt`, `3DSh:28` | 168 | Original material28 -> canvas27 | + +VR01 has two phone booths, using the same verified `phone.omt:3DSh:0` source +binding. Both booth instances remain separate even though their GAM tags match. + +The phone class opens `phone.omt` at EXE `0x43579d` and selects shape0 at +`0x4357c9`. The similarly named `phone.ASE` and standalone `phone.png` are other +assets and are not substituted. Its three material links are `{0:Canv1, +1:Canv0,2:Canv2}`. The 90 triangles span **five** source material draw ranges, +with index counts `[120,6,12,6,126]`; retaining only a single final draw would omit +parts of the booth. + +Button resource registrations are recovered at EXE `0x411695`, `0x4116c3`, +`0x411722`. InitObject at `0x411b93` selects literal `UP` (`0x4ed9bc`), so the +default static variant is source-backed. The consumer recognizes `UP` / `HIUP` +and `DOWN` / `HIDOWN`. It displays the first authored pose of the selected +variant; it does not imply that button morph transition timing is reconstructed. +Bars and other explicit ASEFile/PNGFile pairs retain the first authored sample +and the proven ASE-to-OMT axis/UV conversion. No additional node transform or +floor correction is introduced. + +## Preparation interface + +```python +prepare_models(original: Path, level_file: str, output: Path) -> dict +``` + +From `GamePort/`: + +```sh +python3 tools/extractors/models.py --level level1b.gam --output artifacts/extracted/level1b/models +python3 tools/extractors/models.py --level VR01.gam --output artifacts/extracted/VR01/models +python3 -m unittest discover -s tests -p test_models.py -v +``` + +`models.json` schema1 contains: + +- Source GAM path/hash and level code. +- `models`: unique keys, relative scene JSON paths, source hashes/resource + identities and geometry counts. +- `actors`: original ordinal/byte offset/tag/class, default variant, variant-to- + model-key references, and mapping evidence. +- `unresolved`: incomplete explicit mappings; no class default is invented. + +Each OMT model exports only its selected `3DSh` and transitively referenced +`3DMa` / `Canv` resources. Source material/texture IDs remain local inside each +model scene file. No unrelated archive geometry is copied. Existing ASE and PNG +assets are decoded locally, without modifying originals. + +The source corpus contains one Level3C button at GAM offset33909 whose explicit +`UpDown.Png` is `none`. It is recorded unresolved and omitted from model actors +until its actual constructor/fallback binding is recovered. LV1B/VR01 have no +unresolved entries in this subset. Other classes without explicit bindings are +outside this consumer and are not presumed invisible or complete. + +## Runtime interface and invariants + +```csharp +new StaticSceneVisuals(Mesh combined, SceneDirector director, + string assetsRoot, string preparedRoot); +Mesh Mesh { get; } +void Update(Mesh destination); +``` + +`preparedRoot` is the scene's `models` directory containing `models.json`. +All required geometry/texture bytes are prepared; no speculative runtime fallback +uses `assetsRoot`. Actor lookup uses original source GAM byte offsets rather than +tags, preserving duplicate tags. The integration can append later consumers and +pass the resulting combined mesh to `Update`. + +All source model vertex/index/draw ranges are retained. Each instance/variant +gets distinct texture IDs starting at `int.MinValue+20000`; preexisting identity +collisions are rejected. The actual lab consumer adds19 original draw ranges +and15 texture identities. Every phone material draw follows actor visibility. +Button inactive variants keep allocated ranges but do not draw. + +Director position/rotation updates transform original local vertices directly. +The current shared actor rotation convention is X, negative yaw Y, then Z, +followed by the director position. Exact general Euler composition still requires +original comparison; tests establish the implemented translation and yaw behavior. +No character grounding/floor correction is applied to these props. Bars movement +is visible only when a separate recovered gameplay consumer changes its actor +root; this visual consumer itself does not invent opening motion. + +Null material handling matches the existing original DX rule: preserve geometry +but skip draws whose original material is null or unresolved. The original LV1B +invisible proxies reference absent material18; selective extraction preserves +those links and reports `nullMaterialIds` rather than fabricating a white material. +An explicit empty draw list stays empty on mesh integration. + +## Verification + +Eight Python test groups include a locally compiled .NET10 consumer harness. +They verify actual phone geometry and all five material ranges, explicit model +bindings, OMT subset export, duplicate tags, source hashes/output boundaries, +missing mapping reporting, distinct texture IDs, translation/yaw/no floor +correction, hide/show, independent button variants, retained combined buffers, +reserved-ID conflict rejection, and null-material geometry without invented draws. + +The main C# project builds with zero warnings/errors after adding the consumer. +Prepared asset and managed harness checks are not GPU or original-runtime fidelity +verification. Primary integration must verify scene rendering, updating the final +combined buffers, source entity transitions, packaging, and native platform behavior. diff --git a/docs/analysis/sound-effects.md b/docs/analysis/sound-effects.md new file mode 100644 index 0000000..a09dd70 --- /dev/null +++ b/docs/analysis/sound-effects.md @@ -0,0 +1,45 @@ +# Original default effects bank + +Read-only EXE/OMT recovery and port SDL stream checks,2026-10-24. Text offsets +are VA minus0x400000. This is not original-game audio comparison or speaker testing. + +Jimmy PostLoad423642 pushes string4EE08C=`SoundEffects.omt`, calls46A910, +and stores its database pointer to current sound database696008 at423656. +The separate sounds.omt has only4 waves and is not the numeric gameplay SFX bank. +SoundEffects.omt supplies251 Wave identities, including58=`door closing`, +59=`Door opening loop`,230=`winning prize2`. + +458980 forwards three arguments to47D390;4589C0 forwards four to47D640 after +checking global4F8434. Both set volume through47DC80 from4F6B38.47D390 checks +current database696008 and tests/loads FourCC Wave/id via interface slots20/14 +at47D3B6..DA. Contextual voice/music paths may temporarily switch the current +bank; the consumer currently uses the proven default for pickup/mechanism events. +This does not recover the entire original bank-switching/channel system. + +Vertical-door417B28..43 calls4589C0(actor,-1,59,1), retaining its returned handle +while moving.41797E..4179AE stops that handle through458A00(handle,0), clears it +to-1 and calls4589C0(actor,-1,58,0). Reversing while the handle exists does not +start a second loop. Button411Cxx uses serialized AvailSound. Pickup435Fxx uses +serialized SoundIndex; trophy's230 identity is retained by the interaction path. + +`tools/extractors/sound_bank.py` preserves each bounded source RIFF byte sequence, +archive/id/name/offset/hash and PCM duration in effects/effects.json. One resource, +162 bird1, contains format55 (MPEG Layer3) in RIFF. Its explicit fact sample count +is25344 at11025Hz; the encoded payload is retained unchanged. SDL3.4.2 local +src/audio/SDL_wave.c1755..57 explicitly rejects MPEG formats. Playback of162 +therefore requires a separate decoder/conversion and remains unsupported; it is +not silently substituted. The currently connected lab effects use PCM resources. + +PreparedEntityResources merges the bank with per-scene explicit references; +duplicate identities require equal duration and identical payload bytes. SceneAudio +uses independent one-shot streams and owner-keyed loops, stops door loops on +completion/reset, and disposes all voices on scene rebuild. Music and speech remain +independent. Original attenuation/pan/volume/channel limits and full jetpack sound +callbacks are incomplete, so current SDL mixing is an implementation policy. + +Verification:2 Python tests compare all251 emitted RIFFs to exact original slices, +check original bank/call/FourCC instruction bytes, preserve source hash and reject +output in Original. Managed merge tests reject conflicting identities. The SDL +dummy-device --effects-audio-smoke consumes original58/59 streams, retains a +one-shot while stopping the loop, adds230 independently and clears all streams. +No physical speaker, original timing/position or native Windows audio claim follows. diff --git a/docs/analysis/ui.md b/docs/analysis/ui.md new file mode 100644 index 0000000..2b894e5 --- /dev/null +++ b/docs/analysis/ui.md @@ -0,0 +1,133 @@ +# Original laboratory objectives and practice modal + +Evidence: read-only Neutron.exe disassembly (`artifacts/binary/neutron.asm`), +original `omt/screens.omt`, and `alpha.omt`. EXE VAs below equal file offsets +plus `0x400000` for these sections. Static evidence and decoded original art +are verified; original modal/HUD runtime comparison remains outstanding. + +## Recovered screen resources and coordinates + +`402687..4026E8` registers slot0=`screens:Canv156` objectivePad, +slot1=120 labobjective0A, slot2=121 labobjective0B, slot3=122 labobjective0C. +Their original pixels say **GET JET PACK.**, **TALK TO CARL.**, and +**FOLLOW CARL OUTSIDE.** respectively. GAM pickup tag `shrinkray` is the +prototype/internal name of the lab jetpack (inventory group0/item3); the art +does not describe it as a shrink-ray weapon. + +| Element | Original identity | Native dimensions | Reference top-left | +| --- | --- | --- | --- | +| Objective pad | screens Canv156 | 320x173 | (384,380+offset) | +| Current objective | screens Canv120/121/122 | 256x29 | (384,448+offset) | +| Objective selector digit | alpha Canv83/84/85 | 8x8 | (393,450+offset) | +| PracticeYesNo | screens Canv169 | 207x100 | (210,210) | + +`402C40` positions visible flagged objectives at x384, +y=`448 + self[4EC] + visibleRow*15`. `407070` renders the pad at x384, +y=`380+self[4EC]` during its stationary phase and prints selector `%d` +(`4EC794`) at (393,450+offset), font tag SMAL (`534D414C`). `401F9D` +initializes offset=-69; `406590` changes -69 to0, while `406650` changes0 to-69. +These source paths toggle vertical layout and other gadget UI, not a simple +objective visibility bit. The pad extends beyond the640x480 reference viewport; +retain clipping rather than repositioning it to fit. + +`406F50(index,flag)` only accepts index>0: it clears44 dword flags at4F7D00, +sets selector4F8194, resets animation timer4F8188, then enables the selected +entry. It does not map selector0 to objective1. The source has sliding/timed +objective presentation; the consumer currently renders its stationary geometry +under caller-controlled visibility. Animation and exact source visibility timing +are not yet implemented. + +`402D70/402CC0` convert positions using windowWidth/640 and windowHeight/480; +constants at file8D40C=1/640 and8D408=1/480. The port quads use NDC +`(2*x/640-1,2*y/480-1,0)` with an identity overlay transform. Original bitmap +UV orientation is top-down, retained as(0,0) at top-left. + +Gameplay text uses individual `alpha.omt` canvases, not editor +`fontsmall.png`: `4683E0` loads `alpha.omt` (string4F51D8), copies6x64 +Canv pointer sets from table4F4ED8, and `468B80` maps uppercase ASCII-32. +SMAL selects set1; table entries for '1'/'2'/'3' are83/84/85. The separate +fontsmall CanvasFont is created in editor initialization46B280..46B3C7 and +must not silently substitute for gameplay digits. + +## Practice request, input and dispatch + +`402243..402273` binds Canv169 at(210,210). `406F90(type)` guards against +an existing modal (4F8198), shows the matching canvas, enables cursor, +pauses the main game through virtual168, then stores type at4F8048. Type0 +uses169, whose pixels explicitly ask **DO YOU WANT TO PRACTICE? YES / NO**. + +`46A360/46A380` set/clear keyboard bytes at509838+virtualKey; +46A3A0/46A3B0 track left mouse at509834. Consequently modal code reads +Y=509891, N=509886, Enter=509845. Source404523..404586 defines strict +Yes hit bounds2254046AF. It hides the +modal/highlight, clears4F8198, disables cursor, invokes4063E0 for screen155, +and calls Jimmy virtual168 (`43B5A0`) with: + +``` +targetLevel = "VR04.gam" (4EC77C) +targetStart = "PHONEBOOTH" (4EC788) +returnLevel = Jimmy+955 +returnStart = Jimmy+724 +``` + +The latter field names follow how43B5A0 stages requested/current strings; +the argument addresses and literal targets are certain. Modal1/2/3 dispatch +VR03/VR02/VR01 respectively, so type0 must not be routed toVR01. +Runtime checkpoint42AF00 captures the current level code and a16-byte +actor root into Jimmy+1E48/+1E38 separately. This does not prove the +meaning of the saved TSK StoredVector or justify overwriting it. + +No path404D1E hides practice elements, clears4F8198, disables cursor and +unpauses main game virtual168(0); yes continues into the level transition. + +## Implementation and verification + +- `tools/extractors/ui.py` exports only the8 proven canvases, retaining original + identity, database, offset, source size, whole-input hashes and decoded RGBA + hashes. It validates every requested identity/dimension before writing and + rejects destinations overlapping source directories. +- `Application/SceneHud.cs` bounds manifest/depth/count, exact canvas dimensions, + paths and decoded byte counts; appends screen-space indexed quads to the scene, + preserves world draws/textures, and updates the final merged vertex buffer. + Selector0 produces no invented objective image. Input/modal state belongs to + the caller. +- `python3 tests/GamePort.HudTests/test_ui.py` verifies exact original RGBA, + output roundtrip, missing-resource rejection and input hash preservation. +- `dotnet run --project tests/GamePort.HudTests -- artifacts/prepared/ui/ui.json` + verifies final-buffer writes, original coordinates, digit/objective/modal + visibility, retained implicit world draw, and malformed-resource rejection. + +Both targeted commands passed24Oct2026. Integrated headless overlays/VR04 entry +and GTX1070/Xvfb modal pause/N/resume/resize pass with zero validation errors. +The packaged Windows Wine64 modal check also passes with validation disabled; +native Windows/original-game comparison remain outstanding. + +## Return-context field confirmation + +Follow-up field tracing confirms the meaning of the two staged return arguments: + +- Literal4EF524 is `level1b.gam`. Jimmy constructor437656..437684 copies it + to complete-object+955, initializing the current/requested GAM filename. +- Constructor437589..4375B5 initializes+724 from4ECA6C=`none`, not PHONEBOOTH. +- PlayerLoadLevel43B5A0 copies its second argument (requested start tag) to+724 + at43B6A7..43B6E0, first argument (requested GAM) to+955 at43B764..43B78C, + third argument (return GAM) to+88C, and fourth argument (return start) to+8F0. +- TSK load460A83..460AE5 reads the saved StartPoint string and copies it to + +724 and+774. The supplied NewGame StartPoint is STARTEXP, so a lab practice + transition after loading NewGame should carry ReturnStart=STARTEXP, rather + than copying NewGame's preexisting ReturnStart=`none`. +-40B70A..40B770 looks up+724 with actor lookup474070 and assigns that actor's + root transform to Jimmy, independently confirming that this buffer is a + start entity tag. Runtime checkpoint42AF00 does not alter it. + +Therefore source modal0 Yes preserves current `level1b.gam`/`STARTEXP` as the +return pair for the normal NewGame route, while entering VR04/PHONEBOOTH. +Its separately captured checkpoint root and unknown TSK StoredVector remain +distinct evidence; a new PHONEBOOTH return marker must not be invented. diff --git a/docs/architecture.md b/docs/architecture.md index 751c4fb..27fdc01 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -40,7 +40,7 @@ and pause simulation, while C pauses for inspection and R resets the start area. triangles, including invisible proxies, and clips the chase camera with a sphere sweep. Solver/masks/radius/pivot are explicit approximations. The physical position is feet; a separate original-root height feeds camera math and standing mesh minimum -Y feeds visual placement. GAM/ASE data is preserved. There is no task/trigger engine. +Y feeds visual placement. GAM/ASE data is preserved. SceneDirector supplies the separate task/trigger interpreter. Application/PreviewCharacterPlacement and PreviewAnimationLibrary keep inspection policies available alongside the walking checkpoint. Inspector ground contact is a model-only offset @@ -53,3 +53,58 @@ floor-derived pivot still require original comparison and further recovery. Subsystem implementation and validated ownership are documented in `infrastructure.md`, `analysis/graphics.md` and `rendering.md` as they become available. Persistent docs distinguish planned architecture from verified behavior. + + +SceneDirector interprets original synchronous AI actions and CAM/MCA speech/camera +sequences from mutable copies of GAM actors. PreparedEntityResources retains +archive/type/id identities and PCM durations; SceneAudio independently streams +music and speech. SceneActorVisuals and SceneSpriteVisuals append original morphs +and source-sized Canv quads to a combined mesh. Shared draw visibility changes +before synchronous rendering; vertex ranges remain independent after composition. +SpriteSequence implements recovered per-call timing/stop/hide modes. Billboard +orientation, some actor aliases, pivots and actual playback-end synchronization +remain provisional. + +TaskStates and TaskActivation retain original case/sentinel/numeric gates. +OriginalSave accounts for every TSK byte and preserves unknown data. SceneInteractions +implements star/trophy/lab jetpack contacts, Carl dialogue dispatch and LOAD requests, tracking +contact entry by source offset (duplicate tags remain distinct). Main disposes +renderer/window/audio before rebuilding the next scene, carrying task/items/score. +Checkpoint CLI saves use atomic replacement outside asset directories; complete +runtime saves, menus and configuration are not yet implemented. + + +ActorPatrol implements the recovered common patrol phases and actor-specific +profiles. OriginalScenePhysics uses recovered support/trace/magnitude and source +wall-mask metadata, with a provisional modern wall solver. LabSimulation retains +its provisional feet capsule, recovered normal root clearance75.9 and visual sole +placement. DynamicSceneCollision builds source3DUD box triangles/broadphase; +DynamicBodyResponse supplies the modern narrowphase. Keep these evidence boundaries +explicit rather than presenting the complete original solver as recovered. + +SceneMechanisms consumes button contacts and explicit door toggle requests, maintains +vertical-door movement/hold/reversal and emits sound/stop events. StaticSceneVisuals +transforms original model actors into the final combined buffer, preserving source +local bounds separately from visible material geometry. Collision uses source flags +and transforms rather than draw visibility. + +JetpackBurst exposes controller/effect phases independently; LabSimulation currently +orders controller -> collision -> effect at60Hz. Inventory slot0/3, current energy, +level exceptions, effect radius and original FLY/fire morph consumers are connected. +The complete original global object update order is unverified. SceneInteractions +snapshots live energy, tasks, inventory, objective selector and RETURN strings. + +PracticePrompt implements source strict Yes/No regions and keyboard dispatch; +Program pauses simulation while modal, clears held input and rebuilds VR04 on Yes. +SceneHud appends source640x480 screen quads; the Vulkan overlay pipeline disables +depth and draws after world geometry using identity transforms. Panel slide timing, +full HUD state and practice highlighting remain incomplete. Fixed-size authored art +is scaled with the viewport; input uses matching logical-window coordinates. + +Prepared effects/effects.json preserves251 original SoundEffects.omt identities +and RIFF payloads, including one MPEG-in-RIFF resource whose playback is unverified. +PreparedEntityResources merges this explicit bank with per-scene named resources. +SceneAudio mixes independent SDL streams for music/speech/one-shots and owner-keyed +effect loops. Pickup and mechanism events are connected, including loop stop on +bar movement completion/reset. Original positional/channel/volume policies and +jetpack sound callbacks remain open; no online audio or services are used. diff --git a/docs/compatibility.md b/docs/compatibility.md index 4bb19b2..0e06408 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -11,10 +11,10 @@ separate evidence categories. **The game is not fully reconstructed/playable yet | C# original loaders | Linux runtime | All128 PNG /254 ASE base meshes; morph/base UV tests | | .NET10 Linux build | Pass, zero warnings/errors | Local SDK10.0.402/runtime10.0.13 | | Windows x64 publish | Pass | Correct PE32+ app and SDL3.dll; initial native rendering user-reported | -| Windows package under Wine64 | Preliminary headless pass | Two frames, exit0; fixed-time readback identical to Linux on lavapipe; validation disabled | +| Windows story/practice package under Wine64 | Preliminary headless/window pass |12s story;12-frame practice pause/N/resume/resize and original streams; simulation matches Linux; validation disabled | | Corrected Windows preview under Wine64 | Preliminary window pass | Six frames, key2 animation switch, resize800x600, exit0; validation disabled | | Windows walking package under Wine64 | Preliminary240-step window pass | SDL arrows/Shift, walking/jump/landing and800x600 resize; matches Linux movement statistics; validation disabled | -| Linux self-contained package | Native run verified | Two headless frames without SDK/source/originals mounted | +| Linux self-contained package | Native headless/window verified |12s story without SDK/source/Original mounted; GTX1070 practice pause/N/resume/resize, zero validation errors | | Vulkan1.3 lab | llvmpipe + GTX1070 | Real indexed/textured/depth frame/readback; validation enabled, zero errors | | Original camera/projection | Data/math integrated | GAM camera, recovered FOV/clips; startup/follow behavior not compared | | Jimmy normal texture / morph | Native preview verified | Correct atlas slot0, base topology/UV retained; state speed/loop unverified | @@ -32,12 +32,27 @@ separate evidence categories. **The game is not fully reconstructed/playable yet | Simulation cadence | 13 movement groups pass | Fixed60Hz independent of60/120/144Hz rendering, ten-minute finite run; original cadence unresolved | | Walking camera and animation | Linux headless/window pass | Original five motion clips, recovered eye180/target99; pivot, timing and obstruction solver provisional | | Walk SDL input/resize | GTX1070/Xvfb240-step pass | Arrows/Shift injected through SDL; travel1250.12,jump/landing; resize800x600; zero validation errors | -| Intro/task/entity/gameplay loop | Incomplete | GAM data recovery is not task execution or gameplay | +| TSK saves/task gates | All12 originals byte-round-trip | Bounded parse/write, task/items/score/checkpoint CLI resume; full game-state/menu save incomplete | +| Lab CAM/MCA/AI interpreter | Source sequence tests + Linux GPU pass |16 speech cues, recovered camera formulas, skip/actions/control restoration; no original comparison | +| Dynamic actors/sprites/models | Linux GPU pass |Carl/Goddard/Jimmy morphs, source Canv timing and9 original lab props; billboard/alpha, pivots and playback timing remain provisional | +| Scene music/speech | Linux dummy-device pass |Independent stream consumption and speech replacement; speakers/latency/Windows audio unverified | +| VR01 star/trophy contacts | Source-data tests pass |5-point stars,300 trophy, acquired flags and contact-enter semantics; distance/exclusions/box approximation | +| RETURN / renderer recreation | Linux headless pass |Original VR01 RETURN dispatch renders VR01 thenLV1B, zero validation errors; fades/window transition unverified | +| Supplied scene availability |All35 GAMs supplied;33 have OMT geometry |Level3B/E GAMs are duplicate four-entity records apart from level code; registered OMT archives absent, normal gameplay use unverified; no substitution or established blocker | +| Lab task/contact route | Managed and headless GPU pass |Explanation/jetpack/Carl/exit reachesSCENE60, score150 andlevel1; direct contacts do not verify navigation | +| Patrol/support |10 patrol +13 support groups pass |Source phases/profiles and8 DLL magnitude refs; Carl sensing, Goddard follow and full wall response incomplete | +| Buttons/doors | Source state tests and GPU props pass |Cooldown, hold/reversal, original model transforms; source broadphase/box order with modern narrowphase | +| Dynamic collision |10 managed groups pass |Includes actual closed/open lab bars; full source solver/activation exclusions incomplete | +| Lab objectives/practice | Art/data/managed/headless + native Linux window pass |Exact source coordinates, modal pause, Y/N/pointer rules; N resumes and resize800x600 onGTX1070, zero errors; slide/highlight incomplete | +| Jetpack tutorial |14 state groups +300-step VR04 GPU pass |FLY/fire effect, radius/timer/energy/VR rules; maxrise418.98/landing, zero validation errors; phase/shadow/collision approximations | +| Default effects bank |251 exact RIFF exports, SDL dummy pass |Pickup/button/door sounds and owner-loop stop; positional/volume/channel policy incomplete; MPEG-in-RIFF bird1/id162 unsupported by SDL WAV | +| Complete scene/gameplay loop | Incomplete |Lab navigation, exact collision/pivot/cadence and original reference comparison still required | | Menus/AI/combat/progression/saves | Incomplete | Required future work | | Original execution | Attempted under isolated Wine11 | Window created, GL/Vulkan rendering unusable; no reference comparison | -| Native Windows functionality | Loading/rendering user-confirmed | This movement checkpoint/input/audio/resize still unverified natively | +| Native Windows functionality | Loading/rendering user-confirmed | Current story/tutorial/input/audio/resize still unverified natively | -Generated evidence: artifacts/final-tests.log, test-level1b.ppm, test-player.ppm, +Generated evidence: artifacts/full-integration-test.log, practice-window.log, +practice-transition.log, jetpack-runtime.log, final-tests.log, test-level1b.ppm, test-player.ppm, resize-input.ppm, package-linux.ppm, extracted/audit.json and reference*/ logs. The lab/player images have been visually inspected; they do not establish original visual equivalence. Windows cross-publishing must not be represented as Windows @@ -45,6 +60,6 @@ runtime validation. Package scope and prerequisites are in infrastructure.md. Known visual/behavior limits include incomplete lighting/fog/blend/culling/material mapping, inferred model/root pivot, provisional collision/cadence/animation timing, -close-wall camera clipping near Jimmy, absent intro/trigger/interaction execution, +close-wall camera clipping near Jimmy, incomplete class-specific triggers/interactions, and no original comparison captures. Walk evidence: artifacts/walk-tests.log, test-walk.ppm, walk-start.png and walk-window.ppm. Original fidelity is unverified. diff --git a/docs/decisions.md b/docs/decisions.md index 97f435b..bcaf52f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -33,3 +33,33 @@ masks. Document the skipped intro, missing interactions, transient jump-state simplification, animation timing and close-wall camera limitation. Test against source geometry and build both packages without calling this a faithful full scene. + +10. **Source-driven scene interpreter.** Preserve synchronous AI action dispatch, + original camera formulas and audio-duration advancement rather than adding a + fixed intro timer or completingSCENE on intro end. Separate task activation, + sprite playback, draw visibility and physical collision. Report unrecovered + behavior explicitly. Preserve unknown TSK fields and original checkpoint resume; + no claim of arbitrary-position/full-state save support. +11. **Separate supplied records from required content.** All35 GAM entity files + exist;33 have matching OMT geometry archives. Level3B/Level3E GAMs contain the + same four entities apart from their level code, with no incoming serialized + GAM transition or supplied save selecting them. Their original classes name + absent OMT archives, but registration alone does not prove normal gameplay use. + Record unavailable geometry without substitution; do not classify it as a + reconstruction blocker or request more files unless progression requires it. + +12. **Preserve source physics boundaries.** Recovered quick magnitude, support trace, + radii/factors and3DUD broadphase/triangle ordering stay separate from provisional + wall/capsule response. Check isolated original DLL results without executing or + modifying originals in place. Keep visual soles distinct from logical root75.9. +13. **Correct prototype names from original evidence.** The pickup tagged SHRINKRAY + is the jet pack in original objective art and inventory slot0/3 code. Practice0 + entersVR04/PHONEBOOTH with current GAM/STRT return context. Do not invent a + shrink-ray weapon, VR01 mapping or TSK StoredVector checkpoint meaning. +14. **Compose original UI and effect assets.** Draw source640x480 UI in a separate + depth-disabled overlay; retain clipped original coordinates. Use exact default + SoundEffects.omt identities for lab effects, preserve encoded RIFF resources + and document unsupported decoders. Do not substitute editor fonts/audio banks. +15. **Default recovered scene play.** Start the integrated lab story/interactions by + default; retain --inspect and deterministic smoke modes. Passing direct-contact + tests does not establish navigation, original fidelity or full-game completion. diff --git a/docs/infrastructure.md b/docs/infrastructure.md index fa2674b..5beb0ba 100644 --- a/docs/infrastructure.md +++ b/docs/infrastructure.md @@ -61,18 +61,22 @@ animation state/render sorting are incomplete. See rendering.md for evidence. ## Scope limits -This is a controllable lab checkpoint, not complete reconstructed gameplay. -Collision solver/masks/dimensions, pivot,60Hz cadence, camera obstruction and -animation state timing remain provisional. Original task/trigger execution, -introductory cutscene, inventory, combat, enemies, progression, save/load, mouse -steering and remaining scenes are incomplete. The default now walks/jumps from -the original start area; `--inspect` retains clip selection with keys1/2/3/4. -Default idle samples remain identical. The floor-derived visual transform is -separate from original physics; details are in the movement/collision reports. +The default now runs the lab story and recovered interactions, source props/patrol, +objectives/practice modal and jet pack tutorial. --skip-intro restores control; +--inspect retains the scene/clip inspector. Collision response, visual pivot, +60Hz cadence, global phase order and animation/render-state fidelity remain +provisional. Full combat/AI/progression/menus/runtime saves are incomplete. -Packages include local copies of asset directories (ASE/png/gam/omt), original -font PNGs/NewGame/readme, lab/Jimmy scene resources, recovered music, .NET runtime, -SDL3, SPIR-V and these limitations. Legacy EXEs/DLLs, old user save slots, tool -caches and analysis databases are not runtime dependencies. Vulkan drivers remain -platform prerequisites. Initial native Windows rendering is user-reported; the -movement checkpoint and broader native Windows functionality remain unverified. +Packages include all33 available prepared scene pairs, original ASE/png/gam/omt +copies, alpha.omt, entity speech/canvases, actor clips, original UI,251 preserved +effect RIFF resources, .NET runtime, native SDL3 and SPIR-V. Legacy EXE/DLLs, tool +caches and original save slots are not runtime dependencies. Level3B/E GAMs are +supplied; registered geometry archives are absent but gameplay use is unverified, +so this is not an established missing-content blocker. No substitutes are used. + +SceneAudio connects music/speech, pickup/button/door effects and owner loop stops. +Original positioning/volume/channel policy, jetpack callbacks and MPEG-in-RIFF +bird1/id162 decoding are unfinished. Linux dummy streams establish consumption, +not speaker output or historical fidelity. Native Windows story/input/audio and +original comparison remain unverified. See compatibility.md and progress.md for +current tests; these packages are investigation checkpoints, not a finished release. diff --git a/docs/progress.md b/docs/progress.md index 0ff4fd8..72b0580 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -1,134 +1,103 @@ -# Progress — current checkpoint +# Progress — 2026-10-24 -**Full reconstruction is incomplete.** The current milestone is an evidence-backed -asset recovery toolchain and a controllable original lab with local Linux/Windows -packages. This is a movement checkpoint, not a completely reconstructed scene. +**The full reconstruction is incomplete.** The current implementation extends the +user-verified Windows rendering checkpoint into an interactive original lab and +jet pack tutorial flow. This is not a verified faithful complete scene or release. -## Controllable lab checkpoint +## Current integrated behavior -The user confirmed that the previous Windows build loads and renders and asked -to advance. The default now runs walking/backpedaling/turning, ballistic no-gadget -jumping, source-triangle collision, a chase camera, and original idle/run/backpedal/ -jump/fall clips. Arrows move, Shift/Insert/numpad0/right mouse jump, R resets, C -pauses for inspection/resumes, F11 fullscreen, Escape quits. The intro is skipped. +- Default play runs LV1B STARTEXP and its16-cue CAM/MCA/AI camera/speech sequence. + Escape/Space skips actions and restores control; `--inspect` retains inspection. +- Original walking/backpedal/turn/jump arithmetic, source clips, chase camera and + fixed60Hz port simulation. Powered jumping now translates the recovered state + table,8-second effect timer,60/100 contact radii and energy/VR immunity rules. +- Original Carl/Goddard morphs, sprite quads and9 lab model actors, including the + OMT phones, source buttons and moving bars. Goddard's unregistered STOP/WALK/TALK + requests retain the current source clip rather than invented aliases. +- Shared patrol states1/3/7, state9 base motion and Carl's WALK/STOP profile. + Body support uses recovered radii, factors, quick magnitude and one-sided trace; + full wall response and Carl sensing remain incomplete. +- Lab explanation -> SCENE35 -> jet pack pickup -> SCENE50 -> Carl contact/talk + -> SCENE60 -> outside LOAD dispatch. Pickup adds50, Carl callback adds100 before + dialogue. Source task gates/objective selector and inventory slot0/3 persist. +- The pickup's internal tag `shrinkray` names the lab jet pack, proven by original + GET JET PACK art and powered-jump inventory checks. It is not a shrink-ray weapon. +- Original objective pad, three lab objective images, digits and PracticeYesNo + are rendered at source640x480 coordinates. O changes stationary panel offset. + Practice pauses the simulation; Y enters VR04/PHONEBOOTH and N resumes. + Return context is current GAM/latest STRT (LV1B/STARTEXP for NewGame), separate + from the still-unrecovered runtime checkpoint-root restoration. +- Button contact/cooldown/down/up/next-trigger and vertical-door duration, + reversal/hold/next-trigger logic. Source dynamic-box broadphase/triangle ordering + is translated; narrowphase/response still uses a modern approximation. +- Ordinary stars/trophy, score and acquired flags; all12 TSK files round-trip. + CLI checkpoint load/write preserves unknown fields, inventory, tasks, energy, + objective selector and RETURN context. Complete runtime/menu saving is unfinished. +- Music and speech use independent SDL streams. Positional effects/banks and + physical audio verification remain unfinished. Original default-bank pickup/button/ + moving-door one-shots and owner loop stop are now connected; attenuation/volume + policy and jetpack sound callbacks remain unfinished. -Recovered arithmetic and addresses are in `analysis/movement-checkpoint.md`. -Notable corrections: Left precedence; current-yaw target offsets rather than -accumulating destination yaw; Up halves keyboard turn; turning alone decays speed; -no ordinary midair arrow steering; disabled-gadget long hold can repeat on landing; -normal camera eye `(0,180,-350)` and target `(0,99,0)`. Exact original frame order -is unresolved; the transient disabled-gadget state3 transition is collapsed. +## Source availability and evidence -Explicit port approximations: fixed60Hz cadence, capsule radius24 and standing -height209.4361, floor-derived model/root separation, static sweep/slide solver and -all-source-triangle mask, camera sphere obstruction, animation state/loop timing. -Collision retains all2869 lab triangles including325 invisible proxy triangles. -Original solver/masks, actor pivot/scale, stairs/dynamic objects and state activation -remain unresolved. At walls the clipped camera can move close to Jimmy. +All539 original hashes remain the baseline. All35 GAM files are supplied and33 +have matching OMT geometry. Level3B/E GAMs exist, each1777 bytes, and are identical +after their four-byte level identifiers. Their classes name absent OMT archives, +but no serialized incoming GAM transition or supplied save selects them; loader +null handling does not establish a fatal failure. Normal gameplay use is unverified, +so these are not an established blocker and no extra files are currently requested. +The catalog preserves absent geometry without substitution. -Verification: 11 collision and13 movement groups pass, including real lab source -geometry, long/high-speed sweeps, held/re-pressed jumping, ten-minute stability, -deterministic replay and60/120/144Hz presentation yielding the same simulation. -A240-step GPU walk/jump replay travels1250.12 units, jumps once, lands, and ends -grounded; maximum rise137.62. This is port behavior, not original fidelity proof. -The Linux SDL window run receives injected movement/jump keys, resizes800x600, -and reports zero Vulkan validation errors on GTX1070. Headless llvmpipe also -reports zero errors. User-confirmed native Windows loading/rendering applies to -the previous build; native Windows movement validation remains outstanding. -Both self-contained packages were rebuilt. The Linux package passes the same -GTX1070 window replay; the Windows package passes240 windowed frames under isolated -Wine64 with SDL keys/jump/resize and identical movement statistics (validation -disabled there). Wine is preliminary compatibility evidence, not native Windows. -One additional inspector-window regression was not executed because automatic -approval review was unavailable; the full headless inspector regressions passed. +Detailed recovery: analysis/lab-progression.md, scene-entities.md, scene-models.md, +patrol.md, original-collision.md, dynamic-collision.md, buttons-doors.md, ui.md, +jetpack.md, level-resource-mapping.md, and save-format.md. Addresses, source offsets, +confidence and approximation boundaries are retained there. -## Latest user-reported preview fix +## Verification -The user ran the Windows build and observed a static Jimmy partially inside the -lab floor. This verifies initial Windows startup/rendering by user report, with -OS/GPU/version/input/audio details unspecified. The user subsequently confirmed that the corrected build loads and renders. +Managed checks cover source data, director/actions/cameras, task/interactions, +patrol, recovered support, moving-box collision, jetpack states and HUD composition. +Python currently has35 top-level regression tests plus2 targeted UI extraction tests. +Existing11 collision and13 movement groups pass;14 jetpack groups pass. Eight +quick-magnitude float results are checked against an isolated original DLL probe. +Original mode2 standing/jump animation probes confirm zero dynamic-point offsets +for the tested clips. This is DLL evidence, not observed original game behavior. -Both issues were reproduced from actual assets: jimstop has two byte-identical -vertex poses, and its minimum local Y=-64.6165 plus GAM Y=26.6619 places the soles -at -37.9546 while the original visible floor is near Y=0.5486. Calling the default -an animated idle was inaccurate. The idle stays faithful to its still source pose; -1/2/3/4 now explicitly select idle/run/jump/scratch previews and the window title -states the mode/controls. A source-data-based preview correction of +38.503 Y -places the standing model on visible floor triangles, leaving GAM data unchanged. -This is an explicit preview policy, not the recovered game collision solver. +Headless llvmpipe runs render the story, model actors, practice prompt, lab exit +and VR04 entry with zero Vulkan validation errors. The300-step VR04 powered replay +jumps once, rises418.98 units and lands; VR immunity retains20 energy. The ordinary +240-step replay travels1250.12 and rises137.62; port landing-count telemetry changed +with the explicit state table. These measurements verify port behavior only. +See artifacts/full-integration-test.log and practice/jetpack logs for current checks. -Tests verify real lab grounding, ceiling/invisible-proxy rejection, still idle and -moving clips, automatic animation advance in actual GPU readbacks, and SDL keyboard -switching to a run cycle. Khronos validation reports zero errors on llvmpipe and -GTX1070. Source assets remain unchanged. See rendering.md for evidence/scope. -The rebuilt Windows package additionally passed an isolated Wine64 window test: -six frames, animation key2 selected moving source samples, resize800x600, exit0. -Validation was disabled in that Wine test; corrected native Windows retest is pending. +The full scripts/test.sh integration passed:35 Python regressions,2 targeted UI +checks, all managed groups, GPU story/route/practice/VR04 replays, SDL dummy streams +and539 unchanged original hashes. Both self-contained packages rebuilt successfully. +Linux package runs the12s story without SDK/source/Original mounted, zero Vulkan +validation errors. Its GTX1070/Xvfb practice window pauses, receives N, resumes11 +steps and resizes800x600 with zero validation errors and original pickup audio. +The Windows package passes the same12-frame practice/input/resize/stream check +under isolated Wine64, matching simulation statistics (validation disabled). +It also renders the12s story under Wine. Generated package logs live under +artifacts/package-integration.log, linux-package-integration/, package-practice-window.log +and windows-practice-package/. Initial native Windows loading/rendering remains +user-confirmed for the earlier checkpoint; current native Windows story/input/audio +is still unverified. Wine is preliminary compatibility evidence only. -## Verified +## Next work and limits -- Full `../prompt.MD` specification read; originals preserved and local Git initialized. -- All 539 original files (224,601,234 bytes) still match recorded SHA-256 hashes. -- Native PE32 x86 MSVC C++ game, Open Media Toolkit 2.0 DR4, Direct3D7/DirectDraw7, - DirectInput8 and DirectSound identified with addresses in analysis reports. -- 35 GAM files: 3,299 entities, 93 class codes, 84,044 properties, byte-for-byte - round-trip in Python and full corpus decoding in native C#. -- 100 OMT files / 7,027 indexed resources audited: 2,155 meshes, 2,183 materials, - 1,614 textures, 875 bounded RIFF resources; zero decode failures. -- ASE/OMT coordinate and UV conversion proven with duplicate assets. Jimmy morph - sample vectors retain original base UV/topology; normal texture corrected to - jimycarl.png via actual InitObject code, with shock atlas kept separate. -- .NET SDK10.0.402/runtime10.0.13, Silk.NET2.23.0, SDL3.4.2 provisioned locally. -- C# builds without warnings/errors; 20 Python tests plus native C# corpus, - malformed-data, arithmetic, visibility, case lookup, morph and merge tests pass. -- Native Vulkan lab rendering: 2,869 triangles / 33 textures; combined Jimmy - preview: 3,683 triangles / 34 textures. Real GPU readback, zero validation errors - under llvmpipe; scene/player screenshots visually reviewed. -- Fixed original null-material skipping removes false white collision-proxy - surfaces. Original startpoint/camera and recovered projection are available. -- SDL3 hardware window/presentation on GTX1070 under Xvfb: six frames, injected - keyboard received, resize to800x600, zero validation errors. -- SDL3 recovered WAV stream consumes bytes on dummy device. Speaker output untested. -- Self-contained linux-x64/win-x64 packages built under dist/. Linux package also - renders inside a separate filesystem namespace with no SDK/project/original - directory mounted. Initial Windows rendering is now user-reported as noted above. -- Windows x64 package also renders two headless frames under isolated Wine64, - exit0, without source/SDK/originals mounted. Its fixed-time PPM is byte-identical - to the Linux package on the same lavapipe driver (checkpoint670adb4). Broader native Windows remains untested; - Wine test did not enable validation or exercise SDL window/audio/input. -- Official Wine11 original-copy runs attempted in isolated filesystem/network - namespaces. Both GL and Vulkan backends produce unusable frames; details below. +No usable original gameplay reference has been captured: isolated Wine GL/Vulkan +attempts fail rendering. Continue static recovery and isolated DLL probes locally; +comparison on a working original installation remains required for fidelity. -## Build and run +Next priorities are lab navigation/door collision and checkpoint return-position +fidelity; original collision47BD80/479D20 and phase/cadence; audio-bank/SFX mapping; +UI slide/highlights/energy gauges; actor sensing/animation completion. Then expand +remaining gadgets, damage/combat/enemies, menus/configuration, full saves and all +level progression. Lighting/fog/blend/culling and sprite/pivot fidelity are open. +Do not claim complete gameplay based on direct-contact route or GPU smoke tests. -From GamePort: `source scripts/env.sh`, `dotnet build`, then `dotnet run -- --with-player`. -Asset preparation: `python3 tools/extractors/prepare.py --audio sounds musicsecretlab`. -Tests: `scripts/test.sh`; packages: `scripts/package.sh`. See README for exact options. -Generated outputs and dependencies are ignored, and everything remains local. - -## Remaining and current constraints - -No original gameplay reference has been captured. Wine GL cannot obtain a suitable -pixel format/3D surface; Wine Vulkan logs unsupported fixed-function state and a -swapchain image count mismatch. Native Windows/VM access has been requested for -reference/fidelity and native port validation. These failures do not establish -original behavior. Static reverse engineering can continue independently. - -Original collision resolution, introductory LABEXP cutscene, entity activation/ -task/trigger execution, interactions, combat, AI, progression, menus, mouse aiming -and saves remain incomplete. The no-gadget controller checkpoint requires original -runtime comparison. Animation looping/speed and collider/pivot remain approximations. -Rendering material/lighting/fog/blend state mapping also remains incomplete. - -Two investigators contributed movement evidence/tests and collision implementation/ -tests for this checkpoint. Primary integrated the runtime, input, animation, packages -and verification. Reports distinguish static recovery from runtime checks. - -## Continuation - -Read AGENTS, tasks, architecture, compatibility, reverse-engineering index, and -analysis reports. Check Git status before editing. Avoid repeating solved inventory, -GAM decoding or OMT extraction. LV1B/STARTEXP is initial scene evidence; its LABEXP -trigger still needs reconstruction. VR01 provides a smaller, 16-entity test scene. -Next actionable addresses/tasks are in tasks.md; original execution procedure and -errors are in reference-testing.md. Commit history preserves local milestones. +All previous agent file ownership has returned to primary; investigators that +reached usage limits are not dependencies. Generated output stays separate from +Original and the nested local repository has no remotes. Read tasks.md and Git +status before continuing; preserve source evidence and update these notes. diff --git a/docs/reverse-engineering.md b/docs/reverse-engineering.md index 6363089..477e41b 100644 --- a/docs/reverse-engineering.md +++ b/docs/reverse-engineering.md @@ -2,8 +2,22 @@ Authoritative reference is supplied originals. Findings must be supported by file offsets, virtual addresses, API symbols or observed behavior. Decompiled output is -evidence, not original source. Runtime behavior has not yet been observed. +evidence, not original source. Original gameplay has not yet been observed successfully; isolated original DLL +probes and modern runtime checks are recorded separately. +- `save-format.md`: full supplied TSK layout, task query/assignment and activation gates. +- `analysis/lab-progression.md`: CAM/MCA/AI dispatch, original lab chain and skip/camera formulas. +- `analysis/scene-entities.md`: exact entity-resource preparation and contact/sprite evidence. +- `analysis/level-resource-mapping.md`: supplied Level3B/E GAMs, separate registered + OMT loader paths, null-database handling and unverified gameplay reachability. +- `analysis/original-collision.md`: radius/mask follow-up; unresolved original pivot/solver. +- `analysis/scene-models.md`: explicit OMT/ASE model bindings, source bounds and props. +- `analysis/patrol.md`: shared state/waypoint phases, Goddard/Carl profiles and limits. +- `analysis/dynamic-collision.md`: source3DUD broadphase/triangle order and modern response boundary. +- `analysis/buttons-doors.md`: button contact/cooldown and moving-bar state machine. +- `analysis/ui.md`: original objective/practice canvases, coordinates, input and return strings. +- `analysis/jetpack.md`: corrected lab pickup identity, powered-jump/effect/energy phases. +- `analysis/sound-effects.md`: default bank identity, preserved wave payloads and loop lifecycle. - `original-manifest.json`: complete original SHA-256 baseline. - `reconnaissance.md`: input/tool inventory, game identity and initial environment. - `analysis/binary.md`: PE/compiler, entry points, imports and function mappings. @@ -34,5 +48,5 @@ the older preliminary movement interpretations. ## Unresolved Original execution under isolated Wine/Windows; complete gameplay algorithms; -archive animations and render states; save schema; exact historical timing and +remaining actor animations and render states; full runtime save state; exact historical timing and Windows runtime compatibility. Follow `tasks.md` for concrete next actions. diff --git a/docs/save-format.md b/docs/save-format.md new file mode 100644 index 0000000..f554a9f --- /dev/null +++ b/docs/save-format.md @@ -0,0 +1,57 @@ +# Original TSK save and task state + +All12 supplied TSK files decode completely and byte-round-trip in C#. +Originals remain read-only; implementation is `Assets/OriginalSave.cs`. +This establishes the wire format, not complete runtime saving or resume behavior. + +Original writer EXE`0x45FEE0` and loader`0x4603F0` use OMT stream operators +(big endian scalars; one-byte Latin1 string length). Writer calls at +`0x45FFD3–0x46003C`, `0x460057–0x4600AF`, `0x4600B2–0x46013F` independently +support these field sizes/order. Reader calls at`0x4605A8–0x460633`, +`0x460A83–0x460BCF`, `0x460BDD–0x460D60` mirror them. + +| Offset / order | Wire type | Evidence / current interpretation | +| --- | --- | --- | +|0|4-byte FourCC|Current level code; NewGame LV1B| +|4|float32|Global0x4F83D4; NewGame20.0; energy consumed by jetpack, adjustment0x42A920 clamps0..100; other uses pending| +|8|int16|Global0x4F83CC; preserve signed/raw value| +|10|int32|Score0x4F83C0; pickup addition0x42ADC0| +|14|int32|Global0x4F8194; selected objective index, set by0x406F50| +|18|4200 int32|Global0x4F8438..0x4FC5D8; acquired-item slots referenced by pickup code| +|16818|29 int32|One int at each8-byte record from0x4F7DB8..0x4F7EA0; semantics pending| +|16934|4 Pascal strings|Startpoint, reserved name, return level, return start| +|after strings|3 float32|Stored vector; exact meaning unresolved, not assumed player position| +|after vector|19 int32|9 group0 and10 group1 inventory states; source getters sign-extend shorts| +|after inventory|int32 count|Task entry count| +|per task|Pascal string +int32|Task name and state, in original order| + +No version tag/checksum was found in this supplied format. Unknown tables/fields +and unusual existing inventory values are preserved. Several old saves contain +large or negative inventory states; normalizing them to booleans would break +the forensic round-trip and is not justified by current evidence. + +NewGame's12 tasks are MOM, LIBBY, BENNY, SCENE, DINO, CLONE, KITTY1/2/3, +HYDRANT1/2 and REACTOR. Only SCENE is nonzero, initially30. + +`TaskStates.Get` implements EXE`0x45FEA0`: first matching name, missing returns0. +Comparison helper`0x487C20` folds ASCII A-Z (locale fallback exists in the original; +the supplied task names are ASCII). Setter`0x45F990` updates matching existing +entries and broadcasts assignment to objects sharing TaskName via slot0x424. +It does not insert a missing task, and repeated assignments still broadcast. +SCENE milestone dispatch now updates the selected objective through the recovered +44-entry mapping (`SceneInteractions.ObjectiveForScene`), including35/50/60 to1/2/3. +The original helper0x406F50 clears transient objective flags and selects the new +entry. The TSK field currently retains its generic C# name `OtherCounter` to avoid +changing the wire representation; its recovered meaning is the objective selector. + +`TaskActivation` implements the corrected animated-entity, pickup and LOAD gates. +ExactLevel is a numeric state, not a boolean. Animated entities prioritize exact +match, otherwise RequiredLevel threshold and exclusive RemoveLevel; Required=-1 +leaves state unchanged. Pickup override omits RemoveLevel. LOAD accepts no required +task, taskstate-1, or threshold plus optional exact equality. These are gate +formulas only; scene visibility/collision/state execution requires integration. + +Tests cover all12 original saves, truncation/trailing bytes, mutations, +case-insensitive task query, missing tasks and assignment notification. Remaining: +map every remaining global field and task side effect, original checkpoint selection, +complete state serialization/resume, port configuration and native platform tests. diff --git a/docs/tasks.md b/docs/tasks.md index b16edc8..853b2b2 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -1,78 +1,69 @@ # Tasks -## Completed milestones +Full-game completion remains the objective. Original files are authoritative; +compile, runtime and original-fidelity verification are separate. -- [x] Entire specification; original inventory/hashes; local-only Git and guidance. -- [x] Binary/compiler/API identification and address-based reports. -- [x] All GAM entities decoded and byte-round-tripped; C# corpus reader tested. -- [x] All indexed OMT meshes/materials/textures/RIFF resources decoded and audited. -- [x] ASE transform/morph-base UV/topology recovery and regression tests. -- [x] .NET10 + SDL3 + Vulkan1.3 shared source; real scene/model/texture rendering. -- [x] Original LV1B lab plus original Jimmy morph preview at GAM startpoint. -- [x] Correct normal atlas and null-material visibility from binary evidence. -- [x] Recovered impulse/gravity/speed/RNG arithmetic fragments with tests. -- [x] Native Linux Vulkan offscreen and SDL3 window/input/resize verification. -- [x] SDL3 recovered WAV stream consumption test (dummy device). -- [x] Self-contained Linux and Windows local packages, matching SDL3 libraries. -- [x] Packaged Linux runtime isolated from SDK/source/originals; renders successfully. -- [x] Preliminary Wine64 Windows-package render; exact fixed-time readback matches Linux. -- [x] Isolated copied-original Wine attempts; actual failures documented. -- [x] Correct preview floor overlap, identify still idle, add explicit animation inspection controls/tests. -- [x] User confirmed corrected Windows build loads and renders. -- [x] Controllable lab: recovered walking/backpedal/turn/no-gadget jump formulas, - original animation clips, fixed60Hz simulation, collision and chase camera. -- [x] 11 collision and13 movement test groups; source lab and synthetic edge cases, - render-rate independence, held/re-pressed jumping and ten-minute stability. -- [x] Linux240-step SDL key/jump/resize replay and GPU readback, zero validation errors. -- [x] Rebuilt both packages; packaged Linux window and preliminary Windows Wine64 - window240-step walking/key/jump/resize pass, matching movement statistics. -- [ ] Test this movement checkpoint natively on Windows (previous rendering confirmed). +## Integrated milestones -## Next implementation priorities +- [x] Inventory/hashes, binary/API identification, full GAM round-trip and OMT audit. +- [x] .NET10/SDL3/Vulkan1.3 shared native code and self-contained platform packages. +- [x] Original lab geometry, corrected Jimmy atlas, original morphs and inspection. +- [x] Walking/jumping/chase camera and source-triangle provisional collision. +- [x] Linux headless/window/input/resize/audio-stream checks; initial native Windows + rendering user-confirmed; preliminary Wine64 movement package checks. +- [x] Original TSK/task gates/checkpoint CLI and independent music/speech streams. +- [x]16-cue lab camera/speech/actions/control restoration and skip execution. +- [x] Source actor/sprite/model preparation,9 lab props and all33 available scenes. +- [x] B/E GAM correction: both supplied; missing registered OMT geometry is not an + established progression blocker. No substitution or extra-file request. +- [x] Lab jet pack/Carl/exit task route and objective/inventory/score effects. +- [x] Original objective/practice art, strict input regions, modal pause and VR04 entry. +- [x] Shared Goddard/Carl patrol subset and recovered body support with DLL checks. +- [x] Button/vertical-door behavior and source dynamic broadphase/box triangle rules. +- [x] Powered-jump state/effect/energy arithmetic, original FLY/fire morphs and GPU replay. -1. Replace provisional capsule collision/pivot with recovered original behavior. - Trace `0x479D20` past displacement integration, shared collision call - via interface slot0x130 in `0x462520`, and object collision caches. Retain - invisible/null-material geometry; its exact collision masks remain unresolved. - Recover original actor/model pivot, scale and spawn settling: the preview now - uses a floor-derived model offset, which must be replaced with proven behavior. - Recover stair/step handling, dynamic collider activation, and camera obstruction. -2. Compare reconstructed no-gadget airborne behavior with the original. Walking, - jump state table and zero-fuel held/re-press repeat path are now recovered in - `analysis/movement-checkpoint.md`; transient state3 and takeoff phase remain - approximations. Recover powered gadget states and original animation routing. -3. Recover original frame cadence and phase order; current fixed60Hz preserves - per-call speed increments independent of rendering. Find reverse timer+0x830 - writer before implementing its >1.5 turnaround branch. Recover mouse steering. -4. Execute LV1B STARTEXP/LABEXP intro. GAM parsing supplies records; implement task - prerequisites, object activation/visibility, camera triggers and progression - from code/observations. Then build a complete small scene (VR01 if useful). -5. Recover original morph state selection, playback speed, smooth normals and - transitions. Current interpolation is original; loop/speed are preview policy. -6. Continue material/fog/light/blend/culling and render sorting mapping, then - compare visuals to original; current unlit modulation is only a foundation. +## Immediate continuation -## Required validation and expansion +1. Integration suite and both packages pass; commit this stable milestone locally. + Keep native Windows story/input/audio pending and preserve current evidence. + Re-run checks only when new changes or unresolved concerns justify them. +2. Exercise the lab route through actual walking/navigation, buttons and doors. + Current lab-route smoke directly invokes source contacts; it is not navigation + or original-fidelity evidence. Recover runtime42AF00 checkpoint restoration on + VR return separately from saved STRT/RETURN strings and unknown TSK StoredVector. +3. Recover47BD80 collision response/479D20 movement phase and source object exclusions. + Support trace/magnitude/radii/factors and dynamic broadphase are recovered; + wall response, Jimmy capsule/visual pivot, stairs and camera obstruction remain + modern approximations. Preserve source normals and invisible proxy geometry. +4. Complete contextual SFX bank switching, source volume/pan/attenuation/channel + policies, jetpack sound callbacks and MPEG-in-RIFF bird1/id162 decoding. Default + SoundEffects.omt identity and pickup/button/door stream lifecycle are integrated; + physical/native Windows output and original timing remain unverified. +5. Complete objective slide/timing, practice highlights/cursor/controller handling, + energy/gadget UI. Stationary geometry and keyboard/pointer choices are recovered. +6. Recover Carl sensing409CC0, Goddard follow-state4, actor class defaults and full + morph state/playback-end synchronization. Generic patrol states alone are not AI. +7. Recover original global cadence/object phase order, mouse steering/relative input, + exact clipping/fullscreen/focus/scaling behavior and material/fog/light/blend states. -- [ ] Usable original reference captures under local Windows/VM or working Wine. -- [ ] Original walking/jump/collision/camera/input comparisons and first complete scene - including intro/triggers/interactions (movement checkpoint implemented). -- [ ] Physical audio output and original SFX/music timing, mixing/panning/positional audio. -- [ ] Fullscreen, minimized-window, mouse/relative capture, display scaling and controller behavior. -- [ ] Pickups, score/health, gadgets/inventory, combat/AI, all levels and transitions. -- [ ] Original menus, cutscenes, dialogue/voice and state-dependent rendering. -- [ ] Save/load schema and configuration persistence; NewGame reference is not save support. -- [ ] Full native Windows input/audio/resize/driver testing (initial rendering is user-reported). -- [ ] Fidelity regression references, remaining discrepancies and actual release candidate. +## Full reconstruction and verification -## Repeatable commands +- [ ] Working original gameplay captures and physics/input/render/audio comparisons. +- [ ] One complete, source-faithful playable scene including navigation and transitions. +- [ ] All inventory/gadgets, health/damage, enemies/combat, scoring and win/loss behavior. +- [ ] All levels, class-specific triggers/AI and full original progression. +- [ ] Menus, cutscenes, configuration and complete runtime save/load. +- [ ] Original render-state, animation, lighting/fog/alpha and camera fidelity. +- [ ] Speaker output, positional mixing, original timing and native Windows audio. +- [ ] Native Windows input/resize/story/driver validation of the current build. +- [ ] Verified Linux/Windows release packages and documented remaining discrepancies. -- `source scripts/env.sh; dotnet build` -- `scripts/test.sh` (20 Python tests, C# checks, native offscreen/audio, original hashes) -- `python3 tools/extractors/audit.py ../Original --report artifacts/extracted/audit.json` -- `NEUTRON_WINDOW_TEST=1 scripts/test.sh` with DISPLAY for input/resize smoke -- `scripts/package.sh` for local investigation packages (not a finished game release) +## Commands -Keep runtime, tests and docs coherent. No remotes/uploads/cloud CI. Do not modify -originals or claim unobserved fidelity. All prior agent ownership has returned to -primary; use explicit file ownership if further parallel work is started. +From GamePort: `source scripts/env.sh`, `dotnet build`, `scripts/test.sh`. +`scripts/package.sh` rebuilds local packages. `NEUTRON_WINDOW_TEST=1 scripts/test.sh` +adds window checks with a working DISPLAY. `tools/recon/reference_capture.py` +executes copied originals/generated probes in an isolated local harness. +Verify preservation using `python3 tools/recon/inventory.py ../Original --verify + docs/original-manifest.json`. No remotes/uploads/cloud work. Check Git status and +exclusive file ownership before edits; all prior agent ownership returned to primary. diff --git a/scripts/package.sh b/scripts/package.sh index 8973f2b..1e66f64 100755 --- a/scripts/package.sh +++ b/scripts/package.sh @@ -3,14 +3,26 @@ set -euo pipefail source "$(dirname "$0")/env.sh" scripts/build-linux.sh scripts/build-windows.sh -python3 tools/extractors/prepare.py --audio sounds musicsecretlab +python3 tools/extractors/prepare.py --all-scenes --audio sounds musicsecretlab for rid in linux-x64 win-x64; do out="dist/$rid" - mkdir -p "$out/assets" "$out/scenes/level1b" "$out/scenes/animations" "$out/audio/sounds" "$out/licenses" "$out/docs" + mkdir -p "$out/assets" "$out/scenes/level1b" "$out/scenes/VR01" "$out/scenes/animations" "$out/scenes/actors" "$out/scenes/ui" "$out/audio/sounds" "$out/licenses" "$out/docs" for directory in ASE png gam omt; do cp -a "../Original/$directory" "$out/assets/"; done - cp ../Original/fontsmall.png ../Original/green_font.png ../Original/NewGame.tsk ../Original/readme.txt "$out/assets/" + cp ../Original/fontsmall.png ../Original/green_font.png ../Original/alpha.omt ../Original/NewGame.tsk ../Original/readme.txt "$out/assets/" cp -a artifacts/extracted/level1b/. "$out/scenes/level1b/" cp -a artifacts/extracted/animations/. "$out/scenes/animations/" + cp -a artifacts/extracted/actors/. "$out/scenes/actors/" + cp -a artifacts/extracted/ui/. "$out/scenes/ui/" + mkdir -p "$out/scenes/effects" + cp -a artifacts/extracted/effects/. "$out/scenes/effects/" + cp artifacts/extracted/scene-catalog.json "$out/scenes/scene-catalog.json" + cp -a artifacts/extracted/VR01/. "$out/scenes/VR01/" + for manifest in artifacts/extracted/*/scene.json; do + scene_directory="$(dirname "$manifest")" + scene_name="$(basename "$scene_directory")" + mkdir -p "$out/scenes/$scene_name" + cp -a "$scene_directory/." "$out/scenes/$scene_name/" + done cp -a artifacts/extracted/musicsecretlab/. "$out/audio/" cp -a artifacts/extracted/sounds/. "$out/audio/sounds/" cp .tools/sdl-win/LICENSE.txt "$out/licenses/SDL3.txt" @@ -20,7 +32,7 @@ for rid in linux-x64 win-x64; do cp -a docs/. "$out/docs/" cp README.md "$out/SOURCE-README.md" cat > "$out/README.md" <<'NOTES' -# Neutron controllable lab checkpoint +# Neutron lab story and jet pack checkpoint Linux: run ./launch-scene.sh. Windows: run launch-scene.cmd. Append --headless --frames 2 to render without a window, or --screenshot lab.ppm @@ -32,12 +44,18 @@ Shift, Insert, numpad 0 or right mouse jump. R resets to the original start area C pauses into inspection and resumes the chase camera. F11 fullscreen, Escape quit. Inspection: arrows/WASD orbit, +/- zoom, 1 idle, 2 run, 3 jump, 4 scratch preview. Append --inspect to start directly in the old scene inspector. +The default runs the recovered lab camera/speech sequence; Escape/Space skips +its actions and restores control. --skip-intro starts with control; --mute disables +scene audio. O raises/lowers objectives. The original jet pack pickup opens the +practice prompt: Y/Yes enters VR04; N/No resumes. Hold jump for a powered burst +after obtaining it. --headless --story-time 12 renders a deterministic story shot. -This checkpoint implements recovered walking/jump/camera arithmetic and original -animation clips. Collision solver/masks, collider/pivot, 60Hz cadence and animation -state timing remain provisional. Intro, interactions, progression, AI and saves -remain incomplete. A user verified rendering on Windows; this new movement build -still needs native Windows input/physics testing. +Original actor/model/sprite props, common patrol, buttons/moving bars, lab task +route, objectives, practice flow and checkpoint CLI are integrated. Collision, +60Hz cadence, pivots, rendering states and animation timing remain provisional. +Full combat, AI, progression, menus and runtime saves remain incomplete. Initial +Windows rendering is user-confirmed for an older build; this story/tutorial +checkpoint still needs native Windows input/physics/audio validation. See BUILD-AND-LIMITATIONS.md, COMPATIBILITY.md and docs/ for evidence and remaining work. SOURCE-README.md describes development from the separate source repository. diff --git a/scripts/test.sh b/scripts/test.sh index eb47132..4249126 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -2,16 +2,32 @@ set -euo pipefail source "$(dirname "$0")/env.sh" python3 -m unittest discover -s tests -p 'test_*.py' -v -python3 tools/extractors/prepare.py --audio sounds musicsecretlab +python3 tools/extractors/prepare.py --all-scenes --audio sounds musicsecretlab dotnet run --project tests/GamePort.DataTests -- ../Original dotnet run --project tests/GamePort.CollisionTests -- ../Original dotnet run --project tests/GamePort.MovementTests -- ../Original +dotnet run --project tests/GamePort.DirectorTests -- ../Original +dotnet run --project tests/GamePort.PatrolTests -- ../Original +dotnet run --project tests/GamePort.SupportTests -- ../Original +dotnet run --project tests/GamePort.InteractionTests -- ../Original +dotnet run --project tests/GamePort.DynamicCollisionTests -- ../Original +dotnet run --project tests/GamePort.JetpackTests +python3 tests/GamePort.HudTests/test_ui.py +dotnet run --project tests/GamePort.HudTests -- artifacts/extracted/ui/ui.json dotnet build GamePort.csproj dotnet run --no-build -- --verify-assets --assets ../Original python3 tools/extractors/omt.py ../Original/omt/level1b.omt --scene --output artifacts/extracted/level1b dotnet run --no-build -- --headless --assets ../Original --scene artifacts/extracted/level1b/scene.json --level gam/level1b.gam --original-camera --screenshot artifacts/test-level1b.ppm dotnet run --no-build -- --inspect --headless --with-player --time 0.05 --screenshot artifacts/test-player.ppm dotnet run --no-build -- --headless --smoke-walk --screenshot artifacts/test-walk.ppm +dotnet run --no-build -- --headless --story --story-time 12 --screenshot artifacts/test-story.ppm +dotnet run --no-build -- --headless --story --smoke-practice-prompt --screenshot artifacts/test-practice.ppm +dotnet run --no-build -- --headless --story --smoke-practice-transition +dotnet run --no-build -- --headless --story --smoke-lab-route +dotnet run --no-build -- --headless --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-jetpack --screenshot artifacts/test-jetpack.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 dotnet run --no-build -- --headless --animation artifacts/extracted/animations/jimrun/animation.json --time 0 --screenshot artifacts/test-run-start.ppm dotnet run --no-build -- --headless --animation artifacts/extracted/animations/jimrun/animation.json --frames 7 --screenshot artifacts/test-run-advanced.ppm python3 - <<'PY' @@ -19,9 +35,12 @@ from pathlib import Path assert Path('artifacts/test-run-start.ppm').read_bytes() != Path('artifacts/test-run-advanced.ppm').read_bytes(), 'Animation did not advance in GPU readback' print('PASS: original run preview advances across rendered frames') PY +SDL_AUDIODRIVER=dummy dotnet run --no-build -- --effects-audio-smoke artifacts/extracted/effects/effects.json SDL_AUDIODRIVER=dummy dotnet run --no-build -- --audio-smoke artifacts/extracted/sounds/Wave_00000001_save.wav +SDL_AUDIODRIVER=dummy dotnet run --no-build -- --scene-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 -- --smoke-practice-window --frames 12 --screenshot artifacts/test-practice-window.ppm dotnet run --no-build -- --scene artifacts/extracted/level1b/scene.json --smoke-window --frames 6 --screenshot artifacts/test-window.ppm dotnet run --no-build -- --smoke-walk --screenshot artifacts/test-walk-window.ppm fi diff --git a/src/GamePort/Application/JetpackVisuals.cs b/src/GamePort/Application/JetpackVisuals.cs new file mode 100644 index 0000000..86bbfc0 --- /dev/null +++ b/src/GamePort/Application/JetpackVisuals.cs @@ -0,0 +1,31 @@ +using System.Numerics; +using GamePort.Assets; +using GamePort.Game; + +namespace GamePort.Application; + +/// Original C3DJetpackFire DEFAULT shape/texture, following the owner root/Euler. +public sealed class JetpackVisuals +{ + private readonly MorphAnimation clip; + private readonly int offset; + private readonly MeshDraw draw; + public Mesh Mesh { get; } + + public JetpackVisuals(Mesh combined, string preparedRoot) + { + clip = new MorphAnimation(Path.Combine(preparedRoot, "actors/jetpack/fire/animation.json")); + offset = combined.Vertices.Length; + Mesh = clip.AppendTo(combined, int.MinValue + 10_000); + draw = Mesh.Draws[^1]; draw.Visible = false; + } + + public void Update(Mesh destination, LabSimulation owner) + { + draw.Visible = owner.JetpackEffectVisible; + if (!draw.Visible) return; + var model = Matrix4x4.CreateRotationY(-owner.Yaw * MathF.PI / 180) + * Matrix4x4.CreateTranslation(owner.ActorRoot); + clip.Sample(owner.Steps / 60d, destination.Vertices.AsSpan(offset, clip.Base.Vertices.Length), model); + } +} diff --git a/src/GamePort/Application/LabRouteSmoke.cs b/src/GamePort/Application/LabRouteSmoke.cs new file mode 100644 index 0000000..b56ae3d --- /dev/null +++ b/src/GamePort/Application/LabRouteSmoke.cs @@ -0,0 +1,32 @@ +using System.Numerics; +using GamePort.Assets; +using GamePort.Game; + +namespace GamePort.Application; + +/// +/// Deterministic integration check using direct contacts at original actor roots. +/// This does not test navigation, player input, physics or original runtime fidelity. +/// +public static class LabRouteSmoke +{ + public static void Run(GamLevel level, SceneDirector director, SceneInteractions interactions, Action? dismissPractice = null) + { + if (level.Code != "LV1B") throw new ArgumentException("Lab route check requires original LV1B"); + director.Skip(); + var player = level.Player!.Tag!; + director.Touch(player, level.Entities.Single(e => e.Tag == "teleportexplanation").Position); + director.Skip(); + interactions.Update(director.FindActor("shrinkray")!.Position); + dismissPractice?.Invoke(); + var carl = director.FindActor("C3DCARL")!; + director.SyncActor(player, carl.Position, Vector3.Zero); + interactions.Update(carl.Position); + director.Skip(); + if (!director.Controlled || interactions.Score != 150 || interactions.Inventory.State(0, 3) != 1 + || interactions.CurrentObjective != 3) + throw new InvalidOperationException("Original lab contact route did not reach the recovered exit state"); + interactions.Update(level.Entities.Single(e => e.Tag == "LABTONEIGH").Position); + Console.WriteLine("Lab direct-contact integration: explanation, shrinkray, Carl callback and exit; score150, gadget3, objective3. Navigation was not exercised."); + } +} diff --git a/src/GamePort/Application/PreviewAnimationLibrary.cs b/src/GamePort/Application/PreviewAnimationLibrary.cs index cd8e958..169cfdf 100644 --- a/src/GamePort/Application/PreviewAnimationLibrary.cs +++ b/src/GamePort/Application/PreviewAnimationLibrary.cs @@ -8,6 +8,7 @@ public sealed class PreviewAnimationLibrary { private readonly Dictionary choices = []; private readonly Dictionary movement = []; + private readonly Dictionary actions = new(StringComparer.OrdinalIgnoreCase); public MorphAnimation Current { get; private set; } public string Name { get; private set; } public string WindowTitle => $"Jimmy Neutron — scene preview | {Name}{(Current.HasVertexMotion ? "" : " (still pose)")} | 1 idle, 2 run, 3 jump, 4 scratch | C camera"; @@ -46,12 +47,18 @@ public sealed class PreviewAnimationLibrary if (ReferenceEquals(clip, Current)) Name = label; } foreach (var (pose, folder) in new[] { (PlayerPose.Idle, "jimstop"), (PlayerPose.Run, "jimrun"), - (PlayerPose.Backpedal, "jimbackpedal"), (PlayerPose.Jump, "jimjump"), (PlayerPose.Fall, "jimfall") }) + (PlayerPose.Backpedal, "jimbackpedal"), (PlayerPose.Jump, "jimjump"), (PlayerPose.Fall, "jimfall"), (PlayerPose.Fly, "jimfly") }) { var path = Path.Combine(parent, folder, "animation.json"); if (!File.Exists(path)) continue; movement[pose] = Load(path); } + foreach (var (action, folder) in new[] { ("STOP", "jimstop"), ("TALK", "jimtalk"), ("RUN", "jimrun"), + ("JUMP", "jimjump"), ("FALL", "jimfall"), ("SCRATCH", "jimscratch"), ("FLY", "jimfly") }) + { + var path = Path.Combine(parent, folder, "animation.json"); + if (File.Exists(path)) actions[action] = Load(path); + } } public bool Select(uint scancode) @@ -70,4 +77,10 @@ public sealed class PreviewAnimationLibrary Name = pose.ToString(); return true; } + + public bool SelectAction(string action) + { + if (!actions.TryGetValue(action, out var clip) || ReferenceEquals(Current, clip)) return false; + Current = clip; Name = action; return true; + } } diff --git a/src/GamePort/Application/SceneActorVisuals.cs b/src/GamePort/Application/SceneActorVisuals.cs new file mode 100644 index 0000000..1ed148e --- /dev/null +++ b/src/GamePort/Application/SceneActorVisuals.cs @@ -0,0 +1,98 @@ +using System.Numerics; +using System.Text.Json; +using GamePort.Assets; +using GamePort.Game; + +namespace GamePort.Application; + +/// Prepared original Carl/Goddard morphs driven by recovered director state. +public sealed class SceneActorVisuals +{ + private sealed class Visual(DirectorActor actor, Dictionary clips, + MorphAnimation initial, string clipName, HashSet ignored, int offset, MeshDraw draw, float correction) + { + public DirectorActor Actor = actor; + public Dictionary Clips = clips; + public MorphAnimation Clip = initial; + public string ClipName = clipName; + public HashSet Ignored = ignored; + public int Offset = offset; + public MeshDraw Draw = draw; + public float Correction = correction; + public double Time; + } + private readonly List visuals = []; + private readonly HashSet missing = []; + public Mesh Mesh { get; } + public IReadOnlyCollection UnsupportedAnimations => missing; + + public SceneActorVisuals(Mesh combined, Mesh world, SceneDirector director, string preparedRoot, + Func? usesPhysicsRoot = null) + { + foreach (var actor in director.Actors) + { + var family = actor.Kind switch { "3CAR" => "carl", "3DOG" => "goddard", "3TRO" => "trophy", _ => null }; + if (family == null) continue; + var manifest = Path.Combine(preparedRoot, "actors", family, "family.json"); + if (!File.Exists(manifest)) throw new FileNotFoundException("Prepare original actor animation resources", manifest); + using var doc = JsonDocument.Parse(File.ReadAllText(manifest)); + var clips = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var entry in doc.RootElement.GetProperty("actions").EnumerateObject()) + clips.Add(entry.Name, new MorphAnimation(Path.Combine(Path.GetDirectoryName(manifest)!, entry.Value.GetString()!))); + var initialName = doc.RootElement.GetProperty("default").GetString()!; + var initial = clips[initialName]; + var ignored = doc.RootElement.TryGetProperty("ignoredAnimations", out var ignoredNames) + ? new HashSet(ignoredNames.EnumerateArray().Select(n => n.GetString()!), StringComparer.OrdinalIgnoreCase) + : new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var clip in clips.Values) + if (clip.Base.Vertices.Length != initial.Base.Vertices.Length || !clip.Base.Indices.SequenceEqual(initial.Base.Indices) + || !clip.Base.Vertices.Select(v => v.Uv).SequenceEqual(initial.Base.Vertices.Select(v => v.Uv)) + || !clip.Texture.Rgba.SequenceEqual(initial.Texture.Rgba)) throw new InvalidDataException("Actor morph family mismatch"); + var offset = combined.Vertices.Length; + var correction = actor.Kind == "3TRO" || usesPhysicsRoot?.Invoke(actor) == true ? 0 + : PreviewCharacterPlacement.Create(world, initial.Base, actor.Position, actor.Rotation.Y).VerticalCorrection; + combined = initial.AppendTo(combined, int.MinValue + 1 + visuals.Count); + visuals.Add(new(actor, clips, initial, initialName, ignored, offset, combined.Draws[^1], correction)); + } + Mesh = combined; + Update(0); + // Original animation selection is synchronous. Preserve intermediate + // SIT then ignored TALK requests even if both occur before a render. + director.ActorChanged += actor => + { + var visual = visuals.Find(v => ReferenceEquals(v.Actor, actor)); + if (visual != null) SelectAnimation(visual); + }; + } + + public void Update(double seconds, Mesh? destination = null) + { + foreach (var visual in visuals) + { + var actor = visual.Actor; + SelectAnimation(visual); + visual.Time += seconds; + var rotation = Matrix4x4.CreateRotationX(actor.Rotation.X * MathF.PI / 180) + * Matrix4x4.CreateRotationY(-actor.Rotation.Y * MathF.PI / 180) + * Matrix4x4.CreateRotationZ(actor.Rotation.Z * MathF.PI / 180); + var model = rotation * Matrix4x4.CreateTranslation(actor.Position + Vector3.UnitY * visual.Correction); + visual.Clip.Sample(visual.Time, (destination ?? Mesh).Vertices.AsSpan(visual.Offset, visual.Clip.Base.Vertices.Length), model); + visual.Draw.Visible = actor.Visible; + } + } + + private void SelectAnimation(Visual visual) + { + var actor = visual.Actor; + if (visual.Clips.TryGetValue(actor.Animation, out var clip)) + { + if (!ReferenceEquals(clip, visual.Clip)) { visual.Clip = clip; visual.Time = 0; } + visual.ClipName = actor.Animation; + } + // EXE40DF18..22: an unregistered definition returns without selecting + // or renaming the current animation. These aliases have no Goddard + // registrations; this is an ignored request, not a made-up asset alias. + else if (visual.Ignored.Contains(actor.Animation)) actor.Animation = visual.ClipName; + else if (actor.Animation != "none") missing.Add(actor.Tag + ":" + actor.Animation); + } +} diff --git a/src/GamePort/Application/SceneHud.cs b/src/GamePort/Application/SceneHud.cs new file mode 100644 index 0000000..acd59d4 --- /dev/null +++ b/src/GamePort/Application/SceneHud.cs @@ -0,0 +1,97 @@ +using System.Numerics; +using System.Text.Json; +using GamePort.Assets; + +namespace GamePort.Application; + +/// Original screens.omt laboratory objectives and PracticeYesNo; positions from EXE 402C40/407070. +public sealed class SceneHud +{ + private sealed record Quad(int Canvas, int VertexOffset, uint FirstIndex, uint Width, uint Height); + private readonly List quads = []; + private static readonly Dictionary Dimensions = new() + { + [120] = (256, 29), [121] = (256, 29), [122] = (256, 29), + [156] = (320, 173), [169] = (207, 100), [83] = (8, 8), [84] = (8, 8), [85] = (8, 8) + }; + public Mesh Mesh { get; } + + public SceneHud(Mesh combined, string manifest) + { + var full = Path.GetFullPath(manifest); + if (new FileInfo(full).Length > 64 * 1024) throw new InvalidDataException("UI manifest exceeds limit"); + var directory = Path.GetDirectoryName(full)!; + using var doc = JsonDocument.Parse(File.ReadAllBytes(full), new JsonDocumentOptions { MaxDepth = 12 }); + var root = doc.RootElement; + if (root.GetProperty("version").GetInt32() != 1 || root.GetProperty("referenceWidth").GetInt32() != 640 + || root.GetProperty("referenceHeight").GetInt32() != 480) + throw new InvalidDataException("Unsupported prepared UI format"); + var recovered = new Dictionary(); + var entries = root.GetProperty("textures"); + if (entries.GetArrayLength() != Dimensions.Count) throw new InvalidDataException("Unexpected UI texture count"); + foreach (var entry in entries.EnumerateArray()) + { + var id = entry.GetProperty("id").GetInt32(); + var width = entry.GetProperty("width").GetUInt32(); + var height = entry.GetProperty("height").GetUInt32(); + if (!Dimensions.TryGetValue(id, out var expected) || expected != (width, height)) + throw new InvalidDataException("Unexpected UI canvas identity/dimensions"); + var path = Path.GetFullPath(Path.Combine(directory, entry.GetProperty("path").GetString()!)); + if (!path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + throw new InvalidDataException("UI resource escapes prepared directory"); + var bytes = checked((long)width * height * 4); + if (new FileInfo(path).Length != bytes) throw new InvalidDataException("Invalid prepared UI pixel count"); + if (!recovered.TryAdd(id, new(width, height, File.ReadAllBytes(path)))) + throw new InvalidDataException("Duplicate prepared UI canvas"); + } + var vertices = combined.Vertices.ToList(); + var indices = combined.Indices.ToList(); + var draws = combined.Draws.ToList(); + if (!combined.HasExplicitDraws && draws.Count == 0 && indices.Count != 0) + draws.Add(new(0, (uint)indices.Count, -1)); + var textures = new Dictionary(combined.Textures); + // Pad precedes writing; modal follows the HUD, exactly as layered screen elements. + foreach (var id in new[] { 156, 120, 121, 122, 83, 84, 85, 169 }) + { + var image = recovered[id]; + var texture = int.MinValue; + while (textures.ContainsKey(texture)) texture++; + textures.Add(texture, image); + var first = (uint)vertices.Count; + quads.Add(new(id, vertices.Count, (uint)indices.Count, image.Width, image.Height)); + vertices.AddRange(new[] { new MeshVertex(Vector3.Zero, new(0, 0), Vector3.One), + new MeshVertex(Vector3.Zero, new(1, 0), Vector3.One), + new MeshVertex(Vector3.Zero, new(1, 1), Vector3.One), + new MeshVertex(Vector3.Zero, new(0, 1), Vector3.One) }); + draws.Add(new((uint)indices.Count, 6, texture) { ScreenSpace = true, Visible = false }); + indices.AddRange(new[] { first, first + 1, first + 2, first, first + 2, first + 3 }); + } + Mesh = new(vertices.ToArray(), indices.ToArray()) { Draws = draws.ToArray(), HasExplicitDraws = true, + Textures = textures, CollisionPolygons = combined.CollisionPolygons }; + } + + /// Writes the final merged buffer, including when later visual composers copied these vertices. + public void Update(Mesh destination, int currentObjective, bool objectivesVisible, bool practiceVisible, + float objectiveYOffset = -69) + { + if (!float.IsFinite(objectiveYOffset) || objectiveYOffset < -480 || objectiveYOffset > 480) + throw new ArgumentOutOfRangeException(nameof(objectiveYOffset)); + if (destination.Vertices.Length < Mesh.Vertices.Length || destination.Indices.Length < Mesh.Indices.Length) + throw new ArgumentException("Destination omits HUD ranges", nameof(destination)); + foreach (var quad in quads) + { + var draw = destination.Draws.FirstOrDefault(d => d.FirstIndex == quad.FirstIndex && d.ScreenSpace + && d.IndexCount == 6) ?? throw new ArgumentException("Destination omits HUD draws", nameof(destination)); + draw.Visible = quad.Canvas == 169 ? practiceVisible : objectivesVisible && currentObjective is >= 1 and <= 3 + && (quad.Canvas == 156 || quad.Canvas == 119 + currentObjective || quad.Canvas == 82 + currentObjective); + var digit = quad.Canvas is >= 83 and <= 85; + var x = quad.Canvas == 169 ? 210f : digit ? 393f : 384f; + var y = quad.Canvas == 169 ? 210f : (quad.Canvas == 156 ? 380f : digit ? 450f : 448f) + objectiveYOffset; + Vector3 Position(float px, float py) => new(2 * px / 640 - 1, 2 * py / 480 - 1, 0); + destination.Vertices[quad.VertexOffset].Position = Position(x, y); + destination.Vertices[quad.VertexOffset + 1].Position = Position(x + quad.Width, y); + destination.Vertices[quad.VertexOffset + 2].Position = Position(x + quad.Width, y + quad.Height); + destination.Vertices[quad.VertexOffset + 3].Position = Position(x, y + quad.Height); + } + } +} diff --git a/src/GamePort/Application/SceneSpriteVisuals.cs b/src/GamePort/Application/SceneSpriteVisuals.cs new file mode 100644 index 0000000..53d8584 --- /dev/null +++ b/src/GamePort/Application/SceneSpriteVisuals.cs @@ -0,0 +1,92 @@ +using System.Numerics; +using GamePort.Assets; +using GamePort.Game; + +namespace GamePort.Application; + +/// Source-sized, center-aligned Canv quads. Camera-facing orientation is still a port approximation. +public sealed class SceneSpriteVisuals +{ + private sealed class Visual(DirectorActor actor, int offset, MeshDraw[] draws, SpriteSequence sequence) + { + public DirectorActor Actor = actor; + public int Offset = offset; + public MeshDraw[] Draws = draws; + public SpriteSequence Sequence = sequence; + public int Revision = actor.SpriteRevision; + } + private readonly List visuals = []; + public Mesh Mesh { get; } + public SceneSpriteVisuals(Mesh combined, SceneDirector director, PreparedEntityResources resources) + { + var vertices = combined.Vertices.ToList(); + var indices = combined.Indices.ToList(); + var draws = combined.Draws.ToList(); + var textures = new Dictionary(combined.Textures); + foreach (var actor in director.Actors) + { + if (actor.Kind is not ("3PIC" or "3ANI") || actor.SourceGam is not { } source) continue; + var database = source.Text("SpriteDatabase") ?? "none"; + var identities = actor.Kind == "3ANI" ? Enumerable.Range(1, 9) + .Select(i => source.Integer("Sprite" + i, -1)).TakeWhile(i => i >= 0).ToArray() + : [source.Integer("SpriteIndex", -1)]; + if (identities.Length == 0) continue; + var frameDraws = new List(); + var offset = vertices.Count; + var color = new Vector3(source.Number("Red", 1), source.Number("Green", 1), source.Number("Blue", 1)); + foreach (var identity in identities) + { + var canvas = resources.Canvas(database, identity) ?? throw new FileNotFoundException($"Missing original canvas {database}:{identity}"); + var texture = int.MinValue + 1000 + textures.Count; + textures.Add(texture, canvas); + var first = (uint)vertices.Count; + vertices.AddRange(new[] { new MeshVertex(Vector3.Zero, new(0,1),color), new MeshVertex(Vector3.Zero,new(1,1),color), + new MeshVertex(Vector3.Zero,new(1,0),color),new MeshVertex(Vector3.Zero,new(0,0),color) }); + var draw = new MeshDraw((uint)indices.Count, 6, texture); + indices.AddRange(new[] { first, first+1, first+2, first, first+2, first+3 }); + draws.Add(draw); frameDraws.Add(draw); + } + var sequence = new SpriteSequence(identities.Length, source.Number("FPS", 1), source.Integer("Loop", 1)); + if (actor.Kind == "3ANI" && actor.SpritePlaying) sequence.Start(); + visuals.Add(new(actor, offset, frameDraws.ToArray(), sequence)); + } + Mesh = new(vertices.ToArray(), indices.ToArray()) { Draws = draws.ToArray(), HasExplicitDraws = true, Textures = textures }; + } + + public void Step(float dt) + { + foreach (var visual in visuals) + { + if (visual.Revision != visual.Actor.SpriteRevision) + { + visual.Revision = visual.Actor.SpriteRevision; + if (visual.Actor.SpritePlaying) visual.Sequence.Start(); + } + if (visual.Actor.SpritePlaying) visual.Sequence.Step(dt); + } + } + + public void FaceCamera(Vector3 eye, Vector3 target, Mesh? destination = null) + { + var output = destination ?? Mesh; + if (output.Vertices.Length < Mesh.Vertices.Length) + throw new ArgumentException("Destination omits sprite vertex ranges", nameof(destination)); + var direction = target - eye; + if (direction.LengthSquared() < .000001f) direction = Vector3.UnitZ; + var right = Vector3.Cross(Vector3.UnitY, direction); + right = right.LengthSquared() < .000001f ? Vector3.UnitX : Vector3.Normalize(right); + var up = Vector3.Normalize(Vector3.Cross(Vector3.Normalize(direction), right)); + foreach (var visual in visuals) + { + var half = visual.Actor.SourceGam!.Integer("SpriteSize", 50) * .5f; + var center = visual.Actor.Position; + var corners = new[] { center-right*half-up*half, center+right*half-up*half, + center+right*half+up*half, center-right*half+up*half }; + for (var frame = 0; frame < visual.Draws.Length; frame++) + { + visual.Draws[frame].Visible = visual.Actor.Visible && !visual.Sequence.Hidden && frame == visual.Sequence.Frame; + for (var corner = 0; corner < 4; corner++) output.Vertices[visual.Offset + frame * 4 + corner].Position = corners[corner]; + } + } + } +} diff --git a/src/GamePort/Application/StaticSceneVisuals.cs b/src/GamePort/Application/StaticSceneVisuals.cs new file mode 100644 index 0000000..9195a3a --- /dev/null +++ b/src/GamePort/Application/StaticSceneVisuals.cs @@ -0,0 +1,160 @@ +using System.Numerics; +using System.Text.Json; +using GamePort.Assets; +using GamePort.Game; + +namespace GamePort.Application; + +/// +/// Prepared original OMT props, phone booths and explicitly authored ASE models. +/// Keeps source-local positions, every non-null material draw, and director visibility. +/// +public sealed class StaticSceneVisuals +{ + private sealed record Variant(string Name, MeshVertex[] LocalVertices, int Offset, MeshDraw[] Draws); + private sealed record Visual(DirectorActor Actor, string DefaultVariant, Variant[] Variants, + (Vector3 Min, Vector3 Max)? LocalBounds); + private readonly List visuals = []; + public Mesh Mesh { get; } + public int ActorCount => visuals.Count; + + public StaticSceneVisuals(Mesh combined, SceneDirector director, string assetsRoot, string preparedRoot) + { + // All authored ASE/PNG data is prepared locally too; runtime does not + // invent model defaults or silently fall back to an unrelated file. + _ = assetsRoot; + var root = Path.GetFullPath(preparedRoot); + using var document = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "models.json"))); + if (document.RootElement.GetProperty("schema").GetInt32() != 1) + throw new InvalidDataException("Unsupported prepared static model manifest"); + string Resolve(string relative) + { + if (Path.IsPathRooted(relative)) throw new InvalidDataException("Static model path must be relative"); + var path = Path.GetFullPath(Path.Combine(root, relative)); + if (!path.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + throw new InvalidDataException("Prepared static model escapes its directory"); + return path; + } + var models = new Dictionary(StringComparer.Ordinal); + var bounds = new Dictionary(StringComparer.Ordinal); + foreach (var model in document.RootElement.GetProperty("models").EnumerateArray()) + { + models.Add(model.GetProperty("key").GetString()!, Mesh.LoadSceneJson(Resolve(model.GetProperty("path").GetString()!))); + if (model.TryGetProperty("source", out var source) && source.TryGetProperty("localBounds", out var box)) + { + Vector3 Read(string key) => new(box.GetProperty(key)[0].GetSingle(), box.GetProperty(key)[1].GetSingle(), box.GetProperty(key)[2].GetSingle()); + bounds.Add(model.GetProperty("key").GetString()!, (Read("min"), Read("max"))); + } + } + var sourceActors = director.Actors.Where(a => a.SourceGam is not null) + .ToDictionary(a => a.SourceGam!.Offset); + var vertices = combined.Vertices.ToList(); + var indices = combined.Indices.ToList(); + var draws = combined.HasExplicitDraws ? combined.Draws.ToList() + : [new MeshDraw(0, (uint)combined.Indices.Length, -1)]; + var textures = new Dictionary(combined.Textures); + var nextTexture = int.MinValue + 20_000; + var added = new HashSet(); + foreach (var entry in document.RootElement.GetProperty("actors").EnumerateArray()) + { + var sourceOffset = entry.GetProperty("offset").GetInt32(); + if (!added.Add(sourceOffset) || !sourceActors.TryGetValue(sourceOffset, out var actor) + || actor.Kind != entry.GetProperty("kind").GetString()) + throw new InvalidDataException("Prepared static model actor does not match its source GAM offset"); + var variants = new List(); + var tint = new Vector3(actor.SourceGam!.Number("Red", 1), actor.SourceGam.Number("Green", 1), + actor.SourceGam.Number("Blue", 1)); + foreach (var variant in entry.GetProperty("variants").EnumerateObject()) + { + var model = models[variant.Value.GetString()!]; + var local = model.Vertices.Select(v => new MeshVertex(v.Position, v.Uv, v.Color * tint)).ToArray(); + var vertexOffset = vertices.Count; + var indexOffset = indices.Count; + var identities = new Dictionary(); + foreach (var texture in model.Textures) + { + if (textures.ContainsKey(nextTexture)) + throw new InvalidDataException("Reserved static model texture identity is already in use"); + identities.Add(texture.Key, nextTexture); + textures.Add(nextTexture++, texture.Value); + } + vertices.AddRange(local); + indices.AddRange(model.Indices.Select(i => checked(i + (uint)vertexOffset))); + var retained = new List(); + // LoadSceneJson intentionally omits null-material draws. Never + // replace an empty explicit list with a white whole-model draw. + var modelDraws = model.HasExplicitDraws ? model.Draws + : [new MeshDraw(0, (uint)model.Indices.Length, -1)]; + foreach (var draw in modelDraws) + { + var textureId = draw.TextureId == -1 ? -1 + : identities.TryGetValue(draw.TextureId, out var mapped) ? mapped + : throw new InvalidDataException("Static model draw references a missing texture"); + var retainedDraw = new MeshDraw(checked(draw.FirstIndex + (uint)indexOffset), draw.IndexCount, textureId); + retained.Add(retainedDraw); + draws.Add(retainedDraw); + } + variants.Add(new(variant.Name, local, vertexOffset, retained.ToArray())); + } + var defaultVariant = entry.GetProperty("defaultVariant").GetString()!; + if (!variants.Any(v => Equal(v.Name, defaultVariant))) + throw new InvalidDataException("Missing default static model variant"); + var defaultKey = entry.GetProperty("variants").GetProperty(defaultVariant).GetString()!; + visuals.Add(new(actor, defaultVariant, variants.ToArray(), bounds.TryGetValue(defaultKey, out var box) ? box : null)); + } + Mesh = new(vertices.ToArray(), indices.ToArray()) + { + Draws = draws.ToArray(), HasExplicitDraws = true, Textures = textures + }; + Update(Mesh); + } + + /// Apply the director's current root transform/visibility to retained model ranges. + public void Update(Mesh destination) + { + if (destination.Vertices.Length < Mesh.Vertices.Length) + throw new ArgumentException("Destination omits static model vertex ranges", nameof(destination)); + foreach (var visual in visuals) + { + var actor = visual.Actor; + var selected = visual.DefaultVariant; + if (actor.Kind == "3BUT") + { + if (Equal(actor.Animation, "DOWN") || Equal(actor.Animation, "HIDOWN")) selected = "DOWN"; + else if (Equal(actor.Animation, "UP") || Equal(actor.Animation, "HIUP")) selected = "UP"; + } + var transform = Transform(actor); + foreach (var variant in visual.Variants) + { + for (var i = 0; i < variant.LocalVertices.Length; i++) + { + var vertex = variant.LocalVertices[i]; + vertex.Position = Vector3.Transform(vertex.Position, transform); + destination.Vertices[variant.Offset + i] = vertex; + } + foreach (var draw in variant.Draws) + draw.Visible = actor.Visible && Equal(variant.Name, selected); + } + } + } + + public IEnumerable DoorColliders() + { + foreach (var visual in visuals) + { + if (visual.Actor.Kind != "3DUD") continue; + var box = visual.LocalBounds ?? throw new InvalidDataException("Prepare original local door bounds before dynamic collision"); + var flags = DynamicSceneCollision.DoorCollisionFlags(visual.Actor.SourceGam!.Integer("HasCollision", -1)); + yield return new(visual.Actor.SourceGam.Offset, visual.Actor.Position, box.Min, box.Max, + Transform(visual.Actor), CollisionEnabled: flags.EntityCollision); + } + } + + private static Matrix4x4 Transform(DirectorActor actor) => + Matrix4x4.CreateRotationX(actor.Rotation.X * MathF.PI / 180) + * Matrix4x4.CreateRotationY(-actor.Rotation.Y * MathF.PI / 180) + * Matrix4x4.CreateRotationZ(actor.Rotation.Z * MathF.PI / 180) + * Matrix4x4.CreateTranslation(actor.Position); + + private static bool Equal(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase); +} diff --git a/src/GamePort/Assets/Mesh.cs b/src/GamePort/Assets/Mesh.cs index 5f7d612..b473c3d 100644 --- a/src/GamePort/Assets/Mesh.cs +++ b/src/GamePort/Assets/Mesh.cs @@ -14,6 +14,7 @@ public struct MeshVertex(Vector3 position, Vector2 uv, Vector3 color) public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices) { + public MeshPolygonSource[] CollisionPolygons { get; init; } = []; public MeshDraw[] Draws { get; init; } = []; public bool HasExplicitDraws { get; init; } public Dictionary Textures { get; init; } = []; @@ -38,6 +39,14 @@ public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices) var indices = root.GetProperty("indices").EnumerateArray().Select(p => p.GetUInt32()).ToArray(); if (indices.Length % 3 != 0 || indices.Any(i => i >= vertices.Length)) throw new InvalidDataException("Invalid scene triangle indices."); if (vertices.Length == 0 || indices.Length == 0) throw new InvalidDataException("Empty scene mesh."); + var collisionPolygons = root.TryGetProperty("collisionPolygons", out var polygonList) + ? polygonList.EnumerateArray().Select(p => new MeshPolygonSource(p.GetProperty("shapeId").GetInt32(), + p.GetProperty("polygonIndex").GetInt32(), + new Vector3(p.GetProperty("normal")[0].GetSingle(), p.GetProperty("normal")[1].GetSingle(), p.GetProperty("normal")[2].GetSingle()), + p.GetProperty("materialName").GetString())).ToArray() : []; + if (collisionPolygons.Length != 0 && (collisionPolygons.Length != indices.Length / 3 + || collisionPolygons.Any(p => !float.IsFinite(p.Normal.X + p.Normal.Y + p.Normal.Z)))) + throw new InvalidDataException("Invalid source collision polygon metadata"); var textures = new Dictionary(); if(root.TryGetProperty("textures",out var textureList)) foreach(var t in textureList.EnumerateArray()) { @@ -71,8 +80,14 @@ public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices) for(var i=first;i checked(i + (uint)scene.Vertices.Length))).ToArray(); var draws = scene.HasExplicitDraws ? scene.Draws : [new MeshDraw(0, (uint)scene.Indices.Length, -1)]; - var textures = new Dictionary(scene.Textures) { [int.MinValue] = Texture }; + if (scene.Textures.ContainsKey(textureId)) throw new InvalidDataException("Actor texture identity already in use"); + var textures = new Dictionary(scene.Textures) { [textureId] = Texture }; return new Mesh(vertices, indices) { HasExplicitDraws = true, - Draws = [.. draws, new MeshDraw((uint)scene.Indices.Length, (uint)Base.Indices.Length, int.MinValue)], + Draws = [.. draws, new MeshDraw((uint)scene.Indices.Length, (uint)Base.Indices.Length, textureId)], Textures = textures }; } diff --git a/src/GamePort/Assets/OriginalSave.cs b/src/GamePort/Assets/OriginalSave.cs new file mode 100644 index 0000000..79d92c5 --- /dev/null +++ b/src/GamePort/Assets/OriginalSave.cs @@ -0,0 +1,114 @@ +using System.Buffers.Binary; +using System.Numerics; +using System.Text; + +namespace GamePort.Assets; + +public sealed record SavedTask(string Name, int State); + +/// Original TSK wire layout recovered at EXE0x45FEE0/0x4603F0; unknown fields retained. +public sealed record OriginalSave(string LevelCode, float PlayerValue, short Counter, + int Score, int OtherCounter, int[] ItemStates, int[] LevelCounters, + string StartPoint, string ReservedName, string ReturnLevel, string ReturnStart, + Vector3 StoredVector, int[] InventoryStates, SavedTask[] Tasks) +{ + public const int ItemCount = 4200, LevelCounterCount = 29, InventoryCount = 19; + public static OriginalSave Load(string path) => Parse(File.ReadAllBytes(path)); + + public static OriginalSave Parse(ReadOnlySpan bytes) + { + var reader = new Reader(bytes); + var code = reader.Text(4); + if (code.Any(c => !char.IsAsciiLetterOrDigit(c))) throw new InvalidDataException("Invalid TSK level code"); + var playerValue = reader.Float(); + var counter = reader.Short(); + var score = reader.Integer(); + var otherCounter = reader.Integer(); + var items = reader.Integers(ItemCount); + var levels = reader.Integers(LevelCounterCount); + var start = reader.Pascal(); + var reserved = reader.Pascal(); + var returnLevel = reader.Pascal(); + var returnStart = reader.Pascal(); + var vector = new Vector3(reader.Float(), reader.Float(), reader.Float()); + var inventory = reader.Integers(InventoryCount); + var count = reader.Integer(); + if (count < 0 || count > reader.Remaining / 5) throw new InvalidDataException("Invalid TSK task count"); + var tasks = new SavedTask[count]; + for (var i = 0; i < count; i++) tasks[i] = new(reader.Pascal(), reader.Integer()); + if (reader.Remaining != 0) throw new InvalidDataException("Unexpected TSK trailing bytes"); + return new(code, playerValue, counter, score, otherCounter, items, levels, start, reserved, + returnLevel, returnStart, vector, inventory, tasks); + } + + public byte[] Encode() + { + using var output = new MemoryStream(); + void Integer(int value) + { + Span raw = stackalloc byte[4]; + BinaryPrimitives.WriteInt32BigEndian(raw, value); + output.Write(raw); + } + void Float(float value) + { + if (!float.IsFinite(value)) throw new InvalidDataException("Nonfinite TSK float"); + Integer(BitConverter.SingleToInt32Bits(value)); + } + void Text(string value, bool pascal) + { + if (value.Any(c => c > 255) || pascal && value.Length > 255) + throw new InvalidDataException("TSK text must fit original Latin1 Pascal string"); + if (pascal) output.WriteByte((byte)value.Length); + output.Write(Encoding.Latin1.GetBytes(value)); + } + void Table(int[] values, int length) + { + if (values.Length != length) throw new InvalidDataException("Invalid fixed TSK table length"); + foreach (var value in values) Integer(value); + } + if (LevelCode.Length != 4 || LevelCode.Any(c => !char.IsAsciiLetterOrDigit(c))) + throw new InvalidDataException("Invalid TSK level code"); + Text(LevelCode, false); + Float(PlayerValue); + Span shortBytes = stackalloc byte[2]; + BinaryPrimitives.WriteInt16BigEndian(shortBytes, Counter); + output.Write(shortBytes); + Integer(Score); Integer(OtherCounter); + Table(ItemStates, ItemCount); Table(LevelCounters, LevelCounterCount); + Text(StartPoint, true); Text(ReservedName, true); Text(ReturnLevel, true); Text(ReturnStart, true); + Float(StoredVector.X); Float(StoredVector.Y); Float(StoredVector.Z); + Table(InventoryStates, InventoryCount); + Integer(Tasks.Length); + foreach (var task in Tasks) { Text(task.Name, true); Integer(task.State); } + return output.ToArray(); + } + + private ref struct Reader(ReadOnlySpan data) + { + private readonly ReadOnlySpan bytes = data; + private int offset; + public int Remaining => bytes.Length - offset; + private ReadOnlySpan Take(int count) + { + if (count < 0 || count > Remaining) throw new InvalidDataException($"Truncated TSK at0x{offset:X}"); + var value = bytes.Slice(offset, count); offset += count; return value; + } + public string Text(int count) => Encoding.Latin1.GetString(Take(count)); + public string Pascal() => Text(Take(1)[0]); + public short Short() => BinaryPrimitives.ReadInt16BigEndian(Take(2)); + public int Integer() => BinaryPrimitives.ReadInt32BigEndian(Take(4)); + public float Float() + { + var value = BitConverter.Int32BitsToSingle(Integer()); + return float.IsFinite(value) ? value : throw new InvalidDataException("Nonfinite TSK float"); + } + public int[] Integers(int count) + { + if (count > Remaining / 4) throw new InvalidDataException("Truncated fixed TSK table"); + var values = new int[count]; + for (var i = 0; i < count; i++) values[i] = Integer(); + return values; + } + } +} diff --git a/src/GamePort/Assets/PreparedEntityResources.cs b/src/GamePort/Assets/PreparedEntityResources.cs new file mode 100644 index 0000000..c2ee9f0 --- /dev/null +++ b/src/GamePort/Assets/PreparedEntityResources.cs @@ -0,0 +1,60 @@ +using System.Text.Json; + +namespace GamePort.Assets; + +public sealed record PreparedWave(string Path, double Seconds); + +/// Original database/type/id resource identities retained by entities.py. +public sealed class PreparedEntityResources +{ + private readonly Dictionary<(string Database, int Id), PreparedWave> waves = []; + private readonly Dictionary<(string Database, int Id), PngImage> canvases = []; + public PreparedEntityResources(params string[] manifests) + { + foreach (var manifest in manifests) Load(manifest); + } + private void Load(string manifest) + { + var directory = Path.GetDirectoryName(Path.GetFullPath(manifest))!; + string Resolve(string relative) + { + var full = Path.GetFullPath(Path.Combine(directory, relative)); + if (!full.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + throw new InvalidDataException("Prepared resource escapes its directory"); + return full; + } + using var doc = JsonDocument.Parse(File.ReadAllText(manifest)); + foreach (var resource in doc.RootElement.GetProperty("resources").EnumerateArray()) + { + if (!resource.TryGetProperty("path", out var path)) continue; + var key = (Normalize(resource.GetProperty("database").GetString()!), resource.GetProperty("id").GetInt32()); + switch (resource.GetProperty("type").GetString()) + { + case "Wave": + var seconds = resource.GetProperty("audio").GetProperty("seconds").GetDouble(); + if (!double.IsFinite(seconds) || seconds < 0) throw new InvalidDataException("Invalid prepared audio duration"); + var resolved = Resolve(path.GetString()!); + if (waves.TryGetValue(key, out var previous)) + { + if (previous.Seconds != seconds || !File.ReadAllBytes(previous.Path).AsSpan().SequenceEqual(File.ReadAllBytes(resolved))) + throw new InvalidDataException("Conflicting prepared wave identity"); + } + else waves.Add(key, new(resolved, seconds)); + break; + case "Canv": + var width = resource.GetProperty("width").GetUInt32(); + var height = resource.GetProperty("height").GetUInt32(); + var rgba = File.ReadAllBytes(Resolve(path.GetString()!)); + if (width == 0 || height == 0 || width > 8192 || height > 8192 || rgba.Length != checked((int)(width * height * 4))) + throw new InvalidDataException("Invalid prepared canvas"); + canvases.Add(key, new(width, height, rgba)); + break; + } + } + } + private static string Normalize(string name) => Path.GetFileName(name.Replace('\\', '/')).ToUpperInvariant(); + public PreparedWave? Wave(string database, int id) => waves.GetValueOrDefault((Normalize(database), id)); + public PngImage? Canvas(string database, int id) => canvases.GetValueOrDefault((Normalize(database), id)); + public double Duration(string database, int id) => Wave(database, id)?.Seconds + ?? throw new FileNotFoundException($"Prepare original speech resource {database}:Wave:{id}"); +} diff --git a/src/GamePort/Audio/SceneAudio.cs b/src/GamePort/Audio/SceneAudio.cs new file mode 100644 index 0000000..5875774 --- /dev/null +++ b/src/GamePort/Audio/SceneAudio.cs @@ -0,0 +1,61 @@ +using GamePort.Assets; + +namespace GamePort.Audio; + +/// Independent original music and sequential speech streams. +public sealed class SceneAudio : IDisposable +{ + private readonly PreparedEntityResources resources; + private SdlAudio? music, speech; + private readonly List effects = []; + private readonly Dictionary loops = new(StringComparer.OrdinalIgnoreCase); + public int EffectCount => effects.Count; + public int LoopCount => loops.Count; + public int QueuedEffectBytes => effects.Sum(effect => effect.QueuedBytes) + loops.Values.Sum(effect => effect.QueuedBytes); + public int QueuedMusicBytes => music?.QueuedBytes ?? 0; + public int QueuedSpeechBytes => speech?.QueuedBytes ?? 0; + public SceneAudio(PreparedEntityResources resources) => this.resources = resources; + public void Music(string database, int id) + { + music?.Dispose(); music = null; + if (resources.Wave(database, id) is { } wave) music = new(wave.Path, true); + } + public void Speech(string database, int id) + { + StopSpeech(); + var wave = resources.Wave(database, id) ?? throw new FileNotFoundException($"Missing prepared speech: {database}:{id}"); + speech = new(wave.Path); + } + public void StopSpeech() { speech?.Dispose(); speech = null; } + // Default current bank set by Jimmy PostLoad423642..656; positional attenuation + // and original channel/volume policy are separate unrecovered consumers. + public void Effect(int id, string? loopOwner = null) + { + var wave = resources.Wave("SoundEffects.omt", id) + ?? throw new FileNotFoundException($"Missing original default sound effect {id}"); + if (loopOwner == null) effects.Add(new(wave.Path)); + else + { + StopLoop(loopOwner); + loops.Add(loopOwner, new(wave.Path, true)); + } + } + public void StopLoop(string owner) + { + if (loops.Remove(owner, out var stream)) stream.Dispose(); + } + public void StopEffects() + { + foreach (var effect in effects) effect.Dispose(); + foreach (var effect in loops.Values) effect.Dispose(); + effects.Clear(); loops.Clear(); + } + public void Pump() + { + music?.Pump(); speech?.Pump(); + foreach (var effect in loops.Values) effect.Pump(); + for (var i = effects.Count - 1; i >= 0; i--) + if (effects[i].QueuedBytes == 0) { effects[i].Dispose(); effects.RemoveAt(i); } + } + public void Dispose() { StopEffects(); StopSpeech(); music?.Dispose(); music = null; } +} diff --git a/src/GamePort/Game/ActorPatrol.cs b/src/GamePort/Game/ActorPatrol.cs new file mode 100644 index 0000000..8fb4d3f --- /dev/null +++ b/src/GamePort/Game/ActorPatrol.cs @@ -0,0 +1,214 @@ +using System.Numerics; + +namespace GamePort.Game; + +/// Root state exchanged with the separately implemented body solver. +public readonly record struct PatrolBodyState(Vector3 Position, Vector3 Velocity); + +/// +/// Goddard/Carl's ordinary state3 patrol and state7 waypoint wait. The original base +/// update consumes the preceding velocity/heading before choosing the next ones. +/// Physical collision/gravity are supplied by the caller. Magnitude uses the +/// recovered OMT table algorithm; flat atan2 heading and modern table-generation +/// trig still require comparison against original angle/x87 results. +/// See docs/analysis/patrol.md for recovered order, addresses and limitations. +/// +public sealed class ActorPatrol +{ + public const float ArrivalDistance = 110; + public const float YawFactor = 3.2f; + private readonly DirectorActor actor; + private readonly Func findActor; + private readonly Func integrateBody; + private readonly Func magnitude; + private readonly float yawFactor; + private readonly string movingAnimation, waitingAnimation; + private DirectorActor? waypoint; + private DirectorActor? previousWaypoint; + private Vector3 publishedPosition, publishedRotation; + private string? publishedPatrol; + private int publishedState, previousState; + private float desiredYaw; + + public Vector3 Velocity { get; private set; } + public Vector3 DestinationDelta { get; private set; } + public float DestinationDistance { get; private set; } + public bool Arrived { get; private set; } + 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 ActorPatrol(DirectorActor actor, Func findActor, + Func integrateBody, + Func? magnitude = null) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(findActor); + ArgumentNullException.ThrowIfNull(integrateBody); + if (actor.Kind is not ("3DOG" or "3CAR")) throw new ArgumentException("Recovered patrol requires Goddard or Carl", nameof(actor)); + this.actor = actor; + this.findActor = findActor; + this.integrateBody = integrateBody; + this.magnitude = magnitude ?? OriginalBodySupport.QuickMagnitude; + // Carl413BFC..43 installs WALK/STOP; his Y factor remains3 (407CF8). + yawFactor = actor.Kind == "3DOG" ? YawFactor : 3; + movingAnimation = actor.Kind == "3DOG" ? "RUN" : "WALK"; + waitingAnimation = actor.Kind == "3DOG" ? "WAG" : "STOP"; + desiredYaw = actor.Rotation.Y; + Publish(); + } + + /// + /// Observe authored AI/teleport actions without changing their animation. + /// Teleports reset the port body's motion/route cache; their full original + /// physics bookkeeping is not yet recovered. Camera-only animation changes + /// leave the body and waypoint intact. Internal patrol changes emit no event. + /// + public void SynchronizeAuthoredState() + { + if (actor.Position != publishedPosition) + { + Velocity = Vector3.Zero; + ResetRoute(); + desiredYaw = actor.Rotation.Y; + } + if (actor.Rotation != publishedRotation) desiredYaw = actor.Rotation.Y; + if (!Equal(actor.Patrol, publishedPatrol) + || actor.AIstate != publishedState && actor.AIstate == 3) + ResetRoute(); + Publish(); + } + + /// False when the current AI state lies outside this recovered subset. + public bool Step(float dt) + { + if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt)); + SynchronizeAuthoredState(); + if (!SupportedState) return false; + if (!actor.Active) return true; + if (!float.IsFinite(actor.Speed)) throw new InvalidOperationException("Nonfinite Goddard speed"); + + // EXE408023->40E050: the body consumes the *previous* velocity first. + var body = integrateBody(new(actor.Position, Velocity), dt); + if (!Finite(body.Position) || !Finite(body.Velocity)) + throw new InvalidOperationException("Goddard body solver produced nonfinite state"); + actor.Position = body.Position; + Velocity = body.Velocity; + var yawError = (desiredYaw - actor.Rotation.Y) % 360; + if (yawError > 180) yawError -= 360; + if (yawError < -180) yawError += 360; + actor.Rotation = actor.Rotation with { Y = actor.Rotation.Y + yawError * yawFactor * dt }; + + switch (actor.AIstate) + { + case 1: Velocity = Vector3.Zero; break; // EXE40835D, after body integration. + case 3: StepPatrol(); break; + case 7: StepWait(dt); break; + // State9 jumps directly to the common finisher408911. State6 calls + // sensing409CC0 first; source player-contact dispatch is implemented + // by SceneInteractions, while general FOV/visibility sensing is open. + case 6: case 9: break; + } + // 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) + desiredYaw = MathF.Atan2(-DestinationDelta.X, DestinationDelta.Z) * (180 / MathF.PI); + Publish(); + return true; + } + + private void StepPatrol() + { + waypoint ??= findActor(actor.Patrol ?? "none"); + if (waypoint == null) + { + SetState(1); + Velocity = new(0, Velocity.Y, 0); // Missing initial waypoint preserves Y. + } + else + { + DestinationDelta = waypoint.Position - actor.Position; + DestinationDistance = DestinationDelta.Length(); + if (!float.IsFinite(DestinationDistance)) throw new InvalidOperationException("Patrol destination exceeds finite arithmetic range"); + } + // This remains after the waypoint resolver even if it changed state1. + actor.Animation = movingAnimation; + if (waypoint == null) return; + + if (Arrived) + { + Velocity = Vector3.Zero; + actor.Animation = waitingAnimation; + } + else if (DestinationDelta == Vector3.Zero) Velocity = Vector3.Zero; + else + { + var length = magnitude(DestinationDelta); + if (!float.IsFinite(length) || length <= 0) throw new InvalidOperationException("Invalid patrol magnitude"); + Velocity = DestinationDelta / length * actor.Speed; + } + // EXE408BC0 compares distance only after selecting the next velocity. + if (DestinationDistance < ArrivalDistance) Arrived = true; + else if (DestinationDistance > ArrivalDistance) Arrived = false; + if (!Arrived || waypoint.Kind != "3PAT" || waypoint.SourceGam is not { } point) return; + + var wait = point.Number("WaitTime"); + if (wait > 0) + { + SetState(7); + actor.Animation = point.Text("WaitAnim") ?? "none"; + WaitRemaining = wait; + Velocity = Vector3.Zero; + return; + } + previousWaypoint = waypoint; + var next = point.Text("NextPatrolPoint") ?? "none"; + waypoint = findActor(next); + if (waypoint != null) return; + if (Equal(next, "WAIT")) SetState(1); + else if (Equal(next, "SCAN")) SetState(6); + // Ordinary unresolved names, including "none", retain state3. Next tick + // resolves the initial PatrolPoint; there is no terminal-route snap. + } + + private void StepWait(float dt) + { + Velocity = Vector3.Zero; + if (WaitRemaining <= 0) return; // Source checks positivity before subtract. + WaitRemaining -= dt; + if (WaitRemaining > 0) return; // Equality expires: EXE4083B0 testah41/je. + SetState(previousState); + Arrived = false; + // The timed-wait branch does not interpret WAIT/SCAN specially. + waypoint = waypoint?.SourceGam is { } point && waypoint.Kind == "3PAT" + ? findActor(point.Text("NextPatrolPoint") ?? "none") : null; + } + + private void SetState(int state) + { + previousState = actor.AIstate; + actor.AIstate = state; + if (state == 1) actor.Animation = waitingAnimation; + else if (state == 3) actor.Animation = movingAnimation; + } + + private void ResetRoute() + { + waypoint = previousWaypoint = null; + Arrived = false; + WaitRemaining = 0; + DestinationDelta = Vector3.Zero; + DestinationDistance = 0; + } + + private void Publish() + { + publishedPosition = actor.Position; + publishedRotation = actor.Rotation; + publishedPatrol = actor.Patrol; + publishedState = actor.AIstate; + } + private static bool Equal(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase); + private static bool Finite(Vector3 v) => float.IsFinite(v.X) && float.IsFinite(v.Y) && float.IsFinite(v.Z); +} diff --git a/src/GamePort/Game/DynamicBodyResponse.cs b/src/GamePort/Game/DynamicBodyResponse.cs new file mode 100644 index 0000000..d4ebc84 --- /dev/null +++ b/src/GamePort/Game/DynamicBodyResponse.cs @@ -0,0 +1,34 @@ +using System.Numerics; +using GamePort.Assets; + +namespace GamePort.Game; + +/// +/// Explicit provisional narrowphase adapter. Source mode2 gates/corners/order +/// come from DynamicSceneCollision; sweep/slide uses the modern sphere kernel. +/// This is not a translation of original47BD80. +/// +public static class DynamicBodyResponse +{ + public static Vector3 Resolve(IEnumerable boxes, Vector3 previous, Vector3 position, float radius) + { + foreach (var box in boxes) + { + var response = DynamicSceneCollision.Resolve(box, new(previous, position, radius), Sweep); + if (response.Contact) position = response.Position; + } + return position; + } + + private static DynamicCollisionResponse Sweep(DynamicBoxSweep sweep) + { + var vertices = sweep.Triangles.SelectMany(t => new[] { t.A, t.B, t.C }) + .Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(); + var mesh = new Mesh(vertices, Enumerable.Range(0, vertices.Length).Select(i => (uint)i).ToArray()); + var radius = sweep.Sphere.Radius; + var moved = new SceneCollision(mesh).Move(sweep.Sphere.PreviousPosition - Vector3.UnitY * radius, + sweep.Sphere.Position - sweep.Sphere.PreviousPosition, radius, radius * 2); + var position = moved.Position + Vector3.UnitY * radius; + return new(Vector3.DistanceSquared(position, sweep.Sphere.Position) > .0001f, position); + } +} diff --git a/src/GamePort/Game/DynamicSceneCollision.cs b/src/GamePort/Game/DynamicSceneCollision.cs new file mode 100644 index 0000000..01c205c --- /dev/null +++ b/src/GamePort/Game/DynamicSceneCollision.cs @@ -0,0 +1,128 @@ +using System.Numerics; + +namespace GamePort.Game; + +/// +/// A mode2 entity's original local shape cube and current transform. Drawing +/// visibility and own physics integration are independent of CollisionEnabled. +/// +public readonly record struct DynamicBoxCollider( + int Identity, Vector3 Root, Vector3 LocalMin, Vector3 LocalMax, Matrix4x4 LocalToWorld, + float Radius = 40, bool CollisionEnabled = true, bool InhibitResponse = false); + +public readonly record struct DynamicSphereMotion( + Vector3 PreviousPosition, Vector3 Position, float Radius, + bool CollisionEnabled = true, bool GeometryCollisionEnabled = true, int Mode = 1); + +public sealed record DynamicBoxSweep( + DynamicBoxCollider Box, DynamicSphereMotion Sphere, IReadOnlyList Triangles); + +public readonly record struct DynamicCollisionResponse(bool Contact, Vector3 Position); + +/// +/// Recovered mode2 dispatch, broadphase and oriented local-cube triangulation +/// from EXE47A430/47A5E0. The narrowphase is injected because47BD80 and its +/// static-world response have not been fully translated. See dynamic-collision.md. +/// +public static class DynamicSceneCollision +{ + // C3DDoorUpDown constructor/PostLoad: pair tests on, own integration off, + // mode2 and current radius40. HasCollision=-1 preserves those defaults. + public const float DoorRadius = 40; + public const int DoorMode = 2; + public const bool DoorEntityCollisionDefault = true; + public const bool DoorIntegrationDefault = false; + + // Corner bits X=4,Y=2,Z=1. Source jump table47B3AC selects these12 triples. + private static readonly int[] triangleCorners = [ + 0, 1, 2, 1, 3, 2, 0, 2, 4, 2, 6, 4, + 4, 6, 5, 6, 7, 5, 5, 7, 3, 5, 3, 1, + 0, 4, 1, 4, 5, 1, 2, 3, 7, 7, 6, 2 + ]; + + public static (bool EntityCollision, bool Integrate) DoorCollisionFlags(int hasCollision) => + hasCollision == -1 ? (DoorEntityCollisionDefault, DoorIntegrationDefault) + : (hasCollision != 0, hasCollision != 0); + + /// + /// Preserve the original inclusive root-distance gate. Normal sphere-mode + /// bodies use 2*boxRadius+sphereRadius, even for a large shape-local cube. + /// Mode2-vs-mode2 instead uses the radius sum and skips the triangle sweep. + /// + public static bool BroadPhase(DynamicBoxCollider box, DynamicSphereMotion sphere) + { + Validate(box, sphere); + if (!box.CollisionEnabled || !sphere.CollisionEnabled || !sphere.GeometryCollisionEnabled) return false; + var limit = sphere.Mode == 2 ? box.Radius + sphere.Radius : 2 * box.Radius + sphere.Radius; + return OriginalBodySupport.QuickMagnitude(sphere.Position - box.Root) <= limit; + } + + public static Vector3[] Corners(DynamicBoxCollider box) + { + ValidateBox(box); + var corners = new Vector3[8]; + for (var i = 0; i < corners.Length; i++) + { + var local = new Vector3((i & 4) == 0 ? box.LocalMin.X : box.LocalMax.X, + (i & 2) == 0 ? box.LocalMin.Y : box.LocalMax.Y, + (i & 1) == 0 ? box.LocalMin.Z : box.LocalMax.Z); + corners[i] = Vector3.Transform(local, box.LocalToWorld); + RequireFinite(corners[i]); + } + return corners; + } + + public static SupportTriangle[] Triangles(DynamicBoxCollider box) + { + var corners = Corners(box); + return Enumerable.Range(0, 12).Select(i => new SupportTriangle( + corners[triangleCorners[3 * i]], corners[triangleCorners[3 * i + 1]], + corners[triangleCorners[3 * i + 2]], box.Identity, i)).ToArray(); + } + + /// + /// Caller supplies mutual exclusion/class gates via pairAllowed and the current + /// source cube/transform. Triangle geometry follows the moving box's current + /// root; no invented relative-door sweep or permanent closed-position mesh. + /// + public static DynamicCollisionResponse Resolve(DynamicBoxCollider box, DynamicSphereMotion sphere, + Func narrowPhase, bool pairAllowed = true) + { + ArgumentNullException.ThrowIfNull(narrowPhase); + var unchanged = new DynamicCollisionResponse(false, sphere.Position); + if (!pairAllowed || !BroadPhase(box, sphere)) return unchanged; + // EXE47A712..47A72C returns contact directly for a second mode2 entity. + if (sphere.Mode == 2) return new(true, sphere.Position); + var response = narrowPhase(new(box, sphere, Triangles(box))); + if (!response.Contact) return unchanged; + RequireFinite(response.Position); + // EXE47B2EF checks the box's iface1E0 flag after narrowphase; touch events + // can still occur even when its ordinary root response is inhibited. + return new(true, box.InhibitResponse ? sphere.Position : response.Position); + } + + private static void Validate(DynamicBoxCollider box, DynamicSphereMotion sphere) + { + ValidateBox(box); + RequireFinite(sphere.Position); RequireFinite(sphere.PreviousPosition); + if (!float.IsFinite(sphere.Radius) || sphere.Radius < 0) + throw new ArgumentOutOfRangeException(nameof(sphere), "Finite nonnegative sphere radius required"); + } + private static void ValidateBox(DynamicBoxCollider box) + { + RequireFinite(box.Root); RequireFinite(box.LocalMin); RequireFinite(box.LocalMax); + if (box.LocalMin.X > box.LocalMax.X || box.LocalMin.Y > box.LocalMax.Y || box.LocalMin.Z > box.LocalMax.Z + || !float.IsFinite(box.Radius) || box.Radius < 0) + throw new ArgumentOutOfRangeException(nameof(box), "Ordered source cube and finite nonnegative radius required"); + var m = box.LocalToWorld; + if (new[] { m.M11, m.M12, m.M13, m.M14, m.M21, m.M22, m.M23, m.M24, + m.M31, m.M32, m.M33, m.M34, m.M41, m.M42, m.M43, m.M44 }.Any(v => !float.IsFinite(v)) + || m.M14 != 0 || m.M24 != 0 || m.M34 != 0 || m.M44 != 1) + throw new ArgumentOutOfRangeException(nameof(box), "Finite affine source transform required"); + } + private static void RequireFinite(Vector3 v) + { + if (!float.IsFinite(v.X) || !float.IsFinite(v.Y) || !float.IsFinite(v.Z)) + throw new ArgumentOutOfRangeException(nameof(v), "Finite source coordinates required"); + } +} diff --git a/src/GamePort/Game/JetpackBurst.cs b/src/GamePort/Game/JetpackBurst.cs new file mode 100644 index 0000000..c37643f --- /dev/null +++ b/src/GamePort/Game/JetpackBurst.cs @@ -0,0 +1,202 @@ +namespace GamePort.Game; + +public readonly record struct JetpackBurstState( + int JumpState = 0, float HoldSeconds = 0, float EffectRemaining = 0); + +public readonly record struct JetpackBurstInput( + bool Grounded, bool JumpHeld, float VelocityY, float ShadowDistance, + int InventoryState, float Energy, string LevelCode, int GadgetMode, + float DeltaSeconds, float CurrentExtraAccelerationY, + bool EffectAvailable = true, float GravityY = -800); + +public enum JetpackPose { None, Jump, Fall, Fly } + +public readonly record struct JetpackBurstResult( + JetpackBurstState State, float ImpulseY, float? VelocityYOverride, + float ExtraAccelerationY, JetpackPose Pose, float? RadiusOverride, + bool StartGadget, bool StopGadget, int? MovementModeOverride); + +public readonly record struct JetpackEffectResult( + JetpackBurstState State, float Energy, bool Visible); + +/// +/// The jump/jetpack branches of EXE437F90 and effect timer of EXE421FB0. +/// Controller and effect phases are separate: their full-scene order has not +/// been recovered. The caller must explicitly choose an order. Horizontal +/// movement, shadow queries, visuals and sound callbacks belong to the caller. +/// +public static class JetpackBurst +{ + public const float Duration = 8; + public const float HoldThreshold = .4f; + public const float JumpImpulse = 550; + public const float BurstInitialVelocityY = 10; + public const float BurstRadius = 100; + public const float LandingRadius = 60; + public const float EnergyPerSecond = .5f; + + /// + /// Includes the outer update's ordinary grounded/released reset (437B9E). + /// CurrentExtraAccelerationY is required because the expired-effect branch + /// returns before writing acceleration. Results describe this invocation; + /// a newly started/stopped burst changes acceleration on the next call. + /// + public static JetpackBurstResult Step(JetpackBurstState state, JetpackBurstInput input) + { + ValidateState(state); + ValidateSeconds(input.DeltaSeconds); + RequireFinite(input.VelocityY); + RequireFinite(input.ShadowDistance); + RequireFinite(input.Energy); + RequireFinite(input.CurrentExtraAccelerationY); + RequireFinite(input.GravityY); + ArgumentNullException.ThrowIfNull(input.LevelCode); + var extra = input.CurrentExtraAccelerationY; + JetpackBurstResult Result(float impulse = 0, float? velocity = null, + JetpackPose pose = JetpackPose.None, float? radius = null, + bool start = false, bool stop = false, int? mode = null) => + new(state, impulse, velocity, extra, pose, radius, start, stop, mode); + + if (input.Grounded && !input.JumpHeld) + { + // This path runs ground apply instead of air apply; it does not + // itself clear the effect timer or restore the radius. + state = state with { JumpState = 0 }; + return Result(mode: 0); + } + + if (state.JumpState < 3) + extra = input.GravityY * 1.33f - input.GravityY; + else + { + if (input.EffectAvailable && state.EffectRemaining <= 0 && state.JumpState is 3 or 4) + { + state = state with { JumpState = 0, EffectRemaining = 0 }; + return Result(pose: JetpackPose.Fall, stop: true, mode: 1); + } + // The near-floor constants are doubles in the original; the far + // branch uses float .1. Preserve those distinct constant widths. + extra = input.ShadowDistance < 500 + ? (float)(-input.GravityY - (input.VelocityY < -1 ? .3 : .1) * input.GravityY) + : .1f * input.GravityY - input.GravityY; + } + + if (!input.JumpHeld) + { + switch (state.JumpState) + { + case 1: + state = state with { JumpState = 2 }; + break; + case 3: + state = state with { JumpState = 4, + EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining }; + return Result(pose: JetpackPose.Fall, stop: true, mode: 1); + case 4: + // Table4387C4 entry3 jumps directly43879A. Only state5's + // entry checks grounded at43878C (outer reset above too). + state = state with { JumpState = 0 }; + break; + } + return Result(); + } + + switch (state.JumpState) + { + case 0: + if (!input.Grounded) return Result(pose: JetpackPose.Fall, stop: true); + state = state with { JumpState = 1, HoldSeconds = 0, + EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining }; + return Result(impulse: JumpImpulse, pose: JetpackPose.Jump); + case 1: + state = state with { HoldSeconds = state.HoldSeconds + input.DeltaSeconds }; + if (state.HoldSeconds <= HoldThreshold) return Result(); + break; + case 2: + break; + case 3: + if (!input.Grounded) return Result(); + state = state with { JumpState = 4, + EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining }; + return Result(pose: JetpackPose.Fall, radius: LandingRadius, stop: true, mode: 1); + case 5: + if (input.Grounded) state = state with { JumpState = 0 }; + return Result(); + default: + return Result(); + } + + // Both the >.4-second and released-then-held branches enter state3 + // even when no gadget is available. The next expired-effect guard + // then returns to state0, preserving the ballistic acceleration. + state = state with { JumpState = 3 }; + if (!CanStart(input.LevelCode, input.GadgetMode, input.InventoryState, input.Energy)) return Result(); + if (input.EffectAvailable) state = state with { EffectRemaining = Duration }; + return Result(velocity: BurstInitialVelocityY, pose: JetpackPose.Fly, + radius: input.EffectAvailable ? BurstRadius : null, start: true); + } + + public static bool CanStart(string levelCode, int gadgetMode, int inventoryState, float energy) + { + ArgumentNullException.ThrowIfNull(levelCode); + RequireFinite(energy); + if (levelCode == "VR04") return true; + return levelCode is not ("LEV6" or "LV4B" or "LV6A" or "LEV3" or "LV3A" or "LV3B" or "LV3C" or "LV3D") + && gadgetMode is not (2 or 6 or 7) && energy > 0 && inventoryState is not (0 or 4); + } + + /// + /// Effect421FB0 resets grounded remaining time to0, subtracts dt (including + /// when inactive), then drains only if the stored result is positive. + /// Owner/effect absence leaves timer and energy unchanged. Energy reaching + /// zero does not cancel an already running burst. Visibility is this phase's + /// request; the controller phase does not itself show/hide the effect. + /// + public static JetpackEffectResult StepEffect(JetpackBurstState state, bool grounded, + float deltaSeconds, float energy, string levelCode, + bool ownerAvailable = true, bool effectAvailable = true) + { + ValidateState(state); + ValidateSeconds(deltaSeconds); + RequireFinite(energy); + ArgumentNullException.ThrowIfNull(levelCode); + if (!ownerAvailable || !effectAvailable) return new(state, energy, false); + var remaining = (grounded ? 0 : state.EffectRemaining) - deltaSeconds; + state = state with { EffectRemaining = remaining }; + if (remaining <= 0) return new(state, energy, false); + return new(state, AdjustEnergy(energy, -deltaSeconds * EnergyPerSecond, levelCode), true); + } + + /// EXE42A920 numeric VR01..VR08 immunity and [0,100] clamp. SFX are external. + public static float AdjustEnergy(float energy, float delta, string levelCode) + { + RequireFinite(energy); + RequireFinite(delta); + ArgumentNullException.ThrowIfNull(levelCode); + // The source compares a big-endian FourCC numerically, not by prefix. + if (levelCode.Length == 4) + { + var code = ((uint)levelCode[0] << 24) | ((uint)levelCode[1] << 16) + | ((uint)levelCode[2] << 8) | levelCode[3]; + if (code is >= 0x56523031 and <= 0x56523038) return energy; + } + return Math.Clamp(energy + delta, 0, 100); + } + + private static void ValidateState(JetpackBurstState state) + { + if (state.JumpState is < 0 or > 5) throw new ArgumentOutOfRangeException(nameof(state)); + RequireFinite(state.HoldSeconds); + RequireFinite(state.EffectRemaining); + } + + private static void ValidateSeconds(float seconds) + { + if (!float.IsFinite(seconds) || seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds)); + } + + private static void RequireFinite(float value) + { + if (!float.IsFinite(value)) throw new ArgumentOutOfRangeException(nameof(value)); + } +} diff --git a/src/GamePort/Game/LabSimulation.cs b/src/GamePort/Game/LabSimulation.cs index 2fef872..b5a842e 100644 --- a/src/GamePort/Game/LabSimulation.cs +++ b/src/GamePort/Game/LabSimulation.cs @@ -4,7 +4,7 @@ using GamePort.Assets; namespace GamePort.Game; public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump); -public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall } +public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly } /// /// No-gadget walking checkpoint. Recovered input/arithmetic is described in @@ -16,9 +16,18 @@ public sealed class LabSimulation public const float BodyRadius = 24; // Provisional, not a recovered collider dimension. private readonly SceneCollision collision; private readonly Vector3 sourceStart; - private readonly float startYaw, modelMinimumY, rootHeight; - private float targetYaw, jumpHeldTime; - private int jumpState; + private readonly float startYaw, modelMinimumY, rootHeight, startFloor; + private float targetYaw, extraAirAcceleration, shadowDistance; + private JetpackBurstState jumpState; + private bool forceFall; + public Func? JetpackInventoryState { get; set; } + public string LevelCode { get; set; } = "LV1B"; + public int GadgetMode { get; set; } = -1; + public float Energy { get; set; } = 20; + public float InteractionRadius { get; private set; } = 60; + public bool JetpackEffectVisible { get; private set; } + public float JetpackRemaining => jumpState.EffectRemaining; + public int Bursts { get; private set; } public float BodyHeight { get; } public Vector3 Position { get; private set; } // Feet, not original actor root. public Vector3 Velocity { get; private set; } @@ -26,13 +35,15 @@ public sealed class LabSimulation public float Speed { get; private set; } public bool Grounded { get; private set; } public PlayerPose Pose => Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle - : Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall; + : jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly + : !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall; public int Steps { get; private set; } public int Jumps { get; private set; } public int Landings { get; private set; } public int WallHits { get; private set; } public float Travel { get; private set; } public float MaximumRise { get; private set; } + public Func? DynamicRootResolver { get; set; } public Vector3 ActorRoot => Position + Vector3.UnitY * rootHeight; public Vector3 CameraEye { get; private set; } public Vector3 CameraTarget => ActorRoot + new Vector3(0, 99, 0); @@ -49,7 +60,11 @@ public sealed class LabSimulation BodyHeight = bounds.Max.Y - bounds.Min.Y; var floor = collision.GroundHeight(start, 2500) ?? throw new InvalidDataException("No support below GAM startpoint"); - rootHeight = start.Y - floor; + startFloor = floor; + // Normal Jimmy PostLoad4236A3..BA and support47BAE1 place the actor + // root at floor+60*1.265. Serialized spawnY is settled by physics. + // Feet collision and sole-based visual placement remain provisional. + rootHeight = OriginalBodySupport.JimmyRadius * OriginalBodySupport.JimmyFactor; Reset(); } @@ -59,8 +74,10 @@ public sealed class LabSimulation Position = new(sourceStart.X, floor + SceneCollision.Skin, sourceStart.Z); Velocity = Vector3.Zero; Yaw = targetYaw = startYaw; - Speed = jumpHeldTime = 0; - jumpState = 0; + Speed = extraAirAcceleration = shadowDistance = 0; + jumpState = default; + forceFall = JetpackEffectVisible = false; + InteractionRadius = 60; Bursts = 0; Grounded = true; Steps = Jumps = Landings = WallHits = 0; Travel = MaximumRise = 0; @@ -83,7 +100,7 @@ public sealed class LabSimulation float lateral = 0; if (Grounded) { - if (!input.Jump) jumpState = 0; + InteractionRadius = 60; // Jimmy's ordinary grounded update42469B. float yawDelta = 0; if (input.Left) { yawDelta += 20; lateral = -1000; Speed = RecoveredMotion.AddSpeed(Speed); } else if (input.Right) { yawDelta -= 20; lateral = 1000; Speed = RecoveredMotion.AddSpeed(Speed); } @@ -97,34 +114,47 @@ public sealed class LabSimulation var (sin, cos) = Trig(Yaw); var velocity = new Vector3(-sin * Speed, Velocity.Y, cos * Speed); if (Grounded) velocity += new Vector3(cos, 0, sin) * (lateral * dt); - var impulse = Vector3.Zero; - if (Grounded && input.Jump && jumpState == 0) - { - impulse.Y = RecoveredMotion.JumpImpulse; - jumpState = 1; - jumpHeldTime = 0; - Grounded = false; - Jumps++; - } - if (!Grounded && jumpState == 1) - { - if (!input.Jump) jumpState = 2; - else if ((jumpHeldTime += dt) > 0.4f) jumpState = 0; // Zero-fuel jetpack path resets to FALL. - } - else if (!Grounded && jumpState == 2 && input.Jump) - jumpState = 0; // Renewed hold enters the same disabled-gadget reset path. + if (collision.GroundHeight(ActorRoot, 2500) is { } shadowFloor) + shadowDistance = MathF.Abs(ActorRoot.Y - shadowFloor - 13); + var air = JetpackBurst.Step(jumpState, new(Grounded, input.Jump, velocity.Y, shadowDistance, + JetpackInventoryState?.Invoke() ?? 0, Energy, LevelCode, GadgetMode, dt, extraAirAcceleration)); + jumpState = air.State; extraAirAcceleration = air.ExtraAccelerationY; + var impulse = new Vector3(0, air.ImpulseY, 0); + if (air.ImpulseY != 0) { Grounded = false; Jumps++; } + if (air.VelocityYOverride is { } vertical) velocity.Y = vertical; + if (air.RadiusOverride is { } radius) InteractionRadius = radius; + if (air.Pose == JetpackPose.Fall) forceFall = true; + else if (air.Pose is JetpackPose.Jump or JetpackPose.Fly) forceFall = false; + if (air.StartGadget) Bursts++; var displacement = RecoveredMotion.Integrate(ref velocity, ref impulse, - RecoveredMotion.Gravity * 0.33f, RecoveredMotion.Gravity, dt); + Vector3.UnitY * extraAirAcceleration, RecoveredMotion.Gravity, dt); var before = Position; var result = collision.Move(Position, displacement, BodyRadius, BodyHeight); Position = result.Position; + if (DynamicRootResolver != null) + { + var root = ActorRoot; + var resolved = DynamicRootResolver(before + Vector3.UnitY * rootHeight, root, InteractionRadius); + if (resolved != root) + { + // Original47A5E0 re-clips against static geometry before storing + // the new root. Here both kernels remain explicitly provisional. + result = collision.Move(Position, resolved - root, BodyRadius, BodyHeight); + Position = result.Position; + } + } Grounded = result.Grounded && velocity.Y <= 0; if (Grounded && velocity.Y < 0 || result.HitCeiling && velocity.Y > 0) velocity.Y = 0; + if (Grounded) { extraAirAcceleration = 0; forceFall = false; } Velocity = velocity; + // Explicit port phase policy: controller, collision, then effect update. + // Original global object iteration order has not yet been matched. + var effect = JetpackBurst.StepEffect(jumpState, Grounded, dt, Energy, LevelCode); + jumpState = effect.State; Energy = effect.Energy; JetpackEffectVisible = effect.Visible; if (!wasGrounded && Grounded) Landings++; if (result.HitWall) WallHits++; Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z)); - MaximumRise = Math.Max(MaximumRise, Position.Y - sourceStart.Y + rootHeight); + MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor); Steps++; var desired = DesiredEye(); var delta = (desired - CameraEye) * new Vector3(1.6f, 1.2f, 1.6f) * dt; diff --git a/src/GamePort/Game/OriginalBodySupport.cs b/src/GamePort/Game/OriginalBodySupport.cs new file mode 100644 index 0000000..3310965 --- /dev/null +++ b/src/GamePort/Game/OriginalBodySupport.cs @@ -0,0 +1,167 @@ +using System.Numerics; + +namespace GamePort.Game; + +public readonly record struct SupportTriangle(Vector3 A, Vector3 B, Vector3 C, int ShapeId = 0, int PolygonId = 0); +public readonly record struct SupportHit(Vector3 Position, int ShapeId, int PolygonId, float Distance); +public delegate SupportHit? SupportSegmentQuery(Vector3 start, Vector3 end, bool twoSided); + +public readonly record struct SupportBody( + Vector3 Position, Vector3 PreviousPosition, Vector3 Velocity, Vector3 Acceleration, + float Radius, float Factor, bool PreventLowering = true); + +public readonly record struct SupportResult( + SupportBody Body, bool Supported, bool Landed, SupportHit? Hit, Vector3 SupportAnchor); + +/// +/// Bounded translation of EXE47B890 and its source triangle query. This handles +/// root support, not the wall/ceiling sphere solver or entity collisions. Lookup +/// tables use the recovered initializer constants with modern trig; exact x87 +/// table values and full original frame ordering still require comparison. +/// +public static class OriginalBodySupport +{ + public const float JimmyRadius = 60; + public const float JimmyFactor = 1.265f; + public const float GoddardRadius = 130; + public const float GoddardFactor = 0.3f; + private const float TriangleEpsilon = 1.1920928955078125e-7f; + private static readonly float[] sine = BuildSine(); + private static readonly ushort[] halfAcos = BuildHalfAcos(); + + /// OMT1001FF70: largest component divided by a quantized sine lookup. + public static float QuickMagnitude(Vector3 vector) + { + RequireFinite(vector); + var x = (double)MathF.Abs(vector.X); + var y = (double)MathF.Abs(vector.Y); + var z = (double)MathF.Abs(vector.Z); + if (x > y) { if (x > z) (x, z) = (z, x); } + else if (y > z) (y, z) = (z, y); + // The original passes 0/0 through _ftol. The port handles zero directly + // instead of depending on an invalid x87 conversion/control-word mode. + if (z == 0) return 0; + var otherSquared = x * x + y * y; + var index = (int)(otherSquared * 16384 / (otherSquared + z * z)) & 0x3fff; + return (float)(z / sine[halfAcos[index] & 0x3fff]); + } + + /// + /// Apply support after motion/wall resolution. The caller captures previous + /// grounded state and clears its current grounded flag before this phase. + /// A successful support preserves horizontal velocity/acceleration, sets their + /// Y components to zero and emits a landing only on an ungrounded-to-grounded step. + /// + public static SupportResult Resolve(SupportBody body, bool wasGrounded, + SupportSegmentQuery query, bool geometryEnabled = true) + { + ArgumentNullException.ThrowIfNull(query); + RequireFinite(body.Position); RequireFinite(body.PreviousPosition); + RequireFinite(body.Velocity); RequireFinite(body.Acceleration); + if (!float.IsFinite(body.Radius) || body.Radius <= 0 || !float.IsFinite(body.Factor)) + throw new ArgumentOutOfRangeException(nameof(body), "Finite support factor and positive finite radius required"); + var unchanged = new SupportResult(body, false, false, null, Vector3.Zero); + if (!geometryEnabled) return unchanged; + + var product = body.Radius * body.Factor; + var top = MathF.Max(body.Position.Y, body.PreviousPosition.Y); + var motionHit = query(body.PreviousPosition, body.Position, false); + if (motionHit is { } crossed) + top += QuickMagnitude(body.Position - body.PreviousPosition) + - QuickMagnitude(crossed.Position - body.PreviousPosition); + // EXE48D920 is .1f, not .5f. Final root offset always uses r*factor. + var clearance = body.Factor == 1 || body.Factor < 0.1f ? body.Radius : product; + var start = new Vector3(body.Position.X, top + clearance, body.Position.Z); + var end = new Vector3(body.Position.X, body.Position.Y - 2 * body.Radius, body.Position.Z); + var hit = query(start, end, false); + if (hit is not { } floor) return unchanged; + var supportedY = floor.Position.Y + product; + // EXE47BAF3 queries iface208. It rejects a downward root correction, + // independently of vertical velocity, when this flag is enabled. + if (body.PreventLowering && body.Position.Y > supportedY) return unchanged; + var grounded = body with { + Position = new(body.Position.X, supportedY, body.Position.Z), + Velocity = new(body.Velocity.X, 0, body.Velocity.Z), + Acceleration = new(body.Acceleration.X, 0, body.Acceleration.Z) + }; + return new SupportResult(grounded, true, !wasGrounded, floor, new Vector3(0, supportedY, 0)); + } + + /// + /// EXE469B70/47C6E0 source-winding segment query. Null-material polygons must + /// be included. The caller supplies the statically registered polygons; + /// checkpoint/material and game-specific registration filters are separate. + /// A linear scan replaces the original 260x260 broad phase. Equal-distance + /// selection follows input order, which can differ from original grid order. + /// + public static SupportHit? Trace(IEnumerable triangles, + Vector3 start, Vector3 end, bool twoSided = false) + { + ArgumentNullException.ThrowIfNull(triangles); + RequireFinite(start); RequireFinite(end); + var direction = end - start; + var length = QuickMagnitude(direction); + if (length == 0) return null; + direction /= length; + SupportHit? nearest = null; + var nearestDistance = length; + foreach (var triangle in triangles) + { + RequireFinite(triangle.A); RequireFinite(triangle.B); RequireFinite(triangle.C); + var edge1 = triangle.B - triangle.A; + var edge2 = triangle.C - triangle.A; + var p = Cross(direction, edge2); + var determinant = Dot(edge1, p); + // Source indices use the opposite sign from a conventional right- + // handed visible-front-face test. Preserve the actual serialized order. + if (twoSided ? MathF.Abs(determinant) < TriangleEpsilon : determinant > -TriangleEpsilon) + continue; + var inverse = 1 / determinant; + var relative = start - triangle.A; + var u = Dot(relative, p) * inverse; + if (u < 0 || u > 1) continue; + var q = Cross(relative, edge1); + var v = Dot(q, direction) * inverse; + if (v < 0 || u + v > 1) continue; + var distance = Dot(q, edge2) * inverse; + // Source accepts the beginning, but rejects its endpoint and equal + // distance candidates. No invented extra ray distance or skin is used. + if (distance < 0 || distance >= length) continue; + var position = start + direction * distance; + var fromStart = QuickMagnitude(position - start); + if (fromStart >= nearestDistance) continue; + nearestDistance = fromStart; + nearest = new SupportHit(position, triangle.ShapeId, triangle.PolygonId, fromStart); + } + return nearest; + } + + private static float Dot(Vector3 a, Vector3 b) => + (float)((double)a.X * b.X + (double)a.Y * b.Y + (double)a.Z * b.Z); + private static Vector3 Cross(Vector3 a, Vector3 b) => new( + (float)((double)a.Y * b.Z - (double)a.Z * b.Y), + (float)((double)a.Z * b.X - (double)a.X * b.Z), + (float)((double)a.X * b.Y - (double)a.Y * b.X)); + + private static float[] BuildSine() + { + var table = new float[16384]; + // DLL100EDC21 uses this stored double, rather than Math.Tau/16384. + for (var i = 0; i < table.Length; i++) table[i] = (float)Math.Sin(i * 0.0003834951969604492); + table[0] = table[8192] = 0; table[4096] = 1; table[12288] = -1; + return table; + } + private static ushort[] BuildHalfAcos() + { + var table = new ushort[16384]; + // DLL100EDC8C..100EDCB4 truncates half of the acos angular-unit result. + for (var i = 0; i < table.Length; i++) + table[i] = (ushort)(Math.Acos(i * 0.0001220703125 - 1) * 2607.5945876921437 * 0.5); + return table; + } + private static void RequireFinite(Vector3 vector) + { + if (!float.IsFinite(vector.X) || !float.IsFinite(vector.Y) || !float.IsFinite(vector.Z)) + throw new ArgumentOutOfRangeException(nameof(vector), "Finite source coordinates required"); + } +} diff --git a/src/GamePort/Game/OriginalScenePhysics.cs b/src/GamePort/Game/OriginalScenePhysics.cs new file mode 100644 index 0000000..fe17271 --- /dev/null +++ b/src/GamePort/Game/OriginalScenePhysics.cs @@ -0,0 +1,45 @@ +using System.Numerics; +using GamePort.Assets; + +namespace GamePort.Game; + +/// +/// Recovered source wall-grid selection and root-support phase, with the port's +/// provisional swept-sphere wall response. This is not the full original solver. +/// The caller supplies body radius/factor from the actual actor class. +/// +public sealed class OriginalScenePhysics +{ + private readonly SceneCollision walls; + private readonly SupportTriangle[] support; + + public OriginalScenePhysics(Mesh world) + { + if (world.CollisionPolygons.Length != world.Indices.Length / 3) + throw new InvalidDataException("Prepare source collision polygon metadata before original root support"); + walls = new SceneCollision(world, wallsAndCeilingsOnly: true); + support = Enumerable.Range(0, world.Indices.Length / 3) + .Where(i => !Checkpoint(world.CollisionPolygons[i].MaterialName)) + .Select(i => new SupportTriangle(world.Vertices[world.Indices[i * 3]].Position, + world.Vertices[world.Indices[i * 3 + 1]].Position, world.Vertices[world.Indices[i * 3 + 2]].Position, + world.CollisionPolygons[i].ShapeId, world.CollisionPolygons[i].PolygonIndex)).ToArray(); + } + + public SupportResult Step(Vector3 position, Vector3 velocity, float radius, float factor, bool wasGrounded, float dt) + { + if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt)); + var previous = position; + velocity += RecoveredMotion.Gravity * dt; + // A capsule with height=diameter is a sphere. Floor polygons are handled + // by the separate original support query, not by this wall response. + var moved = walls.Move(position - Vector3.UnitY * radius, velocity * dt, radius, radius * 2); + position = moved.Position + Vector3.UnitY * radius; + if (moved.HitCeiling && velocity.Y > 0) velocity.Y = 0; + return OriginalBodySupport.Resolve(new(position, previous, velocity, Vector3.Zero, radius, factor), + wasGrounded, (start, end, twoSided) => OriginalBodySupport.Trace(support, start, end, twoSided)); + } + + private static bool Checkpoint(string? name) => name != null + && (name.Equals("cstart", StringComparison.OrdinalIgnoreCase) + || name.Length == 7 && name.StartsWith("ccheck", StringComparison.OrdinalIgnoreCase) && name[6] is >= '1' and <= '9'); +} diff --git a/src/GamePort/Game/PracticePrompt.cs b/src/GamePort/Game/PracticePrompt.cs new file mode 100644 index 0000000..ac6b5ea --- /dev/null +++ b/src/GamePort/Game/PracticePrompt.cs @@ -0,0 +1,46 @@ +using System.Numerics; + +namespace GamePort.Game; + +/// EXE404523..404D1E keyboard and pointer selection for PracticeYesNo. +public sealed class PracticePrompt +{ + public bool Active { get; private set; } + public int Mode { get; private set; } + public event Action? Chosen; + + public void Show(int mode) + { + if (mode is < 0 or > 3) throw new NotSupportedException("Practice mode is outside recovered VR04..VR01 mapping"); + if (Active) return; + Mode = mode; Active = true; + } + + public void Key(uint scancode, Vector2 pointer) + { + if (!Active) return; + if (scancode == 28) Choose(true); // Y. + else if (scancode == 17) Choose(false); // N. + else if (scancode is 40 or 88) Choose(Yes(pointer)); // Enter / keypad Enter. + } + + public void Click(Vector2 pointer) + { + if (!Active) return; + if (Yes(pointer)) Choose(true); + else if (pointer.X > 315 && pointer.X < 395 && pointer.Y > 240 && pointer.Y < 300) Choose(false); + } + + public static string Destination(int mode) => mode switch + { + 0 => "VR04.gam", 1 => "VR03.gam", 2 => "VR02.gam", 3 => "VR01.gam", + _ => throw new NotSupportedException("Unrecovered practice destination") + }; + + private void Choose(bool accepted) + { + Active = false; + Chosen?.Invoke(Mode, accepted); + } + private static bool Yes(Vector2 p) => p.X > 225 && p.X < 305 && p.Y > 240 && p.Y < 300; +} diff --git a/src/GamePort/Game/SceneCollision.cs b/src/GamePort/Game/SceneCollision.cs index 4f5167c..4b8306a 100644 --- a/src/GamePort/Game/SceneCollision.cs +++ b/src/GamePort/Game/SceneCollision.cs @@ -25,14 +25,22 @@ public sealed class SceneCollision public float DistanceSquared => Vector3.DistanceSquared(Capsule, Surface); } - public SceneCollision(Mesh mesh) + public SceneCollision(Mesh mesh, bool wallsAndCeilingsOnly = false) { if (mesh.Indices.Length % 3 != 0) throw new ArgumentException("Collision indices must be triangles", nameof(mesh)); + if (wallsAndCeilingsOnly && mesh.CollisionPolygons.Length != mesh.Indices.Length / 3) + throw new InvalidDataException("Original wall grid requires prepared source polygon normals"); var result = new List(); // Render visibility is not a proven collision mask. Original null-material // proxies remain present and block movement in this provisional policy. for (var i = 0; i < mesh.Indices.Length; i += 3) { + // EXE4798B3 registers only stored normal.Y<.7 in the wall/ceiling + // grid. Render normals and a recomputed cross product differ. + if (wallsAndCeilingsOnly && mesh.CollisionPolygons[i / 3].Normal.Y >= .7f) continue; + if (wallsAndCeilingsOnly && mesh.CollisionPolygons[i / 3].MaterialName is { } material + && (material.Equals("cstart", StringComparison.OrdinalIgnoreCase) + || material.Length == 7 && material.StartsWith("ccheck", StringComparison.OrdinalIgnoreCase) && material[6] is >= '1' and <= '9')) continue; if (mesh.Indices[i] >= mesh.Vertices.Length || mesh.Indices[i + 1] >= mesh.Vertices.Length || mesh.Indices[i + 2] >= mesh.Vertices.Length) throw new ArgumentException("Collision index outside vertex table", nameof(mesh)); diff --git a/src/GamePort/Game/SceneDirector.cs b/src/GamePort/Game/SceneDirector.cs new file mode 100644 index 0000000..f284a87 --- /dev/null +++ b/src/GamePort/Game/SceneDirector.cs @@ -0,0 +1,527 @@ +using System.Numerics; +using GamePort.Assets; + +namespace GamePort.Game; + +/// Mutable source-entity state for the reconstructed trigger/camera interpreter. +public sealed class DirectorActor +{ + public GamEntity? SourceGam { get; } + public string Tag { get; } + public string Kind { get; } + public bool ConstructorCreated => SourceGam is null; + public Vector3 Position { get; internal set; } + public Vector3 Rotation { get; internal set; } + public bool Visible { get; internal set; } + public bool Active { get; internal set; } + public string Animation { get; internal set; } = "STOP"; + public int AIstate { get; internal set; } + public float Speed { get; internal set; } + public string? Patrol { get; internal set; } + public int SpriteRevision { get; internal set; } + public bool SpritePlaying { get; internal set; } + + internal DirectorActor(GamEntity? source, string tag, string kind, Vector3 position) + { + SourceGam = source; Tag = tag; Kind = kind; Position = position; + Rotation = source?.Rotation ?? Vector3.Zero; + Visible = source?.Integer("InitiallyVisible", -1) != 0; + Active = source?.Integer("InitallyActive", source?.Integer("Activated", 1) ?? 1) != 0; + if (kind == "3PIC") Visible = Active; + AIstate = source?.Integer("AIState", kind == "3DOG" ? 4 : 0) ?? (kind == "3DOG" ? 4 : 0); + Speed = kind switch { "3CAR" => 200, "3DOG" => 1, _ => 0 }; // EXE413BCB /41C8FA. + if (kind == "3DOG") Animation = "none"; // Initial pose selection is not recovered; no fabricated STOP alias. + Patrol = source?.Text("PatrolPoint"); + SpritePlaying = (source?.Integer("Activated") ?? 0) != 0; + } +} + +public sealed record DirectorIssue(string Tag, string Kind, string Detail); + +/// +/// Recovered synchronous AI-trigger dispatch and audio-duration-driven CAM/MCA +/// sequence. See lab-progression.md. Actor physics/AI, sprites, inventory effects +/// and fades remain separate consumers; unsupported execution is reported. +/// +public sealed class SceneDirector +{ + private readonly GamLevel level; + private readonly TaskStates tasks; + private readonly Func soundDuration; + private readonly Dictionary entities = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary actors = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary activations = []; + private readonly Queue<(string Tag, string? Caller)> pending = []; + private readonly List issues = []; + private readonly HashSet reported = new(StringComparer.Ordinal); + private readonly HashSet patrolConsumers = new(StringComparer.OrdinalIgnoreCase); + private Shot? shot; + private bool draining, skipping; + private string? blockedNext, blockedCaller; + + private sealed class Shot(GamEntity source, int index, DirectorActor target, double duration) + { + public GamEntity Source { get; } = source; + public int Index { get; } = index; // -1 for a single CAM. + public DirectorActor Target { get; } = target; + public double Duration { get; } = duration; + public double Elapsed { get; set; } + } + + public List Actors { get; } = []; + public IReadOnlyList Issues => issues; + public bool Controlled => Equal(ControlledTag, level.Player?.Tag); + public string? ControlledTag { get; private set; } + public bool InventoryEnabled { get; private set; } = true; + public bool Blocked { get; private set; } + public bool Playing => shot is not null; + public string? CurrentTag => shot?.Source.Tag; + public int CurrentShot => shot?.Index ?? -1; + public Vector3? CameraEye { get; private set; } + public Vector3? CameraTarget { get; private set; } + public event Action? Speech; + public event Action? ActorChanged; + public event Action? Unsupported; + + public SceneDirector(GamLevel level, TaskStates tasks, Func soundDuration) + { + this.level = level; + this.tasks = tasks; + this.soundDuration = soundDuration; + foreach (var entity in level.Entities) + { + if (entity.Tag is not { Length: > 0 } tag) continue; + // Original tag lookup scans in object-list order and returns the first. + entities.TryAdd(tag, entity); + var actor = new DirectorActor(entity, tag, entity.Kind, entity.Position); + Actors.Add(actor); + actors.TryAdd(tag, actor); + } + // Jimmy creates Goddard in EXE423C98->41C810, independently of GAM. + // LV1B's explicit SITGODDARD command positions him at gstart before his + // first shot. This initial binding is a documented placement inference. + if (!actors.ContainsKey("C3DGODDARD") && entities.TryGetValue("gstart", out var goddardStart)) + { + var goddard = new DirectorActor(null, "C3DGODDARD", "3DOG", goddardStart.Position); + Actors.Add(goddard); + actors.Add(goddard.Tag, goddard); + } + ControlledTag = level.Player?.Tag; + foreach (var actor in Actors) ApplyTask(actor, tasks.Get(actor.SourceGam?.Text("TaskName"))); + tasks.Assigned += OnTaskAssigned; + } + + public void Begin(GamEntity start) + { + if (start.Kind != "STRT") throw new ArgumentException("Expected original STRT entity", nameof(start)); + shot = null; pending.Clear(); activations.Clear(); + Blocked = skipping = false; blockedNext = blockedCaller = null; + CameraEye = CameraTarget = null; + InventoryEnabled = true; + foreach (var actor in Actors) + { + if (actor.SourceGam is not { } source) continue; + var initial = new DirectorActor(source, actor.Tag, actor.Kind, source.Position); + actor.Position = initial.Position; actor.Rotation = initial.Rotation; + actor.Visible = initial.Visible; actor.Active = initial.Active; + actor.Animation = initial.Animation; actor.AIstate = initial.AIstate; + actor.Speed = initial.Speed; actor.Patrol = initial.Patrol; + actor.SpritePlaying = initial.SpritePlaying; actor.SpriteRevision++; + ApplyTask(actor, tasks.Get(source.Text("TaskName"))); + } + var trigger = start.Text("StartTrigger"); + ControlledTag = IsNone(trigger) ? level.Player?.Tag : null; // EXE4426B7. + if (!IsNone(trigger)) Trigger(trigger!, start.Tag); + } + + public void Trigger(string tag, string? callerTag = null) + { + if (tag.Length > 100) throw new ArgumentException("Trigger tag exceeds original field size", nameof(tag)); + pending.Enqueue((tag, callerTag)); + Drain(); + } + + /// + /// Port contact query: point against the source trigger radius. Original + /// collision callback selection/radius combination is not yet reproduced. + /// The actual AI trigger's actor, animation and task-child checks are retained. + /// + public void Touch(string activatorTag, Vector3 position) + { + if (!Finite(position)) throw new ArgumentOutOfRangeException(nameof(position)); + foreach (var entity in level.Entities) + { + if (entity.Kind != "3AIT" || entity.Integer("TouchActivated") == 0) continue; + var radius = entity.Number("Radius"); + if (radius < 0 || Vector3.DistanceSquared(position, entity.Position) > radius * radius) continue; + if (entity.Tag is { } tag) pending.Enqueue((tag, activatorTag)); + } + Drain(); + } + + public DirectorActor? FindActor(string tag) => actors.GetValueOrDefault(tag); + + public void RegisterPatrolConsumer(string tag) => patrolConsumers.Add(tag); + + public void SyncActor(string tag, Vector3 position, Vector3 rotation) + { + if (!Finite(position) || !Finite(rotation)) throw new ArgumentOutOfRangeException(nameof(position)); + if (!actors.TryGetValue(tag, out var actor)) return; + actor.Position = position; actor.Rotation = rotation; + if (shot is not null) UpdateCamera(shot); + } + + public void Step(float dt) + { + if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt)); + foreach (var actor in Actors) + if (actor.Kind == "3TRO") actor.Rotation = actor.Rotation with { Y = (actor.Rotation.Y + dt * 90) % 360 }; + var remaining = (double)dt; + for (var count = 0; count < 256 && shot is not null; count++) + { + var current = shot; + var untilEnd = Math.Max(0, current.Duration - current.Elapsed); + var consumed = Math.Min(remaining, untilEnd); + current.Elapsed += consumed; + remaining -= consumed; + UpdateCamera(current); + if (current.Elapsed + 1e-8 < current.Duration) return; + FinishShot(current); + if (remaining <= 0 && (shot is null || shot.Duration > 0)) return; + } + if (shot is not null && shot.Duration <= 0) + Block(shot.Source, "Zero-duration scene sequence exceeded bounded dispatch", shot.Source.Text("NextTrigger")); + } + + /// Escape/Space original chain skip: preserve AI/toggle actions and skip remaining speech/shots. + public void Skip() + { + skipping = true; + if (Blocked) + { + Blocked = false; + if (blockedNext is { } next) pending.Enqueue((next, blockedCaller)); + blockedNext = blockedCaller = null; + } + if (shot is { } current) + { + shot = null; + DeactivateAnimation(current); + if (current.Index >= 0) FinishMulti(current.Source); + else EnqueueNext(current.Source); + } + Drain(); + } + + private void Drain() + { + if (draining || Blocked) return; + draining = true; + var visited = new HashSet(StringComparer.OrdinalIgnoreCase); + try + { + for (var count = 0; pending.Count > 0 && !Blocked; count++) + { + var (tag, caller) = pending.Dequeue(); + if (IsNone(tag)) continue; + if (Equal(tag, "default")) { RestoreControl(); continue; } + if (count >= 256 || !visited.Add(tag)) + { + Report(tag, "cycle", "Synchronous trigger cycle or dispatch limit"); + pending.Clear(); Blocked = true; return; + } + if (!entities.TryGetValue(tag, out var entity)) + { + Report(tag, "missing", "Trigger target absent from original GAM"); + Blocked = true; return; + } + switch (entity.Kind) + { + case "3AIT": ExecuteAi(entity, caller); break; + case "3CAM": StartCamera(entity, -1); break; + case "3MCA": StartMulti(entity); break; + default: Block(entity, "Trigger class execution not recovered", entity.Text("NextTrigger")); break; + } + } + } + finally { draining = false; } + } + + private void ExecuteAi(GamEntity entity, string? caller) + { + var by = entity.Text("ActivateBy"); + var isA = entity.Text("IsA"); + var matchesActor = !IsNone(by) && Equal(by, caller); + if (!IsNone(isA)) + { + Report(entity.Tag!, entity.Kind, "IsA predicate requires original class hierarchy; trigger not executed"); + return; + } + if (!IsNone(by) && !matchesActor) return; + var byAnimation = entity.Text("ActivateByAnim"); + if (!IsNone(byAnimation) && (!actors.TryGetValue(caller ?? "", out var callerActor) + || !Equal(byAnimation, callerActor.Animation))) return; + var times = entity.Integer("TimesToTrigger", -1); + var number = activations.GetValueOrDefault(entity.Offset) + 1; + activations[entity.Offset] = number; + if (times != -1 && number > times) return; + SetControl(entity); + + var targetTag = entity.Text("AITarget"); + if (!IsNone(targetTag)) + { + if (!actors.TryGetValue(targetTag!, out var target)) + Report(entity.Tag!, entity.Kind, $"AI target {targetTag} absent"); + else + { + var hide = entity.Integer("AIHideObj", -1); + if (hide != -1) target.Visible = hide == 0; + var positionTag = entity.Text("AINewPos"); + if (!IsNone(positionTag)) + { + if (actors.TryGetValue(positionTag!, out var marker)) target.Position = marker.Position; + else Report(entity.Tag!, entity.Kind, $"AINewPos {positionTag} absent"); + } + var animation = entity.Text("AIAnim"); + if (!IsNone(animation)) target.Animation = animation!; + target.AIstate = entity.Integer("AIState", target.AIstate); + var speed = entity.Integer("AISpeed", -1); + if (speed != -1) target.Speed = speed; + var patrol = entity.Text("AIPatrol"); + if (!IsNone(patrol)) target.Patrol = patrol; + var yaw = entity.Number("AINewRotY", -1); + if (yaw != -1) target.Rotation = target.Rotation with { Y = yaw }; + ActorChanged?.Invoke(target); + if (target.AIstate == 3 && (target.Kind is "3DOG" or "3CAR") && !patrolConsumers.Contains(target.Tag)) + Report(target.Tag, target.Kind, "Patrol motion/arrival is not yet reconstructed; actor-state callback emitted"); + } + } + Toggle(entity); + var conditional = ConditionalChild(entity); + // EXE40CB43: the nearby teleport explanation advances the task before its camera chain. + if (Equal(entity.Tag, "teleportexplanation") && tasks.Get("SCENE") is 30 or 31) + tasks.SetExisting("SCENE", 35); + pending.Enqueue((conditional ?? entity.Text("NextTrigger") ?? "none", entity.Tag)); + } + + private string? ConditionalChild(GamEntity entity) + { + var state = tasks.Get(entity.Text("TaskName")); + for (var i = 0; i < 5; i++) + { + var desired = entity.Integer($"ActivateState{i}", -1); + var target = entity.Text($"ActivateObject{i}"); + if (desired != -1 && desired == state && !IsNone(target) && entities.ContainsKey(target!)) return target; + } + return null; + } + + private void StartMulti(GamEntity entity) + { + SetControl(entity); + Toggle(entity); + if (skipping) { FinishMulti(entity); return; } + StartCamera(entity, 0, applyCommon: false); + } + + private void StartCamera(GamEntity entity, int index, bool applyCommon = true) + { + if (applyCommon) { SetControl(entity); Toggle(entity); } + if (entity.Integer("DeactivateInv") != 0) InventoryEnabled = false; + if (skipping) + { + if (index >= 0) FinishMulti(entity); + else EnqueueNext(entity); + return; + } + var suffix = index < 0 ? "" : index.ToString(System.Globalization.CultureInfo.InvariantCulture); + var targetTag = entity.Text("CameraTarget" + suffix); + var sound = entity.Integer("SoundIndex" + suffix, -1); + if (index >= 8 || IsNone(targetTag) || sound == -1) + { + if (index >= 0) FinishMulti(entity); + else Block(entity, "CAM target/sound unavailable", entity.Text("NextTrigger")); + return; + } + if (!actors.TryGetValue(targetTag!, out var target)) + { + Block(entity, $"Camera target {targetTag} absent", entity.Text("NextTrigger")); + return; + } + var database = entity.Text("SoundDatabase") ?? "none"; + var duration = soundDuration(database, sound); + if (!double.IsFinite(duration) || duration < 0) + { + Block(entity, $"Missing original sound duration {database}:{sound}", entity.Text("NextTrigger")); + return; + } + var animation = entity.Text(index < 0 ? "TargetActAnim" : "TargetAnim" + suffix); + if (!IsNone(animation)) { target.Animation = animation!; ActorChanged?.Invoke(target); } + shot = new Shot(entity, index, target, duration); + UpdateCamera(shot); + Speech?.Invoke(database, sound); + } + + private void FinishShot(Shot current) + { + if (shot != current) return; + shot = null; + DeactivateAnimation(current); + if (current.Index < 0) EnqueueNext(current.Source); + else StartCamera(current.Source, current.Index + 1, applyCommon: false); + Drain(); + } + + private void DeactivateAnimation(Shot current) + { + var animation = current.Source.Text("TargetDeactAnim"); + if (!IsNone(animation)) + { + current.Target.Animation = animation!; + ActorChanged?.Invoke(current.Target); + } + } + + private void FinishMulti(GamEntity entity) + { + // MCA finisher4311F0 preserves 'none'/NULL semantics for PlayerControlled. + SetControl(entity); + EnqueueNext(entity); + } + + private void EnqueueNext(GamEntity entity) + { + pending.Enqueue((entity.Text("NextTrigger") ?? "none", entity.Tag)); + } + + private void UpdateCamera(Shot current) + { + var source = current.Source; + var target = current.Target; + var t = (float)current.Elapsed; + if (current.Index >= 0) + { + var suffix = current.Index.ToString(System.Globalization.CultureInfo.InvariantCulture); + var type = source.Integer("CameraType" + suffix); + var local = type switch + { + 1 => new Vector3(0, 140, MathF.Max(100, 300 - 15 * t)), + 2 => new Vector3(0, 240, MathF.Max(100, 500 - 35 * t)), + 3 => new Vector3(200, 240, MathF.Max(100, 700 - 55 * t)), + 4 => new Vector3(-200, 190, MathF.Max(100, 700 - 55 * t)), + _ => new Vector3(0, 40, 200), + }; + CameraEye = TransformLocal(target, local); + CameraTarget = target.Position + Vector3.UnitY * (source.Number("LookatVOffset" + suffix, 100) - 60); + return; + } + if (source.Integer("CameraType") == 2) + { + CameraEye = source.Position; + CameraTarget = target.Position; + return; + } + var minimum = source.Number("MinDist", 100); + var maximum = source.Number("MaxDist", 1000); + var distance = Math.Clamp(source.Number("InitialDist", 200) - source.Number("ZoomSpeed") * t, + MathF.Min(minimum, maximum), MathF.Max(minimum, maximum)); + var offset = new Vector3(source.Number("TargOffsetX"), source.Number("TargOffsetY"), source.Number("TargOffsetZ")); + if (source.Integer("ViewFromCamera") == 0) + { + CameraEye = TransformLocal(target, offset with { Z = distance }); + CameraTarget = target.Position + Vector3.UnitY * source.Number("LookVoffset"); + } + else + { + var point = TransformLocal(target, offset); + var direction = source.Position - point; + if (direction.LengthSquared() < .000001f) + { + Report(source.Tag!, source.Kind, "CAM eye coincides with target offset; original normalization undefined"); + CameraEye = source.Position; + } + else CameraEye = point + Vector3.Normalize(direction) * distance; + CameraTarget = point; + } + } + + private static Vector3 TransformLocal(DirectorActor target, Vector3 point) + { + // Original OMT Euler local-to-world routine472980; quantized modern + // sin/cos here retains the source angular grid, not x87 bit identity. + var (sx, cx) = LabSimulation.Trig(target.Rotation.X); + var (sy, cy) = LabSimulation.Trig(target.Rotation.Y); + var (sz, cz) = LabSimulation.Trig(target.Rotation.Z); + var x = point.X * cz - point.Y * sz; + var y = point.X * sz + point.Y * cz; + var z = point.Z; + var pitchedY = y * cx - z * sx; + var pitchedZ = y * sx + z * cx; + return target.Position + new Vector3(x * cy - pitchedZ * sy, pitchedY, x * sy + pitchedZ * cy); + } + + private void SetControl(GamEntity entity) + { + var control = entity.Text("PlayerControlled"); + if (IsNone(control)) return; + if (Equal(control, "NULL")) ControlledTag = null; + else if (actors.ContainsKey(control!)) ControlledTag = control; + else Report(entity.Tag!, entity.Kind, $"PlayerControlled target {control} absent"); + } + + private void Toggle(GamEntity entity) + { + var tag = entity.Text("ToggleObject"); + var toggle = entity.Integer("Toggle", -1); + if (toggle is not (0 or 1) || IsNone(tag)) return; + if (!actors.TryGetValue(tag!, out var actor)) { Report(entity.Tag!, entity.Kind, $"ToggleObject {tag} absent"); return; } + actor.Visible = actor.Active = toggle == 1; + if (actor.Kind == "3ANI") { actor.SpritePlaying = toggle == 1; actor.SpriteRevision++; } + ActorChanged?.Invoke(actor); + } + + private void RestoreControl() + { + shot = null; + ControlledTag = level.Player?.Tag; + InventoryEnabled = true; + CameraEye = CameraTarget = null; + skipping = false; + // Original DEFAULT invokes a Jimmy help/inventory callback at SCENE30; + // it does not assign a new task value or complete the lab. + } + + private void OnTaskAssigned(string name, int state) + { + foreach (var actor in Actors) + if (Equal(actor.SourceGam?.Text("TaskName"), name)) ApplyTask(actor, state); + } + + private void ApplyTask(DirectorActor actor, int state) + { + if (actor.SourceGam is not { } source) return; + // LOAD.RequiredLevel belongs to its RequiredTask contact gate, not the + // animated actor's TaskName activation contract. Applying the latter + // here disables the lab exit even when SCENE reaches60. + if (source.Kind == "LOAD") return; + var active = source.Kind == "3PIC" ? TaskActivation.Pickup(source, state) : TaskActivation.Animated(source, state); + if (active.HasValue) { actor.Active = actor.Visible = active.Value; ActorChanged?.Invoke(actor); } + } + + private void Block(GamEntity source, string detail, string? next) + { + shot = null; Blocked = true; + blockedNext = next; blockedCaller = source.Tag; + Report(source.Tag ?? "?", source.Kind, detail); + } + + private void Report(string tag, string kind, string detail) + { + if (!reported.Add(tag + "\0" + kind + "\0" + detail)) return; + issues.Add(new DirectorIssue(tag, kind, detail)); + Unsupported?.Invoke(tag, kind); + } + private static bool Equal(string? a, string? b) => a is not null && b is not null && string.Equals(a, b, StringComparison.OrdinalIgnoreCase); + private static bool IsNone(string? value) => string.IsNullOrEmpty(value) || Equal(value, "none"); + private static bool Finite(Vector3 p) => float.IsFinite(p.X) && float.IsFinite(p.Y) && float.IsFinite(p.Z); +} diff --git a/src/GamePort/Game/SceneInteractions.cs b/src/GamePort/Game/SceneInteractions.cs new file mode 100644 index 0000000..f7388c0 --- /dev/null +++ b/src/GamePort/Game/SceneInteractions.cs @@ -0,0 +1,240 @@ +using System.Numerics; +using GamePort.Assets; + +namespace GamePort.Game; + +public sealed record LevelTransition(string LevelFile, string StartPoint, float FadeTime, int FadeType); + +/// +/// Recovered star/trophy/lab jetpack contacts, Carl talk dispatch and LOAD gates. Uses source root spheres +/// with recovered lookup magnitude (x87 table identity/exclusions/box contacts pending). +/// Other pickup effects and general AI sensing remain explicit unsupported cases. +/// +public sealed class SceneInteractions +{ + private readonly SceneDirector director; + private readonly TaskStates tasks; + private readonly OriginalSave initial; + private readonly string levelCode; + private readonly int[] itemStates; + private readonly HashSet contacts = []; + private readonly HashSet unsupported = []; + public int Score { get; private set; } + public float Energy { get; private set; } + public int CurrentObjective { get; private set; } + public string ReturnLevel { get; private set; } + public string ReturnStart { get; private set; } + public SceneInventory Inventory { get; } + public IReadOnlyCollection Unsupported => unsupported; + public event Action? Collected; + public event Action? Transition; + public event Action? SoundEffect; + public event Action? PracticeRequested; + public event Action? CheckpointCaptured; + public event Action? ConversationStarted; + public event Action? ObjectiveChanged; + + public SceneInteractions(SceneDirector director, TaskStates tasks, OriginalSave save, string? levelCode = null) + { + this.director = director; this.tasks = tasks; initial = save; + this.levelCode = levelCode ?? save.LevelCode; + Inventory = new SceneInventory(save.InventoryStates); + itemStates = save.ItemStates.ToArray(); Score = save.Score; + Energy = save.PlayerValue; + CurrentObjective = save.OtherCounter; + ReturnLevel = save.ReturnLevel; ReturnStart = save.ReturnStart; + tasks.Assigned += OnTaskAssigned; + Reset(); + } + public void UpdateEnergy(float energy) + { + if (!float.IsFinite(energy)) throw new ArgumentOutOfRangeException(nameof(energy)); + Energy = energy; + } + + public OriginalSave Snapshot() => initial with { Score = Score, PlayerValue = Energy, ItemStates = itemStates.ToArray(), + InventoryStates = Inventory.Snapshot(), Tasks = tasks.Snapshot(), OtherCounter = CurrentObjective, + ReturnLevel = ReturnLevel, ReturnStart = ReturnStart }; + + public void SetReturnContext(string levelFile, string start) + { + if (levelFile.Length > 100 || start.Length > 100 || !levelFile.EndsWith(".gam", StringComparison.OrdinalIgnoreCase) + || levelFile.Contains('/') || levelFile.Contains('\\')) throw new ArgumentException("Invalid original return level/start"); + ReturnLevel = levelFile; ReturnStart = start; + } + + /// Call after SceneDirector.Begin, including a scene reset. + public void Reset() + { + contacts.Clear(); + HideCollected(); + ApplyCarlTask(); + } + + public void HideCollected() + { + foreach (var actor in director.Actors) + if (actor.SourceGam is { Kind: "3PIC" } source && source.Integer("PickupIndex", -1) is var id + && id > 0 && id < itemStates.Length && itemStates[id] != 0) actor.Active = actor.Visible = false; + } + + public void Update(Vector3 activePlayerRoot, float playerRadius = 60) + { + if (!float.IsFinite(activePlayerRoot.X + activePlayerRoot.Y + activePlayerRoot.Z) + || !float.IsFinite(playerRadius) || playerRadius < 0) throw new ArgumentOutOfRangeException(nameof(activePlayerRoot)); + if (!director.Controlled) return; + HideCollected(); + foreach (var actor in director.Actors) + { + if (!director.Controlled) break; + if (actor.SourceGam is not { } source || source.Kind is not ("3PIC" or "3TRO" or "LOAD" or "3CAR")) continue; + // C3DFriend update41B972..988 calls the talk dispatcher every update + // in state0, even when a prior contact found no matching TalkTrigger. + if (source.Kind == "3CAR" && actor.Active && actor.AIstate == 0) + { + TryBeginCarlTalk(actor, source); + if (!director.Controlled) break; + } + // Carl InitObject413E2F..45 sets radius100 and support factor0.75. + var radius = playerRadius + (source.Kind == "3TRO" ? 20 : source.Kind == "3CAR" ? 100 : source.Number("Radius")); + var overlaps = actor.Active && OriginalBodySupport.QuickMagnitude(activePlayerRoot - actor.Position) < radius; + if (!overlaps) { contacts.Remove(source.Offset); continue; } + if (!contacts.Add(source.Offset)) continue; + switch (source.Kind) + { + case "3PIC": CollectPickup(actor, source, activePlayerRoot); break; + case "3CAR": + //40A44C..45C/40A676..68D: target contact in state6 sets0. + var player = director.Actors.FirstOrDefault(a => a.Kind == "3JIM"); + if (actor.AIstate == 6 && Equal(source.Text("TargetName"), player?.Tag)) + { + actor.AIstate = 0; + TryBeginCarlTalk(actor, source); + } + break; + case "3TRO": + Score = Math.Max(0, unchecked(Score + 300)); + actor.Active = actor.Visible = false; + SoundEffect?.Invoke(230); + Collected?.Invoke(source, 300); + break; + case "LOAD": + if (!TaskActivation.Load(source, tasks)) break; + var destination = source.Text("LevelName") ?? "none"; + var start = source.Text("StartPoint") ?? "none"; + if (string.Equals(destination, "RETURN", StringComparison.OrdinalIgnoreCase)) + { destination = ReturnLevel; start = ReturnStart; } + if (string.Equals(destination, "none", StringComparison.OrdinalIgnoreCase)) + { unsupported.Add("RETURN has no stored destination"); break; } + Transition?.Invoke(new(destination, start, source.Number("FadeTime"), source.Integer("FadeType"))); + break; + } + } + } + + private void CollectPickup(DirectorActor actor, GamEntity source, Vector3 playerRoot) + { + var id = source.Integer("PickupIndex", -1); + // The source tag is SHRINKRAY; original objective art120 calls this + // pickup the jet pack, matching group0/item3 and powered-jump ownership. + var jetpack = Equal(source.Tag, "SHRINKRAY"); + var ordinaryStar = id is >= 3000 and < 4000 && source.Integer("PointValue") == 5; + if (id is <= 0 or >= OriginalSave.ItemCount || !(ordinaryStar || jetpack && source.Integer("PointValue") == 50) + || source.Integer("PIC_NUMBER", -1) != -1 + || source.Integer("PickedUpIndex", -1) != -1 || source.Integer("RequiredPicNum", -1) != -1) + { unsupported.Add($"Pickup {source.Tag}@0x{source.Offset:X}: inventory/special effect not reconstructed"); return; } + if (itemStates[id] != 0) return; + itemStates[id] = 1; // EXE435E11..31: ordinary acquired state, hide and disable. + actor.Active = actor.Visible = false; + //435FCB invokes the special hook before the positive PointValue award. + if (jetpack && tasks.Get("SCENE") == 35) + { + //436603..67E: Jimmy checkpoint capture42AF00, task35->50, group0 + //item3 state1, practice prompt0, then gadget selection3. The checkpoint + //event does not assign the still-unidentified TSK StoredVector. + CheckpointCaptured?.Invoke(playerRoot); + tasks.SetExisting("SCENE", 50); + Inventory.SetState(0, 3, 1); + PracticeRequested?.Invoke(0); + Inventory.SelectGadget(3); + } + var points = source.Integer("PointValue"); + Score = Math.Max(0, unchecked(Score + points)); + var sound = source.Integer("SoundIndex", -1); + if (sound >= 0) SoundEffect?.Invoke(sound); + Collected?.Invoke(source, points); + var next = source.Text("NextTrigger"); + if (!string.IsNullOrEmpty(next) && !string.Equals(next, "none", StringComparison.OrdinalIgnoreCase)) + director.Trigger(next, source.Tag); + } + + private void TryBeginCarlTalk(DirectorActor actor, GamEntity source) + { + var state = tasks.Get(source.Text("TaskName")); + for (var i = 0; i < 5; i++) + { + var tag = source.Text("TalkTrigger" + i); + var required = source.Integer("TalkState" + i, -1); + if (required == -1 || required != state && required != -2 || string.IsNullOrEmpty(tag) + || Equal(tag, "none") || director.FindActor(tag) is null) continue; + //41B7B0 calls derived slot180 BEFORE dispatching the selected object. + //Carl413E50 calls base41B810 (+100) then changes SCENE milestones. + Score = Math.Max(0, unchecked(Score + 100)); + var scene = tasks.Get("SCENE"); + var next = scene switch { 50 => 60, 65 => 70, 270 => 280, _ => scene }; + if (next != scene) tasks.SetExisting("SCENE", next); + director.Trigger(tag, tag); //Original target receives itself as caller. + actor.AIstate = 9; + ConversationStarted?.Invoke(actor, tag); + return; + } + } + + private void OnTaskAssigned(string name, int value) + { + HideCollected(); + if (Equal(name, "SCENE")) + { + //45F990 jump tables ->406F50: clear the transient objective flags, + //select this objective and set its flag1; TSK writes selector4F8194. + var objective = ObjectiveForScene(value); + if (objective != 0) { CurrentObjective = objective; ObjectiveChanged?.Invoke(objective); } + ApplyCarlTask(); + } + } + + private void ApplyCarlTask() + { + //Carl's override413F30 follows generic activation; LV1B branch414068. + //Other levels' custom visibility/position policies are not ported here. + if (levelCode != "LV1B") return; + var state = tasks.Get("SCENE"); + foreach (var actor in director.Actors.Where(a => a.Kind == "3CAR" && Equal(a.SourceGam?.Text("TaskName"), "SCENE"))) + { + if (state is < 0 or > 60) { actor.Visible = actor.Active = false; continue; } + if (state > 30 && director.FindActor("CARLESC3") is { } marker) + { + actor.AIstate = 6; + actor.Position = marker.Position; + } + //At60 the override leaves the generic activation result unchanged. + if (state < 60) actor.Active = actor.Visible = true; + } + } + + private static bool Equal(string? a, string? b) => a is not null && b is not null + && string.Equals(a, b, StringComparison.OrdinalIgnoreCase); + + public static int ObjectiveForScene(int scene) => scene switch + { + 35 => 1, 50 => 2, 60 => 3, 70 => 4, 90 => 5, 100 => 6, 108 => 7, + 140 or 141 => 8, 160 => 9, 162 => 10, 168 => 11, 178 => 12, + 200 => 13, 205 => 14, 210 => 15, 220 => 16, 230 => 17, + 250 => 18, 260 => 19, 270 => 20, 280 => 21, 290 => 22, + 300 => 23, 310 => 24, 320 => 25, 330 => 26, 340 => 27, + 350 => 28, 360 => 29, 380 => 30, 390 => 31, 400 => 32, + 410 => 33, 420 => 34, 430 => 35, 460 => 36, 470 => 37, + 480 => 38, 500 => 39, 510 => 40, 520 => 41, 540 => 42, 550 => 43, + _ => 0, + }; +} diff --git a/src/GamePort/Game/SceneInventory.cs b/src/GamePort/Game/SceneInventory.cs new file mode 100644 index 0000000..7b48d9c --- /dev/null +++ b/src/GamePort/Game/SceneInventory.cs @@ -0,0 +1,43 @@ +using GamePort.Assets; + +namespace GamePort.Game; + +/// +/// The two inventory-state groups serialized by the original TSK writer. +/// Preserves unknown existing values; this is not a complete inventory UI or +/// implementation of the separate 29-item consumable-count group. +/// +public sealed class SceneInventory +{ + private readonly int[] states; + public int SelectedGadget { get; private set; } = -1; + public event Action? GadgetSelected; + + public SceneInventory(IEnumerable savedStates) + { + states = savedStates.ToArray(); + if (states.Length != OriginalSave.InventoryCount) + throw new ArgumentException("Expected the original 19 inventory states", nameof(savedStates)); + } + + public int State(int group, int item) => states[Offset(group, item)]; + + public void SetState(int group, int item, int state) => states[Offset(group, item)] = state; + + public void SelectGadget(int item) + { + if (item != -1 && (item is < 0 or >= 9 || State(0, item) == 0)) + throw new ArgumentOutOfRangeException(nameof(item), "Gadget is outside the recovered group or unavailable"); + SelectedGadget = item; + GadgetSelected?.Invoke(item); + } + + public int[] Snapshot() => states.ToArray(); + + private static int Offset(int group, int item) => group switch + { + 0 when item is >= 0 and < 9 => item, + 1 when item is >= 0 and < 10 => 9 + item, + _ => throw new ArgumentOutOfRangeException(nameof(item), "Only the two serialized inventory groups are recovered here"), + }; +} diff --git a/src/GamePort/Game/SceneMechanisms.cs b/src/GamePort/Game/SceneMechanisms.cs new file mode 100644 index 0000000..d9911ea --- /dev/null +++ b/src/GamePort/Game/SceneMechanisms.cs @@ -0,0 +1,176 @@ +using System.Numerics; + +namespace GamePort.Game; + +/// +/// Recovered player-contact button and vertical-door state machines. Contact +/// broadphase uses the recovered lookup magnitude; moving-object collision and material pulses +/// are separate, still incomplete consumers. See analysis/buttons-doors.md. +/// +public sealed class SceneMechanisms +{ + private sealed class Button(DirectorActor actor) + { + public DirectorActor Actor = actor; + public bool Available; + public bool Down; + public float Cooldown; + } + private sealed class Door(DirectorActor actor) + { + public DirectorActor Actor = actor; + public Vector3 Origin = actor.SourceGam!.Position; + public bool Closed; + public float Remaining; + public float OpenElapsed; + public bool Looping; + public float Duration = actor.SourceGam!.Number("DoorSpeed", 1); + public float OpenTime = actor.SourceGam!.Number("OpenTime", 3); + public float Amount = actor.SourceGam!.Number("OpenAmount", 500); + } + private readonly SceneDirector director; + private readonly List