using System.Numerics; using GamePort.Assets; namespace GamePort.Game; public readonly record struct CameraRayPolygon(SupportTriangle Triangle, Vector3 StoredNormal, string? ShapeName = null, string? MaterialName = null, int? MaterialId = null); public readonly record struct CameraRayResult(Vector3 Eye, float Gain, SupportHit? Hit); public readonly record struct CameraRaySelection(SupportHit Hit, CameraRayPolygon Polygon); /// /// Source47C210 static camera predicate: first accepted wall-grid polygon, then /// first general-grid polygon. Cell rectangle order and FIFO registration matter; /// this is not the support query's nearest-hit reducer or a camera sphere sweep. /// See checkpoint/camera-ray-predicate.md for addresses and approximation limits. /// public sealed class OriginalCameraRay { public const int GridSize = 260; public const float CellScale = 0.0020000000949949026f; //4D6A04. public const float CellOrigin = 130; //49B1FC. private readonly Dictionary> walls = []; private readonly Dictionary> all = []; private readonly Dictionary<(int Shape,int Polygon),CameraRayPolygon> sources = []; public bool Enabled { get; set; } = true; // Modern camera-only debug override. public int PolygonCount { get; } public int WallPolygonCount { get; } /// Modern query diagnostic; repeated cells are intentionally counted. public int LastTriangleTests { get; private set; } /// /// Caller supplies raw, untranslated static source triangles. Registration /// follows shape resource ID then polygon array index, not render-draw order. /// Game-specific polygon exclusion must be resolved by the caller. /// public OriginalCameraRay(IEnumerable polygons) { ArgumentNullException.ThrowIfNull(polygons); var identities = new HashSet<(int Shape, int Polygon)>(); foreach (var polygon in polygons.OrderBy(p => p.Triangle.ShapeId).ThenBy(p => p.Triangle.PolygonId)) { if (polygon.ShapeName?.StartsWith("nc", StringComparison.OrdinalIgnoreCase) == true || IsCheckpoint(polygon.MaterialName)) continue; var triangle = polygon.Triangle; RequireFinite(triangle.A); RequireFinite(triangle.B); RequireFinite(triangle.C); RequireFinite(polygon.StoredNormal); if (!identities.Add((triangle.ShapeId, triangle.PolygonId))) throw new InvalidDataException("Camera query needs one source triangle per polygon; fan-triangulated polygons are unsupported"); sources.Add((triangle.ShapeId,triangle.PolygonId),polygon); var wall = polygon.StoredNormal.Y < .7f; //4798B3; equality excluded. var min = Vector3.Min(triangle.A, Vector3.Min(triangle.B, triangle.C)); var max = Vector3.Max(triangle.A, Vector3.Max(triangle.B, triangle.C)); foreach (var cell in CellsBetween(min, max)) { Append(all, cell, triangle); if (wall) Append(walls, cell, triangle); } PolygonCount++; if (wall) WallPolygonCount++; } } /// /// Route/tutorial complete game slot134 is475CD0 (false), including VR02's ///4CDD30 and VR08's4D00D0 tables, so only the proven /// NC/checkpoint gates apply. Reject other levels rather than inventing masks. /// Prepared source metadata is required; raw render visibility is irrelevant. /// public static OriginalCameraRay FromRouteScene(Mesh mesh, string levelCode) { ArgumentNullException.ThrowIfNull(mesh); if (levelCode is not ("LV1B" or "VR01" or "VR02" or "VR04" or "VR05" or "VR07" or "VR08" or "LEV1")) throw new NotSupportedException("Static camera game-filter recovery covers only selected route/tutorial scenes"); if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3) throw new InvalidDataException("Original camera query requires source polygon metadata"); var polygons = new CameraRayPolygon[mesh.CollisionPolygons.Length]; for (var i = 0; i < polygons.Length; i++) { var source = mesh.CollisionPolygons[i]; var a = mesh.Indices[i * 3]; var b = mesh.Indices[i * 3 + 1]; var c = mesh.Indices[i * 3 + 2]; if (a >= mesh.Vertices.Length || b >= mesh.Vertices.Length || c >= mesh.Vertices.Length) throw new InvalidDataException("Camera triangle index outside vertex table"); polygons[i] = new(new(mesh.Vertices[a].Position, mesh.Vertices[b].Position, mesh.Vertices[c].Position, source.ShapeId, source.PolygonIndex), source.Normal, source.ShapeName, source.MaterialName, source.MaterialId); } return new(polygons); } /// 47C210/47C280/47C4B0: increasing X, increasing Z, FIFO first hit. public SupportHit? Trace(Vector3 start, Vector3 end, bool twoSided = false) { RequireFinite(start); RequireFinite(end); LastTriangleTests = 0; if (!Enabled) return null; return TraceCore(start, end, twoSided, diagnostic: true); } /// 425170 also uses47C210. Camera-only debug controls must not /// disable physical ceiling checks or overwrite camera-query diagnostics. public SupportHit? TraceGeometry(Vector3 start, Vector3 end, bool twoSided = false) { RequireFinite(start); RequireFinite(end); return TraceCore(start, end, twoSided, diagnostic: false); } /// Capture47C210's hit and selected polygon/material together. /// This geometry query is independent of the modern camera debug toggle. public CameraRaySelection? TraceSelectedGeometry(Vector3 start,Vector3 end,bool twoSided=false) { var hit=TraceGeometry(start,end,twoSided); return hit is{} h?new(h,sources[(h.ShapeId,h.PolygonId)]):null; } private SupportHit? TraceCore(Vector3 start, Vector3 end, bool twoSided, bool diagnostic) { foreach (var grid in new[] { walls, all }) foreach (var cell in CellsBetween(start, end)) if (grid.TryGetValue(cell, out var triangles)) foreach (var triangle in triangles) { if (diagnostic) LastTriangleTests++; if (OriginalBodySupport.IntersectSegment(triangle, start, end, twoSided) is { } hit) return hit; } return null; } /// 43B820: ray originates at computed look target, never actor root. public CameraRayResult Constrain(Vector3 lookPoint, Vector3 desiredEye) { var hit = Trace(lookPoint, desiredEye); return hit is { } accepted ? new(lookPoint - (lookPoint - accepted.Position) * .75f, 1.5f, accepted) : new(desiredEye, 1, null); } /// ///47F940 truncation then signed16. Double intermediates approximate source /// x87, not bit-exact boundary emulation. Conversion overflow is unsupported. /// public static short CellCoordinate(float value) { if (!float.IsFinite(value)) throw new ArgumentOutOfRangeException(nameof(value)); var scaled = (double)value * CellScale + CellOrigin; if (scaled <= long.MinValue || scaled >= long.MaxValue) throw new ArgumentOutOfRangeException(nameof(value), "Original x87 integer-overflow behavior is not recovered"); return unchecked((short)(long)Math.Truncate(scaled)); } private static IEnumerable CellsBetween(Vector3 a, Vector3 b) { var ax = (int)CellCoordinate(a.X); var bx = (int)CellCoordinate(b.X); var az = (int)CellCoordinate(a.Z); var bz = (int)CellCoordinate(b.Z); var minX = Math.Max(0, Math.Min(ax, bx)); var maxX = Math.Min(GridSize - 1, Math.Max(ax, bx)); var minZ = Math.Max(0, Math.Min(az, bz)); var maxZ = Math.Min(GridSize - 1, Math.Max(az, bz)); for (var x = minX; x <= maxX; x++) for (var z = minZ; z <= maxZ; z++) yield return GridSize * x + z; } private static void Append(Dictionary> grid, int cell, SupportTriangle triangle) { if (!grid.TryGetValue(cell, out var list)) grid.Add(cell, list = []); list.Add(triangle); } private static bool IsCheckpoint(string? material) => material is not null && (material.Equals("cstart", StringComparison.OrdinalIgnoreCase) || material.Length == 7 && material.StartsWith("ccheck", StringComparison.OrdinalIgnoreCase) && material[6] is >= '1' and <= '9'); 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"); } }