diff --git a/client/Puppet.cs b/client/Puppet.cs index 11a0739..a257195 100644 --- a/client/Puppet.cs +++ b/client/Puppet.cs @@ -156,22 +156,18 @@ public partial class Puppet : Node3D /// /// The shape as one surface: VERTEX in the spread bind, the facet NORMAL, CUSTOM0 (the edge-distance basis: vertex k of a triangle holds /// its altitude h_k = 2 * area / |edge k| in component k and 0 in the others, the triangle's smallest altitude in w), CUSTOM1 (bone A, - /// bone B, weight A) and CUSTOM2 (the triangle's three creases, the same at all three vertices). + /// bone B, weight A) and CUSTOM2 (the triangle's three creases: zero until PuppetSkin derives them, so the bevel does nothing here). /// private static ArrayMesh MeshOf(PuppetShape s) { - int n = s.Positions.Length; + int n = s.Corners.Length; var vertex = new Vector3[n]; var normal = new Vector3[n]; var edge = new float[4 * n]; var skin = new float[3 * n]; var crease = new float[3 * n]; - for (int i = 0; i < n; i++) - { - vertex[i] = new Vector3(s.Positions[i].x, s.Positions[i].y, s.Positions[i].z); - normal[i] = new Vector3(s.Normals[i].x, s.Normals[i].y, s.Normals[i].z); - skin[3 * i] = s.BoneA[i]; skin[3 * i + 1] = s.BoneB[i]; skin[3 * i + 2] = s.WeightA[i]; - } for (int t = 0; t < n; t += 3) { - var p = new[] { s.Positions[t], s.Positions[t + 1], s.Positions[t + 2] }; - float twiceArea = CultMath.math.length(CultMath.math.cross(p[1] - p[0], p[2] - p[0])); + var p = new[] { s.Vertices[s.Corners[t]], s.Vertices[s.Corners[t + 1]], s.Vertices[s.Corners[t + 2]] }; + var cross = CultMath.math.cross(p[1] - p[0], p[2] - p[0]); + float twiceArea = CultMath.math.length(cross); + var facet = -cross / twiceArea; var h = new float[3]; for (int k = 0; k < 3; k++) { @@ -181,9 +177,11 @@ public partial class Puppet : Node3D float smallest = Mathf.Min(h[0], Mathf.Min(h[1], h[2])); for (int k = 0; k < 3; k++) { - int i = t + k; + int i = t + k, c = s.Corners[i]; + vertex[i] = new Vector3(p[k].x, p[k].y, p[k].z); + normal[i] = new Vector3(facet.x, facet.y, facet.z); + skin[3 * i] = s.BoneA[c]; skin[3 * i + 1] = s.BoneB[c]; skin[3 * i + 2] = s.WeightA[c]; edge[4 * i + k] = h[k]; edge[4 * i + 3] = smallest; - for (int e = 0; e < 3; e++) crease[3 * i + e] = s.Crease[t + e]; } } var arrays = new Godot.Collections.Array(); diff --git a/client/PuppetField.cs b/client/PuppetField.cs index 6992899..0c25f42 100644 --- a/client/PuppetField.cs +++ b/client/PuppetField.cs @@ -49,26 +49,29 @@ public readonly record struct PuppetBody(ulong Id, Box3DSoaKind Kind, float3 Siz public readonly record struct PuppetJoint(Box3DSoaJointKind Kind, int A, int B, float3 LocalOrigin); /// -/// What the puppet is made of, read-only: the spread bind per shape body (bone i is body i), the joints, and the -/// mesh as unwelded flat triangles (three entries per triangle) with each vertex's two bones and the first one's weight. +/// What the puppet is made of, read-only: the spread bind per shape body (bone i is body i), the joints, and the mesh welded: +/// each vertex once, in the spread bind, with its two bones and the first one's weight, and the triangles as indices into the vertices. /// public sealed class PuppetShape { public required ulong[] Ids { get; init; } public required Rigid[] SpreadBind { get; init; } public required (Box3DSoaJointKind Kind, int A, int B, float3 Origin)[] Joints { get; init; } - public required float3[] Positions { get; init; } - public required float3[] Normals { get; init; } + + /// The vertices in the spread bind. + public required float3[] Vertices { get; init; } public required int[] BoneA { get; init; } public required int[] BoneB { get; init; } public required float[] WeightA { get; init; } + /// The triangles, three vertex indices each, wound clockwise seen from outside (Godot's front face). + public required int[] Corners { get; init; } + /// - /// One entry per triangle corner slot, 3t+k = edge k of triangle t, the edge opposite corner k: half the turn from this facet's - /// normal to the neighbour's across that edge, in radians, positive where the edge is convex. An edge not shared by exactly two - /// triangles has 0, and so has a fold (two triangles lying over each other, which the Newton step can make). Both sides of an edge carry the same value, so the shader turns both facets to one bisector. + /// One entry per corner slot: for slot 3t+k, which is edge k of triangle t (the edge opposite corner k), the slot of the neighbour's corner + /// opposite that same edge, or -1 unless exactly two triangles share the edge. Whoever pairs the two sides of an edge reads it here. /// - public required float[] Crease { get; init; } + public required int[] Across { get; init; } /// How far a skinned vertex can lie from its bone's origin. public required float Reach { get; init; } @@ -77,7 +80,7 @@ public sealed class PuppetShape public required int Pulled { get; init; } public required float OffSurface { get; init; } - public int Triangles => Positions.Length / 3; + public int Triangles => Corners.Length / 3; } /// @@ -186,23 +189,24 @@ public static class PuppetField } var (v, tris, pulled, offSurface) = Untangle(f, nets.Quads, net, projected); - var pos = new List(); var nor = new List(); - var ba = new List(); var bb = new List(); var wa = new List(); - var corner = new List(); // The nets wind every quad counter-clockwise seen from the field's outside; Godot's front face is clockwise, so each triangle is emitted reversed. + // Only the vertices some triangle uses are kept, in the order they are first used. + var welded = new int[v.Length]; Array.Fill(welded, -1); + var vertices = new List(); var ba = new List(); var bb = new List(); var wa = new List(); + var corners = new int[tris.Length]; for (int k = 0; k < tris.Length; k += 3) - { - int ia = tris[k], ib = tris[k + 2], ic = tris[k + 1]; - var cross = math.cross(v[ib] - v[ia], v[ic] - v[ia]); - var normal = -cross / math.length(cross); - foreach (int i in new[] { ia, ib, ic }) + for (int c = 0; c < 3; c++) { - f.Eval(v[i], out int bone, out int other, out float w); - pos.Add(v[i]); nor.Add(normal); ba.Add(bone); bb.Add(other); wa.Add(w); + int i = tris[k + (3 - c) % 3]; // reversed: 0, 2, 1 + if (welded[i] < 0) + { + welded[i] = vertices.Count; + f.Eval(v[i], out int bone, out int other, out float w); + vertices.Add(v[i]); ba.Add(bone); bb.Add(other); wa.Add(w); + } + corners[k + c] = welded[i]; } - corner.Add(ia); corner.Add(ib); corner.Add(ic); - } - var crease = Creases(corner, pos, nor); + var across = Across(corners); float maxBall = 0; for (int i = 0; i < n; i++) maxBall = MathF.Max(maxBall, f.BallR[i]); @@ -213,7 +217,7 @@ public static class PuppetField return new PuppetShape { Ids = ids, SpreadBind = t, Joints = js, - Positions = pos.ToArray(), Normals = nor.ToArray(), BoneA = ba.ToArray(), BoneB = bb.ToArray(), WeightA = wa.ToArray(), Crease = crease, + Vertices = vertices.ToArray(), BoneA = ba.ToArray(), BoneB = bb.ToArray(), WeightA = wa.ToArray(), Corners = corners, Across = across, Reach = 2 * reach + 2 * maxBall + smin, Pulled = pulled, OffSurface = offSurface, }; } @@ -304,41 +308,23 @@ public static class PuppetField return MathF.Atan2(math.length(math.cross(na, nb)), math.dot(na, nb)) >= 1e-2f; } - /// - /// Each triangle edge is matched to its neighbour by the two net-vertex indices it joins. An edge that exactly two triangles share - /// gets, on each side, half the turn from this facet's normal to the other's: with u the edge's in-plane unit normal pointing away - /// from the opposite corner and b the normalized sum of the two facet normals, atan2(b.u, b.n). Any other edge gets 0, and so does a fold. - /// - private static float[] Creases(List corner, List pos, List nor) + /// Each triangle edge is matched to its neighbour by the two vertex indices it joins; . + private static int[] Across(int[] corners) { var sides = new Dictionary<(int, int), List>(); - for (int s = 0; s < corner.Count; s++) + for (int s = 0; s < corners.Length; s++) { int t = s / 3, k = s % 3; - int p = corner[3 * t + (k + 1) % 3], q = corner[3 * t + (k + 2) % 3]; + int p = corners[3 * t + (k + 1) % 3], q = corners[3 * t + (k + 2) % 3]; var key = p < q ? (p, q) : (q, p); if (!sides.TryGetValue(key, out var list)) sides[key] = list = new List(2); list.Add(s); } - var crease = new float[corner.Count]; + var across = new int[corners.Length]; + Array.Fill(across, -1); foreach (var list in sides.Values) - { - if (list.Count != 2) continue; - foreach (int s in list) - { - int t = s / 3, k = s % 3, other = list[0] == s ? list[1] : list[0]; - var n = nor[3 * t]; var m = nor[3 * (other / 3)]; - var p = pos[3 * t + (k + 1) % 3]; var q = pos[3 * t + (k + 2) % 3]; var r = pos[3 * t + k]; - var u = Unit(math.cross(Unit(q - p), n)); - if (math.dot(u, r - p) > 0) u = -u; - var b = Unit(n + m); - if (math.lengthsq(b) == 0) continue; - crease[s] = MathF.Atan2(math.dot(b, u), math.dot(b, n)); - } - // A fold, two triangles lying over each other, has no edge to bevel: the sides disagree on which way it turns. - if (crease[list[0]] * crease[list[1]] < 0) crease[list[0]] = crease[list[1]] = 0; - } - return crease; + if (list.Count == 2) { across[list[0]] = list[1]; across[list[1]] = list[0]; } + return across; } private static float3 Unit(float3 v) diff --git a/client/tests/PuppetChecks.cs b/client/tests/PuppetChecks.cs index a875996..ae2639c 100644 --- a/client/tests/PuppetChecks.cs +++ b/client/tests/PuppetChecks.cs @@ -95,7 +95,7 @@ public static class PuppetChecks { var shape = Build(cell); var owned = new int[real.Count]; - for (int v = 0; v < shape.Positions.Length; v++) owned[shape.WeightA[v] >= 0.5f ? shape.BoneA[v] : shape.BoneB[v]]++; + for (int v = 0; v < shape.Vertices.Length; v++) owned[shape.WeightA[v] >= 0.5f ? shape.BoneA[v] : shape.BoneB[v]]++; return cell <= thinnest + 1e-6f && Pieces(shape) == 1 && owned.Min() > 0; } // The look constants may be changed by the operator's joint-look question, within what the mesh can hold: a blend wider than @@ -123,7 +123,17 @@ public static class PuppetChecks Check(worstLength90 <= 0.25f, $"every joint bent up to 90 degrees makes a skinned edge {worstLength90:F3} m long, over 0.25 m"); Mesher(puppet, Check); - Creases(puppet, Check); + AcrossIsPositionWeld(puppet, Check); + } + + /// The corner slot's vertex, in the spread bind. + private static float3 At(PuppetShape shape, int slot) => shape.Vertices[shape.Corners[slot]]; + + /// The unit normal of a triangle seen from outside (the winding is clockwise from outside), from its corners. + private static float3 Facet(PuppetShape shape, int triangle) + { + var cross = math.cross(At(shape, 3 * triangle + 1) - At(shape, 3 * triangle), At(shape, 3 * triangle + 2) - At(shape, 3 * triangle)); + return -cross / math.length(cross); } /// @@ -135,48 +145,35 @@ public static class PuppetChecks private static void Mesher(PuppetShape shape, Action check) { int count = shape.Triangles; - var id = new Dictionary<(long, long, long), int>(); - var corner = new int[shape.Positions.Length]; - for (int i = 0; i < corner.Length; i++) + int folds = 0, edges = 0; + for (int s = 0; s < shape.Across.Length; s++) { - var p = shape.Positions[i]; - var key = ((long)Math.Round(p.x * 1e5), (long)Math.Round(p.y * 1e5), (long)Math.Round(p.z * 1e5)); - if (!id.TryGetValue(key, out corner[i])) id[key] = corner[i] = id.Count; - } - var sides = new Dictionary<(int, int), List>(); - for (int s = 0; s < corner.Length; s++) - { - int t = s / 3, k = s % 3, p = corner[3 * t + (k + 1) % 3], q = corner[3 * t + (k + 2) % 3]; - var key = p < q ? (p, q) : (q, p); - if (!sides.TryGetValue(key, out var list)) sides[key] = list = new List(); - list.Add(s); - } - int folds = 0; - foreach (var list in sides.Values) - { - if (list.Count != 2) continue; - int a = list[0], b = list[1]; - float3 na = shape.Normals[3 * (a / 3)], nb = shape.Normals[3 * (b / 3)]; - if (MathF.Atan2(math.length(math.cross(na, nb)), math.dot(na, nb)) < 1e-2f) continue; - bool convexA = math.dot(na, shape.Positions[b] - shape.Positions[3 * (a / 3) + (a % 3 + 1) % 3]) < 0; - bool convexB = math.dot(nb, shape.Positions[a] - shape.Positions[3 * (b / 3) + (b % 3 + 1) % 3]) < 0; + int o = shape.Across[s]; + if (o < s) continue; + edges++; + float3 na = Facet(shape, s / 3), nb = Facet(shape, o / 3); + if (MathF.Atan2(math.length(math.cross(na, nb)), math.dot(na, nb)) < 1e-2f) continue; // a flatter edge has no convexity to speak of + // Convex from a side: the neighbour's far corner (the corner opposite the shared edge) lies behind this facet's plane. + bool convexA = math.dot(na, At(shape, o) - At(shape, 3 * (s / 3) + (s % 3 + 1) % 3)) < 0; + bool convexB = math.dot(nb, At(shape, s) - At(shape, 3 * (o / 3) + (o % 3 + 1) % 3)) < 0; if (convexA != convexB) folds++; } - check(folds == 0, $"{folds} of {sides.Count} edges are folds: their two triangles disagree on convexity"); + check(edges > 1000, $"the mesher check is vacuous: {edges} shared edges"); + check(folds == 0, $"{folds} of {edges} shared edges are folds: their two triangles disagree on convexity"); // Facing into the body: an odd crossing count from just outside the face means the face looks inward. var directions = new[] { math.normalize(new float3(0.5773f, 0.3011f, 0.7571f)), math.normalize(new float3(-0.2113f, 0.8317f, -0.5129f)) }; int inward = 0; float smallest = float.MaxValue; for (int t = 0; t < count; t++) { - var a = shape.Positions[3 * t]; var b = shape.Positions[3 * t + 1]; var c = shape.Positions[3 * t + 2]; + var a = At(shape, 3 * t); var b = At(shape, 3 * t + 1); var c = At(shape, 3 * t + 2); smallest = MathF.Min(smallest, 0.5f * math.length(math.cross(b - a, c - a))); - var origin = (a + b + c) / 3f + shape.Normals[3 * t] * 1e-3f; + var origin = (a + b + c) / 3f + Facet(shape, t) * 1e-3f; bool both = true; foreach (var d in directions) { int crossings = 0; - for (int u = 0; u < count; u++) if (Crosses(origin, d, shape.Positions[3 * u], shape.Positions[3 * u + 1], shape.Positions[3 * u + 2])) crossings++; + for (int u = 0; u < count; u++) if (Crosses(origin, d, At(shape, 3 * u), At(shape, 3 * u + 1), At(shape, 3 * u + 2))) crossings++; both &= crossings % 2 == 1; } if (both) inward++; @@ -200,82 +197,45 @@ public static class PuppetChecks } /// - /// The bevel's creases, measured without PuppetField's indices: corners are welded by position and each edge is matched by its two - /// welded corners. An edge two triangles share carries the same crease on both sides, half the angle between the facet normals, - /// positive exactly where the neighbour's far corner lies behind this facet's plane; every other edge carries 0. + /// is the edge match a weld by position makes: vertices at the same place are one, and an edge joins + /// the corners opposite it in the two triangles that have it, or nothing where it has other than two. /// - private static void Creases(PuppetShape shape, Action check) + private static void AcrossIsPositionWeld(PuppetShape shape, Action check) { var id = new Dictionary<(long, long, long), int>(); - var corner = new int[shape.Positions.Length]; - for (int i = 0; i < corner.Length; i++) + var weld = new int[shape.Corners.Length]; + for (int s = 0; s < weld.Length; s++) { - var p = shape.Positions[i]; + var p = At(shape, s); var key = ((long)Math.Round(p.x * 1e5), (long)Math.Round(p.y * 1e5), (long)Math.Round(p.z * 1e5)); - if (!id.TryGetValue(key, out corner[i])) id[key] = corner[i] = id.Count; + if (!id.TryGetValue(key, out weld[s])) id[key] = weld[s] = id.Count; } var sides = new Dictionary<(int, int), List>(); - for (int s = 0; s < corner.Length; s++) + for (int s = 0; s < weld.Length; s++) { - int t = s / 3, k = s % 3, p = corner[3 * t + (k + 1) % 3], q = corner[3 * t + (k + 2) % 3]; + int t = s / 3, k = s % 3, p = weld[3 * t + (k + 1) % 3], q = weld[3 * t + (k + 2) % 3]; var key = p < q ? (p, q) : (q, p); if (!sides.TryGetValue(key, out var list)) sides[key] = list = new List(); list.Add(s); } - check(shape.Crease.Length == shape.Positions.Length, $"the puppet has {shape.Crease.Length} creases for {shape.Positions.Length} triangle corners"); - if (shape.Crease.Length != shape.Positions.Length) return; - int shared = 0, creased = 0, folds = 0, badFold = 0, asymmetric = 0, notHalf = 0, badSign = 0, loose = 0, badLoose = 0; + int wrong = 0, shared = 0, loose = 0; foreach (var list in sides.Values) { - if (list.Count != 2) - { - loose++; - if (list.Any(s => shape.Crease[s] != 0)) badLoose++; - continue; - } - shared++; - int a = list[0], b = list[1]; - float3 na = shape.Normals[3 * (a / 3)], nb = shape.Normals[3 * (b / 3)]; - float angle = MathF.Atan2(math.length(math.cross(na, nb)), math.dot(na, nb)); - if (angle < 1e-2f) continue; // a flat edge has no convexity to speak of, and its crease is below the float noise of the sign - // Convex from a side: the neighbour's far corner (the corner opposite the shared edge) lies behind this facet's plane. - bool convexA = math.dot(na, shape.Positions[b] - shape.Positions[3 * (a / 3) + (a % 3 + 1) % 3]) < 0; - bool convexB = math.dot(nb, shape.Positions[a] - shape.Positions[3 * (b / 3) + (b % 3 + 1) % 3]) < 0; - if (convexA != convexB) - { - // The triangles lie over each other: there is no edge to bevel. - folds++; - if (shape.Crease[a] != 0 || shape.Crease[b] != 0) badFold++; - continue; - } - creased++; - if (MathF.Abs(shape.Crease[a] - shape.Crease[b]) > 1e-5f) asymmetric++; - if (MathF.Abs(MathF.Abs(shape.Crease[a]) - 0.5f * angle) > 1e-4f || MathF.Abs(MathF.Abs(shape.Crease[b]) - 0.5f * angle) > 1e-4f) notHalf++; - if ((shape.Crease[a] > 0) != convexA || (shape.Crease[b] > 0) != convexB) badSign++; + if (list.Count == 2) { shared++; if (shape.Across[list[0]] != list[1] || shape.Across[list[1]] != list[0]) wrong++; } + else { loose++; foreach (int s in list) if (shape.Across[s] != -1) wrong++; } } - check(shared > 1000 && creased > 100, $"the crease check is vacuous: {shared} shared edges, {creased} turning more than a hundredth of a radian"); - check(badFold == 0, $"{badFold} of {folds} fold edges carry a crease"); - check(asymmetric == 0, $"{asymmetric} of {shared} shared edges carry different creases on their two sides"); - check(notHalf == 0, $"{notHalf} of {shared} shared edges have a crease that is not half the angle between the facet normals"); - check(badSign == 0, $"{badSign} of {creased} turning edges have a crease whose sign does not match the edge's convexity"); - check(badLoose == 0, $"{badLoose} of {loose} edges not shared by exactly two triangles carry a crease"); + check(shape.Across.Length == shape.Corners.Length, $"the puppet has {shape.Across.Length} Across entries for {shape.Corners.Length} corner slots"); + check(shared > 1000, $"the Across check is vacuous: {shared} shared edges and {loose} not"); + check(wrong == 0, $"{wrong} corner slots' Across differs from the edge match a weld by position makes"); } - /// The mesh's connected pieces with coincident triangle corners welded. + /// The mesh's connected pieces. public static int Pieces(PuppetShape shape) { - var id = new Dictionary<(long, long, long), int>(); - var corner = new int[shape.Positions.Length]; - for (int i = 0; i < corner.Length; i++) - { - var p = shape.Positions[i]; - var key = ((long)Math.Round(p.x * 1e5), (long)Math.Round(p.y * 1e5), (long)Math.Round(p.z * 1e5)); - if (!id.TryGetValue(key, out corner[i])) id[key] = corner[i] = id.Count; - } - var parent = Enumerable.Range(0, id.Count).ToArray(); + var parent = Enumerable.Range(0, shape.Vertices.Length).ToArray(); int Find(int x) { while (parent[x] != x) x = parent[x] = parent[parent[x]]; return x; } - for (int t = 0; t < corner.Length; t += 3) { parent[Find(corner[t + 1])] = Find(corner[t]); parent[Find(corner[t + 2])] = Find(corner[t]); } - return corner.Select(Find).Distinct().Count(); + for (int t = 0; t < shape.Corners.Length; t += 3) { parent[Find(shape.Corners[t + 1])] = Find(shape.Corners[t]); parent[Find(shape.Corners[t + 2])] = Find(shape.Corners[t]); } + return shape.Corners.Select(Find).Distinct().Count(); } /// @@ -284,13 +244,13 @@ public static class PuppetChecks /// public static (float Ratio, float Length) Stretch(PuppetShape shape, Rigid[] bones) { - float3 Skin(int v) { float w = shape.WeightA[v]; var p = shape.Positions[v]; return bones[shape.BoneA[v]].Apply(p) * w + bones[shape.BoneB[v]].Apply(p) * (1 - w); } + float3 Skin(int v) { float w = shape.WeightA[v]; var p = shape.Vertices[v]; return bones[shape.BoneA[v]].Apply(p) * w + bones[shape.BoneB[v]].Apply(p) * (1 - w); } float ratio = 0, length = 0; - for (int t = 0; t < shape.Positions.Length; t += 3) + for (int t = 0; t < shape.Corners.Length; t += 3) for (int e = 0; e < 3; e++) { - int a = t + e, b = t + (e + 1) % 3; - float bind = math.length(shape.Positions[a] - shape.Positions[b]); + int a = shape.Corners[t + e], b = shape.Corners[t + (e + 1) % 3]; + float bind = math.length(shape.Vertices[a] - shape.Vertices[b]); float now = math.length(Skin(a) - Skin(b)); length = MathF.Max(length, now); if (bind > 1e-5f) ratio = MathF.Max(ratio, now / bind); diff --git a/client/tests/RenderCheck.cs b/client/tests/RenderCheck.cs index 574610b..22b387c 100644 --- a/client/tests/RenderCheck.cs +++ b/client/tests/RenderCheck.cs @@ -12,11 +12,7 @@ namespace BadDay.Client.Tests; /// puppet alone on black, and compares the rendered silhouette with the silhouette of the same mesh skinned on the CPU from the /// carriers and the spread bind (not from anything Puppet computed) and projected through the camera. Intersection over union must be /// at least . It also looks at the light, with the chamber near full glow: the puppet's faces must not clip to white and must differ from each other, and the chamber's light must lift the puppet over the same frame with that light off (so the glow is bounded from below as well). -/// It also reads the shading normal the shader draws (ShowNormals: the view-space normal as emission) close up on the torso and compares it -/// pixel by pixel with a CPU reference: the skinned facet normal tilted toward each edge's bisector within , from -/// a depth raster of the skinned triangles, the shape's creases and the edge distances from barycentrics. The 90th percentile error over -/// the interior pixels must be at most degrees and the median over the bevel band at most . -/// godot --path client res://tests/RenderCheck.tscn [-- --png=path] [-- --normals-png=path]; exit code 0 passes, 1 fails. It needs a window, so it is +/// godot --path client res://tests/RenderCheck.tscn [-- --png=path]; exit code 0 passes, 1 fails. It needs a window, so it is /// not part of the headless smoke. /// public partial class RenderCheck : Node @@ -38,16 +34,6 @@ public partial class RenderCheck : Node /// The chamber's glow must light the puppet: with the light on, the mean level of the puppet's pixels must exceed the same frame with the light off by at least this many of 255 levels (the shipped light lifts it 9.8). A glow of 0 fails. private const float MinGlowLift = 5f; - /// The 90th percentile angular error (degrees) of the drawn normal against the CPU reference, over the interior pixels. A correct render measures under 1. - private const float MaxNormalP90 = 2f; - - /// The median angular error (degrees) over the bevel band: pixels within 0.6 of the bevel width of an edge that turns by more than 0.1 radian. A correct render measures under 0.5. - private const float MaxBandMedian = 1.5f; - - /// Vacuity floors: the check must reach this many interior pixels and this many band pixels, and the band's reference normal must lie this many degrees (median) from the facet's, or a bevel that is off would pass. - private const int MinKept = 200000, MinBand = 20000; - private const float MinBandTilt = 4f; - private const int BendSeed = 7; private const float BendDegrees = 60f; @@ -116,17 +102,17 @@ public partial class RenderCheck : Node // What the same mesh covers skinned on the CPU: bones from the carriers' world poses and the spread bind, nothing from Puppet. var camera = GetViewport().GetCamera3D(); var scale = new Vector2(w, h) / GetViewport().GetVisibleRect().Size; - var skinned = new Vector3[shape.Positions.Length]; + var skinned = new Vector3[shape.Vertices.Length]; var world = carriers.Select((c, i) => c.GlobalTransform * Puppet.ToTransform(shape.SpreadBind[i].Inverse())).ToArray(); for (int v = 0; v < skinned.Length; v++) { - var p = new Vector3(shape.Positions[v].x, shape.Positions[v].y, shape.Positions[v].z); + var p = new Vector3(shape.Vertices[v].x, shape.Vertices[v].y, shape.Vertices[v].z); skinned[v] = world[shape.BoneA[v]] * p * shape.WeightA[v] + world[shape.BoneB[v]] * p * (1f - shape.WeightA[v]); } var covered = new bool[w * h]; - for (int t = 0; t < skinned.Length; t += 3) + for (int t = 0; t < shape.Corners.Length; t += 3) { - var a = camera.UnprojectPosition(skinned[t]) * scale; var b = camera.UnprojectPosition(skinned[t + 1]) * scale; var c = camera.UnprojectPosition(skinned[t + 2]) * scale; + var a = camera.UnprojectPosition(skinned[shape.Corners[t]]) * scale; var b = camera.UnprojectPosition(skinned[shape.Corners[t + 1]]) * scale; var c = camera.UnprojectPosition(skinned[shape.Corners[t + 2]]) * scale; Fill(covered, w, h, a, b, c); } @@ -169,128 +155,6 @@ public partial class RenderCheck : Node if (share > MaxClipped) { GD.PrintErr($"RENDER FAIL: {share:P1} of the puppet's pixels are clipped to white, over {MaxClipped:P0}; the facets cannot read"); ok = false; } if (spread < MinSpread) { GD.PrintErr($"RENDER FAIL: the puppet's pixels span only {spread:F0} levels between the 10th and 90th percentile, under {MinSpread}; the facets do not differ"); ok = false; } if (lift < MinGlowLift) { GD.PrintErr($"RENDER FAIL: the chamber's light lifts the puppet by {lift:F2} levels, under {MinGlowLift}; the box's glow does not light the body"); ok = false; } - ok &= await NormalCheck(main, shape, carriers, world); - return ok; - } - - /// - /// The drawn shading normal against the shader's formula evaluated on the CPU. The puppet is seen close up from the torso's front-top - /// (the camera 0.35, 0.2, 0.55 m off body 101, FOV 30) in the same bent pose; the view-space normal is read raw from the frame - /// (n * 0.5 + 0.5, not sRGB-decoded) and turned to world by the camera's basis. - /// - private async Task NormalCheck(Main main, PuppetShape shape, Node3D[] carriers, Transform3D[] world) - { - int torso = Array.IndexOf(shape.Ids, 101UL); - if (torso < 0) { GD.PrintErr("RENDER FAIL: the puppet has no body 101 to look at"); return false; } - var target = carriers[torso].GlobalPosition; - var camera = new Camera3D { Fov = 30f, Current = true }; - AddChild(camera); - camera.GlobalPosition = target + new Vector3(0.35f, 0.2f, 0.55f); - camera.LookAt(target, Vector3.Up); - var puppet = main.Bodies.GetNode("Puppet"); - puppet.ShowNormals = true; - for (int i = 0; i < 4; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); - var image = GetViewport().GetTexture().GetImage(); - image.Convert(Image.Format.Rgba8); - puppet.ShowNormals = false; - foreach (var arg in OS.GetCmdlineUserArgs()) - if (arg.StartsWith("--normals-png=")) image.SavePng(arg["--normals-png=".Length..]); - int w = image.GetWidth(), h = image.GetHeight(); - - // The skinned corners and their normals: the facet normal turned by the blended bone, as vertex() does. - int n = shape.Positions.Length; - var skinned = new Vector3[n]; var turned = new Vector3[n]; - for (int v = 0; v < n; v++) - { - var p = new Vector3(shape.Positions[v].x, shape.Positions[v].y, shape.Positions[v].z); - var f = new Vector3(shape.Normals[v].x, shape.Normals[v].y, shape.Normals[v].z); - float wa = shape.WeightA[v]; - skinned[v] = world[shape.BoneA[v]] * p * wa + world[shape.BoneB[v]] * p * (1f - wa); - turned[v] = (world[shape.BoneA[v]].Basis * f * wa + world[shape.BoneB[v]].Basis * f * (1f - wa)).Normalized(); - } - - // Depth raster: the nearest triangle under each pixel centre, with its barycentrics. - var origin = camera.GlobalPosition; var basis = camera.GlobalBasis; - float tanHalf = Mathf.Tan(Mathf.DegToRad(camera.Fov) / 2f), aspect = (float)w / h; - Vector3 Ray(int x, int y) => (basis * new Vector3((2f * (x + 0.5f) / w - 1f) * tanHalf * aspect, -(2f * (y + 0.5f) / h - 1f) * tanHalf, -1f)).Normalized(); - var depth = new float[w * h]; var tri = new int[w * h]; var bary = new Vector3[w * h]; - Array.Fill(depth, float.MaxValue); Array.Fill(tri, -1); - var scale = new Vector2(w, h) / GetViewport().GetVisibleRect().Size; - for (int t = 0; t < n / 3; t++) - { - Vector3 a = skinned[3 * t], b = skinned[3 * t + 1], c = skinned[3 * t + 2]; - var pa = camera.UnprojectPosition(a) * scale; var pb = camera.UnprojectPosition(b) * scale; var pc = camera.UnprojectPosition(c) * scale; - int x0 = Math.Max(0, (int)Math.Floor(Math.Min(pa.X, Math.Min(pb.X, pc.X))) - 1), x1 = Math.Min(w - 1, (int)Math.Ceiling(Math.Max(pa.X, Math.Max(pb.X, pc.X))) + 1); - int y0 = Math.Max(0, (int)Math.Floor(Math.Min(pa.Y, Math.Min(pb.Y, pc.Y))) - 1), y1 = Math.Min(h - 1, (int)Math.Ceiling(Math.Max(pa.Y, Math.Max(pb.Y, pc.Y))) + 1); - Vector3 e1 = b - a, e2 = c - a; - for (int y = y0; y <= y1; y++) - for (int x = x0; x <= x1; x++) - { - var d = Ray(x, y); - var pv = d.Cross(e2); - float det = e1.Dot(pv); - if (Mathf.Abs(det) < 1e-12f) continue; - var tv = origin - a; - float u = tv.Dot(pv) / det; - var qv = tv.Cross(e1); - float vv = d.Dot(qv) / det; - if (u < 0 || vv < 0 || u + vv > 1) continue; - float dist = e2.Dot(qv) / det; - if (dist <= 0 || dist >= depth[y * w + x]) continue; - depth[y * w + x] = dist; tri[y * w + x] = t; bary[y * w + x] = new Vector3(1 - u - vv, u, vv); - } - } - - float bevel = Look.BevelWidth; - var errors = new System.Collections.Generic.List(); var band = new System.Collections.Generic.List(); var bandTilt = new System.Collections.Generic.List(); - for (int y = 1; y < h - 1; y++) - for (int x = 1; x < w - 1; x++) - { - int t = tri[y * w + x]; - if (t < 0) continue; - bool interior = true; - for (int dy = -1; dy <= 1 && interior; dy++) for (int dx = -1; dx <= 1; dx++) if (tri[(y + dy) * w + x + dx] != t) { interior = false; break; } - if (!interior) continue; - var bc = bary[y * w + x]; - var a = skinned[3 * t]; var b = skinned[3 * t + 1]; var c = skinned[3 * t + 2]; - var nf = (turned[3 * t] * bc.X + turned[3 * t + 1] * bc.Y + turned[3 * t + 2] * bc.Z).Normalized(); - // The bind altitudes give the distances; the skinned triangle gives the directions. - var bind = new[] { shape.Positions[3 * t], shape.Positions[3 * t + 1], shape.Positions[3 * t + 2] }; - float twiceArea = CultMath.math.length(CultMath.math.cross(bind[1] - bind[0], bind[2] - bind[0])); - var alt = new float[3]; var corner = new[] { a, b, c }; - for (int k = 0; k < 3; k++) alt[k] = twiceArea / CultMath.math.length(bind[(k + 1) % 3] - bind[(k + 2) % 3]); - float width = Mathf.Min(bevel, 0.5f * Mathf.Min(alt[0], Mathf.Min(alt[1], alt[2]))); - var tilt = Vector3.Zero; bool inBand = false; - var triNormal = (b - a).Cross(c - a).Normalized(); - for (int k = 0; k < 3; k++) - { - float d = bc[k] * alt[k]; - float crease = shape.Crease[3 * t + k]; - if (crease == 0f || width <= 0f) continue; - var edge = corner[(k + 2) % 3] - corner[(k + 1) % 3]; - var inward = triNormal.Cross(edge).Normalized(); - if (inward.Dot(corner[k] - corner[(k + 1) % 3]) < 0) inward = -inward; - float s = 1f - Mathf.SmoothStep(0f, width, d); - tilt += s * Mathf.Tan(Mathf.Clamp(crease, -1.4f, 1.4f)) * inward; - if (d < 0.6f * bevel && Mathf.Abs(crease) > 0.1f) inBand = true; - } - var reference = (nf - tilt).Normalized(); - var px = image.GetPixel(x, y); - var drawn = (basis * new Vector3(px.R * 2f - 1f, px.G * 2f - 1f, px.B * 2f - 1f)).Normalized(); - float err = Mathf.RadToDeg(Mathf.Acos(Mathf.Clamp(drawn.Dot(reference), -1f, 1f))); - errors.Add(err); - if (inBand) { band.Add(err); bandTilt.Add(Mathf.RadToDeg(Mathf.Acos(Mathf.Clamp(reference.Dot(nf), -1f, 1f)))); } - } - errors.Sort(); band.Sort(); bandTilt.Sort(); - float p90 = errors.Count == 0 ? float.MaxValue : errors[(int)(errors.Count * 0.9f)]; - float bandMedian = band.Count == 0 ? float.MaxValue : band[band.Count / 2]; - float tiltMedian = bandTilt.Count == 0 ? 0 : bandTilt[bandTilt.Count / 2]; - GD.Print($"RENDER normals: p90 error {p90:F2} deg over {errors.Count} interior pixels; band median error {bandMedian:F2} deg over {band.Count} pixels, reference tilt from the facet {tiltMedian:F1} deg"); - bool ok = true; - if (errors.Count < MinKept || band.Count < MinBand) { GD.PrintErr($"RENDER FAIL: the normal check reached {errors.Count} interior and {band.Count} band pixels, under {MinKept} and {MinBand}; it proves nothing"); ok = false; } - if (tiltMedian < MinBandTilt) { GD.PrintErr($"RENDER FAIL: the bevel band's reference normal is {tiltMedian:F1} degrees from the facet's, under {MinBandTilt}; the check cannot see a bevel"); ok = false; } - if (p90 > MaxNormalP90) { GD.PrintErr($"RENDER FAIL: the drawn shading normal is {p90:F2} degrees from the CPU reference at the 90th percentile, over {MaxNormalP90}"); ok = false; } - if (bandMedian > MaxBandMedian) { GD.PrintErr($"RENDER FAIL: across the bevel band the drawn normal is {bandMedian:F2} degrees from the CPU reference (median), over {MaxBandMedian}; the bevel is not where or as large as the creases say"); ok = false; } return ok; }