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); /// /// 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. /// 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(); /// OMT1001FF70: largest component divided by a quantized sine lookup. public static float QuickMagnitude(Vector3 vector) => (float)QuickMagnitudeIntermediate(vector); // OMT returns its quotient in an x87 register. Callers with no intervening // float store must retain that intermediate; this is not general x87 emulation. internal static double QuickMagnitudeIntermediate(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 z / sine[halfAcos[index] & 0x3fff]; } /// /// 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. /// 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)); } /// /// 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. /// public static SupportHit? Trace(IEnumerable triangles, Vector3 start, Vector3 end, bool twoSided = false) { ArgumentNullException.ThrowIfNull(triangles); RequireFinite(start); RequireFinite(end); var direction = end - start; var length = QuickMagnitudeIntermediate(direction); if (length == 0) return null; var reciprocal = 1 / length; direction = new((float)(direction.X*reciprocal),(float)(direction.Y*reciprocal), (float)(direction.Z*reciprocal)); SupportHit? nearest = null; var nearestDistance = (float)length; foreach (var triangle in triangles) { var hit = IntersectSegment(triangle, start, direction, length, twoSided); if (hit is not { } candidate || candidate.Distance >= nearestDistance) continue; nearestDistance = candidate.Distance; nearest = candidate; } return nearest; } /// /// EXE469B70's individual source-winding triangle test, without47C6E0's /// nearest-hit reduction. Camera47C210 instead accepts the first grid hit. /// public static SupportHit? IntersectSegment(SupportTriangle triangle, Vector3 start, Vector3 end, bool twoSided = false) { RequireFinite(start); RequireFinite(end); var direction = end - start; var length = QuickMagnitudeIntermediate(direction); if (length == 0) return null; var reciprocal = 1 / length; return IntersectSegment(triangle, start,new((float)(direction.X*reciprocal), (float)(direction.Y*reciprocal),(float)(direction.Z*reciprocal)),length,twoSided); } private static SupportHit? IntersectSegment(SupportTriangle triangle, Vector3 start, Vector3 direction, double length, bool twoSided) { 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); // Preserve serialized winding, opposite to the conventional visible front. if (twoSided ? MathF.Abs(determinant) < TriangleEpsilon : determinant > -TriangleEpsilon) return null; var inverse = 1 / determinant; var relative = start - triangle.A; var u = Dot(relative, p) * inverse; if (u < 0 || u > 1) return null; var q = Cross(relative, edge1); var v = Dot(q, direction) * inverse; if (v < 0 || u + v > 1) return null; var distance = Dot(q, edge2) * inverse; // Beginning accepted, endpoint rejected; no invented camera radius/skin. if (distance < 0 || distance >= length) return null; //469DF0..469E13 stores each hit coordinate only after multiply+add. //Keep the product until that store, including near-cancelling inputs. var position = new Vector3((float)(start.X+(double)direction.X*distance), (float)(start.Y+(double)direction.Y*distance),(float)(start.Z+(double)direction.Z*distance)); return new SupportHit(position, triangle.ShapeId, triangle.PolygonId, QuickMagnitude(position - start)); } 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"); } }