using EvilEngine.Formats; using EvilEngine.Formats.Collision; using EvilEngine.Formats.Maps; using EvilEngine.Host.Collision; using EvilEngine.Host.Movement; using EvilEngine.Shared; using EvilEngine.Shared.World; using Godot; namespace EvilEngine.Client.World; public partial class SurfaceCheck : Node { private const double Tick = 0.015; private const int Ticks = 200; private const int Grid = 64; private const int Layers = 64; public override async void _Ready() { var args = OS.GetCmdlineUserArgs() .Select(arg => arg.Split('=', 2)) .Where(pair => pair.Length == 2) .ToDictionary(pair => pair[0], pair => pair[1]); var code = await Run(args.GetValueOrDefault("--map") ?? "gmod:gm_construct", (args.GetValueOrDefault("--surfaces") ?? "grass,sand").Split(',', StringSplitOptions.RemoveEmptyEntries)); GetTree().Quit(code); } private static async Task Run(string id, string[] wanted) { var boot = await EngineBoot.Start(_ => { }); if (boot.Registry.Map(ContentId.Parse(id)) is not { } map) { GD.PrintErr($"No map record {id}."); return 2; } var (world, _) = await Task.Run(() => MapStart.Build(boot.Host.Conversion, map, (_, _) => { })); if (world is null) { GD.PrintErr($"{id} didn't build."); return 2; } var clock = System.Diagnostics.Stopwatch.StartNew(); var start = world.SessionStart(map.Id, boot.Registry.Surface); GD.Print($"surface check: {id}'s session world with its surfaces built in {clock.Elapsed.TotalSeconds:0.###} s"); using var physics = start.Physics as JoltWorld ?? throw new InvalidOperationException("The map has no Jolt world."); using var ray = new PhysicsRayQueryParameters3D { CollisionMask = WorldCollision.WorldLayer }; using var hit = new PhysicsIntersectRayResult3D(); var failed = 0; foreach (var name in wanted) if (!Check(physics, name, ray, hit)) failed++; if (!Agree(physics, start.World, ray, hit)) failed++; world.QueueFree(); GD.Print(failed == 0 ? $"surface check: {string.Join(", ", wanted)} named by a ray and a contact on {id}, and every ray agrees with the hull traces" : $"surface check: {failed} of {wanted.Length + 1} checks failed on {id}"); return failed == 0 ? 0 : 1; } private static bool Check(JoltWorld physics, string name, PhysicsRayQueryParameters3D ray, PhysicsIntersectRayResult3D hit) { var tried = 0; foreach (var (body, triangle, centre) in Candidates(physics, name)) { if (tried++ == 64) break; var space = PhysicsServer3D.SpaceGetDirectState(physics.Space); ray.From = Vec(centre) + Vector3.Up * 2; ray.To = Vec(centre) + Vector3.Down * 0.5f; if (!space.IntersectRayInto(ray, hit) || hit.ColliderRid != body) continue; var cast = physics.Surface(hit.ColliderRid, hit.ColliderShape, hit.ColliderFaceIndex); var castName = Named(physics, cast); if (!Is(castName, name)) { GD.PrintErr($"{name}: the ray onto triangle {triangle} reported {castName}, face {hit.ColliderFaceIndex}."); return false; } var contact = Contact(physics, centre); if (contact is not var (rid, shape, face, normal)) { GD.PrintErr($"{name}: the box dropped on triangle {triangle} touched nothing."); return false; } var touched = physics.Surface(rid, shape, face, normal); var touchedName = Named(physics, touched); if (!Is(touchedName, name)) { GD.PrintErr($"{name}: the box on triangle {triangle} touched {touchedName}, shape {shape} face {face}."); return false; } using var data = (Godot.Collections.Dictionary)PhysicsServer3D.ShapeGetData(PhysicsServer3D.BodyGetShape(rid, shape)); var held = data.TryGetValue("friction", out var frictions) ? frictions.AsFloat32Array()[face] : float.NaN; var friction = physics.Record(touched)?.Friction; GD.Print($"{name}: triangle {triangle} at {Format(centre)}, ray face {hit.ColliderFaceIndex} {castName}, " + $"contact shape {shape} face {face} {touchedName}, friction {friction:0.###} held by Jolt as {held:0.###}"); if (friction is { } wanted && Math.Abs(held - wanted) > 1e-6) { GD.PrintErr($"{name}: Jolt holds friction {held} for triangle {face}, not the surface's {wanted}."); return false; } return true; } GD.PrintErr($"{name}: no open, upward triangle of the map's meshes is {name}."); return false; } private static bool Agree(JoltWorld physics, IHullWorld hulls, PhysicsRayQueryParameters3D ray, PhysicsIntersectRayResult3D hit) { var points = physics.MapBodies.SelectMany(physics.MapSurfaces.Shapes) .SelectMany(collider => collider.Shape is MapColliderShape.Hull hull ? hull.Points : []).ToArray(); var min = new MapVector(points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z)); var max = new MapVector(points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z)); var space = PhysicsServer3D.SpaceGetDirectState(physics.Space); var point = new HullBox(MapVector.Zero, MapVector.Zero); int agreed = 0, apart = 0, differed = 0, meshes = 0, edges = 0; var named = new HashSet(); for (var i = 0; i < Grid; i++) for (var j = 0; j < Grid; j++) { var x = min.X + (max.X - min.X) * (i + 0.5) / Grid; var z = min.Z + (max.Z - min.Z) * (j + 0.5) / Grid; var top = max.Y + 1; var stride = 0.25; for (var layer = 0; layer < Layers; layer++) { var from = new MapVector(x, top, z); var to = new MapVector(x, min.Y - 1, z); var traced = hulls.Trace(point, from, to); if (traced.StartSolid) { top -= stride; stride *= 2; continue; } stride = 0.25; ray.From = Vec(from); ray.To = Vec(to); var hitAny = space.IntersectRayInto(ray, hit); if (!hitAny || traced.Fraction >= 1) { if (hitAny || traced.Fraction < 1) apart++; break; } var at = hit.Position; top = Math.Min(at.Y, traced.End.Y) - 0.01; if (Math.Abs(at.Y - traced.End.Y) > 0.01) { apart++; continue; } var n = hit.Normal; var jolt = physics.Surface(hit.ColliderRid, hit.ColliderShape, hit.ColliderFaceIndex, new MapVector(n.X, n.Y, n.Z)); if (jolt == traced.Surface) { agreed++; named.Add(jolt); if (hit.ColliderFaceIndex >= 0) meshes++; continue; } var t = traced.Normal; if (n.X * t.X + n.Y * t.Y + n.Z * t.Z < 0.999 && physics.Surface(hit.ColliderRid, hit.ColliderShape, hit.ColliderFaceIndex, t) == traced.Surface) { edges++; continue; } if (differed++ < 8) GD.PrintErr($"rays: at {x:0.###} {at.Y:0.###} {z:0.###} Jolt named {Named(physics, jolt)}, " + $"the hull trace {Named(physics, traced.Surface)}"); } } GD.Print($"rays: {agreed} hits over {Grid * Grid} columns name the hull trace's surface ({meshes} on triangles, " + $"{named.Count(surface => surface != CollisionSurface.None)} surfaces), {edges} on an edge Jolt and the trace " + $"each gave a face of, {differed} differ, " + $"{apart} hit elsewhere or only one world"); return differed == 0 && named.Count > 1; } private static IEnumerable<(Rid Body, int Triangle, MapVector Centre)> Candidates(JoltWorld physics, string name) { foreach (var body in physics.MapBodies) { if (physics.MapSurfaces.Collider(body, 0)?.Shape is not MapColliderShape.Triangles triangles) continue; var mesh = triangles.Mesh; var parts = mesh.Surfaces.Select(surface => Is(Named(physics, surface), name)).ToArray(); if (!parts.Contains(true)) continue; for (var step = 0; step < mesh.Count; step += Math.Max(1, mesh.Count / 97)) { var triangle = (mesh.Count / 2 + step) % mesh.Count; if (!parts[mesh.Parts[triangle]]) continue; var a = triangles.Transform.Apply(mesh.Positions[mesh.Indices[triangle * 3]]); var b = triangles.Transform.Apply(mesh.Positions[mesh.Indices[triangle * 3 + 1]]); var c = triangles.Transform.Apply(mesh.Positions[mesh.Indices[triangle * 3 + 2]]); var normal = (Vec(b) - Vec(a)).Cross(Vec(c) - Vec(a)).Normalized(); if (Math.Abs(normal.Y) < 0.9) continue; yield return (body, triangle, new MapVector((a.X + b.X + c.X) / 3, (a.Y + b.Y + c.Y) / 3, (a.Z + b.Z + c.Z) / 3)); } } } private static (Rid Body, int Shape, int Face, MapVector Normal)? Contact(JoltWorld physics, MapVector centre) { var shape = PhysicsServer3D.BoxShapeCreate(); PhysicsServer3D.ShapeSetData(shape, new Vector3(0.1f, 0.1f, 0.1f)); var box = PhysicsServer3D.BodyCreate(); try { PhysicsServer3D.BodySetMode(box, PhysicsServer3D.BodyMode.Rigid); PhysicsServer3D.BodyAddShape(box, shape); PhysicsServer3D.BodySetCollisionLayer(box, WorldCollision.PropLayer); PhysicsServer3D.BodySetCollisionMask(box, WorldCollision.WorldLayer); PhysicsServer3D.BodySetMaxContactsReported(box, 8); PhysicsServer3D.BodySetState(box, PhysicsServer3D.BodyState.Transform, new Transform3D(Basis.Identity, Vec(centre) + Vector3.Up * 0.3f)); PhysicsServer3D.BodySetSpace(box, physics.Space); for (var tick = 0; tick < Ticks; tick++) { physics.Step(Tick); var state = PhysicsServer3D.BodyGetDirectState(box); if (state.GetContactCount() == 0) continue; var n = state.GetContactLocalNormal(0); return (state.GetContactCollider(0), state.GetContactColliderShape(0), (int)state.Call("get_contact_collider_face", 0), new MapVector(n.X, n.Y, n.Z)); } return null; } finally { PhysicsServer3D.FreeRid(box); PhysicsServer3D.FreeRid(shape); } } private static string Named(JoltWorld physics, CollisionSurface surface) { return physics.Record(surface)?.Id.ToString() ?? surface.Surface?.ToString() ?? surface.Material?.ToString() ?? "none"; } private static bool Is(string found, string name) { return found.EndsWith("/" + name, StringComparison.Ordinal); } private static string Format(MapVector point) { return $"{point.X:0.##} {point.Y:0.##} {point.Z:0.##}"; } private static Vector3 Vec(MapVector v) { return new Vector3(v.X, v.Y, v.Z); } }