Implement Bubble controller, sprite and VR01 body behavior

This commit is contained in:
UnixNight committed 2026-11-02 16:57:54 -05:00
1 parent 9ea578492d
commit 1ae5f4251c
51 files changed
+2810 -53

No files matched your search

+4 -3
View File
@@ -46,9 +46,10 @@ changes. Current gadget controls/resources/primary-fire findings belong in
docs/gameplay/. Distinguish static recovery, implementation, port tests and original
runtime evidence. Main owns integration/runtime; gadget investigators have
exclusive named files, not shared directories.
Latest continuation: docs/gameplay/invisible-implementation.md. Invisible's timed
effect, original meter, companion/cutscene cleanup and shared energy warnings are
implemented; Bubble source is recorded in bubble.md pending movementmode2/body.
Latest continuation: docs/gameplay/bubble-implementation.md. Bubble's mode2,
original sprite and boundedVR01 source body/floor state are implemented and tested;
Invisible, ray/jetpack and shared energy state remain integrated. Other gadgets
and broader collision/camera/retained-helper behavior remain separate gates.
All current investigator ownership has returned to primary. Keep full enemy AI,
suppression globals, render state and original/native Windows verification distinct.
+8 -2
View File
@@ -16,11 +16,11 @@ collision and shared camera state remain incomplete.
The user requested this change after milestone35a2a66/0272f7b. Gadget work uses
original controls, state and assets; the collision checkpoint remains available
to resume after this gameplay work.
VR04 now uses recovered static body response/support/friction with original-code
VR04 and the bounded VR01 Bubble tutorial now use recovered static body response/support/friction with original-code
numeric references. Lab/outside retain the capsule until special contacts and
dynamic collision are recovered; see [body implementation](docs/checkpoint/collision-body-implementation.md).
**Current milestone: gadget screen, shrink ray and timed Invisible device.**
**Current milestone: Bubble, Invisible, shrink ray and their gadget screen.**
Tab/Space selects owned gadgets and their practice levels; the default device
fires on Enter/Ctrl/left mouse and supports actual VR04 soldier shrink/restore
with original morphs and score effects. Invisible uses the recovered recharge,
@@ -30,6 +30,8 @@ See [gadget implementation](docs/gameplay/gadgets-implementation.md) for recover
rules, modern policies and the verification boundary.
The [Invisible continuation](docs/gameplay/invisible-implementation.md) records
the later implementation and shared energy-warning sounds.
The [Bubble continuation](docs/gameplay/bubble-implementation.md) adds its source
controller, original sprite, automatic/high bounces and VR01 floor behavior.
The runtime includes recovered camera/speech triggers, moving props, Carl/Goddard
patrol logic, pickups, objectives, the practice prompt, VR04 powered jumping and
@@ -74,6 +76,10 @@ F1→Player also grants/selects Invisible, unequips it, and shows its timers and
targetability state. After selecting Invisible, allow7 seconds to recharge, then
fire without jump to activate for7 seconds at a fixed2-energy cost (tutorials
are exempt). Its last3 seconds flash before normal rendering returns.
F1→Player can also Give/Select Bubble. **Up or primary fire** accelerates, arrows
steer, and holding jump makes higher bounces. Tab/Space first unequips it; the
original sprite fades afterward. VR01 uses source body/floor rules; lab/outside
collision remains provisional.
**F2** toggles a compact live debug overlay without pausing play. It shows frame
timing, position/velocity, movement, control/force state, tasks, camera/clipping
+9
View File
@@ -5,6 +5,15 @@ SDL3 for platform windowing, input and audio. Linux x64 and Windows x64 are
equally required. Source is `src/GamePort/`; root executable csproj allows
`dotnet build` and `dotnet run` from GamePort. No runtime network dependencies.
Bubble adds separate `BubbleMotion` input/apply, `BubbleEffect` owned clock and
`BubbleVisuals` original canvas. LabSimulation keeps body factor, current maximum,
movement mode and captured sprite root distinct. The source static factory also
admits VR01; its retained support ID feeds bounded `Vr01FloorState` before the
controller, independently of current support/control. `PlayerAppearance` stores
material writes from Invisible alpha/blend requests and late lava RGBA, preserving
source phase order instead of rebuilding one effect's alpha every render.
See gameplay/bubble-implementation.md for coverage and remaining gates.
The Invisible continuation adds `InvisibleGadget` in Jimmy's post-movement wrapper
phase, separate from input identity. `PlayerSceneBinding` supplies raw-any-control,
handles equip/companion flags and receives a named-Jimmy cleanup event from CAM/
+14
View File
@@ -3,6 +3,20 @@
Compilation, native runtime, original behavior and full feature completion are
separate evidence categories. **The game is not fully reconstructed/playable yet.**
Bubble (2026-11-02): original mode2 controller, sprite/flags/pulse/fade, controlled
drain, loop/boing ownership, cleanup650 and boundedVR01 source body/floor111 are
integrated. Six isolated copied-original body references match managed output.
Independent review and13 integration/11 motion/8 visual groups pass. Full suite:
202 Python+2 HUD, all managed checks,31 main GPU completions and17 Vulkan material
checks, zero enabled validation errors; SDL dummy lifecycle and539 originals pass.
Native Linux GTX1070/private Xvfb1920×1080 passes real Ctrl/Left/Shift/Tab and all
eight rendered phases. The fixture advances306 extra normal player ticks; this
is not original cadence/manual completion/full hazard or original visual parity.
Lab/outside capsule, fixed render bridge, generic camera/Euler scheduling, other
damage flags, mouse/analog and retained-helper lifetime remain explicit limits.
New package results follow the clean milestone; native Windows remains unverified.
See gameplay/bubble-implementation.md and artifacts/bubble-implementation/.
Invisible continuation (2026-11-02): recovered mode2 timers, fixed energy cost,
alpha/blend flashing, original meter and companion/cutscene cleanup are integrated.
Shared source energy warning latch/audio now serves ray/jetpack/Invisible. Fifteen
+2
View File
@@ -33,6 +33,8 @@ player, staged jetpack states0/1/4 with a separate Apply row, energy refill,
Give/Select Invisible and Unequip Current Gadget. Invisible obeys its source
energy/recharge gates; a grant is not instant activation. The header shows
remaining time, recharge and targetability. Full enemy sensing is not implied.
Give/Select Bubble uses the implemented mode2 controller, while Unequip starts
its original fade. Diagnostics show Bubble phase and source radius/factor.
State0 means unowned,1 enabled and4 disabled by the level. The full availability
action re-enables the matching VR practice gadget and applies LV1B restrictions
on gadgets1/7 after the common prefix. Other level-specific tails remain incomplete. These controls expose
+10
View File
@@ -209,3 +209,13 @@
Energy scalar and warning latch share one session owner; raw saved/refill
assignment is not a helper-driven warning rearm. Full enemy sensing,
suppression globals, graphics options and canvas alignment remain explicit.
38. **Integrate Bubble's controller and body together.** Mode2 is persistent and
has fire throttle, its own turn cap and direct300/900 supported bounce; it
must not enter the ordinary550/jetpack table. Pass radius160/factor.415 to the
tested static body, preserve queued work/root and restore source650 maximum
on cleanup. VR01's floor111 has a retained-material callback even in air, so
implement that bounded policy with original bypass/debounce/material ordering.
Original Canv1 remains an independently updated sprite with full RGBA fade,
not invented sphere geometry. Keep the render bridge, generic camera/Euler,
other damage states and retained helper lifetime explicit. Bubble practice
precedes live equip; menu gating reads raw mode, not display selection.
+183
View File
@@ -0,0 +1,183 @@
# Bubble body, VR01 registration and support material
2026-11-02. Independent investigation; no modern runtime files changed. The
ordinary body can accept Bubble's radius/factor and actual VR01 static geometry,
provided the separate retained support-material callback is preserved. VR01 has
no special wall374 polygons; it does have a consequential lava floor111.
This does not reopen dynamic actors or all special-contact policies.
## Evidence and scope
EXE SHA256 `f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
OMT DLL SHA256 `3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943`.
`tools/binary/bubble_body.py` PE-maps eight bounded body hashes,27 fixed sites,
ten virtual targets and the DLL texture-pointer publication, then independently
decodes VR01/VR04. Text VA minus400000 gives EXE raw offset here; DLL source
100013B5 maps raw13B5. Full facts/hashes are in
`artifacts/bubble/body/source-contract.json`; raw disassemblies sit beside it.
Relevant reused REA Evidence, with complete reports already retained:
| Source | Evidence | Retained location |
| --- | --- | --- |
|479D20 integration|`ev_5439072b32ae9f9208795ad2b07bc524e2407b46da487072fb3dfd8c10e7c4b0`|artifacts/collision-response/rea-response/|
|40E050 animated base|`ev_03a109302788b85597e253293bbcb535c4080732e41cc828bb33d01d2b2da09a`|artifacts/uncontrolled-phases/rea/|
|462520 support/material bridge|`ev_f0a2e1fd465472295b272f2fdbfb6be4651aeb8c35d90dc2ca02a495ed359edd`|same|
|OMT material read10001490|`ev_f592b625a60ec683a17627d671c47d78d722eb39d5eb407744d53a283ee2586d`|artifacts/collision-integration/contacts/rea-material-identity/03.json|
|Bubble equip/cleanup|[Bubble source report](bubble.md)|artifacts/bubble/rea-effect/|
New REA/Ghidra factor-setter4711E0 Evidence
`ev_5d2495e741932d9eb7b5a687d31b4fcc7a398d890797247ddf262677f6cf490f`
is saved/exported/closed under `artifacts/bubble/body/rea-ipc/`.
It confirms authored2C is stored and forwarded through254 to live154; the
setter changes no root.424600/44E030/4252E0 were not recognized as procedures;
their VA queries fell through to unmapped file-offset errors. These are saved
provider gaps, not successful pseudocode. Their contracts use reviewed bounded
instructions and fixed guards. The first `rea/` attempt failed because the host
sandbox denied the Unix socket; the successful local IPC retry is separate.
## Body parameters and root alignment — recovered and probed
Equip429049/429058 sets authored/live radius160 and factorfloat32(.415).
Cleanup42809C/4280AB sets60/float32(1.265). Supported wrapper42469B..4246E9
restores **live** radius160 for raw mode0,60 otherwise; it does not set factor,
reposition root or add a landing callback. It is outside the controller raw-owner
gate. The existing OriginalBodyPhysics.Step already accepts radius and factor;
the live caller must pass the current factor instead of fixed1.265.
Support47B890 uses radius×factor for final root offset. Bubble's66.4 is lower
than ordinary75.9 despite the larger collision sphere. Prevent-lowering208=true
rejects downward root correction. Consequently equip must not immediately move
the root downward, and cleanup must not preserve Bubble66.4 as the ordinary floor
offset. Inherited Jimmy landing37C→472970 is a return. Support publishes shape34C
and polygon33C through plain setters4725C0/472580; these perform no special callback.
Six additional copied-original body fixtures ran atdtfloat32(1/60), gravity−800,
friction.8, suppression.5, ordinary integration/support/world flags, no dynamic
pass and a synthetic flat triangle. Source479D20/support instructions ran inside
a copied generated32bit process; synthetic virtual methods supplied body state,
no-op contacts and a landing observer. The game entry point, real Jimmy, source
input/audio/scripts and actual VR01 geometry did not execute.
| Fixture | Original observed rootY | Original observed Vy/support |
| --- | ---: | --- |
|160/.415 at66.4|66.4000015|0/true|
|160/.415 at26|66.4000015|0/true|
|Equip160/.415 from ordinary75.9|75.6777802|−13.333334/false; no forced lowering|
|Cleanup60/1.265 from66.4|75.9000015|0/true|
|160/.415 at66.4, priorVy300|71.1777802|286.666656/false|
|160/.415 at66.4, priorVy900|81.1777802|886.666687/false|
Data, binary/source/header hashes and scope are in
`artifacts/bubble/body/original-body-results.json`; full output is
`probe/wine.log`. `--probe-source` generates the fixture source from the existing
body harness. Compile with `i686-w64-mingw32-gcc -O0 -Wall -Wextra -Itools/binary
-Iartifacts/bubble/body artifacts/bubble/body/bubble-body-probe.c -o
artifacts/bubble/body/probe.exe -lm`; generate the guarded header through
body_step_evidence.py. Run only through reference_capture.py with its copied game
directory and no-network/no-original-mount namespace. Initial6second Wine prefix
setup did not complete; the next prefix failed kernel32 loading. Both logs remain.
A separate copy of the prior working prefix completed the probe with exit0.
The constant75.9 ActorRoot/feet/render bridge remains a **modern approximation**.
Changing that bridge to radius×factor on every equip would introduce an immediate
root/render movement not justified by either setters or this probe. Preserve the
documented visual boundary and test source physics roots independently.
## Actual VR01 static filter and material coverage — closed for this archive
455EF0 constructor binds complete game table4CD740 at455F5A and registers
FourCCVR01 at455FA8. Its134→475CD0 returnsfalse, so the shared loader imposes
no extra game polygon exclusion. Shared NC44DD64, checkpoint4791C7 and
game4791D9 filters match the existing route adapter. Source shape-ID enumeration
is valid here: the archive has only contiguous shapeID0, VRRoom. All polygons
have three corners. No NC shape or checkpoint material is used.
| Archive | Shapes | Registered/all | Wall grid | Used material IDs |
| --- | --- | ---: | ---: | --- |
|VR01.omt|0 VRRoom,60 vertices|80|60|0,1,2,3,4,111|
|VR04.omt|0 Box01,336 vertices|508|420|0,2,3,4,6|
VR01 polygons48..53 alone use111 (`112lava`), all stored normalY=.991954..1.
They never register in the wall grid (requiresY<.7), so cannot dispatch370/374
through static traversal. The other eligible wall374 IDs0..4 are ordinary.
VR01 source GAM contains16 entities including one3ROC, two3PHO and a3TRO, no3SOL;
absence of soldiers does not prove all actor pairs ineligible. Dynamic actor
collision remains excluded exactly as in the bounded VR04 body implementation.
## Retained support polygon and floor111 — distinct callback
Support's no-op landing does **not** prove the floor harmless. Current support
is cleared at the next body start, but stored polygon338 is not cleared there.
462520 checks gameplay475CA0, integration210 and nonnull stored polygon338.
It reads polygon+4 material and material+80 **texture pointer**, then calls game130
with actor/material/texture/dt.44E030 requires nonnull actor and texture, resolves
material+0C→chunk+8 signed resourceID, and checks actor FourCC3JIM.
There is no218-grounded test in the110..119 branch. Preserve the last successful
support polygon until a later successful support overwrites it, even in flight.
The actual VR01 used materials all link Canv resources;111 links Canv6. This
nonnull texture gate is not the material payload's trailing3. OMT's exported
set_texture100013A0 writes the texture at+80,100013BB.
Order:424C34 calls437940;43796A calls40E050;40E0EB calls462520;46258F invokes
VR01 game130→44E030. This is before controller ownership437A2B, before applying
mode2 bounce and after the wrapper ceiling/downward queries. It remains eligible
when Jimmy is uncontrolled, subject to the common gameplay/integration gates.
For actualVR01 IDs0..4/111, the bounded source policy is:
- Enter110..119 at44E170: if complete1E02 isfalse, invoke198→42AB00 then set1E02.
42AB00 requestsSFX39 unconditionally and190 only if raw mode!=0. Bubble keeps39.
- Invoke164→42A8D0 every eligible base tick. It returns immediately if complete
1DEC isalreadytrue or raw mode==0. Otherwise set1DEC=true, sharedtimer1DE8=0,
call42A920(−5),42ADC0(−5), then complete1E0→425120. Energy retains common VR01
exemption; score still clamps after−5.425120 cancels only movementmode1.
- Leaving110..119 clears1E02 through19C→472970(no-op). Leaving does not clear1DEC.
Cleanup while still over retained111 therefore starts damage on the next base
tick without replaying entrySFX39/190 if the entry latch is stilltrue.
-111 chooses game sound selector35; IDs0..4 choose5. Selector change invokes
complete1E4→42AEC0, which only retargets a pre-existing A44 loop handle, stops it
and starts the new resource repeating. Full movement-footstep ownership is open.
This policy justifies an explicit VR01 floor111 handler, not every special contact
on LV1B/LEV1. The source ordinary wall callback remains unchanged for Bubble;
do not add generic horizontal reflection. Controller bounce/held-jump/SFX106 is
recovered separately in [bubble-motion.md](bubble-motion.md).
## Lava flash phase and rendering boundary
Late wrapper424C88 invokes4255C0. With other damage states1DED/1E03 false,
4257D6 addsdt to shared1DE8 while1DEC=true.4257E8 compares the retained x87 sum
before4257EE stores thefloat timer; the later pulse also consumes the retained
sum. Strict sum>4 (49D5E8) clears1DEC and writeswhite; at exactly4 it still flashes.
A sum just above4 can clear1DEC while the persisted timer rounds to4. Otherwise
`pulse=(sin(timer*20)+1)*.5`. It directly writes complete5C0 material+4C..58 as
RGBA(pulse,1,pulse,1). Raw mode0 does not stop a previously active flash.
42A8D0 does not call114 or another linked-material alpha setter.
1DED has earlier priority/return;1E03 precedes lava and shares the timer, possibly
addingdt before lava addsdt again. Those other damage policies remain outside
this slice. Invisible114 writes all linked materials, while this late source
write targets the one5C0 material. A port must retain explicit material-write
ordering or document the bounded renderer approximation. A fresh per-frame
Invisible RGBA snapshot cannot silently erase a retained lava write.
## Validation and recommendation
Five Python groups pass in `artifacts/bubble/body/tests.log`: original guards,
actual archive registration/texture/material coverage, Bubble entry bypass,
cleanup damage/strict4second flash including compare-before-store, and base callback gates. Six copied original
numeric cases pass as above. No modern build, port gameplay or whole original
gameplay was run by this investigator. Confidence is high for guarded source
order, actual archive counts and the isolated flatfloor body outputs; whole actor
pair eligibility, all damage-state interactions and original visual equivalence
remain open.
Minimum bounded integration: admitVR01 in the source static factory after these
registration checks; pass radius160/factor.415 and restore60/1.265 without direct
root correction; retain support polygon/material independently ofcurrent support;
run the explicit111 phase before controlled movement plus its late flash clock.
Keep dynamic/special walls parked, and preserve the75.9 render bridge explicitly.
If the111 pipeline is omitted, limit claims to raw0 Bubble body and keep ordinary
VR01/postcleanup floor behavior marked incomplete. A mode0 radius alone never
establishes full Bubble support/collision fidelity.
@@ -0,0 +1,55 @@
# Bubble implementation review
2026-11-02. Independent source review of the current integration against
`bubble.md`, `bubble-motion.md`, `bubble-body.md`, `bubble-rendering.md` and
their recorded source contracts. Read-only inspection of runtime/test files;
this report is the reviewer's only edited file. No new binary recovery or
original-game execution was performed. No blocking implementation mismatch was
found within the declared bounded profile.
## Checked contracts
| Contract / source evidence | Current implementation |
| --- | --- |
| Equip429049..429085 and cleanup428037..4280BB | `LabSimulation.GadgetMode` sets raw0/movement2, radius160/factor.415/max1350, preserves root/queued body state, and rejects existing effect flags. Cleanup restores60/1.265/mode0 and source max650, calls Stop and separately clears expansion. |
| Input426084 then drain426264..42629F and placement4262A5..4263DA | `StepInput` updates steering/camera, adjusts shared energy, performs depletion cleanup, then captures BubbleRoot from the resulting camera eye even when that cleanup changed mode. Rendering consumes this stored root. |
| Input/Jimmy/Bubble partial order | Fresh `Step` schedules input before the player and owned effect afterward; retained-order policy places input after the effect. Effect time advances without raw input ownership. Retained helper lifetime is still an explicit inference. |
| Mode2 apply4387E0 and input439900 | Fire supplies throttle while ordinary beam/jetpack dispatch is suppressed. Supported input decay and later scalar halving remain separate. Bounce assigns liveY300/900 after XZ composition, publishes the post-half scalar, retains mode2 and requests106 only for held jump. |
| Supported wrapper42469B..4246E9 | Supported Bubble retains radius160 and STOP; equip/cleanup do not directly recenter the actor root. The fixed75.9 render bridge remains a stated modern boundary. |
| Body479D20/support47B890 | Current radius/factor reach `OriginalBodyPhysics`. Production admission remains VR01/VR04; lab/outside retain their prior capsule adapter. No dynamic actor or generic special wall policy is newly implied. |
| Retained polygon338 →462520→44E030 | Successful source support updates retained material independently of current support. Actual VR01 profile0..4/111 runs before the controller gate, including airborne/uncontrolled ticks; Bubble skips the specific damage callback but preserves entry39 and the latch. Cleanup permits damage on the retained111 without replaying entry sounds. |
| Late lava4257D6..4257EE | Float timer persistence is separated from the unrounded strict>4 comparison and pulse input. `Vr01FloorState.Step` runs after Invisible's material requests; stored `PlayerAppearance` prevents a fresh Invisible snapshot from erasing late RGBA. |
| Source practice428F61..428FCA | Bubble practice selection updates display selection and requests the scene without starting live body/effect setup. `GadgetScreen` and cleanup use raw mode separately from display selection, including rejected Invisible equip. |
| Sprite410AE0/410CA0/410D00 | Independent flags, active/expanding/collapsing priority, strict fade boundaries, full RGBA, retained dimensions and original Canv1 pixels remain intact in effect/visual components. |
## Verification
Reviewer reran from `GamePort/`, with the local SDK environment and
`--no-restore`:
- `dotnet run --project tests/GamePort.BubbleTests`:13 groups passed, including
six copied-original numeric body references and actual VR01 retained111.
- `dotnet run --project tests/GamePort.BubbleMotionTests`:11 groups passed.
- `dotnet run --project tests/GamePort.BubbleVisualTests`:8 groups passed.
These are managed source-projection/integration checks. They do not establish
whole original-game behavior, GPU appearance, sound audibility or native Windows
runtime compatibility. Full-suite, packaging and presentation results belong to
the primary integration report.
## Remaining boundaries and useful follow-up
The declared `TracksBubbleOrientation` profile preserves the prior yaw-only
baseline before first Bubble use. Its destination handoff follows the recovered
conditional ground/ordinary-air contracts; shared generic interpolation enable,
dirty flags and transform scheduling remain open. The source camera adapter,
mouse/analog extensions, complete retained-helper lifetime, other damage flags,
footstep-loop ownership, dynamic pairs and broader special contacts likewise
remain open. No universal hazard immunity or original visual parity follows from
this slice.
Optional future regression strengthening: assert the exact captured-root formula
against the post-input camera eye, and explicitly compare fresh versus retained
input scheduling at an effect start/cleanup boundary. Current code follows those
orders, but existing frozen-root/independent-clock assertions cover only part of
that contract. No extra runtime code or new tests were added during this review.
+100
View File
@@ -0,0 +1,100 @@
# Bubble gameplay integration
2026-11-02. User-directed gadget continuation after1897dd2/9ea5784. The broader
collision checkpoint remains parked. This adds Bubble's original sprite/controller
and a bounded source static-body/floor profile in its actual VR01 tutorial.
## Coverage map
| Original system | Current implementation | Evidence / remaining boundary |
| --- | --- | --- |
| Item0/raw0, movement2 | Separate inventory/display/body/controller state; failed transitions retain raw−1 | bubble.md, bubble-motion.md; full inventory/equip policies for other gadgets remain open |
| Radius160/factor.415, cleanup60/1.265 | Source body parameters; no direct root recenter; cleanup maximum650 | bubble-body.md; six isolated copied-original body references match managed results |
|439900 input/4387E0 apply | Fire/Up throttle, turn±50, supported input decay, XZ before scalar halving, direct300/900 bounce | Keyboard subset; mouse/analog and full scheduler remain open |
| Action/orientation | Supported STOP, retained unsupported pose, recovered tilt targets/math | Bubble orientation bridge; complete generic Euler/dirty/camera ownership remains open |
| Bubble410AE0/410CA0/410D00 | Independent visual clock; exact flag priority/strict fade;240 pulse; full RGBA | bubble-rendering.md; default additive branch, modern world-billboard basis/depth policy |
| RetainedSprites.omt Canv1 | Exact146×146 pixels, bounded exporter/manifest/runtime hash check | No invented sphere or Jimmy scaling; original renderer orientation/UV padding remains open |
| Controlled drain/sound |−.5dt via shared energy owner; loop2; held supported106; cleanup stops loop | Tutorial helper immunity; raw-null input can stop drain without stopping visual clock |
| VR01 floor111 | Retained support identity, entry39/optional190, raw0 damage bypass,−5 score/energy and strict4-second flash | Other damage flags and full footstep-loop ownership remain open |
| Material write order | Stored PlayerAppearance receives Invisible alpha/blend requests and later lava RGBA | Current single-atlas material; complete linked models/material/render states remain open |
| Practice/cutscene/debug | Bubble practice precedes live equip; actual raw-mode menu gate; named Jimmy cleanup; F1 grant and diagnostics | Owned helper lifetime across ordinary loads and native Windows/original whole-game comparison remain open |
Source hashes, VAs/file offsets, structures, byte guards and REA Evidence are in
[bubble.md](bubble.md), [motion](bubble-motion.md), [body](bubble-body.md) and
[rendering](bubble-rendering.md). Complete exports and closed snapshots stay in
artifacts/bubble*/. Copied-original execution is limited to the isolated body
routine with synthetic virtuals, not the game entry point or original gameplay.
## Runtime ownership and boundaries
LabSimulation owns BubbleEffect, its captured world root, radius/factor/current
maximum and mode2 motion. Input uses source steering/camera before drain/placement;
depletion cleans the mode but still captures the final sprite root. Fresh input
precedes Jimmy; the effect clock runs after Jimmy before retained-input policy.
Fresh callback partial order is source-supported. Complete retained helper
survival/initialization remains unresolved, so retained-helper parity is not claimed.
The supported wrapper selects STOP and radius160. Mode2 bypasses normal550 jump/
jetpack state changes and remains2 through landing. Apply preserves incoming liveY
when unsupported. On support, held jump sets liveY900 and requests106; released
jump composes XZ, then halves the published scalar and sets liveY300 without sound.
Acceleration and pending impulse are not cleared on equip/apply. Cleanup restores
radius60/factor1.265/movement0/current maximum650 and begins the independent fade.
SourceA20=.5 cleanup write has no closed consumer; no guessed countdown is added.
Source static response is enabled for VR01 in addition to VR04. Actual VR01's
80 polygons/60 wall entries have only ordinary wall materials; its six111 polygons
are support surfaces, not wall374. All used original materials have linked textures.
The base callback consumes retained support material even while currently airborne
or uncontrolled, before controller movement. Ordinary floors clear entry state;
Bubble raw0 prevents new lava damage but does not erase an existing flash.
Tutorial exemption skips energy loss, not score loss. The late flash writes RGBA
and preserves blend-enable/factors, correctly retaining its interaction with
Invisible's material requests. Other damage flags and dynamic pairs remain out
of this bounded profile. Missing material is skipped; texture-link eligibility
is source-verified for these actual VR01 IDs, not a general textureless-material
implementation for other scenes.
The existing fixed75.9 root-to-feet/render bridge remains explicit: Bubble physical
support is66.4 and equip does not force a downward root correction. Lab/outside
continue using their provisional capsule/dynamic adapter; this is not a claim of
source Bubble collision in those scenes. Shared camera targets/smoothing/clipping
retain existing approximation gates, including known Bubble follow differences.
TracksBubbleOrientation preserves the earlier yaw-only baseline until Bubble first
needs pitch/roll. It then uses recovered target/easing/full-forward math and retains
normal cleanup handoff: accepted ground direction restores target pitch/roll0,
no input does not invent a reset, and normal air targets0/−turn. Exact generic Euler
update enable/phase remains separate. Modern reset clears this bridge. Source
logical root and original visual pivot are not conflated.
Bubble practice selection records the display item but skips live equip before
requesting VR01, matching the source early practice branch. Failed live selection
can leave a display item with raw−1; GadgetScreen now reads the actual raw mode.
Named-Jimmy CAM/MCA cleanup uses the earlier recovered DeactivateInv path. Modern
F3/Stop Motion releases Bubble and lets its owned fade finish; noclip still bypasses
body/contact/energy actions. Reset/new scene clears the port-owned effect; exact
retained original helper fade across loads remains open.
## Verification and continuation
Thirteen focused integration groups cover six copied-body numeric references,
queued work/root preservation,300/900 bounces and mode persistence, independent
clock/drain, depletion/selection/audio, transition rejection, ray suppression,
actual111 retained-floor behavior, strict flash, stored material order, practice
and raw/display gates, cutscene cleanup and modern flight fade. Eleven motion
and eight effect/visual groups are separate. Source projection checks do not
claim original execution. The initial synthetic test floor had visible winding;
corrected to source winding before matching the original references.
The eight-frame smoke uses actual VR01/PHONEBOOTH, source input/body/effect paths
and extra ordinary player ticks between rendered phases. It does not relocate
actors or directly mutate timers/velocities. Ctrl/Left and Shift exercise throttle,
steering and an actual supported900 bounce/SFX106; Tab cleans, then full RGBA fade
and hidden state are captured. Extra ticks and verification results are logged
explicitly in artifacts/bubble-implementation/. This is an accelerated port
fixture, not original cadence, manual tutorial completion or full-game comparison.
Complete integration, native input and package results are recorded in progress.md
when verified. Next gadget work must retain the documented body, camera, material,
input and helper-lifetime boundaries rather than assuming universal immunity.
+242
View File
@@ -0,0 +1,242 @@
# Bubble movement mode2
2026-11-02. Completes the static movement/input/bounce contract needed after
[Bubble equip/effect](bubble.md), with a pure C# arithmetic component. This
investigator ran no original gameplay. Source projections and component tests
remain separate from live port integration and original runtime comparison.
EXE SHA-256 `f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
All VAs below PE-map to file offsets VA−400000 in these original ranges.
`tools/binary/bubble_motion.py` verifies identity,11 complete bounded span hashes,
17 decisive instruction sites,8 virtual bindings and11 constants. Generated
`artifacts/bubble-motion/source-contract.json` records bytes, offsets and hashes.
## REA and source coverage
Local REA6.8.0/Ghidra12.1.4 used generated
`artifacts/uncontrolled-phases/rea/Neutron.exe`. Complete replies, Evidence bundle
and closed snapshot are under `artifacts/bubble-motion/rea-native/`:
| Routine | Evidence |
| --- | --- |
|438A60 dispatch|`ev_e645423e5ad809add30e5c0c5893df7ffda0b885988f9cf438d2d2b117502c56`,02.json|
|437940 frame|`ev_de7097867d129a4232318e667e9496c6868cdb1da4b37a1f3304c94b0b101677`,03.json|
|429A00 refresh148|`ev_0028e3f28c5aed508fab954fe8da6170690efa742614dab2044408ddd0062180`,06.json|
4387E0,439900,42A720,4378D0 numeric VA queries did not return pseudocode: the
profile failed to match a procedure and then interpreted the number as an
unmapped file offset. Corrected file-offset selectors387E0,39900,2A720,378D0 and
72B10 are retained separately under `rea-offsets/`: all explicitly report that
no procedure matches the identifier. That session exported its complete empty
Evidence bundle and closed/snapshotted. These are provider coverage gaps.
The first sandboxed batch (`rea-movement/`) encountered the known Unix-socket
`Operation not permitted` host restriction. Its worker was interrupted and its
owned session closed/snapshotted; it contains zero successful Evidence. This was
not a target execution or analysis-completeness success. An explicitly allowed
local static invocation resolved IPC without configuration changes.
Supplementary fixed-range objdump source is saved as frame.asm,input.asm,
callback.asm,pose.asm,transform.asm. Unsupported decompiler routines are recovered
from these guarded instructions/virtual bindings, not invented REA successes.
Profile digest is `e1ad533d4cc0333c2136fe0894217de2d61feea098240326e78633f9e4ddcbf9`.
## Owners, dispatch and phases
Jimmy complete object has game interface+C0; complete vtable4A3BDC and game
vtable4A373C. Input438A60/frame437940 receive interface;439900/4387E0 receive
complete object. Relevant complete fields:
| Offset | Meaning |
| --- | --- |
|6BC/6C0/6C4/6C8|Per-input increment30 / decay35 / current maximum / scalar speed|
|6D4/6D8|Turn rate / copied apply turn rate|
|6E4/6E5/6E6|Forward/backward/keyboard turn flags|
|7C4|Movement mode, not equipped raw gadget|
|7EC/7F0|Forward/backward destination pitch; apply writes−10/+10 every call|
Game2BC→471F10 gets live body velocity,2C4→471F40 sets it; game38C→472B10
rotates a local vector by current Euler. These are separate from pending impulse
2CC and acceleration. Complete128→439900 input;13C→4387E0 Bubble apply;
154→42A720 landing hook;158→4378D0 jump held;15C→42A7A0 fire held.
437940 calls40E050 before control identity/suppression/menu checks. Only afterward
437A49..437A79 dispatches mode2 directly to13C. Mode2 bypasses every ordinary
ground/air mode0/1 landing reset and jetpack jump-state table. After13C returns,
437C22..437C2D publishes controller scalar to game26C body speed. Landing keeps
movementmode2. No new radius, jump state, pending impulse or acceleration write
occurs in4387E0; do not clear those on equip/apply without another source owner.
Prior queued impulse/acceleration may therefore survive equip until another body
phase replaces them. Generic gravity/support behavior belongs to the body report.
426030 input first checks407060 false,475CA0 true, nonnull controlled5099E4,
4F8430 false and interface1D2D false. Its order is:
1.426084 calls438A60; modes1/2 share439900 (438B60 fall-through438B6D).
This changes steering, destination Euler and camera eye before Bubble placement.
2.426098 calls complete188→429D00. Raw Bubble0 fails that handler's raw7 guard
at429DBB, returns false42A652 and does not consume the callback.
3.Unsupported Bubble skips jetpack input at4260D3; supported input passes the
existing grounded path (including any pre-existing fall-impact flag handling).
4.426264 tests movementmode2, drains−.5dt and calls cleanup178 if energy<=0.
5.Even if cleanup switched mode0,4262A5 still positions Bubble from **the current
camera eye after439900**, using the formula already recovered in bubble.md.
Shared later menu/fire phases follow. Beam suppression does not suppress the
steering use of the fire predicate.
## Input439900
Keyboard subset, in source order:
| Rule | Exact source behavior |
| --- | --- |
|Turn|Left precedes Right; ±100dt. Release moves toward0 by100dt, clamped crossing. Mode2 caps±50 at439CB2..439CFB, ordinary air caps±30. Turning adds no speed.|
|Throttle|Up **or held primary fire in mode2** sets6E4; adds30 per call when below max, capped at current6C4=1350. Fire predicate is15C, not jump158.|
|Coast|Without throttle, speed>max×float.909090936 subtracts17.5; otherwise retained.|
|Supported decay|439BA2..439BED: if grounded and speed>0 subtract17.5, with **no clamp crossing0**; if grounded and speed<=0 set0. Applies even with throttle.|
|Brake|Down sets6E5. Positive speed subtracts35 if supported,17.5 otherwise, clamped to0. Negative speed adds35, clamped to0. Does not start reverse.|
|Destination Euler|For mode2 set(−10,currentYaw,−.25×turn) with throttle;(+10,currentYaw,−.25×turn) with brake; otherwise(0,currentYaw,−.25×turn). Forward takes priority over backward.|
Example source composition while supported: speed100+Up→130−17.5=112.5 in input;
later released-jump apply computes XZ from112.5, then publishes56.25. These two
grounded reductions have distinct owners and must not be collapsed into one.
At small positive speed5 the supported input decay yields−12.5; next supported
input zeroes it. This intermediate sign is a source fact, not a clamp omission.
Mouse/analog extensions are also statically bounded:46A460 supplies signed16
mouse axes. Nonzero horizontal mouse overrides keyboard turn and adds mouseX×dt
to turn; absent mouse, analogX<−.5 selects left, analogX>.5 selects right. Vertical
rate is mouseY/dt. Up, analogY>.5, rate>40 or mode2 fire selects throttle; fixed30
is used for keyboard/analog/fire, otherwise the positive rate is added. Down,
analogY<−.5 or rate<−40 selects brake. Strict inequalities are at439A97..439AE6
and439BF5..439C1D. Projections deliberately accept only keyboard flags; no mouse
or analog runtime implementation is claimed here. Zero dt division is not modeled
as safe input; actual frame contract is0<dt<1.
## Apply4387E0 and supported bounces
Every apply writes7EC=−10 and7F0=+10. It reads **incoming live body velocity**.
Only when its magnitude is nonzero does it copy turn6D4→6D8, add yaw+=turn×dt
through game334, and compute the side term:
```
sideSpeed = turn * (1-friction) * speed * float(1/55)
```
Zero incoming velocity skips direct yaw and produces sideSpeed0, but still
constructs forward velocity. Friction getter game248 supplies the existing.8;
factor.415 is a different body property. Unlike ground apply there is no extra
dt in this side speed. Source yaw uses degree-to-index float45.5111122,
truncate47F940 and mask3FFF, then the16384-entry float sine/cosine tables.
472B10 transforms local(0,0,speed), producing
`(-sin(yaw)*cos(pitch)*speed, sin(pitch)*speed, cos(yaw)*cos(pitch)*speed)`.
Roll has no effect for this particular local vector.438950..438976 uses only
transformed X/Z plus the yaw-only side vector and preserves incoming velocityY.
Pitch therefore changes horizontal forward magnitude, **not** vertical velocity.
Full transform source is guarded; host continuous trig in the projection is an
explicit precision approximation. The existing destination Euler interpolator
43A420 uses4.5/sec for pitch/roll and3.7/sec for wrapped yaw; this investigation
does not re-claim all its enable/dirty/base-transform phase ownership.
After composing XZ,43899A calls grounded218. If false, return. If true:
-Call complete154→42A720, which loadsA14 and jumps472970.472970 is a single RET;
it has no landing-effect mutation in this shipped EXE.
-Call complete158→4378D0 current jump-held predicate. It reads the same five
source jump inputs (50993A,509865,509848,509898,509AC5). Its raw6 exception
requires fire+support; raw Bubble0 has no extra denial.
-Held jump: directly set live velocityY900, retaining freshly composed XZ;
play SFX106 (`bubble_boing`) at4389F8. No edge latch: each supported apply can
invoke this sound/velocity write. Scalar speed is retained.
-Released jump: **after XZ composition**, halve scalar6C8 and directly set live
velocityY300. There is no SFX106 in this path. The reduced scalar is then
published by437C22, while current live XZ still represents the pre-half scalar.
These are automatic repeated bounces, not ordinary550 queued jump impulses.
Movementmode2 persists after both branches; ordinary jetpack JumpState/held-clock
logic is not called. Unsupported apply preserves liveY and the mode.
The Jimmy wrapper separately tests support42469B. For raw Bubble0 it restores
live radius160 and directly requests completeE0("STOP",1) at4246CD..4246D4.
The string is4ED040. Unsupported wrapper makes no action request at this site.
4387E0 and439900 contain no JUMP/FLY/RUN selection. Equip's refresh148→429A00
only stops A44 sound; it does not reset Euler or select a flying animation. Retain
these proven boundaries instead of inventing a Bubble flight pose.
## Camera dependency and verification limits
439900 retains shared camera destination calls120/384 and scalar16C→43B820.
Mode2 branch439F4D..43A03A scales horizontal follow by1.8×dt×that scalar.
Vertical follow uses1.5 outside the close-height branch; when
abs(truncate(rootY−eyeY))<=800 and rootY+20<=eyeY, its scale is.8 when
abs(truncate(deltaY−eyeY))>550, else.2. That second expression uses the existing
target-minus-eye delta before subtracting eyeY; do not simplify it into a more
plausible height expression. Shared complete851 overrides all axes with.1dt.
Exact scalar16C, destination geometry and native camera clipping retain their
separate existing camera gates. Sprite placement order after this handler is
closed even when that modern camera adapter remains approximate.
Ten Python groups pass (`artifacts/bubble-motion/tests.log`): original span/
binding/constants guards; fire throttle; turn/pose priorities; supported input
reduction and negative crossing; coast/brake; pitch-forward/liveY preservation;
direct900/300 bounce, sound and scalar/XZ ordering; zero-velocity yaw gate and
bounded inputs. These are static/projection checks, not original runtime probes.
`src/GamePort/Game/BubbleMotion.cs` implements the keyboard input and apply
component using the port's quantized `LabSimulation.Trig` for current pitch/yaw.
Its public results are `BubbleSteering(Speed,TurnRate,TargetPitch,TargetRoll)` and
`BubbleApply(Velocity,Yaw,Speed,Boing)`; methods are `StepInput` and `StepApply`.
Eleven C# numeric/bounds groups pass in `artifacts/bubble-motion/csharp-tests.log`,
including112.5 XZ versus56.25 publication and quantized pitch cosine. Run with
`dotnet run --project tests/GamePort.BubbleMotionTests --no-restore` after local
restore. It changes no normal-air component and performs no body integration,
impulse, acceleration, gadget lifetime, sprite, sound playback or mode writes.
Primary owns live C# integration and its port checks. Remaining broader gates are
original/native Windows gameplay comparison, shared base/rotation/camera state,
full mouse/analog integration and dynamic/special collision coverage; source body
radius/factor/support is coordinated in bubble-body.md. No universal immunity or
entire-game completion is implied.
## Cleanup Euler handoff and A20 search boundary
Follow-up2026-11-02. Cleanup428037..4280CC writes Jimmy completeA20=.5 at428045;
it contains no Euler or destination-Euler setter. Do not interpret.5 as an
upright timer without a recovered consumer. Source constructor4226CF initializes
A20=0; another gadget cleanup42821A writes.5. A complete raw DWORD search of EXE
`.text` VA401000, raw length573440, finds six little-endian `200A0000` occurrences:
4226D1,428047,42821C are the displacements of those three MOV writes;45CFE3,
45D024,45D035 are unrelated PUSH immediates. A direct objdump operand search for
completeA20 and game960 found no read. This is a bounded negative search:
derived pointers, bulk access or other interface aliases have not been ruled out;
the consumer remains **unknown**, not proven absent or dead. The helper's
`handoff` block guards the complete search boundary and six supporting spans.
Normal ground438BC0 does provide a source destination handoff, conditional on
accepted steering. ESI initializes0 at438F66. Right4391BB, Left439239,
Forward4392BA and accepted backward4393D5/4393EE set it nonzero. At43951E, if ESI
remains0, execution skips **all** destination setters to4395CF. Thus no-input
ground behavior preserves the prior Bubble target, including pitch/roll.
For accepted steering, each destination setter43957C,439599,4395C9 passes
**pitch0 and roll0**, retaining its separately computed destination yaw.
Ordinary keyboard Left/Right/Forward/Backward all reach this handoff when their
direction is accepted. Backward specifically has the prior438F9A..438FBB gate:
raw−1 or3 with fire held rejects reverse, so Backward+Fire without another
accepted direction need not produce ESI. Raw6 and other special-gadget gates
must retain their own boundaries.
Normal air mode1 always reaches439D81..439E2B and requests destination
`(pitch0,currentYaw,roll−turn)`; Bubble mode2 instead requests its±10 pitch and
−.25turn roll described above. Normal air release eventually reduces turn to0,
so its requested roll also becomes0. This is an input destination update, not
an immediate Euler reset. Shared43A420's active branch interpolates pitch and
roll error×dt×double4.5, yaw error×dt×double3.7 (with angle wrap and dirty flags).
No cleanup-specific A20 ownership is visible in that routine. This follow-up
does not newly close all scheduling/enable/transform ownership for that shared
interpolator or require an invented blend during cleanup.
REA queries43A420 and438BC0 in `artifacts/bubble-motion/rea-upright/` did not
match recognized procedures; their numeric VA requests then returned the
provider's unmapped-file-offset fallback diagnostics. Complete failures, empty
Evidence export and closed snapshot are retained. Supporting conclusions use
the guarded disassembly `normal-input-tail.asm`, `normal-apply.asm` and
`rotation.asm`. Two added Python groups guard A20's bounded search and the
conditional ground/normal-air destination handoff; C# BubbleMotion was unchanged.
+140
View File
@@ -0,0 +1,140 @@
# Bubble sprite implementation and rendering boundary
2026-11-02. Implements the owned visual component and original resource export.
Equip/body/input integration belongs to the primary runtime change. This report
establishes source recovery, asset identity and managed checks; it does not claim
original Bubble execution, exact original sprite orientation or native Windows
runtime verification. Originals remain read only, with539 unchanged hashes.
## Source and additional REA evidence
[bubble.md](bubble.md) retains the authoritative410840/410AE0/410CA0/410D00
contract, source spans, virtual bindings and REA limitations. EXE SHA256 is
`f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8`.
Additional local Ghidra12.1.4 queries used the same generated copy, exported
complete Evidence and closed/snapshotted under
`artifacts/bubble/rea-rendering-ipc/`:
| Procedure | Evidence ID | Observation |
| --- | --- | --- |
|4352F0 sprite base |`ev_7ea79d719ffb701f10a497f5790384aa56801d970a34ea7ecd4152052ac8f8df` |Calls463F10; sets complete+C8 game interface; temporarily sets flagC4 bit1. |
|4645F0 InitSpriteProperties |`ev_ab13438ec345f10472d10965048c34d31654e6d9303d729df98b65aa92d37a1e` |Writes AC/B0 supplied size, WORDC4=1, alignmentBC/C0=3, blend6/7. Graphics flag true writes RGBA(.9,.9,.9,1). |
|464210 preparation |`ev_4d39cc1aaad564de60bb801c08dfeb740d52e507227e630de9b0570e3e1bc43d` |Calls458910, forwards root/Euler to virtual setters, calls479A40; does not recover camera-facing drawing. |
The initial sandbox attempt is retained in `rea-rendering/`; Ghidra imported
successfully but could not bind its local Unix socket (`Operation not permitted`).
The allowed local IPC retry above succeeded. That initial batch supplies no
successful decompilation Evidence; no original code was executed in either.
Supplementary objdump output and independently mapped source-span hashes are in
`artifacts/bubble/*-rendering.asm` and `rendering-spans.json`. End VAs are exclusive:
| VA range | File offset / bytes | SHA256 |
| --- | --- | --- |
|4352F0..4353BF |352F0 /207 |`ee18deb9d0492ee3d921e99d56edea9eb11fc4b28bdbc171ee398a6628a41834` |
|4645F0..4646B8 |645F0 /200 |`1e666182de97533be5e917b5763957ce148bceb831b05061df19ccd89d3bae28` |
|464210..46429F |64210 /143 |`a99be3694789b6b6284b7e171eec0f2f26b59eef6a366265646bf6c8cbd92000` |
Constructor410978 supplies200 to4645F0 before overriding blend to6/1. Start
changes destination to1 or7, with no color reset. The optional conventional
graphics branch therefore starts with(.9,.9,.9,1) before its first fade update;
the default additive branch retains white. Active conventional rendering writes
(1,1,1,.5), while default additive rendering retains the previous RGBA.
Assembly410AEC..410AF2 adds dt and stores a float timer without popping the x87
sum. The expansion comparison410B95 and collapse subtraction/comparison410C12..
410C1E use that unrounded sum. `BubbleEffect.Step` retains a double addition for
those boundaries while storing `Timer` as float. The active pulse reloads stored
Timer at410B4C. A managed test covers Timer rounding to1 while the strict source
comparison has already crossed1. `Math.Sin` is a numeric projection; x87 fsin
bit parity and whole-game timing remain unverified.
## Callback ordering
Jimmy42232C constructs Bubble410840; its410892 call enters4352F0, whose435341
call enters463F10. The independently established chain in
[lab-registry.md](../checkpoint/lab-registry.md) continues463F6C complete+C8 →
4586F0 →46FBE0 → tail insertion. Together with the owned effect slot3C4→410AE0,
this supports fresh-game **input → Jimmy → Bubble update** as a partial order,
with other registered helpers allowed between them. The owned fire registers
earlier during Jimmy's base construction. The source registry, not source60Hz,
establishes that relative order.
Retained Bubble survival, teardown flags and update eligibility have not been
independently traced here. Reusing the same owned component across ordinary
Jimmy retention, and scheduling Jimmy → Bubble → newly appended game input,
remains an integration inference until that helper lifecycle is closed. The
modern fixed-step cadence is a separate port policy. Do not gate visual time on
raw input ownership merely because placement/drain happen in controlled input.
## Assets and exported format
`tools/extractors/bubble_resources.py` resolves the archive case-insensitively,
validates its complete hash, unique Canv1 metadata, payload and decoded pixels
before writing. It rejects outputs in/above originals and preexisting output
file symlinks. Export contains no generated sphere or recolored image:
```bash
python3 tools/extractors/bubble_resources.py ../Original \
--output artifacts/extracted/bubble
```
`bubble.json` schema1 contains `source`, archive `sourceSha256` and exactly one
`textures` record with id/name/width/height/path/png/sourceOffset/sourceBytes/
sourceSha256/rgbaSha256. `canvas_1.rgba` and `canvas_1.png` retain the original
146×146 image, including5492 alpha0 and15824 alpha255 texels.
- Archive SHA256: `b584ffa4a38f4bc809b3ea8f4321e0c08f2719e22df41a3fb4cd143ed89b3bef`.
- Payload offset17FCE/66322 bytes, SHA256: `9b6cdce95bd408fa1dc806d30520df65971f25d1663ab8da4ca6bf41380805ec`.
- Decoded RGBA SHA256: `a3a678c47c1ce94946b1136560a84f3ef86c6884b981256a9fbff62fe8a988e4`.
## Implemented renderer and explicit policies
`BubbleEffect` owns independent Active/Expanding/Collapsing/Visible flags, Timer,
full Vector4 Color and dimensions. `Start()` only sets expansion/visibility and
resets Timer. `Stop()` is the original leaf and deliberately preserves expansion;
Jimmy cleanup must additionally call `ClearExpansion()`. Active beats expansion,
which beats collapse. Fade does not change size; the first active invocation
changes200×200 to240×(240+sin(timer*10)*30), retaining the last pulse size during
collapse. Exactly1 remains expanding; exactly zero fade remains collapsing and
visible. A subsequent negative fade hides it. `Reset()` reconstructs initial
owned visual state rather than pretending to be the original Stop leaf.
`BubbleVisuals(Mesh combined, string preparedRoot)` loads `bubble/bubble.json`,
bounds its manifest/pixel sizes, validates the original pixel hash and appends
four vertices/six indices. It preserves existing draws/textures and collision
metadata. `Update(destination,effect,root,eye,target)` receives the already
captured source BubbleRoot; it applies no extra Jimmy scale or root offset.
RGB multiplies all four vertex colors; alpha goes through MeshDraw.Opacity.
Default blend is SRC_ALPHA/ONE; optional graphics mode uses
SRC_ALPHA/ONE_MINUS_SRC_ALPHA. Current Vulkan blended world draws test existing
opaque depth without writing depth.
The quad is centered on root and uses the same camera-facing basis as the
existing scene sprite adapter: direction=normalize(target−eye), right from
worldUp×direction, up=direction×right, with deterministic degenerate-camera
fallbacks. Width/height are complete world-space edge lengths; UVs cover the
complete original image. **This basis, centered interpretation, modern UV0..1,
filtering/alpha-cutout behavior and depth-write policy remain modern rendering
boundaries.** Alignment3/3 is recovered, but complete original engine alignment
scheduling, local-axis orientation, camera roll, render-state ownership and
zero-length original placement normalization are not closed. The result must
not be described as original visual parity without comparison.
## Validation
- Five Python checks pass: exact archive/resource/decoded PNG identity, output
separation, child symlink protection and rejection before writing on bad
archive/dimensions/pixels.
- Eight managed effect/visual groups pass: strict boundaries and full RGBA,
pulse/graphics branches, Stop priority/cleanup, unrounded fade comparison,
independent clocks/reset, original quad/material/metadata, camera degeneracy
and malformed/path-traversing/altered resource rejection.
- Main `dotnet build --no-restore` passes with zero errors; cached NU1900
vulnerability-feed warning is unrelated to this change. All539 original hashes
verify unchanged. Logs: `artifacts/bubble/visual-validation/`.
Commands: `python3 -m unittest discover -s tests -p test_bubble_resources.py -v`
and `source scripts/env.sh; dotnet run --project tests/GamePort.BubbleVisualTests`.
Managed/asset checks and compilation do not establish GPU rendering, original
runtime comparison or Windows execution. Primary integration owns those results.
+34
View File
@@ -1,5 +1,39 @@
# Progress — 2026-11-02
## Bubble continuation
User continued gadgets after clean1897dd2/9ea5784. Bubble mode2 motion, body,
sprite and VR01 floor dependencies are recovered in gameplay/bubble-motion.md,
bubble-body.md and bubble-rendering.md. Six isolated copied-original body cases
establish160/.415 support66.4, no forced lowering on equip, cleanup60/1.265 and
300/900 bounce motion. REA Evidence, guarded source reports and probe fixtures
are retained locally. Full original gameplay/native Windows remain separate.
Primary integrated BubbleEffect/Motion/Visuals, controlled−.5dt, fire-as-throttle,
persistent movementmode2, direct300/900 bounces, source cleanup650, original Canv1
full RGBA fade and F1 grant/select. VR01 now uses the recovered static body subset
with retained-material111 lava/score/audio/debounce policy. A stored material
owner preserves Invisible114/FC versus late lava RGBA write order. The original
fixed75.9 root/render bridge remains; lab/outside still use provisional collision.
GadgetScreen reads actual raw mode and Bubble practice loads before live equip.
Thirteen Bubble integration groups pass, alongside11 pure motion and8 effect/
visual groups. Independent review reruns those suites and finds no blocker within
the declared profile. Complete scripts/test.sh passes202 Python+2 HUD checks,
all managed suites,31 main GPU completions,17 isolated material checks and SDL
dummy lifecycle, with zero enabled Vulkan validation errors. All539 originals
verify. Native GTX1070/private Xvfb at1920×1080 passes all eight Bubble SDL phases,
including real supported900/SFX106, cleanup650 and visible full RGBA fade. Its
accelerated fixture advances306 extra ordinary player ticks and retains tutorial
energy20; it does not prove original cadence or manual tutorial completion.
Readbacks were inspected. Logs: artifacts/bubble-implementation/.
All investigator ownership has returned to primary. A20's consumer remains open;
normal accepted-input target handoff is recovered without guessing a countdown.
Source commit and both package/standalone release checks follow. No broad C4/C5 resume:
dynamic/special lab/outside collision, shared camera/Euler ownership, all damage
flags and retained owned-helper lifetime remain explicit boundaries.
## Invisible and shared energy continuation
Implemented original item2/raw mode2: initial7-second recharge, fixed2-energy
+6
View File
@@ -5,6 +5,12 @@ offsets, virtual addresses, API symbols or observed behavior. Decompiled output
evidence, not original source. Original gameplay has not yet been observed successfully; isolated original DLL
probes and modern runtime checks are recorded separately.
- `gameplay/bubble-motion.md`, `bubble-body.md`, `bubble-rendering.md`,
`bubble-implementation.md`, `bubble-implementation-review.md`: mode2 controller,
copied-original radius/factor/support references, actualVR01 floor111/texture
linkage, original owned sprite and bounded implementation/review. Source and
runtime evidence remain distinct; retained helper/camera/Euler gates persist.
- `gameplay/invisible.md`, `invisible-implementation.md`, `invisible-review.md`:
timed mode2/targetability/material state, named-Jimmy versus raw-owner cleanup,
bounded implementation and independent review. `gadget-followup-assets.md`
+10 -3
View File
@@ -72,9 +72,16 @@ the resume backlog, not prerequisites imposed on this user-directed gadget work.
- [x] Build clean1897dd2 Invisible Linux/Windows packages, check exact meter pixels
in both and standalone Linux six-phase/F1 widescreen renders from /tmp.
- [x] Recover Bubble visual/equip/drain/cleanup source contracts with REA/guards.
- [ ] Close Bubble movementmode2/jump/body contract, then implement original sprite
effect and physics in a bounded tutorial. Other effects/full enemy AI and
original/native Windows comparison remain independent backlog.
- [x] Recover Bubble movementmode2 input/apply, direct300/900 bounce, actualVR01
static/floor111 coverage and six copied-original body numeric references.
- [x] Implement original Canv1/effect/motion and boundedVR01 body/floor state;
13 integration/11 motion/8 visual groups and independent review pass.
- [x] Complete202 Python+2 HUD, managed,31 GPU+17 material and native1920×1080
SDL Bubble checks;539 original hashes unchanged.
- [ ] Commit clean Bubble milestone, rebuild Linux/Windows packages and validate
standalone assets/gameplay/debug view.
- [ ] Rocketship, Scooter, Remote, Baseball and Grappler; full enemy AI and
original/native Windows comparison. Retain collision/camera/retained-helper gates.
Details: [first gadget slice](gameplay/gadgets-implementation.md). Investigators
have returned all file ownership to primary. Complete final regression, native
+6
View File
@@ -17,6 +17,8 @@ for rid in linux-x64 win-x64; do
cp -a artifacts/extracted/gadgets/. "$out/scenes/gadgets/"
mkdir -p "$out/scenes/invisible-meter"
cp -a artifacts/extracted/invisible-meter/. "$out/scenes/invisible-meter/"
mkdir -p "$out/scenes/bubble"
cp -a artifacts/extracted/bubble/. "$out/scenes/bubble/"
mkdir -p "$out/scenes/effects"
cp -a artifacts/extracted/effects/. "$out/scenes/effects/"
cp artifacts/extracted/scene-catalog.json "$out/scenes/scene-catalog.json"
@@ -77,6 +79,10 @@ then fire without jump for a7-second effect costing2 energy (tutorials exempt).
F1/Player can Give/Select Invisible, Unequip, and show its timers/targetability.
The original meter and final3-second flashing are included; enemy sensing remains
incomplete. Source warning sounds for low/empty energy are shared by gadgets.
Bubble is implemented too: F1/Player can Give/Select Bubble, Up or primary fire
accelerates, arrows steer, and jump holds produce higher bounces. Tab/Space first
unequips it, then the original sprite fades. VR01 uses recovered static body and
floor111 behavior; lab/outside still have provisional collision.
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
+5
View File
@@ -14,6 +14,9 @@ dotnet run --project tests/GamePort.StaticCollisionTests
dotnet run --project tests/GamePort.BodyPhysicsTests
dotnet run --project tests/GamePort.GadgetTests
dotnet run --project tests/GamePort.InvisibleTests
dotnet run --project tests/GamePort.BubbleMotionTests
dotnet run --project tests/GamePort.BubbleVisualTests
dotnet run --project tests/GamePort.BubbleTests
dotnet run --project tests/GamePort.HeadingTests
dotnet run --project tests/GamePort.BlendTests
dotnet run --project tests/GamePort.CameraRayTests
@@ -55,6 +58,7 @@ dotnet run --no-build -- --headless --smoke-objective-panel --story-time 9 --scr
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 --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-shrink-ray --screenshot artifacts/test-shrink-ray.ppm
dotnet run --no-build -- --headless --scene artifacts/extracted/VR03/scene.json --level gam/VR03.gam --smoke-invisible --screenshot artifacts/test-invisible.ppm
dotnet run --no-build -- --headless --scene artifacts/extracted/VR01/scene.json --level gam/VR01.gam --smoke-bubble --screenshot artifacts/test-bubble.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
@@ -71,6 +75,7 @@ SDL_AUDIODRIVER=dummy dotnet run --no-build -- --scene-audio-smoke artifacts/ext
SDL_AUDIODRIVER=dummy dotnet run --no-build -- --cutscene-audio-smoke artifacts/extracted/level1b/entities/entities.json
python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json
if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then
dotnet run --no-build -- --scene artifacts/extracted/VR01/scene.json --level gam/VR01.gam --smoke-bubble --width 1920 --height 1080 --screenshot artifacts/test-bubble-window.ppm
dotnet run --no-build -- --scene artifacts/extracted/VR03/scene.json --level gam/VR03.gam --smoke-invisible --width 1920 --height 1080 --screenshot artifacts/test-invisible-window.ppm
dotnet run --no-build -- --smoke-gadget-menu --width 1920 --height 1080 --screenshot artifacts/test-gadget-menu-window.ppm
dotnet run --no-build -- --scene artifacts/extracted/VR04/scene.json --level gam/VR04.gam --smoke-shrink-ray --screenshot artifacts/test-shrink-ray-window.ppm
+131
View File
@@ -0,0 +1,131 @@
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Eight rendered port-verification phases, with accelerated full
/// player ticks between them. This is an input fixture, not original cadence.</summary>
public sealed class BubbleSmoke
{
private readonly LabSimulation player;
private readonly SceneInventory inventory;
private readonly bool[] checks = new bool[8];
private readonly float initialEnergy;
private float? supportedRootY;
private int acceleratedTicks, boingSounds, bouncesBeforeHeld, soundsBeforeHeld;
public BubbleSmoke(LabSimulation player, SceneInventory inventory)
{
this.player = player;
this.inventory = inventory;
initialEnergy = player.Energy;
player.GadgetSound += (id, _) => { if (id == 106) boingSounds++; };
inventory.SetState(0, 0, 1);
inventory.SelectGadget(0);
if (player.GadgetMode != 0 || player.MovementMode != 2 || player.InteractionRadius != 160
|| MathF.Abs(player.BodyFactor - .415f) > .00001f || player.MaximumSpeed != 1350
|| !player.Bubble.Expanding)
throw new InvalidOperationException("Bubble fixture requires a connected, eligible mode0/movement2 player binding with radius160/factor.415/max1350");
}
public void BeforeFrame(int count, Action<uint, bool> injectKey, bool headless)
{
if (count == 1) Advance(80);
if (count == 2 && !headless)
{
injectKey(224, true); //Left Ctrl: shared primary-fire throttle.
injectKey(80, true); //Left arrow: airborne steering.
}
if (count == 3)
{
PrepareLanding();
bouncesBeforeHeld = player.BubbleBounces;
soundsBeforeHeld = boingSounds;
//The next ordinary application tick consumes this SDL event.
//Never advance the jump helper before actual input processing.
if (!headless) injectKey(225, true);
}
if (count == 4 && !headless)
{
injectKey(224, false);
injectKey(80, false);
injectKey(225, false);
}
if (count == 5)
{
//Release near the next support contact so the fixed captured
//sprite remains in view while its source-owned fade runs.
PrepareLanding();
if (headless) inventory.SelectGadget(-1);
else injectKey(43, true);
}
if (count == 6)
{
if (!headless) injectKey(43, false);
Advance(40);
}
if (count == 7) Advance(40);
}
private void Advance(int count)
{
for (var i = 0; i < count; i++) Tick();
}
private void Tick()
{
player.Step(default);
acceleratedTicks++;
ObserveSupport();
}
private void ObserveSupport()
{
//Read the actual supported root; initial placement's Grounded flag is
//not an observed floor height until at least one real player tick.
if (player.Grounded) supportedRootY = player.ActorRoot.Y;
}
private void PrepareLanding()
{
for (var i = 0; i < 600; i++)
{
var predictedY = player.ActorRoot.Y
+ (player.Velocity.Y - 800 * FixedStepClock.Step) * FixedStepClock.Step;
if (supportedRootY is { } floor && player.Velocity.Y < 0 && predictedY <= floor) return;
Tick();
}
throw new InvalidOperationException($"Bubble fixture could not find an imminent supported landing within600 full player ticks: rootY={player.ActorRoot.Y:F4}, velocityY={player.Velocity.Y:F4}, last supported rootY={supportedRootY?.ToString("F4") ?? "unobserved"}");
}
public void AfterFrame(int count)
{
ObserveSupport();
var effect = player.Bubble;
if (count == 0) checks[0] = effect.Expanding && effect.Visible && !effect.Active
&& effect.Color.X > 0 && effect.Color.X < 1;
if (count == 1) checks[1] = effect.Active && !effect.Expanding && effect.Visible
&& effect.Width == 240 && effect.Height >= 210 && effect.Height <= 270;
if (count == 2) checks[2] = player.GadgetMode == 0 && player.MovementMode == 2
&& player.Speed > 0 && player.TurnRate > 0 && player.Pitch < 0 && !player.Shooting;
if (count == 3) checks[3] = player.BubbleBounces > bouncesBeforeHeld
&& MathF.Abs(player.Velocity.Y - 900) < .001f && boingSounds > soundsBeforeHeld;
if (count == 4) checks[4] = player.GadgetMode == 0 && effect.Active && !player.Shooting;
if (count == 5) checks[5] = player.GadgetMode == -1 && player.MaximumSpeed == 650
&& player.InteractionRadius == 60 && MathF.Abs(player.BodyFactor - 1.265f) < .00001f
&& effect.Collapsing && !effect.Active && !effect.Expanding;
if (count == 6) checks[6] = effect.Visible && effect.Collapsing && effect.Color.X > 0
&& effect.Color.X < 1 && effect.Color.X == effect.Color.Y && effect.Color.X == effect.Color.Z
&& effect.Color.X == effect.Color.W;
if (count == 7) checks[7] = !effect.Visible && !effect.Collapsing && effect.Color == System.Numerics.Vector4.Zero;
}
private bool EnergyPreserved => !player.IgnoresGadgetEnergy || player.Energy == initialEnergy;
public bool Passed => checks.All(value => value) && EnergyPreserved;
public string Report => $"Bubble fixture: expanding={checks[0]}, active={checks[1]}, fire/left throttle={checks[2]}, held support900/SFX106={checks[3]}, input release={checks[4]}, cleanup650={checks[5]}, fullRGBA fade={checks[6]}, hidden={checks[7]}, accelerated player ticks={acceleratedTicks}, boing sounds={boingSounds}, level={player.LevelCode}, energy={player.Energy:F3}/{initialEnergy:F3}, tutorial energy preserved={EnergyPreserved}.";
public static string? StageName(int count) => count switch
{ 0 => "expand", 1 => "active", 2 => "steer", 3 => "high-bounce", 5 => "release", 6 => "fade", 7 => "hidden", _ => null };
public static PlayerInput Input(int count) => new(false, false, count is 2 or 3, false,
count == 3, Fire: count is 2 or 3);
}
+86
View File
@@ -0,0 +1,86 @@
using System.Numerics;
using System.Security.Cryptography;
using System.Text.Json;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Original Canv1 world quad with full RGBA fade. Camera-facing basis
/// and center alignment are declared port policies pending original render recovery.</summary>
public sealed class BubbleVisuals
{
private const string PixelHash = "a3a678c47c1ce94946b1136560a84f3ef86c6884b981256a9fbff62fe8a988e4";
private readonly int offset;
private readonly uint firstIndex;
public Mesh Mesh { get; }
public BubbleVisuals(Mesh combined, string preparedRoot)
{
var manifest = Path.GetFullPath(Path.Combine(preparedRoot, "bubble/bubble.json"));
if (new FileInfo(manifest).Length > 16 * 1024) throw new InvalidDataException("Bubble manifest exceeds limit");
using var document = JsonDocument.Parse(File.ReadAllBytes(manifest), new JsonDocumentOptions { MaxDepth = 10 });
var root = document.RootElement;
if (root.GetProperty("schema").GetInt32() != 1 || root.GetProperty("textures").GetArrayLength() != 1)
throw new InvalidDataException("Unsupported Bubble resource format");
var entry = root.GetProperty("textures")[0];
if (entry.GetProperty("id").GetInt32() != 1 || entry.GetProperty("name").GetString() != "orangebubble"
|| entry.GetProperty("width").GetInt32() != 146 || entry.GetProperty("height").GetInt32() != 146
|| entry.GetProperty("rgbaSha256").GetString() != PixelHash)
throw new InvalidDataException("Invalid source Bubble canvas");
var directory = Path.GetDirectoryName(manifest)!;
var path = Path.GetFullPath(Path.Combine(directory, entry.GetProperty("path").GetString()!));
if (!path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal)
|| new FileInfo(path).Length != 146 * 146 * 4)
throw new InvalidDataException("Invalid Bubble pixel path/length");
var rgba = File.ReadAllBytes(path);
if (!Convert.ToHexStringLower(SHA256.HashData(rgba)).Equals(PixelHash, StringComparison.Ordinal))
throw new InvalidDataException("Bubble decoded pixels differ from the original canvas");
offset = combined.Vertices.Length;
firstIndex = (uint)combined.Indices.Length;
var textures = new Dictionary<int, PngImage>(combined.Textures);
var textureId = int.MinValue + 16000;
while (textures.ContainsKey(textureId)) textureId++;
textures.Add(textureId, new(146, 146, rgba));
var vertices = combined.Vertices.ToList();
vertices.AddRange([new(Vector3.Zero, new(0, 1), Vector3.One), new(Vector3.Zero, new(1, 1), Vector3.One),
new(Vector3.Zero, new(1, 0), Vector3.One), new(Vector3.Zero, new(0, 0), Vector3.One)]);
var first = (uint)offset;
var indices = combined.Indices.ToList();
indices.AddRange([first, first + 1, first + 2, first, first + 2, first + 3]);
var draws = combined.Draws.ToList();
if (!combined.HasExplicitDraws && firstIndex != 0) draws.Add(new(0, firstIndex, -1));
draws.Add(new(firstIndex, 6, textureId) { Visible = false, Blend = MeshBlend.Additive });
Mesh = new(vertices.ToArray(), indices.ToArray()) { HasExplicitDraws = true, Draws = draws.ToArray(),
Textures = textures, CollisionPolygons = combined.CollisionPolygons,
HasCollisionMaterialIds = combined.HasCollisionMaterialIds };
}
public void Update(Mesh destination, BubbleEffect effect, Vector3 root, Vector3 eye, Vector3 target)
{
if (destination.Vertices.Length < offset + 4)
throw new ArgumentException("Destination omits Bubble vertices", nameof(destination));
var draw = destination.Draws.First(d => !d.ScreenSpace && d.FirstIndex == firstIndex && d.IndexCount == 6);
draw.Visible = effect.Visible;
draw.Blend = effect.ConventionalBlend ? MeshBlend.Alpha : MeshBlend.Additive;
draw.Opacity = effect.Color.W;
if (!draw.Visible) return;
if (!Finite(root) || !Finite(eye) || !Finite(target))
throw new ArgumentException("Bubble root and camera must be finite");
var direction = target - eye;
if (direction.LengthSquared() < .000001f) direction = Vector3.UnitZ;
direction = Vector3.Normalize(direction);
var right = Vector3.Cross(Vector3.UnitY, direction);
right = right.LengthSquared() < .000001f ? Vector3.UnitX : Vector3.Normalize(right);
var up = Vector3.Normalize(Vector3.Cross(direction, right));
var x = right * (effect.Width * .5f);
var y = up * (effect.Height * .5f);
var color = new Vector3(effect.Color.X, effect.Color.Y, effect.Color.Z);
destination.Vertices[offset] = new(root - x - y, new(0, 1), color);
destination.Vertices[offset + 1] = new(root + x - y, new(1, 1), color);
destination.Vertices[offset + 2] = new(root + x + y, new(1, 0), color);
destination.Vertices[offset + 3] = new(root - x + y, new(0, 0), color);
}
private static bool Finite(Vector3 value) => float.IsFinite(value.X) && float.IsFinite(value.Y) && float.IsFinite(value.Z);
}
+9 -5
View File
@@ -8,7 +8,7 @@ public sealed record DebugScene(string LevelFile, string Code, string[] Starts);
public enum DebugAction { None, Resume, Camera, SkipCutscene, RefillEnergy, GiveJetpack, ApplySceneTask, LoadScene, Reset, ForceControl, ToggleOverlay,
Noclip, NoclipSpeed, StopMotion, ShowObjective, ReturnNoclipEntry, LevelAvailability, InputOrder, ApplyJetpackState,
CameraObstruction, MuteMusic, MuteSpeech, MuteEffects, RestartMusic, StopEffects, SaveCheckpoint, LoadCheckpoint, Practice,
GiveInvisible, UnequipGadget }
GiveInvisible, UnequipGadget, GiveBubble }
public sealed record DebugMenuView(string[] Lines, int SelectedLine);
public sealed record DebugStatus(string Level, string Start, Vector3 Root, float Yaw, float Speed,
bool Grounded, float Energy, int Score, int SceneTask, string Cutscene, bool Controlled,
@@ -29,6 +29,9 @@ public sealed record DebugSystems
public float InvisibleRemaining { get; init; }
public float InvisibleRecharge { get; init; }
public bool Targetable { get; init; } = true;
public string BubblePhase { get; init; } = "OFF";
public float BodyRadius { get; init; } = 60;
public float BodyFactor { get; init; } = 1.265f;
public int Objective { get; init; }
public float ObjectiveTime { get; init; }
public bool? CameraObstruction { get; init; }
@@ -52,7 +55,7 @@ public sealed class DebugMenu
public const int ItemCount = 12;
public const int PageCount = 3;
public int Page { get; private set; }
public int PageItems => Page switch { 1 => 12, 2 => 9, _ => ItemCount };
public int PageItems => Page switch { 1 => 13, 2 => 9, _ => ItemCount };
private static readonly float[] FlySpeeds = [300, 600, 1200, 2400];
private int flySpeedIndex = 1, jetpackStateIndex = 1;
private static readonly int[] JetpackStates = [0, 1, 4];
@@ -115,7 +118,7 @@ public sealed class DebugMenu
3 => DebugAction.ShowObjective, 4 => DebugAction.ReturnNoclipEntry,
5 => DebugAction.LevelAvailability, 6 => DebugAction.InputOrder,
8 => DebugAction.ApplyJetpackState, 9 => DebugAction.RefillEnergy,
10 => DebugAction.GiveInvisible, 11 => DebugAction.UnequipGadget, _ => DebugAction.None
10 => DebugAction.GiveInvisible, 11 => DebugAction.UnequipGadget, 12 => DebugAction.GiveBubble, _ => DebugAction.None
};
if (Page == 2) return Selected switch
{
@@ -153,14 +156,15 @@ public sealed class DebugMenu
Page == 1 ? $"JUMP {system.JumpState} HOLD {F(system.JumpHold)} BURN {F(system.BurnRemaining)}"
: $"EFFECT BYTES {system.EffectBytes} AUDIO AVAILABLE {system.AudioAvailable}",
$"OBJECTIVE {system.Objective} TIME {F(system.ObjectiveTime)} GADGET STATE {system.JetpackAvailability}",
$"INVISIBLE {F(system.InvisibleRemaining)} RECHARGE {F(system.InvisibleRecharge)}/7 TARGETABLE {system.Targetable}", ""];
$"INVISIBLE {F(system.InvisibleRemaining)} RECHARGE {F(system.InvisibleRecharge)}/7 TARGETABLE {system.Targetable}",
$"BUBBLE {system.BubblePhase} BODY R {F(system.BodyRadius)} FACTOR {system.BodyFactor.ToString("0.000",c)}", ""];
string[] items = Page == 1 ? [
$"NOCLIP (F3): {system.Noclip} (ENTER TOGGLE)",
$"FLY SPEED: {F(FlySpeed)} LIVE {F(system.NoclipSpeed)} (ENTER APPLIES)", "STOP MOTION / CLEAR QUEUED JUMP", "SHOW CURRENT OBJECTIVE",
"RETURN TO NOCLIP ENTRY POSITION", "APPLY THIS LEVEL'S GADGET AVAILABILITY",
$"INPUT AFTER PLAYER: {system.InputAfterPlayer} (TOGGLE)",
$"JET PACK STATE: {JetpackState} (0 NONE / 1 OWNED / 4 DISABLED)", "APPLY JET PACK STATE", "REFILL ENERGY TO 100",
"GIVE / SELECT INVISIBLE", "UNEQUIP CURRENT GADGET"] : [
"GIVE / SELECT INVISIBLE", "UNEQUIP CURRENT GADGET", "GIVE / SELECT BUBBLE"] : [
$"STATIC CAMERA OBSTRUCTION: {(system.CameraObstruction?.ToString() ?? "UNAVAILABLE")}",
$"MUTE MUSIC: {system.MusicMuted}", $"MUTE SPEECH: {system.SpeechMuted}", $"MUTE EFFECTS: {system.EffectsMuted}",
"RESTART SELECTED MUSIC", "STOP ALL EFFECTS / LOOPS", "SAVE DEBUG CHECKPOINT", "LOAD DEBUG CHECKPOINT", "SHOW JET PACK PRACTICE PROMPT"];
@@ -7,6 +7,8 @@ namespace GamePort.Application;
/// indexed0 FC blend changes affect that draw without changing pose/visibility.</summary>
public static class PlayerGadgetMaterial
{
public static void Apply(MeshDraw draw, PlayerAppearance appearance)
{ draw.Opacity=appearance.Color.W; draw.Blend=appearance.Blend; }
public static void Apply(MeshDraw draw, InvisibleGadget invisible)
{
draw.Opacity = invisible.Opacity;
+6 -4
View File
@@ -11,9 +11,11 @@ public static class AirSteering
public const float TurnLimit = 30; //439D81..439DB7, ordinary mode1.
public const float CoastThreshold = 0.9090909361839294f; //49D5DC.
public static AirSteeringResult Step(float speed, float turnRate, PlayerInput input, float seconds)
public static AirSteeringResult Step(float speed, float turnRate, PlayerInput input, float seconds,
float maximumSpeed = RecoveredMotion.MaximumSpeed)
{
if (!float.IsFinite(speed) || !float.IsFinite(turnRate) || !float.IsFinite(seconds) || seconds < 0 || seconds >= 1)
if (!float.IsFinite(speed) || !float.IsFinite(turnRate) || !float.IsFinite(seconds)
|| !float.IsFinite(maximumSpeed) || maximumSpeed<=0 || seconds < 0 || seconds >= 1)
throw new ArgumentOutOfRangeException(nameof(seconds));
var turnStep = TurnAcceleration * seconds;
if (input.Left) turnRate += turnStep;
@@ -22,8 +24,8 @@ public static class AirSteering
else if (turnRate > 0) turnRate = MathF.Max(0, turnRate - turnStep);
turnRate = Math.Clamp(turnRate, -TurnLimit, TurnLimit);
if (input.Forward) speed = RecoveredMotion.AddSpeed(speed);
else if (speed > RecoveredMotion.MaximumSpeed * CoastThreshold)
if (input.Forward) speed = RecoveredMotion.AddSpeed(speed,maximumSpeed);
else if (speed > maximumSpeed * CoastThreshold)
speed -= RecoveredMotion.SpeedDecay * .5f;
//439C1D..439CB2 brakes to0, without starting reverse flight.
if (input.Backward)
+73
View File
@@ -0,0 +1,73 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>Owned C3DBubble sprite transitions (410AE0/410CA0/410D00).
/// The caller owns equip, cleanup, placement and callback scheduling.</summary>
public sealed class BubbleEffect(bool conventionalBlend = false)
{
public bool Visible { get; private set; }
public bool Active { get; private set; }
public bool Expanding { get; private set; }
public bool Collapsing { get; private set; }
public float Timer { get; private set; }
public Vector4 Color { get; private set; } = conventionalBlend ? new(.9f, .9f, .9f, 1) : Vector4.One;
public float Width { get; private set; } = 200;
public float Height { get; private set; } = 200;
public bool ConventionalBlend { get; } = conventionalBlend;
public void Start()
{
// Source equip rejects all three flags before calling this leaf.
Expanding = true;
Timer = 0;
Visible = true;
}
public void Stop()
{
// Source410D00 leaves expansion alone. Jimmy cleanup clears it separately.
Collapsing = true;
Active = false;
Timer = 0;
}
public void ClearExpansion() => Expanding = false;
public void Step(float seconds)
{
if (!float.IsFinite(seconds) || seconds < 0 || seconds >= 1)
throw new ArgumentOutOfRangeException(nameof(seconds));
//410AF2 stores float timer but retains the addition on the x87 stack
//for the fade comparisons. Preserve that distinction at strict boundaries.
var sum = (double)Timer + seconds;
Timer = (float)sum;
if (Active)
{
Width = 240;
Height = (float)(240 + Math.Sin((double)Timer * 10) * 30);
if (ConventionalBlend) Color = new(1, 1, 1, .5f);
}
else if (Expanding)
{
var scalar = (float)sum;
if (sum > 1) { scalar = 1; Active = true; Expanding = false; }
Color = new(scalar);
}
else if (Collapsing)
{
var fade = 1 - sum;
var scalar = (float)fade;
if (fade < 0) { scalar = 0; Collapsing = false; Visible = false; }
Color = new(scalar);
}
}
public void Reset()
{
Visible = Active = Expanding = Collapsing = false;
Timer = 0;
Color = ConventionalBlend ? new(.9f, .9f, .9f, 1) : Vector4.One;
Width = Height = 200;
}
}
+91
View File
@@ -0,0 +1,91 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct BubbleSteering(float Speed, float TurnRate, float TargetPitch, float TargetRoll);
public readonly record struct BubbleApply(Vector3 Velocity, float Yaw, float Speed, bool Boing);
/// <summary>
/// Keyboard subset of mode2 input439900 and apply4387E0. Body integration,
/// impulses, acceleration and gadget lifetime belong to their existing phases.
/// Source ownership and precision limits: docs/gameplay/bubble-motion.md.
/// </summary>
public static class BubbleMotion
{
public const float MaximumSpeed = 1350;
public const float TurnLimit = 50;
public const float ReleasedBounceSpeed = 300;
public const float HeldBounceSpeed = 900;
public static BubbleSteering StepInput(float speed, float turn, PlayerInput input,
bool supported, float seconds, float maximumSpeed = MaximumSpeed)
{
Validate(speed, turn, seconds);
if (!float.IsFinite(maximumSpeed) || maximumSpeed <= 0)
throw new ArgumentOutOfRangeException(nameof(maximumSpeed));
var turnStep = AirSteering.TurnAcceleration * seconds;
if (input.Left) turn += turnStep;
else if (input.Right) turn -= turnStep;
else if (turn < 0) turn = MathF.Min(0, turn + turnStep);
else if (turn > 0) turn = MathF.Max(0, turn - turnStep);
//439ABB..439AE6: mode2 also uses the shared fire predicate as throttle.
var forward = input.Forward || input.Fire;
if (forward && speed < maximumSpeed)
speed = MathF.Min(maximumSpeed, speed + RecoveredMotion.SpeedIncrement);
if (!forward && speed > maximumSpeed * AirSteering.CoastThreshold)
speed -= RecoveredMotion.SpeedDecay * .5f;
//439BA2..439BED: this subtraction deliberately has no crossing clamp.
if (supported) speed = speed > 0 ? speed - RecoveredMotion.SpeedDecay * .5f : 0;
if (input.Backward)
{
if (speed > 0)
speed = MathF.Max(0, speed - RecoveredMotion.SpeedDecay * (supported ? 1 : .5f));
else if (speed < 0)
speed = MathF.Min(0, speed + RecoveredMotion.SpeedDecay);
}
turn = Math.Clamp(turn, -TurnLimit, TurnLimit);
return new(speed, turn, forward ? -10 : input.Backward ? 10 : 0, -.25f * turn);
}
public static BubbleApply StepApply(float speed, float turn, float yaw, float pitch,
Vector3 velocity, bool supported, bool jump, float seconds)
{
Validate(speed, turn, seconds);
if (!float.IsFinite(yaw) || !float.IsFinite(pitch)
|| !float.IsFinite(velocity.X) || !float.IsFinite(velocity.Y) || !float.IsFinite(velocity.Z))
throw new ArgumentOutOfRangeException(nameof(velocity));
float sideSpeed = 0;
//43884E..4388AE: test incoming velocity before replacing its X/Z.
if (velocity != Vector3.Zero)
{
yaw += turn * seconds;
const float friction = .8f;
sideSpeed = turn * .0181818176060915f * (1 - friction) * speed;
}
var (sin, cos) = LabSimulation.Trig(yaw);
var forwardSpeed = LabSimulation.Trig(pitch).Cos * speed;
velocity = new(-sin * forwardSpeed + cos * sideSpeed, velocity.Y,
cos * forwardSpeed + sin * sideSpeed);
//43899A..438A50: direct liveY assignment, after composing current X/Z.
//Only the published scalar halves; current velocity keeps pre-half X/Z.
if (supported)
{
velocity.Y = jump ? HeldBounceSpeed : ReleasedBounceSpeed;
if (!jump) speed *= .5f;
}
return new(velocity, yaw, speed, supported && jump);
}
private static void Validate(float speed, float turn, float seconds)
{
if (!float.IsFinite(speed) || !float.IsFinite(turn) || !float.IsFinite(seconds)
|| seconds < 0 || seconds >= 1)
throw new ArgumentOutOfRangeException(nameof(seconds));
}
}
+4 -3
View File
@@ -5,7 +5,7 @@ namespace GamePort.Game;
public readonly record struct GadgetCanvas(int Id, Vector2 Position);
/// <summary>Bounded group0 gadget panel; source425870/425EF0/425B20/427370.</summary>
public sealed class GadgetScreen(SceneInventory inventory)
public sealed class GadgetScreen(SceneInventory inventory, Func<int>? rawMode = null)
{
public static IReadOnlyList<Vector2> Positions { get; } = Array.AsReadOnly<Vector2>([new(12,182), new(158,182), new(12,327), new(157,327),
new(342,182), new(487,182), new(342,327), new(487,327)]);
@@ -24,7 +24,7 @@ public sealed class GadgetScreen(SceneInventory inventory)
{
if (Open) { Close(); return true; }
if (!permitted) return false;
if (EquippedMode(inventory.SelectedGadget) != -1)
if ((rawMode?.Invoke() ?? EquippedMode(inventory.SelectedGadget)) != -1)
{
inventory.SelectGadget(-1); Changed?.Invoke(); return true;
}
@@ -72,7 +72,8 @@ public sealed class GadgetScreen(SceneInventory inventory)
var item = Hovered;
var practice = PracticeArmed;
Close();
inventory.SelectGadget(item);
//428F61 loads Bubble practice BEFORE live radius/mode/effect setup.
inventory.SelectGadget(item,equip:!(practice && item==0));
if (practice) PracticeRequested?.Invoke(item);
return true;
}
+9
View File
@@ -17,6 +17,8 @@ public sealed class InvisibleGadget
public int Activations { get; private set; }
public bool Active => Equipped && !Targetable;
public event Action<bool>? EquippedChanged;
public event Action<float>? AlphaRequested;
public event Action<bool>? BlendRequested;
public bool Equip(float energy, bool energyOverride)
{
@@ -30,6 +32,8 @@ public sealed class InvisibleGadget
public void Release()
{
BlendRequested?.Invoke(true);
AlphaRequested?.Invoke(0);
Equipped = false; Remaining = Duration; Recharge = 0;
Targetable = true; Opacity = 1; ConventionalBlend = false;
MeterVisible = false; MeterReady = false;
@@ -62,6 +66,7 @@ public sealed class InvisibleGadget
adjustEnergy(-2);
Remaining = Duration; Recharge = 0; Activations++;
ConventionalBlend = false; Opacity = .7f; Targetable = false;
BlendRequested?.Invoke(false); AlphaRequested?.Invoke(.7f);
}
}
if (Remaining == 0 && (energy > 0 || energyOverride))
@@ -79,9 +84,13 @@ public sealed class InvisibleGadget
{
Remaining = 0; Opacity = 1; Targetable = true;
ConventionalBlend = false; MeterReady = false;
BlendRequested?.Invoke(true); AlphaRequested?.Invoke(0);
return;
}
if (Remaining <= 3)
{
ConventionalBlend = ((int)((double)Remaining * 5) & 1) != 0;
BlendRequested?.Invoke(ConventionalBlend);
}
}
}
+125 -13
View File
@@ -23,6 +23,10 @@ public sealed class LabSimulation
private readonly Vector3 sourceStart;
private readonly float startYaw, modelMinimumY, rootHeight, startFloor;
private float targetYaw, extraAirAcceleration, shadowDistance, lateralContribution;
private float targetPitch, targetRoll;
private int? retainedSupportMaterial;
private bool bubbleLoop;
private PlayerPose bubblePose;
private Vector3 pendingImpulse;
private int movementMode;
private JetpackBurstState jumpState;
@@ -36,13 +40,35 @@ public sealed class LabSimulation
public Func<int>? JetpackInventoryState { get; set; }
public string LevelCode { get; set; } = "LV1B";
public InvisibleGadget Invisible { get; } = new();
public BubbleEffect Bubble { get; } = new();
public PlayerAppearance Appearance { get; } = new();
public Vr01FloorState FloorState { get; } = new();
public Vector3 BubbleRoot { get; private set; }
public float BodyFactor { get; private set; } = OriginalBodySupport.JimmyFactor;
public float MaximumSpeed { get; private set; } = RecoveredMotion.MaximumSpeed;
public float Pitch { get; private set; }
public float Roll { get; private set; }
public bool TracksBubbleOrientation { get; private set; }
public int BubbleBounces { get; private set; }
public int GadgetMode
{
get => gadgetMode;
set
{
var previousPose=Pose;
if (gadgetMode == 0) ReleaseBubble();
if (gadgetMode == 2) Invisible.Release();
gadgetMode = -1;
if (value == 0)
{
if (Energy <= 0 && !IgnoresGadgetEnergy || Bubble.Active || Bubble.Expanding || Bubble.Collapsing) return;
InteractionRadius=160; BodyFactor=.415f; movementMode=2; MaximumSpeed=1350;
bubblePose=previousPose;
TracksBubbleOrientation=true;
gadgetMode=0; Bubble.Start();
if (!bubbleLoop) { GadgetSound?.Invoke(2,true); bubbleLoop=true; }
return;
}
if (value == 2 && !Invisible.Equip(Energy, IgnoresGadgetEnergy)) return;
gadgetMode = value;
}
@@ -51,6 +77,10 @@ public sealed class LabSimulation
public float Energy { get => energy.Value; set => energy.Value = value; }
public bool LowEnergyWarning => energy.LowWarning;
public event Action<int>? EnergySound;
public event Action<int,bool>? GadgetSound;
public event Action? BubbleSoundStopped;
public event Action<int>? ScoreChanged;
public event Action? DefaultGadgetRequested;
//Source260/live15C serves both body collision and contact tests. The name
//predates source-body integration; burst100 is not an interaction-only size.
public float InteractionRadius { get; private set; } = 60;
@@ -76,6 +106,7 @@ public sealed class LabSimulation
public float TurnRate { get; private set; }
public bool Grounded { get; private set; }
public PlayerPose Pose => Noclip ? Velocity.LengthSquared() > 0 ? PlayerPose.Fly : PlayerPose.Idle
: GadgetMode == 0 ? bubblePose
: pendingImpulse.Y > 0 ? PlayerPose.Jump
: Grounded ? Shooting ? PlayerPose.Shoot : Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
: jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly
@@ -94,7 +125,8 @@ public sealed class LabSimulation
public Vector3 ActorRoot => Position + Vector3.UnitY * rootHeight;
public Vector3 CameraEye { get; private set; }
public Vector3 CameraTarget => ActorRoot + new Vector3(0, 99, 0);
public Matrix4x4 Model => Matrix4x4.CreateRotationY(-Yaw * MathF.PI / 180)
public Matrix4x4 Model => Matrix4x4.CreateRotationZ(-(TracksBubbleOrientation?Roll:0) * MathF.PI / 180)
* Matrix4x4.CreateRotationX(-(TracksBubbleOrientation?Pitch:0) * MathF.PI / 180) * Matrix4x4.CreateRotationY(-Yaw * MathF.PI / 180)
* Matrix4x4.CreateTranslation(Position - new Vector3(0, modelMinimumY, 0));
public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, float yaw,
@@ -107,6 +139,8 @@ public sealed class LabSimulation
this.ceilingRay = ceilingRay;
originalBody = originalCollision == null ? null : new OriginalBodyPhysics(originalCollision);
this.energy = energy ?? new PlayerEnergy();
Invisible.AlphaRequested += Appearance.SetAlpha;
Invisible.BlendRequested += Appearance.SetBlend;
sourceStart = start;
startYaw = yaw;
var bounds = standingPose.Bounds();
@@ -124,8 +158,13 @@ public sealed class LabSimulation
public void Reset()
{
if (gadgetMode == 0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); }
if (gadgetMode == 2) gadgetMode = -1;
Invisible.Reset();
Bubble.Reset(); FloorState.Reset(); Appearance.Reset(); retainedSupportMaterial=null;
Pitch=Roll=targetPitch=targetRoll=0; BubbleBounces=0;
TracksBubbleOrientation=false;
MaximumSpeed=RecoveredMotion.MaximumSpeed; BodyFactor=OriginalBodySupport.JimmyFactor;
var floor = collision.GroundHeight(sourceStart, 2500)!.Value;
Position = new(sourceStart.X, floor + (UsesOriginalBody ? 0 : SceneCollision.Skin), sourceStart.Z);
Velocity = Vector3.Zero;
@@ -183,24 +222,35 @@ public sealed class LabSimulation
public void Step(PlayerInput input, bool controlled = true, bool? anyControlled = null)
{
if (Noclip) { StepNoclip(input); return; }
if (Noclip)
{
StepNoclip(input);
Bubble.Step(FixedStepClock.Step); //Modern flight skips body/input, not the released owned sprite's fade.
return;
}
//47E554 global body integration precedes473740 registry callbacks.
// This reconstructs the player/input/fire partial order, not the full
// scene registry, original cadence or original collision response.
StepPhysics();
if (controlled && !InputAfterPlayerUpdate) StepInput(input);
//42469F..4246DC reasserts ordinary grounded radius before ownership
//checks. Bubble mode0's separate radius160 policy remains unimplemented.
if (Grounded) InteractionRadius = 60;
//42469F..4246DC runs independently of raw ownership.
if (Grounded)
{
InteractionRadius = GadgetMode == 0 ? 160 : 60;
if (GadgetMode==0) bubblePose=PlayerPose.Idle;
}
//424BE0..424C34 runs this wrapper before437940's ownership gate.
StepCeiling();
StepFloorPolicy(); //437940's base40E050, before the input-identity gate.
if (controlled) StepPlayer(input);
Invisible.Step(FixedStepClock.Step, anyControlled ?? controlled, input.Fire, input.Jump,
Energy, IgnoresGadgetEnergy, AdjustEnergy);
if (LevelCode == "VR01") FloorState.Step(FixedStepClock.Step,Appearance.SetColor);
var effect = JetpackBurst.StepEffect(jumpState, Grounded, FixedStepClock.Step, Energy, LevelCode);
jumpState = effect.State; JetpackEffectVisible = effect.Visible;
if (effect.Visible) AdjustEnergy(-FixedStepClock.Step * JetpackBurst.EnergyPerSecond);
EffectSteps++;
Bubble.Step(FixedStepClock.Step); //Owned effect clock is not Jimmy input ownership.
if (controlled && InputAfterPlayerUpdate) StepInput(input);
Steps++;
}
@@ -216,6 +266,37 @@ public sealed class LabSimulation
public void SetShooting(bool shooting) => Shooting = shooting;
public void AdjustEnergy(float delta) => energy.Adjust(delta, LevelCode, id => EnergySound?.Invoke(id));
private void ReleaseBubble()
{
movementMode=0; MaximumSpeed=650;
Bubble.Stop(); Bubble.ClearExpansion();
if (bubbleLoop) BubbleSoundStopped?.Invoke();
bubbleLoop=false; InteractionRadius=60; BodyFactor=OriginalBodySupport.JimmyFactor;
}
public void FlattenOrientation() { Pitch=Roll=0; }
public void SeedBubbleTilt(Vector3 euler)
{
if (TracksBubbleOrientation) return;
Pitch=targetPitch=euler.X; Roll=targetRoll=euler.Z;
}
private void StepFloorPolicy()
{
if (LevelCode!="VR01" || originalBody==null) return;
var effect=FloorState.Visit(retainedSupportMaterial,GadgetMode);
if (effect.Entered)
{ GadgetSound?.Invoke(39,false); if (GadgetMode!=0) GadgetSound?.Invoke(190,false); }
if (!effect.Damaged) return;
AdjustEnergy(-5); ScoreChanged?.Invoke(-5); CancelPoweredFlight();
}
private void CancelPoweredFlight()
{
if (movementMode!=1) return;
jumpState=jumpState with {JumpState=0,EffectRemaining=0}; forceFall=true;
}
private void StepCeiling()
{
if (Velocity.Y <= 0 || ceilingRay == null
@@ -224,9 +305,7 @@ public sealed class LabSimulation
CeilingHits++;
//425120 leaves hold, mode, pending impulse and acceleration intact.
//Full sound/selected-gadget cleanup callbacks remain a separate gap.
if (movementMode != 1) return;
jumpState = jumpState with { JumpState = 0, EffectRemaining = 0 };
forceFall = true;
CancelPoweredFlight();
}
/// <summary>Authored AI root/Euler writes. They do not reset body motion or
@@ -244,6 +323,7 @@ public sealed class LabSimulation
if (enabled == Noclip) return false;
if (enabled)
{
if (gadgetMode==0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); }
noclipEntry = Position; noclipEntryYaw = Yaw; HasNoclipEntry = true;
}
var returned = !enabled && !collision.CanOccupy(Position, BodyRadius, BodyHeight);
@@ -257,6 +337,7 @@ public sealed class LabSimulation
public void StopDebugMotion()
{
if (gadgetMode==0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); }
Shooting = false;
Velocity = pendingImpulse = Vector3.Zero;
Speed = PublishedSpeed = TurnRate = extraAirAcceleration = lateralContribution = 0;
@@ -298,23 +379,41 @@ public sealed class LabSimulation
//438A60 dispatches by stored movement mode, not current support.
if (movementMode == 0)
{
if (TracksBubbleOrientation && (input.Forward || input.Left || input.Right
|| input.Backward && !(GadgetMode is -1 or 3 && input.Fire))) targetPitch=targetRoll=0;
float yawDelta = 0;
if (input.Left) { yawDelta += 20; lateralContribution = -1000; Speed = RecoveredMotion.AddSpeed(Speed); }
else if (input.Right) { yawDelta -= 20; lateralContribution = 1000; Speed = RecoveredMotion.AddSpeed(Speed); }
if (input.Forward) { yawDelta *= 0.5f; Speed = RecoveredMotion.AddSpeed(Speed); }
if (input.Left) { yawDelta += 20; lateralContribution = -1000; Speed = RecoveredMotion.AddSpeed(Speed,MaximumSpeed); }
else if (input.Right) { yawDelta -= 20; lateralContribution = 1000; Speed = RecoveredMotion.AddSpeed(Speed,MaximumSpeed); }
if (input.Forward) { yawDelta *= 0.5f; Speed = RecoveredMotion.AddSpeed(Speed,MaximumSpeed); }
if (yawDelta != 0) targetYaw = Yaw + yawDelta;
if (input.Backward) Speed = MathF.Max(Speed - 52.5f, -300);
else if (!input.Forward) Speed = RecoveredMotion.ReleaseSpeed(Speed);
}
else if (movementMode==2)
{
var steering=BubbleMotion.StepInput(Speed,TurnRate,input,Grounded,dt,MaximumSpeed);
Speed=steering.Speed; TurnRate=steering.TurnRate;
targetPitch=steering.TargetPitch; targetRoll=steering.TargetRoll; targetYaw=Yaw;
}
else
{
var steering = AirSteering.Step(Speed, TurnRate, input, dt);
var steering = AirSteering.Step(Speed, TurnRate, input, dt,MaximumSpeed);
Speed = steering.Speed; TurnRate = steering.TurnRate;
if (TracksBubbleOrientation) { targetPitch=0; targetRoll=-TurnRate; }
//439E2B preserves current yaw as the destination; air apply then
//438011..43802B adds the independent turn rate directly to yaw.
targetYaw = Yaw;
}
StepCamera(); //438BC0/439900 input path owns follow; still provisional geometry/state.
if (movementMode==2)
{
AdjustEnergy(-dt*.5f);
if (Energy<=0) { GadgetMode=-1; DefaultGadgetRequested?.Invoke(); }
//4262A5 continues placement even if depletion just cleaned the mode.
var direction=ActorRoot+Vector3.UnitY*100-CameraEye;
direction=direction.LengthSquared()>0 ? Vector3.Normalize(direction) : Vector3.Zero;
BubbleRoot=ActorRoot+Vector3.UnitY*50-direction*80;
}
InputActions?.Invoke(input);
}
@@ -322,6 +421,18 @@ public sealed class LabSimulation
{
ControllerSteps++;
const float dt = FixedStepClock.Step;
if (TracksBubbleOrientation)
{
Pitch+=(targetPitch-Pitch)*dt*4.5f;
Roll+=(targetRoll-Roll)*dt*4.5f;
}
if (movementMode==2)
{
var bubble=BubbleMotion.StepApply(Speed,TurnRate,Yaw,Pitch,Velocity,Grounded,input.Jump,dt);
Velocity=bubble.Velocity; Yaw=bubble.Yaw; Speed=bubble.Speed; PublishedSpeed=Speed;
if (Grounded) { BubbleBounces++; if (bubble.Boing) GadgetSound?.Invoke(106,false); }
return;
}
var yawError = MathF.IEEERemainder(targetYaw - Yaw, 360);
Yaw = (Yaw + yawError * dt * 3.7f) % 360;
//437A96 selects air mode on held jump;437B9E..BAC resets jump/mode/turn
@@ -405,7 +516,8 @@ public sealed class LabSimulation
throw new NotSupportedException("Original ordinary-body subset cannot use the provisional dynamic resolver");
var before = Position;
var result = originalBody!.Step(new(ActorRoot, Velocity, Vector3.UnitY * extraAirAcceleration,
pendingImpulse, Grounded, PublishedSpeed), FixedStepClock.Step, InteractionRadius);
pendingImpulse, Grounded, PublishedSpeed), FixedStepClock.Step, InteractionRadius,BodyFactor);
if (result.SupportHit is { } hit) retainedSupportMaterial=originalBody.MaterialFor(hit);
Position = result.Body.Position - Vector3.UnitY * rootHeight;
Velocity = result.Body.Velocity;
pendingImpulse = result.Body.Impulse;
+2
View File
@@ -34,6 +34,8 @@ public sealed class OriginalBodyPhysics
this.collision = collision;
}
public int? MaterialFor(SupportHit hit) => collision.MaterialFor(hit);
public OrdinaryBodyStep Step(OrdinaryBodyState body, float seconds,
float radius = OriginalBodySupport.JimmyRadius, float factor = OriginalBodySupport.JimmyFactor,
float friction = .8f, float suppressionScale = .5f, bool geometryEnabled = true)
+3 -3
View File
@@ -58,15 +58,15 @@ public sealed class OriginalCameraRay
}
/// <summary>
/// LV1B/VR04/LEV1 complete game slot134 is475CD0 (false), so only the proven
/// LV1B/VR01/VR04/LEV1 complete game slot134 is475CD0 (false), so only the proven
/// NC/checkpoint gates apply. Reject other levels rather than inventing masks.
/// Prepared source metadata is required; raw render visibility is irrelevant.
/// </summary>
public static OriginalCameraRay FromRouteScene(Mesh mesh, string levelCode)
{
ArgumentNullException.ThrowIfNull(mesh);
if (levelCode is not ("LV1B" or "VR04" or "LEV1"))
throw new NotSupportedException("Static camera game-filter recovery currently covers LV1B, VR04 and LEV1");
if (levelCode is not ("LV1B" or "VR01" or "VR04" or "LEV1"))
throw new NotSupportedException("Static camera game-filter recovery covers the route and VR01");
if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3)
throw new InvalidDataException("Original camera query requires source polygon metadata");
var polygons = new CameraRayPolygon[mesh.CollisionPolygons.Length];
+6 -2
View File
@@ -23,6 +23,7 @@ public sealed class OriginalStaticCollision
{
private readonly Dictionary<int, List<CameraRayPolygon>> walls = [];
private readonly Dictionary<int, List<SupportTriangle>> all = [];
private readonly Dictionary<(int Shape,int Polygon),int?> materialIds = [];
public int PolygonCount { get; }
public int WallPolygonCount { get; }
public bool HasSpecialPlayerContacts { get; }
@@ -38,6 +39,7 @@ public sealed class OriginalStaticCollision
Finite(t.A); Finite(t.B); Finite(t.C); Finite(polygon.StoredNormal);
if (!identities.Add((t.ShapeId, t.PolygonId)))
throw new InvalidDataException("Source static collision needs one triangle per polygon");
materialIds.Add((t.ShapeId,t.PolygonId),polygon.MaterialId);
var min = Vector3.Min(t.A, Vector3.Min(t.B, t.C));
var max = Vector3.Max(t.A, Vector3.Max(t.B, t.C));
foreach (var cell in Rectangle(new(Cell(min.X), Cell(max.X), Cell(min.Z), Cell(max.Z))))
@@ -59,8 +61,8 @@ public sealed class OriginalStaticCollision
public static OriginalStaticCollision FromRouteScene(Mesh mesh, string level)
{
ArgumentNullException.ThrowIfNull(mesh);
if (level is not ("LV1B" or "VR04" or "LEV1"))
throw new NotSupportedException("Original static game-filter recovery covers only the three route scenes");
if (level is not ("LV1B" or "VR01" or "VR04" or "LEV1"))
throw new NotSupportedException("Original static game-filter recovery covers the route and VR01");
if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3)
throw new InvalidDataException("Source static collision requires original polygon metadata");
if (!mesh.HasCollisionMaterialIds)
@@ -76,6 +78,8 @@ public sealed class OriginalStaticCollision
}));
}
public int? MaterialFor(SupportHit hit) => materialIds.GetValueOrDefault((hit.ShapeId,hit.PolygonId));
public StaticCollisionMove Move(Vector3 previous, Vector3 delta, float radius,
StaticCollisionContext context, bool edges = true, bool lowerEdges = false, bool geometryEnabled = true)
{
+31
View File
@@ -0,0 +1,31 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>Stored current-atlas material state. Source alpha/FC requests and
/// late direct RGBA writes have different owners and must retain their order.</summary>
public sealed class PlayerAppearance
{
public Vector4 Color { get; private set; } = Vector4.One;
public bool BlendEnabled { get; private set; }
public bool Conventional { get; private set; }
public MeshBlend Blend => !BlendEnabled ? MeshBlend.Opaque : Conventional ? MeshBlend.Alpha : MeshBlend.Additive;
public void SetAlpha(float alpha)
{
if (!float.IsFinite(alpha) || alpha > 1) throw new ArgumentOutOfRangeException(nameof(alpha));
BlendEnabled = alpha > 0;
Color = alpha > 0 ? new(1,1,1,alpha) : Vector4.One;
Conventional = alpha <= 0;
}
public void SetBlend(bool conventional) => Conventional = conventional;
public void SetColor(Vector4 color)
{
if (!float.IsFinite(color.X+color.Y+color.Z+color.W)
|| color.X<0 || color.Y<0 || color.Z<0 || color.W<0 || color.W>1)
throw new ArgumentOutOfRangeException(nameof(color));
Color = color;
}
public void Reset() { Color=Vector4.One; BlendEnabled=false; Conventional=false; }
}
+13 -3
View File
@@ -20,6 +20,7 @@ public sealed class PlayerSceneBinding : IDisposable
director.GadgetReleaseRequested += Release;
inventory.GadgetSelected += Selected;
player.Invisible.EquippedChanged += InvisibleEquipped;
player.DefaultGadgetRequested += DefaultGadget;
Selected(inventory.SelectedGadget);
}
@@ -27,8 +28,10 @@ public sealed class PlayerSceneBinding : IDisposable
{
var acceptsInput = director.Controlled || player.Noclip;
player.Step(input, acceptsInput, director.ControlledTag != null);
if (player.GadgetMode==0 && player.Grounded && director.FindActor(tag) is{} actor) actor.Animation="STOP";
var rotation=director.FindActor(tag)?.Rotation ?? Vector3.Zero;
director.SyncActor(tag, player.ActorRoot, rotation with { Y = player.Yaw });
director.SyncActor(tag,player.ActorRoot,player.TracksBubbleOrientation
? new(player.Pitch,player.Yaw,player.Roll) : rotation with{Y=player.Yaw});
return acceptsInput;
}
@@ -36,6 +39,7 @@ public sealed class PlayerSceneBinding : IDisposable
{
if (!string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) return;
if (action == ScriptPreparation.StopMotion) player.PrepareForScript();
else if (action == ScriptPreparation.FlattenOrientation) player.FlattenOrientation();
else if (action == ScriptPreparation.ReleaseGadget)
Release(actor);
}
@@ -45,12 +49,17 @@ public sealed class PlayerSceneBinding : IDisposable
if (!string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) return;
//427FF0 switches raw mode, not display selection. A rejected Invisible
//equip can leave display2 with raw mode-1; cleanup does not equip it.
if (player.GadgetMode == 2 || inventory.SelectedGadget is -1 or 3)
if (player.GadgetMode is 0 or 2 || inventory.SelectedGadget is -1 or 3)
{ inventory.SelectGadget(-1); player.GadgetMode = -1; }
else if (player.GadgetMode != -1) UnsupportedGadgetCleanups++;
}
private void Selected(int item) => player.GadgetMode = GadgetScreen.EquippedMode(item);
private void Selected(int item)
{
if (item==0 && director.FindActor(tag) is{} actor) player.SeedBubbleTilt(actor.Rotation);
player.GadgetMode=GadgetScreen.EquippedMode(item);
}
private void DefaultGadget() => inventory.SelectGadget(-1);
private void InvisibleEquipped(bool equipped)
{
@@ -74,5 +83,6 @@ public sealed class PlayerSceneBinding : IDisposable
director.GadgetReleaseRequested -= Release;
inventory.GadgetSelected -= Selected;
player.Invisible.EquippedChanged -= InvisibleEquipped;
player.DefaultGadgetRequested -= DefaultGadget;
}
}
+1 -1
View File
@@ -18,7 +18,7 @@ public static class RecoveredMotion
// Deliberately per invocation: original increments omit dt. Call cadence is
// not yet verified. Rendering must not directly choose simulation cadence.
public static float AddSpeed(float speed) => MathF.Min(speed + SpeedIncrement, MaximumSpeed);
public static float AddSpeed(float speed, float maximumSpeed = MaximumSpeed) => MathF.Min(speed + SpeedIncrement, maximumSpeed);
public static float ReleaseSpeed(float speed) => speed > 0
? MathF.Max(0, speed - SpeedDecay) : MathF.Min(0, speed + SpeedDecay);
+2 -2
View File
@@ -54,12 +54,12 @@ public sealed class SceneInventory
}
}
public void SelectGadget(int item)
public void SelectGadget(int item, bool equip = true)
{
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);
if (equip) GadgetSelected?.Invoke(item);
}
public int[] Snapshot() => states.ToArray();
+41
View File
@@ -0,0 +1,41 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct Vr01FloorEffect(bool Entered, bool Damaged);
/// <summary>Textured retained-support callback for actual VR01 IDs0..4/111.
/// Other damage flags, floor classes and footstep-loop playback remain outside.</summary>
public sealed class Vr01FloorState
{
public bool InLava { get; private set; }
public bool Flashing { get; private set; }
public float Timer { get; private set; }
public int SoundSelector { get; private set; } = 5;
public Vr01FloorEffect Visit(int? material, int rawMode)
{
//Null means no eligible textured support. The actual VR01 profile's
//used material IDs all have source-verified texture links.
if (material == null) return default;
if (material is not (0 or 1 or 2 or 3 or 4 or 111))
throw new NotSupportedException("Outside the recovered VR01 floor profile");
var lava = material == 111;
var entered = lava && !InLava;
var damaged = lava && !Flashing && rawMode != 0;
InLava = lava; SoundSelector = lava ? 35 : 5;
if (damaged) { Flashing=true; Timer=0; }
return new(entered,damaged);
}
public void Step(float seconds, Action<Vector4> color)
{
if (!float.IsFinite(seconds) || seconds<0 || seconds>=1) throw new ArgumentOutOfRangeException(nameof(seconds));
ArgumentNullException.ThrowIfNull(color);
if (!Flashing) return;
var sum = (double)Timer + seconds;
Timer = (float)sum;
if (sum>4) { Flashing=false; color(Vector4.One); return; }
var pulse = (float)((Math.Sin(sum*20)+1)*.5);
color(new(pulse,1,pulse,1));
}
public void Reset() { InLava=Flashing=false; Timer=0; SoundSelector=5; }
}
+59 -9
View File
@@ -88,6 +88,7 @@ internal static class Program
--smoke-jetpack 300-step powered steering/jump check in VR04
--smoke-shrink-ray Fire at an actual VR04 soldier; explicit player-placement fixture
--smoke-invisible Accelerated recharge/activation/flash/expiry/unequip fixture in VR03
--smoke-bubble VR01 expand/throttle/bounce/cleanup/fade input fixture
--gadget-menu Render original gadget panel (--skip-intro); fixture owns item3
--smoke-gadget-menu SDL menu input/pause/selection/practice/Return check (24 frames)
--smoke-jump-key NAME Replay using shift/right-shift/insert/keypad0/right-mouse
@@ -258,6 +259,7 @@ internal static class Program
var jetpackSmoke = args.Contains("--smoke-jetpack");
var shrinkSmoke = args.Contains("--smoke-shrink-ray");
var invisibleSmoke = args.Contains("--smoke-invisible");
var bubbleSmoke = args.Contains("--smoke-bubble");
var carlSmoke = args.Contains("--smoke-carl-cutscene");
var controlPhaseSmoke = args.Contains("--smoke-control-phases");
var objectiveWindowSmoke = args.Contains("--smoke-objective-window");
@@ -278,7 +280,7 @@ internal static class Program
var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window")
&& animationPath == null && !args.Contains("--time");
var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time")
|| args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke;
|| args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke;
if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window")))
throw new ArgumentException("Story playback requires its own simulation mode.");
if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode.");
@@ -307,6 +309,7 @@ internal static class Program
ShrinkRayVisuals? rayVisuals = null;
ShrinkSoldierVisuals? soldierVisuals = null;
JetpackVisuals? jetpackVisuals = null;
BubbleVisuals? bubbleVisuals = null;
var practice = new PracticePrompt();
ObjectivePanel? objectivePanel = null;
var patrols = new Dictionary<string, ActorPatrol>(StringComparer.OrdinalIgnoreCase);
@@ -335,13 +338,13 @@ internal static class Program
var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase"));
if (walking)
{
var cameraRay = level!.Code is "LV1B" or "VR04" or "LEV1"
var cameraRay = level!.Code is "LV1B" or "VR01" or "VR04" or "LEV1"
? OriginalCameraRay.FromRouteScene(world, level.Code) : null;
debugCameraRay = cameraRay;
simulation = new LabSimulation(new SceneCollision(world), standingPose, originalStart.Position, originalStart.Rotation.Y,
cameraRay == null ? null : (look, eye) => cameraRay.Trace(look, eye),
cameraRay == null ? null : (start, end) => cameraRay.TraceGeometry(start, end),
level.Code == "VR04" ? OriginalStaticCollision.FromRouteScene(world,level.Code) : null, energy)
level.Code is "VR01" or "VR04" ? OriginalStaticCollision.FromRouteScene(world,level.Code) : null, energy)
{ LevelCode = level.Code, InputAfterPlayerUpdate = carriedSave != null };
if (carriedPlayer != null)
{
@@ -374,12 +377,13 @@ internal static class Program
storyTasks = tasks;
director = new SceneDirector(level!, tasks, resources.Duration);
interactions = new SceneInteractions(director, tasks, save);
gadgetScreen = new GadgetScreen(interactions.Inventory);
gadgetScreen = new GadgetScreen(interactions.Inventory,()=>simulation!.GadgetMode);
interactions.Inventory.ApplyLevelAvailability(level!.Code);
objectivePanel = new ObjectivePanel(interactions.CurrentObjective);
interactions.ObjectiveChanged += objectivePanel.Select;
simulation!.Energy = interactions.Energy;
simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3);
simulation.ScoreChanged += interactions.ChangeScore;
if (level.Code is "LV1B" or "VR04" or "LEV1")
{
gadgets = new SceneGadgets(director,interactions.Inventory,simulation,world);
@@ -439,6 +443,8 @@ internal static class Program
DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius);
jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")));
mesh = jetpackVisuals.Mesh;
bubbleVisuals = new(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!,"..")));
mesh = bubbleVisuals.Mesh;
if (gadgets != null)
{
rayVisuals = new ShrinkRayVisuals(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),root);
@@ -480,13 +486,15 @@ internal static class Program
var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture);
if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless)
throw new ArgumentException("Story time must be0..3600 seconds in headless mode.");
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : shrinkSmoke ? "90" : invisibleSmoke ? "8" : gadgetWindowSmoke ? "24" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0"));
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : shrinkSmoke ? "90" : invisibleSmoke || bubbleSmoke ? "8" : gadgetWindowSmoke ? "24" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0"));
if (gadgetWindowSmoke && (headless || level?.Code != "LV1B" || loadedSave != null || frames < 24))
throw new ArgumentException("Gadget menu SDL fixture requires a fresh windowed lab and24 frames");
if (shrinkSmoke && (level?.Code != "VR04" || gadgets == null || frames < 60))
throw new ArgumentException("Shrink-ray smoke requires actual VR04 and at least60 frames");
if (invisibleSmoke && (level?.Code != "VR03" || frames < 8 || loadedSave != null))
throw new ArgumentException("Invisible smoke requires a fresh VR03 and at least8 frames");
if (bubbleSmoke && (level?.Code!="VR01" || frames<8 || loadedSave!=null))
throw new ArgumentException("Bubble smoke requires a fresh VR01 and at least8 frames");
if (controlPhaseSmoke && (level?.Code != "LV1B" || loadedSave != null || frames < 32 || director == null))
throw new ArgumentException("Control-phase fixture needs a fresh lab and at least32 frames");
if (toolsSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open))
@@ -520,12 +528,19 @@ internal static class Program
var shrinkPhaseMask = 0;
var sawShrinkKey = false;
InvisibleSmoke? invisibleFixture = null;
BubbleSmoke? bubbleFixture = null;
var sawBubbleKeys=0;
Console.WriteLine($"Scene presentation: revision={renderer.SceneRevision}, windows={presentation.WindowCreationCount}, renderers={presentation.RendererCreationCount}, window ID={(window == 0 ? 0 : Sdl.SDL_GetWindowID(window))}, size={renderer.Width}x{renderer.Height}.");
{
using var audio = Option(args, "--audio") is { } audioFile
? new SdlAudio(audioFile, args.Contains("--loop-audio"), debugMenu.Open) : null;
using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null;
sceneAudio?.SetPaused(debugMenu.Open);
if (simulation!=null)
{
simulation.GadgetSound += (id,loop) => sceneAudio?.Effect(id,loop?"bubble":null);
simulation.BubbleSoundStopped += () => sceneAudio?.StopLoop("bubble");
}
if (gadgets != null)
{
gadgets.Sound += (id,loop) => sceneAudio?.Effect(id,loop ? "shrink-ray" : null);
@@ -568,7 +583,7 @@ internal static class Program
Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}, retained player input order={simulation.InputAfterPlayerUpdate}, gadget availability={interactions.Inventory.State(0, 3)}.");
if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions");
}
if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (gadgetWindowSmoke) { interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3); }
if (controlPhaseSmoke)
{
@@ -649,6 +664,7 @@ internal static class Program
gadgetScreen.Point(new(200,380), level!.Code, storyTasks!.Get("SCENE"));
}
if (invisibleSmoke) invisibleFixture = new(simulation!,interactions!.Inventory);
if (bubbleSmoke) bubbleFixture = new(simulation!,interactions!.Inventory);
if (shrinkSmoke)
{
//Explicit test placement near an ACTUAL authored soldier.
@@ -822,6 +838,11 @@ internal static class Program
: "INVISIBLE OWNED - ENERGY REQUIRED TO EQUIP"; break;
case DebugAction.UnequipGadget when interactions != null:
interactions.Inventory.SelectGadget(-1); debugMenu.Message = "GADGET UNEQUIPPED"; break;
case DebugAction.GiveBubble when interactions != null:
interactions.Inventory.SetState(0,0,1); interactions.Inventory.SelectGadget(0);
debugMenu.Message = simulation?.GadgetMode==0 ? "BUBBLE EQUIPPED - FIRE/UP ACCELERATES, JUMP BOUNCES HIGH"
: simulation?.Bubble.Collapsing==true ? "WAIT FOR THE BUBBLE TO FADE BEFORE REEQUIPPING" : "ENERGY REQUIRED TO EQUIP";
break;
case DebugAction.CameraObstruction when debugCameraRay != null:
debugCameraRay.Enabled = !debugCameraRay.Enabled; debugMenu.Message = "STATIC CAMERA QUERY TOGGLED"; break;
case DebugAction.MuteMusic or DebugAction.MuteSpeech or DebugAction.MuteEffects when sceneAudio != null:
@@ -887,6 +908,11 @@ internal static class Program
}
while (running)
{
bubbleFixture?.BeforeFrame(count,(key,down)=>
{
var e=new Sdl.Event{Type=down?Sdl.KeyDown:Sdl.KeyUp,Scancode=key,Down=down?(byte)1:(byte)0};
if(!Sdl.SDL_PushEvent(ref e))throw new InvalidOperationException(Sdl.Error);
},headless);
invisibleFixture?.BeforeFrame(count,(key,down)=>
{
var e = new Sdl.Event {Type=down?Sdl.KeyDown:Sdl.KeyUp,Scancode=key,Down=down?(byte)1:(byte)0};
@@ -938,6 +964,8 @@ internal static class Program
}
while (!headless && Sdl.SDL_PollEvent(out var e))
{
if (bubbleSmoke && e.Type==Sdl.KeyDown)
sawBubbleKeys |= e.Scancode switch {224=>1,80=>2,225=>4,43=>8,_=>0};
if (e.Type is Sdl.Quit or 0x210) running = false;
if (e.Type is Sdl.WindowResized or Sdl.WindowPixelSizeChanged) renderer.Resize();
if (e.Type is Sdl.WindowFocusLost or Sdl.WindowMinimized)
@@ -1062,12 +1090,13 @@ internal static class Program
}
}
if (debugMenu.Open) animationStarted += elapsed;
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
{
var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed);
var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || invisibleSmoke || bubbleSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed);
for (var step = 0; step < steps; step++)
{
var input = carlSmoke || controlPhaseSmoke ? new PlayerInput(true, false, true, false, true)
: bubbleSmoke && headless ? BubbleSmoke.Input(count)
: invisibleSmoke && headless ? new PlayerInput(false,false,false,false,false,Fire:count==1)
: shrinkSmoke && headless ? new PlayerInput(false,false,false,false,false,Fire:true)
: jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps)
@@ -1149,6 +1178,7 @@ internal static class Program
if (gadgets != null) rayVisuals!.Update(mesh,gadgets.Ray,simulation!.Steps / 60d);
if (shrinkSmoke && gadgets!.Ray.Visible) shrinkPhaseMask |= 1 << gadgets.Ray.TexturePhase;
jetpackVisuals?.Update(mesh, simulation!);
bubbleVisuals?.Update(mesh,simulation!.Bubble,simulation.BubbleRoot,renderEye,renderTarget);
spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh);
objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true
&& director is { Controlled: true, InventoryEnabled: true });
@@ -1179,6 +1209,9 @@ internal static class Program
BurnRemaining = simulation?.JetpackRemaining ?? 0, JetpackAvailability = interactions?.Inventory.State(0, 3) ?? 0,
InvisibleRemaining = simulation?.Invisible.Remaining ?? 0, InvisibleRecharge = simulation?.Invisible.Recharge ?? 0,
Targetable = simulation?.Invisible.Targetable ?? true,
BubblePhase = simulation?.Bubble.Active==true ? "ACTIVE" : simulation?.Bubble.Expanding==true ? "EXPAND"
: simulation?.Bubble.Collapsing==true ? "FADE" : "OFF",
BodyRadius = simulation?.InteractionRadius ?? 60, BodyFactor=simulation?.BodyFactor ?? 1.265f,
Objective = interactions?.CurrentObjective ?? 0, ObjectiveTime = objectivePanel?.Elapsed ?? 0,
CameraObstruction = debugCameraRay?.Enabled, CameraPolygons = debugCameraRay?.PolygonCount ?? 0,
CameraWallPolygons = debugCameraRay?.WallPolygonCount ?? 0, CameraTests = debugCameraRay?.LastTriangleTests ?? 0,
@@ -1208,9 +1241,20 @@ internal static class Program
mesh.Vertices.AsSpan(characterOffset, animations.Current.Base.Vertices.Length), characterModel);
}
if (simulation != null && characterDraw != null)
PlayerGadgetMaterial.Apply(characterDraw, simulation.Invisible);
{
PlayerGadgetMaterial.Apply(characterDraw,simulation.Appearance);
var color=simulation.Appearance.Color;
for(var i=0;i<animations!.Current.Base.Vertices.Length;i++)
mesh.Vertices[characterOffset+i].Color *= new Vector3(color.X,color.Y,color.Z);
}
renderer.UpdateVertices(mesh.Vertices);
renderer.Render(view * projection);
if (bubbleFixture!=null)
{
bubbleFixture.AfterFrame(count);
if(BubbleSmoke.StageName(count) is{} stage && Option(args,"--screenshot") is{} capture)
renderer.SavePpm(Path.ChangeExtension(capture,$".{stage}.ppm"));
}
if (invisibleFixture != null)
{
invisibleFixture.AfterFrame(count,characterDraw!);
@@ -1485,6 +1529,12 @@ internal static class Program
if (!headless) Console.WriteLine($"Invisible SDL primary received: {sawShrinkKey}.");
if (!invisibleFixture.Passed || !headless && !sawShrinkKey) return 2;
}
if (bubbleFixture!=null)
{
Console.WriteLine(bubbleFixture.Report);
if(!headless)Console.WriteLine($"Bubble SDL input received: {sawBubbleKeys==15}.");
if(!bubbleFixture.Passed || !headless && sawBubbleKeys!=15)return 2;
}
if (shrinkSmoke)
{
var renderedHeight = soldierVisuals!.RenderedHeight(shrinkVictim!.Actor.Tag,mesh);
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Assets/*.cs" Link="Assets/%(Filename)%(Extension)" />
<Compile Include="../../src/GamePort/Game/*.cs" Link="Game/%(Filename)%(Extension)" />
</ItemGroup>
</Project>
+152
View File
@@ -0,0 +1,152 @@
using System.Numerics;
using GamePort.Game;
var tests = new (string Name, Action Check)[]
{
("mode2 fire throttles without forward arrows and caps at current maximum", FireThrottle),
("turn limit 50, left precedence, release and pose priorities", TurnAndPose),
("supported input reduction precedes brake and permits negative crossing", SupportInput),
("coast threshold and air brake retain source ordering", CoastAndBrake),
("supported XZ 112.5 halves only later published scalar to 56.25", PublishedScalarOrder),
("held bounce 900 and repeat sound versus released 300 without sound", BounceBranches),
("unsupported apply retains vertical velocity and scalar", Unsupported),
("zero incoming velocity suppresses yaw and side, including nonzero scalar", Stationary),
("quantized pitch cosine scales only horizontal forward velocity", QuantizedPitch),
("nonzero incoming velocity turns and adds source lateral term", Lateral),
("finite input and bounded timestep validation", InvalidInputs),
};
foreach (var (name, check) in tests)
{
check();
Console.WriteLine($"PASS {name}");
}
Console.WriteLine($"Bubble motion checks: {tests.Length} passed. Source arithmetic/port regressions; no original gameplay execution.");
static PlayerInput Input(bool forward = false, bool backward = false, bool left = false,
bool right = false, bool fire = false) => new(forward, backward, left, right, false, Fire: fire);
static void FireThrottle()
{
var fire = BubbleMotion.StepInput(0, 0, Input(fire: true), false, .1f);
Check(fire == BubbleMotion.StepInput(0, 0, Input(forward: true), false, .1f), "fire matches forward");
Near(fire.Speed, 30, 0, "source per-call increment");
Near(fire.TargetPitch, -10, 0, "forward target pitch");
Near(BubbleMotion.StepInput(1340, 0, Input(fire: true), false, .1f).Speed, 1350, 0, "Bubble cap");
Near(BubbleMotion.StepInput(640, 0, Input(forward: true), false, .1f, 650).Speed, 650, 0, "caller maximum");
}
static void TurnAndPose()
{
var both = BubbleMotion.StepInput(100, 49, Input(left: true, right: true), false, .5f);
Near(both.TurnRate, 50, 0, "left precedence and positive cap");
Near(both.TargetRoll, -12.5f, 0, "source lean sign");
Near(BubbleMotion.StepInput(100, -49, Input(right: true), false, .5f).TurnRate, -50, 0, "negative cap");
Near(BubbleMotion.StepInput(100, -20, Input(), false, .5f).TurnRate, 0, 0, "release crosses zero");
var throttleBrake = BubbleMotion.StepInput(100, 10, Input(forward: true, backward: true, left: true), false, .1f);
Near(throttleBrake.Speed, 112.5f, 0, "forward before backward");
Near(throttleBrake.TargetPitch, -10, 0, "throttle pitch wins");
Near(throttleBrake.TargetRoll, -5, 0, "updated turn drives lean");
Near(BubbleMotion.StepInput(100, 0, Input(backward: true), false, .1f).TargetPitch, 10, 0, "brake pitch");
Near(BubbleMotion.StepInput(100, 0, Input(), false, .1f).TargetPitch, 0, 0, "coast pitch");
}
static void SupportInput()
{
Near(BubbleMotion.StepInput(100, 0, Input(), true, .1f).Speed, 82.5f, 0, "supported coast");
Near(BubbleMotion.StepInput(100, 0, Input(backward: true), true, .1f).Speed, 47.5f, 0, "support decay then full brake");
var crossed = BubbleMotion.StepInput(5, 0, Input(), true, .1f).Speed;
Near(crossed, -12.5f, 0, "unclamped source crossing");
Near(BubbleMotion.StepInput(crossed, 0, Input(), true, .1f).Speed, 0, 0, "following supported input clears negative");
}
static void CoastAndBrake()
{
Near(BubbleMotion.StepInput(1350, 0, Input(), false, .1f).Speed, 1332.5f, 0, "high coast decay");
Near(BubbleMotion.StepInput(1200, 0, Input(), false, .1f).Speed, 1200, 0, "below coast threshold");
Near(BubbleMotion.StepInput(5, 0, Input(backward: true), false, .1f).Speed, 0, 0, "positive brake clamps");
Near(BubbleMotion.StepInput(-5, 0, Input(backward: true), false, .1f).Speed, 0, 0, "negative brake clamps");
}
static void PublishedScalarOrder()
{
var steering = BubbleMotion.StepInput(100, 0, Input(forward: true), true, .1f);
Near(steering.Speed, 112.5f, 0, "supported input scalar");
var applied = BubbleMotion.StepApply(steering.Speed, steering.TurnRate, 0, 0, Vector3.UnitZ, true, false, .1f);
Near(applied.Velocity.Z, 112.5f, 0, "XZ composed before bounce decay");
Near(applied.Speed, 56.25f, 0, "only later published scalar halves");
Near(applied.Velocity.Y, 300, 0, "automatic released bounce");
}
static void BounceBranches()
{
var held = BubbleMotion.StepApply(100, 0, 0, 0, new(0, -800, 10), true, true, .1f);
Check(held.Velocity == new Vector3(0, 900, 100) && held.Boing, "direct held velocity and sound");
Near(held.Speed, 100, 0, "held bounce retains scalar");
Check(BubbleMotion.StepApply(100, 0, 0, 0, held.Velocity, true, true, .1f).Boing, "no invented edge latch");
var released = BubbleMotion.StepApply(100, 0, 0, 0, new(0, -800, 10), true, false, .1f);
Check(released.Velocity == new Vector3(0, 300, 100) && !released.Boing, "released velocity without boing");
Near(released.Speed, 50, 0, "released scalar");
}
static void Unsupported()
{
var applied = BubbleMotion.StepApply(100, 0, 0, 0, new(0, -99, 10), false, true, .1f);
Near(applied.Velocity.Y, -99, 0, "unsupported liveY retained");
Near(applied.Speed, 100, 0, "unsupported scalar retained");
Check(!applied.Boing, "unsupported jump produces no sound");
}
static void Stationary()
{
var applied = BubbleMotion.StepApply(100, 50, 0, 0, Vector3.Zero, false, false, .1f);
Near(applied.Yaw, 0, 0, "zero incoming velocity skips direct yaw");
Check(applied.Velocity == new Vector3(0, 0, 100), "forward still starts, side remains zero");
}
static void QuantizedPitch()
{
const float pitch = 17.123f;
var expected = LabSimulation.Trig(pitch).Cos * 100;
var applied = BubbleMotion.StepApply(100, 0, 0, pitch, new(0, -12, 1), false, false, .1f);
Near(applied.Velocity.Z, expected, 0, "same quantized cosine helper");
Near(applied.Velocity.Y, -12, 0, "transformed forwardY deliberately unused");
Check(applied.Velocity.Z != MathF.Cos(pitch * MathF.PI / 180) * 100, "continuous cosine would differ");
}
static void Lateral()
{
var applied = BubbleMotion.StepApply(100, 50, 0, 0, Vector3.UnitY, false, false, .1f);
Near(applied.Yaw, 5, 0, "direct yaw from nonzero incomingY");
var (sin, cos) = LabSimulation.Trig(5);
var side = 50 * .0181818176060915f * (1 - .8f) * 100;
Near(applied.Velocity.X, -sin * 100 + cos * side, 0, "yaw-only lateralX");
Near(applied.Velocity.Z, cos * 100 + sin * side, 0, "yaw-only lateralZ");
}
static void InvalidInputs()
{
foreach (var seconds in new[] { -1f, 1f, float.NaN, float.PositiveInfinity })
{
Throws(() => BubbleMotion.StepInput(0, 0, Input(), false, seconds));
Throws(() => BubbleMotion.StepApply(0, 0, 0, 0, Vector3.Zero, false, false, seconds));
}
Throws(() => BubbleMotion.StepInput(float.NaN, 0, Input(), false, .1f));
Throws(() => BubbleMotion.StepInput(0, 0, Input(), false, .1f, 0));
Throws(() => BubbleMotion.StepApply(0, 0, 0, 0, new(float.NaN, 0, 0), false, false, .1f));
}
static void Check(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
static void Near(float actual, float expected, float tolerance, string message) =>
Check(float.IsFinite(actual) && MathF.Abs(actual - expected) <= tolerance,
$"{message}: expected {expected}, got {actual}");
static void Throws(Action action)
{
try { action(); }
catch (ArgumentOutOfRangeException) { return; }
throw new InvalidOperationException("Expected bounded-input rejection");
}
@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
<ItemGroup><Compile Include="Program.cs" /><Compile Include="../../src/GamePort/Assets/*.cs" />
<Compile Include="../../src/GamePort/Game/*.cs" /><Compile Include="../../src/GamePort/Application/PlayerGadgetMaterial.cs" />
</ItemGroup>
</Project>
+149
View File
@@ -0,0 +1,149 @@
using System.Numerics;
using System.Buffers.Binary;
using System.Text;
using GamePort.Assets;
using GamePort.Game;
using GamePort.Application;
var count=0;
void Check(bool value,string message){if(!value)throw new Exception(message);}
void Near(float actual,float expected,string message)=>Check(MathF.Abs(actual-expected)<.002f,$"{message}: {actual} != {expected}");
void Test(string name,Action action){action();count++;Console.WriteLine($"PASS {name}");}
Mesh Floor(int material=0)=>new(
[new(new(-4000,0,-4000),Vector2.Zero,Vector3.One),new(new(4000,0,-4000),Vector2.Zero,Vector3.One),
new(new(4000,0,4000),Vector2.Zero,Vector3.One),new(new(-4000,0,4000),Vector2.Zero,Vector3.One)],
[0,1,2,0,2,3]){HasCollisionMaterialIds=true,CollisionPolygons=[new(0,0,Vector3.UnitY,"floor","floor",material),new(0,1,Vector3.UnitY,"floor","floor",material)]};
LabSimulation Player(string level="VR01",Mesh? world=null)
{
world??=Floor();
return new(new SceneCollision(world),AseMesh.Load("../Original/ASE/jimstop.ase"),new(0,80,0),0,
originalCollision:OriginalStaticCollision.FromRouteScene(world,"VR01")){LevelCode=level};
}
void Until(LabSimulation player,Func<bool> done,PlayerInput input=default)
{for(var i=0;i<700&&!done();i++)player.Step(input);Check(done(),"requested phase not reached");}
Test("six copied-original radius/factor body references",()=>{
var physics=new OriginalBodyPhysics(OriginalStaticCollision.FromRouteScene(Floor(),"VR01"));
foreach(var c in new[]{
(66.4f,0f,160f,.415f,66.4000015f,0f,true),(26f,0f,160f,.415f,66.4000015f,0f,true),
(75.9f,0f,160f,.415f,75.6777802f,-13.333334f,false),(66.4f,0f,60f,1.265f,75.9000015f,0f,true),
(66.4f,300f,160f,.415f,71.1777802f,286.666656f,false),(66.4f,900f,160f,.415f,81.1777802f,886.666687f,false)})
{
var r=physics.Step(new(new(0,c.Item1,0),new(0,c.Item2,0),Vector3.Zero,Vector3.Zero),1f/60,c.Item3,c.Item4);
Near(r.Body.Position.Y,c.Item5,"root");Near(r.Body.Velocity.Y,c.Item6,"velocity");Check(r.Body.Supported==c.Item7,"support");
}
});
Test("equip and cleanup retain logical root, queued impulse and source650 maximum",()=>{
var p=Player();p.Step(new(false,false,false,false,true));var root=p.ActorRoot;var impulse=p.PendingImpulse;
p.GadgetMode=0;
Check(p.ActorRoot==root&&p.PendingImpulse==impulse&&impulse.Y==550,"equip must not recenter/reset queued impulse");
Check(p.MovementMode==2&&p.InteractionRadius==160&&p.BodyFactor==.415f&&p.MaximumSpeed==1350,"source body/controller settings");
p.GadgetMode=-1;
Check(p.ActorRoot==root&&p.PendingImpulse==impulse&&p.MovementMode==0&&p.MaximumSpeed==650&&p.BodyFactor==1.265f&&p.InteractionRadius==60,
"cleanup changes its fields without a teleport or blanket physics clear");
});
Test("mode2 persists through repeated automatic300 bounces without550/jetpack",()=>{
var p=Player();p.JetpackInventoryState=()=>1;p.GadgetMode=0;var sounds=new List<int>();p.GadgetSound+=(id,_)=>sounds.Add(id);
Until(p,()=>p.BubbleBounces>=3);
Check(p.GadgetMode==0&&p.MovementMode==2&&p.Velocity.Y==300&&p.Jumps==0&&p.Bursts==0,"automatic bounce path");
Check(p.Pose==PlayerPose.Idle&&!sounds.Contains(106),"supported STOP, released bounce has no boing");
});
Test("held supported bounce is direct900 and requests106",()=>{
var p=Player();p.GadgetMode=0;var sounds=new List<int>();p.GadgetSound+=(id,_)=>sounds.Add(id);
Until(p,()=>p.BubbleBounces>0,new(false,false,false,false,true));
Check(p.Velocity.Y==900&&sounds.SequenceEqual(new[]{106})&&p.PendingImpulse==Vector3.Zero&&p.MovementMode==2,"direct liveY/source sound");
});
Test("controlled drain, independent sprite clock and tutorial bypass",()=>{
var p=Player("LV1B");p.GadgetMode=0;p.Step(default);Near(p.Energy,20-1f/120,"ordinary controlled cost");
var root=p.BubbleRoot;var energy=p.Energy;var time=p.Bubble.Timer;var controllers=p.ControllerSteps;
p.Step(default,false,false);
Check(p.Energy==energy&&p.Bubble.Timer>time&&p.BubbleRoot==root&&p.ControllerSteps==controllers,"raw control loss does not stop effect clock or move captured sprite");
var vr=Player();vr.GadgetMode=0;for(var i=0;i<90;i++)vr.Step(default);
Check(vr.Energy==20&&vr.Bubble.Active,"VR01 exemption and expansion");
});
Test("depletion cleans once and notifies selection owner without restarting loop",()=>{
var p=Player("LV1B");p.Energy=.001f;var director=new SceneDirector(new("LV1B",[Entity("3JIM","JIM1")]),new TaskStates([]),(_,_)=>1);
var bag=new SceneInventory(new int[19]);bag.SetState(0,0,1);using var binding=new PlayerSceneBinding(director,p,bag,"JIM1");
var starts=0;var stops=0;var warnings=new List<int>();p.GadgetSound+=(_,loop)=>{if(loop)starts++;};p.BubbleSoundStopped+=()=>stops++;p.EnergySound+=warnings.Add;
bag.SelectGadget(0);binding.Step(default);
Check(p.Energy==0&&p.GadgetMode==-1&&p.MovementMode==0&&p.MaximumSpeed==650&&p.Bubble.Collapsing&&!p.Bubble.Expanding,"source depletion cleanup");
Check(starts==1&&stops==1&&bag.SelectedGadget==-1&&warnings.SequenceEqual(new[]{80,182}),"one loop and shared warning/selection ownership");
});
Test("transition flags reject re-equip until original fade finishes",()=>{
var p=Player();p.GadgetMode=0;p.GadgetMode=0;
Check(p.GadgetMode==-1&&p.Bubble.Collapsing&&!p.Bubble.Expanding,"select-again caller cleanup precedes active flag gate");
p.GadgetMode=0;Check(p.GadgetMode==-1,"collapsing owned effect blocks re-equip");
Until(p,()=>!p.Bubble.Visible);p.GadgetMode=0;
Check(p.GadgetMode==0&&p.Bubble.Expanding&&p.MaximumSpeed==1350,"hidden after strict fade allows next activation");
});
Test("Bubble fire throttles without starting the ordinary ray",()=>{
var world=Floor();var p=Player("LV1B",world);var director=new SceneDirector(new("LV1B",[Entity("3JIM","JIM1")]),new TaskStates([]),(_,_)=>1);
var bag=new SceneInventory(new int[19]);bag.SetState(0,3,1);using var ray=new SceneGadgets(director,bag,p,world);
p.GadgetMode=0;for(var i=0;i<20;i++)p.Step(new(false,false,true,false,false,Fire:true));
Check(p.Speed>0&&p.TurnRate>0&&p.Pitch<0&&!ray.Ray.Visible&&!p.Shooting,"shared fire predicate is Bubble throttle, not shoot");
});
Test("lava bypass, retained entry and strict4-second debounce",()=>{
var state=new Vr01FloorState();var e=state.Visit(111,0);
Check(e.Entered&&!e.Damaged&&!state.Flashing&&state.SoundSelector==35,"Bubble entry bypass");
e=state.Visit(111,-1);Check(!e.Entered&&e.Damaged&&state.Flashing,"cleanup starts damage without replaying entry");
for(var i=0;i<16;i++)state.Step(.25f,_=>{});
Check(state.Flashing&&state.Timer==4,"exact4 still flashes");
Vector4 color=default;state.Step(MathF.Pow(2,-24),c=>color=c);
Check(!state.Flashing&&state.Timer==4&&color==Vector4.One,"unrounded comparison before float store");
state.Visit(0,-1);Check(!state.InLava&&state.SoundSelector==5,"ordinary floor resets entry and selector");
});
Test("actual VR01 floor111 retained through airborne cleanup and raw control loss",()=>{
var mesh=Mesh.LoadSceneJson("artifacts/extracted/VR01/scene.json");var collision=OriginalStaticCollision.FromRouteScene(mesh,"VR01");
Check(!collision.HasSpecialPlayerContacts&&collision.PolygonCount==80&&collision.WallPolygonCount==60,"actual static-only wall coverage");
var index=Array.FindIndex(mesh.CollisionPolygons,p=>p.MaterialId==111);var first=index*3;
var center=(mesh.Vertices[mesh.Indices[first]].Position+mesh.Vertices[mesh.Indices[first+1]].Position+mesh.Vertices[mesh.Indices[first+2]].Position)/3;
var p=Player("VR01",mesh);p.GadgetMode=0;p.RestoreReturnRoot(center+Vector3.UnitY*66.4f);
var score=0;var sounds=new List<int>();p.ScoreChanged+=delta=>score+=delta;p.GadgetSound+=(id,_)=>sounds.Add(id);
p.Step(new(false,false,false,false,true));
Check(p.Velocity.Y==900&&score==0&&sounds.Contains(39)&&!sounds.Contains(190)&&p.FloorState.InLava,"Bubble supports lava and skips damage");
p.GadgetMode=-1;p.Step(default,false,false);
Check(!p.Grounded&&score==-5&&p.FloorState.Flashing&&p.Energy==20,"retained material callback runs airborne/uncontrolled; VR energy alone exempt");
});
Test("stored material writes preserve Invisible/lava phase ownership",()=>{
var appearance=new PlayerAppearance();var inv=new InvisibleGadget();inv.AlphaRequested+=appearance.SetAlpha;inv.BlendRequested+=appearance.SetBlend;
inv.Equip(20,false);for(var i=0;i<14;i++)inv.Step(.5f,true,false,false,20,false,_=>{});inv.Step(0,true,true,false,20,false,_=>{});
Check(appearance.Color.W==.7f&&appearance.Blend==MeshBlend.Additive,"activation material request");
var lava=new Vr01FloorState();lava.Visit(111,2);lava.Step(.25f,appearance.SetColor);
Check(appearance.Color.W==1&&appearance.Blend==MeshBlend.Additive,"late direct RGBA changes alpha without changing blend bit");
for(var i=0;i<8;i++)inv.Step(.5f,true,false,false,18,false,_=>{});
Check(appearance.Color.W==1&&appearance.Blend==MeshBlend.Alpha,"indexed flash does not reapply alpha.7");
inv.Release();Check(appearance.Color==Vector4.One&&appearance.Blend==MeshBlend.Opaque,"alpha-reset clears blending");
});
Test("practice0 loads before live equip; rejected raw mode opens panel directly",()=>{
var p=Player("LV1B");var bag=new SceneInventory(new int[19]);bag.SetState(0,0,1);bag.SetState(0,2,1);bag.GadgetSelected+=i=>p.GadgetMode=GadgetScreen.EquippedMode(i);
var screen=new GadgetScreen(bag,()=>p.GadgetMode);var destination=-1;screen.PracticeRequested+=i=>destination=i;
screen.Toggle(true);screen.Point(new(520,120),"LV1B",60);screen.Activate("LV1B",60);
screen.Point(new(50,200),"LV1B",60);screen.Activate("LV1B",60);
Check(destination==0&&bag.SelectedGadget==0&&p.GadgetMode==-1&&!p.Bubble.Visible,"source practice branch precedes body/effect setup");
p.Energy=0;bag.SelectGadget(2);Check(p.GadgetMode==-1&&bag.SelectedGadget==2,"rejected Invisible display/raw split");
Check(screen.Toggle(true)&&screen.Open,"key dispatcher reads raw mode, not display index");
});
Test("camera cleanup and modern debug stop release Bubble and restore defaults",()=>{
var p=Player("LV1B");var command=Entity("3MCA","cleanup",("CameraTarget0","none"));
var director=new SceneDirector(new("LV1B",[Entity("3JIM","JIM1"),command]),new TaskStates([]),(_,_)=>1);
var bag=new SceneInventory(new int[19]);bag.SetState(0,0,1);using var binding=new PlayerSceneBinding(director,p,bag,"JIM1");
bag.SelectGadget(0);director.Trigger("cleanup");
Check(p.GadgetMode==-1&&p.MaximumSpeed==650&&p.Bubble.Collapsing&&binding.UnsupportedGadgetCleanups==0,"named-Jimmy source cleanup");
Until(p,()=>!p.Bubble.Visible);bag.SelectGadget(0);p.StopDebugMotion();
Check(p.GadgetMode==-1&&bag.SelectedGadget==-1&&p.MovementMode==0,"modern stop boundary prevents dangling movement2 gadget");
Until(p,()=>!p.Bubble.Visible);bag.SelectGadget(0);p.SetNoclip(true);
for(var i=0;i<70;i++)p.Step(default);
Check(!p.Bubble.Visible&&p.Noclip&&p.GadgetMode==-1,"owned fade advances during modern flight after cleanup");
});
Console.WriteLine($"Bubble integration:{count} groups passed; broader damage, dynamic collision and original whole-game comparison remain separate.");
GamEntity Entity(string kind,string tag,params(string Name,object Value)[] values)
{
var props=new Dictionary<string,GamProperty>(StringComparer.Ordinal);
foreach(var(name,value) in new[]{("ObjectTag",(object)tag)}.Concat(values))
{
if(value is string text)props[name]=new(name,1,Encoding.Latin1.GetBytes(text));
else{var raw=new byte[4];BinaryPrimitives.WriteInt32BigEndian(raw,(int)value);props[name]=new(name,6,raw);}
}
return new(kind,props.Count,props,[]);
}
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Assets/*.cs" />
<Compile Include="../../src/GamePort/Game/BubbleEffect.cs" />
<Compile Include="../../src/GamePort/Application/BubbleVisuals.cs" />
</ItemGroup>
</Project>
+161
View File
@@ -0,0 +1,161 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Application;
using GamePort.Assets;
using GamePort.Game;
var count = 0;
void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
void Near(float actual, float expected, string message) =>
Check(MathF.Abs(actual - expected) < .0002f, $"{message}: {actual} != {expected}");
void Test(string name, Action action) { action(); count++; Console.WriteLine($"PASS {name}"); }
void Invalid(Action action)
{
try { action(); }
catch (Exception exception) when (exception is ArgumentException or InvalidDataException) { return; }
throw new Exception("Invalid input accepted");
}
BubbleEffect Active(bool conventionalBlend = false)
{
var effect = new BubbleEffect(conventionalBlend);
effect.Start(); effect.Step(.5f); effect.Step(.5f); effect.Step(.01f);
Check(effect.Active && !effect.Expanding, "expansion completes strictly after1");
return effect;
}
Test("strict expansion boundary changes all RGBA without changing geometry", () =>
{
var effect = new BubbleEffect();
Check(!effect.Visible && effect.Width == 200 && effect.Height == 200, "constructor hidden200 square");
effect.Start(); effect.Step(.5f);
Check(effect.Visible && effect.Expanding && !effect.Active && effect.Color == new Vector4(.5f), "half expansion fullRGBA");
Check(effect.Width == 200 && effect.Height == 200, "fade retains source dimensions");
effect.Step(.5f);
Check(effect.Expanding && !effect.Active && effect.Color == Vector4.One, "exact1 still expanding");
effect.Step(.01f);
Check(effect.Active && !effect.Expanding && effect.Width == 200, "completion frame still fade branch");
effect.Step(0);
Check(effect.Width == 240, "next active invocation adopts pulse geometry");
Near(effect.Height, (float)(240 + Math.Sin((double)effect.Timer * 10) * 30), "height pulse");
});
Test("active graphics branches preserve additive RGBA or set half alpha", () =>
{
foreach (var conventional in new[] { false, true })
{
var initial = new BubbleEffect(conventional);
Check(initial.Color == (conventional ? new Vector4(.9f, .9f, .9f, 1) : Vector4.One), "source initialization graphics branch");
var effect = Active(conventional);
effect.Step(.25f);
Check(effect.Color == (conventional ? new Vector4(1, 1, 1, .5f) : Vector4.One), "source graphics branch");
Near(effect.Width, 240, "pulse fixed width");
Check(effect.Height >= 210 && effect.Height <= 270, "30 unit height excursion");
}
});
Test("Stop leaf retains expansion priority; cleanup explicitly clears it", () =>
{
var leaf = new BubbleEffect(); leaf.Start(); leaf.Step(.25f); leaf.Stop(); leaf.Step(.25f);
Check(leaf.Expanding && leaf.Collapsing && leaf.Color == new Vector4(.25f), "expansion still wins without cleanup write");
leaf.Stop(); leaf.ClearExpansion(); leaf.Step(.25f);
Check(!leaf.Expanding && leaf.Collapsing && leaf.Color == new Vector4(.75f), "cleanup reveals collapse");
leaf.Step(.75f);
Check(leaf.Timer == 1 && leaf.Color == Vector4.Zero && leaf.Visible && leaf.Collapsing, "exactzero remains visible/collapsing");
leaf.Step(.001f);
Check(!leaf.Visible && !leaf.Collapsing && leaf.Color == Vector4.Zero, "strictnegative hides");
});
Test("fade compares unrounded addition even when stored timer rounds to one", () =>
{
var effect = new BubbleEffect(); effect.Start(); effect.Step(.5f); effect.Step(.5f);
effect.Step(MathF.Pow(2, -25));
Check(effect.Timer == 1 && effect.Active && !effect.Expanding, "x87 sum before float store controls strict comparison");
effect.Stop(); effect.ClearExpansion(); effect.Step(.5f); effect.Step(.5f); effect.Step(MathF.Pow(2, -25));
Check(effect.Timer == 1 && !effect.Collapsing && !effect.Visible, "unrounded collapse comparison");
});
Test("independent timer, retained dimensions, Reset and bounded timestep", () =>
{
var effect = Active(); effect.Step(.2f);
var height = effect.Height;
effect.Stop(); effect.ClearExpansion(); effect.Step(.5f);
Check(effect.Width == 240 && effect.Height == height && effect.Color == new Vector4(.5f), "collapse fades last active geometry");
effect.Step(.6f);
var hiddenTimer = effect.Timer; effect.Step(.1f);
Check(effect.Timer > hiddenTimer, "hidden effect still advances independently");
effect.Reset();
Check(!effect.Visible && !effect.Active && !effect.Expanding && !effect.Collapsing
&& effect.Timer == 0 && effect.Color == Vector4.One && effect.Width == 200 && effect.Height == 200, "explicit reset");
foreach (var seconds in new[] { -.1f, 1f, float.NaN, float.PositiveInfinity }) Invalid(() => effect.Step(seconds));
});
var prepared = args.Length == 0 ? "artifacts/extracted" : args[0];
Test("original texture world quad preserves source colors and collision metadata", () =>
{
var source = new Mesh([new(Vector3.Zero, Vector2.Zero, Vector3.One)], [0, 0, 0])
{
CollisionPolygons = [new(2, 3, Vector3.UnitY, "material")], HasCollisionMaterialIds = true,
Textures = new() { [int.MinValue + 16000] = PngImage.White }
};
var visual = new BubbleVisuals(source, prepared);
Check(visual.Mesh.Vertices.Length == 5 && visual.Mesh.Indices.Length == 9 && visual.Mesh.Draws.Length == 2, "append quad and implicit source draw");
Check(ReferenceEquals(visual.Mesh.CollisionPolygons, source.CollisionPolygons) && visual.Mesh.HasCollisionMaterialIds, "collision metadata preserved");
var draw = visual.Mesh.Draws[^1];
Check(!draw.ScreenSpace && draw.Blend == MeshBlend.Additive && !draw.Visible, "world-space blended draw starts hidden");
Check(draw.TextureId != int.MinValue + 16000 && visual.Mesh.Textures[draw.TextureId].Width == 146, "texture collision avoided");
var effect = new BubbleEffect(); effect.Start(); effect.Step(.5f);
var root = new Vector3(10, 20, 30);
visual.Update(visual.Mesh, effect, root, new(0, 0, -1000), Vector3.Zero);
Check(draw.Visible && draw.Opacity == .5f && draw.Blend == MeshBlend.Additive, "RGBA alpha and additive blend");
var corners = visual.Mesh.Vertices.Skip(1).ToArray();
Check(corners.All(v => v.Color == new Vector3(.5f)), "RGB fade carried by all vertices");
Check(corners.Aggregate(Vector3.Zero, (sum, v) => sum + v.Position) / 4 == root, "caller root is quad center");
Near(Vector3.Distance(corners[0].Position, corners[1].Position), 200, "width remains200 while fading");
Near(Vector3.Distance(corners[1].Position, corners[2].Position), 200, "height remains200 while fading");
Check(corners.Select(v => v.Uv).SequenceEqual(new Vector2[] { new(0, 1), new(1, 1), new(1, 0), new(0, 0) }), "entire original image");
effect = Active(true); effect.Step(.1f);
visual.Update(visual.Mesh, effect, root, new(0, 0, -1000), Vector3.Zero);
Check(draw.Blend == MeshBlend.Alpha && draw.Opacity == .5f && visual.Mesh.Vertices[1].Color == Vector3.One, "conventional graphics branch");
effect.Reset(); visual.Update(visual.Mesh, effect, root, Vector3.Zero, Vector3.Zero);
Check(!draw.Visible, "reset hides owned quad");
});
Test("camera degeneracies produce finite orthonormal corners", () =>
{
var visual = new BubbleVisuals(new([], []), prepared);
var effect = Active();
foreach (var target in new[] { Vector3.Zero, Vector3.UnitY, -Vector3.UnitY, new Vector3(3, 4, 5) })
{
visual.Update(visual.Mesh, effect, Vector3.One, Vector3.Zero, target);
Check(visual.Mesh.Vertices.All(v => float.IsFinite(v.Position.X + v.Position.Y + v.Position.Z)), "finite camera-facing basis");
Near(Vector3.Distance(visual.Mesh.Vertices[0].Position, visual.Mesh.Vertices[1].Position), 200, "orthonormal horizontal edge");
Near(Vector3.Distance(visual.Mesh.Vertices[1].Position, visual.Mesh.Vertices[2].Position), 200, "orthonormal vertical edge");
}
Invalid(() => visual.Update(new([], []), effect, Vector3.Zero, Vector3.Zero, Vector3.UnitZ));
Invalid(() => visual.Update(visual.Mesh, effect, new(float.NaN), Vector3.Zero, Vector3.UnitZ));
});
Test("manifest traversal, dimensions and altered original pixels are rejected", () =>
{
var directory = Path.Combine(Path.GetTempPath(), "neutron-bubble-test-" + Guid.NewGuid());
Directory.CreateDirectory(Path.Combine(directory, "bubble"));
try
{
var source = Path.Combine(prepared, "bubble");
using var manifest = JsonDocument.Parse(File.ReadAllBytes(Path.Combine(source, "bubble.json")));
var root = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(manifest.RootElement.GetRawText())!;
var texture = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(root["textures"][0].GetRawText())!;
void Save() { root["textures"] = JsonSerializer.SerializeToElement(new[] { texture }); File.WriteAllText(Path.Combine(directory, "bubble/bubble.json"), JsonSerializer.Serialize(root)); }
texture["path"] = JsonSerializer.SerializeToElement("../outside.rgba"); Save();
File.Copy(Path.Combine(source, "canvas_1.rgba"), Path.Combine(directory, "outside.rgba"));
Invalid(() => new BubbleVisuals(new([], []), directory));
texture["path"] = JsonSerializer.SerializeToElement("canvas_1.rgba");
texture["width"] = JsonSerializer.SerializeToElement(145); Save();
Invalid(() => new BubbleVisuals(new([], []), directory));
texture["width"] = JsonSerializer.SerializeToElement(146); Save();
File.WriteAllBytes(Path.Combine(directory, "bubble/canvas_1.rgba"), new byte[146 * 146 * 4]);
Invalid(() => new BubbleVisuals(new([], []), directory));
}
finally { Directory.Delete(directory, true); }
});
Console.WriteLine($"Bubble effect/visual checks passed: {count}");
+1
View File
@@ -70,6 +70,7 @@ menu.Key(43);
for(var i=0;i<10;i++)menu.Key(81);
Require(menu.Key(40)==DebugAction.GiveInvisible,"Player tools can grant/select implemented Invisible device");
menu.Key(81);Require(menu.Key(40)==DebugAction.UnequipGadget,"Explicit gadget unequip");
menu.Key(81);Require(menu.Key(40)==DebugAction.GiveBubble,"Player tools grant/select the implemented Bubble");
var invisibleView=menu.View(new("LV1B","STARTEXP",Vector3.Zero,0,0,true,20,0,30,"NONE",true,0,10000,false,
Systems:new(){InvisibleRemaining=4.5f,InvisibleRecharge=0,Targetable=false}));
Require(invisibleView.Lines.Length<=32 && invisibleView.Lines.Any(s=>s.Contains("INVISIBLE 4.5")),"Bounded Invisible timer/target diagnostics");
@@ -18,6 +18,10 @@
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerEnergy.cs"/>
<Compile Include="../../src/GamePort/Game/InvisibleGadget.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleEffect.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleMotion.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerAppearance.cs"/>
<Compile Include="../../src/GamePort/Game/Vr01FloorState.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
<Compile Include="../../src/GamePort/Game/RecoveredMotion.cs"/>
<Compile Include="../../src/GamePort/Game/FixedStepClock.cs"/>
@@ -22,6 +22,10 @@
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerEnergy.cs"/>
<Compile Include="../../src/GamePort/Game/InvisibleGadget.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleEffect.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleMotion.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerAppearance.cs"/>
<Compile Include="../../src/GamePort/Game/Vr01FloorState.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
<Compile Include="../../src/GamePort/Game/RecoveredMotion.cs"/>
<Compile Include="../../src/GamePort/Game/FixedStepClock.cs"/>
+83
View File
@@ -0,0 +1,83 @@
"""Guard original Bubble body boundaries and actual VR01 policy coverage."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from bubble_body import LavaState, collect, floor_phase, lava_flash
class BubbleBodyTests(unittest.TestCase):
def test_source_identity_guards_and_vr01_virtual_filter(self):
report = collect(ROOT.parent / 'Original')
self.assertEqual(len(report['bodies']), 8)
self.assertEqual(len(report['sites']), 27)
self.assertEqual(len(report['tables']), 10)
bindings = {(int(t['table'], 16), int(t['slot'], 16)): int(t['target'], 16)
for t in report['tables']}
self.assertEqual(bindings[0x4cd740, 0x134], 0x475cd0)
self.assertEqual(bindings[0x4cd740, 0x130], 0x44e030)
self.assertEqual(bindings[0x4a373c, 0x37c], 0x472970)
self.assertTrue(all(int(b['va'], 16) - int(b['file_offset'], 16) == 0x400000
for b in report['bodies']))
def test_actual_vr01_lava_is_support_only_not_wall374(self):
report = collect(ROOT.parent / 'Original')
room = report['archives'][0]
self.assertEqual((room['polygon_count'], room['registered'], room['walls']), (80, 80, 60))
self.assertEqual([(s['id'], s['name'], s['vertices']) for s in room['shapes']], [(0, 'VRRoom', 60)])
self.assertEqual({p['corners'] for p in room['polygons']}, {3})
self.assertEqual({p['material'] for p in room['polygons']}, {0, 1, 2, 3, 4, 111})
self.assertTrue(all(p['texture'] is not None for p in room['polygons']))
lava = [p for p in room['polygons'] if p['material'] == 111]
self.assertEqual([p['polygon'] for p in lava], list(range(48, 54)))
self.assertTrue(all(not p['wall'] and not p['callback374'] for p in lava))
self.assertEqual(report['vr01_entities'].get('3SOL', 0), 0)
self.assertEqual(report['vr01_entities']['3ROC'], 1) # Dynamic eligibility remains a gate.
def test_bubble_bypasses_lava_damage_but_keeps_entry_sound_and_selector(self):
state, actions = floor_phase(LavaState(), 111, 0)
self.assertEqual(actions, ('sound39', 'retarget_existing_floor_loop_35'))
self.assertTrue(state.entered)
self.assertFalse(state.flashing)
self.assertEqual(floor_phase(state, 111, 0), (state, ()))
state, actions = floor_phase(state, 4, 0)
self.assertFalse(state.entered)
self.assertEqual(actions, ('retarget_existing_floor_loop_5',))
def test_lava_cleanup_mode_changes_damage_before_next_flash_tick(self):
bubble, _ = floor_phase(LavaState(), 111, 0)
state, actions = floor_phase(bubble, 111, -1)
self.assertEqual(actions, ('energy_minus5_common_helper', 'score_minus5_common_helper', 'cancel_mode1'))
self.assertTrue(state.flashing)
self.assertEqual(floor_phase(state, 111, -1), (state, ()))
state, color = lava_flash(LavaState(entered=True, flashing=True, timer=3.5), .5)
self.assertTrue(state.flashing) # Strict >4, not >=4.
self.assertEqual(color[1::2], (1., 1.))
state, color = lava_flash(state, .125)
self.assertFalse(state.flashing)
self.assertEqual(color, (1.,) * 4)
state, actions = floor_phase(state, 111, -1)
self.assertEqual(actions[0], 'energy_minus5_common_helper')
# FCOM precedes thefloat store: a sum just above4 clears the latch
# even when the persisted timer rounds to exactly4.
state, color = lava_flash(LavaState(flashing=True, timer=4), 2 ** -24)
self.assertEqual(state.timer, 4)
self.assertFalse(state.flashing)
self.assertEqual(color, (1.,) * 4)
def test_base_eligibility_and_linked_texture_gates(self):
original = LavaState()
for kwargs in ({'eligible': False}, {'integration': False}, {'polygon_present': False},
{'material_present': False}, {'texture_present': False}):
self.assertEqual(floor_phase(original, 111, -1, **kwargs), (original, ()))
_, actions = floor_phase(original, 111, -1)
self.assertEqual(actions[:2], ('sound39', 'sound190'))
# Current support is deliberately not an input: source consumes retained338.
with self.assertRaises(ValueError):
floor_phase(original, 120, -1)
if __name__ == '__main__':
unittest.main()
+96
View File
@@ -0,0 +1,96 @@
"""Original-byte guards and mode2 arithmetic projections, not native gameplay."""
from pathlib import Path
import math
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/binary'))
from bubble_motion import apply_step, collect, keyboard_step, ordinary_destination
class BubbleMotionTests(unittest.TestCase):
def test_source_spans_virtuals_constants_and_offsets(self):
report = collect(ROOT.parent/'Original')
self.assertEqual((len(report['bodies']),len(report['vtables'])), (11,8))
self.assertEqual(len(report['sites']),17)
self.assertTrue(all(int(b['va'],16)-int(b['file_offset'],16)==0x400000
for b in report['bodies']))
self.assertFalse(report['landing_mode_reset'])
def test_fire_is_bubble_throttle_without_ordinary_beam(self):
a = keyboard_step(0,0,.25,fire=True)
b = keyboard_step(0,0,.25,forward=True)
self.assertEqual(a,b)
self.assertEqual((a.speed,a.target_pitch), (30,-10))
self.assertEqual(keyboard_step(1340,0,.25,fire=True).speed,1350)
def test_mode2_turn_cap_release_and_forward_backward_pose_priority(self):
self.assertEqual(keyboard_step(0,49,.5,left=True,right=True).turn,50)
self.assertEqual(keyboard_step(0,-49,.5,right=True).turn,-50)
a = keyboard_step(100,20,.5)
self.assertEqual((a.turn,a.target_pitch,a.target_roll),(0,0,0))
b = keyboard_step(100,10,.1,forward=True,backward=True,left=True)
self.assertEqual((b.speed,b.target_pitch,b.target_roll),(112.5,-10,-5))
def test_grounded_input_decay_precedes_brake_and_can_cross_below_zero(self):
self.assertEqual(keyboard_step(100,0,.1,supported=True).speed,82.5)
self.assertEqual(keyboard_step(100,0,.1,supported=True,backward=True).speed,47.5)
self.assertEqual(keyboard_step(100,0,.1,supported=True,forward=True).speed,112.5)
crossed = keyboard_step(5,0,.1,supported=True).speed
self.assertEqual(crossed,-12.5)
self.assertEqual(keyboard_step(crossed,0,.1,supported=True).speed,0)
def test_coast_threshold_and_air_brake_do_not_start_reverse(self):
self.assertEqual(keyboard_step(1350,0,.1).speed,1332.5)
self.assertEqual(keyboard_step(1200,0,.1).speed,1200)
self.assertEqual(keyboard_step(5,0,.1,backward=True).speed,0)
self.assertEqual(keyboard_step(-5,0,.1,backward=True).speed,0)
def test_apply_preserves_vertical_and_pitch_scales_horizontal_only(self):
a = apply_step(100,0,0,60,(0,-12,10),.1)
self.assertAlmostEqual(a.velocity[2],50)
self.assertEqual(a.velocity[1],-12)
self.assertEqual((a.published_speed,a.sound,a.movement_mode),(100,None,2))
def test_supported_jump_direct_velocity_and_released_scalar_order(self):
a = apply_step(100,0,0,0,(0,-800,10),.1,supported=True)
self.assertEqual(a.velocity,(0,300,100))
self.assertEqual((a.published_speed,a.sound,a.movement_mode),(50,None,2))
b = apply_step(100,0,0,0,(0,-800,10),.1,supported=True,jump=True)
self.assertEqual(b.velocity,(0,900,100))
self.assertEqual((b.published_speed,b.sound),(100,106))
# No edge latch: a second supported apply also produces the high bounce.
self.assertEqual(apply_step(100,0,0,0,b.velocity,.1,supported=True,jump=True).sound,106)
def test_zero_incoming_velocity_suppresses_direct_yaw_and_side_only(self):
stopped = apply_step(100,50,0,0,(0,0,0),.1)
self.assertEqual((stopped.yaw,stopped.velocity),(0,(0,0,100)))
moving = apply_step(100,50,0,0,(0,1,0),.1)
self.assertEqual(moving.yaw,5)
self.assertNotEqual(moving.velocity[0],stopped.velocity[0])
for seconds in (-1,1,math.inf,math.nan):
with self.assertRaises(ValueError): apply_step(0,0,0,0,(0,0,0),seconds)
with self.assertRaises(ValueError): keyboard_step(0,0,seconds)
def test_cleanup_and_ground_no_input_do_not_invent_upright_reset(self):
report = collect(ROOT.parent/'Original')['handoff']
self.assertEqual(len(report['bodies']),6)
self.assertEqual(len(report['a20_raw_dword_occurrences']),6)
self.assertEqual(report['a20_direct_writes'],['0x4226cf','0x428045','0x42821a'])
self.assertIsNone(report['a20_consumer'])
self.assertFalse(report['derived_aliases_excluded'])
self.assertFalse(report['cleanup_resets_euler'])
self.assertFalse(report['ground_no_input_resets_euler'])
target = (-10.,42.,-12.5)
self.assertEqual(ordinary_destination(target,43,20),target)
self.assertEqual(ordinary_destination(target,43,20,accepted_ground_direction=True),(0,43,0))
def test_ordinary_air_handoff_targets_zero_pitch_but_retains_turn_lean(self):
target = (-10.,42.,-12.5)
self.assertEqual(ordinary_destination(target,43,20,airborne=True),(0,43,-20))
self.assertEqual(ordinary_destination(target,43,0,airborne=True),(0,43,0))
if __name__ == '__main__':
unittest.main()
+76
View File
@@ -0,0 +1,76 @@
from pathlib import Path
import hashlib
import json
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent/'Original'
sys.path.insert(0, str(ROOT/'tools/extractors'))
from bubble_resources import ARCHIVE_SHA256, PAYLOAD_SHA256, RGBA_SHA256, export_bubble
from omt import FormatError
from png import read_png
@unittest.skipUnless(ORIGINAL.exists(), 'Original assets are local integration fixtures')
class BubbleResourceTests(unittest.TestCase):
def test_exact_canvas_pixels_and_source_provenance(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'bubble'
manifest = export_bubble(ORIGINAL, output)
self.assertEqual(manifest, json.loads((output/'bubble.json').read_text()))
self.assertEqual((manifest['schema'], manifest['source'], manifest['sourceSha256']),
(1, 'RetainedSprites.omt', ARCHIVE_SHA256))
self.assertEqual(len(manifest['textures']), 1)
entry = manifest['textures'][0]
self.assertEqual((entry['id'], entry['name'], entry['width'], entry['height']),
(1, 'orangebubble', 146, 146))
self.assertEqual((entry['sourceOffset'], entry['sourceBytes'], entry['sourceSha256']),
(0x17FCE, 66322, PAYLOAD_SHA256))
rgba = (output/entry['path']).read_bytes()
self.assertEqual((len(rgba), hashlib.sha256(rgba).hexdigest()), (146*146*4, RGBA_SHA256))
self.assertEqual(read_png(output/entry['png'])['rgba'], rgba)
self.assertEqual((rgba[3::4].count(0), rgba[3::4].count(255)), (5492, 15824))
def test_original_subtrees_and_ancestors_rejected_before_writes(self):
for output in (ORIGINAL, ORIGINAL/'omt/generated-bubble', ORIGINAL.parent):
with self.subTest(output=output), self.assertRaises(ValueError):
export_bubble(ORIGINAL, output)
def test_output_child_symlinks_cannot_overwrite_another_file(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
target = root/'unchanged'
target.write_bytes(b'unchanged')
output = root/'bubble'
output.mkdir()
for name in ('canvas_1.rgba', 'canvas_1.png', 'bubble.json'):
(output/name).symlink_to(target)
with self.subTest(name=name), self.assertRaises(ValueError):
export_bubble(ORIGINAL, output)
self.assertEqual(target.read_bytes(), b'unchanged')
(output/name).unlink()
def test_bad_decoded_dimensions_or_pixels_rejected_before_output(self):
for canvas in (dict(width=1, height=1, rgba=b'\0'*4),
dict(width=146, height=146, rgba=b'\0'*(146*146*4))):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'bubble'
with patch('bubble_resources.read_canvas', return_value=canvas), self.assertRaises(FormatError):
export_bubble(ORIGINAL, output)
self.assertFalse(output.exists())
def test_bad_archive_identity_rejected_before_decode(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'bubble'
with patch('bubble_resources.digest', return_value='0'*64), \
patch('bubble_resources.read_canvas') as decoder, self.assertRaises(FormatError):
export_bubble(ORIGINAL, output)
decoder.assert_not_called()
self.assertFalse(output.exists())
if __name__ == '__main__':
unittest.main()
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""Read-only Bubble body/VR01 coverage and bounded floor-policy projections.
Static evidence and source projections are distinct from the generated copied-code
probe. No original file is changed or executed in place.
"""
from __future__ import annotations
import argparse
from collections import Counter
from dataclasses import dataclass, replace
import hashlib
import json
import math
from pathlib import Path
import struct
import sys
from bubble import f32
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'extractors'))
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'levels'))
from omt import Database, read_material, read_shape
from gam import parse
BODIES = (
('vr01_ctor', 0x455ef0, 0x455fd8, '93c98d72b0c8f0da102068beff19f9b8ebb0da58fa6a4d524ae09415f814f088'),
('floor_game', 0x44e030, 0x44e444, '6ae67944afc53bd050279c1e2356c614e8cd534c7a94ef9628bf0bbfd028fe91'),
('base_floor', 0x462520, 0x462647, 'ba8f47f8b62db304821b751872db003d37605031c57423542f8040c9ef9d7e68'),
('lava_enter', 0x42ab00, 0x42ab2a, '06010f1d0ca453459062f8cb0f96caf3fd2c605cee88547315ddee43b051430a'),
('lava_damage', 0x42a8d0, 0x42a918, '88a303b3ae7cca7fc4c3935848077bbaf5393f83ed184b8e042e67803c3c4863'),
('lava_flash', 0x4257d6, 0x425864, '7f239b21895a710aa766c8d4b8213c70d931e785399c01f8ea1fbec66e19f65d'),
('polygon_setter', 0x472580, 0x47258d, 'e7fe0271b3f9cffbde6e23f64ff533a86042f4c063a804430921b7fe1e9e036b'),
('shape_setter', 0x4725c0, 0x4725cd, '4f7a906d71c1d56117bba8c9ccd2d757c1ed9ee09e40e2a3930388b650b4427d'),
)
SITES = (
('player_base_before_owner', 0x43796a, 'e8e166fdff'),
('animated_base_floor', 0x40e0eb, 'e830440500'),
('base_integrates', 0x46253d, 'ff9010020000'),
('base_polygon', 0x46254f, 'ff9238030000'),
('base_game130', 0x46258f, 'ff9530010000'),
('lava_low', 0x44e170, '83fd6e7c32'),
('lava_high', 0x44e175, '83fd777f2d'),
('lava_entry_callback', 0x44e18e, 'ff9098010000'),
('lava_latch_on', 0x44e194, 'c686021e000001'),
('lava_damage_callback', 0x44e19f, 'ff9264010000'),
('lava_leave_callback', 0x44e1bb, 'ff909c010000'),
('lava_latch_off', 0x44e1c1, '889e021e0000'),
('lava_sound35', 0x44e32c, 'c7824c05000023000000'),
('ordinary_sound5', 0x44e407, 'c7824c05000005000000'),
('floor_sound_changed', 0x44e426, 'ff92e4010000'),
('wrapper_flash_late', 0x424c88, 'ff92b4010000'),
('flash_duration4', 0x49d5e8, '00008040'),
('support_polygon_publish', 0x47bba1, 'ff923c030000'),
('support_shape_publish', 0x47bb91, 'ff904c030000'),
('landing_noop', 0x472970, 'c3'),
('grounded_radius160', 0x4246b4, '6800002043'),
('grounded_radius60', 0x4246dc, '6800007042'),
('factor_authored_live', 0x4711e0, '8b4424048b115089412cff9254020000'),
('game_filter_false', 0x475cd0, '32c0c21800'),
('nc_shape_skip', 0x44dd64, '83f86374078b178bcfff522c'),
('checkpoint_filter', 0x4791c7, '5355e8f202000083c40884'),
('game_filter', 0x4791d9, '5355e8c005000083c40884c0740c'),
)
TABLES = (
(0x4cd740, 0x134, 0x475cd0), (0x4cd740, 0x130, 0x44e030),
(0x4a373c, 0x338, 0x472570), (0x4a373c, 0x33c, 0x472580),
(0x4a373c, 0x34c, 0x4725c0), (0x4a373c, 0x37c, 0x472970),
(0x4a3bdc, 0x198, 0x42ab00), (0x4a3bdc, 0x19c, 0x472970),
(0x4a3bdc, 0x164, 0x42a8d0), (0x4a3bdc, 0x1e4, 0x42aec0),
)
def geometry(root, name):
db = Database(find_case(root, 'omt/' + name))
materials = {e.id: e.name for e in db.entries if e.type == '3DMa'}
textures = {e.id: read_material(db.payload(e))['texture'] for e in db.entries if e.type == '3DMa'}
shapes, records = [], []
for entry in sorted((e for e in db.entries if e.type == '3DSh'), key=lambda e: e.id):
shape = read_shape(db.payload(entry))
shapes.append(dict(id=entry.id, name=entry.name, payload_offset=entry.offset,
payload_sha256=hashlib.sha256(db.payload(entry)).hexdigest(),
vertices=len(shape['vertices']), polygons=len(shape['polygons'])))
for index, polygon in enumerate(shape['polygons']):
link = polygon['material']
identity = link['id'] if link and link['type'] == '3DMa' else None
material = materials.get(identity)
registered = not (entry.name or '').lower().startswith('nc') and not (
material and material.lower() in {'cstart', *(f'ccheck{i}' for i in range(1, 10))})
ny = polygon['normal'][1]
records.append(dict(shape=entry.id, polygon=index, corners=len(polygon['corners']),
material=identity, material_name=material, texture=textures.get(identity),
normal=polygon['normal'],
registered=registered, wall=registered and ny < f32(.7),
callback374=registered and f32(-.7) < ny < f32(.7)))
return dict(name=name, sha256=hashlib.sha256(db.data).hexdigest(), shapes=shapes,
polygon_count=len(records), registered=sum(p['registered'] for p in records),
walls=sum(p['wall'] for p in records), polygons=records)
def collect(root):
root = Path(root)
pe = PE(find_case(root, 'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256:
raise ValueError('Unsupported original executable')
bodies, sites, tables = [], [], []
for name, start, end, expected in BODIES:
if hashlib.sha256(read_va(pe, start, end-start)).hexdigest() != expected:
raise ValueError('Changed source body ' + name)
bodies.append(dict(name=name, va=hex(start), file_offset=hex(pe.offset(start-pe.base)),
length=end-start, sha256=expected))
for name, va, expected in SITES:
actual = read_va(pe, va, len(bytes.fromhex(expected))).hex()
if actual != expected:
raise ValueError(f'Changed {name} at {va:x}: {actual}')
sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), bytes=actual))
for table, slot, target in TABLES:
if struct.unpack('<I', read_va(pe, table+slot, 4))[0] != target:
raise ValueError('Changed virtual binding')
tables.append(dict(table=hex(table), slot=hex(slot), target=hex(target),
file_offset=hex(pe.offset(table+slot-pe.base))))
dll = PE(find_case(root, 'OMT2.dll'))
dll_hash = '3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943'
if hashlib.sha256(dll.data).hexdigest() != dll_hash:
raise ValueError('Unsupported OMT DLL')
texture_set = '8b44240485c0898180000000'
if read_va(dll, 0x100013b5, len(bytes.fromhex(texture_set))).hex() != texture_set:
raise ValueError('Changed OMT material texture publication')
gam = find_case(root, 'gam/VR01.gam').read_bytes()
return dict(sha256=EXE_SHA256, bodies=bodies, sites=sites, tables=tables,
archives=[geometry(root, name) for name in ('VR01.omt', 'VR04.omt')],
vr01_gam_sha256=hashlib.sha256(gam).hexdigest(),
vr01_entities=dict(Counter(e.kind for e in parse(gam).entities)),
material_texture=dict(dll_sha256=dll_hash, exported_set_texture=hex(0x100013a0),
write_va=hex(0x100013b5), file_offset=hex(dll.offset(0x100013b5-dll.base)), bytes=texture_set),
scope='Static guarded source and bounded projections; isolated original probe is separate.')
@dataclass(frozen=True)
class LavaState:
entered: bool = False
flashing: bool = False
timer: float = 0
sound_selector: int = 5
def floor_phase(state, material, raw_mode, *, eligible=True, integration=True,
polygon_present=True, material_present=True, texture_present=True):
"""462520→44E030 restricted to actualVR01 IDs; excludes other damage flags.
This phase consumes retained338 even if current218=false. Caller preserves
that polygon until next successful support. Energy/score helpers own clamps
and tutorial exemption. Audio requests are distinct from playback evidence.
"""
if material not in (None, 0, 1, 2, 3, 4, 111):
raise ValueError('Outside VR01 floor-policy projection')
if not (eligible and integration and polygon_present and material_present and texture_present):
return state, ()
actions = []
lava = material == 111
if lava:
if not state.entered:
actions += ['sound39']
if raw_mode != 0:
actions += ['sound190']
state = replace(state, entered=True)
if not state.flashing and raw_mode != 0:
state = replace(state, flashing=True, timer=0)
actions += ['energy_minus5_common_helper', 'score_minus5_common_helper', 'cancel_mode1']
elif state.entered:
state = replace(state, entered=False)
selector = 35 if lava else 5
if selector != state.sound_selector:
actions += [f'retarget_existing_floor_loop_{selector}']
return replace(state, sound_selector=selector), tuple(actions)
def lava_flash(state, seconds):
"""4257D6 finite projection, assuming1DED/1E03 false; no x87/fsin parity."""
if not math.isfinite(seconds) or not 0 <= seconds < 1:
raise ValueError('Bounded finite timestep required')
if not state.flashing:
return state, None
#4257E8 compares the unrounded x87 sum before4257EE storesfloat; FSIN
#also consumes that retained sum. Python double models this bounded sum.
total = f32(state.timer) + f32(seconds)
timer = f32(total)
if total > 4:
return replace(state, flashing=False, timer=timer), (1., 1., 1., 1.)
pulse = f32((math.sin(total * 20) + 1) * .5)
return replace(state, timer=timer), (pulse, 1., pulse, 1.)
def generate_probe(output):
"""Reuse the isolated body's synthetic virtuals; no game actor/input/audio."""
source = Path(__file__).with_name('body_step_probe.c').read_text()
marker = ' puts("BODY_COMPONENT_COMPLETE:'
if source.count(marker) != 1:
raise ValueError('Unexpected body fixture source')
extra = ''' b=initial();b.radius=160;b.factor=.415f;b.position.y=66.4f;b.previous=b.position;run("bubble_floor",b,1);
b=initial();b.radius=160;b.factor=.415f;b.position.y=26;b.previous=b.position;run("bubble_spawn",b,1);
b=initial();b.radius=160;b.factor=.415f;run("bubble_equip_no_forced_lowering",b,1);
b=initial();b.position.y=66.4f;b.previous=b.position;run("bubble_cleanup_raise",b,1);
b=initial();b.radius=160;b.factor=.415f;b.position.y=66.4f;b.previous=b.position;b.supported=1;b.velocity.y=300;run("bubble_small_bounce",b,1);
b=initial();b.radius=160;b.factor=.415f;b.position.y=66.4f;b.previous=b.position;b.supported=1;b.velocity.y=900;run("bubble_held_bounce",b,1);
'''
output = Path(output).resolve()
project = Path(__file__).resolve().parents[2]
if output.is_relative_to(project.parent / 'Original'):
raise ValueError('Generated source must be outside originals')
output.write_text(source.replace(marker, extra + marker))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
parser.add_argument('--probe-source', type=Path)
args = parser.parse_args()
report = collect(args.original)
if args.probe_source:
generate_probe(args.probe_source)
print(json.dumps(report, indent=2))
+229
View File
@@ -0,0 +1,229 @@
#!/usr/bin/env python3
"""Read-only Bubble movement source guards and bounded arithmetic projections.
Static source projections do not execute original gameplay or emulate x87/trig
table precision. REA Evidence/provider limitations are in bubble-motion.md.
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
import hashlib
import json
import math
from pathlib import Path
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
BODIES = (
('frame', 0x437940, 0x437c3a, '9579bfb1c4d9ae6abf2a1c78d6f99544871a63216fb80b9a906e3a76ebe27983'),
('apply', 0x4387e0, 0x438a58, 'c4de9afecf895c0ae30d5e939716e66abe33e7306506ddf0da981ede5061371c'),
('input', 0x439900, 0x43a111, '895f27be2ad03f49230fe34e98753095285a61f52b4adbbb15f1dd7c868b2901'),
('dispatch', 0x438a60, 0x438bb4, '99717e7fbac658abcb4b825047d2c35714b8b9e1361534374a109e8556641fc9'),
('jump_predicate', 0x4378d0, 0x43793a, 'f723e460743e29309cdb0efdb8b25df2513490bd84e9d175e6493f963614ab01'),
('landing_hook', 0x42a720, 0x42a72b, '157917f7713b11d5959c99602ce485abe99a268e396dc380d329bc52acd7e93a'),
('empty_hook', 0x472970, 0x472971, 'ae3f4619b0413d70d3004b9131c3752153074e45725be13b9a148978895e359e'),
('fire_predicate', 0x42a7a0, 0x42a7d6, 'c8fa10f42eefe68a195d9980f1a57558a240cd7877bfeab567e7868c0ddf419f'),
('support_pose', 0x42469b, 0x4246e9, '40e025e4bdc8bcdbcb24651e3d81908a5b7a9e2cc8de81d733da7490ea76c1d4'),
('wrapper_input', 0x426030, 0x4263f0, '365773538a65d99bd9e5d04c790eee7758ee528bdc385dba309f49d49ea9e5bb'),
('vector_transform', 0x472b10, 0x472c10, 'ee9516aef07738fcf7da370af74185f7522686759218ad1bf4d93be46f0c28b2'),
)
VTABLES = (
(0x4a3bdc, 0x128, 0x439900), (0x4a3bdc, 0x13c, 0x4387e0),
(0x4a3bdc, 0x154, 0x42a720), (0x4a3bdc, 0x158, 0x4378d0),
(0x4a3bdc, 0x15c, 0x42a7a0), (0x4a373c, 0x2bc, 0x471f10),
(0x4a373c, 0x2c4, 0x471f40), (0x4a373c, 0x38c, 0x472b10),
)
CONSTANTS = ((0x48d948, 'f', .5), (0x48d96c, 'f', 100.),
(0x4a3e78, 'f', -50.), (0x48d400, 'f', 50.),
(0x49d5b8, 'f', 0.0181818176060915),
(0x4afd2c, 'f', -.25), (0x49d5dc, 'f', 0.9090909361839294),
(0x494cb8, 'd', 1.8), (0x4a6850, 'd', .8),
(0x4a2ad0, 'd', .2), (0x48e598, 'd', 1.5))
SITES = (
('mode2_apply_dispatch', 0x437a5d, 33), ('publish_speed', 0x437c22, 17),
('nonzero_velocity_gate', 0x43884e, 17), ('yaw_add', 0x43885f, 34),
('velocity_store', 0x438950, 44), ('support_gate', 0x43899a, 18),
('held_jump_bounce900', 0x4389d8, 45), ('released_bounce300', 0x438a0c, 68),
('fire_forward_mode2', 0x439abb, 43), ('support_input_decay', 0x439ba2, 75),
('turn50', 0x439cb2, 73), ('mode2_lean', 0x439cfb, 55),
('mode2_camera', 0x439f4d, 239), ('base_input_first', 0x426081, 8),
('gadget_input_consumes', 0x426095, 17), ('drain_after_input', 0x426264, 65),
('supported_stop', 0x4246a9, 51),
)
HANDOFF_BODIES = (
('cleanupA20', 0x428037, 0x4280cc, 'b8891ee4fb67c566785ed329194717c3e30a895bd15bda91eedd81d76d026a55'),
('normal_destinations', 0x43951e, 0x4395cf, 'b3c30081c2f5dad2b51b240d1b91eb345700bcf9f3ff356793724890340a40ce'),
('normal_direction_flags', 0x438f66, 0x4393fb, '5e8af054cbf28fb5f676f6f05a0efea4c8e2ebc1ae69cce09abbca57f60a68e2'),
('rotation', 0x43a420, 0x43a5cf, 'e052ee855e625d03a3317dcc7d507081c7519576381afa5741572157e5ffb988'),
('constructorA20', 0x4226c9, 0x4226d5, '41cfd341bf4e4602eb69c04e4837e05de62746a3117335b651e4ab29ddac9c8d'),
('normal_air_pose', 0x439d81, 0x439e33, '38d71efb31ca7ee03e248658bf469e0141a1cbf47f177b63d10cea9c7b5469da'),
)
def collect_handoff(pe: PE):
"""Bounded direct-displacement search; does not rule out derived aliases."""
bodies = []
for name, start, end, expected in HANDOFF_BODIES:
actual = hashlib.sha256(read_va(pe, start, end-start)).hexdigest()
if actual != expected:
raise ValueError(f'Changed handoff span {name}')
bodies.append(dict(name=name, va=hex(start), file_offset=hex(pe.offset(start-pe.base)),
length=end-start, sha256=actual))
text = next(s for s in pe.sections if s['name'] == '.text')
start, size = text['file_offset'], text['raw_size']
raw = pe.data[start:start+size]
matches = []
offset = 0
while (offset := raw.find(struct.pack('<I', 0xa20), offset)) >= 0:
matches.append(pe.va(start+offset))
offset += 1
expected = [0x4226d1,0x428047,0x42821c,0x45cfe3,0x45d024,0x45d035]
if matches != expected:
raise ValueError('Changed A20 literal/displacement search boundary')
# First3 are MOV disp32 writes; remaining3 are unrelated PUSH immediates.
for va, prefix in [(0x4226cf,b'\x89\x9d'), (0x428045,b'\xc7\x86'), (0x42821a,b'\xc7\x86')]:
if read_va(pe, va, 2) != prefix:
raise ValueError('Changed direct A20 write')
return dict(bodies=bodies, text_va=hex(pe.base+text['rva']), text_size=size,
a20_raw_dword_occurrences=[hex(a) for a in matches],
a20_direct_writes=['0x4226cf','0x428045','0x42821a'],
a20_consumer=None, derived_aliases_excluded=False,
cleanup_resets_euler=False, ground_no_input_resets_euler=False,
accepted_ground_destination_pitch=0, accepted_ground_destination_roll=0,
ordinary_air_destination_pitch=0, ordinary_air_roll_multiplier=-1)
def collect(original: Path | str):
pe = PE(find_case(Path(original), 'Neutron.exe'))
digest = hashlib.sha256(pe.data).hexdigest()
if digest != EXE_SHA256:
raise ValueError('Unexpected original EXE identity')
bodies = []
for name, start, end, expected in BODIES:
actual = hashlib.sha256(read_va(pe, start, end-start)).hexdigest()
if actual != expected:
raise ValueError(f'Changed source span {name}')
bodies.append(dict(name=name, va=hex(start), file_offset=hex(pe.offset(start-pe.base)),
length=end-start, sha256=actual))
for base, slot, expected in VTABLES:
if struct.unpack('<I', read_va(pe, base+slot, 4))[0] != expected:
raise ValueError(f'Changed virtual {base:x}+{slot:x}')
for va, kind, expected in CONSTANTS:
if struct.unpack('<'+kind, read_va(pe, va, struct.calcsize(kind)))[0] != expected:
raise ValueError(f'Changed constant {va:x}')
return dict(sha256=digest, bodies=bodies,
sites=[dict(name=n, va=hex(v), file_offset=hex(pe.offset(v-pe.base)),
bytes=read_va(pe, v, z).hex()) for n,v,z in SITES],
vtables=[dict(table=hex(b), slot=hex(s), target=hex(t)) for b,s,t in VTABLES],
constants=[dict(va=hex(a), value=v) for a,k,v in CONSTANTS],
movement_mode=2, max_speed=1350, bounce_released=300, bounce_held=900,
bounce_sound=106, landing_mode_reset=False, handoff=collect_handoff(pe))
def finite(*values):
if not all(math.isfinite(v) for v in values):
raise ValueError('Finite bounded inputs required')
@dataclass(frozen=True)
class InputResult:
speed: float
turn: float
target_pitch: float
target_roll: float
def keyboard_step(speed: float, turn: float, seconds: float, *, forward=False,
backward=False, left=False, right=False, fire=False, supported=False,
maximum=1350.) -> InputResult:
"""439900 keyboard subset; effective fire predicate supplied by caller.
Includes supported slowdown before Down and separate later apply slowdown.
Mouse/analog and camera are documented but deliberately not approximated here.
"""
finite(speed, turn, seconds, maximum)
if not 0 <= seconds < 1 or maximum <= 0:
raise ValueError('Bounded timestep and positive maximum required')
amount = 100*seconds
if left:
turn += amount
elif right:
turn -= amount
elif turn < 0:
turn = min(0, turn+amount)
elif turn > 0:
turn = max(0, turn-amount)
throttle = forward or fire
if throttle and speed < maximum:
speed = min(maximum, speed+30)
if not throttle and speed > maximum*0.9090909361839294:
speed -= 17.5
if supported:
speed = speed-17.5 if speed > 0 else 0.
if backward:
if speed > 0:
speed = max(0., speed-(35. if supported else 17.5))
elif speed < 0:
speed = min(0., speed+35.)
turn = max(-50., min(50., turn))
return InputResult(speed, turn, -10. if throttle else 10. if backward else 0., -.25*turn)
@dataclass(frozen=True)
class ApplyResult:
velocity: tuple[float, float, float]
yaw: float
published_speed: float
sound: int | None
movement_mode: int = 2
def apply_step(speed: float, turn: float, yaw: float, pitch: float,
velocity: tuple[float, float, float], seconds: float, *,
supported=False, jump=False, friction=.8) -> ApplyResult:
"""4387E0 algebra with host trig; original table quantization is not emulated.
XZ is composed using pre-bounce speed, while the published scalar can halve.
Original acceleration and impulse are untouched by this routine.
"""
finite(speed, turn, yaw, pitch, seconds, friction, *velocity)
if not 0 <= seconds < 1:
raise ValueError('Bounded timestep required')
side = 0.
if any(v != 0 for v in velocity):
yaw += turn*seconds
side = turn*(1-friction)*speed*0.0181818176060915
sine, cosine = math.sin(math.radians(yaw)), math.cos(math.radians(yaw))
forward = speed*math.cos(math.radians(pitch))
vx, vy, vz = -sine*forward+cosine*side, velocity[1], cosine*forward+sine*side
sound = None
if supported:
if jump:
vy, sound = 900., 106
else:
speed *= .5
vy = 300.
return ApplyResult((vx,vy,vz), yaw, speed, sound)
def ordinary_destination(previous: tuple[float,float,float], yaw: float, turn: float,
*, airborne=False, accepted_ground_direction=False):
"""Bounded destination handoff, not rotation/interpolation scheduling.
Ordinary ground no-input preserves the prior Bubble target. Accepted ground
steering replaces pitch/roll with0; normal airborne input supplies roll-turn.
"""
finite(*previous, yaw, turn)
if airborne:
return (0., yaw, -turn)
if accepted_ground_direction:
return (0., yaw, 0.)
return previous
if __name__ == '__main__':
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('original', type=Path)
print(json.dumps(collect(cli.parse_args().original), indent=2))
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Export the original C3DBubble Canv1 unchanged into a generated directory.
Archive/id binding is recovered in docs/gameplay/bubble.md. This utility reads
assets only; it neither executes original code nor bakes pulse, tint or scaling.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
from entities import resolve_asset
from omt import Database, FormatError, read_canvas, write_png
ARCHIVE_SHA256 = 'b584ffa4a38f4bc809b3ea8f4321e0c08f2719e22df41a3fb4cd143ed89b3bef'
PAYLOAD_SHA256 = '9b6cdce95bd408fa1dc806d30520df65971f25d1663ab8da4ca6bf41380805ec'
RGBA_SHA256 = 'a3a678c47c1ce94946b1136560a84f3ef86c6884b981256a9fbff62fe8a988e4'
def digest(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def export_bubble(original: Path, output: Path) -> dict:
original, output = original.resolve(), output.resolve()
if output.is_relative_to(original) or original.is_relative_to(output):
raise ValueError('Output must be separate from the original installation')
# Guard output aliases before any write, including existing child symlinks.
files = {name: output/name for name in ('canvas_1.rgba', 'canvas_1.png', 'bubble.json')}
if any(path.resolve() != path for path in files.values()):
raise ValueError('Generated Bubble files must not be symlinks')
database = Database(resolve_asset(original, 'omt/RetainedSprites.omt'))
if digest(database.data) != ARCHIVE_SHA256:
raise FormatError('Unexpected original Bubble archive identity')
matches = [e for e in database.entries if e.type == 'Canv' and e.id == 1]
if len(matches) != 1:
raise FormatError('Expected one original Bubble Canv1')
entry = matches[0]
if (entry.name, entry.offset, entry.size) != ('orangebubble', 0x17FCE, 66322):
raise FormatError('Unexpected original Bubble canvas metadata')
payload = database.payload(entry)
if digest(payload) != PAYLOAD_SHA256:
raise FormatError('Unexpected original Bubble payload identity')
canvas = read_canvas(payload)
rgba = canvas['rgba']
if (canvas['width'], canvas['height'], len(rgba)) != (146, 146, 146*146*4):
raise FormatError('Unexpected original Bubble canvas dimensions')
if digest(rgba) != RGBA_SHA256:
raise FormatError('Unexpected original Bubble decoded pixels')
manifest = dict(schema=1, source=database.path.name, sourceSha256=ARCHIVE_SHA256,
textures=[dict(id=1, name=entry.name, width=146, height=146,
path='canvas_1.rgba', png='canvas_1.png', sourceOffset=entry.offset,
sourceBytes=entry.size, sourceSha256=PAYLOAD_SHA256, rgbaSha256=RGBA_SHA256)])
output.mkdir(parents=True, exist_ok=True)
files['canvas_1.rgba'].write_bytes(rgba)
write_png(files['canvas_1.png'], 146, 146, rgba)
files['bubble.json'].write_text(json.dumps(manifest, indent=2)+'\n', encoding='utf-8')
return manifest
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
parser.add_argument('--output', type=Path, required=True, help='Generated texture directory')
args = parser.parse_args()
export_bubble(args.original, args.output)
print(f'Original Bubble Canv1 exported: {args.output}/bubble.json')
if __name__ == '__main__':
main()
+2
View File
@@ -12,6 +12,7 @@ from models import prepare_models
from ui import export_ui
from gadget_resources import export_gadget_resources
from gadget_followup_assets import export_meter
from bubble_resources import export_bubble
from sound_bank import export_sound_bank
@@ -82,6 +83,7 @@ def main():
export_ui(Database(find_archive(args.original, 'screens')), args.output / 'ui', Database(args.original / 'alpha.omt'))
export_gadget_resources(Database(find_archive(args.original, 'screens')), args.output / 'gadgets')
export_meter(args.original, args.output / 'invisible-meter')
export_bubble(args.original,args.output/'bubble')
effects = export_sound_bank(args.original, args.output / 'effects')
print(f"SoundEffects.omt: {len(effects['resources'])} original sound identities")
for name in args.audio: