diff --git a/Assets/Scripts/ServerShared/Delaunay.cs b/Assets/Scripts/ServerShared/Delaunay.cs index b6a25bba6..f791a8d41 100644 --- a/Assets/Scripts/ServerShared/Delaunay.cs +++ b/Assets/Scripts/ServerShared/Delaunay.cs @@ -1,17 +1,34 @@ using System; using System.Collections.Generic; +using System.Numerics; using CultMath; // The Delaunay triangulation of a galaxy's zone positions, as the edges Galaxy links zones along. Bowyer-Watson -// (Bowyer 1981, Watson 1981) in double precision: each point is inserted by removing every triangle whose -// circumcircle holds it and fanning the cavity's boundary to it. Every point lands in the triangulation, so for two or -// more distinct points the edge graph is connected. +// (Bowyer 1981, Watson 1981): each point is inserted by removing every triangle whose circumcircle strictly holds it and +// fanning the cavity's boundary to it. The orientation and in-circle predicates are exact: a double-precision +// determinant answers when it clears its rounding-error bound (Shewchuk 1997), otherwise the determinant is evaluated +// in BigInteger, since every double is a dyadic rational. For two or more distinct points the edge graph is connected: +// collinear points link each to its neighbour along the line; duplicate or non-finite points throw. public static class Delaunay { // Each edge once, as (lower index, higher index), in ascending order. public static List<(int a, int b)> Edges(IReadOnlyList points) { var n = points.Count; + var order = new int[n]; + for (var i = 0; i < n; i++) + { + if (!float.IsFinite(points[i].x) || !float.IsFinite(points[i].y)) + throw new ArgumentException($"Delaunay point {i} is not finite: ({points[i].x}, {points[i].y})"); + order[i] = i; + } + // Lexicographic order runs along any line, and puts equal points side by side. + Array.Sort(order, (i, j) => points[i].x != points[j].x ? points[i].x.CompareTo(points[j].x) : points[i].y.CompareTo(points[j].y)); + for (var i = 1; i < n; i++) + if (points[order[i - 1]].x == points[order[i]].x && points[order[i - 1]].y == points[order[i]].y) + throw new ArgumentException($"Delaunay points {Math.Min(order[i - 1], order[i])} and {Math.Max(order[i - 1], order[i])} are the same point ({points[order[i]].x}, {points[order[i]].y})"); + if (n < 2) return new List<(int a, int b)>(); + var x = new double[n + 3]; var y = new double[n + 3]; double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue; @@ -25,9 +42,22 @@ public static class Delaunay maxY = Math.Max(maxY, y[i]); } - // A super-triangle far outside the points, so its vertices bend no edge between them; its triangles are - // dropped at the end. - var size = Math.Max(Math.Max(maxX - minX, maxY - minY), 1e-6) * 1000; + var collinear = true; + for (var i = 2; i < n && collinear; i++) + collinear = Orientation(x, y, order[0], order[1], order[i]) == 0; + if (collinear) + { + var line = new List<(int a, int b)>(); + for (var i = 1; i < n; i++) line.Add(Ordered(order[i - 1], order[i])); + line.Sort(); + return line; + } + + // A super-triangle so far outside the points that its vertices bend no edge between them: a float's coordinates + // are multiples of 2^-149, so a triple of distinct non-collinear points has circumradius under extent^3 * 2^300, + // which 2^700 * extent exceeds for any extent a float holds. Its triangles are dropped at the end. Its + // coordinates overflow the double determinants, which then fail every comparison and fall to the exact path. + var size = Math.Max(maxX - minX, maxY - minY) * Math.Pow(2, 700); double midX = (minX + maxX) / 2, midY = (minY + maxY) / 2; x[n] = midX - size; y[n] = midY - size; x[n + 1] = midX + size; y[n + 1] = midY - size; @@ -41,9 +71,7 @@ public static class Delaunay for (var t = triangles.Count - 1; t >= 0; t--) { var triangle = triangles[t]; - var dx = x[p] - triangle.CenterX; - var dy = y[p] - triangle.CenterY; - if (dx * dx + dy * dy >= triangle.RadiusSquared) continue; + if (InCircle(x, y, triangle.A, triangle.B, triangle.C, p) * triangle.Orientation <= 0) continue; Count(cavity, triangle.A, triangle.B); Count(cavity, triangle.B, triangle.C); Count(cavity, triangle.C, triangle.A); @@ -79,19 +107,90 @@ public static class Delaunay private readonly struct Triangle { public readonly int A, B, C; - public readonly double CenterX, CenterY, RadiusSquared; + // +1 if A, B, C run counter-clockwise, -1 if clockwise; a triangle never has zero area. + public readonly int Orientation; public Triangle(int a, int b, int c, double[] x, double[] y) { A = a; B = b; C = c; - double ax = x[a], ay = y[a], bx = x[b], by = y[b], cx = x[c], cy = y[c]; - var d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)); - double a2 = ax * ax + ay * ay, b2 = bx * bx + by * by, c2 = cx * cx + cy * cy; - CenterX = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d; - CenterY = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d; - RadiusSquared = (ax - CenterX) * (ax - CenterX) + (ay - CenterY) * (ay - CenterY); + Orientation = Delaunay.Orientation(x, y, a, b, c); + if (Orientation == 0) throw new InvalidOperationException($"Delaunay built a zero-area triangle on points {a}, {b}, {c}"); + } + } + + // Shewchuk's error bounds for the double-precision determinants: (3 + 16e)e and (10 + 96e)e, e = 2^-53. + private const double OrientationBound = 3.3306690738754716e-16; + private const double InCircleBound = 1.1102230246251577e-15; + + // The sign of the area a, b, c span: +1 counter-clockwise, -1 clockwise, 0 collinear. + private static int Orientation(double[] x, double[] y, int a, int b, int c) + { + var left = (x[a] - x[c]) * (y[b] - y[c]); + var right = (y[a] - y[c]) * (x[b] - x[c]); + var det = left - right; + var bound = OrientationBound * (Math.Abs(left) + Math.Abs(right)); + if (det > bound) return 1; + if (-det > bound) return -1; + var exact = Exact.Of(x, y, a, b, c); + return (exact[0] * exact[3] - exact[1] * exact[2]).Sign; + } + + // The sign of the in-circle determinant: +1 when p is strictly inside the circle through a, b, c taken + // counter-clockwise, -1 strictly outside, 0 on it. + private static int InCircle(double[] x, double[] y, int a, int b, int c, int p) + { + double adx = x[a] - x[p], ady = y[a] - y[p], bdx = x[b] - x[p], bdy = y[b] - y[p], cdx = x[c] - x[p], cdy = y[c] - y[p]; + double abL = adx * bdy, abR = bdx * ady, bcL = bdx * cdy, bcR = cdx * bdy, caL = cdx * ady, caR = adx * cdy; + double alift = adx * adx + ady * ady, blift = bdx * bdx + bdy * bdy, clift = cdx * cdx + cdy * cdy; + var det = alift * (bcL - bcR) + blift * (caL - caR) + clift * (abL - abR); + var permanent = (Math.Abs(bcL) + Math.Abs(bcR)) * alift + (Math.Abs(caL) + Math.Abs(caR)) * blift + (Math.Abs(abL) + Math.Abs(abR)) * clift; + var bound = InCircleBound * permanent; + if (det > bound) return 1; + if (-det > bound) return -1; + var e = Exact.Of(x, y, a, b, c, p); + BigInteger ax = e[0], ay = e[1], bx = e[2], by = e[3], cx = e[4], cy = e[5]; + return (e[6] * (bx * cy - cx * by) + e[7] * (cx * ay - ax * cy) + e[8] * (ax * by - bx * ay)).Sign; + } + + // Coordinates exactly, as integers in units of the smallest binary exponent among them. + private static class Exact + { + // Orientation: [a.x - c.x, a.y - c.y, b.x - c.x, b.y - c.y] with the cross product the caller takes. + public static BigInteger[] Of(double[] x, double[] y, int a, int b, int c) + { + var v = Scaled(new[] { x[a], y[a], x[b], y[b], x[c], y[c] }); + return new[] { v[0] - v[4], v[1] - v[5], v[2] - v[4], v[3] - v[5] }; + } + + // In-circle: [a - p (x, y), b - p, c - p, then each one's squared length]. + public static BigInteger[] Of(double[] x, double[] y, int a, int b, int c, int p) + { + var v = Scaled(new[] { x[a], y[a], x[b], y[b], x[c], y[c], x[p], y[p] }); + BigInteger adx = v[0] - v[6], ady = v[1] - v[7], bdx = v[2] - v[6], bdy = v[3] - v[7], cdx = v[4] - v[6], cdy = v[5] - v[7]; + return new[] { adx, ady, bdx, bdy, cdx, cdy, adx * adx + ady * ady, bdx * bdx + bdy * bdy, cdx * cdx + cdy * cdy }; + } + + private static BigInteger[] Scaled(double[] values) + { + var mantissa = new long[values.Length]; + var exponent = new int[values.Length]; + var lowest = int.MaxValue; + for (var i = 0; i < values.Length; i++) + { + var bits = BitConverter.DoubleToInt64Bits(values[i]); + var biased = (int) ((bits >> 52) & 0x7FF); + var fraction = bits & 0xFFFFFFFFFFFFFL; + mantissa[i] = biased == 0 ? fraction : fraction | (1L << 52); + exponent[i] = biased == 0 ? -1074 : biased - 1075; + if (bits < 0) mantissa[i] = -mantissa[i]; + if (mantissa[i] != 0) lowest = Math.Min(lowest, exponent[i]); + } + var scaled = new BigInteger[values.Length]; + for (var i = 0; i < values.Length; i++) + scaled[i] = mantissa[i] == 0 ? BigInteger.Zero : new BigInteger(mantissa[i]) << (exponent[i] - lowest); + return scaled; } } } diff --git a/Assets/Scripts/ServerShared/Galaxy.cs b/Assets/Scripts/ServerShared/Galaxy.cs index 929fa3493..5befe2ad5 100644 --- a/Assets/Scripts/ServerShared/Galaxy.cs +++ b/Assets/Scripts/ServerShared/Galaxy.cs @@ -451,6 +451,21 @@ public class Galaxy } } + // A zone no link reaches would throw far from here, placing homes or the entrance; refuse it where it is made. + public static void RequireEveryZoneLinked(GalaxyZone[] zones, IEnumerable<(GalaxyZone, GalaxyZone)> links) + { + if (zones.Length < 2) return; + var linked = new HashSet(); + foreach (var link in links) + { + linked.Add(link.Item1); + linked.Add(link.Item2); + } + var stranded = zones.Where(zone => !linked.Contains(zone)).ToList(); + if (stranded.Count > 0) + throw new InvalidOperationException($"Triangulation left {stranded.Count} of {zones.Length} zones unlinked, first at {stranded[0].Position}"); + } + private void GenerateLinks(float linkDensity, Action progressCallback = null) { progressCallback?.Invoke("Triangulating Zone Positions"); @@ -460,6 +475,7 @@ public class Galaxy var links = Delaunay.Edges(Zones.Select(z => z.Position).ToArray()) .Select(edge => (Zones[edge.a], Zones[edge.b])) .ToList(); + RequireEveryZoneLinked(Zones, links); progressCallback?.Invoke("Eliminating Zone Links"); if (progressCallback != null) Thread.Sleep(500); // Inserting Delay to make it seem like it's doing more work lmao diff --git a/tests/Aetheria.Shared.Tests/DelaunayTests.cs b/tests/Aetheria.Shared.Tests/DelaunayTests.cs new file mode 100644 index 000000000..573579ba4 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/DelaunayTests.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using System.Threading.Tasks; +using CultMath; +using Xunit; +using static CultMath.math; + +// Delaunay.Edges is exact: it agrees with an empty-circumcircle oracle evaluated in BigInteger, and degenerate input +// either links correctly or throws. +public sealed class DelaunayTests +{ + // Every edge of a triangle whose circumcircle holds no other point strictly inside, evaluated exactly. When no + // empty circle has a point on it the triangulation is unique and these are its edges; otherwise they are a superset. + internal static (SortedSet<(int a, int b)> Edges, bool Unique) Oracle(IReadOnlyList points) + { + var n = points.Count; + var raw = new (BigInteger m, int e)[n, 2]; + var lowest = int.MaxValue; + for (var i = 0; i < n; i++) + for (var axis = 0; axis < 2; axis++) + { + var bits = BitConverter.SingleToInt32Bits(axis == 0 ? points[i].x : points[i].y); + var biased = (bits >> 23) & 0xFF; + var m = biased == 0 ? bits & 0x7FFFFF : (bits & 0x7FFFFF) | 0x800000; + raw[i, axis] = (bits < 0 ? -m : m, biased == 0 ? -149 : biased - 150); + if (m != 0) lowest = Math.Min(lowest, raw[i, axis].e); + } + var px = new BigInteger[n]; + var py = new BigInteger[n]; + for (var i = 0; i < n; i++) + { + px[i] = raw[i, 0].m << Math.Max(0, raw[i, 0].e - lowest); + py[i] = raw[i, 1].m << Math.Max(0, raw[i, 1].e - lowest); + } + + var edges = new SortedSet<(int a, int b)>(); + var unique = true; + for (var i = 0; i < n; i++) + for (var j = i + 1; j < n; j++) + for (var k = j + 1; k < n; k++) + { + var orient = (px[i] - px[k]) * (py[j] - py[k]) - (py[i] - py[k]) * (px[j] - px[k]); + if (orient.IsZero) continue; + var inside = false; + var onCircle = false; + for (var m = 0; m < n && !inside; m++) + { + if (m == i || m == j || m == k) continue; + BigInteger adx = px[i] - px[m], ady = py[i] - py[m], bdx = px[j] - px[m], bdy = py[j] - py[m], cdx = px[k] - px[m], cdy = py[k] - py[m]; + var det = (adx * adx + ady * ady) * (bdx * cdy - cdx * bdy) + (bdx * bdx + bdy * bdy) * (cdx * ady - adx * cdy) + + (cdx * cdx + cdy * cdy) * (adx * bdy - bdx * ady); + var sign = det.Sign * orient.Sign; + inside = sign > 0; + onCircle |= sign == 0; + } + if (inside) continue; + unique &= !onCircle; + edges.Add((i, j)); + edges.Add((j, k)); + edges.Add((i, k)); + } + return (edges, unique); + } + + // The triangulation lies within the oracle's edges, and equals them when the oracle's answer is unique. + internal static void AssertDelaunay(IReadOnlyList points, string context) + { + var edges = Delaunay.Edges(points); + var (oracle, unique) = Oracle(points); + Assert.True(edges.All(oracle.Contains), $"{context}: edge outside the Delaunay set: {string.Join(" ", edges.Where(e => !oracle.Contains(e)))}"); + if (unique) + Assert.True(oracle.SetEquals(edges), $"{context}: missed Delaunay edges: {string.Join(" ", oracle.Where(e => !edges.Contains(e)))}"); + Assert.Equal(points.Count, edges.SelectMany(e => new[] { e.a, e.b }).Distinct().Count()); + } + + // Distinct points on a 1/1024 lattice inside [0, 1024), then lifted by offset. + private static float2[] RandomPoints(int seed, int count, float offset = 0) + { + var random = new System.Random(seed); + var seen = new HashSet<(int, int)>(); + var points = new List(); + while (points.Count < count) + { + (int, int) cell = (random.Next(1 << 20), random.Next(1 << 20)); + if (seen.Add(cell)) points.Add(float2(cell.Item1 / 1024f + offset, cell.Item2 / 1024f + offset)); + } + return points.ToArray(); + } + + // Kills: the plain double-precision in-circle (a seed in 0..400 that missed a true edge), the filter bound too small. + [Fact] + public void TwoHundredRandomSetsOf64PointsAreExactlyDelaunay() + { + Parallel.For(0, 200, seed => AssertDelaunay(RandomPoints(seed, 64), $"seed {seed}")); + } + + // The seeds the double-precision predicate got wrong (found sweeping 0..400 on the old code: 42 and 184), by name. + // Kills: the plain double-precision in-circle. + [Theory] + [InlineData(42)] + [InlineData(184)] + public void SeedsTheDoublePredicateMissedStayExact(int seed) => AssertDelaunay(RandomPoints(seed, 64), $"seed {seed}"); + + // Kills: the filter bound too small (it answers wrongly where the double determinant is within rounding of zero). + [Fact] + public void NearlyCocircularPointsChooseTheTrueDiagonal() + { + // Eight lattice points exactly on a circle, then one nudged by an ulp inward and outward. + var circle = new[] { (5f, 0f), (-5f, 0f), (0f, 5f), (0f, -5f), (3f, 4f), (-3f, 4f), (3f, -4f), (-3f, -4f), (4f, 3f), (-4f, 3f), (4f, -3f), (-4f, -3f) }; + foreach (var nudge in new[] { 0, 1, -1 }) + foreach (var scale in new[] { 1f, 1e4f, 1e-3f }) + for (var which = 0; which < circle.Length; which++) + { + var points = circle.Select(p => float2(p.Item1 * scale, p.Item2 * scale)).ToArray(); + if (nudge != 0 && points[which].x != 0) + points[which] = float2(BitConverter.Int32BitsToSingle(BitConverter.SingleToInt32Bits(points[which].x) + nudge), points[which].y); + AssertDelaunay(points, $"nudge {nudge} scale {scale} point {which}"); + } + } + + // Kills: no offset-safe predicate (squares of 1e6-sized coordinates drown the differences in double precision). + [Fact] + public void LargeCoordinateOffsetsStayExact() + { + Parallel.For(0, 40, seed => + { + AssertDelaunay(RandomPoints(seed, 64, 1e6f), $"offset 1e6 seed {seed}"); + AssertDelaunay(RandomPoints(seed, 32, -3e7f), $"offset -3e7 seed {seed}"); + }); + } + + // A lattice is cocircular everywhere: every edge is a true one and every point is linked. + [Fact] + public void ALatticeLinksEveryPointAlongTrueEdges() + { + var grid = new List(); + for (var i = 0; i < 6; i++) + for (var j = 0; j < 6; j++) + grid.Add(float2(i * 100 + 1e6f, j * 100 + 1e6f)); + AssertDelaunay(grid, "lattice"); + var linked = Delaunay.Edges(grid).SelectMany(e => new[] { e.a, e.b }).ToHashSet(); + Assert.Equal(grid.Count, linked.Count); + } + + // Kills: the guard on fewer than two points, the collinear branch dropped (every triangle then holds a super-vertex + // and nothing links). + [Fact] + public void DegenerateInputGivesTheSpecifiedOutcome() + { + Assert.Empty(Delaunay.Edges(new float2[0])); + Assert.Empty(Delaunay.Edges(new[] { float2(3, 4) })); + Assert.Equal(new[] { (0, 1) }, Delaunay.Edges(new[] { float2(3, 4), float2(-1, 2) })); + + // Collinear: each point links to its neighbour along the line, whatever the index order and slope. + var line = new[] { float2(30, 15), float2(0, 0), float2(20, 10), float2(10, 5), float2(-10, -5) }; + Assert.Equal(new[] { (0, 2), (1, 3), (1, 4), (2, 3) }, Delaunay.Edges(line)); + var vertical = new[] { float2(7, 2), float2(7, -9), float2(7, 40) }; + Assert.Equal(new[] { (0, 1), (0, 2) }, Delaunay.Edges(vertical)); + // Exactly collinear off the axes, where a double cross product need not be zero. + var slanted = Enumerable.Range(0, 20).Select(i => float2(1e6f + i, 3e6f + 3 * i)).ToArray(); + Assert.Equal(19, Delaunay.Edges(slanted).Count); + } + + // Kills: the duplicate check. + [Fact] + public void DuplicatePointsAreRefusedByIndex() + { + var exception = Assert.Throws(() => Delaunay.Edges(new[] { float2(0, 0), float2(5, 5), float2(9, 1), float2(5, 5) })); + Assert.Contains("points 1 and 3", exception.Message); + Assert.Throws(() => Delaunay.Edges(new[] { float2(1, 1), float2(1, 1) })); + Assert.Throws(() => Delaunay.Edges(new[] { float2(0, 0), float2(float.NaN, 1), float2(2, 2) })); + } + + // Kills: the Galaxy guard removed. + [Fact] + public void GalaxyRefusesAZoneNoLinkReaches() + { + var zones = new[] { new GalaxyZone { Position = float2(0, 0) }, new GalaxyZone { Position = float2(1, 0) }, new GalaxyZone { Position = float2(2, 5) } }; + var exception = Assert.Throws(() => Galaxy.RequireEveryZoneLinked(zones, new[] { (zones[0], zones[1]) })); + Assert.Contains("1 of 3 zones", exception.Message); + Galaxy.RequireEveryZoneLinked(zones, new[] { (zones[0], zones[1]), (zones[1], zones[2]) }); + Galaxy.RequireEveryZoneLinked(new[] { zones[0] }, new (GalaxyZone, GalaxyZone)[0]); + } +} diff --git a/tests/Aetheria.Shared.Tests/ScenarioTests.cs b/tests/Aetheria.Shared.Tests/ScenarioTests.cs index f7a8f6a78..3be4c5c0e 100644 --- a/tests/Aetheria.Shared.Tests/ScenarioTests.cs +++ b/tests/Aetheria.Shared.Tests/ScenarioTests.cs @@ -220,7 +220,7 @@ public sealed partial class RunStartTests // Every zone is linked into one graph. These seeds left zones with no link at all (the vendored float-precision // convex-hull triangulation dropped them), so the constructor threw KeyNotFoundException placing homes (prelude) // or the entrance (main). Each galaxy's links are a subset of its zone positions' Delaunay edges, and the - // triangulation agrees with a brute-force empty-circumcircle oracle. + // triangulation agrees with DelaunayTests' exact empty-circumcircle oracle. [Theory] [InlineData(103u, true)] [InlineData(134u, true)] @@ -236,7 +236,7 @@ public sealed partial class RunStartTests var positions = galaxy.Zones.Select(zone => zone.Position).ToArray(); var edges = Delaunay.Edges(positions); - Assert.Equal(BruteForceDelaunay(positions), edges); + DelaunayTests.AssertDelaunay(positions, $"seed {seed}"); var delaunay = new HashSet<(int, int)>(edges); for (var i = 0; i < galaxy.Zones.Length; i++) foreach (var adjacent in galaxy.Zones[i].AdjacentZones) @@ -246,36 +246,6 @@ public sealed partial class RunStartTests } } - // Every triangle whose circumcircle holds no other point, as sorted edges. - private static List<(int a, int b)> BruteForceDelaunay(float2[] points) - { - var edges = new SortedSet<(int a, int b)>(); - for (var i = 0; i < points.Length; i++) - for (var j = i + 1; j < points.Length; j++) - for (var k = j + 1; k < points.Length; k++) - { - double ax = points[i].x, ay = points[i].y, bx = points[j].x, by = points[j].y, cx = points[k].x, cy = points[k].y; - var d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)); - if (d == 0) continue; - double a2 = ax * ax + ay * ay, b2 = bx * bx + by * by, c2 = cx * cx + cy * cy; - var ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d; - var uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d; - var r2 = (ax - ux) * (ax - ux) + (ay - uy) * (ay - uy); - var empty = true; - for (var m = 0; m < points.Length && empty; m++) - if (m != i && m != j && m != k) - { - double dx = points[m].x - ux, dy = points[m].y - uy; - empty = dx * dx + dy * dy >= r2; - } - if (!empty) continue; - edges.Add((i, j)); - edges.Add((j, k)); - edges.Add((i, k)); - } - return edges.ToList(); - } - // A scenario naming one unknown design admits nothing, not even the parts that built, and names the design. [Fact] public void StagingIsAllOrNothing()