using System.Numerics; namespace GamePort.Game; /// Root state exchanged with the separately implemented body solver. public readonly record struct PatrolBodyState(Vector3 Position, Vector3 Velocity); /// /// Goddard/Carl's ordinary state3 patrol and state7 waypoint wait. The original base /// update consumes the preceding velocity/heading before choosing the next ones. /// Physical collision/gravity are supplied by the caller. Magnitude uses the /// recovered OMT table algorithm; flat atan2 heading and modern table-generation /// trig still require comparison against original angle/x87 results. /// See docs/analysis/patrol.md for recovered order, addresses and limitations. /// public sealed class ActorPatrol { public const float ArrivalDistance = 110; public const float YawFactor = 3.2f; private readonly DirectorActor actor; private readonly Func findActor; private readonly Func integrateBody; private readonly Func magnitude; private readonly float yawFactor; private readonly string movingAnimation, waitingAnimation; private DirectorActor? waypoint; private DirectorActor? previousWaypoint; private Vector3 publishedPosition, publishedRotation; private string? publishedPatrol; private int publishedState, previousState; private float desiredYaw; public Vector3 Velocity { get; private set; } public Vector3 DestinationDelta { get; private set; } public float DestinationDistance { get; private set; } public bool Arrived { get; private set; } public float WaitRemaining { get; private set; } public string? CurrentWaypoint => waypoint?.Tag; public string? PreviousWaypoint => previousWaypoint?.Tag; public bool FollowPlayer {get;set;} public bool SupportedState => actor.AIstate is 1 or 3 or 7 or 9 || actor.Kind == "3CAR" && actor.AIstate == 6 || FollowPlayer&&actor.Kind=="3DOG"&&actor.AIstate==4; public ActorPatrol(DirectorActor actor, Func findActor, Func integrateBody, Func? magnitude = null) { ArgumentNullException.ThrowIfNull(actor); ArgumentNullException.ThrowIfNull(findActor); ArgumentNullException.ThrowIfNull(integrateBody); if (actor.Kind is not ("3DOG" or "3CAR")) throw new ArgumentException("Recovered patrol requires Goddard or Carl", nameof(actor)); this.actor = actor; this.findActor = findActor; this.integrateBody = integrateBody; this.magnitude = magnitude ?? OriginalBodySupport.QuickMagnitude; // Carl413BFC..43 installs WALK/STOP; his Y factor remains3 (407CF8). yawFactor = actor.Kind == "3DOG" ? YawFactor : 3; movingAnimation = actor.Kind == "3DOG" ? "RUN" : "WALK"; waitingAnimation = actor.Kind == "3DOG" ? "WAG" : "STOP"; desiredYaw = actor.Rotation.Y; Publish(); } /// /// Observe authored AI/teleport actions without changing their animation. /// Teleports reset the port body's motion/route cache; their full original /// physics bookkeeping is not yet recovered. Camera-only animation changes /// leave the body and waypoint intact. Internal patrol changes emit no event. /// public void SynchronizeAuthoredState() { if (actor.Position != publishedPosition) { Velocity = Vector3.Zero; ResetRoute(); desiredYaw = actor.Rotation.Y; } if (actor.Rotation != publishedRotation) desiredYaw = actor.Rotation.Y; if (!Equal(actor.Patrol, publishedPatrol) || actor.AIstate != publishedState && actor.AIstate == 3) ResetRoute(); Publish(); } /// False when the current AI state lies outside this recovered subset. public bool Step(float dt) { if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt)); SynchronizeAuthoredState(); if (!SupportedState) return false; if (!actor.Active||!actor.MovementEnabled) return true; if (!float.IsFinite(actor.Speed)) throw new InvalidOperationException("Nonfinite Goddard speed"); // EXE408023->40E050: the body consumes the *previous* velocity first. var body = actor.BodyEnabled ? integrateBody(new(actor.Position, Velocity), dt) : new PatrolBodyState(actor.Position, Velocity); if (!Finite(body.Position) || !Finite(body.Velocity)) throw new InvalidOperationException("Goddard body solver produced nonfinite state"); actor.Position = body.Position; Velocity = body.Velocity; if(FollowPlayer&&actor.Kind=="3DOG") actor.Rotation=GoddardFacing(actor.Rotation,desiredYaw,dt); else { 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 4: StepFollow(); 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 is 3 or 4 && DestinationDelta.X * DestinationDelta.X + DestinationDelta.Z * DestinationDelta.Z > 0) desiredYaw = MathF.Atan2(-DestinationDelta.X, DestinationDelta.Z) * (180 / MathF.PI); Publish(); return true; } /// 4096E0 with41C8DB Goddard factors and the ordinary supported /// follow target (pitch/roll0). Dismount copies tilt; this later AI phase /// gradually levels it. Full airborne AI target selection remains separate. public static Vector3 GoddardFacing(Vector3 rotation,float yaw,float dt) { static float Arc(float delta)=>delta>180?delta-360:delta< -180?delta+360:delta; var delta=new Vector3(Arc(-rotation.X)*.3f*dt,Arc(yaw-rotation.Y)*3.2f*dt,Arc(-rotation.Z)*.3f*dt); return RocketOrientation.Add(rotation,delta); } private void StepFollow() { var target=findActor("JIM1");if(target==null||!target.Active)return; DestinationDelta=target.Position-actor.Position;DestinationDistance=DestinationDelta.Length(); var length=magnitude(DestinationDelta); float multiplier=DestinationDistance>=2000?3:DestinationDistance>=1000?1.7f:1; Velocity=Arrived||length==0?Vector3.Zero:DestinationDelta/length*(actor.Speed*multiplier); if(DestinationDistanceArrivalDistance*1.5f)Arrived=false; actor.Speed=DestinationDistance>440?600:450; if(DestinationDistance>1500) { actor.Position=target.Position+RocketOrientation.Rotate(new(0,0,-800),target.Rotation); Velocity=Vector3.Zero; } actor.Animation=magnitude(Velocity)>20?"RUN":"WAG"; } 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); }