Add controllable lab walking checkpoint with collision and chase camera

This commit is contained in:
UnixNight committed 2026-10-23 23:29:40 -04:00
1 parent 37fa18094f
commit 58424120bb
26 files changed
+1842 -104

No files matched your search

+24 -20
View File
@@ -4,11 +4,11 @@ Local reconstruction of the supplied **Jimmy Neutron: Boy Genius** installation
using C#/.NET 10, Silk.NET.Vulkan (Vulkan 1.3), and SDL3. Original files remain using C#/.NET 10, Silk.NET.Vulkan (Vulkan 1.3), and SDL3. Original files remain
untouched in `../Original`. There are no Git remotes or runtime online services. untouched in `../Original`. There are no Git remotes or runtime online services.
**Current milestone: recovered original assets, a native rendered lab scene with **Current milestone: controllable original lab with walking, jumping, collision,
selectable Jimmy animation previews, and Linux/Windows investigation packages. Full chase camera and original animation clips.** Recovered controller arithmetic is
playable gameplay has not been reconstructed.** Controls, collision, introductory integrated; collision/pivot/cadence and animation timing remain provisional.
cutscenes, interactions, progression and saves still require implementation and Introductory cutscenes, interactions, progression and saves remain incomplete.
comparison. See [progress](docs/progress.md) and [compatibility](docs/compatibility.md). See [progress](docs/progress.md) and [compatibility](docs/compatibility.md).
## Build and run locally ## Build and run locally
@@ -18,24 +18,27 @@ From `GamePort/`, using an installed .NET 10 SDK or the already provisioned loca
source scripts/env.sh source scripts/env.sh
dotnet build dotnet build
python3 tools/extractors/prepare.py --audio sounds musicsecretlab python3 tools/extractors/prepare.py --audio sounds musicsecretlab
dotnet run -- --with-player dotnet run
``` ```
The default scene is the original secret lab (LV1B) with its recorded start camera. The default is the original secret lab (LV1B), starting at the GAM location after
Press **C** to switch between stored and inspection cameras; arrows/WASD orbit, settling onto source floor geometry. **Arrows** walk/backpedal/turn; **Shift,
plus/minus zoom, F11 toggles fullscreen, Escape quits. These are investigation Insert, numpad 0 or right mouse** jump. **R** resets, **C** pauses into inspection
controls. Original gameplay controls are documented in `docs/analysis/gameplay.md`. and resumes the chase camera, **F11** toggles fullscreen, **Escape** quits.
The default idle asset is a still pose: its two original samples are identical. No-gadget held jump can repeat on landing; normal midair arrows do not steer.
Press **1** for idle, **2** for the run animation, **3** for the jump animation, The original STARTEXP/LABEXP intro is skipped for this checkpoint.
or **4** for the scratch animation. These preview cycles do not control movement.
The player mesh is raised onto visible floor geometry for preview; exact original Use `--inspect` for the previous inspector: arrows/WASD orbit, plus/minus zoom;
actor/collision transforms remain under investigation. GAM positions are unchanged. 1 idle, 2 run, 3 jump, 4 scratch preview. With no simulation, C toggles stored/orbit
Without a prepared scene, the app previews the original Jimmy base model. camera. Idle is a still original pose. Exact actor pivot and animation state timing
remain under investigation; GAM/ASE source data is unchanged. Without a prepared
scene the app previews the Jimmy base model.
Headless verification on a machine with Vulkan 1.3 (Mesa lavapipe works): Headless verification on a machine with Vulkan 1.3 (Mesa lavapipe works):
```bash ```bash
dotnet run -- --headless --with-player --time 0.05 --screenshot artifacts/lab.ppm dotnet run -- --headless --with-player --time 0.05 --screenshot artifacts/lab.ppm
dotnet run -- --headless --smoke-walk --screenshot artifacts/walk.ppm
dotnet run -- --headless --model ASE/jimstop.ase --texture png/jimycarl.png dotnet run -- --headless --model ASE/jimstop.ase --texture png/jimycarl.png
dotnet run -- --audio artifacts/extracted/musicsecretlab/Wave_00000000_HuntingBuildupVar2_11k.wav --loop-audio dotnet run -- --audio artifacts/extracted/musicsecretlab/Wave_00000000_HuntingBuildupVar2_11k.wav --loop-audio
dotnet run -- --help dotnet run -- --help
@@ -43,7 +46,8 @@ dotnet run -- --help
Explicit original paths can be supplied with `--assets /path/to/Original`. Explicit original paths can be supplied with `--assets /path/to/Original`.
`--scene` accepts generated scene JSON; `--level` accepts an original GAM relative `--scene` accepts generated scene JSON; `--level` accepts an original GAM relative
to the original root. `--original-camera` uses its matching startpoint. Player to the original root. Use `--walk` for an explicitly selected scene/GAM pair.
`--original-camera` uses its matching startpoint in inspection mode. Player
preview uses `--with-player` or `--animation path/to/animation.json`. Morph sample preview uses `--with-player` or `--animation path/to/animation.json`. Morph sample
interpolation is recovered; loop closure and playback speed remain preview policies. interpolation is recovered; loop closure and playback speed remain preview policies.
@@ -75,11 +79,11 @@ Packages are local directories `dist/linux-x64` and `dist/win-x64`. Run
render smoke test. They include the .NET runtime, SDL3 native library, SPIR-V, render smoke test. They include the .NET runtime, SDL3 native library, SPIR-V,
original asset copies, prepared lab/Jimmy resources, audio and limitations. original asset copies, prepared lab/Jimmy resources, audio and limitations.
Windows cross-publishing and preliminary headless Wine64 rendering are verified. Windows cross-publishing and preliminary headless Wine64 rendering are verified.
A user reported initial native Windows rendering; this floor/animation update A user confirmed native Windows loading/rendering; this movement update still
still needs native Windows retesting. Full native Windows functionality is unverified. needs native Windows input/physics testing. Full native Windows functionality is unverified.
These are investigation packages, not a finished game release. These are investigation packages, not a finished game release.
`scripts/test.sh` runs 20 Python regressions, native C# data/algorithm checks, `scripts/test.sh` runs Python regressions, native C# data/collision/movement checks,
all PNG/ASE decoders, actual Vulkan GPU readback, dummy-device SDL3 audio, and all PNG/ASE decoders, actual Vulkan GPU readback, dummy-device SDL3 audio, and
original SHA-256 verification. Set `NEUTRON_WINDOW_TEST=1` with a working DISPLAY original SHA-256 verification. Set `NEUTRON_WINDOW_TEST=1` with a working DISPLAY
to include injected keyboard and swapchain-resize verification. Full OMT audit: to include injected keyboard and swapchain-resize verification. Full OMT audit:
+140
View File
@@ -0,0 +1,140 @@
# Controllable lab: provisional collision reconstruction
This checkpoint implements deterministic static geometric collision against the
extracted original scene. It is **not the recovered original collision solver**.
The original collision masks, class activation rules, shape selection, tolerances,
step handling and controller state integration are still unresolved. No original
runtime comparison establishes collision fidelity.
## Source geometry and inclusion policy
`level1b.omt` SHA-256:
`5a33d11311fc222631eb8f7384d1863192cb1f55f7e67035caa0ae12fd9892ab`.
The existing read-only extractor produces
`artifacts/extracted/level1b/scene.json` in unchanged original Y-up world units:
8,607 expanded vertices and 2,869 triangles. Collision uses **all nondegenerate
source triangles**, independent of `Mesh.Draws`, texture or material resolution.
The actual lab has no degenerate triangles removed by this rule. Mesh vertex/index
arrays and original files are not modified.
The lab includes 45 draw ranges / 325 triangles referencing unresolved material18.
The renderer correctly skips those ranges under recovered null-material behavior
(see graphics.md). Names include `blockfan`, `blockfan01`, `blockfan02`,
`blockscreen`, `blockwaterthing`, `blockwindow`, `blockcrate*`, `phoneblock*`,
`doorblock*`, plus Box/Plane/Cylinder/Mesh objects. These names and simplified
surfaces support a proxy interpretation; they do not prove a complete original
collision mask. Rendering visibility alone is therefore not used to discard them.
The regression creates a mesh with no visible draws and proves its original
triangles still block movement.
No decorative surface is excluded at this checkpoint: there is insufficient
specific evidence for a general exclusion rule. This conservative policy can block
on decorative surfaces or invisible proxies that original state/activation logic
would disable. Animated/dynamic scene entities are not added to this static mesh.
There is no invented room-sized collision box or coordinate clamp.
## Capsule coordinates and API
`src/GamePort/Game/SceneCollision.cs` accepts an extracted `Mesh` and provides:
- `Move(feetPosition, displacement, radius, height)` returns final feet `Position`,
final-support `Grounded`, and `HitCeiling`/`HitWall` impacts during the move.
- `GroundHeight(point, maxDrop, maxRise=0)` returns the highest triangle surface
inside the requested vertical interval at point.XZ. The default upper bound is
point.Y, so an overhead ceiling cannot replace the floor below a GAM root.
- `ClipCamera(target, desiredEye, radius=8)` sweeps a sphere from the camera target
toward the desired eye and stops at the first source surface.
The collision volume is a vertical capsule: its lower sphere center is feet.Y plus
radius, its upper center is feet.Y plus height minus radius. Height includes both
caps; all units retain original asset scale. Ground surfaces and ceiling undersides
are treated as two-sided geometry. The provisional walkable threshold is contact
normal.Y >=0.65 (about49.46 degrees); steeper contacts classify as walls. Skin is
0.05 world units; numerical tolerance is0.005. These constants are implementation
choices, not recovered original values.
The recovered standing Jimmy base bounds are Y=-64.6165..144.8196, height209.4361,
X width76.6604 (X=-34.1281..42.5323), and Z=-20.4173..49.0276. The collision code
does not assume a radius or a model-root offset. Callers supply dimensions and
render the base model with origin.Y=feet.Y-minBaseY. Regression radii24 and34.7
exercise both a narrower provisional torso volume and a larger standing volume;
neither is claimed as recovered. A base-mesh bounding radius can overestimate limbs
or underestimate a different animated pose, so it does not establish original
physics geometry.
At GAM root (5071.933105,26.661896,824.103943), the highest floor below root is
Y=0.5486332. Either tested radius stands at feet Y=0.59863245 after collision skin,
with no lateral spawn correction. GAM root data remains unchanged. The model's
negative base Y and the original actor-root offset remain separate from capsule
feet; the integrating controller is responsible for that transform.
## Algorithm and bounded behavior
Triangles are validated once; invalid indices/nonfinite positions are rejected,
and zero-area triangles are ignored. Per-triangle axis-aligned bounds only prune
queries; they are not solid collision volumes. Narrow-phase distance uses the
closest pair between the vertical capsule axis segment and a triangle: face
intersection, endpoint-to-triangle regions, and segment-to-each-edge distances.
This covers triangle edges and vertices that an axis-center ray would miss.
Movement first resolves initial overlaps, choosing the deepest contact for at most
12 passes. It then uses conservative advancement of capsule/triangle closest
features to find the earliest contact, with at most40 iterations per triangle.
The separating closest-pair plane supplies a safe advance; the finite-limit
fallback stops conservatively. Remaining motion is projected along the contact
plane and swept again, for at most8 slide passes. Support is queried at the final
position, so crossing a floor earlier does not keep the actor grounded after a
ledge. Falling/jumping actors are never snapped down by a ground-height query.
Face-region closest points use direct plane projection. When a closest contact
cannot be distinguished from that plane within0.005 units, its exact plane normal
is used. This avoids false horizontal normals from floating-point cancellation on
large coplanar triangle seams. Tests include far-apart vertices and original-scale
translated geometry. Float32 arithmetic is deterministic for the same input stream
on the tested .NET runtime; cross-architecture bit identity is not established.
Impossible spawn gaps, initially deeply intersecting solid volumes, more than8
successive slide constraints in one move, and extreme grazing feature sequences
can exhaust bounds and stop short. This is a bounded static checkpoint solver,
not a general rigid-body engine. There is no recovered stair step-up, moving
platform, entity collision, friction, original slope state, trigger or damage
behavior. Camera sweep does not depenetrate an initially embedded target.
## Verification
From GamePort, after normal asset preparation:
```bash
source scripts/env.sh
dotnet run --project tests/GamePort.CollisionTests/GamePort.CollisionTests.csproj
```
Eleven deterministic checks pass on local Linux .NET10. They compile linked
collision/Mesh/PNG sources without an additional NuGet test framework. Coverage:
flat support and bounded ground queries;10,000-unit floor/wall falls/sweeps;
wall sliding/departure; corner persistence; ceiling/underside; slope climbing and
landing; ledge departure; isolated triangle edges/vertices; camera sphere sweeps;
100,000-unit sweeps in a translated original-scale room;2,000 repeated floor-seam
moves; invisible proxy retention; malformed input; and actual lab data.
Actual lab tests use both radius24 and34.7, height209.4361. Two identical240-tick
traces at3 horizontal units/tick replay identically, stay finite/above the floor,
and travel720 units in the initial155-degree direction to approximately
(4767.5977,0.598948,171.56355). Six hundred eastward movement ticks encounter
original geometry and stop near these positions:
| Radius | X | Y | Z |
| --- | --- | --- | --- |
| 24 | 5405.448 | 0.601050 | 730.06195 |
| 34.7 | 5394.750 | 0.601352 | 724.18370 |
The small Z slide follows original source surfaces; no room boundary is supplied.
A synthetic jump trajectory using550 units/s initial speed and1064 units/s²
acceleration rises and lands back at (5071.933,0.598633,824.1037) for both radii.
Those trajectory inputs exercise the collision API and are not claimed as the
recovered complete jump state machine. Original-lab replay/wall/jump checks took
about0.5s combined locally, excluding scene loading/compilation.
These are algorithm and source-data tests. Controller/input/render integration,
GPU output and native Windows behavior require the primary checkpoint validation;
this report does not claim those tests ran as part of the isolated collision suite.
+266
View File
@@ -0,0 +1,266 @@
# Walking and jump checkpoint evidence
Static investigation, 2026-10-23. Sources: read-only `Original/Neutron.exe`,
`artifacts/binary/neutron.asm`, and the existing RTTI/PE analysis. No original
program was executed for these findings. Recovered instructions are not runtime
verification. Addresses below are executable VAs; for these `.text` ranges the
on-disk file offset is VA minus `0x400000`.
## Pointer and update conventions
`C3DJimmy` has its game interface at complete-object offset `0xC0`. The interface
vtable is `0x4A373C`, complete-object OMT vtable `0x4A3BDC`. Confusing these
pointers changes every field interpretation. Input dispatcher `0x438A60` and
update `0x437940` receive interface pointers; walking `0x438BC0`, ground apply
`0x437C40`, and air apply `0x437F90` receive complete-object pointers.
Relevant interface methods:
| Slot | Target | Meaning recovered here |
|---|---|---|
| `0x218` | `0x458960` | Grounded predicate |
| `0x248` | `0x471AD0` | Friction getter, interface `+0x150` |
| `0x24C` | `0x471AE0` | Friction setter |
| `0x310` | `0x472300` | Current position vector |
| `0x318` | `0x472330` | Set position vector |
| `0x328` | `0x4723F0` | Current Euler rotation |
| `0x334` | `0x458F90` | Add current Euler rotation |
| `0x36C` | `0x472660` | Set destination rotation |
World integration at `0x479EBB–0x479F8D` adds queued impulse to velocity and
clears the queue, adds object acceleration times `dt`, adds global gravity
times `dt`, then obtains the updated velocity for displacement times `dt`.
This is semiimplicit Euler. Game gravity is `(0,-800,0)`, set at `0x44D414`;
the engine initialization value `-5000` is superseded. Exact ordering of input,
rotation interpolation, physics and rendering across the entire frame remains
unverified. A fixed 60 Hz simulation is a port compatibility choice: original
speed increments are per invocation, while displacement and interpolation use
seconds. Original gameplay cadence has not been observed.
The physics support-hit branch `0x479DF7–0x479E54` sets grounded, zeroes
vertical velocity and sets object acceleration to cancel gravity. Because
queued impulses are applied afterward, a takeoff step which still finds
support can receive the full 550 impulse with no net gravity that step,
before airborne acceleration begins. A port's immediate grounded-to-airborne
transition can differ by one tick; do not claim an exact original jump apex.
Movement dispatcher mode 1 (`0x438B60`) logs and returns without running
walking input. Ordinary arrow acceleration/turn input is therefore absent
while that air mode is active. Air apply reuses takeoff speed and rotation,
preserving vertical velocity; with the default extra turn rate zero, it has
no new keyboard steering. Its nonzero extra-turn lateral calculation uses
`turnRate*(1-friction)*speed/55`, without the ground branch's additional `dt`
on lateral magnitude, and omits the keyboard side contribution. A port that
allows normal walking input in the air should identify that as an approximation.
## Normal keyboard walking
Constructor `0x437280` initializes complete-object fields `+0x6BC=30` speed
increment, `+0x6C0=35` speed decay, `+0x6C4=600` maximum speed,
`+0x6C8=0` current speed, `+0x6D4=0` extra turn rate. Constructor `0x4373B0`
sets friction to float `0.8` through `0x4711B0`, which forwards via slot
`0x24C`. The subsequent `0.7` at `0x4373C2` is a different property and must
not replace this friction value.
Arrow booleans are `0x50985D` left, `0x50985E` up, `0x50985F` right,
`0x509860` down. Key array starts at `0x509838`, indexed by Windows virtual
key; event setters `0x46A360`/`0x46A380` confirm these arrow indices.
Ignoring mouse/analog input and special gadgets, walking input proceeds in
this order:
1. Down enables the reverse flag at `0x438F9A–0x438FDD`.
2. Left has precedence over Right. Left at `0x43921C` sets yaw delta `+20`
degrees and side contribution `-1000`; Right at `0x4391A7` sets `-20`
and `+1000`. Either adds 30 to speed, capped at 600.
3. Up at `0x4392A9` separately adds 30, capped at 600. Thus Up+Left/Right
increments speed twice per invocation. Up halves any nonzero accumulated
yaw delta at `0x4392CC`; keyboard Up+Left/Right therefore produces
`+10`/`-10` rather than `+20`/`-20` degrees of target offset.
4. If reverse is enabled and the reverse-run flag is clear, subtract
`35*1.5=52.5` from speed, clamped below at `-600*0.5=-300`
(`0x439344–0x43937D`). Up+Down is processed in this order too.
5. If neither Up nor reverse marked the moving flag, decay speed by 35
toward zero (`0x439416–0x43948A`). Turning by itself adds 30 above but
still encounters this decay, because the turn branch sets `+0x6E6`,
not the forward moving flag `+0x6E4`.
6. If a yaw input was supplied, set destination yaw to **current yaw plus
this invocation's delta**, at `0x4395A1–0x4395C9`. It does not repeatedly
accumulate into the previous destination. A pending pushed setter argument
shifts the apparent local stack offset by four bytes here.
Rotation interpolation `0x43A420–0x43A5C2` wraps the yaw error to
`[-180,180]` and adds `error * dt * 3.7` to current yaw. The `3.7` is a
double at `0x4AFCF0`; pitch and roll use `4.5` at `0x4AFD38`. Consequently
held Left/Right alone requests about 74 degrees/s, and Up+Left/Right about
37 degrees/s, before any other turn source. The full interpolator also has
enable/dirty flags, so these formulas describe its active branch.
At zero pitch/roll, forward is `(-sin(yaw), 0, cos(yaw))` and right is
`(cos(yaw),0,sin(yaw))`. Ground apply `0x437CC9–0x437DF0` preserves vertical
velocity and computes:
```text
currentYaw += extraTurnRate * dt
sideSpeed = (extraTurnRate * (1-friction) * speed / 45 + sideContribution) * dt
velocityXZ = forward(currentYaw) * speed + right(currentYaw) * sideSpeed
```
The ordinary keyboard walking path does not assign `extraTurnRate`;
constructor zero is therefore the relevant baseline. Its lateral key term is
still present, e.g. Left at `dt=1/60` contributes about `-16.667` units/s to
local right. Original angle lookup converts float degrees by multiplying
float `45.5111122`, truncating through `0x47F940`, then masking with `0x3FFF`.
It uses 16384-entry float sine/cosine arrays. Continuous host trigonometry
is an approximation to that lookup.
### Reverse-run branch uncertainty
There is a branch when complete `+0x830 > 1.5` at `0x439383` which sets
speed 600, remembers current yaw plus 180 degrees, and sets reverse-run flag
`+0x828`. While that flag remains set, reverse keeps speed 600. Input release
clears the flag. However, the cached full executable disassembly only shows
initialization/reset and reads of this timer in the player code; no increment
was found. The timed transition's reachability is unresolved. Persistent
backpedal capped at -300 is the directly usable baseline. Do not silently add
a hold timer or claim the turnaround runs in the original.
## Basic jump and held-input behavior
Complete field `+0x7C4` is the movement mode (walking 0, air 1, flying 2,
seated 3), while `+0x7E8` is a separate jump state. The outer update
`0x437A7E–0x437C1C` calls air apply while jump is held or while an existing
air mode has not yet landed. A released, grounded player is returned to
walking, and **jump state is reset to 0** at `0x437B9E`
(`interface +0x728 = complete +0x7E8`).
Jump-held predicate `0x4378D0` accepts global right mouse, Insert, Shift,
numpad 0, or controller flag, subject to gadget-6/ground gating. The
previously cited Jimmy helper `0x42A730` is separate; the complete-object
vtable slot `0x158` used by base player here targets `0x4378D0`.
For jump states less than 3, `0x438148–0x43818D` sets additional object
acceleration Y to `gravityY*1.33 - gravityY`. Combined with global gravity,
net acceleration is approximately `-1064` units/s². The factor is float
`1.33000004` at `0x4AFCE4`. Input release from state 1 does not shorten the
impulse or alter this acceleration immediately.
Held dispatch table at `0x4387AC` is:
| State | Target | Effect |
|---|---|---|
| 0 | `0x438379` | If grounded, select `JUMP`, queue `(0,550,0)`, enter 1, clear hold timer `+0x874` |
| 1 | `0x4383FD` | Add `dt` to hold timer; after `>0.4`, run gadget/level checks and enter 3 |
| 2 | `0x438559` | On renewed hold, run gadget/level checks and enter 3 |
| 3 | `0x438693` | On ground contact, stop effect and enter 4 |
| 4 | `0x4387A1` | No action while held |
| 5 | `0x4386FB` | Reset to 0 if grounded |
Released table at `0x4387C4`, indexed by state minus 1, maps 1 to
`0x438732` (enter 2), 2 to no action, 3 to `0x438745` (stop effect, enter
4), 4 to `0x43879A` (grounded resets 0), and 5 to `0x43878C` (same).
The outer grounded-release reset usually handles landing before this table.
State 4 blocks automatic repetition while held. The zero-burn gadget-disabled
path below resets state 3 to 0 sooner and can repeat on landing while held.
### Long hold without an available gadget
Absence of a gadget does **not** leave the jump in state 1. At
`0x43848E–0x4384C8`, profile 0/item 3 state 0 or 4 branches to a path that
sets jump state 3 on every level except `VR04`. This skips the effect/animation
and velocity-Y=10 branch used when the gadget is allowed. `0x403950` retrieves
that profile item state. Initial current gadget is -1 at `0x42225F`.
Crucially, there is an earlier guard at `0x438192–0x43820D`. Complete
`+0x7F8` points to `C3DJetpackFire`, allocated in the player constructor
(`0x4374DF`, stored `0x4374EF`, debug name at `0x4F058C`). Its constructor
`0x421D80` initializes burn time `+0x6C0=0` at `0x421E68`; takeoff also
clears it at `0x438387–0x438391`. If this object exists and burn time is
<=0, states 3 or 4 reset to jump state 0, retain air mode 1, select `FALL`,
and return **before** changing object acceleration. Thus a normal disabled
gadget keeps the prior extra acceleration `-264` and remains ballistic at
net `-1064`, even after a long hold. No powered hover needs to be invented
for that case. If jump is still held when grounded after this state reset,
state 0 can queue another jump. This repeat-on-landing is a static call-path
consequence, awaiting original runtime comparison.
Only a null effect pointer or positive burn time reaches the following
distance-controlled acceleration branch for state >=3
(`0x438210–0x43830D`). For `g=-800`:
| Condition | Additional Y acceleration | Net including gravity |
|---|---:|---:|
| complete `+0x86C <500`, vertical velocity >=-1 | `-g -0.1*g = 880` | 80 |
| complete `+0x86C <500`, vertical velocity <-1 | `-g -0.3*g = 1040` | 240 |
| complete `+0x86C >=500` | `0.1*g-g = 720` | -80 |
`+0x86C` is **not a timer**: `0x425450–0x42547C` writes the distance between
Jimmy and his `C3DShadow` (`complete +0xA2C`). Jimmy constructor `0x42250C`
creates it via `0x43F640`, stores it at `0x42251C`, and names it with the
debug string `C3DShadow` at `0x4EE75C`. Shadow constructor `0x43F775` sets
its height field `+0x5EA` to 30. Update `0x4252E0` queries a vertical segment
from Jimmy root `P` to `P-(0,2500,0)` through `0x47C6E0`; the returned hit at
global `0x5CFC60` supplies the shadow's Y. `0x4253BE–0x42541C` sets shadow
position to `(playerX, hitY+height/2-2, playerZ)`. With default height30 the
distance is therefore `abs(playerRootY-hitY-13)`. Global `0x4F8210 !=0`, a
failed query, or absent shadow leaves the previous distance unchanged.
Ground-distance semantics are directly supported, but the exact original
query filter/surface selection remains unverified.
## Walking follow camera
Default fields at `0x437740` are local eye `(0,200,-350)`, target `(0,80,0)`,
and interpolation coefficients `(1.6,1,1.6)`. Normal nongadget walking sets
complete `+0x84C=10` at `0x438CC6`; camera construction adjusts those to:
```text
desiredEye = transformLocal(0, 200-2*10, -350) = transformLocal(0,180,-350)
lookTarget = transformLocal(0, 80+1.9*10, 0) = transformLocal(0,99,0)
```
Eye construction is `0x439625–0x439652`; target construction
`0x4396A9–0x4396DA`. The factor at `0x4AFCE8` is **double 1.9**.
`0x472980` transforms the local point by actor Euler rotation and position.
Normal interpolation at `0x4397B1–0x4397F1` is:
```text
camera += (desiredEye - previousCamera) * (1.6, 1.2, 1.6) * obstructionFactor * dt
```
The extra 0.2 in Y comes from double `0x4A2AD0`. Unobstructed factor is 1;
`0x43B820` performs a scene ray query, modifies the desired eye if hit, and
returns factor 1.5. The precise obstruction geometry and reverse-run camera
remain unported details. A special flag `+0x851` instead uses 0.2 on every
axis. The ordinary code looks toward the target using the camera position
saved at the start of the handler (`+0x714,+0x718,+0x71C`), then writes the
viewport angles; copying a conventional look-at using the new eye is a small
but real approximation.
## Actor pivot, scale and collider
No reliable original capsule/cylinder dimensions or actor-specific model
translation/scale were recovered in this investigation. Jimmy InitObject's
call with `(0,600,100)` is a **position setter**, slot `0x318`, and supplies
no collider dimensions. Shape-change hook `0x462270` reads the shape bounding
radius and six min/max values, forwarding them to object properties; this
does not establish a capsule radius or the player-specific collision proxy.
Raw standing model bounds, the GAM root placement and the preview sole
correction remain separately documented in existing scene/gameplay findings.
A capsule based on raw mesh width/height and a separate simulation-feet
origin is a port approximation. Neither the observed floor contact nor the
raw bounding box proves an original scale factor or root-to-feet offset.
## Checks and remaining work
Instruction ranges were re-read with bounded `objdump -d -M intel` commands;
float/double constants and jump tables were independently decoded from file
bytes with `tools/binary/pe_inspect.py` and Python `struct`. This caught three
material preliminary errors: key strafe signs, assuming the target yaw
accumulates, and interpreting the look-target multiplier as a float.
Outstanding: original frame phase order/cadence; reverse timer writer;
long-hold jump/repeat comparison; shadow query surface selection; original
collision proxy and shape converter mode-2/pivot behavior. No runtime fidelity
claim follows from the static formulas or a successful port build.
+15 -7
View File
@@ -30,17 +30,25 @@ avoids a Python runtime dependency in native packages. Mesh draw ranges omit nul
materials following the original renderer, while retaining their geometry. Default materials following the original renderer, while retaining their geometry. Default
normal atlas and morph transforms are supported by binary/duplicate-asset evidence. normal atlas and morph transforms are supported by binary/duplicate-asset evidence.
Physics arithmetic fragments are independent of a full controller; no invented `Game/LabSimulation` supplies the no-gadget walking/jump checkpoint, using recovered
collision/task system has been silently inserted. The main program remains a speed/yaw/impulse/airborne/camera formulas. `FixedStepClock` supplies a deliberate
scene investigation runtime; future simulation must be a separate stateful module 60Hz port policy independent of rendering; original invocation cadence remains
with recovered timing, input, collision, triggers and progression. unverified. SDL events feed held keyboard/mouse state; focus/minimize clear input
and pause simulation, while C pauses for inspection and R resets the start area.
`SceneCollision` sweeps/slides a vertical capsule against retained original scene
triangles, including invisible proxies, and clips the chase camera with a sphere
sweep. Solver/masks/radius/pivot are explicit approximations. The physical position
is feet; a separate original-root height feeds camera math and standing mesh minimum
Y feeds visual placement. GAM/ASE data is preserved. There is no task/trigger engine.
Application/PreviewCharacterPlacement and PreviewAnimationLibrary keep inspection Application/PreviewCharacterPlacement and PreviewAnimationLibrary keep inspection
policies separate from gameplay fragments. Ground contact is a model-only offset policies available alongside the walking checkpoint. Inspector ground contact is a model-only offset
derived once from visible surfaces and the standing bind pose, with raw source derived once from visible surfaces and the standing bind pose, with raw source
placement preserved. Clip selection displays actual still/moving state and does placement preserved. Clip selection displays actual still/moving state and does
not simulate walking/jumping actions. These policies need replacement/integration not simulate walking/jumping actions. In walking mode, original idle/run/backpedal/
as original controller, actor transforms and state behavior are recovered. jump/fall clips follow simulation state. Looping, timing, transitions and the visual
floor-derived pivot still require original comparison and further recovery.
Subsystem implementation and validated ownership are documented in Subsystem implementation and validated ownership are documented in
`infrastructure.md`, `analysis/graphics.md` and `rendering.md` as they become `infrastructure.md`, `analysis/graphics.md` and `rendering.md` as they become
+11 -3
View File
@@ -13,6 +13,7 @@ separate evidence categories. **The game is not fully reconstructed/playable yet
| Windows x64 publish | Pass | Correct PE32+ app and SDL3.dll; initial native rendering user-reported | | Windows x64 publish | Pass | Correct PE32+ app and SDL3.dll; initial native rendering user-reported |
| Windows package under Wine64 | Preliminary headless pass | Two frames, exit0; fixed-time readback identical to Linux on lavapipe; validation disabled | | Windows package under Wine64 | Preliminary headless pass | Two frames, exit0; fixed-time readback identical to Linux on lavapipe; validation disabled |
| Corrected Windows preview under Wine64 | Preliminary window pass | Six frames, key2 animation switch, resize800x600, exit0; validation disabled | | Corrected Windows preview under Wine64 | Preliminary window pass | Six frames, key2 animation switch, resize800x600, exit0; validation disabled |
| Windows walking package under Wine64 | Preliminary240-step window pass | SDL arrows/Shift, walking/jump/landing and800x600 resize; matches Linux movement statistics; validation disabled |
| Linux self-contained package | Native run verified | Two headless frames without SDK/source/originals mounted | | Linux self-contained package | Native run verified | Two headless frames without SDK/source/originals mounted |
| Vulkan1.3 lab | llvmpipe + GTX1070 | Real indexed/textured/depth frame/readback; validation enabled, zero errors | | Vulkan1.3 lab | llvmpipe + GTX1070 | Real indexed/textured/depth frame/readback; validation enabled, zero errors |
| Original camera/projection | Data/math integrated | GAM camera, recovered FOV/clips; startup/follow behavior not compared | | Original camera/projection | Data/math integrated | GAM camera, recovered FOV/clips; startup/follow behavior not compared |
@@ -26,10 +27,15 @@ separate evidence categories. **The game is not fully reconstructed/playable yet
| Mouse/relative input/controller | Incomplete | SDL entry point declaration alone is not behavior | | Mouse/relative input/controller | Incomplete | SDL entry point declaration alone is not behavior |
| Audio stream | Linux dummy device | Original11025Hz mono WAV consumed10752bytes/500ms; speakers untested | | Audio stream | Linux dummy device | Original11025Hz mono WAV consumed10752bytes/500ms; speakers untested |
| Physics fragments/RNG | Standalone C# tests | Recovered arithmetic; controller/jump/collision state incomplete | | Physics fragments/RNG | Standalone C# tests | Recovered arithmetic; controller/jump/collision state incomplete |
| No-gadget walking/jump controller | Linux tests and GPU replay pass | Recovered speed/yaw/ballistic formulas; transient jump state/order approximated |
| Static source collision | 11 deterministic groups pass | Capsule sweep/slide, walls/ceilings/slopes/ledges; all2869 lab triangles retained; masks/dimensions provisional |
| Simulation cadence | 13 movement groups pass | Fixed60Hz independent of60/120/144Hz rendering, ten-minute finite run; original cadence unresolved |
| Walking camera and animation | Linux headless/window pass | Original five motion clips, recovered eye180/target99; pivot, timing and obstruction solver provisional |
| Walk SDL input/resize | GTX1070/Xvfb240-step pass | Arrows/Shift injected through SDL; travel1250.12,jump/landing; resize800x600; zero validation errors |
| Intro/task/entity/gameplay loop | Incomplete | GAM data recovery is not task execution or gameplay | | Intro/task/entity/gameplay loop | Incomplete | GAM data recovery is not task execution or gameplay |
| Menus/AI/combat/progression/saves | Incomplete | Required future work | | Menus/AI/combat/progression/saves | Incomplete | Required future work |
| Original execution | Attempted under isolated Wine11 | Window created, GL/Vulkan rendering unusable; no reference comparison | | Original execution | Attempted under isolated Wine11 | Window created, GL/Vulkan rendering unusable; no reference comparison |
| Native Windows functionality | Partially user-reported | Initial window/3D frame displayed; corrected build/input/audio/resize still unverified natively | | Native Windows functionality | Loading/rendering user-confirmed | This movement checkpoint/input/audio/resize still unverified natively |
Generated evidence: artifacts/final-tests.log, test-level1b.ppm, test-player.ppm, Generated evidence: artifacts/final-tests.log, test-level1b.ppm, test-player.ppm,
resize-input.ppm, package-linux.ppm, extracted/audit.json and reference*/ logs. resize-input.ppm, package-linux.ppm, extracted/audit.json and reference*/ logs.
@@ -38,5 +44,7 @@ visual equivalence. Windows cross-publishing must not be represented as Windows
runtime validation. Package scope and prerequisites are in infrastructure.md. runtime validation. Package scope and prerequisites are in infrastructure.md.
Known visual/behavior limits include incomplete lighting/fog/blend/culling/material Known visual/behavior limits include incomplete lighting/fog/blend/culling/material
mapping, inferred initial look-at, preview animation loop/speed, no reconstructed mapping, inferred model/root pivot, provisional collision/cadence/animation timing,
intro/controller/collision/trigger execution and no original comparison captures. close-wall camera clipping near Jimmy, absent intro/trigger/interaction execution,
and no original comparison captures. Walk evidence: artifacts/walk-tests.log,
test-walk.ppm, walk-start.png and walk-window.ppm. Original fidelity is unverified.
+9
View File
@@ -24,3 +24,12 @@
model-only floor correction derived from standing soles and visible geometry, model-only floor correction derived from standing soles and visible geometry,
with explicit preview labeling and regression tests. Preserve GAM/ASE data and with explicit preview labeling and regression tests. Preserve GAM/ASE data and
per-frame morph displacement; this is not the original collision algorithm. per-frame morph displacement; this is not the original collision algorithm.
9. **Controllable lab before complete scene.** Integrate evidence-backed no-gadget
walking/jumping/camera now, with separate stateful simulation and explicit
provisional source-triangle capsule collision. Rendering does not set the number
of movement calls: use60Hz until original cadence is recovered. Preserve source
GAM/ASE positions; keep physical feet, inferred actor-root height and visual
pivot separate. Include invisible geometry rather than inventing visibility
masks. Document the skipped intro, missing interactions, transient jump-state
simplification, animation timing and close-wall camera limitation. Test against
source geometry and build both packages without calling this a faithful full scene.
+15 -8
View File
@@ -22,6 +22,8 @@ downloads are permitted by the specification; no project material is uploaded.
- Original OMT-derived world geometry/materials/textures; original ASE model and - Original OMT-derived world geometry/materials/textures; original ASE model and
retained-base vertex morph animation samples; original GAM entities/camera. retained-base vertex morph animation samples; original GAM entities/camera.
- Self-contained Linux/Windows publishing with matching native SDL3 libraries. - Self-contained Linux/Windows publishing with matching native SDL3 libraries.
- Controllable lab with separate60Hz simulation, source-triangle capsule collision,
original no-gadget walking/jump formulas, chase camera and original motion clips.
The renderer completes submissions synchronously. This deliberately simple early The renderer completes submissions synchronously. This deliberately simple early
implementation is maintainable but does not target final performance. It currently implementation is maintainable but does not target final performance. It currently
@@ -52,20 +54,25 @@ animation state/render sorting are incomplete. See rendering.md for evidence.
Windows drivers remain untested. See reference-testing.md for exact scope. Windows drivers remain untested. See reference-testing.md for exact scope.
- Corrected Windows preview also passes a six-frame Wine64 window/input/animation - Corrected Windows preview also passes a six-frame Wine64 window/input/animation
selection/resize smoke (validation disabled). Native Windows retest is pending. selection/resize smoke (validation disabled). Native Windows retest is pending.
- Movement checkpoint packages rebuilt: Linux GTX1070 window and Windows Wine64
window each pass240 steps, SDL arrows/Shift, jump/landing and resize800x600.
Movement statistics match (travel1250.12, maxrise137.62, grounded final).
Linux Khronos validation is enabled with zero errors; Wine validation is disabled.
## Scope limits ## Scope limits
This is an investigation/runtime foundation, not complete reconstructed gameplay. This is a controllable lab checkpoint, not complete reconstructed gameplay.
Original collisions, task/trigger execution, introductory cutscene, inventory, Collision solver/masks/dimensions, pivot,60Hz cadence, camera obstruction and
combat, enemies, progression, save/load, original mouse/control behavior and animation state timing remain provisional. Original task/trigger execution,
remaining scenes are incomplete. Player rendering at the original startpoint is introductory cutscene, inventory, combat, enemies, progression, save/load, mouse
an animation inspection preview; default idle samples are identical. Keys1/2/3/4 steering and remaining scenes are incomplete. The default now walks/jumps from
select original clips. Preview floor correction is separate from original physics; the original start area; `--inspect` retains clip selection with keys1/2/3/4.
its transform and interpolation loop/speed are not a recovered state machine. Default idle samples remain identical. The floor-derived visual transform is
separate from original physics; details are in the movement/collision reports.
Packages include local copies of asset directories (ASE/png/gam/omt), original Packages include local copies of asset directories (ASE/png/gam/omt), original
font PNGs/NewGame/readme, lab/Jimmy scene resources, recovered music, .NET runtime, font PNGs/NewGame/readme, lab/Jimmy scene resources, recovered music, .NET runtime,
SDL3, SPIR-V and these limitations. Legacy EXEs/DLLs, old user save slots, tool SDL3, SPIR-V and these limitations. Legacy EXEs/DLLs, old user save slots, tool
caches and analysis databases are not runtime dependencies. Vulkan drivers remain caches and analysis databases are not runtime dependencies. Vulkan drivers remain
platform prerequisites. Initial native Windows rendering is user-reported; the platform prerequisites. Initial native Windows rendering is user-reported; the
corrected preview and broader native Windows functionality remain unverified. movement checkpoint and broader native Windows functionality remain unverified.
+49 -14
View File
@@ -1,15 +1,52 @@
# Progress — current checkpoint # Progress — current checkpoint
**Full reconstruction is incomplete.** The current milestone is an evidence-backed **Full reconstruction is incomplete.** The current milestone is an evidence-backed
asset recovery toolchain and a native original-scene/animation investigation asset recovery toolchain and a controllable original lab with local Linux/Windows
runtime with local Linux/Windows packages. No completed playable-scene claim. packages. This is a movement checkpoint, not a completely reconstructed scene.
## Controllable lab checkpoint
The user confirmed that the previous Windows build loads and renders and asked
to advance. The default now runs walking/backpedaling/turning, ballistic no-gadget
jumping, source-triangle collision, a chase camera, and original idle/run/backpedal/
jump/fall clips. Arrows move, Shift/Insert/numpad0/right mouse jump, R resets, C
pauses for inspection/resumes, F11 fullscreen, Escape quits. The intro is skipped.
Recovered arithmetic and addresses are in `analysis/movement-checkpoint.md`.
Notable corrections: Left precedence; current-yaw target offsets rather than
accumulating destination yaw; Up halves keyboard turn; turning alone decays speed;
no ordinary midair arrow steering; disabled-gadget long hold can repeat on landing;
normal camera eye `(0,180,-350)` and target `(0,99,0)`. Exact original frame order
is unresolved; the transient disabled-gadget state3 transition is collapsed.
Explicit port approximations: fixed60Hz cadence, capsule radius24 and standing
height209.4361, floor-derived model/root separation, static sweep/slide solver and
all-source-triangle mask, camera sphere obstruction, animation state/loop timing.
Collision retains all2869 lab triangles including325 invisible proxy triangles.
Original solver/masks, actor pivot/scale, stairs/dynamic objects and state activation
remain unresolved. At walls the clipped camera can move close to Jimmy.
Verification: 11 collision and13 movement groups pass, including real lab source
geometry, long/high-speed sweeps, held/re-pressed jumping, ten-minute stability,
deterministic replay and60/120/144Hz presentation yielding the same simulation.
A240-step GPU walk/jump replay travels1250.12 units, jumps once, lands, and ends
grounded; maximum rise137.62. This is port behavior, not original fidelity proof.
The Linux SDL window run receives injected movement/jump keys, resizes800x600,
and reports zero Vulkan validation errors on GTX1070. Headless llvmpipe also
reports zero errors. User-confirmed native Windows loading/rendering applies to
the previous build; native Windows movement validation remains outstanding.
Both self-contained packages were rebuilt. The Linux package passes the same
GTX1070 window replay; the Windows package passes240 windowed frames under isolated
Wine64 with SDL keys/jump/resize and identical movement statistics (validation
disabled there). Wine is preliminary compatibility evidence, not native Windows.
One additional inspector-window regression was not executed because automatic
approval review was unavailable; the full headless inspector regressions passed.
## Latest user-reported preview fix ## Latest user-reported preview fix
The user ran the Windows build and observed a static Jimmy partially inside the The user ran the Windows build and observed a static Jimmy partially inside the
lab floor. This verifies initial Windows startup/rendering by user report, with lab floor. This verifies initial Windows startup/rendering by user report, with
OS/GPU/version/input/audio details unspecified. Updated native Windows testing OS/GPU/version/input/audio details unspecified. The user subsequently confirmed that the corrected build loads and renders.
remains pending.
Both issues were reproduced from actual assets: jimstop has two byte-identical Both issues were reproduced from actual assets: jimstop has two byte-identical
vertex poses, and its minimum local Y=-64.6165 plus GAM Y=26.6619 places the soles vertex poses, and its minimum local Y=-64.6165 plus GAM Y=26.6619 places the soles
@@ -77,17 +114,15 @@ swapchain image count mismatch. Native Windows/VM access has been requested for
reference/fidelity and native port validation. These failures do not establish reference/fidelity and native port validation. These failures do not establish
original behavior. Static reverse engineering can continue independently. original behavior. Static reverse engineering can continue independently.
Original controller, collision resolution, introductory LABEXP cutscene, entity Original collision resolution, introductory LABEXP cutscene, entity activation/
activation/task/trigger execution, interactions, combat, AI, progression, menus, task/trigger execution, interactions, combat, AI, progression, menus, mouse aiming
mouse behavior and saves remain incomplete. Gravity/impulse integration fragments and saves remain incomplete. The no-gadget controller checkpoint requires original
are tested, but the player jump state machine adds extra acceleration and is not runtime comparison. Animation looping/speed and collider/pivot remain approximations.
implemented as a complete controller. Animation looping/speed are explicit preview Rendering material/lighting/fog/blend state mapping also remains incomplete.
policies. Rendering material/lighting/fog/blend state mapping also remains incomplete.
Three subagents contributed independent investigation/infrastructure work and then Two investigators contributed movement evidence/tests and collision implementation/
hit a usage limit. Primary reviewed/integrated their work, corrected texture and tests for this checkpoint. Primary integrated the runtime, input, animation, packages
visibility assumptions, finished scripts/tests/packages, and owns the current files. and verification. Reports distinguish static recovery from runtime checks.
Do not assume their final reports imply completed gameplay.
## Continuation ## Continuation
+12
View File
@@ -67,3 +67,15 @@ frames, preview correction+38.503Y, injected key2 switched to Run cycle, and
tests separately enabled Khronos validation and reported zero errors. The latest tests separately enabled Khronos validation and reported zero errors. The latest
artifacts/windows-smoke contains that updated window test, superseding the earlier artifacts/windows-smoke contains that updated window test, superseding the earlier
headless capture. Native Windows retesting is still pending. headless capture. Native Windows retesting is still pending.
The controllable lab checkpoint supersedes that capture with
`python3 tools/recon/reference_capture.py --port-walk --seconds 60`.
The rebuilt self-contained Windows package rendered240 windowed frames under
isolated Wine64, received SDL arrow/Shift events, jumped/landed, resized800x600,
and exited0. Travel1250.12, maxrise137.62, one jump, two landing transitions and
final grounded feet `(4524.3555,0.62445164,-280.2899)` match Linux replay statistics.
The extra landing transition is stepping off/recontacting source geometry; it is
not a second jump. Validation was disabled in Wine. Logs/readback now live in
`artifacts/windows-smoke/`, with harness summary `artifacts/walk-wine-test.log`.
This validates preliminary port compatibility only; native Windows movement and
original-game movement/collision/camera comparison remain outstanding.
+7 -1
View File
@@ -11,6 +11,10 @@ evidence, not original source. Runtime behavior has not yet been observed.
- `analysis/assets.md`, `file-formats.md`: recovered OMT/ASE/texture/audio evidence. - `analysis/assets.md`, `file-formats.md`: recovered OMT/ASE/texture/audio evidence.
- `gam-format.md`: fully accounted GAM wire format and exact round-trip validation. - `gam-format.md`: fully accounted GAM wire format and exact round-trip validation.
- `analysis/gameplay.md`: original controls, startpoint/camera, entities and limits. - `analysis/gameplay.md`: original controls, startpoint/camera, entities and limits.
- `analysis/movement-checkpoint.md`: corrected walking/yaw/airborne/jump-held and
chase-camera evidence; original frame order, pivot and collider remain unresolved.
- `analysis/collision-checkpoint.md`: explicit provisional source-triangle solver,
geometry/mask choices, tests and limitations; not an original algorithm recovery.
## Function map under investigation ## Function map under investigation
@@ -23,7 +27,9 @@ these coefficients timestep-independent. Gravity and jump have since been
resolved: game setup 0x44D414 sets gravity Y=-800; jump branch 0x4383B3 queues resolved: game setup 0x44D414 sets gravity Y=-800; jump branch 0x4383B3 queues
Y=550 impulse, consumed/cleared at 0x479EBB..0x479EF2. Semi-implicit free-motion Y=550 impulse, consumed/cleared at 0x479EBB..0x479EF2. Semi-implicit free-motion
fragment implemented in Game/RecoveredMotion.cs and regression tested; collision fragment implemented in Game/RecoveredMotion.cs and regression tested; collision
and activation gating remain unresolved. See analysis/gameplay.md. and activation gating remain unresolved. The no-gadget controller checkpoint now
integrates the corrected formulas; see analysis/movement-checkpoint.md rather than
the older preliminary movement interpretations.
## Unresolved ## Unresolved
+21 -11
View File
@@ -18,23 +18,32 @@
- [x] Preliminary Wine64 Windows-package render; exact fixed-time readback matches Linux. - [x] Preliminary Wine64 Windows-package render; exact fixed-time readback matches Linux.
- [x] Isolated copied-original Wine attempts; actual failures documented. - [x] Isolated copied-original Wine attempts; actual failures documented.
- [x] Correct preview floor overlap, identify still idle, add explicit animation inspection controls/tests. - [x] Correct preview floor overlap, identify still idle, add explicit animation inspection controls/tests.
- [ ] Retest corrected Windows build natively; initial rendering is user-reported. - [x] User confirmed corrected Windows build loads and renders.
- [x] Controllable lab: recovered walking/backpedal/turn/no-gadget jump formulas,
original animation clips, fixed60Hz simulation, collision and chase camera.
- [x] 11 collision and13 movement test groups; source lab and synthetic edge cases,
render-rate independence, held/re-pressed jumping and ten-minute stability.
- [x] Linux240-step SDL key/jump/resize replay and GPU readback, zero validation errors.
- [x] Rebuilt both packages; packaged Linux window and preliminary Windows Wine64
window240-step walking/key/jump/resize pass, matching movement statistics.
- [ ] Test this movement checkpoint natively on Windows (previous rendering confirmed).
## Next implementation priorities ## Next implementation priorities
1. Recover full player physics/collision and controller before calling any preview 1. Replace provisional capsule collision/pivot with recovered original behavior.
playable. Trace `0x479D20` past displacement integration, shared collision call Trace `0x479D20` past displacement integration, shared collision call
via interface slot0x130 in `0x462520`, and object collision caches. Retain via interface slot0x130 in `0x462520`, and object collision caches. Retain
invisible/null-material geometry; its exact collision masks remain unresolved. invisible/null-material geometry; its exact collision masks remain unresolved.
Recover original actor/model pivot, scale and spawn settling: the preview now Recover original actor/model pivot, scale and spawn settling: the preview now
uses a floor-derived model offset, which must be replaced with proven behavior. uses a floor-derived model offset, which must be replaced with proven behavior.
2. Finish airborne state table at `0x437F90` (jump at `0x4383B3`, extra acceleration Recover stair/step handling, dynamic collider activation, and camera obstruction.
`0x438148`, held predicate `0x42A730`, mode dispatch `0x437A8C`). Gravity is -800, 2. Compare reconstructed no-gadget airborne behavior with the original. Walking,
queued impulse550, but normal jump states add gravity*1.33-gravity; avoid the jump state table and zero-fuel held/re-press repeat path are now recovered in
incomplete '-800 only' jump model. Map landing, retrigger and jetpack gates. `analysis/movement-checkpoint.md`; transient state3 and takeoff phase remain
3. Finish walking friction/input/cadence: `0x438BC0`, `0x437C40`, destination yaw approximations. Recover powered gadget states and original animation routing.
`0x472660`, yaw interpolation `0x43A430`. Resolve mixed per-call acceleration 3. Recover original frame cadence and phase order; current fixed60Hz preserves
with timed integration; rendering refresh rate must not accelerate movement. per-call speed increments independent of rendering. Find reverse timer+0x830
writer before implementing its >1.5 turnaround branch. Recover mouse steering.
4. Execute LV1B STARTEXP/LABEXP intro. GAM parsing supplies records; implement task 4. Execute LV1B STARTEXP/LABEXP intro. GAM parsing supplies records; implement task
prerequisites, object activation/visibility, camera triggers and progression prerequisites, object activation/visibility, camera triggers and progression
from code/observations. Then build a complete small scene (VR01 if useful). from code/observations. Then build a complete small scene (VR01 if useful).
@@ -46,7 +55,8 @@
## Required validation and expansion ## Required validation and expansion
- [ ] Usable original reference captures under local Windows/VM or working Wine. - [ ] Usable original reference captures under local Windows/VM or working Wine.
- [ ] Original walking/jump/collision/camera/input comparisons and first complete scene. - [ ] Original walking/jump/collision/camera/input comparisons and first complete scene
including intro/triggers/interactions (movement checkpoint implemented).
- [ ] Physical audio output and original SFX/music timing, mixing/panning/positional audio. - [ ] Physical audio output and original SFX/music timing, mixing/panning/positional audio.
- [ ] Fullscreen, minimized-window, mouse/relative capture, display scaling and controller behavior. - [ ] Fullscreen, minimized-window, mouse/relative capture, display scaling and controller behavior.
- [ ] Pickups, score/health, gadgets/inventory, combat/AI, all levels and transitions. - [ ] Pickups, score/health, gadgets/inventory, combat/AI, all levels and transitions.
+13 -12
View File
@@ -20,23 +20,24 @@ for rid in linux-x64 win-x64; do
cp -a docs/. "$out/docs/" cp -a docs/. "$out/docs/"
cp README.md "$out/SOURCE-README.md" cp README.md "$out/SOURCE-README.md"
cat > "$out/README.md" <<'NOTES' cat > "$out/README.md" <<'NOTES'
# Neutron original-scene investigation package # Neutron controllable lab checkpoint
Linux: run ./launch-scene.sh. Windows: run launch-scene.cmd. Linux: run ./launch-scene.sh. Windows: run launch-scene.cmd.
Append --headless --frames 2 to render without a window, or --screenshot lab.ppm Append --headless --frames 2 to render without a window, or --screenshot lab.ppm
to save GPU readback. A Vulkan 1.3 graphics driver/loader is required. to save GPU readback. A Vulkan 1.3 graphics driver/loader is required.
This package includes the .NET runtime, SDL3, shaders and local asset copies. This package includes the .NET runtime, SDL3, shaders and local asset copies.
The default shows the original lab and Jimmy's still idle pose, grounded on the The default opens the controllable original lab. Arrows walk/backpedal/turn;
visible floor for preview. Press 1 for idle, 2 for a running animation cycle, Shift, Insert, numpad 0 or right mouse jump. R resets to the original start area;
3 for a jump animation cycle, or 4 for a scratch animation cycle. C switches C pauses into inspection and resumes the chase camera. F11 fullscreen, Escape quit.
stored/orbit camera; arrows/WASD orbit, +/- zoom, F11 fullscreen, Escape quit. Inspection: arrows/WASD orbit, +/- zoom, 1 idle, 2 run, 3 jump, 4 scratch preview.
These are investigation controls; animation selection does not move the player. Append --inspect to start directly in the old scene inspector.
This is not the finished playable game. Original collision, controller, intro, This checkpoint implements recovered walking/jump/camera arithmetic and original
interactions, progression, AI and saves remain incomplete. Animation loop/speed animation clips. Collision solver/masks, collider/pivot, 60Hz cadence and animation
and grounding are preview policies. A user verified initial rendering on Windows; state timing remain provisional. Intro, interactions, progression, AI and saves
this corrected build still needs native Windows retesting. remain incomplete. A user verified rendering on Windows; this new movement build
still needs native Windows input/physics testing.
See BUILD-AND-LIMITATIONS.md, COMPATIBILITY.md and docs/ for evidence and remaining See BUILD-AND-LIMITATIONS.md, COMPATIBILITY.md and docs/ for evidence and remaining
work. SOURCE-README.md describes development from the separate source repository. work. SOURCE-README.md describes development from the separate source repository.
@@ -46,11 +47,11 @@ cat > dist/linux-x64/launch-scene.sh <<'LAUNCH'
#!/usr/bin/env bash #!/usr/bin/env bash
set -euo pipefail set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)" here="$(cd "$(dirname "$0")" && pwd)"
exec "$here/GamePort" --assets "$here/assets" --scene "$here/scenes/level1b/scene.json" --level gam/level1b.gam --original-camera --with-player "$@" exec "$here/GamePort" --assets "$here/assets" --scene "$here/scenes/level1b/scene.json" --level gam/level1b.gam --walk "$@"
LAUNCH LAUNCH
chmod +x dist/linux-x64/launch-scene.sh chmod +x dist/linux-x64/launch-scene.sh
cat > dist/win-x64/launch-scene.cmd <<'LAUNCH' cat > dist/win-x64/launch-scene.cmd <<'LAUNCH'
@echo off @echo off
"%~dp0GamePort.exe" --assets "%~dp0assets" --scene "%~dp0scenes\level1b\scene.json" --level gam/level1b.gam --original-camera --with-player %* "%~dp0GamePort.exe" --assets "%~dp0assets" --scene "%~dp0scenes\level1b\scene.json" --level gam/level1b.gam --walk %*
LAUNCH LAUNCH
printf '%s\n' 'Local Linux and Windows investigation packages prepared in dist/.' printf '%s\n' 'Local Linux and Windows investigation packages prepared in dist/.'
+5 -1
View File
@@ -4,11 +4,14 @@ source "$(dirname "$0")/env.sh"
python3 -m unittest discover -s tests -p 'test_*.py' -v python3 -m unittest discover -s tests -p 'test_*.py' -v
python3 tools/extractors/prepare.py --audio sounds musicsecretlab python3 tools/extractors/prepare.py --audio sounds musicsecretlab
dotnet run --project tests/GamePort.DataTests -- ../Original dotnet run --project tests/GamePort.DataTests -- ../Original
dotnet run --project tests/GamePort.CollisionTests -- ../Original
dotnet run --project tests/GamePort.MovementTests -- ../Original
dotnet build GamePort.csproj dotnet build GamePort.csproj
dotnet run --no-build -- --verify-assets --assets ../Original dotnet run --no-build -- --verify-assets --assets ../Original
python3 tools/extractors/omt.py ../Original/omt/level1b.omt --scene --output artifacts/extracted/level1b python3 tools/extractors/omt.py ../Original/omt/level1b.omt --scene --output artifacts/extracted/level1b
dotnet run --no-build -- --headless --assets ../Original --scene artifacts/extracted/level1b/scene.json --level gam/level1b.gam --original-camera --screenshot artifacts/test-level1b.ppm dotnet run --no-build -- --headless --assets ../Original --scene artifacts/extracted/level1b/scene.json --level gam/level1b.gam --original-camera --screenshot artifacts/test-level1b.ppm
dotnet run --no-build -- --headless --with-player --time 0.05 --screenshot artifacts/test-player.ppm dotnet run --no-build -- --inspect --headless --with-player --time 0.05 --screenshot artifacts/test-player.ppm
dotnet run --no-build -- --headless --smoke-walk --screenshot artifacts/test-walk.ppm
dotnet run --no-build -- --headless --animation artifacts/extracted/animations/jimrun/animation.json --time 0 --screenshot artifacts/test-run-start.ppm dotnet run --no-build -- --headless --animation artifacts/extracted/animations/jimrun/animation.json --time 0 --screenshot artifacts/test-run-start.ppm
dotnet run --no-build -- --headless --animation artifacts/extracted/animations/jimrun/animation.json --frames 7 --screenshot artifacts/test-run-advanced.ppm dotnet run --no-build -- --headless --animation artifacts/extracted/animations/jimrun/animation.json --frames 7 --screenshot artifacts/test-run-advanced.ppm
python3 - <<'PY' python3 - <<'PY'
@@ -20,4 +23,5 @@ SDL_AUDIODRIVER=dummy dotnet run --no-build -- --audio-smoke artifacts/extracted
python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json python3 tools/recon/inventory.py ../Original --verify docs/original-manifest.json
if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then if [[ "${NEUTRON_WINDOW_TEST:-0}" == 1 ]]; then
dotnet run --no-build -- --scene artifacts/extracted/level1b/scene.json --smoke-window --frames 6 --screenshot artifacts/test-window.ppm dotnet run --no-build -- --scene artifacts/extracted/level1b/scene.json --smoke-window --frames 6 --screenshot artifacts/test-window.ppm
dotnet run --no-build -- --smoke-walk --screenshot artifacts/test-walk-window.ppm
fi fi
@@ -1,11 +1,13 @@
using GamePort.Assets; using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application; namespace GamePort.Application;
/// <summary>Explicit animation inspection; does not simulate player actions.</summary> /// <summary>Shared original clips for explicit inspection and simulation pose selection.</summary>
public sealed class PreviewAnimationLibrary public sealed class PreviewAnimationLibrary
{ {
private readonly Dictionary<uint, (string Name, MorphAnimation Animation)> choices = []; private readonly Dictionary<uint, (string Name, MorphAnimation Animation)> choices = [];
private readonly Dictionary<PlayerPose, MorphAnimation> movement = [];
public MorphAnimation Current { get; private set; } public MorphAnimation Current { get; private set; }
public string Name { get; private set; } public string Name { get; private set; }
public string WindowTitle => $"Jimmy Neutron — scene preview | {Name}{(Current.HasVertexMotion ? "" : " (still pose)")} | 1 idle, 2 run, 3 jump, 4 scratch | C camera"; public string WindowTitle => $"Jimmy Neutron — scene preview | {Name}{(Current.HasVertexMotion ? "" : " (still pose)")} | 1 idle, 2 run, 3 jump, 4 scratch | C camera";
@@ -15,6 +17,22 @@ public sealed class PreviewAnimationLibrary
Current = new MorphAnimation(manifest); Current = new MorphAnimation(manifest);
Name = Path.GetFileName(Path.GetDirectoryName(Path.GetFullPath(manifest)))!; Name = Path.GetFileName(Path.GetDirectoryName(Path.GetFullPath(manifest)))!;
var parent = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(manifest)!, "..")); var parent = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(manifest)!, ".."));
var loaded = new Dictionary<string, MorphAnimation>(StringComparer.Ordinal)
{ [Path.GetFullPath(manifest)] = Current };
MorphAnimation Load(string path)
{
path = Path.GetFullPath(path);
if (loaded.TryGetValue(path, out var cached)) return cached;
var clip = new MorphAnimation(path);
if (clip.Base.Vertices.Length != Current.Base.Vertices.Length
|| !clip.Base.Indices.SequenceEqual(Current.Base.Indices)
|| !clip.Base.Vertices.Select(v => v.Uv).SequenceEqual(Current.Base.Vertices.Select(v => v.Uv))
|| clip.Texture.Width != Current.Texture.Width || clip.Texture.Height != Current.Texture.Height
|| !clip.Texture.Rgba.SequenceEqual(Current.Texture.Rgba))
throw new InvalidDataException($"Animation family mismatch: {path}");
loaded[path] = clip;
return clip;
}
foreach (var (scancode, folder, label) in new[] foreach (var (scancode, folder, label) in new[]
{ {
(30u, "jimstop", "Idle"), (31u, "jimrun", "Run cycle"), (30u, "jimstop", "Idle"), (31u, "jimrun", "Run cycle"),
@@ -23,16 +41,17 @@ public sealed class PreviewAnimationLibrary
{ {
var path = Path.Combine(parent, folder, "animation.json"); var path = Path.Combine(parent, folder, "animation.json");
if (!File.Exists(path)) continue; if (!File.Exists(path)) continue;
var clip = Path.GetFullPath(path) == Path.GetFullPath(manifest) ? Current : new MorphAnimation(path); var clip = Load(path);
if (clip.Base.Vertices.Length != Current.Base.Vertices.Length
|| !clip.Base.Indices.SequenceEqual(Current.Base.Indices)
|| !clip.Base.Vertices.Select(v => v.Uv).SequenceEqual(Current.Base.Vertices.Select(v => v.Uv))
|| clip.Texture.Width != Current.Texture.Width || clip.Texture.Height != Current.Texture.Height
|| !clip.Texture.Rgba.SequenceEqual(Current.Texture.Rgba))
throw new InvalidDataException($"Animation family mismatch: {path}");
choices[scancode] = (label, clip); choices[scancode] = (label, clip);
if (ReferenceEquals(clip, Current)) Name = label; if (ReferenceEquals(clip, Current)) Name = label;
} }
foreach (var (pose, folder) in new[] { (PlayerPose.Idle, "jimstop"), (PlayerPose.Run, "jimrun"),
(PlayerPose.Backpedal, "jimbackpedal"), (PlayerPose.Jump, "jimjump"), (PlayerPose.Fall, "jimfall") })
{
var path = Path.Combine(parent, folder, "animation.json");
if (!File.Exists(path)) continue;
movement[pose] = Load(path);
}
} }
public bool Select(uint scancode) public bool Select(uint scancode)
@@ -42,4 +61,13 @@ public sealed class PreviewAnimationLibrary
Name = clip.Name; Name = clip.Name;
return true; return true;
} }
public bool SelectPose(PlayerPose pose)
{
if (!movement.TryGetValue(pose, out var clip)) throw new InvalidDataException($"Prepare original {pose} animation first");
if (ReferenceEquals(Current, clip)) return false;
Current = clip;
Name = pose.ToString();
return true;
}
} }
+17
View File
@@ -0,0 +1,17 @@
namespace GamePort.Game;
/// <summary>Explicit port policy: 60 simulation calls/second, independent of presentation.</summary>
public sealed class FixedStepClock
{
public const float Step = 1f / 60;
private double accumulated;
public int Advance(double elapsed)
{
if (!double.IsFinite(elapsed) || elapsed < 0) throw new ArgumentOutOfRangeException(nameof(elapsed));
accumulated += Math.Min(elapsed, 0.25);
var steps = (int)Math.Floor((accumulated + 1e-10) * 60);
accumulated -= steps / 60.0;
return steps;
}
public void Reset() => accumulated = 0;
}
+145
View File
@@ -0,0 +1,145 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump);
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall }
/// <summary>
/// No-gadget walking checkpoint. Recovered input/arithmetic is described in
/// movement-checkpoint.md. Capsule, floor-derived pivot and 60Hz are port policies;
/// original collision, intro, object interactions and animation timing remain open.
/// </summary>
public sealed class LabSimulation
{
public const float BodyRadius = 24; // Provisional, not a recovered collider dimension.
private readonly SceneCollision collision;
private readonly Vector3 sourceStart;
private readonly float startYaw, modelMinimumY, rootHeight;
private float targetYaw, jumpHeldTime;
private int jumpState;
public float BodyHeight { get; }
public Vector3 Position { get; private set; } // Feet, not original actor root.
public Vector3 Velocity { get; private set; }
public float Yaw { get; private set; }
public float Speed { get; private set; }
public bool Grounded { get; private set; }
public PlayerPose Pose => Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
: Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
public int Steps { get; private set; }
public int Jumps { get; private set; }
public int Landings { get; private set; }
public int WallHits { get; private set; }
public float Travel { get; private set; }
public float MaximumRise { get; private set; }
public 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)
* Matrix4x4.CreateTranslation(Position - new Vector3(0, modelMinimumY, 0));
public LabSimulation(SceneCollision collision, Mesh standingPose, Vector3 start, float yaw)
{
this.collision = collision;
sourceStart = start;
startYaw = yaw;
var bounds = standingPose.Bounds();
modelMinimumY = bounds.Min.Y;
BodyHeight = bounds.Max.Y - bounds.Min.Y;
var floor = collision.GroundHeight(start, 2500)
?? throw new InvalidDataException("No support below GAM startpoint");
rootHeight = start.Y - floor;
Reset();
}
public void Reset()
{
var floor = collision.GroundHeight(sourceStart, 2500)!.Value;
Position = new(sourceStart.X, floor + SceneCollision.Skin, sourceStart.Z);
Velocity = Vector3.Zero;
Yaw = targetYaw = startYaw;
Speed = jumpHeldTime = 0;
jumpState = 0;
Grounded = true;
Steps = Jumps = Landings = WallHits = 0;
Travel = MaximumRise = 0;
CameraEye = DesiredEye();
}
// EXE 0x47F940 truncates, then degree lookup masks to the 16384-entry table.
// Table generated with modern trig; x87 bit-identical table recovery is pending.
public static (float Sin, float Cos) Trig(float degrees)
{
var index = (int)(degrees * 45.5111122f) & 0x3fff;
var radians = index * (Math.Tau / 16384);
return ((float)Math.Sin(radians), (float)Math.Cos(radians));
}
public void Step(PlayerInput input)
{
const float dt = FixedStepClock.Step;
var wasGrounded = Grounded;
float lateral = 0;
if (Grounded)
{
if (!input.Jump) jumpState = 0;
float yawDelta = 0;
if (input.Left) { yawDelta += 20; lateral = -1000; Speed = RecoveredMotion.AddSpeed(Speed); }
else if (input.Right) { yawDelta -= 20; lateral = 1000; Speed = RecoveredMotion.AddSpeed(Speed); }
if (input.Forward) { yawDelta *= 0.5f; Speed = RecoveredMotion.AddSpeed(Speed); }
if (yawDelta != 0) targetYaw = Yaw + yawDelta;
if (input.Backward) Speed = MathF.Max(Speed - 52.5f, -300);
else if (!input.Forward) Speed = RecoveredMotion.ReleaseSpeed(Speed);
}
var yawError = MathF.IEEERemainder(targetYaw - Yaw, 360);
Yaw = (Yaw + yawError * dt * 3.7f) % 360;
var (sin, cos) = Trig(Yaw);
var velocity = new Vector3(-sin * Speed, Velocity.Y, cos * Speed);
if (Grounded) velocity += new Vector3(cos, 0, sin) * (lateral * dt);
var impulse = Vector3.Zero;
if (Grounded && input.Jump && jumpState == 0)
{
impulse.Y = RecoveredMotion.JumpImpulse;
jumpState = 1;
jumpHeldTime = 0;
Grounded = false;
Jumps++;
}
if (!Grounded && jumpState == 1)
{
if (!input.Jump) jumpState = 2;
else if ((jumpHeldTime += dt) > 0.4f) jumpState = 0; // Zero-fuel jetpack path resets to FALL.
}
else if (!Grounded && jumpState == 2 && input.Jump)
jumpState = 0; // Renewed hold enters the same disabled-gadget reset path.
var displacement = RecoveredMotion.Integrate(ref velocity, ref impulse,
RecoveredMotion.Gravity * 0.33f, RecoveredMotion.Gravity, dt);
var before = Position;
var result = collision.Move(Position, displacement, BodyRadius, BodyHeight);
Position = result.Position;
Grounded = result.Grounded && velocity.Y <= 0;
if (Grounded && velocity.Y < 0 || result.HitCeiling && velocity.Y > 0) velocity.Y = 0;
Velocity = velocity;
if (!wasGrounded && Grounded) Landings++;
if (result.HitWall) WallHits++;
Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z));
MaximumRise = Math.Max(MaximumRise, Position.Y - sourceStart.Y + rootHeight);
Steps++;
var desired = DesiredEye();
var delta = (desired - CameraEye) * new Vector3(1.6f, 1.2f, 1.6f) * dt;
CameraEye = collision.ClipCamera(CameraTarget, CameraEye + delta);
}
private Vector3 DesiredEye()
{
var (sin, cos) = Trig(Yaw);
return collision.ClipCamera(CameraTarget, ActorRoot + new Vector3(sin * 350, 180, -cos * 350));
}
public static PlayerInput SmokeInput(int step) => new(step < 120, false, false,
step >= 120 && step < 180, step >= 72 && step < 84);
public bool SmokePassed => Steps >= 240 && Travel > 50 && MaximumRise > 20 && Jumps > 0 && Landings > 0 && Grounded;
public string Report => $"Walk checkpoint: steps={Steps}, travel={Travel:F2}, jumps={Jumps}, landings={Landings}, max rise={MaximumRise:F2}, wall hits={WallHits}, grounded={Grounded}, feet={Position}.";
}
+316
View File
@@ -0,0 +1,316 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>
/// Provisional geometric reconstruction for the controllable-scene checkpoint.
/// Uses source triangles, including invisible proxies, without claiming the
/// original game's unrecovered collision-mask/state rules or solver tolerances.
/// Positions are the bottom of a vertical capsule in original Y-up world units.
/// </summary>
public sealed class SceneCollision
{
public const float Skin = 0.05f;
public const float MinimumGroundNormal = 0.65f;
private const float Tolerance = 0.005f;
private readonly Triangle[] triangles;
public int TriangleCount => triangles.Length;
private readonly record struct Triangle(Vector3 A, Vector3 B, Vector3 C,
Vector3 Normal, Vector3 Min, Vector3 Max);
private readonly record struct Hit(float Time, Vector3 Normal);
private readonly record struct Pair(Vector3 Capsule, Vector3 Surface)
{
public float DistanceSquared => Vector3.DistanceSquared(Capsule, Surface);
}
public SceneCollision(Mesh mesh)
{
if (mesh.Indices.Length % 3 != 0) throw new ArgumentException("Collision indices must be triangles", nameof(mesh));
var result = new List<Triangle>();
// Render visibility is not a proven collision mask. Original null-material
// proxies remain present and block movement in this provisional policy.
for (var i = 0; i < mesh.Indices.Length; i += 3)
{
if (mesh.Indices[i] >= mesh.Vertices.Length || mesh.Indices[i + 1] >= mesh.Vertices.Length
|| mesh.Indices[i + 2] >= mesh.Vertices.Length)
throw new ArgumentException("Collision index outside vertex table", nameof(mesh));
var a = mesh.Vertices[mesh.Indices[i]].Position;
var b = mesh.Vertices[mesh.Indices[i + 1]].Position;
var c = mesh.Vertices[mesh.Indices[i + 2]].Position;
if (!Finite(a) || !Finite(b) || !Finite(c)) throw new ArgumentException("Nonfinite collision coordinate", nameof(mesh));
var normal = Vector3.Cross(b - a, c - a);
var normalLengthSquared = normal.LengthSquared();
if (!float.IsFinite(normalLengthSquared)) throw new ArgumentException("Collision triangle exceeds finite arithmetic range", nameof(mesh));
if (normalLengthSquared < 0.000001f) continue;
result.Add(new Triangle(a, b, c, Vector3.Normalize(normal),
Vector3.Min(a, Vector3.Min(b, c)), Vector3.Max(a, Vector3.Max(b, c))));
}
triangles = result.ToArray();
}
/// <summary>Highest walkable surface in the requested vertical interval.</summary>
public float? GroundHeight(Vector3 point, float maxDrop, float maxRise = 0)
{
if (!Finite(point) || !float.IsFinite(maxDrop) || !float.IsFinite(maxRise) || maxDrop < 0 || maxRise < 0)
throw new ArgumentOutOfRangeException(nameof(point));
float? highest = null;
var low = point.Y - maxDrop;
var high = point.Y + maxRise;
foreach (var triangle in triangles)
{
if (MathF.Abs(triangle.Normal.Y) < MinimumGroundNormal || point.X < triangle.Min.X - Tolerance
|| point.X > triangle.Max.X + Tolerance || point.Z < triangle.Min.Z - Tolerance
|| point.Z > triangle.Max.Z + Tolerance || triangle.Min.Y > high || triangle.Max.Y < low) continue;
var t = triangle;
var denominator = (t.B.Z - t.C.Z) * (t.A.X - t.C.X) + (t.C.X - t.B.X) * (t.A.Z - t.C.Z);
if (MathF.Abs(denominator) < 0.000001f) continue;
var u = ((t.B.Z - t.C.Z) * (point.X - t.C.X) + (t.C.X - t.B.X) * (point.Z - t.C.Z)) / denominator;
var v = ((t.C.Z - t.A.Z) * (point.X - t.C.X) + (t.A.X - t.C.X) * (point.Z - t.C.Z)) / denominator;
if (u < -0.00001f || v < -0.00001f || u + v > 1.00001f) continue;
var y = u * t.A.Y + v * t.B.Y + (1 - u - v) * t.C.Y;
if (y < low - Tolerance || y > high + Tolerance || highest.HasValue && y <= highest.Value) continue;
highest = y;
}
return highest;
}
/// <summary>Resolve initial overlaps and sweep/slide a capsule continuously.</summary>
public CollisionMove Move(Vector3 feetPosition, Vector3 displacement, float radius, float height)
{
Validate(feetPosition, displacement, radius, height);
var position = feetPosition;
var grounded = false;
var ceiling = false;
var wall = false;
// Recover gently from a spawn touching/intersecting source triangles. A
// finite iteration bound also handles impossible narrow-gap input safely.
for (var iteration = 0; iteration < 12; iteration++)
{
var bestDepth = Tolerance;
var bestNormal = Vector3.Zero;
CapsuleBounds(position, radius + Skin, height, out var min, out var max);
foreach (var triangle in triangles)
{
if (!Overlaps(min, max, triangle)) continue;
var pair = Closest(position, radius, height, triangle);
var distance = MathF.Sqrt(pair.DistanceSquared);
var depth = radius + Skin - distance;
if (depth <= bestDepth) continue;
bestDepth = depth;
bestNormal = ContactNormal(pair, triangle, position, height, displacement);
}
if (bestNormal == Vector3.Zero) break;
position += bestNormal * bestDepth;
Classify(bestNormal, ref grounded, ref ceiling, ref wall);
}
var remaining = displacement;
for (var iteration = 0; iteration < 8 && remaining.LengthSquared() > 0.00000001f; iteration++)
{
var hit = Sweep(position, remaining, radius, height);
if (!hit.HasValue) { position += remaining; remaining = Vector3.Zero; break; }
position += remaining * Math.Clamp(hit.Value.Time, 0, 1);
Classify(hit.Value.Normal, ref grounded, ref ceiling, ref wall);
remaining *= 1 - Math.Clamp(hit.Value.Time, 0, 1);
var into = Vector3.Dot(remaining, hit.Value.Normal);
if (into < 0) remaining -= hit.Value.Normal * into;
else break;
}
// Contact persistence matters for a stationary character and tangential
// motion. This query does not snap a falling or jumping actor to a floor.
// Grounded describes support at the final position, not a floor crossed
// earlier in this move (for example after walking over a ledge).
grounded = false;
CapsuleBounds(position, radius + Skin + Tolerance, height, out var contactMin, out var contactMax);
foreach (var triangle in triangles)
{
if (!Overlaps(contactMin, contactMax, triangle)) continue;
var pair = Closest(position, radius, height, triangle);
if (pair.DistanceSquared <= (radius + Skin + Tolerance) * (radius + Skin + Tolerance))
Classify(ContactNormal(pair, triangle, position, height, displacement), ref grounded, ref ceiling, ref wall);
}
if (!Finite(position)) throw new InvalidOperationException("Collision produced nonfinite position");
return new CollisionMove(position, grounded, ceiling, wall);
}
/// <summary>Sphere sweep for a follow camera; stops before source geometry.</summary>
public Vector3 ClipCamera(Vector3 target, Vector3 desiredEye, float radius = 8)
{
Validate(target - Vector3.UnitY * radius, desiredEye - target, radius, radius * 2);
var movement = desiredEye - target;
var hit = Sweep(target - Vector3.UnitY * radius, movement, radius, radius * 2);
return hit.HasValue ? target + movement * Math.Clamp(hit.Value.Time, 0, 1) : desiredEye;
}
private Hit? Sweep(Vector3 position, Vector3 movement, float radius, float height)
{
CapsuleBounds(position, radius + Skin, height, out var startMin, out var startMax);
CapsuleBounds(position + movement, radius + Skin, height, out var endMin, out var endMax);
var min = Vector3.Min(startMin, endMin);
var max = Vector3.Max(startMax, endMax);
Hit? closest = null;
foreach (var triangle in triangles)
{
if (!Overlaps(min, max, triangle)) continue;
var limit = closest?.Time ?? 1f;
var time = 0f;
for (var iteration = 0; iteration < 40; iteration++)
{
var current = position + movement * time;
var pair = Closest(current, radius, height, triangle);
var distance = MathF.Sqrt(pair.DistanceSquared);
var normal = ContactNormal(pair, triangle, current, height, movement);
var closing = -Vector3.Dot(movement, normal);
if (distance <= radius + Skin + Tolerance)
{
// A tangent or departing contact must not lock movement.
if (closing > 0.000001f || distance < radius - Tolerance)
closest = new Hit(time, normal);
break;
}
if (closing <= 0.000001f) break;
// The closest-pair plane separates two convex shapes. Advancing
// to where that plane's gap closes is conservative even when the
// closest feature later changes, unlike endpoint-only sampling.
var advance = (distance - radius - Skin) / closing;
if (advance <= 0.0000001f)
{
closest = new Hit(time, normal);
break;
}
time += advance;
if (time > limit || time > 1) break;
if (iteration == 39) closest = new Hit(time, normal);
}
}
return closest;
}
private static Pair Closest(Vector3 feet, float radius, float height, Triangle triangle)
{
var p = feet + Vector3.UnitY * radius;
var q = feet + Vector3.UnitY * (height - radius);
var denominator = Vector3.Dot(triangle.Normal, q - p);
if (MathF.Abs(denominator) > 0.000001f)
{
var time = Vector3.Dot(triangle.Normal, triangle.A - p) / denominator;
if (time is >= 0 and <= 1)
{
var intersection = p + (q - p) * time;
if (Vector3.DistanceSquared(intersection, ClosestPoint(intersection, triangle)) < 0.000001f)
return new Pair(intersection, intersection);
}
}
var best = new Pair(p, ClosestPoint(p, triangle));
var candidate = new Pair(q, ClosestPoint(q, triangle));
if (candidate.DistanceSquared < best.DistanceSquared) best = candidate;
candidate = ClosestSegments(p, q, triangle.A, triangle.B);
if (candidate.DistanceSquared < best.DistanceSquared) best = candidate;
candidate = ClosestSegments(p, q, triangle.B, triangle.C);
if (candidate.DistanceSquared < best.DistanceSquared) best = candidate;
candidate = ClosestSegments(p, q, triangle.C, triangle.A);
if (candidate.DistanceSquared < best.DistanceSquared) best = candidate;
return best;
}
private static Vector3 ClosestPoint(Vector3 p, Triangle t)
{
var ab = t.B - t.A;
var ac = t.C - t.A;
var ap = p - t.A;
var d1 = Vector3.Dot(ab, ap);
var d2 = Vector3.Dot(ac, ap);
if (d1 <= 0 && d2 <= 0) return t.A;
var bp = p - t.B;
var d3 = Vector3.Dot(ab, bp);
var d4 = Vector3.Dot(ac, bp);
if (d3 >= 0 && d4 <= d3) return t.B;
var vc = d1 * d4 - d3 * d2;
if (vc <= 0 && d1 >= 0 && d3 <= 0) return t.A + ab * (d1 / (d1 - d3));
var cp = p - t.C;
var d5 = Vector3.Dot(ab, cp);
var d6 = Vector3.Dot(ac, cp);
if (d6 >= 0 && d5 <= d6) return t.C;
var vb = d5 * d2 - d1 * d6;
if (vb <= 0 && d2 >= 0 && d6 <= 0) return t.A + ac * (d2 / (d2 - d6));
var va = d3 * d6 - d5 * d4;
if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0)
return t.B + (t.C - t.B) * ((d4 - d3) / (d4 - d3 + d5 - d6));
// Once the face region is known, project onto its plane directly. A
// barycentric sum of far-apart vertices loses enough precision to give
// an axis-aligned floor a false horizontal normal at original scales.
return p - t.Normal * Vector3.Dot(p - t.A, t.Normal);
}
private static Pair ClosestSegments(Vector3 p, Vector3 q, Vector3 a, Vector3 b)
{
var d1 = q - p;
var d2 = b - a;
var r = p - a;
var aa = Vector3.Dot(d1, d1);
var ee = Vector3.Dot(d2, d2);
var f = Vector3.Dot(d2, r);
float s, t;
if (aa <= 0.00000001f && ee <= 0.00000001f) return new Pair(p, a);
if (aa <= 0.00000001f) { s = 0; t = Math.Clamp(f / ee, 0, 1); }
else
{
var c = Vector3.Dot(d1, r);
if (ee <= 0.00000001f) { t = 0; s = Math.Clamp(-c / aa, 0, 1); }
else
{
var dot = Vector3.Dot(d1, d2);
var denominator = aa * ee - dot * dot;
s = MathF.Abs(denominator) > 0.00000001f ? Math.Clamp((dot * f - c * ee) / denominator, 0, 1) : 0;
t = (dot * s + f) / ee;
if (t < 0) { t = 0; s = Math.Clamp(-c / aa, 0, 1); }
else if (t > 1) { t = 1; s = Math.Clamp((dot - c) / aa, 0, 1); }
}
}
return new Pair(p + d1 * s, a + d2 * t);
}
private static Vector3 ContactNormal(Pair pair, Triangle triangle, Vector3 feet, float height, Vector3 movement)
{
var difference = pair.Capsule - pair.Surface;
if (difference.LengthSquared() > 0.00000001f)
{
var distance = difference.Length();
var planeDistance = Vector3.Dot(pair.Capsule - triangle.A, triangle.Normal);
// A contact indistinguishable from the face plane at our world-unit
// tolerance uses its exact normal. Otherwise tiny closest-edge
// rounding on a coplanar triangle seam can turn a tangent sweep into
// a large sideways/upward correction at high velocity.
if (MathF.Abs(planeDistance) >= distance - Tolerance && MathF.Abs(planeDistance) > Tolerance)
return planeDistance > 0 ? triangle.Normal : -triangle.Normal;
return difference / distance;
}
var side = Vector3.Dot(feet + Vector3.UnitY * (height * 0.5f) - triangle.A, triangle.Normal);
if (MathF.Abs(side) > 0.0001f) return side > 0 ? triangle.Normal : -triangle.Normal;
return Vector3.Dot(movement, triangle.Normal) > 0 ? -triangle.Normal : triangle.Normal;
}
private static void CapsuleBounds(Vector3 feet, float radius, float height, out Vector3 min, out Vector3 max)
{
min = feet - new Vector3(radius, Skin + Tolerance, radius);
max = feet + new Vector3(radius, height + Skin + Tolerance, radius);
}
private static bool Overlaps(Vector3 min, Vector3 max, Triangle t) =>
min.X <= t.Max.X && max.X >= t.Min.X && min.Y <= t.Max.Y && max.Y >= t.Min.Y && min.Z <= t.Max.Z && max.Z >= t.Min.Z;
private static void Classify(Vector3 normal, ref bool ground, ref bool ceiling, ref bool wall)
{
if (normal.Y >= MinimumGroundNormal) ground = true;
else if (normal.Y <= -MinimumGroundNormal) ceiling = true;
else wall = true;
}
private static bool Finite(Vector3 p) => float.IsFinite(p.X) && float.IsFinite(p.Y) && float.IsFinite(p.Z);
private static void Validate(Vector3 position, Vector3 movement, float radius, float height)
{
if (!Finite(position) || !Finite(movement) || !float.IsFinite(radius) || !float.IsFinite(height)
|| radius <= 0 || height < radius * 2)
throw new ArgumentOutOfRangeException(nameof(radius), "Finite capsule coordinates, positive radius and height >= diameter are required");
}
}
public readonly record struct CollisionMove(Vector3 Position, bool Grounded, bool HitCeiling, bool HitWall);
+2
View File
@@ -21,11 +21,13 @@ internal static unsafe class Sdl
public const uint InitVideo=0x20, InitAudio=0x10; public const uint InitVideo=0x20, InitAudio=0x10;
public const ulong WindowVulkan=0x10000000, WindowResizable=0x20, WindowHighPixelDensity=0x2000; public const ulong WindowVulkan=0x10000000, WindowResizable=0x20, WindowHighPixelDensity=0x2000;
public const uint Quit=0x100, KeyDown=0x300, KeyUp=0x301, WindowResized=0x206, WindowPixelSizeChanged=0x207, WindowFocusLost=0x20F; public const uint Quit=0x100, KeyDown=0x300, KeyUp=0x301, WindowResized=0x206, WindowPixelSizeChanged=0x207, WindowFocusLost=0x20F;
public const uint WindowFocusGained=0x20E, WindowMinimized=0x209, WindowRestored=0x20B, MouseButtonDown=0x401, MouseButtonUp=0x402;
[StructLayout(LayoutKind.Explicit,Size=128)] public struct Event [StructLayout(LayoutKind.Explicit,Size=128)] public struct Event
{ {
[FieldOffset(0)]public uint Type; [FieldOffset(0)]public uint Type;
[FieldOffset(16)]public uint WindowId; [FieldOffset(16)]public uint WindowId;
[FieldOffset(24)]public uint Scancode; [FieldOffset(24)]public uint Scancode;
[FieldOffset(24)]public byte MouseButton;
[FieldOffset(28)]public uint Key; [FieldOffset(28)]public uint Key;
[FieldOffset(36)]public byte Down; [FieldOffset(36)]public byte Down;
[FieldOffset(37)]public byte Repeat; [FieldOffset(37)]public byte Repeat;
+102 -14
View File
@@ -3,6 +3,7 @@ using System.Numerics;
using GamePort.Assets; using GamePort.Assets;
using GamePort.Application; using GamePort.Application;
using GamePort.Audio; using GamePort.Audio;
using GamePort.Game;
using GamePort.Platform; using GamePort.Platform;
using GamePort.Rendering.Vulkan; using GamePort.Rendering.Vulkan;
@@ -39,6 +40,9 @@ internal static class Program
--original-camera Stored GAM start camera and recovered projection --original-camera Stored GAM start camera and recovered projection
--animation PATH Prepared Jimmy animation.json; place at GAM startpoint --animation PATH Prepared Jimmy animation.json; place at GAM startpoint
--with-player Use prepared jimstop animation in scene --with-player Use prepared jimstop animation in scene
--walk Controllable lab (default with prepared lab)
--inspect Pause simulation and inspect scene/animation
--smoke-walk Deterministic 240-step movement/jump check
--time SECONDS Fixed animation time for comparisons --time SECONDS Fixed animation time for comparisons
--headless Render offscreen through Vulkan --headless Render offscreen through Vulkan
--screenshot PATH Save actual GPU readback as PPM --screenshot PATH Save actual GPU readback as PPM
@@ -48,9 +52,11 @@ internal static class Program
--verify-assets Decode all original PNG/ASE files --verify-assets Decode all original PNG/ASE files
--smoke-window Test keyboard event/resize (requires --frames 6 or more) --smoke-window Test keyboard event/resize (requires --frames 6 or more)
--no-validation Disable development validation --no-validation Disable development validation
Viewer: C toggles stored/orbit camera, arrows/WASD orbit, +/- zoom, Walk: arrows move/turn; Shift, Insert or right mouse jump; R reset.
C pauses into inspection / resumes chase camera. F11 fullscreen, Escape quit.
Inspector: arrows/WASD orbit, +/- zoom,
F11 fullscreen, Escape quit. Animation preview: 1 idle, 2 run, 3 jump, 4 scratch. F11 fullscreen, Escape quit. Animation preview: 1 idle, 2 run, 3 jump, 4 scratch.
Gameplay, original animation speed/state and cutscenes remain under reconstruction. Collision/pivot/cadence and animation timing are provisional. Intro/interactions remain incomplete.
"""); """);
return 0; return 0;
} }
@@ -90,9 +96,17 @@ internal static class Program
var target = (bounds.Min + bounds.Max) / 2; var target = (bounds.Min + bounds.Max) / 2;
var radius = Math.Max(Vector3.Distance(bounds.Min, bounds.Max) * 1.15f, 1); var radius = Math.Max(Vector3.Distance(bounds.Min, bounds.Max) * 1.15f, 1);
var animationPath = Option(args, "--animation"); var animationPath = Option(args, "--animation");
if (args.Contains("--with-player") && scene != null) var walkSmoke = args.Contains("--smoke-walk");
if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode.");
if (walkSmoke && args.Contains("--smoke-window")) throw new ArgumentException("Select one window smoke mode.");
var walking = !args.Contains("--inspect") && !args.Contains("--smoke-window") && (args.Contains("--walk") || walkSmoke
|| defaultScene && animationPath == null && !args.Contains("--time"));
if ((args.Contains("--with-player") || args.Contains("--walk") || defaultScene || walking) && scene != null)
animationPath ??= Path.Combine(Path.GetDirectoryName(scene)!, "../animations/jimstop/animation.json"); animationPath ??= Path.Combine(Path.GetDirectoryName(scene)!, "../animations/jimstop/animation.json");
if (walking && (scene == null || originalStart == null))
throw new ArgumentException("Walking requires a scene and matching GAM startpoint.");
PreviewAnimationLibrary? animations = null; PreviewAnimationLibrary? animations = null;
LabSimulation? simulation = null;
var characterOffset = mesh.Vertices.Length; var characterOffset = mesh.Vertices.Length;
var characterModel = Matrix4x4.Identity; var characterModel = Matrix4x4.Identity;
if (animationPath != null) if (animationPath != null)
@@ -101,17 +115,21 @@ internal static class Program
throw new ArgumentException("A scene and matching GAM are required to place an animated player."); throw new ArgumentException("A scene and matching GAM are required to place an animated player.");
animations = new PreviewAnimationLibrary(animationPath); animations = new PreviewAnimationLibrary(animationPath);
var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase")); var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase"));
if (walking) simulation = new LabSimulation(new SceneCollision(mesh), standingPose, originalStart.Position, originalStart.Rotation.Y);
var placement = PreviewCharacterPlacement.Create(mesh, standingPose, originalStart.Position, originalStart.Rotation.Y); var placement = PreviewCharacterPlacement.Create(mesh, standingPose, originalStart.Position, originalStart.Rotation.Y);
characterModel = placement.Model; characterModel = placement.Model;
mesh = animations.Current.AppendTo(mesh); mesh = animations.Current.AppendTo(mesh);
Console.WriteLine($"Preview floor correction: +{placement.VerticalCorrection:F3} Y; original GAM position remains unchanged."); if (walking)
Console.WriteLine("Scene preview: 1 idle (still pose), 2 run, 3 jump, 4 scratch. Playback loop/speed are preview policies; gameplay is incomplete."); Console.WriteLine("Controllable lab: arrows move/turn; Shift/Insert/right mouse jump; R reset; C pause/inspect; F11 fullscreen; Escape quit. Collision, pivot and timing remain provisional.");
else
Console.WriteLine($"Preview floor correction: +{placement.VerticalCorrection:F3} Y. 1 idle, 2 run, 3 jump, 4 scratch.");
} }
Console.WriteLine($"Loaded original geometry: {mesh.Vertices.Length} vertices, {mesh.Indices.Length / 3} triangles, {mesh.Textures.Count + (scene == null ? 1 : 0)} textures."); Console.WriteLine($"Loaded original geometry: {mesh.Vertices.Length} vertices, {mesh.Indices.Length / 3} triangles, {mesh.Textures.Count + (scene == null ? 1 : 0)} textures.");
var fixedTimeText = Option(args, "--time"); var fixedTimeText = Option(args, "--time");
double? fixedTime = fixedTimeText == null ? null : double.Parse(fixedTimeText, System.Globalization.CultureInfo.InvariantCulture); double? fixedTime = fixedTimeText == null ? null : double.Parse(fixedTimeText, System.Globalization.CultureInfo.InvariantCulture);
var headless = args.Contains("--headless"); var headless = args.Contains("--headless");
var frames = int.Parse(Option(args, "--frames") ?? (headless ? "1" : "0")); var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : headless ? "1" : "0"));
if (walkSmoke && frames < 240) throw new ArgumentException("Walk smoke requires at least 240 frames.");
var smoke = args.Contains("--smoke-window"); var smoke = args.Contains("--smoke-window");
if (frames < 0 || (smoke && (headless || frames < 6))) if (frames < 0 || (smoke && (headless || frames < 6)))
throw new ArgumentException("Invalid frame count; window smoke requires at least six frames."); throw new ArgumentException("Invalid frame count; window smoke requires at least six frames.");
@@ -119,7 +137,7 @@ internal static class Program
if (!headless) if (!headless)
{ {
if (!Sdl.SDL_Init(Sdl.InitVideo)) throw new InvalidOperationException(Sdl.Error); if (!Sdl.SDL_Init(Sdl.InitVideo)) throw new InvalidOperationException(Sdl.Error);
window = Sdl.SDL_CreateWindow(animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera", 960, 720, window = Sdl.SDL_CreateWindow(walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera", 960, 720,
Sdl.WindowVulkan | Sdl.WindowResizable | Sdl.WindowHighPixelDensity); Sdl.WindowVulkan | Sdl.WindowResizable | Sdl.WindowHighPixelDensity);
if (window == 0) { Sdl.SDL_Quit(); throw new InvalidOperationException(Sdl.Error); } if (window == 0) { Sdl.SDL_Quit(); throw new InvalidOperationException(Sdl.Error); }
} }
@@ -136,29 +154,67 @@ internal static class Program
var clock = Stopwatch.StartNew(); var clock = Stopwatch.StartNew();
var animationStarted = 0.0; var animationStarted = 0.0;
var animationSwitched = false; var animationSwitched = false;
var inspecting = !walking;
var active = true;
var mouseJump = false;
var stepClock = new FixedStepClock();
double poseTime = 0;
var injectedInput = default(PlayerInput);
var sawWalkKeys = 0;
double last = clock.Elapsed.TotalSeconds; double last = clock.Elapsed.TotalSeconds;
float angle = 0.6f, elevation = 0.32f; float angle = 0.6f, elevation = 0.32f;
var count = 0; var count = 0;
while (running) while (running)
{ {
if (walkSmoke && !headless)
{
var requested = LabSimulation.SmokeInput(simulation!.Steps);
foreach (var (scancode, down, previous) in new[] {
(82u, requested.Forward, injectedInput.Forward),
(79u, requested.Right, injectedInput.Right), (225u, requested.Jump, injectedInput.Jump) })
{
if (down == previous) continue;
var injected = new Sdl.Event { Type = down ? Sdl.KeyDown : Sdl.KeyUp, Scancode = scancode, Down = down ? (byte)1 : (byte)0 };
if (!Sdl.SDL_PushEvent(ref injected)) throw new InvalidOperationException(Sdl.Error);
}
injectedInput = requested;
}
while (!headless && Sdl.SDL_PollEvent(out var e)) while (!headless && Sdl.SDL_PollEvent(out var e))
{ {
if (e.Type is Sdl.Quit or 0x210) running = false; 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.WindowResized or Sdl.WindowPixelSizeChanged) renderer.Resize();
if (e.Type == Sdl.WindowFocusLost) keys.Clear(); if (e.Type is Sdl.WindowFocusLost or Sdl.WindowMinimized)
{ keys.Clear(); mouseJump = false; active = false; stepClock.Reset(); }
if (e.Type is Sdl.WindowFocusGained or Sdl.WindowRestored)
{ active = true; stepClock.Reset(); last = clock.Elapsed.TotalSeconds; }
if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 3) mouseJump = true;
if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 3) mouseJump = false;
if (e.Type == Sdl.KeyDown) if (e.Type == Sdl.KeyDown)
{ {
keys.Add(e.Scancode); keys.Add(e.Scancode);
if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == 225 ? 4 : 0;
if (smoke && e.Scancode == 79) sawKey = true; if (smoke && e.Scancode == 79) sawKey = true;
if (e.Scancode == 41) running = false; if (e.Scancode == 41) running = false;
if (e.Repeat == 0 && animations?.Select(e.Scancode) == true) if (inspecting && e.Repeat == 0 && animations?.Select(e.Scancode) == true)
{ {
animationStarted = clock.Elapsed.TotalSeconds; animationStarted = clock.Elapsed.TotalSeconds;
animationSwitched = true; animationSwitched = true;
if (!Sdl.SDL_SetWindowTitle(window, animations.WindowTitle)) throw new InvalidOperationException(Sdl.Error); if (!Sdl.SDL_SetWindowTitle(window, animations.WindowTitle)) throw new InvalidOperationException(Sdl.Error);
} }
if (e.Scancode == 6 && e.Repeat == 0 && originalStart != null) if (e.Scancode == 6 && e.Repeat == 0 && originalStart != null)
originalCamera = !originalCamera; {
if (simulation != null)
{
inspecting = !inspecting;
keys.Clear(); mouseJump = false; stepClock.Reset();
originalCamera = false;
target = simulation.ActorRoot;
radius = 600;
if (!Sdl.SDL_SetWindowTitle(window, inspecting ? animations!.WindowTitle : WalkTitle)) throw new InvalidOperationException(Sdl.Error);
}
else originalCamera = !originalCamera;
}
if (!inspecting && e.Scancode == 21 && e.Repeat == 0) { simulation!.Reset(); poseTime = 0; }
if (e.Scancode == 68 && e.Repeat == 0) if (e.Scancode == 68 && e.Repeat == 0)
{ {
fullscreen = !fullscreen; fullscreen = !fullscreen;
@@ -168,33 +224,56 @@ internal static class Program
if (e.Type == Sdl.KeyUp) keys.Remove(e.Scancode); if (e.Type == Sdl.KeyUp) keys.Remove(e.Scancode);
} }
var now = clock.Elapsed.TotalSeconds; var now = clock.Elapsed.TotalSeconds;
var dt = (float)Math.Min(now - last, 0.1); var elapsed = now - last;
var dt = (float)Math.Min(elapsed, 0.1);
last = now; last = now;
if (simulation != null && !inspecting && (active || headless || walkSmoke))
{
var steps = headless || walkSmoke ? 1 : stepClock.Advance(elapsed);
for (var step = 0; step < steps; step++)
{
var input = walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput(
keys.Contains(82), keys.Contains(81), keys.Contains(80), keys.Contains(79),
mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98));
simulation.Step(input);
if (animations!.SelectPose(simulation.Pose)) poseTime = 0;
poseTime += FixedStepClock.Step;
}
characterModel = simulation.Model;
}
if (inspecting)
{
if (keys.Contains(80) || keys.Contains(4)) angle -= dt; if (keys.Contains(80) || keys.Contains(4)) angle -= dt;
if (keys.Contains(79) || keys.Contains(7)) angle += dt; if (keys.Contains(79) || keys.Contains(7)) angle += dt;
if (keys.Contains(82) || keys.Contains(26)) elevation = Math.Min(elevation + dt, 1.4f); if (keys.Contains(82) || keys.Contains(26)) elevation = Math.Min(elevation + dt, 1.4f);
if (keys.Contains(81) || keys.Contains(22)) elevation = Math.Max(elevation - dt, -1.4f); if (keys.Contains(81) || keys.Contains(22)) elevation = Math.Max(elevation - dt, -1.4f);
if (keys.Contains(46) || keys.Contains(87)) radius *= MathF.Exp(-dt); if (keys.Contains(46) || keys.Contains(87)) radius *= MathF.Exp(-dt);
if (keys.Contains(45) || keys.Contains(86)) radius *= MathF.Exp(dt); if (keys.Contains(45) || keys.Contains(86)) radius *= MathF.Exp(dt);
}
radius = Math.Max(radius, 0.01f); radius = Math.Max(radius, 0.01f);
var eye = target + radius * new Vector3(MathF.Cos(elevation) * MathF.Sin(angle), var eye = target + radius * new Vector3(MathF.Cos(elevation) * MathF.Sin(angle),
MathF.Sin(elevation), MathF.Cos(elevation) * MathF.Cos(angle)); MathF.Sin(elevation), MathF.Cos(elevation) * MathF.Cos(angle));
var view = originalCamera var view = originalCamera
? Matrix4x4.CreateLookAtLeftHanded(originalStart!.CameraPosition, originalStart.Position + new Vector3(0, 80, 0), Vector3.UnitY) ? Matrix4x4.CreateLookAtLeftHanded(originalStart!.CameraPosition, originalStart.Position + new Vector3(0, 80, 0), Vector3.UnitY)
: Matrix4x4.CreateLookAt(eye, target, Vector3.UnitY); : Matrix4x4.CreateLookAt(eye, target, Vector3.UnitY);
if (simulation != null && !inspecting)
view = Matrix4x4.CreateLookAtLeftHanded(simulation.CameraEye, simulation.CameraTarget, Vector3.UnitY);
var far = level?.Code == "LV1B" ? 10000 : 3200; var far = level?.Code == "LV1B" ? 10000 : 3200;
var projection = originalCamera var projection = originalCamera || simulation != null && !inspecting
? Matrix4x4.CreatePerspectiveFieldOfViewLeftHanded(0xAAA / 16384f * MathF.Tau, (float)renderer.Width / renderer.Height, 20, far) ? Matrix4x4.CreatePerspectiveFieldOfViewLeftHanded(0xAAA / 16384f * MathF.Tau, (float)renderer.Width / renderer.Height, 20, far)
: Matrix4x4.CreatePerspectiveFieldOfView(MathF.PI / 3, (float)renderer.Width / renderer.Height, Math.Max(radius / 10000, 0.01f), radius * 20); : Matrix4x4.CreatePerspectiveFieldOfView(MathF.PI / 3, (float)renderer.Width / renderer.Height, Math.Max(radius / 10000, 0.01f), radius * 20);
projection.M22 *= -1; projection.M22 *= -1;
if (animations != null) if (animations != null)
{ {
animations.Current.Sample(fixedTime ?? (headless ? count / 60.0 : now - animationStarted), mesh.Vertices.AsSpan(characterOffset), characterModel); animations.Current.Sample(simulation != null && !inspecting ? poseTime
: fixedTime ?? (headless ? count / 60.0 : now - animationStarted), mesh.Vertices.AsSpan(characterOffset), characterModel);
renderer.UpdateVertices(mesh.Vertices); renderer.UpdateVertices(mesh.Vertices);
} }
renderer.Render(view * projection); renderer.Render(view * projection);
count++; count++;
audio?.Pump(); audio?.Pump();
if (walkSmoke && !headless && count == 1 && !Sdl.SDL_SetWindowSize(window, 800, 600))
throw new InvalidOperationException(Sdl.Error);
if (smoke && count == 1) if (smoke && count == 1)
{ {
var key = new Sdl.Event { Type = Sdl.KeyDown, Scancode = 79, Down = 1 }; var key = new Sdl.Event { Type = Sdl.KeyDown, Scancode = 79, Down = 1 };
@@ -206,7 +285,7 @@ internal static class Program
if (!Sdl.SDL_PushEvent(ref cycle)) throw new InvalidOperationException(Sdl.Error); if (!Sdl.SDL_PushEvent(ref cycle)) throw new InvalidOperationException(Sdl.Error);
} }
} }
if (smoke && renderer.Width == 800 && renderer.Height == 600) didResize = true; if ((smoke || walkSmoke) && renderer.Width == 800 && renderer.Height == 600) didResize = true;
if (frames > 0 && count >= frames) break; if (frames > 0 && count >= frames) break;
} }
if (Option(args, "--screenshot") is { } screenshot) if (Option(args, "--screenshot") is { } screenshot)
@@ -219,6 +298,13 @@ internal static class Program
for (var i = 0; i < pixels.Length; i += 4) for (var i = 0; i < pixels.Length; i += 4)
if (Math.Abs(pixels[i] - 31) + Math.Abs(pixels[i + 1] - 51) + Math.Abs(pixels[i + 2] - 76) > 6) changed++; if (Math.Abs(pixels[i] - 31) + Math.Abs(pixels[i + 1] - 51) + Math.Abs(pixels[i + 2] - 76) > 6) changed++;
Console.WriteLine($"Rendered {count} frame(s), {changed} non-background pixels, {renderer.ValidationErrors} Vulkan validation error(s)."); Console.WriteLine($"Rendered {count} frame(s), {changed} non-background pixels, {renderer.ValidationErrors} Vulkan validation error(s).");
if (simulation != null) Console.WriteLine(simulation.Report);
if (walkSmoke && !simulation!.SmokePassed) return 2;
if (walkSmoke && !headless)
{
Console.WriteLine($"Walk SDL keyboard events received: {sawWalkKeys == 7}; resize800x600: {didResize}.");
if (sawWalkKeys != 7 || !didResize) return 2;
}
if (smoke) if (smoke)
{ {
Console.WriteLine($"SDL3 injected keyboard event received: {sawKey}; swapchain resized to 800x600: {didResize}."); Console.WriteLine($"SDL3 injected keyboard event received: {sawKey}; swapchain resized to 800x600: {didResize}.");
@@ -237,6 +323,8 @@ internal static class Program
} }
} }
private const string WalkTitle = "Jimmy Neutron — lab checkpoint | Arrows move | Shift / Insert / right mouse jump | R reset | C inspect";
private static int VerifyAssets(string root) private static int VerifyAssets(string root)
{ {
var pngs = Directory.GetFiles(root, "*", SearchOption.AllDirectories) var pngs = Directory.GetFiles(root, "*", SearchOption.AllDirectories)
@@ -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/Game/SceneCollision.cs" Link="SceneCollision.cs" />
<Compile Include="../../src/GamePort/Assets/Mesh.cs" Link="Mesh.cs" />
<Compile Include="../../src/GamePort/Assets/PngImage.cs" Link="PngImage.cs" />
</ItemGroup>
</Project>
+288
View File
@@ -0,0 +1,288 @@
using System.Diagnostics;
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
var tests = new (string Name, Action Check)[]
{
("flat support and ground-height interval", FlatFloor),
("continuous high-speed floor and wall collision", HighSpeed),
("wall sliding, departure and corner", Walls),
("ceiling and underside", Ceiling),
("sloped floor and landing", Slope),
("walking over an edge releases support", Edge),
("triangle edge and vertex sweep", TriangleEdges),
("camera sphere sweep", Camera),
("original-scale translated room and repeated seam crossings", TranslatedRoom),
("invisible source triangles and invalid input", SourcePolicy),
("original lab spawn, traversal, jump and deterministic replay", OriginalLab),
};
foreach (var (name, check) in tests)
{
check();
Console.WriteLine($"PASS {name}");
}
Console.WriteLine($"Collision checks: {tests.Length} passed");
static void FlatFloor()
{
var mesh = new Builder().Floor(0, -100, 100, -100, 100).Floor(10, -100, 100, -100, 100).Build();
var scene = new SceneCollision(mesh);
Near(scene.GroundHeight(new Vector3(0, 5, 0), 20)!.Value, 0, .0001f, "floor below queried point");
Near(scene.GroundHeight(new Vector3(0, 5, 0), 20, 6)!.Value, 10, .0001f, "highest permitted surface");
Check(scene.GroundHeight(new Vector3(0, 5, 0), 4) is null, "floor outside drop interval");
var standing = scene.Move(Vector3.Zero, Vector3.Zero, 1, 4);
Check(standing.Grounded, "stationary support");
Near(standing.Position.Y, SceneCollision.Skin, .01f, "surface skin");
var moved = scene.Move(standing.Position, new Vector3(30, 0, 20), 1, 4);
Check(moved.Grounded && !moved.HitWall && !moved.HitCeiling, "tangent floor motion");
Near(moved.Position.X, 30, .01f, "free horizontal x");
Near(moved.Position.Z, 20, .01f, "free horizontal z");
}
static void HighSpeed()
{
var scene = new SceneCollision(new Builder().Floor(0, -20000, 20000, -20000, 20000)
.WallX(5, 0, 100, -100, 100).Build());
var landing = scene.Move(new Vector3(0, 1000, 0), new Vector3(0, -10000, 0), 1, 4);
Check(landing.Grounded, "fast fall lands");
Near(landing.Position.Y, SceneCollision.Skin, .01f, "no floor tunneling");
var wall = scene.Move(new Vector3(0, 1, 0), new Vector3(10000, 0, 0), 1, 4);
Check(wall.HitWall, "fast horizontal hit");
Near(wall.Position.X, 4 - SceneCollision.Skin, .02f, "no wall tunneling");
var diagonal = scene.Move(new Vector3(-100, 100, 0), new Vector3(10000, -10000, 20), 1, 4);
Check(diagonal.Grounded && diagonal.HitWall, $"fast diagonal hits floor and wall: {diagonal}");
Check(diagonal.Position.X <= 4 && diagonal.Position.Y >= -.01f, "diagonal safe position");
}
static void Walls()
{
var scene = new SceneCollision(new Builder().Floor(0, -100, 100, -100, 100)
.WallX(5, 0, 20, -100, 100).WallZ(5, 0, 20, -100, 100).Build());
var slide = scene.Move(new Vector3(0, .1f, -10), new Vector3(10, 0, 10), 1, 4);
Near(slide.Position.X, 4 - SceneCollision.Skin, .02f, "wall x limit");
Near(slide.Position.Z, 0, .02f, "wall preserves tangent travel");
var leave = scene.Move(slide.Position, new Vector3(-3, 0, 0), 1, 4);
Near(leave.Position.X, slide.Position.X - 3, .02f, "depart contact freely");
var corner = scene.Move(new Vector3(0, .1f, 0), new Vector3(100, 0, 100), 1, 4);
Near(corner.Position.X, 4 - SceneCollision.Skin, .02f, "corner x");
Near(corner.Position.Z, 4 - SceneCollision.Skin, .02f, "corner z");
var resting = corner.Position;
for (var i = 0; i < 100; i++) resting = scene.Move(resting, new Vector3(1, -.2f, 1), 1, 4).Position;
Check(Vector3.Distance(resting, new Vector3(4 - SceneCollision.Skin, SceneCollision.Skin, 4 - SceneCollision.Skin)) < .03f,
"corner remains stable under sustained input");
}
static void Ceiling()
{
var scene = new SceneCollision(new Builder().Floor(0, -100, 100, -100, 100)
.Floor(6, -100, 100, -100, 100).Build());
var rise = scene.Move(new Vector3(0, .1f, 0), new Vector3(0, 100, 0), 1, 4);
Check(rise.HitCeiling && !rise.Grounded, "ceiling hit classification");
Near(rise.Position.Y, 2 - SceneCollision.Skin, .02f, "head stops below underside");
var descend = scene.Move(rise.Position, new Vector3(0, -20, 0), 1, 4);
Check(descend.Grounded, "leaves underside and lands");
Near(descend.Position.Y, SceneCollision.Skin, .02f, "underside does not trap actor");
}
static void Slope()
{
var builder = new Builder().Quad(new(-30, -15, -30), new(-30, -15, 30), new(30, 15, 30), new(30, 15, -30));
var scene = new SceneCollision(builder.Build());
Near(scene.GroundHeight(new Vector3(4, 10, 0), 100)!.Value, 2, .0001f, "slope height");
var landed = scene.Move(new Vector3(0, 20, 0), new Vector3(0, -30, 0), 1, 4);
Check(landed.Grounded, "sloped landing");
// Sliding projects the remaining downward displacement onto the slope.
Check(landed.Position.Y >= landed.Position.X * .5f - .01f, "slope cannot penetrate");
var position = scene.Move(Vector3.Zero, Vector3.Zero, 1, 4).Position;
for (var i = 0; i < 20; i++)
{
var move = scene.Move(position, new Vector3(.25f, -.01f, 0), 1, 4);
Check(move.Grounded, "slope support while climbing");
Check(move.Position.Y >= move.Position.X * .5f, "climb above plane");
position = move.Position;
}
Check(position.X > 3 && position.Y > 1.5f, "walk uphill");
}
static void Edge()
{
var scene = new SceneCollision(new Builder().Floor(0, -10, 0, -10, 10).Build());
var standing = scene.Move(new Vector3(-2, 0, 0), Vector3.Zero, 1, 4);
var moved = scene.Move(standing.Position, new Vector3(5, 0, 0), 1, 4);
Check(!moved.Grounded, "support is evaluated at final position");
var falling = scene.Move(moved.Position, new Vector3(0, -5, 0), 1, 4);
Check(!falling.Grounded && falling.Position.Y < -4, "fall beyond ledge");
}
static void TriangleEdges()
{
var scene = new SceneCollision(new Builder().Triangle(new(5, 0, 0), new(5, 8, 0), new(5, 0, 8)).Build());
var edge = scene.Move(new Vector3(0, 0, -.5f), new Vector3(1000, 0, 0), 1, 4);
Check(edge.HitWall && edge.Position.Z < -.5f, $"capsule catches and slides around triangle edge with center outside face: {edge}");
var miss = scene.Move(new Vector3(0, 0, -2), new Vector3(10, 0, 0), 1, 4);
Near(miss.Position.X, 10, .0001f, "clears isolated edge");
var camera = scene.ClipCamera(new Vector3(0, -.5f, -.5f), new Vector3(10, -.5f, -.5f), 1);
Check(camera.X < 5, "sphere catches triangle vertex");
}
static void Camera()
{
var scene = new SceneCollision(new Builder().WallX(5, -10, 10, -10, 10).Build());
var clipped = scene.ClipCamera(Vector3.Zero, new Vector3(1000, 0, 0), .5f);
Near(clipped.X, 4.5f - SceneCollision.Skin, .02f, "camera clips wall");
var free = scene.ClipCamera(Vector3.Zero, new Vector3(-100, 0, 0), .5f);
Near(free.X, -100, .001f, "camera clear path");
}
static void TranslatedRoom()
{
var scene = new SceneCollision(new Builder().Floor(.5486332f, 4000, 6000, -2000, 3000)
.WallX(5430, .5486332f, 1000, -2000, 3000)
.WallZ(2433, .5486332f, 1000, 4000, 6000).Build());
var start = new Vector3(5071.933f, .5486332f, 824.10394f);
var fast = scene.Move(start, new Vector3(100000, -100000, 100000), 34.7f, 209.4361f);
Check(fast.Grounded && fast.HitWall, $"translated room fast collision: {fast}");
Check(fast.Position.X <= 5430 - 34.7f + .02f && fast.Position.Z <= 2433 - 34.7f + .02f, "translated room walls");
Near(fast.Position.Y, .5486332f + SceneCollision.Skin, .02f, "translated room floor");
var position = scene.Move(start, Vector3.Zero, 34.7f, 209.4361f).Position;
for (var i = 0; i < 2000; i++)
{
var movement = new Vector3(i % 400 < 200 ? 2 : -2, -.3f, i % 200 < 100 ? 2 : -2);
var moved = scene.Move(position, movement, 34.7f, 209.4361f);
Check(moved.Grounded, "translated floor repeated support");
Near(moved.Position.Y, .5486332f + SceneCollision.Skin, .02f, "translated floor repeated height");
position = moved.Position;
}
}
static void SourcePolicy()
{
var mesh = new Builder().WallX(5, 0, 20, -20, 20).Build() with { HasExplicitDraws = true, Draws = [] };
var scene = new SceneCollision(mesh);
Check(scene.TriangleCount == 2, "unrendered source proxy retained");
Check(scene.Move(Vector3.Zero, new Vector3(100, 0, 0), 1, 4).HitWall, "proxy blocks under provisional policy");
var degenerate = new SceneCollision(new Builder().Triangle(Vector3.Zero, Vector3.One, Vector3.One).Build());
Check(degenerate.TriangleCount == 0, "degenerate triangles skipped");
Throws<ArgumentOutOfRangeException>(() => scene.Move(Vector3.Zero, Vector3.Zero, 0, 4));
Throws<ArgumentOutOfRangeException>(() => scene.Move(Vector3.Zero, Vector3.Zero, 3, 4));
Throws<ArgumentOutOfRangeException>(() => scene.Move(new Vector3(float.NaN, 0, 0), Vector3.Zero, 1, 4));
Throws<ArgumentException>(() => new SceneCollision(new Mesh([], [0, 1, 2])));
Throws<ArgumentException>(() => new SceneCollision(new Builder().Triangle(Vector3.Zero,
new Vector3(float.PositiveInfinity, 0, 0), Vector3.One).Build()));
Throws<ArgumentException>(() => new SceneCollision(new Builder().Triangle(Vector3.Zero,
new Vector3(1e30f, 0, 0), new Vector3(0, 1e30f, 0)).Build()));
}
static void OriginalLab()
{
var root = FindRoot();
var file = Path.Combine(root, "artifacts/extracted/level1b/scene.json");
Check(File.Exists(file), "prepared original lab required (run extractors/prepare.py)");
var scene = new SceneCollision(Mesh.LoadSceneJson(file));
Check(scene.TriangleCount == 2869, "all original lab triangles included");
var originalRoot = new Vector3(5071.933105f, 26.661896f, 824.103943f);
var floor = scene.GroundHeight(originalRoot, 100)!.Value;
Near(floor, .5486332f, .001f, "actual lab floor below GAM root");
var stopwatch = Stopwatch.StartNew();
foreach (var radius in new[] { 24f, 34.7f })
{
var feet = new Vector3(originalRoot.X, floor, originalRoot.Z);
var standing = scene.Move(feet, Vector3.Zero, radius, 209.4361f);
Check(standing.Grounded, $"actual lab standing radius {radius}");
Check(Vector3.Distance(standing.Position, feet) < .2f, $"lab spawn does not need horizontal relocation radius {radius}");
var first = Traverse(scene, standing.Position, radius);
var second = Traverse(scene, standing.Position, radius);
Check(first == second, "same input stream replays identically");
Check(Vector3.Distance(first, standing.Position) > 100, $"actual lab traversal radius {radius}");
// This direction reaches original geometry near the east side of the
// room, rather than an invented room-sized bounding box.
var east = standing.Position;
var hitOriginalWall = false;
for (var i = 0; i < 600; i++)
{
var moved = scene.Move(east, new Vector3(3, -.3f, 0), radius, 209.4361f);
hitOriginalWall |= moved.HitWall;
Check(Finite(moved.Position), "original wall traversal finite");
Check(moved.Position.Y > floor - .05f, "original wall traversal above lab floor");
east = moved.Position;
}
Check(hitOriginalWall && east.X < standing.Position.X + 1750, $"original east wall blocks radius {radius}");
var position = standing.Position;
var velocity = 550f;
var reachedAir = false;
var landed = false;
for (var i = 0; i < 180; i++)
{
velocity -= 1064f / 60f;
var moved = scene.Move(position, new Vector3(0, velocity / 60f, 0), radius, 209.4361f);
Check(Finite(moved.Position), "lab jump finite");
if (moved.HitCeiling && velocity > 0) velocity = 0;
if (!moved.Grounded) reachedAir = true;
if (reachedAir && moved.Grounded && velocity < 0) { landed = true; position = moved.Position; break; }
position = moved.Position;
}
Check(reachedAir && landed, $"lab jump rises and lands radius {radius}");
Near(position.Y, floor + SceneCollision.Skin, .03f, "lab landing above floor");
Console.WriteLine($" lab radius={radius}: start={standing.Position}, traverse={first}, eastWall={east}, jumpLand={position}");
}
Console.WriteLine($" lab replay and jump checks {stopwatch.ElapsedMilliseconds} ms");
}
static Vector3 Traverse(SceneCollision scene, Vector3 position, float radius)
{
var angle = 155f * MathF.PI / 180;
var forward = new Vector3(-MathF.Sin(angle), 0, MathF.Cos(angle));
for (var i = 0; i < 240; i++)
{
var moved = scene.Move(position, forward * (180f / 60) - Vector3.UnitY * .3f, radius, 209.4361f);
Check(Finite(moved.Position), "lab traversal finite");
var below = scene.GroundHeight(moved.Position + Vector3.UnitY * .01f, 1000);
if (below.HasValue) Check(moved.Position.Y >= below.Value - .02f, "lab traverse stays above nearby floor");
position = moved.Position;
}
return position;
}
static string FindRoot()
{
var directory = new DirectoryInfo(Environment.CurrentDirectory);
while (directory is not null)
{
if (File.Exists(Path.Combine(directory.FullName, "GamePort.slnx"))) return directory.FullName;
directory = directory.Parent;
}
throw new InvalidOperationException("Run from within GamePort");
}
static bool Finite(Vector3 p) => float.IsFinite(p.X) && float.IsFinite(p.Y) && float.IsFinite(p.Z);
static void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
static void Near(float actual, float expected, float tolerance, string message) =>
Check(MathF.Abs(actual - expected) <= tolerance, $"{message}: actual={actual}, expected={expected}, tolerance={tolerance}");
static void Throws<T>(Action check) where T : Exception
{
try { check(); } catch (T) { return; }
throw new Exception($"Expected {typeof(T).Name}");
}
sealed class Builder
{
private readonly List<MeshVertex> vertices = [];
private readonly List<uint> indices = [];
public Builder Triangle(Vector3 a, Vector3 b, Vector3 c)
{
var offset = (uint)vertices.Count;
vertices.Add(new(a, Vector2.Zero, Vector3.One));
vertices.Add(new(b, Vector2.Zero, Vector3.One));
vertices.Add(new(c, Vector2.Zero, Vector3.One));
indices.AddRange([offset, offset + 1, offset + 2]);
return this;
}
public Builder Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d) => Triangle(a, b, c).Triangle(a, c, d);
public Builder Floor(float y, float left, float right, float back, float front) =>
Quad(new(left, y, back), new(left, y, front), new(right, y, front), new(right, y, back));
public Builder WallX(float x, float bottom, float top, float back, float front) =>
Quad(new(x, bottom, back), new(x, top, back), new(x, top, front), new(x, bottom, front));
public Builder WallZ(float z, float bottom, float top, float left, float right) =>
Quad(new(left, bottom, z), new(left, top, z), new(right, top, z), new(right, bottom, z));
public Mesh Build() => new(vertices.ToArray(), indices.ToArray());
}
@@ -14,7 +14,7 @@
<Compile Include="../../src/GamePort/Assets/AseMesh.cs" Link="AseMesh.cs" /> <Compile Include="../../src/GamePort/Assets/AseMesh.cs" Link="AseMesh.cs" />
<Compile Include="../../src/GamePort/Assets/AssetPath.cs" Link="AssetPath.cs" /> <Compile Include="../../src/GamePort/Assets/AssetPath.cs" Link="AssetPath.cs" />
<Compile Include="../../src/GamePort/Assets/MorphAnimation.cs" Link="MorphAnimation.cs" /> <Compile Include="../../src/GamePort/Assets/MorphAnimation.cs" Link="MorphAnimation.cs" />
<Compile Include="../../src/GamePort/Game/RecoveredMotion.cs" Link="RecoveredMotion.cs" /> <Compile Include="../../src/GamePort/Game/*.cs" />
<Compile Include="../../src/GamePort/Application/PreviewCharacterPlacement.cs" Link="PreviewCharacterPlacement.cs" /> <Compile Include="../../src/GamePort/Application/PreviewCharacterPlacement.cs" Link="PreviewCharacterPlacement.cs" />
<Compile Include="../../src/GamePort/Application/PreviewAnimationLibrary.cs" Link="PreviewAnimationLibrary.cs" /> <Compile Include="../../src/GamePort/Application/PreviewAnimationLibrary.cs" Link="PreviewAnimationLibrary.cs" />
</ItemGroup> </ItemGroup>
@@ -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>
+313
View File
@@ -0,0 +1,313 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
var project = FindProject();
var originals = args.Length == 1 ? Path.GetFullPath(args[0]) : Path.GetFullPath(Path.Combine(project, "../Original"));
var tests = new (string Name, Action Check)[]
{
("60 simulation calls across 60/120/144 Hz presentation", ClockRates),
("clock remainder, stall bound, reset and invalid intervals", ClockBoundaries),
("turn-only speed, forward acceleration/cap and release", SpeedLimits),
("backpedal cap and release", Backpedal),
("yaw sign, forward half-turn and left precedence", Turning),
("fixed-step input replay independent of presentation rate", ReplayRates),
("jump rises, falls and returns to support", JumpLanding),
("held zero-burn jump repeats and release stops repetition", HeldJump),
("airborne jump re-press rearms landing without a double jump", JumpRepress),
("air mode ignores arrow steering", AirControl),
("reset restores spawn, camera and counters", Reset),
("ten-minute simulation remains finite and supported", LongRun),
("original lab placement, floor, walking and jump checkpoint", () => OriginalLab(project, originals)),
};
foreach (var (name, check) in tests)
{
check();
Console.WriteLine($"PASS {name}");
}
Console.WriteLine($"Movement checks: {tests.Length} passed. Static reconstruction/port-policy regressions; no original-runtime comparison.");
static void ClockRates()
{
foreach (var rate in new[] { 60, 120, 144 })
{
var clock = new FixedStepClock();
for (var second = 0; second < 20; second++)
{
var steps = 0;
for (var frame = 0; frame < rate; frame++) steps += clock.Advance(1.0 / rate);
Check(steps == 60, $"{rate} Hz second {second}: {steps} simulation calls");
}
}
}
static void ClockBoundaries()
{
var clock = new FixedStepClock();
Check(clock.Advance(0) == 0, "zero elapsed interval");
Check(clock.Advance(1.0 / 120) == 0 && clock.Advance(1.0 / 120) == 1, "fractional frame remainder retained");
Check(clock.Advance(4) == 15, "stalled presentation advances at most a quarter second");
clock.Advance(1.0 / 120);
clock.Reset();
Check(clock.Advance(1.0 / 120) == 0 && clock.Advance(1.0 / 120) == 1, "reset discards old remainder");
foreach (var elapsed in new[] { -0.01, double.NaN, double.PositiveInfinity, double.NegativeInfinity })
Throws<ArgumentOutOfRangeException>(() => clock.Advance(elapsed));
}
static void SpeedLimits()
{
var turn = FlatSimulation();
for (var i = 0; i < 40; i++) turn.Step(new(false, false, true, false, false));
Near(turn.Speed, 0, 0, "turn-only +30 then decay35 clamps at zero");
Check(turn.Grounded && turn.Pose == PlayerPose.Idle, "turn-only remains supported and idle");
var walk = FlatSimulation();
walk.Step(new(true, false, false, false, false));
Near(walk.Speed, 30, 0, "first forward invocation");
for (var i = 1; i < 40; i++) walk.Step(new(true, false, false, false, false));
Near(walk.Speed, 600, 0, "forward speed cap");
Check(walk.Position.Z > 250 && walk.Pose == PlayerPose.Run, "forward speed produces visible travel");
for (var i = 0; i < 20; i++) walk.Step(default);
Near(walk.Speed, 0, 0, "release decays to zero");
var stopped = walk.Position;
for (var i = 0; i < 30; i++) walk.Step(default);
NearVector(walk.Position, stopped, .001f, "released standing position remains stable");
}
static void Backpedal()
{
var simulation = FlatSimulation();
for (var i = 0; i < 180; i++) simulation.Step(new(false, true, false, false, false));
Near(simulation.Speed, -300, 0, "reverse cap remains -300 without an invented turn-around timer");
Check(simulation.Grounded && simulation.Pose == PlayerPose.Backpedal && simulation.Position.Z < -500,
"backpedal moves opposite forward and stays supported");
for (var i = 0; i < 20; i++) simulation.Step(default);
Near(simulation.Speed, 0, 0, "reverse release clamps toward zero");
}
static void Turning()
{
var left = FlatSimulation();
var right = FlatSimulation();
var forwardLeft = FlatSimulation();
left.Step(new(false, false, true, false, false));
right.Step(new(false, false, false, true, false));
forwardLeft.Step(new(true, false, true, false, false));
Check(left.Yaw > 0 && right.Yaw < 0, "left/right yaw signs");
Near(left.Yaw, -right.Yaw, .00001f, "opposed keyboard yaw symmetry");
Near(forwardLeft.Yaw, left.Yaw / 2, .00001f, "Up halves target turn offset");
Near(forwardLeft.Speed, 60, 0, "Up plus turn performs both speed increments");
Check(left.Position.X < 0 && right.Position.X > 0, "keyboard side-velocity signs");
var both = FlatSimulation();
var leftOnly = FlatSimulation();
for (var i = 0; i < 10; i++)
{
both.Step(new(true, false, true, true, false));
leftOnly.Step(new(true, false, true, false, false));
}
SameState(both, leftOnly, "Left has precedence when Left and Right are held together");
}
static void ReplayRates()
{
LabSimulation? reference = null;
foreach (var rate in new[] { 60, 120, 144 })
{
var simulation = FlatSimulation();
var clock = new FixedStepClock();
for (var frame = 0; frame < rate * 4; frame++)
{
var steps = clock.Advance(1.0 / rate);
for (var step = 0; step < steps; step++) simulation.Step(LabSimulation.SmokeInput(simulation.Steps));
}
Check(simulation.Steps == 240, $"{rate} Hz replay duration");
Check(simulation.SmokePassed, $"{rate} Hz replay walks, jumps and lands: {simulation.Report}");
if (reference is not null) SameState(simulation, reference, $"{rate} Hz replay");
reference = simulation;
}
}
static void JumpLanding()
{
var simulation = FlatSimulation();
var floor = simulation.Position.Y;
simulation.Step(new(false, false, false, false, true));
Check(!simulation.Grounded && simulation.Velocity.Y > 500 && simulation.Jumps == 1 && simulation.Pose == PlayerPose.Jump,
"jump takes off with one queued impulse");
var sawFall = false;
var largestHeight = simulation.Position.Y;
for (var i = 0; i < 120; i++)
{
simulation.Step(default);
largestHeight = Math.Max(largestHeight, simulation.Position.Y);
sawFall |= simulation.Pose == PlayerPose.Fall;
}
Check(sawFall && largestHeight - floor > 100, "jump rises and enters descending phase");
Check(simulation.Grounded && simulation.Jumps == 1 && simulation.Landings == 1, "released jump lands once");
Near(simulation.Position.Y, floor, .01f, "landing returns feet to supporting floor");
Near(simulation.Velocity.Y, 0, 0, "landing clears downward velocity");
}
static void HeldJump()
{
var simulation = FlatSimulation();
for (var i = 0; i < 300; i++) simulation.Step(new(false, false, false, false, true));
Check(simulation.Jumps >= 3 && simulation.Landings >= 2,
$"zero-burn long hold rearms and repeats after landing: {simulation.Report}");
var jumpCount = simulation.Jumps;
for (var i = 0; i < 150; i++) simulation.Step(default);
Check(simulation.Jumps == jumpCount && simulation.Grounded, "release stops held repetition and lands");
simulation.Step(new(false, false, false, false, true));
Check(simulation.Jumps == jumpCount + 1 && !simulation.Grounded, "new grounded press starts another jump");
}
static void AirControl()
{
var idleInput = FlatSimulation();
var arrowInput = FlatSimulation();
for (var i = 0; i < 20; i++)
{
idleInput.Step(new(true, false, false, false, false));
arrowInput.Step(new(true, false, false, false, false));
}
idleInput.Step(new(true, false, false, false, true));
arrowInput.Step(new(true, false, false, false, true));
for (var i = 0; i < 24; i++)
{
Check(!idleInput.Grounded && !arrowInput.Grounded, "comparison remains airborne");
idleInput.Step(default);
arrowInput.Step(new(true, true, true, true, false));
SameState(arrowInput, idleInput, "ordinary arrows ignored while airborne");
}
Near(arrowInput.Speed, 600, 0, "takeoff speed retained in air");
}
static void JumpRepress()
{
var simulation = FlatSimulation();
simulation.Step(new(false, false, false, false, true));
for (var i = 0; i < 5; i++) simulation.Step(default);
Check(!simulation.Grounded && simulation.Jumps == 1, "released first jump remains airborne");
var velocityBeforeRepress = simulation.Velocity.Y;
simulation.Step(new(false, false, false, false, true));
Check(simulation.Jumps == 1 && simulation.Velocity.Y < velocityBeforeRepress,
"re-press cannot consume a second impulse while airborne");
for (var i = 0; i < 120; i++) simulation.Step(new(false, false, false, false, true));
Check(simulation.Jumps >= 2 && simulation.Landings >= 1,
$"released-then-held jump rearms for the next landing: {simulation.Report}");
var jumps = simulation.Jumps;
for (var i = 0; i < 150; i++) simulation.Step(default);
Check(simulation.Jumps == jumps && simulation.Grounded, "release after re-press repeat settles without more jumps");
}
static void Reset()
{
var simulation = FlatSimulation(155);
var fresh = FlatSimulation(155);
for (var i = 0; i < 240; i++) simulation.Step(LabSimulation.SmokeInput(i));
Check(simulation.Travel > 100 && simulation.Jumps > 0, "reset fixture has nontrivial history");
simulation.Reset();
SameState(simulation, fresh, "reset restores a fresh spawn");
Check(simulation.Steps == 0 && simulation.Jumps == 0 && simulation.Landings == 0 && simulation.WallHits == 0
&& simulation.Travel == 0 && simulation.MaximumRise == 0, "reset clears telemetry counters");
for (var i = 0; i < 90; i++)
{
var input = new PlayerInput(i < 60, false, i >= 30, false, i >= 20 && i < 50);
simulation.Step(input);
fresh.Step(input);
}
SameState(simulation, fresh, "reset also clears hidden jump/turn/hold state");
}
static void LongRun()
{
var simulation = FlatSimulation();
for (var i = 0; i < 36000; i++)
{
var phase = i % 600;
simulation.Step(new(phase < 400, phase >= 500, phase is >= 200 and < 400, false, phase is >= 80 and < 180));
Check(Finite(simulation.Position) && Finite(simulation.Velocity) && Finite(simulation.CameraEye)
&& Finite(simulation.CameraTarget) && float.IsFinite(simulation.Yaw) && float.IsFinite(simulation.Speed),
$"simulation remains finite at step {i}");
Check(simulation.Position.Y >= SceneCollision.Skin - .01f, $"no floor penetration at step {i}");
}
Check(simulation.Steps == 36000 && simulation.Jumps > 50 && simulation.Landings > 50, "sustained repeated movement/jump coverage");
for (var i = 0; i < 120; i++) simulation.Step(default);
Check(simulation.Grounded, "long run settles to support");
}
static void OriginalLab(string project, string originals)
{
var sceneFile = Path.Combine(project, "artifacts/extracted/level1b/scene.json");
Check(File.Exists(sceneFile), "prepared original lab required (run tools/extractors/prepare.py)");
var mesh = Mesh.LoadSceneJson(sceneFile);
var standing = AseMesh.Load(AssetPath.Resolve(originals, "ase/JIMSTOP.ASE"));
var level = GamLevel.Load(AssetPath.Resolve(originals, "gam/level1b.gam"));
var start = level.FindStart() ?? throw new Exception("Missing LV1B GAM startpoint");
var collision = new SceneCollision(mesh);
Near(collision.GroundHeight(start.Position, 2500)!.Value, .5486332f, .001f, "original floor below GAM placement");
var simulation = new LabSimulation(collision, standing, start.Position, start.Rotation.Y);
Near(simulation.Position.X, 5071.933105f, .001f, "GAM X retained");
Near(simulation.Position.Z, 824.103943f, .001f, "GAM Z retained");
Near(simulation.Position.Y, .5486332f + SceneCollision.Skin, .001f, "spawn feet on original floor");
Near(simulation.Yaw, 155, .001f, "GAM yaw retained");
Near(simulation.BodyHeight, 209.4361f, .01f, "capsule height from original standing bounds");
var sole = standing.Vertices.Min(vertex => Vector3.Transform(vertex.Position, simulation.Model).Y);
Near(sole, simulation.Position.Y, .001f, "rendered standing sole agrees with simulation feet");
for (var i = 0; i < 240; i++) simulation.Step(LabSimulation.SmokeInput(i));
Check(simulation.SmokePassed, $"original lab checkpoint: {simulation.Report}");
Check(Finite(simulation.Position) && Finite(simulation.CameraEye), "original scene simulation/camera finite");
Console.WriteLine($" {simulation.Report}");
simulation.Reset();
simulation.Step(new(false, false, false, false, true));
for (var i = 0; i < 120; i++) simulation.Step(default);
Check(simulation.Jumps == 1 && simulation.Landings == 1 && simulation.Grounded, "stationary original-lab jump lands once");
Near(simulation.Position.Y, .5486332f + SceneCollision.Skin, .03f, "original lab jump returns to floor");
}
static LabSimulation FlatSimulation(float yaw = 0)
{
var positions = new[]
{
new Vector3(-100000, 0, -100000), new Vector3(-100000, 0, 100000), new Vector3(100000, 0, 100000),
new Vector3(-100000, 0, -100000), new Vector3(100000, 0, 100000), new Vector3(100000, 0, -100000),
};
var floor = new Mesh(positions.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(), [0, 1, 2, 3, 4, 5]);
var standing = new Mesh([new(new(-20, -20, -20), Vector2.Zero, Vector3.One),
new(new(20, 80, 20), Vector2.Zero, Vector3.One)], []);
return new LabSimulation(new SceneCollision(floor), standing, new Vector3(0, 25, 0), yaw);
}
static void SameState(LabSimulation actual, LabSimulation expected, string message)
{
NearVector(actual.Position, expected.Position, .0001f, $"{message}: position");
NearVector(actual.Velocity, expected.Velocity, .0001f, $"{message}: velocity");
NearVector(actual.CameraEye, expected.CameraEye, .0001f, $"{message}: camera");
Near(actual.Yaw, expected.Yaw, .0001f, $"{message}: yaw");
Near(actual.Speed, expected.Speed, 0, $"{message}: speed");
Check(actual.Grounded == expected.Grounded && actual.Pose == expected.Pose && actual.Jumps == expected.Jumps
&& actual.Landings == expected.Landings, $"{message}: movement state/counters");
}
static string FindProject()
{
var directory = new DirectoryInfo(Environment.CurrentDirectory);
while (directory is not null)
{
if (File.Exists(Path.Combine(directory.FullName, "GamePort.slnx"))) return directory.FullName;
directory = directory.Parent;
}
throw new InvalidOperationException("Run from within GamePort");
}
static bool Finite(Vector3 value) => float.IsFinite(value.X) && float.IsFinite(value.Y) && float.IsFinite(value.Z);
static void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
static void Near(float actual, float expected, float tolerance, string message) =>
Check(MathF.Abs(actual - expected) <= tolerance, $"{message}: actual={actual}, expected={expected}, tolerance={tolerance}");
static void NearVector(Vector3 actual, Vector3 expected, float tolerance, string message) =>
Check(Vector3.Distance(actual, expected) <= tolerance, $"{message}: actual={actual}, expected={expected}, tolerance={tolerance}");
static void Throws<T>(Action check) where T : Exception
{
try { check(); } catch (T) { return; }
throw new Exception($"Expected {typeof(T).Name}");
}
+1 -1
View File
@@ -23,7 +23,7 @@ def main():
parser.add_argument('--output', type=Path, default=Path('artifacts/extracted')) parser.add_argument('--output', type=Path, default=Path('artifacts/extracted'))
parser.add_argument('--scenes', nargs='+', default=['level1b', 'VR01']) parser.add_argument('--scenes', nargs='+', default=['level1b', 'VR01'])
parser.add_argument('--audio', nargs='*', default=['sounds', 'musicjimmyshouse', 'musicneighborhood']) parser.add_argument('--audio', nargs='*', default=['sounds', 'musicjimmyshouse', 'musicneighborhood'])
parser.add_argument('--animations', nargs='*', default=['jimstop', 'jimrun', 'jimjump', 'jimscratch']) parser.add_argument('--animations', nargs='*', default=['jimstop', 'jimrun', 'jimjump', 'jimscratch', 'jimbackpedal', 'jimfall'])
args = parser.parse_args() args = parser.parse_args()
if args.output.resolve().is_relative_to(args.original.resolve()): if args.output.resolve().is_relative_to(args.original.resolve()):
parser.error('Output must be outside the original installation') parser.error('Output must be outside the original installation')
+7 -3
View File
@@ -53,9 +53,11 @@ def inside(args):
application = ['/opt/wine-stable/bin/wine', r'Z:\port\GamePort.exe', application = ['/opt/wine-stable/bin/wine', r'Z:\port\GamePort.exe',
'--assets', r'Z:\port\assets', '--scene', r'Z:\port\scenes\level1b\scene.json', '--assets', r'Z:\port\assets', '--scene', r'Z:\port\scenes\level1b\scene.json',
'--level', 'gam/level1b.gam', '--original-camera', '--with-player', '--level', 'gam/level1b.gam', '--original-camera', '--with-player',
'--frames', '6' if args.port_window else '2', '--time', '0.05', '--no-validation', '--frames', '240' if args.port_walk else '6' if args.port_window else '2', '--no-validation',
'--screenshot', r'Z:\work\port-frame.ppm'] '--screenshot', r'Z:\work\port-frame.ppm']
application += ['--smoke-window'] if args.port_window else ['--headless'] application += ['--smoke-walk'] if args.port_walk else ['--inspect', '--time', '0.05']
application += ['--smoke-window'] if args.port_window and not args.port_walk else []
application += [] if args.port_window or args.port_walk else ['--headless']
if args.asset_probe: if args.asset_probe:
application = ['/opt/wine-stable/bin/wine', r'Z:\probe.exe', args.probe_model] application = ['/opt/wine-stable/bin/wine', r'Z:\probe.exe', args.probe_model]
wine = subprocess.Popen(application, cwd='/work' if args.port_smoke else '/work/game', stdout=wlog, stderr=wlog, env=wine_env) wine = subprocess.Popen(application, cwd='/work' if args.port_smoke else '/work/game', stdout=wlog, stderr=wlog, env=wine_env)
@@ -94,11 +96,12 @@ def main():
p.add_argument('--wine-renderer', choices=['gl','vulkan'], default='gl') p.add_argument('--wine-renderer', choices=['gl','vulkan'], default='gl')
p.add_argument('--port-smoke', action='store_true', help='Preliminary Windows port check under Wine64; not native Windows validation') p.add_argument('--port-smoke', action='store_true', help='Preliminary Windows port check under Wine64; not native Windows validation')
p.add_argument('--port-window', action='store_true', help='Windows port SDL window/input/resize/animation smoke under Wine64') p.add_argument('--port-window', action='store_true', help='Windows port SDL window/input/resize/animation smoke under Wine64')
p.add_argument('--port-walk', action='store_true', help='Windows port walking/jump/keyboard/resize checkpoint under Wine64')
p.add_argument('--asset-probe', action='store_true', help='Run compiled read-only OMT shape probe inside isolated copy') p.add_argument('--asset-probe', action='store_true', help='Run compiled read-only OMT shape probe inside isolated copy')
p.add_argument('--probe-model', default=r'ASE\jimstop.ase') p.add_argument('--probe-model', default=r'ASE\jimstop.ase')
p.add_argument('--output', type=Path) p.add_argument('--output', type=Path)
args = p.parse_args() args = p.parse_args()
args.port_smoke = args.port_smoke or args.port_window args.port_smoke = args.port_smoke or args.port_window or args.port_walk
if args.port_smoke and args.asset_probe: p.error('Select either port smoke or asset probe') if args.port_smoke and args.asset_probe: p.error('Select either port smoke or asset probe')
if not 3 <= args.seconds <= 120: p.error('--seconds must be 3..120') if not 3 <= args.seconds <= 120: p.error('--seconds must be 3..120')
if args.inside: return inside(args) if args.inside: return inside(args)
@@ -144,6 +147,7 @@ def main():
if args.enter: cmd += ['--enter'] if args.enter: cmd += ['--enter']
if args.port_smoke: cmd += ['--port-smoke'] if args.port_smoke: cmd += ['--port-smoke']
if args.port_window: cmd += ['--port-window'] if args.port_window: cmd += ['--port-window']
if args.port_walk: cmd += ['--port-walk']
if args.asset_probe: cmd += ['--asset-probe', '--probe-model', args.probe_model] if args.asset_probe: cmd += ['--asset-probe', '--probe-model', args.probe_model]
print('Running isolated Windows port' if args.port_smoke else 'Running copied original', 'with no network and no original-directory mount:', work, flush=True) print('Running isolated Windows port' if args.port_smoke else 'Running copied original', 'with no network and no original-directory mount:', work, flush=True)
subprocess.run(cmd, check=True, timeout=args.seconds + 40) subprocess.run(cmd, check=True, timeout=args.seconds + 40)