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
+1848 -110

No files matched your search

@@ -1,11 +1,13 @@
using GamePort.Assets;
using GamePort.Game;
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
{
private readonly Dictionary<uint, (string Name, MorphAnimation Animation)> choices = [];
private readonly Dictionary<PlayerPose, MorphAnimation> movement = [];
public MorphAnimation Current { get; private set; }
public string Name { get; private set; }
public string WindowTitle => $"Jimmy Neutron — scene preview | {Name}{(Current.HasVertexMotion ? "" : " (still pose)")} | 1 idle, 2 run, 3 jump, 4 scratch | C camera";
@@ -15,6 +17,22 @@ public sealed class PreviewAnimationLibrary
Current = new MorphAnimation(manifest);
Name = Path.GetFileName(Path.GetDirectoryName(Path.GetFullPath(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[]
{
(30u, "jimstop", "Idle"), (31u, "jimrun", "Run cycle"),
@@ -23,16 +41,17 @@ public sealed class PreviewAnimationLibrary
{
var path = Path.Combine(parent, folder, "animation.json");
if (!File.Exists(path)) continue;
var clip = Path.GetFullPath(path) == Path.GetFullPath(manifest) ? Current : 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}");
var clip = Load(path);
choices[scancode] = (label, clip);
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)
@@ -42,4 +61,13 @@ public sealed class PreviewAnimationLibrary
Name = clip.Name;
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 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 WindowFocusGained=0x20E, WindowMinimized=0x209, WindowRestored=0x20B, MouseButtonDown=0x401, MouseButtonUp=0x402;
[StructLayout(LayoutKind.Explicit,Size=128)] public struct Event
{
[FieldOffset(0)]public uint Type;
[FieldOffset(16)]public uint WindowId;
[FieldOffset(24)]public uint Scancode;
[FieldOffset(24)]public byte MouseButton;
[FieldOffset(28)]public uint Key;
[FieldOffset(36)]public byte Down;
[FieldOffset(37)]public byte Repeat;
+108 -20
View File
@@ -3,6 +3,7 @@ using System.Numerics;
using GamePort.Assets;
using GamePort.Application;
using GamePort.Audio;
using GamePort.Game;
using GamePort.Platform;
using GamePort.Rendering.Vulkan;
@@ -39,6 +40,9 @@ internal static class Program
--original-camera Stored GAM start camera and recovered projection
--animation PATH Prepared Jimmy animation.json; place at GAM startpoint
--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
--headless Render offscreen through Vulkan
--screenshot PATH Save actual GPU readback as PPM
@@ -48,9 +52,11 @@ internal static class Program
--verify-assets Decode all original PNG/ASE files
--smoke-window Test keyboard event/resize (requires --frames 6 or more)
--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.
Gameplay, original animation speed/state and cutscenes remain under reconstruction.
Collision/pivot/cadence and animation timing are provisional. Intro/interactions remain incomplete.
""");
return 0;
}
@@ -90,9 +96,17 @@ internal static class Program
var target = (bounds.Min + bounds.Max) / 2;
var radius = Math.Max(Vector3.Distance(bounds.Min, bounds.Max) * 1.15f, 1);
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");
if (walking && (scene == null || originalStart == null))
throw new ArgumentException("Walking requires a scene and matching GAM startpoint.");
PreviewAnimationLibrary? animations = null;
LabSimulation? simulation = null;
var characterOffset = mesh.Vertices.Length;
var characterModel = Matrix4x4.Identity;
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.");
animations = new PreviewAnimationLibrary(animationPath);
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);
characterModel = placement.Model;
mesh = animations.Current.AppendTo(mesh);
Console.WriteLine($"Preview floor correction: +{placement.VerticalCorrection:F3} Y; original GAM position remains unchanged.");
Console.WriteLine("Scene preview: 1 idle (still pose), 2 run, 3 jump, 4 scratch. Playback loop/speed are preview policies; gameplay is incomplete.");
if (walking)
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.");
var fixedTimeText = Option(args, "--time");
double? fixedTime = fixedTimeText == null ? null : double.Parse(fixedTimeText, System.Globalization.CultureInfo.InvariantCulture);
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");
if (frames < 0 || (smoke && (headless || frames < 6)))
throw new ArgumentException("Invalid frame count; window smoke requires at least six frames.");
@@ -119,7 +137,7 @@ internal static class Program
if (!headless)
{
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);
if (window == 0) { Sdl.SDL_Quit(); throw new InvalidOperationException(Sdl.Error); }
}
@@ -136,29 +154,67 @@ internal static class Program
var clock = Stopwatch.StartNew();
var animationStarted = 0.0;
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;
float angle = 0.6f, elevation = 0.32f;
var count = 0;
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))
{
if (e.Type is Sdl.Quit or 0x210) running = false;
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)
{
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 (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;
animationSwitched = true;
if (!Sdl.SDL_SetWindowTitle(window, animations.WindowTitle)) throw new InvalidOperationException(Sdl.Error);
}
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)
{
fullscreen = !fullscreen;
@@ -168,33 +224,56 @@ internal static class Program
if (e.Type == Sdl.KeyUp) keys.Remove(e.Scancode);
}
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;
if (keys.Contains(80) || keys.Contains(4)) 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(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(45) || keys.Contains(86)) radius *= MathF.Exp(dt);
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(79) || keys.Contains(7)) angle += dt;
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(46) || keys.Contains(87)) radius *= MathF.Exp(-dt);
if (keys.Contains(45) || keys.Contains(86)) radius *= MathF.Exp(dt);
}
radius = Math.Max(radius, 0.01f);
var eye = target + radius * new Vector3(MathF.Cos(elevation) * MathF.Sin(angle),
MathF.Sin(elevation), MathF.Cos(elevation) * MathF.Cos(angle));
var view = originalCamera
? Matrix4x4.CreateLookAtLeftHanded(originalStart!.CameraPosition, originalStart.Position + new Vector3(0, 80, 0), 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 projection = originalCamera
var projection = originalCamera || simulation != null && !inspecting
? 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);
projection.M22 *= -1;
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.Render(view * projection);
count++;
audio?.Pump();
if (walkSmoke && !headless && count == 1 && !Sdl.SDL_SetWindowSize(window, 800, 600))
throw new InvalidOperationException(Sdl.Error);
if (smoke && count == 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 (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 (Option(args, "--screenshot") is { } screenshot)
@@ -219,6 +298,13 @@ internal static class Program
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++;
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)
{
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)
{
var pngs = Directory.GetFiles(root, "*", SearchOption.AllDirectories)