Reconstruct lab story, interactions, patrol and jet pack practice flow
This commit is contained in:
1 parent
58424120bb
commit
c929f942e1
84 files changed
+7957
-305
No files matched your search
@@ -0,0 +1,214 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>Root state exchanged with the separately implemented body solver.</summary>
|
||||
public readonly record struct PatrolBodyState(Vector3 Position, Vector3 Velocity);
|
||||
|
||||
/// <summary>
|
||||
/// Goddard/Carl's ordinary state3 patrol and state7 waypoint wait. The original base
|
||||
/// update consumes the preceding velocity/heading before choosing the next ones.
|
||||
/// Physical collision/gravity are supplied by the caller. Magnitude uses the
|
||||
/// recovered OMT table algorithm; flat atan2 heading and modern table-generation
|
||||
/// trig still require comparison against original angle/x87 results.
|
||||
/// See docs/analysis/patrol.md for recovered order, addresses and limitations.
|
||||
/// </summary>
|
||||
public sealed class ActorPatrol
|
||||
{
|
||||
public const float ArrivalDistance = 110;
|
||||
public const float YawFactor = 3.2f;
|
||||
private readonly DirectorActor actor;
|
||||
private readonly Func<string, DirectorActor?> findActor;
|
||||
private readonly Func<PatrolBodyState, float, PatrolBodyState> integrateBody;
|
||||
private readonly Func<Vector3, float> magnitude;
|
||||
private readonly float yawFactor;
|
||||
private readonly string movingAnimation, waitingAnimation;
|
||||
private DirectorActor? waypoint;
|
||||
private DirectorActor? previousWaypoint;
|
||||
private Vector3 publishedPosition, publishedRotation;
|
||||
private string? publishedPatrol;
|
||||
private int publishedState, previousState;
|
||||
private float desiredYaw;
|
||||
|
||||
public Vector3 Velocity { get; private set; }
|
||||
public Vector3 DestinationDelta { get; private set; }
|
||||
public float DestinationDistance { get; private set; }
|
||||
public bool Arrived { get; private set; }
|
||||
public float WaitRemaining { get; private set; }
|
||||
public string? CurrentWaypoint => waypoint?.Tag;
|
||||
public string? PreviousWaypoint => previousWaypoint?.Tag;
|
||||
public bool SupportedState => actor.AIstate is 1 or 3 or 7 or 9 || actor.Kind == "3CAR" && actor.AIstate == 6;
|
||||
|
||||
public ActorPatrol(DirectorActor actor, Func<string, DirectorActor?> findActor,
|
||||
Func<PatrolBodyState, float, PatrolBodyState> integrateBody,
|
||||
Func<Vector3, float>? magnitude = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actor);
|
||||
ArgumentNullException.ThrowIfNull(findActor);
|
||||
ArgumentNullException.ThrowIfNull(integrateBody);
|
||||
if (actor.Kind is not ("3DOG" or "3CAR")) throw new ArgumentException("Recovered patrol requires Goddard or Carl", nameof(actor));
|
||||
this.actor = actor;
|
||||
this.findActor = findActor;
|
||||
this.integrateBody = integrateBody;
|
||||
this.magnitude = magnitude ?? OriginalBodySupport.QuickMagnitude;
|
||||
// Carl413BFC..43 installs WALK/STOP; his Y factor remains3 (407CF8).
|
||||
yawFactor = actor.Kind == "3DOG" ? YawFactor : 3;
|
||||
movingAnimation = actor.Kind == "3DOG" ? "RUN" : "WALK";
|
||||
waitingAnimation = actor.Kind == "3DOG" ? "WAG" : "STOP";
|
||||
desiredYaw = actor.Rotation.Y;
|
||||
Publish();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Observe authored AI/teleport actions without changing their animation.
|
||||
/// Teleports reset the port body's motion/route cache; their full original
|
||||
/// physics bookkeeping is not yet recovered. Camera-only animation changes
|
||||
/// leave the body and waypoint intact. Internal patrol changes emit no event.
|
||||
/// </summary>
|
||||
public void SynchronizeAuthoredState()
|
||||
{
|
||||
if (actor.Position != publishedPosition)
|
||||
{
|
||||
Velocity = Vector3.Zero;
|
||||
ResetRoute();
|
||||
desiredYaw = actor.Rotation.Y;
|
||||
}
|
||||
if (actor.Rotation != publishedRotation) desiredYaw = actor.Rotation.Y;
|
||||
if (!Equal(actor.Patrol, publishedPatrol)
|
||||
|| actor.AIstate != publishedState && actor.AIstate == 3)
|
||||
ResetRoute();
|
||||
Publish();
|
||||
}
|
||||
|
||||
/// <returns>False when the current AI state lies outside this recovered subset.</returns>
|
||||
public bool Step(float dt)
|
||||
{
|
||||
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
|
||||
SynchronizeAuthoredState();
|
||||
if (!SupportedState) return false;
|
||||
if (!actor.Active) return true;
|
||||
if (!float.IsFinite(actor.Speed)) throw new InvalidOperationException("Nonfinite Goddard speed");
|
||||
|
||||
// EXE408023->40E050: the body consumes the *previous* velocity first.
|
||||
var body = integrateBody(new(actor.Position, Velocity), dt);
|
||||
if (!Finite(body.Position) || !Finite(body.Velocity))
|
||||
throw new InvalidOperationException("Goddard body solver produced nonfinite state");
|
||||
actor.Position = body.Position;
|
||||
Velocity = body.Velocity;
|
||||
var yawError = (desiredYaw - actor.Rotation.Y) % 360;
|
||||
if (yawError > 180) yawError -= 360;
|
||||
if (yawError < -180) yawError += 360;
|
||||
actor.Rotation = actor.Rotation with { Y = actor.Rotation.Y + yawError * yawFactor * dt };
|
||||
|
||||
switch (actor.AIstate)
|
||||
{
|
||||
case 1: Velocity = Vector3.Zero; break; // EXE40835D, after body integration.
|
||||
case 3: StepPatrol(); break;
|
||||
case 7: StepWait(dt); break;
|
||||
// State9 jumps directly to the common finisher408911. State6 calls
|
||||
// sensing409CC0 first; source player-contact dispatch is implemented
|
||||
// by SceneInteractions, while general FOV/visibility sensing is open.
|
||||
case 6: case 9: break;
|
||||
}
|
||||
// States1/6/7 return before selecting a destination angle (409186..19B).
|
||||
// Retain the old destination on a waypoint change, as the source does.
|
||||
if (actor.AIstate == 3 && DestinationDelta.X * DestinationDelta.X + DestinationDelta.Z * DestinationDelta.Z > 0)
|
||||
desiredYaw = MathF.Atan2(-DestinationDelta.X, DestinationDelta.Z) * (180 / MathF.PI);
|
||||
Publish();
|
||||
return true;
|
||||
}
|
||||
|
||||
private void StepPatrol()
|
||||
{
|
||||
waypoint ??= findActor(actor.Patrol ?? "none");
|
||||
if (waypoint == null)
|
||||
{
|
||||
SetState(1);
|
||||
Velocity = new(0, Velocity.Y, 0); // Missing initial waypoint preserves Y.
|
||||
}
|
||||
else
|
||||
{
|
||||
DestinationDelta = waypoint.Position - actor.Position;
|
||||
DestinationDistance = DestinationDelta.Length();
|
||||
if (!float.IsFinite(DestinationDistance)) throw new InvalidOperationException("Patrol destination exceeds finite arithmetic range");
|
||||
}
|
||||
// This remains after the waypoint resolver even if it changed state1.
|
||||
actor.Animation = movingAnimation;
|
||||
if (waypoint == null) return;
|
||||
|
||||
if (Arrived)
|
||||
{
|
||||
Velocity = Vector3.Zero;
|
||||
actor.Animation = waitingAnimation;
|
||||
}
|
||||
else if (DestinationDelta == Vector3.Zero) Velocity = Vector3.Zero;
|
||||
else
|
||||
{
|
||||
var length = magnitude(DestinationDelta);
|
||||
if (!float.IsFinite(length) || length <= 0) throw new InvalidOperationException("Invalid patrol magnitude");
|
||||
Velocity = DestinationDelta / length * actor.Speed;
|
||||
}
|
||||
// EXE408BC0 compares distance only after selecting the next velocity.
|
||||
if (DestinationDistance < ArrivalDistance) Arrived = true;
|
||||
else if (DestinationDistance > ArrivalDistance) Arrived = false;
|
||||
if (!Arrived || waypoint.Kind != "3PAT" || waypoint.SourceGam is not { } point) return;
|
||||
|
||||
var wait = point.Number("WaitTime");
|
||||
if (wait > 0)
|
||||
{
|
||||
SetState(7);
|
||||
actor.Animation = point.Text("WaitAnim") ?? "none";
|
||||
WaitRemaining = wait;
|
||||
Velocity = Vector3.Zero;
|
||||
return;
|
||||
}
|
||||
previousWaypoint = waypoint;
|
||||
var next = point.Text("NextPatrolPoint") ?? "none";
|
||||
waypoint = findActor(next);
|
||||
if (waypoint != null) return;
|
||||
if (Equal(next, "WAIT")) SetState(1);
|
||||
else if (Equal(next, "SCAN")) SetState(6);
|
||||
// Ordinary unresolved names, including "none", retain state3. Next tick
|
||||
// resolves the initial PatrolPoint; there is no terminal-route snap.
|
||||
}
|
||||
|
||||
private void StepWait(float dt)
|
||||
{
|
||||
Velocity = Vector3.Zero;
|
||||
if (WaitRemaining <= 0) return; // Source checks positivity before subtract.
|
||||
WaitRemaining -= dt;
|
||||
if (WaitRemaining > 0) return; // Equality expires: EXE4083B0 testah41/je.
|
||||
SetState(previousState);
|
||||
Arrived = false;
|
||||
// The timed-wait branch does not interpret WAIT/SCAN specially.
|
||||
waypoint = waypoint?.SourceGam is { } point && waypoint.Kind == "3PAT"
|
||||
? findActor(point.Text("NextPatrolPoint") ?? "none") : null;
|
||||
}
|
||||
|
||||
private void SetState(int state)
|
||||
{
|
||||
previousState = actor.AIstate;
|
||||
actor.AIstate = state;
|
||||
if (state == 1) actor.Animation = waitingAnimation;
|
||||
else if (state == 3) actor.Animation = movingAnimation;
|
||||
}
|
||||
|
||||
private void ResetRoute()
|
||||
{
|
||||
waypoint = previousWaypoint = null;
|
||||
Arrived = false;
|
||||
WaitRemaining = 0;
|
||||
DestinationDelta = Vector3.Zero;
|
||||
DestinationDistance = 0;
|
||||
}
|
||||
|
||||
private void Publish()
|
||||
{
|
||||
publishedPosition = actor.Position;
|
||||
publishedRotation = actor.Rotation;
|
||||
publishedPatrol = actor.Patrol;
|
||||
publishedState = actor.AIstate;
|
||||
}
|
||||
private static bool Equal(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
|
||||
private static bool Finite(Vector3 v) => float.IsFinite(v.X) && float.IsFinite(v.Y) && float.IsFinite(v.Z);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Numerics;
|
||||
using GamePort.Assets;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>
|
||||
/// Explicit provisional narrowphase adapter. Source mode2 gates/corners/order
|
||||
/// come from DynamicSceneCollision; sweep/slide uses the modern sphere kernel.
|
||||
/// This is not a translation of original47BD80.
|
||||
/// </summary>
|
||||
public static class DynamicBodyResponse
|
||||
{
|
||||
public static Vector3 Resolve(IEnumerable<DynamicBoxCollider> boxes, Vector3 previous, Vector3 position, float radius)
|
||||
{
|
||||
foreach (var box in boxes)
|
||||
{
|
||||
var response = DynamicSceneCollision.Resolve(box, new(previous, position, radius), Sweep);
|
||||
if (response.Contact) position = response.Position;
|
||||
}
|
||||
return position;
|
||||
}
|
||||
|
||||
private static DynamicCollisionResponse Sweep(DynamicBoxSweep sweep)
|
||||
{
|
||||
var vertices = sweep.Triangles.SelectMany(t => new[] { t.A, t.B, t.C })
|
||||
.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray();
|
||||
var mesh = new Mesh(vertices, Enumerable.Range(0, vertices.Length).Select(i => (uint)i).ToArray());
|
||||
var radius = sweep.Sphere.Radius;
|
||||
var moved = new SceneCollision(mesh).Move(sweep.Sphere.PreviousPosition - Vector3.UnitY * radius,
|
||||
sweep.Sphere.Position - sweep.Sphere.PreviousPosition, radius, radius * 2);
|
||||
var position = moved.Position + Vector3.UnitY * radius;
|
||||
return new(Vector3.DistanceSquared(position, sweep.Sphere.Position) > .0001f, position);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>
|
||||
/// A mode2 entity's original local shape cube and current transform. Drawing
|
||||
/// visibility and own physics integration are independent of CollisionEnabled.
|
||||
/// </summary>
|
||||
public readonly record struct DynamicBoxCollider(
|
||||
int Identity, Vector3 Root, Vector3 LocalMin, Vector3 LocalMax, Matrix4x4 LocalToWorld,
|
||||
float Radius = 40, bool CollisionEnabled = true, bool InhibitResponse = false);
|
||||
|
||||
public readonly record struct DynamicSphereMotion(
|
||||
Vector3 PreviousPosition, Vector3 Position, float Radius,
|
||||
bool CollisionEnabled = true, bool GeometryCollisionEnabled = true, int Mode = 1);
|
||||
|
||||
public sealed record DynamicBoxSweep(
|
||||
DynamicBoxCollider Box, DynamicSphereMotion Sphere, IReadOnlyList<SupportTriangle> Triangles);
|
||||
|
||||
public readonly record struct DynamicCollisionResponse(bool Contact, Vector3 Position);
|
||||
|
||||
/// <summary>
|
||||
/// Recovered mode2 dispatch, broadphase and oriented local-cube triangulation
|
||||
/// from EXE47A430/47A5E0. The narrowphase is injected because47BD80 and its
|
||||
/// static-world response have not been fully translated. See dynamic-collision.md.
|
||||
/// </summary>
|
||||
public static class DynamicSceneCollision
|
||||
{
|
||||
// C3DDoorUpDown constructor/PostLoad: pair tests on, own integration off,
|
||||
// mode2 and current radius40. HasCollision=-1 preserves those defaults.
|
||||
public const float DoorRadius = 40;
|
||||
public const int DoorMode = 2;
|
||||
public const bool DoorEntityCollisionDefault = true;
|
||||
public const bool DoorIntegrationDefault = false;
|
||||
|
||||
// Corner bits X=4,Y=2,Z=1. Source jump table47B3AC selects these12 triples.
|
||||
private static readonly int[] triangleCorners = [
|
||||
0, 1, 2, 1, 3, 2, 0, 2, 4, 2, 6, 4,
|
||||
4, 6, 5, 6, 7, 5, 5, 7, 3, 5, 3, 1,
|
||||
0, 4, 1, 4, 5, 1, 2, 3, 7, 7, 6, 2
|
||||
];
|
||||
|
||||
public static (bool EntityCollision, bool Integrate) DoorCollisionFlags(int hasCollision) =>
|
||||
hasCollision == -1 ? (DoorEntityCollisionDefault, DoorIntegrationDefault)
|
||||
: (hasCollision != 0, hasCollision != 0);
|
||||
|
||||
/// <summary>
|
||||
/// Preserve the original inclusive root-distance gate. Normal sphere-mode
|
||||
/// bodies use 2*boxRadius+sphereRadius, even for a large shape-local cube.
|
||||
/// Mode2-vs-mode2 instead uses the radius sum and skips the triangle sweep.
|
||||
/// </summary>
|
||||
public static bool BroadPhase(DynamicBoxCollider box, DynamicSphereMotion sphere)
|
||||
{
|
||||
Validate(box, sphere);
|
||||
if (!box.CollisionEnabled || !sphere.CollisionEnabled || !sphere.GeometryCollisionEnabled) return false;
|
||||
var limit = sphere.Mode == 2 ? box.Radius + sphere.Radius : 2 * box.Radius + sphere.Radius;
|
||||
return OriginalBodySupport.QuickMagnitude(sphere.Position - box.Root) <= limit;
|
||||
}
|
||||
|
||||
public static Vector3[] Corners(DynamicBoxCollider box)
|
||||
{
|
||||
ValidateBox(box);
|
||||
var corners = new Vector3[8];
|
||||
for (var i = 0; i < corners.Length; i++)
|
||||
{
|
||||
var local = new Vector3((i & 4) == 0 ? box.LocalMin.X : box.LocalMax.X,
|
||||
(i & 2) == 0 ? box.LocalMin.Y : box.LocalMax.Y,
|
||||
(i & 1) == 0 ? box.LocalMin.Z : box.LocalMax.Z);
|
||||
corners[i] = Vector3.Transform(local, box.LocalToWorld);
|
||||
RequireFinite(corners[i]);
|
||||
}
|
||||
return corners;
|
||||
}
|
||||
|
||||
public static SupportTriangle[] Triangles(DynamicBoxCollider box)
|
||||
{
|
||||
var corners = Corners(box);
|
||||
return Enumerable.Range(0, 12).Select(i => new SupportTriangle(
|
||||
corners[triangleCorners[3 * i]], corners[triangleCorners[3 * i + 1]],
|
||||
corners[triangleCorners[3 * i + 2]], box.Identity, i)).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Caller supplies mutual exclusion/class gates via pairAllowed and the current
|
||||
/// source cube/transform. Triangle geometry follows the moving box's current
|
||||
/// root; no invented relative-door sweep or permanent closed-position mesh.
|
||||
/// </summary>
|
||||
public static DynamicCollisionResponse Resolve(DynamicBoxCollider box, DynamicSphereMotion sphere,
|
||||
Func<DynamicBoxSweep, DynamicCollisionResponse> narrowPhase, bool pairAllowed = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(narrowPhase);
|
||||
var unchanged = new DynamicCollisionResponse(false, sphere.Position);
|
||||
if (!pairAllowed || !BroadPhase(box, sphere)) return unchanged;
|
||||
// EXE47A712..47A72C returns contact directly for a second mode2 entity.
|
||||
if (sphere.Mode == 2) return new(true, sphere.Position);
|
||||
var response = narrowPhase(new(box, sphere, Triangles(box)));
|
||||
if (!response.Contact) return unchanged;
|
||||
RequireFinite(response.Position);
|
||||
// EXE47B2EF checks the box's iface1E0 flag after narrowphase; touch events
|
||||
// can still occur even when its ordinary root response is inhibited.
|
||||
return new(true, box.InhibitResponse ? sphere.Position : response.Position);
|
||||
}
|
||||
|
||||
private static void Validate(DynamicBoxCollider box, DynamicSphereMotion sphere)
|
||||
{
|
||||
ValidateBox(box);
|
||||
RequireFinite(sphere.Position); RequireFinite(sphere.PreviousPosition);
|
||||
if (!float.IsFinite(sphere.Radius) || sphere.Radius < 0)
|
||||
throw new ArgumentOutOfRangeException(nameof(sphere), "Finite nonnegative sphere radius required");
|
||||
}
|
||||
private static void ValidateBox(DynamicBoxCollider box)
|
||||
{
|
||||
RequireFinite(box.Root); RequireFinite(box.LocalMin); RequireFinite(box.LocalMax);
|
||||
if (box.LocalMin.X > box.LocalMax.X || box.LocalMin.Y > box.LocalMax.Y || box.LocalMin.Z > box.LocalMax.Z
|
||||
|| !float.IsFinite(box.Radius) || box.Radius < 0)
|
||||
throw new ArgumentOutOfRangeException(nameof(box), "Ordered source cube and finite nonnegative radius required");
|
||||
var m = box.LocalToWorld;
|
||||
if (new[] { m.M11, m.M12, m.M13, m.M14, m.M21, m.M22, m.M23, m.M24,
|
||||
m.M31, m.M32, m.M33, m.M34, m.M41, m.M42, m.M43, m.M44 }.Any(v => !float.IsFinite(v))
|
||||
|| m.M14 != 0 || m.M24 != 0 || m.M34 != 0 || m.M44 != 1)
|
||||
throw new ArgumentOutOfRangeException(nameof(box), "Finite affine source transform required");
|
||||
}
|
||||
private static void RequireFinite(Vector3 v)
|
||||
{
|
||||
if (!float.IsFinite(v.X) || !float.IsFinite(v.Y) || !float.IsFinite(v.Z))
|
||||
throw new ArgumentOutOfRangeException(nameof(v), "Finite source coordinates required");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
namespace GamePort.Game;
|
||||
|
||||
public readonly record struct JetpackBurstState(
|
||||
int JumpState = 0, float HoldSeconds = 0, float EffectRemaining = 0);
|
||||
|
||||
public readonly record struct JetpackBurstInput(
|
||||
bool Grounded, bool JumpHeld, float VelocityY, float ShadowDistance,
|
||||
int InventoryState, float Energy, string LevelCode, int GadgetMode,
|
||||
float DeltaSeconds, float CurrentExtraAccelerationY,
|
||||
bool EffectAvailable = true, float GravityY = -800);
|
||||
|
||||
public enum JetpackPose { None, Jump, Fall, Fly }
|
||||
|
||||
public readonly record struct JetpackBurstResult(
|
||||
JetpackBurstState State, float ImpulseY, float? VelocityYOverride,
|
||||
float ExtraAccelerationY, JetpackPose Pose, float? RadiusOverride,
|
||||
bool StartGadget, bool StopGadget, int? MovementModeOverride);
|
||||
|
||||
public readonly record struct JetpackEffectResult(
|
||||
JetpackBurstState State, float Energy, bool Visible);
|
||||
|
||||
/// <summary>
|
||||
/// The jump/jetpack branches of EXE437F90 and effect timer of EXE421FB0.
|
||||
/// Controller and effect phases are separate: their full-scene order has not
|
||||
/// been recovered. The caller must explicitly choose an order. Horizontal
|
||||
/// movement, shadow queries, visuals and sound callbacks belong to the caller.
|
||||
/// </summary>
|
||||
public static class JetpackBurst
|
||||
{
|
||||
public const float Duration = 8;
|
||||
public const float HoldThreshold = .4f;
|
||||
public const float JumpImpulse = 550;
|
||||
public const float BurstInitialVelocityY = 10;
|
||||
public const float BurstRadius = 100;
|
||||
public const float LandingRadius = 60;
|
||||
public const float EnergyPerSecond = .5f;
|
||||
|
||||
/// <summary>
|
||||
/// Includes the outer update's ordinary grounded/released reset (437B9E).
|
||||
/// CurrentExtraAccelerationY is required because the expired-effect branch
|
||||
/// returns before writing acceleration. Results describe this invocation;
|
||||
/// a newly started/stopped burst changes acceleration on the next call.
|
||||
/// </summary>
|
||||
public static JetpackBurstResult Step(JetpackBurstState state, JetpackBurstInput input)
|
||||
{
|
||||
ValidateState(state);
|
||||
ValidateSeconds(input.DeltaSeconds);
|
||||
RequireFinite(input.VelocityY);
|
||||
RequireFinite(input.ShadowDistance);
|
||||
RequireFinite(input.Energy);
|
||||
RequireFinite(input.CurrentExtraAccelerationY);
|
||||
RequireFinite(input.GravityY);
|
||||
ArgumentNullException.ThrowIfNull(input.LevelCode);
|
||||
var extra = input.CurrentExtraAccelerationY;
|
||||
JetpackBurstResult Result(float impulse = 0, float? velocity = null,
|
||||
JetpackPose pose = JetpackPose.None, float? radius = null,
|
||||
bool start = false, bool stop = false, int? mode = null) =>
|
||||
new(state, impulse, velocity, extra, pose, radius, start, stop, mode);
|
||||
|
||||
if (input.Grounded && !input.JumpHeld)
|
||||
{
|
||||
// This path runs ground apply instead of air apply; it does not
|
||||
// itself clear the effect timer or restore the radius.
|
||||
state = state with { JumpState = 0 };
|
||||
return Result(mode: 0);
|
||||
}
|
||||
|
||||
if (state.JumpState < 3)
|
||||
extra = input.GravityY * 1.33f - input.GravityY;
|
||||
else
|
||||
{
|
||||
if (input.EffectAvailable && state.EffectRemaining <= 0 && state.JumpState is 3 or 4)
|
||||
{
|
||||
state = state with { JumpState = 0, EffectRemaining = 0 };
|
||||
return Result(pose: JetpackPose.Fall, stop: true, mode: 1);
|
||||
}
|
||||
// The near-floor constants are doubles in the original; the far
|
||||
// branch uses float .1. Preserve those distinct constant widths.
|
||||
extra = input.ShadowDistance < 500
|
||||
? (float)(-input.GravityY - (input.VelocityY < -1 ? .3 : .1) * input.GravityY)
|
||||
: .1f * input.GravityY - input.GravityY;
|
||||
}
|
||||
|
||||
if (!input.JumpHeld)
|
||||
{
|
||||
switch (state.JumpState)
|
||||
{
|
||||
case 1:
|
||||
state = state with { JumpState = 2 };
|
||||
break;
|
||||
case 3:
|
||||
state = state with { JumpState = 4,
|
||||
EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining };
|
||||
return Result(pose: JetpackPose.Fall, stop: true, mode: 1);
|
||||
case 4:
|
||||
// Table4387C4 entry3 jumps directly43879A. Only state5's
|
||||
// entry checks grounded at43878C (outer reset above too).
|
||||
state = state with { JumpState = 0 };
|
||||
break;
|
||||
}
|
||||
return Result();
|
||||
}
|
||||
|
||||
switch (state.JumpState)
|
||||
{
|
||||
case 0:
|
||||
if (!input.Grounded) return Result(pose: JetpackPose.Fall, stop: true);
|
||||
state = state with { JumpState = 1, HoldSeconds = 0,
|
||||
EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining };
|
||||
return Result(impulse: JumpImpulse, pose: JetpackPose.Jump);
|
||||
case 1:
|
||||
state = state with { HoldSeconds = state.HoldSeconds + input.DeltaSeconds };
|
||||
if (state.HoldSeconds <= HoldThreshold) return Result();
|
||||
break;
|
||||
case 2:
|
||||
break;
|
||||
case 3:
|
||||
if (!input.Grounded) return Result();
|
||||
state = state with { JumpState = 4,
|
||||
EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining };
|
||||
return Result(pose: JetpackPose.Fall, radius: LandingRadius, stop: true, mode: 1);
|
||||
case 5:
|
||||
if (input.Grounded) state = state with { JumpState = 0 };
|
||||
return Result();
|
||||
default:
|
||||
return Result();
|
||||
}
|
||||
|
||||
// Both the >.4-second and released-then-held branches enter state3
|
||||
// even when no gadget is available. The next expired-effect guard
|
||||
// then returns to state0, preserving the ballistic acceleration.
|
||||
state = state with { JumpState = 3 };
|
||||
if (!CanStart(input.LevelCode, input.GadgetMode, input.InventoryState, input.Energy)) return Result();
|
||||
if (input.EffectAvailable) state = state with { EffectRemaining = Duration };
|
||||
return Result(velocity: BurstInitialVelocityY, pose: JetpackPose.Fly,
|
||||
radius: input.EffectAvailable ? BurstRadius : null, start: true);
|
||||
}
|
||||
|
||||
public static bool CanStart(string levelCode, int gadgetMode, int inventoryState, float energy)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(levelCode);
|
||||
RequireFinite(energy);
|
||||
if (levelCode == "VR04") return true;
|
||||
return levelCode is not ("LEV6" or "LV4B" or "LV6A" or "LEV3" or "LV3A" or "LV3B" or "LV3C" or "LV3D")
|
||||
&& gadgetMode is not (2 or 6 or 7) && energy > 0 && inventoryState is not (0 or 4);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Effect421FB0 resets grounded remaining time to0, subtracts dt (including
|
||||
/// when inactive), then drains only if the stored result is positive.
|
||||
/// Owner/effect absence leaves timer and energy unchanged. Energy reaching
|
||||
/// zero does not cancel an already running burst. Visibility is this phase's
|
||||
/// request; the controller phase does not itself show/hide the effect.
|
||||
/// </summary>
|
||||
public static JetpackEffectResult StepEffect(JetpackBurstState state, bool grounded,
|
||||
float deltaSeconds, float energy, string levelCode,
|
||||
bool ownerAvailable = true, bool effectAvailable = true)
|
||||
{
|
||||
ValidateState(state);
|
||||
ValidateSeconds(deltaSeconds);
|
||||
RequireFinite(energy);
|
||||
ArgumentNullException.ThrowIfNull(levelCode);
|
||||
if (!ownerAvailable || !effectAvailable) return new(state, energy, false);
|
||||
var remaining = (grounded ? 0 : state.EffectRemaining) - deltaSeconds;
|
||||
state = state with { EffectRemaining = remaining };
|
||||
if (remaining <= 0) return new(state, energy, false);
|
||||
return new(state, AdjustEnergy(energy, -deltaSeconds * EnergyPerSecond, levelCode), true);
|
||||
}
|
||||
|
||||
/// <summary>EXE42A920 numeric VR01..VR08 immunity and [0,100] clamp. SFX are external.</summary>
|
||||
public static float AdjustEnergy(float energy, float delta, string levelCode)
|
||||
{
|
||||
RequireFinite(energy);
|
||||
RequireFinite(delta);
|
||||
ArgumentNullException.ThrowIfNull(levelCode);
|
||||
// The source compares a big-endian FourCC numerically, not by prefix.
|
||||
if (levelCode.Length == 4)
|
||||
{
|
||||
var code = ((uint)levelCode[0] << 24) | ((uint)levelCode[1] << 16)
|
||||
| ((uint)levelCode[2] << 8) | levelCode[3];
|
||||
if (code is >= 0x56523031 and <= 0x56523038) return energy;
|
||||
}
|
||||
return Math.Clamp(energy + delta, 0, 100);
|
||||
}
|
||||
|
||||
private static void ValidateState(JetpackBurstState state)
|
||||
{
|
||||
if (state.JumpState is < 0 or > 5) throw new ArgumentOutOfRangeException(nameof(state));
|
||||
RequireFinite(state.HoldSeconds);
|
||||
RequireFinite(state.EffectRemaining);
|
||||
}
|
||||
|
||||
private static void ValidateSeconds(float seconds)
|
||||
{
|
||||
if (!float.IsFinite(seconds) || seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));
|
||||
}
|
||||
|
||||
private static void RequireFinite(float value)
|
||||
{
|
||||
if (!float.IsFinite(value)) throw new ArgumentOutOfRangeException(nameof(value));
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ using GamePort.Assets;
|
||||
namespace GamePort.Game;
|
||||
|
||||
public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump);
|
||||
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall }
|
||||
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly }
|
||||
|
||||
/// <summary>
|
||||
/// No-gadget walking checkpoint. Recovered input/arithmetic is described in
|
||||
@@ -16,9 +16,18 @@ public sealed class LabSimulation
|
||||
public const float BodyRadius = 24; // Provisional, not a recovered collider dimension.
|
||||
private readonly SceneCollision collision;
|
||||
private readonly Vector3 sourceStart;
|
||||
private readonly float startYaw, modelMinimumY, rootHeight;
|
||||
private float targetYaw, jumpHeldTime;
|
||||
private int jumpState;
|
||||
private readonly float startYaw, modelMinimumY, rootHeight, startFloor;
|
||||
private float targetYaw, extraAirAcceleration, shadowDistance;
|
||||
private JetpackBurstState jumpState;
|
||||
private bool forceFall;
|
||||
public Func<int>? JetpackInventoryState { get; set; }
|
||||
public string LevelCode { get; set; } = "LV1B";
|
||||
public int GadgetMode { get; set; } = -1;
|
||||
public float Energy { get; set; } = 20;
|
||||
public float InteractionRadius { get; private set; } = 60;
|
||||
public bool JetpackEffectVisible { get; private set; }
|
||||
public float JetpackRemaining => jumpState.EffectRemaining;
|
||||
public int Bursts { get; private set; }
|
||||
public float BodyHeight { get; }
|
||||
public Vector3 Position { get; private set; } // Feet, not original actor root.
|
||||
public Vector3 Velocity { get; private set; }
|
||||
@@ -26,13 +35,15 @@ public sealed class LabSimulation
|
||||
public float Speed { get; private set; }
|
||||
public bool Grounded { get; private set; }
|
||||
public PlayerPose Pose => Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
|
||||
: Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
|
||||
: jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly
|
||||
: !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
|
||||
public int Steps { get; private set; }
|
||||
public int Jumps { get; private set; }
|
||||
public int Landings { get; private set; }
|
||||
public int WallHits { get; private set; }
|
||||
public float Travel { get; private set; }
|
||||
public float MaximumRise { get; private set; }
|
||||
public Func<Vector3, Vector3, float, Vector3>? DynamicRootResolver { get; set; }
|
||||
public Vector3 ActorRoot => Position + Vector3.UnitY * rootHeight;
|
||||
public Vector3 CameraEye { get; private set; }
|
||||
public Vector3 CameraTarget => ActorRoot + new Vector3(0, 99, 0);
|
||||
@@ -49,7 +60,11 @@ public sealed class LabSimulation
|
||||
BodyHeight = bounds.Max.Y - bounds.Min.Y;
|
||||
var floor = collision.GroundHeight(start, 2500)
|
||||
?? throw new InvalidDataException("No support below GAM startpoint");
|
||||
rootHeight = start.Y - floor;
|
||||
startFloor = floor;
|
||||
// Normal Jimmy PostLoad4236A3..BA and support47BAE1 place the actor
|
||||
// root at floor+60*1.265. Serialized spawnY is settled by physics.
|
||||
// Feet collision and sole-based visual placement remain provisional.
|
||||
rootHeight = OriginalBodySupport.JimmyRadius * OriginalBodySupport.JimmyFactor;
|
||||
Reset();
|
||||
}
|
||||
|
||||
@@ -59,8 +74,10 @@ public sealed class LabSimulation
|
||||
Position = new(sourceStart.X, floor + SceneCollision.Skin, sourceStart.Z);
|
||||
Velocity = Vector3.Zero;
|
||||
Yaw = targetYaw = startYaw;
|
||||
Speed = jumpHeldTime = 0;
|
||||
jumpState = 0;
|
||||
Speed = extraAirAcceleration = shadowDistance = 0;
|
||||
jumpState = default;
|
||||
forceFall = JetpackEffectVisible = false;
|
||||
InteractionRadius = 60; Bursts = 0;
|
||||
Grounded = true;
|
||||
Steps = Jumps = Landings = WallHits = 0;
|
||||
Travel = MaximumRise = 0;
|
||||
@@ -83,7 +100,7 @@ public sealed class LabSimulation
|
||||
float lateral = 0;
|
||||
if (Grounded)
|
||||
{
|
||||
if (!input.Jump) jumpState = 0;
|
||||
InteractionRadius = 60; // Jimmy's ordinary grounded update42469B.
|
||||
float yawDelta = 0;
|
||||
if (input.Left) { yawDelta += 20; lateral = -1000; Speed = RecoveredMotion.AddSpeed(Speed); }
|
||||
else if (input.Right) { yawDelta -= 20; lateral = 1000; Speed = RecoveredMotion.AddSpeed(Speed); }
|
||||
@@ -97,34 +114,47 @@ public sealed class LabSimulation
|
||||
var (sin, cos) = Trig(Yaw);
|
||||
var velocity = new Vector3(-sin * Speed, Velocity.Y, cos * Speed);
|
||||
if (Grounded) velocity += new Vector3(cos, 0, sin) * (lateral * dt);
|
||||
var impulse = Vector3.Zero;
|
||||
if (Grounded && input.Jump && jumpState == 0)
|
||||
{
|
||||
impulse.Y = RecoveredMotion.JumpImpulse;
|
||||
jumpState = 1;
|
||||
jumpHeldTime = 0;
|
||||
Grounded = false;
|
||||
Jumps++;
|
||||
}
|
||||
if (!Grounded && jumpState == 1)
|
||||
{
|
||||
if (!input.Jump) jumpState = 2;
|
||||
else if ((jumpHeldTime += dt) > 0.4f) jumpState = 0; // Zero-fuel jetpack path resets to FALL.
|
||||
}
|
||||
else if (!Grounded && jumpState == 2 && input.Jump)
|
||||
jumpState = 0; // Renewed hold enters the same disabled-gadget reset path.
|
||||
if (collision.GroundHeight(ActorRoot, 2500) is { } shadowFloor)
|
||||
shadowDistance = MathF.Abs(ActorRoot.Y - shadowFloor - 13);
|
||||
var air = JetpackBurst.Step(jumpState, new(Grounded, input.Jump, velocity.Y, shadowDistance,
|
||||
JetpackInventoryState?.Invoke() ?? 0, Energy, LevelCode, GadgetMode, dt, extraAirAcceleration));
|
||||
jumpState = air.State; extraAirAcceleration = air.ExtraAccelerationY;
|
||||
var impulse = new Vector3(0, air.ImpulseY, 0);
|
||||
if (air.ImpulseY != 0) { Grounded = false; Jumps++; }
|
||||
if (air.VelocityYOverride is { } vertical) velocity.Y = vertical;
|
||||
if (air.RadiusOverride is { } radius) InteractionRadius = radius;
|
||||
if (air.Pose == JetpackPose.Fall) forceFall = true;
|
||||
else if (air.Pose is JetpackPose.Jump or JetpackPose.Fly) forceFall = false;
|
||||
if (air.StartGadget) Bursts++;
|
||||
var displacement = RecoveredMotion.Integrate(ref velocity, ref impulse,
|
||||
RecoveredMotion.Gravity * 0.33f, RecoveredMotion.Gravity, dt);
|
||||
Vector3.UnitY * extraAirAcceleration, RecoveredMotion.Gravity, dt);
|
||||
var before = Position;
|
||||
var result = collision.Move(Position, displacement, BodyRadius, BodyHeight);
|
||||
Position = result.Position;
|
||||
if (DynamicRootResolver != null)
|
||||
{
|
||||
var root = ActorRoot;
|
||||
var resolved = DynamicRootResolver(before + Vector3.UnitY * rootHeight, root, InteractionRadius);
|
||||
if (resolved != root)
|
||||
{
|
||||
// Original47A5E0 re-clips against static geometry before storing
|
||||
// the new root. Here both kernels remain explicitly provisional.
|
||||
result = collision.Move(Position, resolved - root, BodyRadius, BodyHeight);
|
||||
Position = result.Position;
|
||||
}
|
||||
}
|
||||
Grounded = result.Grounded && velocity.Y <= 0;
|
||||
if (Grounded && velocity.Y < 0 || result.HitCeiling && velocity.Y > 0) velocity.Y = 0;
|
||||
if (Grounded) { extraAirAcceleration = 0; forceFall = false; }
|
||||
Velocity = velocity;
|
||||
// Explicit port phase policy: controller, collision, then effect update.
|
||||
// Original global object iteration order has not yet been matched.
|
||||
var effect = JetpackBurst.StepEffect(jumpState, Grounded, dt, Energy, LevelCode);
|
||||
jumpState = effect.State; Energy = effect.Energy; JetpackEffectVisible = effect.Visible;
|
||||
if (!wasGrounded && Grounded) Landings++;
|
||||
if (result.HitWall) WallHits++;
|
||||
Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z));
|
||||
MaximumRise = Math.Max(MaximumRise, Position.Y - sourceStart.Y + rootHeight);
|
||||
MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor);
|
||||
Steps++;
|
||||
var desired = DesiredEye();
|
||||
var delta = (desired - CameraEye) * new Vector3(1.6f, 1.2f, 1.6f) * dt;
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
public readonly record struct SupportTriangle(Vector3 A, Vector3 B, Vector3 C, int ShapeId = 0, int PolygonId = 0);
|
||||
public readonly record struct SupportHit(Vector3 Position, int ShapeId, int PolygonId, float Distance);
|
||||
public delegate SupportHit? SupportSegmentQuery(Vector3 start, Vector3 end, bool twoSided);
|
||||
|
||||
public readonly record struct SupportBody(
|
||||
Vector3 Position, Vector3 PreviousPosition, Vector3 Velocity, Vector3 Acceleration,
|
||||
float Radius, float Factor, bool PreventLowering = true);
|
||||
|
||||
public readonly record struct SupportResult(
|
||||
SupportBody Body, bool Supported, bool Landed, SupportHit? Hit, Vector3 SupportAnchor);
|
||||
|
||||
/// <summary>
|
||||
/// Bounded translation of EXE47B890 and its source triangle query. This handles
|
||||
/// root support, not the wall/ceiling sphere solver or entity collisions. Lookup
|
||||
/// tables use the recovered initializer constants with modern trig; exact x87
|
||||
/// table values and full original frame ordering still require comparison.
|
||||
/// </summary>
|
||||
public static class OriginalBodySupport
|
||||
{
|
||||
public const float JimmyRadius = 60;
|
||||
public const float JimmyFactor = 1.265f;
|
||||
public const float GoddardRadius = 130;
|
||||
public const float GoddardFactor = 0.3f;
|
||||
private const float TriangleEpsilon = 1.1920928955078125e-7f;
|
||||
private static readonly float[] sine = BuildSine();
|
||||
private static readonly ushort[] halfAcos = BuildHalfAcos();
|
||||
|
||||
/// <summary>OMT1001FF70: largest component divided by a quantized sine lookup.</summary>
|
||||
public static float QuickMagnitude(Vector3 vector)
|
||||
{
|
||||
RequireFinite(vector);
|
||||
var x = (double)MathF.Abs(vector.X);
|
||||
var y = (double)MathF.Abs(vector.Y);
|
||||
var z = (double)MathF.Abs(vector.Z);
|
||||
if (x > y) { if (x > z) (x, z) = (z, x); }
|
||||
else if (y > z) (y, z) = (z, y);
|
||||
// The original passes 0/0 through _ftol. The port handles zero directly
|
||||
// instead of depending on an invalid x87 conversion/control-word mode.
|
||||
if (z == 0) return 0;
|
||||
var otherSquared = x * x + y * y;
|
||||
var index = (int)(otherSquared * 16384 / (otherSquared + z * z)) & 0x3fff;
|
||||
return (float)(z / sine[halfAcos[index] & 0x3fff]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Apply support after motion/wall resolution. The caller captures previous
|
||||
/// grounded state and clears its current grounded flag before this phase.
|
||||
/// A successful support preserves horizontal velocity/acceleration, sets their
|
||||
/// Y components to zero and emits a landing only on an ungrounded-to-grounded step.
|
||||
/// </summary>
|
||||
public static SupportResult Resolve(SupportBody body, bool wasGrounded,
|
||||
SupportSegmentQuery query, bool geometryEnabled = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
RequireFinite(body.Position); RequireFinite(body.PreviousPosition);
|
||||
RequireFinite(body.Velocity); RequireFinite(body.Acceleration);
|
||||
if (!float.IsFinite(body.Radius) || body.Radius <= 0 || !float.IsFinite(body.Factor))
|
||||
throw new ArgumentOutOfRangeException(nameof(body), "Finite support factor and positive finite radius required");
|
||||
var unchanged = new SupportResult(body, false, false, null, Vector3.Zero);
|
||||
if (!geometryEnabled) return unchanged;
|
||||
|
||||
var product = body.Radius * body.Factor;
|
||||
var top = MathF.Max(body.Position.Y, body.PreviousPosition.Y);
|
||||
var motionHit = query(body.PreviousPosition, body.Position, false);
|
||||
if (motionHit is { } crossed)
|
||||
top += QuickMagnitude(body.Position - body.PreviousPosition)
|
||||
- QuickMagnitude(crossed.Position - body.PreviousPosition);
|
||||
// EXE48D920 is .1f, not .5f. Final root offset always uses r*factor.
|
||||
var clearance = body.Factor == 1 || body.Factor < 0.1f ? body.Radius : product;
|
||||
var start = new Vector3(body.Position.X, top + clearance, body.Position.Z);
|
||||
var end = new Vector3(body.Position.X, body.Position.Y - 2 * body.Radius, body.Position.Z);
|
||||
var hit = query(start, end, false);
|
||||
if (hit is not { } floor) return unchanged;
|
||||
var supportedY = floor.Position.Y + product;
|
||||
// EXE47BAF3 queries iface208. It rejects a downward root correction,
|
||||
// independently of vertical velocity, when this flag is enabled.
|
||||
if (body.PreventLowering && body.Position.Y > supportedY) return unchanged;
|
||||
var grounded = body with {
|
||||
Position = new(body.Position.X, supportedY, body.Position.Z),
|
||||
Velocity = new(body.Velocity.X, 0, body.Velocity.Z),
|
||||
Acceleration = new(body.Acceleration.X, 0, body.Acceleration.Z)
|
||||
};
|
||||
return new SupportResult(grounded, true, !wasGrounded, floor, new Vector3(0, supportedY, 0));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EXE469B70/47C6E0 source-winding segment query. Null-material polygons must
|
||||
/// be included. The caller supplies the statically registered polygons;
|
||||
/// checkpoint/material and game-specific registration filters are separate.
|
||||
/// A linear scan replaces the original 260x260 broad phase. Equal-distance
|
||||
/// selection follows input order, which can differ from original grid order.
|
||||
/// </summary>
|
||||
public static SupportHit? Trace(IEnumerable<SupportTriangle> triangles,
|
||||
Vector3 start, Vector3 end, bool twoSided = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(triangles);
|
||||
RequireFinite(start); RequireFinite(end);
|
||||
var direction = end - start;
|
||||
var length = QuickMagnitude(direction);
|
||||
if (length == 0) return null;
|
||||
direction /= length;
|
||||
SupportHit? nearest = null;
|
||||
var nearestDistance = length;
|
||||
foreach (var triangle in triangles)
|
||||
{
|
||||
RequireFinite(triangle.A); RequireFinite(triangle.B); RequireFinite(triangle.C);
|
||||
var edge1 = triangle.B - triangle.A;
|
||||
var edge2 = triangle.C - triangle.A;
|
||||
var p = Cross(direction, edge2);
|
||||
var determinant = Dot(edge1, p);
|
||||
// Source indices use the opposite sign from a conventional right-
|
||||
// handed visible-front-face test. Preserve the actual serialized order.
|
||||
if (twoSided ? MathF.Abs(determinant) < TriangleEpsilon : determinant > -TriangleEpsilon)
|
||||
continue;
|
||||
var inverse = 1 / determinant;
|
||||
var relative = start - triangle.A;
|
||||
var u = Dot(relative, p) * inverse;
|
||||
if (u < 0 || u > 1) continue;
|
||||
var q = Cross(relative, edge1);
|
||||
var v = Dot(q, direction) * inverse;
|
||||
if (v < 0 || u + v > 1) continue;
|
||||
var distance = Dot(q, edge2) * inverse;
|
||||
// Source accepts the beginning, but rejects its endpoint and equal
|
||||
// distance candidates. No invented extra ray distance or skin is used.
|
||||
if (distance < 0 || distance >= length) continue;
|
||||
var position = start + direction * distance;
|
||||
var fromStart = QuickMagnitude(position - start);
|
||||
if (fromStart >= nearestDistance) continue;
|
||||
nearestDistance = fromStart;
|
||||
nearest = new SupportHit(position, triangle.ShapeId, triangle.PolygonId, fromStart);
|
||||
}
|
||||
return nearest;
|
||||
}
|
||||
|
||||
private static float Dot(Vector3 a, Vector3 b) =>
|
||||
(float)((double)a.X * b.X + (double)a.Y * b.Y + (double)a.Z * b.Z);
|
||||
private static Vector3 Cross(Vector3 a, Vector3 b) => new(
|
||||
(float)((double)a.Y * b.Z - (double)a.Z * b.Y),
|
||||
(float)((double)a.Z * b.X - (double)a.X * b.Z),
|
||||
(float)((double)a.X * b.Y - (double)a.Y * b.X));
|
||||
|
||||
private static float[] BuildSine()
|
||||
{
|
||||
var table = new float[16384];
|
||||
// DLL100EDC21 uses this stored double, rather than Math.Tau/16384.
|
||||
for (var i = 0; i < table.Length; i++) table[i] = (float)Math.Sin(i * 0.0003834951969604492);
|
||||
table[0] = table[8192] = 0; table[4096] = 1; table[12288] = -1;
|
||||
return table;
|
||||
}
|
||||
private static ushort[] BuildHalfAcos()
|
||||
{
|
||||
var table = new ushort[16384];
|
||||
// DLL100EDC8C..100EDCB4 truncates half of the acos angular-unit result.
|
||||
for (var i = 0; i < table.Length; i++)
|
||||
table[i] = (ushort)(Math.Acos(i * 0.0001220703125 - 1) * 2607.5945876921437 * 0.5);
|
||||
return table;
|
||||
}
|
||||
private static void RequireFinite(Vector3 vector)
|
||||
{
|
||||
if (!float.IsFinite(vector.X) || !float.IsFinite(vector.Y) || !float.IsFinite(vector.Z))
|
||||
throw new ArgumentOutOfRangeException(nameof(vector), "Finite source coordinates required");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Numerics;
|
||||
using GamePort.Assets;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>
|
||||
/// Recovered source wall-grid selection and root-support phase, with the port's
|
||||
/// provisional swept-sphere wall response. This is not the full original solver.
|
||||
/// The caller supplies body radius/factor from the actual actor class.
|
||||
/// </summary>
|
||||
public sealed class OriginalScenePhysics
|
||||
{
|
||||
private readonly SceneCollision walls;
|
||||
private readonly SupportTriangle[] support;
|
||||
|
||||
public OriginalScenePhysics(Mesh world)
|
||||
{
|
||||
if (world.CollisionPolygons.Length != world.Indices.Length / 3)
|
||||
throw new InvalidDataException("Prepare source collision polygon metadata before original root support");
|
||||
walls = new SceneCollision(world, wallsAndCeilingsOnly: true);
|
||||
support = Enumerable.Range(0, world.Indices.Length / 3)
|
||||
.Where(i => !Checkpoint(world.CollisionPolygons[i].MaterialName))
|
||||
.Select(i => new SupportTriangle(world.Vertices[world.Indices[i * 3]].Position,
|
||||
world.Vertices[world.Indices[i * 3 + 1]].Position, world.Vertices[world.Indices[i * 3 + 2]].Position,
|
||||
world.CollisionPolygons[i].ShapeId, world.CollisionPolygons[i].PolygonIndex)).ToArray();
|
||||
}
|
||||
|
||||
public SupportResult Step(Vector3 position, Vector3 velocity, float radius, float factor, bool wasGrounded, float dt)
|
||||
{
|
||||
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
|
||||
var previous = position;
|
||||
velocity += RecoveredMotion.Gravity * dt;
|
||||
// A capsule with height=diameter is a sphere. Floor polygons are handled
|
||||
// by the separate original support query, not by this wall response.
|
||||
var moved = walls.Move(position - Vector3.UnitY * radius, velocity * dt, radius, radius * 2);
|
||||
position = moved.Position + Vector3.UnitY * radius;
|
||||
if (moved.HitCeiling && velocity.Y > 0) velocity.Y = 0;
|
||||
return OriginalBodySupport.Resolve(new(position, previous, velocity, Vector3.Zero, radius, factor),
|
||||
wasGrounded, (start, end, twoSided) => OriginalBodySupport.Trace(support, start, end, twoSided));
|
||||
}
|
||||
|
||||
private static bool Checkpoint(string? name) => name != null
|
||||
&& (name.Equals("cstart", StringComparison.OrdinalIgnoreCase)
|
||||
|| name.Length == 7 && name.StartsWith("ccheck", StringComparison.OrdinalIgnoreCase) && name[6] is >= '1' and <= '9');
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>EXE404523..404D1E keyboard and pointer selection for PracticeYesNo.</summary>
|
||||
public sealed class PracticePrompt
|
||||
{
|
||||
public bool Active { get; private set; }
|
||||
public int Mode { get; private set; }
|
||||
public event Action<int, bool>? Chosen;
|
||||
|
||||
public void Show(int mode)
|
||||
{
|
||||
if (mode is < 0 or > 3) throw new NotSupportedException("Practice mode is outside recovered VR04..VR01 mapping");
|
||||
if (Active) return;
|
||||
Mode = mode; Active = true;
|
||||
}
|
||||
|
||||
public void Key(uint scancode, Vector2 pointer)
|
||||
{
|
||||
if (!Active) return;
|
||||
if (scancode == 28) Choose(true); // Y.
|
||||
else if (scancode == 17) Choose(false); // N.
|
||||
else if (scancode is 40 or 88) Choose(Yes(pointer)); // Enter / keypad Enter.
|
||||
}
|
||||
|
||||
public void Click(Vector2 pointer)
|
||||
{
|
||||
if (!Active) return;
|
||||
if (Yes(pointer)) Choose(true);
|
||||
else if (pointer.X > 315 && pointer.X < 395 && pointer.Y > 240 && pointer.Y < 300) Choose(false);
|
||||
}
|
||||
|
||||
public static string Destination(int mode) => mode switch
|
||||
{
|
||||
0 => "VR04.gam", 1 => "VR03.gam", 2 => "VR02.gam", 3 => "VR01.gam",
|
||||
_ => throw new NotSupportedException("Unrecovered practice destination")
|
||||
};
|
||||
|
||||
private void Choose(bool accepted)
|
||||
{
|
||||
Active = false;
|
||||
Chosen?.Invoke(Mode, accepted);
|
||||
}
|
||||
private static bool Yes(Vector2 p) => p.X > 225 && p.X < 305 && p.Y > 240 && p.Y < 300;
|
||||
}
|
||||
@@ -25,14 +25,22 @@ public sealed class SceneCollision
|
||||
public float DistanceSquared => Vector3.DistanceSquared(Capsule, Surface);
|
||||
}
|
||||
|
||||
public SceneCollision(Mesh mesh)
|
||||
public SceneCollision(Mesh mesh, bool wallsAndCeilingsOnly = false)
|
||||
{
|
||||
if (mesh.Indices.Length % 3 != 0) throw new ArgumentException("Collision indices must be triangles", nameof(mesh));
|
||||
if (wallsAndCeilingsOnly && mesh.CollisionPolygons.Length != mesh.Indices.Length / 3)
|
||||
throw new InvalidDataException("Original wall grid requires prepared source polygon normals");
|
||||
var result = new List<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)
|
||||
{
|
||||
// EXE4798B3 registers only stored normal.Y<.7 in the wall/ceiling
|
||||
// grid. Render normals and a recomputed cross product differ.
|
||||
if (wallsAndCeilingsOnly && mesh.CollisionPolygons[i / 3].Normal.Y >= .7f) continue;
|
||||
if (wallsAndCeilingsOnly && mesh.CollisionPolygons[i / 3].MaterialName is { } material
|
||||
&& (material.Equals("cstart", StringComparison.OrdinalIgnoreCase)
|
||||
|| material.Length == 7 && material.StartsWith("ccheck", StringComparison.OrdinalIgnoreCase) && material[6] is >= '1' and <= '9')) continue;
|
||||
if (mesh.Indices[i] >= mesh.Vertices.Length || mesh.Indices[i + 1] >= mesh.Vertices.Length
|
||||
|| mesh.Indices[i + 2] >= mesh.Vertices.Length)
|
||||
throw new ArgumentException("Collision index outside vertex table", nameof(mesh));
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
using System.Numerics;
|
||||
using GamePort.Assets;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>Mutable source-entity state for the reconstructed trigger/camera interpreter.</summary>
|
||||
public sealed class DirectorActor
|
||||
{
|
||||
public GamEntity? SourceGam { get; }
|
||||
public string Tag { get; }
|
||||
public string Kind { get; }
|
||||
public bool ConstructorCreated => SourceGam is null;
|
||||
public Vector3 Position { get; internal set; }
|
||||
public Vector3 Rotation { get; internal set; }
|
||||
public bool Visible { get; internal set; }
|
||||
public bool Active { get; internal set; }
|
||||
public string Animation { get; internal set; } = "STOP";
|
||||
public int AIstate { get; internal set; }
|
||||
public float Speed { get; internal set; }
|
||||
public string? Patrol { get; internal set; }
|
||||
public int SpriteRevision { get; internal set; }
|
||||
public bool SpritePlaying { get; internal set; }
|
||||
|
||||
internal DirectorActor(GamEntity? source, string tag, string kind, Vector3 position)
|
||||
{
|
||||
SourceGam = source; Tag = tag; Kind = kind; Position = position;
|
||||
Rotation = source?.Rotation ?? Vector3.Zero;
|
||||
Visible = source?.Integer("InitiallyVisible", -1) != 0;
|
||||
Active = source?.Integer("InitallyActive", source?.Integer("Activated", 1) ?? 1) != 0;
|
||||
if (kind == "3PIC") Visible = Active;
|
||||
AIstate = source?.Integer("AIState", kind == "3DOG" ? 4 : 0) ?? (kind == "3DOG" ? 4 : 0);
|
||||
Speed = kind switch { "3CAR" => 200, "3DOG" => 1, _ => 0 }; // EXE413BCB /41C8FA.
|
||||
if (kind == "3DOG") Animation = "none"; // Initial pose selection is not recovered; no fabricated STOP alias.
|
||||
Patrol = source?.Text("PatrolPoint");
|
||||
SpritePlaying = (source?.Integer("Activated") ?? 0) != 0;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record DirectorIssue(string Tag, string Kind, string Detail);
|
||||
|
||||
/// <summary>
|
||||
/// Recovered synchronous AI-trigger dispatch and audio-duration-driven CAM/MCA
|
||||
/// sequence. See lab-progression.md. Actor physics/AI, sprites, inventory effects
|
||||
/// and fades remain separate consumers; unsupported execution is reported.
|
||||
/// </summary>
|
||||
public sealed class SceneDirector
|
||||
{
|
||||
private readonly GamLevel level;
|
||||
private readonly TaskStates tasks;
|
||||
private readonly Func<string, int, double> soundDuration;
|
||||
private readonly Dictionary<string, GamEntity> entities = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, DirectorActor> actors = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<int, int> activations = [];
|
||||
private readonly Queue<(string Tag, string? Caller)> pending = [];
|
||||
private readonly List<DirectorIssue> issues = [];
|
||||
private readonly HashSet<string> reported = new(StringComparer.Ordinal);
|
||||
private readonly HashSet<string> patrolConsumers = new(StringComparer.OrdinalIgnoreCase);
|
||||
private Shot? shot;
|
||||
private bool draining, skipping;
|
||||
private string? blockedNext, blockedCaller;
|
||||
|
||||
private sealed class Shot(GamEntity source, int index, DirectorActor target, double duration)
|
||||
{
|
||||
public GamEntity Source { get; } = source;
|
||||
public int Index { get; } = index; // -1 for a single CAM.
|
||||
public DirectorActor Target { get; } = target;
|
||||
public double Duration { get; } = duration;
|
||||
public double Elapsed { get; set; }
|
||||
}
|
||||
|
||||
public List<DirectorActor> Actors { get; } = [];
|
||||
public IReadOnlyList<DirectorIssue> Issues => issues;
|
||||
public bool Controlled => Equal(ControlledTag, level.Player?.Tag);
|
||||
public string? ControlledTag { get; private set; }
|
||||
public bool InventoryEnabled { get; private set; } = true;
|
||||
public bool Blocked { get; private set; }
|
||||
public bool Playing => shot is not null;
|
||||
public string? CurrentTag => shot?.Source.Tag;
|
||||
public int CurrentShot => shot?.Index ?? -1;
|
||||
public Vector3? CameraEye { get; private set; }
|
||||
public Vector3? CameraTarget { get; private set; }
|
||||
public event Action<string, int>? Speech;
|
||||
public event Action<DirectorActor>? ActorChanged;
|
||||
public event Action<string, string>? Unsupported;
|
||||
|
||||
public SceneDirector(GamLevel level, TaskStates tasks, Func<string, int, double> soundDuration)
|
||||
{
|
||||
this.level = level;
|
||||
this.tasks = tasks;
|
||||
this.soundDuration = soundDuration;
|
||||
foreach (var entity in level.Entities)
|
||||
{
|
||||
if (entity.Tag is not { Length: > 0 } tag) continue;
|
||||
// Original tag lookup scans in object-list order and returns the first.
|
||||
entities.TryAdd(tag, entity);
|
||||
var actor = new DirectorActor(entity, tag, entity.Kind, entity.Position);
|
||||
Actors.Add(actor);
|
||||
actors.TryAdd(tag, actor);
|
||||
}
|
||||
// Jimmy creates Goddard in EXE423C98->41C810, independently of GAM.
|
||||
// LV1B's explicit SITGODDARD command positions him at gstart before his
|
||||
// first shot. This initial binding is a documented placement inference.
|
||||
if (!actors.ContainsKey("C3DGODDARD") && entities.TryGetValue("gstart", out var goddardStart))
|
||||
{
|
||||
var goddard = new DirectorActor(null, "C3DGODDARD", "3DOG", goddardStart.Position);
|
||||
Actors.Add(goddard);
|
||||
actors.Add(goddard.Tag, goddard);
|
||||
}
|
||||
ControlledTag = level.Player?.Tag;
|
||||
foreach (var actor in Actors) ApplyTask(actor, tasks.Get(actor.SourceGam?.Text("TaskName")));
|
||||
tasks.Assigned += OnTaskAssigned;
|
||||
}
|
||||
|
||||
public void Begin(GamEntity start)
|
||||
{
|
||||
if (start.Kind != "STRT") throw new ArgumentException("Expected original STRT entity", nameof(start));
|
||||
shot = null; pending.Clear(); activations.Clear();
|
||||
Blocked = skipping = false; blockedNext = blockedCaller = null;
|
||||
CameraEye = CameraTarget = null;
|
||||
InventoryEnabled = true;
|
||||
foreach (var actor in Actors)
|
||||
{
|
||||
if (actor.SourceGam is not { } source) continue;
|
||||
var initial = new DirectorActor(source, actor.Tag, actor.Kind, source.Position);
|
||||
actor.Position = initial.Position; actor.Rotation = initial.Rotation;
|
||||
actor.Visible = initial.Visible; actor.Active = initial.Active;
|
||||
actor.Animation = initial.Animation; actor.AIstate = initial.AIstate;
|
||||
actor.Speed = initial.Speed; actor.Patrol = initial.Patrol;
|
||||
actor.SpritePlaying = initial.SpritePlaying; actor.SpriteRevision++;
|
||||
ApplyTask(actor, tasks.Get(source.Text("TaskName")));
|
||||
}
|
||||
var trigger = start.Text("StartTrigger");
|
||||
ControlledTag = IsNone(trigger) ? level.Player?.Tag : null; // EXE4426B7.
|
||||
if (!IsNone(trigger)) Trigger(trigger!, start.Tag);
|
||||
}
|
||||
|
||||
public void Trigger(string tag, string? callerTag = null)
|
||||
{
|
||||
if (tag.Length > 100) throw new ArgumentException("Trigger tag exceeds original field size", nameof(tag));
|
||||
pending.Enqueue((tag, callerTag));
|
||||
Drain();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Port contact query: point against the source trigger radius. Original
|
||||
/// collision callback selection/radius combination is not yet reproduced.
|
||||
/// The actual AI trigger's actor, animation and task-child checks are retained.
|
||||
/// </summary>
|
||||
public void Touch(string activatorTag, Vector3 position)
|
||||
{
|
||||
if (!Finite(position)) throw new ArgumentOutOfRangeException(nameof(position));
|
||||
foreach (var entity in level.Entities)
|
||||
{
|
||||
if (entity.Kind != "3AIT" || entity.Integer("TouchActivated") == 0) continue;
|
||||
var radius = entity.Number("Radius");
|
||||
if (radius < 0 || Vector3.DistanceSquared(position, entity.Position) > radius * radius) continue;
|
||||
if (entity.Tag is { } tag) pending.Enqueue((tag, activatorTag));
|
||||
}
|
||||
Drain();
|
||||
}
|
||||
|
||||
public DirectorActor? FindActor(string tag) => actors.GetValueOrDefault(tag);
|
||||
|
||||
public void RegisterPatrolConsumer(string tag) => patrolConsumers.Add(tag);
|
||||
|
||||
public void SyncActor(string tag, Vector3 position, Vector3 rotation)
|
||||
{
|
||||
if (!Finite(position) || !Finite(rotation)) throw new ArgumentOutOfRangeException(nameof(position));
|
||||
if (!actors.TryGetValue(tag, out var actor)) return;
|
||||
actor.Position = position; actor.Rotation = rotation;
|
||||
if (shot is not null) UpdateCamera(shot);
|
||||
}
|
||||
|
||||
public void Step(float dt)
|
||||
{
|
||||
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
|
||||
foreach (var actor in Actors)
|
||||
if (actor.Kind == "3TRO") actor.Rotation = actor.Rotation with { Y = (actor.Rotation.Y + dt * 90) % 360 };
|
||||
var remaining = (double)dt;
|
||||
for (var count = 0; count < 256 && shot is not null; count++)
|
||||
{
|
||||
var current = shot;
|
||||
var untilEnd = Math.Max(0, current.Duration - current.Elapsed);
|
||||
var consumed = Math.Min(remaining, untilEnd);
|
||||
current.Elapsed += consumed;
|
||||
remaining -= consumed;
|
||||
UpdateCamera(current);
|
||||
if (current.Elapsed + 1e-8 < current.Duration) return;
|
||||
FinishShot(current);
|
||||
if (remaining <= 0 && (shot is null || shot.Duration > 0)) return;
|
||||
}
|
||||
if (shot is not null && shot.Duration <= 0)
|
||||
Block(shot.Source, "Zero-duration scene sequence exceeded bounded dispatch", shot.Source.Text("NextTrigger"));
|
||||
}
|
||||
|
||||
/// <summary>Escape/Space original chain skip: preserve AI/toggle actions and skip remaining speech/shots.</summary>
|
||||
public void Skip()
|
||||
{
|
||||
skipping = true;
|
||||
if (Blocked)
|
||||
{
|
||||
Blocked = false;
|
||||
if (blockedNext is { } next) pending.Enqueue((next, blockedCaller));
|
||||
blockedNext = blockedCaller = null;
|
||||
}
|
||||
if (shot is { } current)
|
||||
{
|
||||
shot = null;
|
||||
DeactivateAnimation(current);
|
||||
if (current.Index >= 0) FinishMulti(current.Source);
|
||||
else EnqueueNext(current.Source);
|
||||
}
|
||||
Drain();
|
||||
}
|
||||
|
||||
private void Drain()
|
||||
{
|
||||
if (draining || Blocked) return;
|
||||
draining = true;
|
||||
var visited = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
try
|
||||
{
|
||||
for (var count = 0; pending.Count > 0 && !Blocked; count++)
|
||||
{
|
||||
var (tag, caller) = pending.Dequeue();
|
||||
if (IsNone(tag)) continue;
|
||||
if (Equal(tag, "default")) { RestoreControl(); continue; }
|
||||
if (count >= 256 || !visited.Add(tag))
|
||||
{
|
||||
Report(tag, "cycle", "Synchronous trigger cycle or dispatch limit");
|
||||
pending.Clear(); Blocked = true; return;
|
||||
}
|
||||
if (!entities.TryGetValue(tag, out var entity))
|
||||
{
|
||||
Report(tag, "missing", "Trigger target absent from original GAM");
|
||||
Blocked = true; return;
|
||||
}
|
||||
switch (entity.Kind)
|
||||
{
|
||||
case "3AIT": ExecuteAi(entity, caller); break;
|
||||
case "3CAM": StartCamera(entity, -1); break;
|
||||
case "3MCA": StartMulti(entity); break;
|
||||
default: Block(entity, "Trigger class execution not recovered", entity.Text("NextTrigger")); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally { draining = false; }
|
||||
}
|
||||
|
||||
private void ExecuteAi(GamEntity entity, string? caller)
|
||||
{
|
||||
var by = entity.Text("ActivateBy");
|
||||
var isA = entity.Text("IsA");
|
||||
var matchesActor = !IsNone(by) && Equal(by, caller);
|
||||
if (!IsNone(isA))
|
||||
{
|
||||
Report(entity.Tag!, entity.Kind, "IsA predicate requires original class hierarchy; trigger not executed");
|
||||
return;
|
||||
}
|
||||
if (!IsNone(by) && !matchesActor) return;
|
||||
var byAnimation = entity.Text("ActivateByAnim");
|
||||
if (!IsNone(byAnimation) && (!actors.TryGetValue(caller ?? "", out var callerActor)
|
||||
|| !Equal(byAnimation, callerActor.Animation))) return;
|
||||
var times = entity.Integer("TimesToTrigger", -1);
|
||||
var number = activations.GetValueOrDefault(entity.Offset) + 1;
|
||||
activations[entity.Offset] = number;
|
||||
if (times != -1 && number > times) return;
|
||||
SetControl(entity);
|
||||
|
||||
var targetTag = entity.Text("AITarget");
|
||||
if (!IsNone(targetTag))
|
||||
{
|
||||
if (!actors.TryGetValue(targetTag!, out var target))
|
||||
Report(entity.Tag!, entity.Kind, $"AI target {targetTag} absent");
|
||||
else
|
||||
{
|
||||
var hide = entity.Integer("AIHideObj", -1);
|
||||
if (hide != -1) target.Visible = hide == 0;
|
||||
var positionTag = entity.Text("AINewPos");
|
||||
if (!IsNone(positionTag))
|
||||
{
|
||||
if (actors.TryGetValue(positionTag!, out var marker)) target.Position = marker.Position;
|
||||
else Report(entity.Tag!, entity.Kind, $"AINewPos {positionTag} absent");
|
||||
}
|
||||
var animation = entity.Text("AIAnim");
|
||||
if (!IsNone(animation)) target.Animation = animation!;
|
||||
target.AIstate = entity.Integer("AIState", target.AIstate);
|
||||
var speed = entity.Integer("AISpeed", -1);
|
||||
if (speed != -1) target.Speed = speed;
|
||||
var patrol = entity.Text("AIPatrol");
|
||||
if (!IsNone(patrol)) target.Patrol = patrol;
|
||||
var yaw = entity.Number("AINewRotY", -1);
|
||||
if (yaw != -1) target.Rotation = target.Rotation with { Y = yaw };
|
||||
ActorChanged?.Invoke(target);
|
||||
if (target.AIstate == 3 && (target.Kind is "3DOG" or "3CAR") && !patrolConsumers.Contains(target.Tag))
|
||||
Report(target.Tag, target.Kind, "Patrol motion/arrival is not yet reconstructed; actor-state callback emitted");
|
||||
}
|
||||
}
|
||||
Toggle(entity);
|
||||
var conditional = ConditionalChild(entity);
|
||||
// EXE40CB43: the nearby teleport explanation advances the task before its camera chain.
|
||||
if (Equal(entity.Tag, "teleportexplanation") && tasks.Get("SCENE") is 30 or 31)
|
||||
tasks.SetExisting("SCENE", 35);
|
||||
pending.Enqueue((conditional ?? entity.Text("NextTrigger") ?? "none", entity.Tag));
|
||||
}
|
||||
|
||||
private string? ConditionalChild(GamEntity entity)
|
||||
{
|
||||
var state = tasks.Get(entity.Text("TaskName"));
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
var desired = entity.Integer($"ActivateState{i}", -1);
|
||||
var target = entity.Text($"ActivateObject{i}");
|
||||
if (desired != -1 && desired == state && !IsNone(target) && entities.ContainsKey(target!)) return target;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void StartMulti(GamEntity entity)
|
||||
{
|
||||
SetControl(entity);
|
||||
Toggle(entity);
|
||||
if (skipping) { FinishMulti(entity); return; }
|
||||
StartCamera(entity, 0, applyCommon: false);
|
||||
}
|
||||
|
||||
private void StartCamera(GamEntity entity, int index, bool applyCommon = true)
|
||||
{
|
||||
if (applyCommon) { SetControl(entity); Toggle(entity); }
|
||||
if (entity.Integer("DeactivateInv") != 0) InventoryEnabled = false;
|
||||
if (skipping)
|
||||
{
|
||||
if (index >= 0) FinishMulti(entity);
|
||||
else EnqueueNext(entity);
|
||||
return;
|
||||
}
|
||||
var suffix = index < 0 ? "" : index.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
var targetTag = entity.Text("CameraTarget" + suffix);
|
||||
var sound = entity.Integer("SoundIndex" + suffix, -1);
|
||||
if (index >= 8 || IsNone(targetTag) || sound == -1)
|
||||
{
|
||||
if (index >= 0) FinishMulti(entity);
|
||||
else Block(entity, "CAM target/sound unavailable", entity.Text("NextTrigger"));
|
||||
return;
|
||||
}
|
||||
if (!actors.TryGetValue(targetTag!, out var target))
|
||||
{
|
||||
Block(entity, $"Camera target {targetTag} absent", entity.Text("NextTrigger"));
|
||||
return;
|
||||
}
|
||||
var database = entity.Text("SoundDatabase") ?? "none";
|
||||
var duration = soundDuration(database, sound);
|
||||
if (!double.IsFinite(duration) || duration < 0)
|
||||
{
|
||||
Block(entity, $"Missing original sound duration {database}:{sound}", entity.Text("NextTrigger"));
|
||||
return;
|
||||
}
|
||||
var animation = entity.Text(index < 0 ? "TargetActAnim" : "TargetAnim" + suffix);
|
||||
if (!IsNone(animation)) { target.Animation = animation!; ActorChanged?.Invoke(target); }
|
||||
shot = new Shot(entity, index, target, duration);
|
||||
UpdateCamera(shot);
|
||||
Speech?.Invoke(database, sound);
|
||||
}
|
||||
|
||||
private void FinishShot(Shot current)
|
||||
{
|
||||
if (shot != current) return;
|
||||
shot = null;
|
||||
DeactivateAnimation(current);
|
||||
if (current.Index < 0) EnqueueNext(current.Source);
|
||||
else StartCamera(current.Source, current.Index + 1, applyCommon: false);
|
||||
Drain();
|
||||
}
|
||||
|
||||
private void DeactivateAnimation(Shot current)
|
||||
{
|
||||
var animation = current.Source.Text("TargetDeactAnim");
|
||||
if (!IsNone(animation))
|
||||
{
|
||||
current.Target.Animation = animation!;
|
||||
ActorChanged?.Invoke(current.Target);
|
||||
}
|
||||
}
|
||||
|
||||
private void FinishMulti(GamEntity entity)
|
||||
{
|
||||
// MCA finisher4311F0 preserves 'none'/NULL semantics for PlayerControlled.
|
||||
SetControl(entity);
|
||||
EnqueueNext(entity);
|
||||
}
|
||||
|
||||
private void EnqueueNext(GamEntity entity)
|
||||
{
|
||||
pending.Enqueue((entity.Text("NextTrigger") ?? "none", entity.Tag));
|
||||
}
|
||||
|
||||
private void UpdateCamera(Shot current)
|
||||
{
|
||||
var source = current.Source;
|
||||
var target = current.Target;
|
||||
var t = (float)current.Elapsed;
|
||||
if (current.Index >= 0)
|
||||
{
|
||||
var suffix = current.Index.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
var type = source.Integer("CameraType" + suffix);
|
||||
var local = type switch
|
||||
{
|
||||
1 => new Vector3(0, 140, MathF.Max(100, 300 - 15 * t)),
|
||||
2 => new Vector3(0, 240, MathF.Max(100, 500 - 35 * t)),
|
||||
3 => new Vector3(200, 240, MathF.Max(100, 700 - 55 * t)),
|
||||
4 => new Vector3(-200, 190, MathF.Max(100, 700 - 55 * t)),
|
||||
_ => new Vector3(0, 40, 200),
|
||||
};
|
||||
CameraEye = TransformLocal(target, local);
|
||||
CameraTarget = target.Position + Vector3.UnitY * (source.Number("LookatVOffset" + suffix, 100) - 60);
|
||||
return;
|
||||
}
|
||||
if (source.Integer("CameraType") == 2)
|
||||
{
|
||||
CameraEye = source.Position;
|
||||
CameraTarget = target.Position;
|
||||
return;
|
||||
}
|
||||
var minimum = source.Number("MinDist", 100);
|
||||
var maximum = source.Number("MaxDist", 1000);
|
||||
var distance = Math.Clamp(source.Number("InitialDist", 200) - source.Number("ZoomSpeed") * t,
|
||||
MathF.Min(minimum, maximum), MathF.Max(minimum, maximum));
|
||||
var offset = new Vector3(source.Number("TargOffsetX"), source.Number("TargOffsetY"), source.Number("TargOffsetZ"));
|
||||
if (source.Integer("ViewFromCamera") == 0)
|
||||
{
|
||||
CameraEye = TransformLocal(target, offset with { Z = distance });
|
||||
CameraTarget = target.Position + Vector3.UnitY * source.Number("LookVoffset");
|
||||
}
|
||||
else
|
||||
{
|
||||
var point = TransformLocal(target, offset);
|
||||
var direction = source.Position - point;
|
||||
if (direction.LengthSquared() < .000001f)
|
||||
{
|
||||
Report(source.Tag!, source.Kind, "CAM eye coincides with target offset; original normalization undefined");
|
||||
CameraEye = source.Position;
|
||||
}
|
||||
else CameraEye = point + Vector3.Normalize(direction) * distance;
|
||||
CameraTarget = point;
|
||||
}
|
||||
}
|
||||
|
||||
private static Vector3 TransformLocal(DirectorActor target, Vector3 point)
|
||||
{
|
||||
// Original OMT Euler local-to-world routine472980; quantized modern
|
||||
// sin/cos here retains the source angular grid, not x87 bit identity.
|
||||
var (sx, cx) = LabSimulation.Trig(target.Rotation.X);
|
||||
var (sy, cy) = LabSimulation.Trig(target.Rotation.Y);
|
||||
var (sz, cz) = LabSimulation.Trig(target.Rotation.Z);
|
||||
var x = point.X * cz - point.Y * sz;
|
||||
var y = point.X * sz + point.Y * cz;
|
||||
var z = point.Z;
|
||||
var pitchedY = y * cx - z * sx;
|
||||
var pitchedZ = y * sx + z * cx;
|
||||
return target.Position + new Vector3(x * cy - pitchedZ * sy, pitchedY, x * sy + pitchedZ * cy);
|
||||
}
|
||||
|
||||
private void SetControl(GamEntity entity)
|
||||
{
|
||||
var control = entity.Text("PlayerControlled");
|
||||
if (IsNone(control)) return;
|
||||
if (Equal(control, "NULL")) ControlledTag = null;
|
||||
else if (actors.ContainsKey(control!)) ControlledTag = control;
|
||||
else Report(entity.Tag!, entity.Kind, $"PlayerControlled target {control} absent");
|
||||
}
|
||||
|
||||
private void Toggle(GamEntity entity)
|
||||
{
|
||||
var tag = entity.Text("ToggleObject");
|
||||
var toggle = entity.Integer("Toggle", -1);
|
||||
if (toggle is not (0 or 1) || IsNone(tag)) return;
|
||||
if (!actors.TryGetValue(tag!, out var actor)) { Report(entity.Tag!, entity.Kind, $"ToggleObject {tag} absent"); return; }
|
||||
actor.Visible = actor.Active = toggle == 1;
|
||||
if (actor.Kind == "3ANI") { actor.SpritePlaying = toggle == 1; actor.SpriteRevision++; }
|
||||
ActorChanged?.Invoke(actor);
|
||||
}
|
||||
|
||||
private void RestoreControl()
|
||||
{
|
||||
shot = null;
|
||||
ControlledTag = level.Player?.Tag;
|
||||
InventoryEnabled = true;
|
||||
CameraEye = CameraTarget = null;
|
||||
skipping = false;
|
||||
// Original DEFAULT invokes a Jimmy help/inventory callback at SCENE30;
|
||||
// it does not assign a new task value or complete the lab.
|
||||
}
|
||||
|
||||
private void OnTaskAssigned(string name, int state)
|
||||
{
|
||||
foreach (var actor in Actors)
|
||||
if (Equal(actor.SourceGam?.Text("TaskName"), name)) ApplyTask(actor, state);
|
||||
}
|
||||
|
||||
private void ApplyTask(DirectorActor actor, int state)
|
||||
{
|
||||
if (actor.SourceGam is not { } source) return;
|
||||
// LOAD.RequiredLevel belongs to its RequiredTask contact gate, not the
|
||||
// animated actor's TaskName activation contract. Applying the latter
|
||||
// here disables the lab exit even when SCENE reaches60.
|
||||
if (source.Kind == "LOAD") return;
|
||||
var active = source.Kind == "3PIC" ? TaskActivation.Pickup(source, state) : TaskActivation.Animated(source, state);
|
||||
if (active.HasValue) { actor.Active = actor.Visible = active.Value; ActorChanged?.Invoke(actor); }
|
||||
}
|
||||
|
||||
private void Block(GamEntity source, string detail, string? next)
|
||||
{
|
||||
shot = null; Blocked = true;
|
||||
blockedNext = next; blockedCaller = source.Tag;
|
||||
Report(source.Tag ?? "?", source.Kind, detail);
|
||||
}
|
||||
|
||||
private void Report(string tag, string kind, string detail)
|
||||
{
|
||||
if (!reported.Add(tag + "\0" + kind + "\0" + detail)) return;
|
||||
issues.Add(new DirectorIssue(tag, kind, detail));
|
||||
Unsupported?.Invoke(tag, kind);
|
||||
}
|
||||
private static bool Equal(string? a, string? b) => a is not null && b is not null && string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
|
||||
private static bool IsNone(string? value) => string.IsNullOrEmpty(value) || Equal(value, "none");
|
||||
private static bool Finite(Vector3 p) => float.IsFinite(p.X) && float.IsFinite(p.Y) && float.IsFinite(p.Z);
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
using System.Numerics;
|
||||
using GamePort.Assets;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
public sealed record LevelTransition(string LevelFile, string StartPoint, float FadeTime, int FadeType);
|
||||
|
||||
/// <summary>
|
||||
/// Recovered star/trophy/lab jetpack contacts, Carl talk dispatch and LOAD gates. Uses source root spheres
|
||||
/// with recovered lookup magnitude (x87 table identity/exclusions/box contacts pending).
|
||||
/// Other pickup effects and general AI sensing remain explicit unsupported cases.
|
||||
/// </summary>
|
||||
public sealed class SceneInteractions
|
||||
{
|
||||
private readonly SceneDirector director;
|
||||
private readonly TaskStates tasks;
|
||||
private readonly OriginalSave initial;
|
||||
private readonly string levelCode;
|
||||
private readonly int[] itemStates;
|
||||
private readonly HashSet<int> contacts = [];
|
||||
private readonly HashSet<string> unsupported = [];
|
||||
public int Score { get; private set; }
|
||||
public float Energy { get; private set; }
|
||||
public int CurrentObjective { get; private set; }
|
||||
public string ReturnLevel { get; private set; }
|
||||
public string ReturnStart { get; private set; }
|
||||
public SceneInventory Inventory { get; }
|
||||
public IReadOnlyCollection<string> Unsupported => unsupported;
|
||||
public event Action<GamEntity, int>? Collected;
|
||||
public event Action<LevelTransition>? Transition;
|
||||
public event Action<int>? SoundEffect;
|
||||
public event Action<int>? PracticeRequested;
|
||||
public event Action<Vector3>? CheckpointCaptured;
|
||||
public event Action<DirectorActor, string>? ConversationStarted;
|
||||
public event Action<int>? ObjectiveChanged;
|
||||
|
||||
public SceneInteractions(SceneDirector director, TaskStates tasks, OriginalSave save, string? levelCode = null)
|
||||
{
|
||||
this.director = director; this.tasks = tasks; initial = save;
|
||||
this.levelCode = levelCode ?? save.LevelCode;
|
||||
Inventory = new SceneInventory(save.InventoryStates);
|
||||
itemStates = save.ItemStates.ToArray(); Score = save.Score;
|
||||
Energy = save.PlayerValue;
|
||||
CurrentObjective = save.OtherCounter;
|
||||
ReturnLevel = save.ReturnLevel; ReturnStart = save.ReturnStart;
|
||||
tasks.Assigned += OnTaskAssigned;
|
||||
Reset();
|
||||
}
|
||||
public void UpdateEnergy(float energy)
|
||||
{
|
||||
if (!float.IsFinite(energy)) throw new ArgumentOutOfRangeException(nameof(energy));
|
||||
Energy = energy;
|
||||
}
|
||||
|
||||
public OriginalSave Snapshot() => initial with { Score = Score, PlayerValue = Energy, ItemStates = itemStates.ToArray(),
|
||||
InventoryStates = Inventory.Snapshot(), Tasks = tasks.Snapshot(), OtherCounter = CurrentObjective,
|
||||
ReturnLevel = ReturnLevel, ReturnStart = ReturnStart };
|
||||
|
||||
public void SetReturnContext(string levelFile, string start)
|
||||
{
|
||||
if (levelFile.Length > 100 || start.Length > 100 || !levelFile.EndsWith(".gam", StringComparison.OrdinalIgnoreCase)
|
||||
|| levelFile.Contains('/') || levelFile.Contains('\\')) throw new ArgumentException("Invalid original return level/start");
|
||||
ReturnLevel = levelFile; ReturnStart = start;
|
||||
}
|
||||
|
||||
/// <summary>Call after SceneDirector.Begin, including a scene reset.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
contacts.Clear();
|
||||
HideCollected();
|
||||
ApplyCarlTask();
|
||||
}
|
||||
|
||||
public void HideCollected()
|
||||
{
|
||||
foreach (var actor in director.Actors)
|
||||
if (actor.SourceGam is { Kind: "3PIC" } source && source.Integer("PickupIndex", -1) is var id
|
||||
&& id > 0 && id < itemStates.Length && itemStates[id] != 0) actor.Active = actor.Visible = false;
|
||||
}
|
||||
|
||||
public void Update(Vector3 activePlayerRoot, float playerRadius = 60)
|
||||
{
|
||||
if (!float.IsFinite(activePlayerRoot.X + activePlayerRoot.Y + activePlayerRoot.Z)
|
||||
|| !float.IsFinite(playerRadius) || playerRadius < 0) throw new ArgumentOutOfRangeException(nameof(activePlayerRoot));
|
||||
if (!director.Controlled) return;
|
||||
HideCollected();
|
||||
foreach (var actor in director.Actors)
|
||||
{
|
||||
if (!director.Controlled) break;
|
||||
if (actor.SourceGam is not { } source || source.Kind is not ("3PIC" or "3TRO" or "LOAD" or "3CAR")) continue;
|
||||
// C3DFriend update41B972..988 calls the talk dispatcher every update
|
||||
// in state0, even when a prior contact found no matching TalkTrigger.
|
||||
if (source.Kind == "3CAR" && actor.Active && actor.AIstate == 0)
|
||||
{
|
||||
TryBeginCarlTalk(actor, source);
|
||||
if (!director.Controlled) break;
|
||||
}
|
||||
// Carl InitObject413E2F..45 sets radius100 and support factor0.75.
|
||||
var radius = playerRadius + (source.Kind == "3TRO" ? 20 : source.Kind == "3CAR" ? 100 : source.Number("Radius"));
|
||||
var overlaps = actor.Active && OriginalBodySupport.QuickMagnitude(activePlayerRoot - actor.Position) < radius;
|
||||
if (!overlaps) { contacts.Remove(source.Offset); continue; }
|
||||
if (!contacts.Add(source.Offset)) continue;
|
||||
switch (source.Kind)
|
||||
{
|
||||
case "3PIC": CollectPickup(actor, source, activePlayerRoot); break;
|
||||
case "3CAR":
|
||||
//40A44C..45C/40A676..68D: target contact in state6 sets0.
|
||||
var player = director.Actors.FirstOrDefault(a => a.Kind == "3JIM");
|
||||
if (actor.AIstate == 6 && Equal(source.Text("TargetName"), player?.Tag))
|
||||
{
|
||||
actor.AIstate = 0;
|
||||
TryBeginCarlTalk(actor, source);
|
||||
}
|
||||
break;
|
||||
case "3TRO":
|
||||
Score = Math.Max(0, unchecked(Score + 300));
|
||||
actor.Active = actor.Visible = false;
|
||||
SoundEffect?.Invoke(230);
|
||||
Collected?.Invoke(source, 300);
|
||||
break;
|
||||
case "LOAD":
|
||||
if (!TaskActivation.Load(source, tasks)) break;
|
||||
var destination = source.Text("LevelName") ?? "none";
|
||||
var start = source.Text("StartPoint") ?? "none";
|
||||
if (string.Equals(destination, "RETURN", StringComparison.OrdinalIgnoreCase))
|
||||
{ destination = ReturnLevel; start = ReturnStart; }
|
||||
if (string.Equals(destination, "none", StringComparison.OrdinalIgnoreCase))
|
||||
{ unsupported.Add("RETURN has no stored destination"); break; }
|
||||
Transition?.Invoke(new(destination, start, source.Number("FadeTime"), source.Integer("FadeType")));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CollectPickup(DirectorActor actor, GamEntity source, Vector3 playerRoot)
|
||||
{
|
||||
var id = source.Integer("PickupIndex", -1);
|
||||
// The source tag is SHRINKRAY; original objective art120 calls this
|
||||
// pickup the jet pack, matching group0/item3 and powered-jump ownership.
|
||||
var jetpack = Equal(source.Tag, "SHRINKRAY");
|
||||
var ordinaryStar = id is >= 3000 and < 4000 && source.Integer("PointValue") == 5;
|
||||
if (id is <= 0 or >= OriginalSave.ItemCount || !(ordinaryStar || jetpack && source.Integer("PointValue") == 50)
|
||||
|| source.Integer("PIC_NUMBER", -1) != -1
|
||||
|| source.Integer("PickedUpIndex", -1) != -1 || source.Integer("RequiredPicNum", -1) != -1)
|
||||
{ unsupported.Add($"Pickup {source.Tag}@0x{source.Offset:X}: inventory/special effect not reconstructed"); return; }
|
||||
if (itemStates[id] != 0) return;
|
||||
itemStates[id] = 1; // EXE435E11..31: ordinary acquired state, hide and disable.
|
||||
actor.Active = actor.Visible = false;
|
||||
//435FCB invokes the special hook before the positive PointValue award.
|
||||
if (jetpack && tasks.Get("SCENE") == 35)
|
||||
{
|
||||
//436603..67E: Jimmy checkpoint capture42AF00, task35->50, group0
|
||||
//item3 state1, practice prompt0, then gadget selection3. The checkpoint
|
||||
//event does not assign the still-unidentified TSK StoredVector.
|
||||
CheckpointCaptured?.Invoke(playerRoot);
|
||||
tasks.SetExisting("SCENE", 50);
|
||||
Inventory.SetState(0, 3, 1);
|
||||
PracticeRequested?.Invoke(0);
|
||||
Inventory.SelectGadget(3);
|
||||
}
|
||||
var points = source.Integer("PointValue");
|
||||
Score = Math.Max(0, unchecked(Score + points));
|
||||
var sound = source.Integer("SoundIndex", -1);
|
||||
if (sound >= 0) SoundEffect?.Invoke(sound);
|
||||
Collected?.Invoke(source, points);
|
||||
var next = source.Text("NextTrigger");
|
||||
if (!string.IsNullOrEmpty(next) && !string.Equals(next, "none", StringComparison.OrdinalIgnoreCase))
|
||||
director.Trigger(next, source.Tag);
|
||||
}
|
||||
|
||||
private void TryBeginCarlTalk(DirectorActor actor, GamEntity source)
|
||||
{
|
||||
var state = tasks.Get(source.Text("TaskName"));
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
var tag = source.Text("TalkTrigger" + i);
|
||||
var required = source.Integer("TalkState" + i, -1);
|
||||
if (required == -1 || required != state && required != -2 || string.IsNullOrEmpty(tag)
|
||||
|| Equal(tag, "none") || director.FindActor(tag) is null) continue;
|
||||
//41B7B0 calls derived slot180 BEFORE dispatching the selected object.
|
||||
//Carl413E50 calls base41B810 (+100) then changes SCENE milestones.
|
||||
Score = Math.Max(0, unchecked(Score + 100));
|
||||
var scene = tasks.Get("SCENE");
|
||||
var next = scene switch { 50 => 60, 65 => 70, 270 => 280, _ => scene };
|
||||
if (next != scene) tasks.SetExisting("SCENE", next);
|
||||
director.Trigger(tag, tag); //Original target receives itself as caller.
|
||||
actor.AIstate = 9;
|
||||
ConversationStarted?.Invoke(actor, tag);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnTaskAssigned(string name, int value)
|
||||
{
|
||||
HideCollected();
|
||||
if (Equal(name, "SCENE"))
|
||||
{
|
||||
//45F990 jump tables ->406F50: clear the transient objective flags,
|
||||
//select this objective and set its flag1; TSK writes selector4F8194.
|
||||
var objective = ObjectiveForScene(value);
|
||||
if (objective != 0) { CurrentObjective = objective; ObjectiveChanged?.Invoke(objective); }
|
||||
ApplyCarlTask();
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyCarlTask()
|
||||
{
|
||||
//Carl's override413F30 follows generic activation; LV1B branch414068.
|
||||
//Other levels' custom visibility/position policies are not ported here.
|
||||
if (levelCode != "LV1B") return;
|
||||
var state = tasks.Get("SCENE");
|
||||
foreach (var actor in director.Actors.Where(a => a.Kind == "3CAR" && Equal(a.SourceGam?.Text("TaskName"), "SCENE")))
|
||||
{
|
||||
if (state is < 0 or > 60) { actor.Visible = actor.Active = false; continue; }
|
||||
if (state > 30 && director.FindActor("CARLESC3") is { } marker)
|
||||
{
|
||||
actor.AIstate = 6;
|
||||
actor.Position = marker.Position;
|
||||
}
|
||||
//At60 the override leaves the generic activation result unchanged.
|
||||
if (state < 60) actor.Active = actor.Visible = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Equal(string? a, string? b) => a is not null && b is not null
|
||||
&& string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public static int ObjectiveForScene(int scene) => scene switch
|
||||
{
|
||||
35 => 1, 50 => 2, 60 => 3, 70 => 4, 90 => 5, 100 => 6, 108 => 7,
|
||||
140 or 141 => 8, 160 => 9, 162 => 10, 168 => 11, 178 => 12,
|
||||
200 => 13, 205 => 14, 210 => 15, 220 => 16, 230 => 17,
|
||||
250 => 18, 260 => 19, 270 => 20, 280 => 21, 290 => 22,
|
||||
300 => 23, 310 => 24, 320 => 25, 330 => 26, 340 => 27,
|
||||
350 => 28, 360 => 29, 380 => 30, 390 => 31, 400 => 32,
|
||||
410 => 33, 420 => 34, 430 => 35, 460 => 36, 470 => 37,
|
||||
480 => 38, 500 => 39, 510 => 40, 520 => 41, 540 => 42, 550 => 43,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using GamePort.Assets;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>
|
||||
/// The two inventory-state groups serialized by the original TSK writer.
|
||||
/// Preserves unknown existing values; this is not a complete inventory UI or
|
||||
/// implementation of the separate 29-item consumable-count group.
|
||||
/// </summary>
|
||||
public sealed class SceneInventory
|
||||
{
|
||||
private readonly int[] states;
|
||||
public int SelectedGadget { get; private set; } = -1;
|
||||
public event Action<int>? GadgetSelected;
|
||||
|
||||
public SceneInventory(IEnumerable<int> savedStates)
|
||||
{
|
||||
states = savedStates.ToArray();
|
||||
if (states.Length != OriginalSave.InventoryCount)
|
||||
throw new ArgumentException("Expected the original 19 inventory states", nameof(savedStates));
|
||||
}
|
||||
|
||||
public int State(int group, int item) => states[Offset(group, item)];
|
||||
|
||||
public void SetState(int group, int item, int state) => states[Offset(group, item)] = state;
|
||||
|
||||
public void SelectGadget(int item)
|
||||
{
|
||||
if (item != -1 && (item is < 0 or >= 9 || State(0, item) == 0))
|
||||
throw new ArgumentOutOfRangeException(nameof(item), "Gadget is outside the recovered group or unavailable");
|
||||
SelectedGadget = item;
|
||||
GadgetSelected?.Invoke(item);
|
||||
}
|
||||
|
||||
public int[] Snapshot() => states.ToArray();
|
||||
|
||||
private static int Offset(int group, int item) => group switch
|
||||
{
|
||||
0 when item is >= 0 and < 9 => item,
|
||||
1 when item is >= 0 and < 10 => 9 + item,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(item), "Only the two serialized inventory groups are recovered here"),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>
|
||||
/// Recovered player-contact button and vertical-door state machines. Contact
|
||||
/// broadphase uses the recovered lookup magnitude; moving-object collision and material pulses
|
||||
/// are separate, still incomplete consumers. See analysis/buttons-doors.md.
|
||||
/// </summary>
|
||||
public sealed class SceneMechanisms
|
||||
{
|
||||
private sealed class Button(DirectorActor actor)
|
||||
{
|
||||
public DirectorActor Actor = actor;
|
||||
public bool Available;
|
||||
public bool Down;
|
||||
public float Cooldown;
|
||||
}
|
||||
private sealed class Door(DirectorActor actor)
|
||||
{
|
||||
public DirectorActor Actor = actor;
|
||||
public Vector3 Origin = actor.SourceGam!.Position;
|
||||
public bool Closed;
|
||||
public float Remaining;
|
||||
public float OpenElapsed;
|
||||
public bool Looping;
|
||||
public float Duration = actor.SourceGam!.Number("DoorSpeed", 1);
|
||||
public float OpenTime = actor.SourceGam!.Number("OpenTime", 3);
|
||||
public float Amount = actor.SourceGam!.Number("OpenAmount", 500);
|
||||
}
|
||||
private readonly SceneDirector director;
|
||||
private readonly List<Button> buttons;
|
||||
private readonly List<Door> doors;
|
||||
private readonly HashSet<int> contacts = [];
|
||||
private readonly HashSet<string> unsupported = [];
|
||||
|
||||
public IReadOnlyCollection<string> Unsupported => unsupported;
|
||||
public event Action<DirectorActor, int, bool>? Sound; // Source bank index and loop flag.
|
||||
public event Action<DirectorActor>? StopSound;
|
||||
|
||||
public SceneMechanisms(SceneDirector director)
|
||||
{
|
||||
this.director = director;
|
||||
buttons = director.Actors.Where(a => a.Kind == "3BUT" && a.SourceGam != null).Select(a => new Button(a)).ToList();
|
||||
doors = director.Actors.Where(a => a.Kind == "3DUD" && a.SourceGam != null).Select(a => new Door(a)).ToList();
|
||||
foreach (var door in doors)
|
||||
if (!float.IsFinite(door.Duration) || door.Duration <= 0 || !float.IsFinite(door.Amount)
|
||||
|| !float.IsFinite(door.OpenTime)) throw new InvalidDataException("Invalid source door timing or displacement");
|
||||
Reset();
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
contacts.Clear();
|
||||
foreach (var button in buttons) ResetButton(button);
|
||||
foreach (var door in doors)
|
||||
{
|
||||
if (door.Looping) StopSound?.Invoke(door.Actor);
|
||||
door.Closed = door.Actor.SourceGam!.Integer("ItemClosed", 1) != 0;
|
||||
door.Remaining = door.OpenElapsed = 0;
|
||||
door.Looping = false;
|
||||
door.Actor.Position = door.Origin + (door.Closed ? Vector3.Zero : Vector3.UnitY * door.Amount);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Player contact-enter only; holding overlap never presses repeatedly.</summary>
|
||||
public void Update(Vector3 root, float radius = 60)
|
||||
{
|
||||
if (!Finite(root) || !float.IsFinite(radius) || radius < 0) throw new ArgumentOutOfRangeException(nameof(root));
|
||||
foreach (var button in buttons)
|
||||
{
|
||||
var source = button.Actor.SourceGam!;
|
||||
// EXE411EF0 PostLoad sets current radius300 after InitObject.
|
||||
var overlap = button.Actor.Active && OriginalBodySupport.QuickMagnitude(root - button.Actor.Position) < radius + 300;
|
||||
if (!overlap) { contacts.Remove(source.Offset); continue; }
|
||||
if (contacts.Add(source.Offset)) Press(button);
|
||||
}
|
||||
}
|
||||
|
||||
public bool Toggle(DirectorActor actor, int requested)
|
||||
{
|
||||
var door = doors.Find(d => ReferenceEquals(d.Actor, actor));
|
||||
if (door == null) return false;
|
||||
var current = door.Closed ? 1 : 0;
|
||||
if (current == requested) return true;
|
||||
door.Remaining = door.Remaining > 0 ? door.Duration - door.Remaining : door.Duration;
|
||||
if (!door.Looping)
|
||||
{
|
||||
door.Looping = true;
|
||||
Sound?.Invoke(actor, 59, true);
|
||||
}
|
||||
var next = actor.SourceGam!.Text("Next");
|
||||
if (!string.IsNullOrEmpty(next) && !Equal(next, "none"))
|
||||
{
|
||||
var target = director.FindActor(next);
|
||||
if (target?.Kind == "3AIT") director.Trigger(next, actor.Tag);
|
||||
else unsupported.Add($"Door {actor.Tag}: chained target {next} class execution is unrecovered");
|
||||
}
|
||||
door.Closed = requested switch { 0 => false, 1 => true, _ => !door.Closed };
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Step(float dt)
|
||||
{
|
||||
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
|
||||
foreach (var button in buttons)
|
||||
{
|
||||
if (!button.Actor.Active || button.Cooldown <= 0) continue;
|
||||
button.Cooldown -= dt;
|
||||
if (button.Cooldown <= 0) ResetButton(button);
|
||||
}
|
||||
foreach (var door in doors)
|
||||
{
|
||||
if (!door.Actor.Active) continue;
|
||||
if (door.Remaining > 0)
|
||||
{
|
||||
door.Remaining -= dt;
|
||||
if (door.Remaining <= 0)
|
||||
{
|
||||
door.Remaining = 0;
|
||||
door.Looping = false;
|
||||
StopSound?.Invoke(door.Actor);
|
||||
Sound?.Invoke(door.Actor, 58, false);
|
||||
}
|
||||
var fraction = door.Remaining / door.Duration;
|
||||
if (!door.Closed) door.OpenElapsed = 0;
|
||||
door.Actor.Position = door.Origin + Vector3.UnitY * door.Amount * (door.Closed ? fraction : 1 - fraction);
|
||||
}
|
||||
else if (!door.Closed)
|
||||
{
|
||||
door.OpenElapsed += dt;
|
||||
if (door.OpenElapsed > door.OpenTime)
|
||||
{
|
||||
door.OpenElapsed = 0;
|
||||
Toggle(door.Actor, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Press(Button button)
|
||||
{
|
||||
if (!button.Available || button.Cooldown > 0) return;
|
||||
if (!button.Down)
|
||||
{
|
||||
button.Cooldown = 4; // EXE411C35.
|
||||
var sound = button.Actor.SourceGam!.Integer("AvailSound", -1);
|
||||
if (sound != -1) Sound?.Invoke(button.Actor, sound, false);
|
||||
}
|
||||
button.Down = !button.Down;
|
||||
button.Actor.Animation = button.Down ? "DOWN" : "UP";
|
||||
var targetName = button.Actor.SourceGam!.Text("ActivateButton");
|
||||
if (string.IsNullOrEmpty(targetName) || Equal(targetName, "none")) return;
|
||||
var target = director.FindActor(targetName);
|
||||
if (target == null) return; // Original missing-tag lookup quietly returns.
|
||||
var toggle = button.Actor.SourceGam.Integer("Toggle", -1);
|
||||
if (!Toggle(target, toggle) && target.Kind != "3BUT")
|
||||
unsupported.Add($"Button {button.Actor.Tag}: target {targetName} toggle is unrecovered");
|
||||
if (button.Down && target.Kind == "3BUT")
|
||||
{
|
||||
var linked = buttons.Find(b => ReferenceEquals(b.Actor, target))!;
|
||||
linked.Available = true;
|
||||
button.Available = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void ResetButton(Button button)
|
||||
{
|
||||
button.Available = button.Actor.SourceGam!.Integer("ButtonAvailable", 1) != 0;
|
||||
button.Down = !button.Available;
|
||||
button.Cooldown = 0;
|
||||
button.Actor.Animation = button.Down ? "DOWN" : "UP";
|
||||
}
|
||||
private static bool Equal(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
|
||||
private static bool Finite(Vector3 v) => float.IsFinite(v.X) && float.IsFinite(v.Y) && float.IsFinite(v.Z);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>Animated sprite timing EXE0x40ED40: strict interval, one frame/call, discard remainder.</summary>
|
||||
public sealed class SpriteSequence(int frames, float fps, int loop)
|
||||
{
|
||||
private float elapsed;
|
||||
private int next;
|
||||
public int Frame { get; private set; }
|
||||
public bool Running { get; private set; }
|
||||
public bool Hidden { get; private set; }
|
||||
public void Start() { elapsed = 0; next = Frame = 0; Running = true; Hidden = false; }
|
||||
public void Step(float dt)
|
||||
{
|
||||
if (!float.IsFinite(dt) || dt < 0) throw new ArgumentOutOfRangeException(nameof(dt));
|
||||
if (!Running || frames <= 0 || fps <= 0) return;
|
||||
elapsed += dt;
|
||||
if (elapsed <= 1 / fps) return;
|
||||
elapsed = 0;
|
||||
Frame = next++;
|
||||
if (next < frames) return;
|
||||
next = 0;
|
||||
if (loop is 0 or 2) Running = false;
|
||||
if (loop == 2) Hidden = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using GamePort.Assets;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>Recovered task gates; -1 sentinels and numeric ExactLevel must retain their original meaning.</summary>
|
||||
public static class TaskActivation
|
||||
{
|
||||
// Animated entity EXE0x40E340. null means keep the prior activation state.
|
||||
public static bool? Animated(GamEntity entity, int state)
|
||||
{
|
||||
var exact = entity.Integer("ExactLevel", -1);
|
||||
if (exact != -1) return state == exact;
|
||||
var required = entity.Integer("RequiredLevel", -1);
|
||||
if (required == -1) return null;
|
||||
var remove = entity.Integer("RemoveLevel", -1);
|
||||
return state >= required && (remove == -1 || state < remove);
|
||||
}
|
||||
|
||||
// Pickup EXE0x45F2B0: no RemoveLevel check in this override.
|
||||
public static bool? Pickup(GamEntity entity, int state)
|
||||
{
|
||||
var exact = entity.Integer("ExactLevel", -1);
|
||||
if (exact != -1) return state == exact;
|
||||
var required = entity.Integer("RequiredLevel", -1);
|
||||
return required == -1 ? null : state >= required;
|
||||
}
|
||||
|
||||
// LOAD EXE0x457F32. A stored task state -1 bypasses the requirements.
|
||||
public static bool Load(GamEntity entity, TaskStates tasks)
|
||||
{
|
||||
var name = entity.Text("RequiredTask");
|
||||
if (string.Equals(name, "none", StringComparison.OrdinalIgnoreCase)) return true;
|
||||
var state = tasks.Get(name);
|
||||
var exact = entity.Integer("ExactLevel", -1);
|
||||
return state == -1 || state >= entity.Integer("RequiredLevel") && (exact == -1 || state == exact);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using GamePort.Assets;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>EXE0x45FEA0 query/0x45F990 assignment; ASCII case folding, missing returns0.</summary>
|
||||
public sealed class TaskStates
|
||||
{
|
||||
private readonly List<SavedTask> tasks;
|
||||
public event Action<string, int>? Assigned;
|
||||
public TaskStates(IEnumerable<SavedTask> initial) => tasks = initial.ToList();
|
||||
private static bool Equal(string a, string b) => Fold(a) == Fold(b);
|
||||
private static string Fold(string text) => string.Create(text.Length, text, (span, source) =>
|
||||
{
|
||||
for (var i = 0; i < span.Length; i++) span[i] = source[i] is >= 'A' and <= 'Z' ? (char)(source[i] + 32) : source[i];
|
||||
});
|
||||
public int Get(string? name) => name == null ? 0 : tasks.FirstOrDefault(t => Equal(t.Name, name))?.State ?? 0;
|
||||
public void SetExisting(string name, int value)
|
||||
{
|
||||
for (var i = 0; i < tasks.Count; i++)
|
||||
if (Equal(tasks[i].Name, name)) tasks[i] = tasks[i] with { State = value };
|
||||
// Original broadcasts even repeated assignments and unknown task names.
|
||||
Assigned?.Invoke(name, value);
|
||||
}
|
||||
public SavedTask[] Snapshot() => tasks.ToArray();
|
||||
}
|
||||
Reference in new issue
Block a user