diff --git a/Assets/Scripts/Editor/IsolineExtractSmoke.cs b/Assets/Scripts/Editor/IsolineExtractSmoke.cs index 5a126913c..93e439ea1 100644 --- a/Assets/Scripts/Editor/IsolineExtractSmoke.cs +++ b/Assets/Scripts/Editor/IsolineExtractSmoke.cs @@ -15,7 +15,7 @@ using Debug = UnityEngine.Debug; namespace Aetheria.EditorTools { /// - /// Batchmode check for campaign aetheria-release, cuts isoline-extraction and isoline-s-from-exact-curvature: + /// Batchmode check for campaign aetheria-release, cuts isoline-extraction and isoline-chain-arclength: /// IsolineExtract.compute evaluates a gravity field in closed form from its lowered wells and writes the segments of its /// contours and iso-angle rays into IsolineExtractor's buffer. Each check reads the buffer back (here only; the runtime /// never reads back) and compares it with what the field says: the real zone's own lowered terms, judged by Zone.GetHeight, @@ -31,7 +31,6 @@ namespace Aetheria.EditorTools public static class IsolineExtractSmoke { const string Tag = "[IsolineExtractSmoke]"; - const float RhoMax = 500f; const float SlopeEpsilon = 1e-3f; const int Contours = 21; @@ -41,29 +40,14 @@ namespace Aetheria.EditorTools // Contour endpoint's |-GetHeight - level|, in level spacings, over the real zone: shipped worst 0.0705, least mutant // (crossing at the edge midpoint) 0.512, separation 7.25. Re-set on the analytic sample if the run moves them. const float LevelErrorBound = 0.19f; - // Ring ratio sum|ds| / sum(length) minus 1, worst over a profile's rings, on the softened log wells (rho = r exactly): - // shipped worst 5.3e-4; least mutant (rho = d / |grad d|, tight well) 0.715, separation 37; the raw-theta mutant reads 0.99. - const float ArcRatioBound = 0.0195f; - // Ray endpoint |s / r - 1| on the same wells: shipped worst 5.4e-4; least mutant (rho = d / |grad d|) 0.697, separation 36. - const float RayRhoBound = 0.0194f; // Ray endpoint's angle off its level, rad: shipped worst 4.0e-4; least mutant (levels half a step off) 0.262, separation 25. const float RayAngleBound = 0.0103f; // Endpoint depth |depth / d(r) - 1| and slope |slope / |d'(r)| - 1| on the radial wells: shipped worst 3.5e-4 and 1.1e-3. // The bounds are the previous fixtures' (their mutants were read on the texture path and not re-read on the well fixtures). const float DepthBound = 0.0049f; const float SlopeBound = 0.0133f; - // Share of the real zone's rays or contours carrying the rho-clamp bit at RhoMax = the zone's radius. - const float ClampedBound = 0.13f; - // Share of unclamped real-zone rays whose s rises with depth. - const float WrongWayBound = 0.226f; // The analytic sample against the law: d within GravityFieldParityVerify.Tolerance (0.03 u), the gradient angle within its - // GradientDegrees (3) where |grad| exceeds its FlatForce (1e-3): the parity verify's own ruled ceilings. kappa through rho - // = 1 / |kappa| against the CPU closed form in double over the same records, worst relative error over unclamped samples - // where |grad| > FlatForce: shipped worst 0.0023 (real zone), least mutant PullSlope = 0 13.1 (the saddle fixture; the - // real zone reads 150), sqrt(0.0023 x 13.1) = 0.174, separation 75. On a radial well kappa does not depend on PullSlope, - // so the radial fixtures cannot claim that mutant. - const float AnalyticRhoBound = 0.174f; - static float _zoneRhoMax; + // GradientDegrees (3) where |grad| exceeds its FlatForce (1e-3): the parity verify's own ruled ceilings. static bool _ok = true; static string _out; @@ -83,7 +67,7 @@ namespace Aetheria.EditorTools public IsolineExtractor.IsoSegment[] Segments; // the written ones public IsolineExtractor.IsoSegment[] Backing; // the whole buffer public uint Written, Requested; - public Vector4[] Samples; // (gx, gy, d, rho) per sample, row-major + public Vector4[] Samples; // (gx, gy, d, |g|) per sample, row-major } static ComputeShader Shader => AssetDatabase.LoadAssetAtPath("Assets/Shaders/IsolineExtract.compute") @@ -115,29 +99,21 @@ namespace Aetheria.EditorTools return records.Take(terms.Count).ToArray(); } - // d = -height, grad d and the Hessian of d at p, in double, from GravityField over the records: the same closed form the - // shader evaluates. mutantSlope replaces PullSlope by 0 (the mutant the kappa bound is set against). - internal static void CpuSample(GravityLowering.TermRecord[] records, float exaggeration, Vector2 p, bool mutantSlope, - out double d, out double gx, out double gy, out double hxx, out double hxy, out double hyy) + // d = -height and grad d at p, in double, from GravityField over the records: the same closed form the shader evaluates. + internal static void CpuSample(GravityLowering.TermRecord[] records, float exaggeration, Vector2 p, out double d, out double gx, out double gy) { double height = 0; - gx = gy = hxx = hxy = hyy = 0; + gx = gy = 0; foreach (var t in records) { double ox = p.x - (double)t.Position.x, oy = p.y - (double)t.Position.y; var r = Math.Sqrt(ox * ox + oy * oy); if (!(r < t.Outer)) continue; height += t.Strength * (double)GravityField.Potential(t.Softening, t.Inner, t.Outer, (float)r) - t.Reference; - var k = -(double)t.Strength / exaggeration; - var slope = mutantSlope ? 0.0 : GravityField.PullSlope(t.Softening, t.Inner, t.Outer, (float)r); - if (r < 1e-6 * t.Softening || r < 1e-20) { hxx += k * slope; hyy += k * slope; continue; } - var pull = (double)GravityField.Pull(t.Softening, t.Inner, t.Outer, (float)r); - double ux = ox / r, uy = oy / r, turn = pull / r; - gx += k * pull * ux; - gy += k * pull * uy; - hxx += k * (slope * ux * ux + turn * (1 - ux * ux)); - hxy += k * (slope - turn) * ux * uy; - hyy += k * (slope * uy * uy + turn * (1 - uy * uy)); + if (r < 1e-20) continue; + var k = -(double)t.Strength / exaggeration * GravityField.Pull(t.Softening, t.Inner, t.Outer, (float)r) / r; + gx += k * ox; + gy += k * oy; } d = -height / exaggeration; } @@ -200,8 +176,6 @@ namespace Aetheria.EditorTools static bool IsRay(uint key) => ((key >> 8) & 1u) != 0; static int LevelOf(uint key) => (int)(key & 0xFFu); - static bool Seam(uint key) => (key & (1u << 9)) != 0; - static bool Clamped(uint key) => (key & (1u << 10)) != 0; static float Length(IsolineExtractor.IsoSegment s) => (s.b - s.a).magnitude; // ---- entry ------------------------------------------------------------------------------------------------------- @@ -268,7 +242,7 @@ namespace Aetheria.EditorTools // A 2 x 2 grid under one well whose single cell holds exactly one contour segment, with every field of it known from the // CPU closed form over the same record: the C# struct is 48 bytes and each field the shader wrote lands in the field the - // C# side reads. RhoMax 10 sits below the contour's radius (17 to 20 u), so the rho-clamp bit is set. + // C# side reads. s is 0 on a contour. static void Layout() { var size = Marshal.SizeOf(); @@ -281,24 +255,22 @@ namespace Aetheria.EditorTools var perTexel = new Vector2(2f, 3f); var corners = new[] { Vector2.zero, new Vector2(1f, 0f), new Vector2(1f, 1f), new Vector2(0f, 1f) } .Select(c => origin + new Vector2(c.x * perTexel.x, c.y * perTexel.y)).ToArray(); - var cpu = corners.Select(c => { CpuSample(records, 1f, c, false, out var d, out var gx, out var gy, out _, out _, out _); return (d, gx, gy); }).ToArray(); + var cpu = corners.Select(c => { CpuSample(records, 1f, c, out var d, out var gx, out var gy); return (d, gx, gy); }).ToArray(); var mean = (float)(cpu[0].d + cpu[3].d) / 2f; var spacing = 4f * (float)Math.Abs(cpu[3].d - cpu[0].d); - var levels = new IsolineExtractor.IsolineLevels(mean - spacing, 20f * spacing, 10f, SlopeEpsilon); + var levels = new IsolineExtractor.IsolineLevels(mean - spacing, 20f * spacing, SlopeEpsilon); var result = Extract(terms, origin, perTexel, new Vector2Int(2, 2), levels, 16); if (result.Written != 1 || result.Requested != 1) { Fail("layout", $"expected one segment, written {result.Written} requested {result.Requested}"); return; } var s = result.Segments[0]; void Near(string what, float got, float want, float tolerance = 1e-3f) { if (Math.Abs(got - want) > tolerance) Fail("layout", $"{what}: {got:G8}, expected {want:G8}"); } Near("a.x", s.a.x, 10f); Near("a.y", s.a.y, 21.5f, 2e-3f); Near("b.x", s.b.x, 12f); Near("b.y", s.b.y, 21.5f, 2e-3f); - // edge 3 joins corners 0 and 3 (a), edge 1 joins corners 1 and 2 (b); every value is the clamped rho (10) times the - // corner's angle, unwrapped to corner 0, halfway along the edge - float Theta(int i) => (float)Math.Atan2(-cpu[i].gy, -cpu[i].gx); - float Unwrapped(int i) => Theta(0) + Mathf.DeltaAngle(Theta(0) * Mathf.Rad2Deg, Theta(i) * Mathf.Rad2Deg) * Mathf.Deg2Rad; + // edge 3 joins corners 0 and 3 (a), edge 1 joins corners 1 and 2 (b); the slopes and depths are the corners' halfway + // along the edge, and s is 0 on a contour float Slope(int i) => (float)Math.Sqrt(cpu[i].gx * cpu[i].gx + cpu[i].gy * cpu[i].gy); - Near("sA", s.sA, 10f * (Unwrapped(0) + Unwrapped(3)) / 2f); Near("sB", s.sB, 10f * (Unwrapped(1) + Unwrapped(2)) / 2f); + Near("sA", s.sA, 0f); Near("sB", s.sB, 0f); Near("slopeA", s.slopeA, (Slope(0) + Slope(3)) / 2f, 1e-4f); Near("slopeB", s.slopeB, (Slope(1) + Slope(2)) / 2f, 1e-4f); Near("depthA", s.depthA, mean, 2e-3f); Near("depthB", s.depthB, mean, 2e-3f); - if (s.key != (1u << 10)) Fail("layout", $"key {s.key:X}, expected level 0, contour, no seam, rho clamped (0x400)"); + if (s.key != 0) Fail("layout", $"key {s.key:X}, expected level 0, contour, reserved bits 0"); if (s.cell != 0) Fail("layout", $"cell {s.cell}, expected 0"); Info($"layout: {size} bytes, segment a={s.a} b={s.b} s={s.sA:G6}/{s.sB:G6} slope={s.slopeA:G4}/{s.slopeB:G4} depth={s.depthA:G4}/{s.depthB:G4} key={s.key:X} cell={s.cell}"); } @@ -326,7 +298,7 @@ namespace Aetheria.EditorTools try { var back = ReadRecords(terms); - float D(int x, int y) { CpuSample(back, 1f, Texel(x, y), false, out var d, out _, out _, out _, out _, out _); return (float)d; } + float D(int x, int y) { CpuSample(back, 1f, Texel(x, y), out var d, out _, out _); return (float)d; } var corner = new[] { D(cx, cx), D(cx + 1, cx), D(cx + 1, cx + 1), D(cx, cx + 1) }; var mean = .25f * (corner[0] + corner[1] + corner[2] + corner[3]); var high = Math.Min(corner[0], corner[2]); @@ -335,7 +307,7 @@ namespace Aetheria.EditorTools var delta = .2f * (Math.Min(corner[0], corner[2]) - Math.Max(corner[1], corner[3])); var spacing = 2f * delta; var start = mean - 3.5f * spacing; - var result = Extract(terms, origin, perTexel, new Vector2Int(n, n), new IsolineExtractor.IsolineLevels(start, 20f * spacing, RhoMax, SlopeEpsilon), 1 << 16); + var result = Extract(terms, origin, perTexel, new Vector2Int(n, n), new IsolineExtractor.IsolineLevels(start, 20f * spacing, SlopeEpsilon), 1 << 16); var cell = (uint)(cx * n + cx); // level index 2 is mean - delta (the centre is high), 3 is mean + delta (the centre is low) foreach (var (level, connected) in new[] { (2, true), (3, false) }) @@ -356,7 +328,7 @@ namespace Aetheria.EditorTools Fail("saddle", $"level {level} ({(connected ? "centre high" : "centre low")}): segments cut off corners {{{string.Join(",", cutOff)}}}, expected {{{string.Join(",", want)}}}"); } Info($"saddle: corners {string.Join(", ", corner.Select(c => c.ToString("G6")))} centre mean {mean:G6}"); - SamplesMatchTheLaw("saddle", result, terms, origin, perTexel, new Vector2Int(n, n), RhoMax, null); + SamplesMatchTheLaw("saddle", result, terms, origin, perTexel, new Vector2Int(n, n), null); } finally { Free(terms); } } @@ -411,55 +383,22 @@ namespace Aetheria.EditorTools var (terms, origin, perTexel, centre, start, range) = RadialField(profile); try { - var result = Extract(terms, origin, perTexel, new Vector2Int(GridSize, GridSize), new IsolineExtractor.IsolineLevels(start, range, RhoMax, SlopeEpsilon), 1 << 18); + var result = Extract(terms, origin, perTexel, new Vector2Int(GridSize, GridSize), new IsolineExtractor.IsolineLevels(start, range, SlopeEpsilon), 1 << 18); var contours = result.Segments.Where(s => !IsRay(s.key)).ToArray(); var rays = result.Segments.Where(s => IsRay(s.key)).ToArray(); if (contours.Length < 200 || rays.Length < 100) { Fail("along-line", $"{profile.Name}: {contours.Length} contour and {rays.Length} ray segments, the check would be vacuous"); continue; } - // contours: summed over a level's ring, the change of s over segment length is 1 where s does not wrap (a single - // short segment is dominated by the endpoint interpolation, so the ratio is taken over the ring) - double arcWorst = 0, arcMutant = 0, arcMutantRho = 0; - var arcLevels = 0; - foreach (var ring in contours.Where(s => !Seam(s.key) && !Clamped(s.key) && InBand((s.a + s.b) * .5f - centre)).GroupBy(s => LevelOf(s.key))) - { - double ds = 0, length = 0, rawTheta = 0, dsRho = 0; - foreach (var s in ring) - { - ds += Math.Abs(s.sB - s.sA); - length += Length(s); - // mutant: s = raw theta (the angle itself, no radius): it grows by 1 / r per unit of length - // mutant: rho = d / |grad d| - var thA = Math.Atan2(s.a.y - centre.y, s.a.x - centre.x); - var thB = thA + Mathf.DeltaAngle((float)(thA * Mathf.Rad2Deg), Mathf.Atan2(s.b.y - centre.y, s.b.x - centre.x) * Mathf.Rad2Deg) * Mathf.Deg2Rad; - dsRho += Math.Abs(thB * s.depthB / s.slopeB - thA * s.depthA / s.slopeA); - rawTheta += Math.Abs(Mathf.DeltaAngle(Mathf.Atan2(s.a.y - centre.y, s.a.x - centre.x) * Mathf.Rad2Deg, Mathf.Atan2(s.b.y - centre.y, s.b.x - centre.x) * Mathf.Rad2Deg)) * Mathf.Deg2Rad; - } - arcWorst = Math.Max(arcWorst, Math.Abs(ds / length - 1.0)); - arcMutant = Math.Max(arcMutant, Math.Abs(rawTheta / length - 1.0)); - arcMutantRho = Math.Max(arcMutantRho, Math.Abs(dsRho / length - 1.0)); - arcLevels++; - } - - // rays: s is the distance to the centre; the mutants take rho = d / |grad d|, and levels half a step off - double rhoWorst = 0, rhoMutant = 0, angleWorst = 0, angleMutant = 0, worstAt = 0; - var rayCount = 0; + // rays: each endpoint's angle off its level; the mutant puts the levels half a step off + double angleWorst = 0, angleMutant = 0; var step = 2 * Math.PI / 12; foreach (var s in rays) + foreach (var p in new[] { s.a, s.b }) { - if (Clamped(s.key)) continue; - foreach (var (p, sv, slope, depth) in new[] { (s.a, s.sA, s.slopeA, s.depthA), (s.b, s.sB, s.slopeB, s.depthB) }) - { - var r = (p - centre).magnitude; - if (!InBand(p - centre)) continue; - var error = Math.Abs(sv / r - 1.0); - if (error > rhoWorst) { rhoWorst = error; worstAt = r; } - rhoMutant = Math.Max(rhoMutant, Math.Abs(depth / slope / r - 1.0)); - var theta = Math.Atan2(p.y - centre.y, p.x - centre.x); - double Off(double level) { var diff = Math.Abs(theta - level); return Math.Min(diff, 2 * Math.PI - diff); } - angleWorst = Math.Max(angleWorst, Off((LevelOf(s.key) + .5) * step - Math.PI)); - angleMutant = Math.Max(angleMutant, Off(LevelOf(s.key) * step - Math.PI)); - rayCount++; - } + if (!InBand(p - centre)) continue; + var theta = Math.Atan2(p.y - centre.y, p.x - centre.x); + double Off(double level) { var diff = Math.Abs(theta - level); return Math.Min(diff, 2 * Math.PI - diff); } + angleWorst = Math.Max(angleWorst, Off((LevelOf(s.key) + .5) * step - Math.PI)); + angleMutant = Math.Max(angleMutant, Off(LevelOf(s.key) * step - Math.PI)); } // no ray in the cell that holds the centre var texel = new Vector2((centre.x - origin.x) / perTexel.x, (centre.y - origin.y) / perTexel.y); @@ -467,21 +406,16 @@ namespace Aetheria.EditorTools if (rays.Any(s => s.cell == holding)) Fail("rays", $"{profile.Name}: a ray segment lies in the cell holding the well centre"); EndpointAttributes(profile, result.Segments, centre, origin, perTexel, GridSize); - SamplesMatchTheLaw("radial " + profile.Name, result, terms, origin, perTexel, new Vector2Int(GridSize, GridSize), RhoMax, null); - Continuity("radial " + profile.Name, contours, perTexel); + SamplesMatchTheLaw("radial " + profile.Name, result, terms, origin, perTexel, new Vector2Int(GridSize, GridSize), null); Info($"ray segments per level, {profile.Name}: {string.Join(" ", Enumerable.Range(0, 12).Select(k => rays.Count(r => LevelOf(r.key) == k)))}"); - Info($"along-line {profile.Name}: {contours.Length} contour / {rays.Length} ray segments; arc ratio error worst over {arcLevels} rings {arcWorst:G4} (mutants: raw theta {arcMutant:G4}, rho = d/|g| {arcMutantRho:G4}); ray rho error worst {rhoWorst:G4} at r={worstAt:F1} (mutant d/|g| worst {rhoMutant:G4}, {rayCount} endpoints); ray angle error worst {angleWorst:G4} rad (mutant half-step levels {angleMutant:G4})"); - { - if (arcWorst > ArcRatioBound) Fail("along-line", $"{profile.Name}: contour |ds|/length is off by {arcWorst:G4} > {ArcRatioBound:G4}"); - if (rhoWorst > RayRhoBound) Fail("along-line", $"{profile.Name}: ray s is off the distance by {rhoWorst:G4} > {RayRhoBound:G4}"); - if (angleWorst > RayAngleBound) Fail("rays", $"{profile.Name}: a ray endpoint's angle is off its level by {angleWorst:G4} rad > {RayAngleBound:G4}"); - } + Info($"along-line {profile.Name}: {contours.Length} contour / {rays.Length} ray segments; ray angle error worst {angleWorst:G4} rad (mutant levels half a step off {angleMutant:G4})"); + if (angleWorst > RayAngleBound) Fail("rays", $"{profile.Name}: a ray endpoint's angle is off its level by {angleWorst:G4} rad > {RayAngleBound:G4}"); } finally { Free(terms); } } } - // ---- endpoint attributes, continuity, cell, ray window ----------------------------------------------------------------- + // ---- endpoint attributes, cell, ray window ----------------------------------------------------------------- // Slope and depth at each endpoint, against the profile's own d(r) and |d'(r)|. A ray's depth runs along its edge, so an // end swap or a missing interpolation moves it by far more than the field's sampling error does. Bounds by the margin @@ -522,48 +456,6 @@ namespace Aetheria.EditorTools if (outside != 0) Fail("cell", $"{what}: {outside} segments have an endpoint outside their cell"); } - // The seam bit says s jumps by a full turn between a straddling cell and its neighbour. At every pair of bitwise-equal - // contour endpoints where s jumps, one side must carry the bit; and the field must have jumps (else the check is vacuous). - static void Continuity(string what, IsolineExtractor.IsoSegment[] contours, Vector2 perTexel) - { - var jump = .5f * Math.Max(Math.Abs(perTexel.x), Math.Abs(perTexel.y)); - var seen = new Dictionary<(int, int, int), (float s, bool seam)>(); - int jumps = 0, unflagged = 0; - foreach (var seg in contours) - foreach (var (p, sv) in new[] { (seg.a, seg.sA), (seg.b, seg.sB) }) - { - var key = (LevelOf(seg.key), BitConverter.SingleToInt32Bits(p.x), BitConverter.SingleToInt32Bits(p.y)); - if (seen.TryGetValue(key, out var other)) - { - if (Math.Abs(other.s - sv) > jump) - { - jumps++; - if (!other.seam && !Seam(seg.key)) unflagged++; - } - seen.Remove(key); - } - else seen[key] = (sv, Seam(seg.key)); - } - Info($"continuity {what}: {jumps} jumps in s between shared endpoints, {unflagged} without a seam bit"); - if (jumps == 0) Fail("seam", $"{what}: no jump in s anywhere; the check is vacuous"); - if (unflagged != 0) Fail("seam", $"{what}: {unflagged} jumps in s have no seam-flagged side"); - } - - // s on the real zone: how much of it the rho clamp spoils, and whether it runs the way the flowing dashes need (a - // ray's s falls as it descends toward a well). The mutant (s negated) reads the complement. - static void RealZoneS(IsolineExtractor.IsoSegment[] segments) - { - var rays = segments.Where(s => IsRay(s.key)).ToArray(); - var contours = segments.Where(s => !IsRay(s.key)).ToArray(); - double rayClamped = rays.Count(s => Clamped(s.key)) / (double)rays.Length; - double contourClamped = contours.Count(s => Clamped(s.key)) / (double)contours.Length; - var live = rays.Where(s => !Clamped(s.key) && Math.Abs(s.depthB - s.depthA) > 1e-4f).ToArray(); - var wrong = live.Count(s => (s.sB - s.sA) * (s.depthB - s.depthA) > 0) / (double)live.Length; - Info($"real zone s: rho clamped on {rayClamped:P1} of rays, {contourClamped:P1} of contours (RhoMax {_zoneRhoMax:G5}); {live.Length} unclamped rays, s rises with depth on {wrong:P1} (mutant s negated {1 - wrong:P1})"); - if (rayClamped > ClampedBound || contourClamped > ClampedBound) Fail("real zone s", $"rho is clamped on {rayClamped:P1} of rays, {contourClamped:P1} of contours > {ClampedBound:P0}"); - if (wrong > WrongWayBound) Fail("real zone s", $"s rises with depth on {wrong:P1} of unclamped rays > {WrongWayBound:P0}"); - } - // Rays exist only where the cell reaches the contour window [Start, Start + Range] (IsolinesUI draws none outside it). // Window r 50..90 of the offset well: no ray beyond a cell's reach of it, and rays in the middle of it. static void RayWindow() @@ -574,7 +466,7 @@ namespace Aetheria.EditorTools { var start = (float)profile.D(90); var range = (float)(profile.D(50) - profile.D(90)); - var result = Extract(terms, origin, perTexel, new Vector2Int(GridSize, GridSize), new IsolineExtractor.IsolineLevels(start, range, RhoMax, SlopeEpsilon), 1 << 18); + var result = Extract(terms, origin, perTexel, new Vector2Int(GridSize, GridSize), new IsolineExtractor.IsolineLevels(start, range, SlopeEpsilon), 1 << 18); var rays = result.Segments.Where(s => IsRay(s.key)).ToArray(); var outside = rays.Count(s => new[] { s.a, s.b }.Any(p => (p - centre).magnitude < 44f || (p - centre).magnitude > 96f)); var inside = rays.Count(s => (((s.a + s.b) * .5f) - centre).magnitude is > 60f and < 80f); @@ -592,7 +484,7 @@ namespace Aetheria.EditorTools var (terms, origin, perTexel, _, start, range) = RadialField(Profiles[0]); try { - var levels = new IsolineExtractor.IsolineLevels(start, range, RhoMax, SlopeEpsilon); + var levels = new IsolineExtractor.IsolineLevels(start, range, SlopeEpsilon); var size = new Vector2Int(GridSize, GridSize); var full = Extract(terms, origin, perTexel, size, levels, 1 << 18); var needed = (int)full.Requested; @@ -619,44 +511,28 @@ namespace Aetheria.EditorTools // ---- the analytic sample ---------------------------------------------------------------------------------------------- // Per sample of the grid: d against the law (truthD, Zone.GetHeight for the real zone; the CPU closed form over the same - // records when null), the gradient angle against the CPU closed form, and rho = 1 / |kappa| against the CPU closed form in - // double, with the mutant PullSlope = 0 (the Hessian's radial part dropped) read beside it. + // records when null), the gradient angle against the CPU closed form. static void SamplesMatchTheLaw(string what, Result result, GravityLowering.GravityTerms terms, Vector2 origin, Vector2 perTexel, - Vector2Int size, float rhoMax, Func truthD) + Vector2Int size, Func truthD) { var records = ReadRecords(terms); - var texel = Math.Max(Math.Abs(perTexel.x), Math.Abs(perTexel.y)); - double dWorst = 0, angleWorst = 0, rhoWorst = 0, rhoMutant = 0; - var rhoCount = 0; + double dWorst = 0, angleWorst = 0; for (var y = 0; y < size.y; y++) for (var x = 0; x < size.x; x++) { var sample = result.Samples[y * size.x + x]; var p = origin + new Vector2(x * perTexel.x, y * perTexel.y); - CpuSample(records, terms.Exaggeration, p, false, out var d, out var gx, out var gy, out var hxx, out var hxy, out var hyy); + CpuSample(records, terms.Exaggeration, p, out var d, out var gx, out var gy); dWorst = Math.Max(dWorst, Math.Abs(sample.z - (truthD?.Invoke(p) ?? d))); var slope = Math.Sqrt(gx * gx + gy * gy); if (slope <= GravityFieldParityVerify.FlatForce) continue; var cross = sample.x * gy - sample.y * gx; var dot = sample.x * gx + sample.y * gy; angleWorst = Math.Max(angleWorst, Math.Abs(Math.Atan2(cross, dot)) * 180 / Math.PI); - double Rho(double hxx_, double hxy_, double hyy_) - { - var kappa = (gy * gy * hxx_ - 2 * gx * gy * hxy_ + gx * gx * hyy_) / (slope * slope * slope); - return Math.Abs(kappa) > 1e-12 ? 1.0 / Math.Abs(kappa) : double.PositiveInfinity; - } - var rho = Rho(hxx, hxy, hyy); - if (!(rho > texel * 1.01 && rho < rhoMax * .99)) continue; - CpuSample(records, terms.Exaggeration, p, true, out _, out _, out _, out var mxx, out var mxy, out var myy); - rhoWorst = Math.Max(rhoWorst, Math.Abs(sample.w / rho - 1)); - rhoMutant = Math.Max(rhoMutant, Math.Abs(Rho(mxx, mxy, myy) / rho - 1)); - rhoCount++; } - Info($"analytic sample, {what}: {size.x * size.y} samples; d worst {dWorst:G3} u (bound {GravityFieldParityVerify.Tolerance:G3}); gradient angle worst {angleWorst:G3} deg (bound {GravityFieldParityVerify.GradientDegrees:G3}); rho worst relative error {rhoWorst:G3} over {rhoCount} unclamped samples (mutant PullSlope = 0 {rhoMutant:G3}, bound {AnalyticRhoBound:G3})"); + Info($"analytic sample, {what}: {size.x * size.y} samples; d worst {dWorst:G3} u (bound {GravityFieldParityVerify.Tolerance:G3}); gradient angle worst {angleWorst:G3} deg (bound {GravityFieldParityVerify.GradientDegrees:G3})"); if (dWorst > GravityFieldParityVerify.Tolerance) Fail("analytic sample", $"{what}: d is off the law by {dWorst:G4} u > {GravityFieldParityVerify.Tolerance:G4} (the fallback is a spec revision: stop)"); if (angleWorst > GravityFieldParityVerify.GradientDegrees) Fail("analytic sample", $"{what}: the gradient angle is off by {angleWorst:G4} degrees > {GravityFieldParityVerify.GradientDegrees:G4} (the fallback is a spec revision: stop)"); - if (rhoCount < 50) Fail("analytic sample", $"{what}: only {rhoCount} samples carry a kappa reading, the check is vacuous"); - if (rhoWorst > AnalyticRhoBound) Fail("analytic sample", $"{what}: rho is off the closed form by {rhoWorst:G4} > {AnalyticRhoBound:G4}"); } // ---- the real zone ----------------------------------------------------------------------------------------------- @@ -703,12 +579,10 @@ namespace Aetheria.EditorTools { TopFrame(ZoneCentre, ZoneHalf, 256, 256, out var origin, out var perTexel); var range = Math.Max(1f, orbits.Max(o => -zone.GetHeight(new float2(o.Position.x, o.Position.y)))); - // RhoMax from the zone: its radius, the largest curvature radius a contour can have inside it. - _zoneRhoMax = zone.Pack.Radius; - var levels = new IsolineExtractor.IsolineLevels(0f, range, _zoneRhoMax, SlopeEpsilon); + var levels = new IsolineExtractor.IsolineLevels(0f, range, SlopeEpsilon); var size = new Vector2Int(256, 256); var result = Extract(terms, origin, perTexel, size, levels, 1 << 20); - SamplesMatchTheLaw("real zone", result, terms, origin, perTexel, size, _zoneRhoMax, p => -zone.GetHeight(new float2(p.x, p.y))); + SamplesMatchTheLaw("real zone", result, terms, origin, perTexel, size, p => -zone.GetHeight(new float2(p.x, p.y))); var spacing = range / (Contours - 1); var contours = result.Segments.Where(s => !IsRay(s.key)).ToArray(); if (result.Written != result.Requested) Fail("real zone", $"{result.Requested} requested, only {result.Written} written"); @@ -758,9 +632,7 @@ namespace Aetheria.EditorTools if (!Border(p) && seen[(LevelOf(s.key), BitConverter.SingleToInt32Bits(p.x), BitConverter.SingleToInt32Bits(p.y))] != 2) open++; Info($"real zone: {open} contour endpoints off the border without exactly one partner"); - Continuity("real zone", contours, perTexel); CellBoxes("real zone", result.Segments, origin, perTexel, 256); - RealZoneS(result.Segments); if (open != 0) Fail("contours close", $"{open} endpoints are not shared with exactly one other endpoint"); } @@ -796,7 +668,7 @@ namespace Aetheria.EditorTools File.WriteAllBytes(Path.Combine(_out, "before.png"), before.EncodeToPNG()); // segments.png: the extracted segments over the same frame, contours cyan and rays magenta. - var levels = new IsolineExtractor.IsolineLevels(0f, range, zone.Pack.Radius, SlopeEpsilon); + var levels = new IsolineExtractor.IsolineLevels(0f, range, SlopeEpsilon); var result = Extract(terms, origin, perTexel, new Vector2Int(128, 128), levels, 1 << 18); var raster = new Texture2D(CaptureSize, CaptureSize, TextureFormat.RGBA32, false); raster.SetPixels32(Enumerable.Repeat(new Color32(0, 0, 0, 255), CaptureSize * CaptureSize).ToArray()); diff --git a/Assets/Scripts/Editor/IsolineRenderSmoke.cs b/Assets/Scripts/Editor/IsolineRenderSmoke.cs index ed94ce185..2b1a94f6a 100644 --- a/Assets/Scripts/Editor/IsolineRenderSmoke.cs +++ b/Assets/Scripts/Editor/IsolineRenderSmoke.cs @@ -27,7 +27,6 @@ namespace Aetheria.EditorTools public static class IsolineRenderSmoke { const string Tag = "[IsolineRenderSmoke]"; - const float RhoMax = 500f; const float SlopeEpsilon = 1e-3f; // The shipped sizes: segments the extractor and the screen scratch hold, and tile-list entries the pool holds. const int ShippedSegments = 1 << 20; @@ -45,14 +44,6 @@ namespace Aetheria.EditorTools const float WrongWayBound = 0.045f; const float FlowLagBound = 3.5f; - // s quality on the map pose (margin rule against Soul's readings on ab17b688b, the finite-difference mutant; the - // shipped reading is this cut's). Rays |ds|/L (1 is arclength): p5 shipped 0.349 against 0.193 (higher is better), p50 1.00 - // against 1.63, p75 1.00 against 7.34, p95 11.4 against 38.7; non-isometric share 19.1% against 57.3%; s sign flips at - // joints 12.2 against 258.4 per 1000; near the deepest well |s - r| / r p50 1.9e-6 against 5.1e-3 (its p95 reads 0.851 on - // both: not separated, unclaimed). Each bound is the geometric mean, separations 1.35, 1.28, 2.7, 1.8, 1.7, 4.6, 52. - const double RayP5Floor = 0.2595, RayP50Ceiling = 1.277, RayP75Ceiling = 2.709, RayP95Ceiling = 21.0; - const double NonIsometricCeiling = 0.3308, SignFlipCeiling = 56.1, NearWellP50Ceiling = 9.86e-5; - static bool _ok = true; static string _out; static string _wrote = ""; @@ -119,7 +110,7 @@ namespace Aetheria.EditorTools static Seg Contour(Vector2 a, Vector2 b) => Segment(a, b, 0f, (b - a).magnitude, .1f, .1f); - static IsolineExtractor.IsolineLevels Levels => new IsolineExtractor.IsolineLevels(0f, 1f, RhoMax, SlopeEpsilon); + static IsolineExtractor.IsolineLevels Levels => new IsolineExtractor.IsolineLevels(0f, 1f, SlopeEpsilon); sealed class Frame { @@ -288,7 +279,6 @@ namespace Aetheria.EditorTools var terms = GravityLowering.Lower(zone, 0f, ref wells); field = GravityLowering.CreateField(material); Guarded("flow follows depth near the real-zone saddle", () => FlowOnRealZone(zone, orbits, terms)); - Guarded("s quality on the map pose", () => SQuality(zone, orbits, terms)); Guarded("stress field and the shipped pool", StressAndPool); Guarded("captures and cost", () => CapturesAndCost(zone, orbits, terms)); Info(_ok ? "PASS" : "FAIL: see errors above"); @@ -607,154 +597,6 @@ namespace Aetheria.EditorTools } } - // The real zone at the map pose (1920 x 1080 at 2.04 u/px) through the extractor, its ray and contour chains measured: - // the |ds| / L of every edge (1 is true arclength), s sign flips at joints, and |s - r| / r near the deepest well, where - // the radius is the truth. Readings against Soul's at ab17b688b (finite-difference kappa, unity-r1.log), which are the - // mutant of this cut. Then the dash runs along 20 ray chains at the map pose, the flow frame's |ds| / L at 1.17 u/px, the - // two named kinks at 0.117 u/texel, and the captures flow-after.png and e1-after.png. - static void SQuality(Zone zone, Orbit[] orbits, GravityLowering.GravityTerms terms) - { - var range = ContourRange(zone, orbits); - var levels = new IsolineExtractor.IsolineLevels(0f, range, zone.Pack.Radius, SlopeEpsilon); - var mapView = Ortho(ZoneCentre, 1100f, 1920, 1080); - try - { - var ppx = 2200f / 1080f; - IsolineExtractSmoke.TopFrame(ZoneCentre, 1100f, 1920, 1080, out var mapOrigin, out var mapPerTexel); - var map = ExtractThrough(terms, mapOrigin, mapPerTexel, new Vector2Int(1920, 1080), levels); - var deepest = orbits.OrderByDescending(o => -zone.GetHeight(new float2(o.Position.x, o.Position.y))).First(); - var well1 = new Vector2(deepest.Position.x, deepest.Position.y); - var rays = BuildChains(map, 1u); - var contours = BuildChains(map, 0u); - Info($"s quality: map pose, {map.Length} segments, {rays.Count} ray chains, {contours.Count} contour chains"); - foreach (var (label, chains) in new[] { ("rays", rays), ("contours", contours) }) - { - var ratio = new List(); - var near = new List(); - int edges = 0, nonIso = 0, joints = 0, flips = 0; - foreach (var chain in chains) - { - var e = EdgesOf(map, chain); - for (var i = 0; i < e.Count; i++) - { - edges++; - var r = e[i].L > 1e-6f ? Mathf.Abs(e[i].Ds) / e[i].L : 0f; - ratio.Add(r); - if (r < .5f || r > 2f) nonIso++; - var mid = (e[i].P0 + e[i].P1) * .5f; - if (label == "rays" && (mid - well1).magnitude < 900f - && orbits.All(o => o == deepest || (mid - new Vector2(o.Position.x, o.Position.y)).magnitude > 250f)) - near.Add(Mathf.Abs((e[i].S0 + e[i].S1) * .5f - (mid - well1).magnitude) / Mathf.Max((mid - well1).magnitude, 1f)); - if (i + 1 < e.Count) - { - joints++; - if (Sgn(e[i].Ds) * Sgn(e[i + 1].Ds) < 0f) flips++; - } - } - } - if (label == "rays") - { - var nonIsoShare = nonIso / (double)Math.Max(edges, 1); - var flipRate = flips * 1000.0 / Math.Max(joints, 1); - if (Pct(ratio, .05) < RayP5Floor) Fail("s quality", $"rays |ds|/L p5 {Pct(ratio, .05):G4} < {RayP5Floor:G4}"); - if (Pct(ratio, .5) > RayP50Ceiling) Fail("s quality", $"rays |ds|/L p50 {Pct(ratio, .5):G4} > {RayP50Ceiling:G4}"); - if (Pct(ratio, .75) > RayP75Ceiling) Fail("s quality", $"rays |ds|/L p75 {Pct(ratio, .75):G4} > {RayP75Ceiling:G4}"); - if (Pct(ratio, .95) > RayP95Ceiling) Fail("s quality", $"rays |ds|/L p95 {Pct(ratio, .95):G4} > {RayP95Ceiling:G4}"); - if (nonIsoShare > NonIsometricCeiling) Fail("s quality", $"non-isometric share {nonIsoShare:P1} > {NonIsometricCeiling:P1}"); - if (flipRate > SignFlipCeiling) Fail("s quality", $"s sign flips {flipRate:F1}/1000 > {SignFlipCeiling:F1}"); - if (near.Count < 1000 || Pct(near, .5) > NearWellP50Ceiling) Fail("s quality", $"near well 1: {near.Count} edges, |s-r|/r p50 {Pct(near, .5):G4} > {NearWellP50Ceiling:G4}"); - } - Info($"s quality {label}: {edges} edges; |ds|/L {Pcts(ratio)}; non-isometric (<0.5 or >2) {nonIso / (double)Math.Max(edges, 1):P1}; s sign flips at joints {flips * 1000.0 / Math.Max(joints, 1):F1}/1000" - + (near.Count > 0 ? $"; near well 1 ({near.Count} edges) |s-r|/r p50 {Pct(near, .5):G3} p95 {Pct(near, .95):G3}" : "")); - } - - // dash runs along the ray chains at the map pose, rays only, Period 160 u (78.5 px) - var rayLook = IsolineLook.Default; - rayLook.Contour.W = 0f; rayLook.Contour.G = 0f; rayLook.Contour.Bloom = 0f; rayLook.Ray.Bloom = 0f; - var e1 = RecordFrame(terms, mapOrigin, mapPerTexel, new Vector2Int(1920, 1080), levels, mapView, rayLook, "e1-after.png"); - var rates = new List(); - var runs = new List(); - foreach (var chain in rays) - { - var e = EdgesOf(map, chain); - if (e.Sum(x => x.L) / ppx < 150f) continue; - var samples = new List(); - foreach (var edge in e) - { - var steps = Mathf.Max(1, Mathf.RoundToInt(edge.L / ppx)); - for (var q = 0; q < steps; q++) - { - var p = Vector2.Lerp(edge.P0, edge.P1, (q + .5f) / steps); - Project(mapView, p, p, out var pa, out _, out _, out _); - var ix = Mathf.Clamp((int)pa.x, 0, 1919); - var iy = Mathf.Clamp((int)pa.y, 0, 1079); - var m = 0f; - for (var dy = -1; dy <= 1; dy++) - for (var dx = -1; dx <= 1; dx++) m = Mathf.Max(m, e1.At(Mathf.Clamp(ix + dx, 0, 1919), Mathf.Clamp(iy + dy, 0, 1079)).w); - samples.Add(m); - } - } - if (samples.Count < 100) continue; - var threshold = .5f * samples.Max(); - if (threshold < .02f) continue; - var on = samples.Select(v => v > threshold).ToList(); - var run = 1; - for (var q = 1; q < on.Count; q++) - { - if (on[q] != on[q - 1]) { runs.Add(run); run = 1; } - else run++; - } - } - Info($"dash runs (E1): {runs.Count} runs along the ray chains over 150 px; run length px {Pcts(runs)} (Soul's shipped p5 1, p25 7, p50 38; true arclength p5 28, p25 45, p50 51)"); - - // the flow frame pose around the saddle (Period 60 u, 512 x 512 over 600 u = 1.17 u/px) - var flowView = Ortho(Saddle, 300f, 512, 512); - try - { - IsolineExtractSmoke.TopFrame(Saddle, 300f, 512, 512, out var flowOrigin, out var flowPerTexel); - var flow = ExtractThrough(terms, flowOrigin, flowPerTexel, new Vector2Int(512, 512), levels); - var flowRatio = new List(); - foreach (var chain in BuildChains(flow, 1u)) - foreach (var edge in EdgesOf(flow, chain)) flowRatio.Add(edge.L > 1e-6f ? Mathf.Abs(edge.Ds) / edge.L : 0f); - Info($"flow frame: {flowRatio.Count} ray edges at 1.17 u/px, |ds|/L {Pcts(flowRatio)} (Soul's shipped p95 62)"); - var flowLook = IsolineLook.Default; - flowLook.Ray.Period = 60f; - flowLook.Ray.Speed = 1f; - RecordFrame(terms, flowOrigin, flowPerTexel, new Vector2Int(512, 512), levels, flowView, flowLook, "flow-after.png"); - } - finally { flowView.Dispose(); } - - // the two named kinks at 0.117 u/texel (a 120 u crop over 1024 samples) against the map's 2.04 - foreach (var (kink, index) in new[] { (new Vector2(586.5f, -625f), 0), (new Vector2(993.5f, -219.7f), 1) }) - { - IsolineExtractSmoke.TopFrame(kink, 60f, 1024, 1024, out var fineOrigin, out var finePerTexel); - var fine = ExtractThrough(terms, fineOrigin, finePerTexel, new Vector2Int(1024, 1024), levels); - float WindowTurn(Seg[] segs) - { - var best = 0f; - foreach (var chain in BuildChains(segs, 1u)) - { - var e = EdgesOf(segs, chain); - var cumulative = new float[e.Count + 1]; - for (var i = 0; i < e.Count; i++) cumulative[i + 1] = cumulative[i] + e[i].L; - for (var i = 1; i < e.Count; i++) - { - if ((e[i].P0 - kink).magnitude > 25f) continue; - int j = i, k = i; - while (j > 0 && cumulative[i] - cumulative[j] < 6f) j--; - while (k < e.Count - 1 && cumulative[k] - cumulative[i] < 6f) k++; - if (cumulative[i] - cumulative[j] < 6f || cumulative[k] - cumulative[i] < 6f) continue; - best = Mathf.Max(best, Vector2.Angle(e[i].P0 - e[j].P0, e[k].P0 - e[i].P0)); - } - } - return best; - } - Info($"kink {index} at {kink}: max net turn over 6 u windows {WindowTurn(map):F0} deg at map resolution, {WindowTurn(fine):F0} deg at {finePerTexel.x:F3} u/texel (Soul's shipped: {(index == 0 ? "49 and 180" : "24 and 172")})"); - } - } - finally { mapView.Dispose(); } - } - static void Guarded(string name, Action check) { try { check(); } @@ -1191,7 +1033,7 @@ namespace Aetheria.EditorTools { IsolineExtractSmoke.TopFrame(ZoneCentre, ZoneHalf, 256, 256, out var origin, out var perTexel); // the contour window is the zone's: from 0 to the deepest body's depth, as MapPresenter.Draw sets it - var levels = new IsolineExtractor.IsolineLevels(0f, ContourRange(zone, orbits), zone.Pack.Radius, SlopeEpsilon); + var levels = new IsolineExtractor.IsolineLevels(0f, ContourRange(zone, orbits), SlopeEpsilon); renderer.Extractor.Extract(command, terms, origin, perTexel, new Vector2Int(256, 256), levels); renderer.Draw(command, renderer.Extractor.Segments, renderer.Extractor.Count, levels, view.ViewProjection, target, IsolineLook.Default, 0f, true, 1); Graphics.ExecuteCommandBuffer(command); @@ -1223,7 +1065,6 @@ namespace Aetheria.EditorTools var i = bestI[k]; if (i < 0 || bestH[k] > 1f) continue; var s = rays[i]; - if ((s.key & (1u << 10)) != 0) continue; // rho clamped: s is not trustworthy there if (((s.a + s.b) * .5f - Saddle).magnitude > 200f) continue; var dChange = Depth(s.b) - Depth(s.a); if (Mathf.Abs(dChange) < 1e-4f) continue; @@ -1282,7 +1123,7 @@ namespace Aetheria.EditorTools var command = new CommandBuffer { name = "IsolineStress" }; try { - var levels = new IsolineExtractor.IsolineLevels(0f, range, 1000f, SlopeEpsilon); + var levels = new IsolineExtractor.IsolineLevels(0f, range, SlopeEpsilon); // texel (x, y) sits at world (x, y) + .5: origin (.5, .5), step 1 renderer.Record(command, terms, new Vector2(.5f, .5f), Vector2.one, new Vector2Int(1920, 1080), levels, view.ViewProjection, target, IsolineLook.Default, 0f); Graphics.ExecuteCommandBuffer(command); @@ -1352,7 +1193,7 @@ namespace Aetheria.EditorTools static void CapturesAndCost(Zone zone, Orbit[] orbits, GravityLowering.GravityTerms terms) { var range = ContourRange(zone, orbits); - var levels = new IsolineExtractor.IsolineLevels(0f, range, zone.Pack.Radius, SlopeEpsilon); + var levels = new IsolineExtractor.IsolineLevels(0f, range, SlopeEpsilon); var look = IsolineLook.Default; var minimapMaterial = AssetDatabase.LoadAssetAtPath("Assets/Materials/UI/Minimap Gravity Lines.mat") ?? throw new InvalidOperationException("No Minimap Gravity Lines.mat."); var mapMaterial = AssetDatabase.LoadAssetAtPath("Assets/Materials/UI/Map Gravity Lines.mat") ?? throw new InvalidOperationException("No Map Gravity Lines.mat."); @@ -1409,7 +1250,7 @@ namespace Aetheria.EditorTools var stressField = RenderField(mapView.Camera, 1920, 1080, out _, out _); // the old material's input; it only times the blit var stressView = Ortho(new Vector2(960f, 540f), 540f, 1920, 1080); Cost("1920 x 1080 (stress)", mapRenderer, stressTerms, new Vector2Int(1920, 1080), stressField, new Vector2(.5f, .5f), Vector2.one, - new IsolineExtractor.IsolineLevels(0f, stressRange, 1000f, SlopeEpsilon), stressView.ViewProjection, mapTarget, look, mapMaterial, mapScale / 2f, stressRange); + new IsolineExtractor.IsolineLevels(0f, stressRange, SlopeEpsilon), stressView.ViewProjection, mapTarget, look, mapMaterial, mapScale / 2f, stressRange); stressTerms.Buffer.Release(); Info("captures:\n" + _wrote); diff --git a/Assets/Scripts/ServerShared/GravityField.cs b/Assets/Scripts/ServerShared/GravityField.cs index 739862306..084aa1f45 100644 --- a/Assets/Scripts/ServerShared/GravityField.cs +++ b/Assets/Scripts/ServerShared/GravityField.cs @@ -90,28 +90,6 @@ public static class GravityField return r * Profile(inner, outer, s) / (s + softening * softening); } - // dB/ds, B's slope in s = r^2: the derivative of the band polynomial over (b2 - a2) inside the band, 0 outside and with no fade. - private static float ProfileSlope(float inner, float outer, float s) - { - if (float.IsPositiveInfinity(outer)) return 0f; - var a2 = inner * inner; - var b2 = outer * outer; - if (s <= a2 || s >= b2) return 0f; - var t = (s - a2) / (b2 - a2); - var acc = 0f; - for (var i = OneMinusS.Length - 1; i >= 1; i--) acc = acc * t + i * OneMinusS[i]; - return acc / (b2 - a2); - } - - /// The slope of the pull, dPull/dr at distance r, per unit strength: B/(s+e2) + 2s (B'(s)/(s+e2) - B/(s+e2)^2), s = r^2. - public static float PullSlope(float softening, float inner, float outer, float r) - { - var s = r * r; - var den = s + softening * softening; - var b = Profile(inner, outer, s); - return b / den + 2f * s * (ProfileSlope(inner, outer, s) / den - b / (den * den)); - } - /// The potential at distance r, per unit strength: 0 at and beyond outer, the global log when outer is +inf. public static float Potential(float softening, float inner, float outer, float r) { diff --git a/Assets/Scripts/ServerShared/GravityShader.cs b/Assets/Scripts/ServerShared/GravityShader.cs index 43700d03f..976fd939e 100644 --- a/Assets/Scripts/ServerShared/GravityShader.cs +++ b/Assets/Scripts/ServerShared/GravityShader.cs @@ -145,42 +145,13 @@ float gravityTermPull(float softening, float a, float b, float r) return r * profile / (s + softening * softening); } -// GravityField.PullSlope: dPull/dr = B/(s+e2) + 2s (B'(s)/(s+e2) - B/(s+e2)^2), B' the derivative of the band polynomial -// over (b2 - a2) inside the band (Horner over GravityOneMinusS's derivative) and 0 outside. -float gravityTermPullSlope(float softening, float a, float b, float r) -{ - float s = r * r; - float den = s + softening * softening; - float profile = 1; - float slope = 0; - if (!isinf(b)) - { - float a2 = a * a; - float b2 = b * b; - if (s > a2) - { - profile = 0; - if (s < b2) - { - float t = (s - a2) / (b2 - a2); - [unroll] for (int i = @N@ - 1; i >= 0; i--) profile = profile * t + GravityOneMinusS[i]; - [unroll] for (int j = @N@ - 1; j >= 1; j--) slope = slope * t + j * GravityOneMinusS[j]; - slope /= b2 - a2; - } - } - } - return profile / den + 2 * s * (slope / den - profile / (den * den)); -} - -// The height's negative d = -Zone.GetHeight, its gradient and Hessian (xx, xy, yy) at world xz, in closed form from the same -// terms: per term, with k = -strength / exaggeration and u the unit vector from the term, grad += k Pull u and -// H += k (PullSlope u u^T + (Pull / r) (I - u u^T)); a point on the centre has the isotropic limit PullSlope I. Terms at or beyond -// outer add nothing, as in gravityHeight. -void gravitySample(float2 p, out float d, out float2 grad, out float3 hessian) +// The height's negative d = -Zone.GetHeight and its gradient at world xz, in closed form from the same terms: per term, with +// k = -strength / exaggeration and u the unit vector from the term, grad += k Pull u. Terms at or beyond outer add nothing, as in +// gravityHeight; the centre itself has no direction and adds no gradient. +void gravitySample(float2 p, out float d, out float2 grad) { float height = 0; grad = float2(0, 0); - hessian = float3(0, 0, 0); for (int i = 0; i < _GravityWellCount; i++) { GravityTerm term = _GravityWells[i]; @@ -189,18 +160,8 @@ void gravitySample(float2 p, out float d, out float2 grad, out float3 hessian) if (r < term.outer) { height += term.strength * gravityTermPotential(term.softening, term.inner, term.outer, r) - term.reference; - float k = -term.strength / _HeightExaggeration; - float slope = gravityTermPullSlope(term.softening, term.inner, term.outer, r); - if (r < 1e-6 * term.softening || r < 1e-20) - hessian += k * slope * float3(1, 0, 1); - else - { - float pull = gravityTermPull(term.softening, term.inner, term.outer, r); - float2 u = offset / r; - float turn = pull / r; - grad += k * pull * u; - hessian += k * float3(slope * u.x * u.x + turn * (1 - u.x * u.x), (slope - turn) * u.x * u.y, slope * u.y * u.y + turn * (1 - u.y * u.y)); - } + if (r >= 1e-20) + grad += (-term.strength / _HeightExaggeration) * gravityTermPull(term.softening, term.inner, term.outer, r) * (offset / r); } } d = -height / _HeightExaggeration; diff --git a/Assets/Scripts/Zone Display/IsolineExtractor.cs b/Assets/Scripts/Zone Display/IsolineExtractor.cs index 6a77e5ced..20ceab319 100644 --- a/Assets/Scripts/Zone Display/IsolineExtractor.cs +++ b/Assets/Scripts/Zone Display/IsolineExtractor.cs @@ -6,7 +6,7 @@ using UnityEngine.Rendering; /// /// The C# side of isoline extraction (campaign aetheria-release, cut isoline-extraction): the one owner of the segment /// buffer. Extract records the dispatches of Assets/Shaders/IsolineExtract.compute onto a command buffer; the compute -/// shader evaluates d, its gradient and its Hessian in closed form from the lowered well terms (GravityLowering.GravityTerms, +/// shader evaluates d, and its gradient in closed form from the lowered well terms (GravityLowering.GravityTerms, /// bound explicitly) at each sample point of a grid the caller chooses, and decides which segments exist and every attribute they /// carry. Nothing here reads a result back or edits a segment, and no texture is a source of d. /// @@ -24,18 +24,17 @@ public sealed class IsolineExtractor public uint cell; } - /// The levels to extract and the clamps of the along-line parameter. Contour levels are + /// The levels to extract. Contour levels are /// Start + i * Range / (ContourCount - 1), i = 1..ContourCount. public readonly struct IsolineLevels { - public readonly float Start, Range, RhoMax, SlopeEpsilon; + public readonly float Start, Range, SlopeEpsilon; public readonly int ContourCount, RayCount; - public IsolineLevels(float start, float range, float rhoMax, float slopeEpsilon, int contourCount = 21, int rayCount = 12) + public IsolineLevels(float start, float range, float slopeEpsilon, int contourCount = 21, int rayCount = 12) { Start = start; Range = range; - RhoMax = rhoMax; SlopeEpsilon = slopeEpsilon; ContourCount = contourCount; RayCount = rayCount; @@ -55,7 +54,7 @@ public sealed class IsolineExtractor readonly int _sample, _march, _finish; RenderTexture _samples; - /// The last grid's (gx, gy, d, rho) per sample: per-frame scratch, exposed for the smokes' reads. + /// The last grid's (gx, gy, d, |g|) per sample: per-frame scratch, exposed for the smokes' reads. public RenderTexture Samples => _samples; /// The segment buffer, IsoSegment[backing]; overwritten by each Extract. @@ -102,7 +101,6 @@ public sealed class IsolineExtractor cmd.SetComputeFloatParam(_shader, "_Range", levels.Range); cmd.SetComputeIntParam(_shader, "_ContourCount", levels.ContourCount); cmd.SetComputeIntParam(_shader, "_RayCount", levels.RayCount); - cmd.SetComputeFloatParam(_shader, "_RhoMax", levels.RhoMax); cmd.SetComputeFloatParam(_shader, "_SlopeEpsilon", levels.SlopeEpsilon); cmd.SetComputeIntParam(_shader, "_Capacity", Capacity); diff --git a/Assets/Shaders/Gravity.cginc b/Assets/Shaders/Gravity.cginc index ad3e6fce3..452110570 100644 --- a/Assets/Shaders/Gravity.cginc +++ b/Assets/Shaders/Gravity.cginc @@ -115,42 +115,13 @@ float gravityTermPull(float softening, float a, float b, float r) return r * profile / (s + softening * softening); } -// GravityField.PullSlope: dPull/dr = B/(s+e2) + 2s (B'(s)/(s+e2) - B/(s+e2)^2), B' the derivative of the band polynomial -// over (b2 - a2) inside the band (Horner over GravityOneMinusS's derivative) and 0 outside. -float gravityTermPullSlope(float softening, float a, float b, float r) -{ - float s = r * r; - float den = s + softening * softening; - float profile = 1; - float slope = 0; - if (!isinf(b)) - { - float a2 = a * a; - float b2 = b * b; - if (s > a2) - { - profile = 0; - if (s < b2) - { - float t = (s - a2) / (b2 - a2); - [unroll] for (int i = 8 - 1; i >= 0; i--) profile = profile * t + GravityOneMinusS[i]; - [unroll] for (int j = 8 - 1; j >= 1; j--) slope = slope * t + j * GravityOneMinusS[j]; - slope /= b2 - a2; - } - } - } - return profile / den + 2 * s * (slope / den - profile / (den * den)); -} - -// The height's negative d = -Zone.GetHeight, its gradient and Hessian (xx, xy, yy) at world xz, in closed form from the same -// terms: per term, with k = -strength / exaggeration and u the unit vector from the term, grad += k Pull u and -// H += k (PullSlope u u^T + (Pull / r) (I - u u^T)); a point on the centre has the isotropic limit PullSlope I. Terms at or beyond -// outer add nothing, as in gravityHeight. -void gravitySample(float2 p, out float d, out float2 grad, out float3 hessian) +// The height's negative d = -Zone.GetHeight and its gradient at world xz, in closed form from the same terms: per term, with +// k = -strength / exaggeration and u the unit vector from the term, grad += k Pull u. Terms at or beyond outer add nothing, as in +// gravityHeight; the centre itself has no direction and adds no gradient. +void gravitySample(float2 p, out float d, out float2 grad) { float height = 0; grad = float2(0, 0); - hessian = float3(0, 0, 0); for (int i = 0; i < _GravityWellCount; i++) { GravityTerm term = _GravityWells[i]; @@ -159,18 +130,8 @@ void gravitySample(float2 p, out float d, out float2 grad, out float3 hessian) if (r < term.outer) { height += term.strength * gravityTermPotential(term.softening, term.inner, term.outer, r) - term.reference; - float k = -term.strength / _HeightExaggeration; - float slope = gravityTermPullSlope(term.softening, term.inner, term.outer, r); - if (r < 1e-6 * term.softening || r < 1e-20) - hessian += k * slope * float3(1, 0, 1); - else - { - float pull = gravityTermPull(term.softening, term.inner, term.outer, r); - float2 u = offset / r; - float turn = pull / r; - grad += k * pull * u; - hessian += k * float3(slope * u.x * u.x + turn * (1 - u.x * u.x), (slope - turn) * u.x * u.y, slope * u.y * u.y + turn * (1 - u.y * u.y)); - } + if (r >= 1e-20) + grad += (-term.strength / _HeightExaggeration) * gravityTermPull(term.softening, term.inner, term.outer, r) * (offset / r); } } d = -height / _HeightExaggeration; diff --git a/Assets/Shaders/IsolineExtract.compute b/Assets/Shaders/IsolineExtract.compute index fbeafcf8e..fb714f260 100644 --- a/Assets/Shaders/IsolineExtract.compute +++ b/Assets/Shaders/IsolineExtract.compute @@ -1,11 +1,11 @@ -// Isoline extraction on the GPU (campaign aetheria-release, cuts isoline-extraction and isoline-s-from-exact-curvature). Evaluates -// d = -Zone.GetHeight, its gradient and its Hessian in closed form from the lowered well terms (Gravity.cginc, generated from +// Isoline extraction on the GPU (campaign aetheria-release, cuts isoline-extraction and isoline-chain-arclength). Evaluates +// d = -Zone.GetHeight and its gradient in closed form from the lowered well terms (Gravity.cginc, generated from // GravityField) at every sample point, and writes world-space line segments of two isoline families into a segment buffer, with // no readback and no texture read as a source of d: // contours: d = _Start + i * _Range / (_ContourCount - 1), i = 1.._ContourCount (the 21 levels of IsolinesUI.shader) // rays: theta = (k + .5) * 2pi / _RayCount - pi, k = 0.._RayCount-1, where theta is the angle of the HEIGHT gradient // (-grad d), the angle the iso-angle loop of IsolinesUI.shader reads, so the level index k matches it -// Kernels, in dispatch order: Sample (d, gradient and the level set's curvature radius), March (marching squares), Finish. +// Kernels, in dispatch order: Sample (d and gradient), March (marching squares), Finish. // The count buffer is cleared by the recorded command list before March (IsolineExtractor). #pragma kernel Sample #pragma kernel March @@ -17,7 +17,7 @@ #define PI 3.14159265358979 #define TWO_PI 6.28318530717959 -RWTexture2D _SampleOut; // Sample: (gx, gy, d, rho), gradient of d in world units per world unit +RWTexture2D _SampleOut; // Sample: (gx, gy, d, |g|), gradient of d in world units per world unit Texture2D _SampleIn; // March RWStructuredBuffer _Segments; RWStructuredBuffer _Count; @@ -29,34 +29,24 @@ float _Start; float _Range; int _ContourCount; int _RayCount; -float _RhoMax; float _SlopeEpsilon; uint _Capacity; -float Texel() { return max(abs(_PerTexel.x), abs(_PerTexel.y)); } float WrapPi(float x) { return x - TWO_PI * round(x / TWO_PI); } -// kappa = div(grad d / |grad d|), the level set's curvature, from the exact Hessian H: (gy^2 Hxx - 2 gx gy Hxy + gx^2 Hyy) / |g|^3. -// rho = 1 / |kappa| clamped to one sample spacing .. RhoMax: the radius of the contour through the point (the distance to the centre -// for any radial well, whatever its profile). [numthreads(8, 8, 1)] void Sample(uint3 id : SV_DispatchThreadID) { if (any(int2(id.xy) >= _Size)) return; float d; float2 g; - float3 h; - gravitySample(_Origin + float2(id.xy) * _PerTexel, d, g, h); - float slope = length(g); - float kappa = slope > 1e-12 ? (g.y * g.y * h.x - 2 * g.x * g.y * h.y + g.x * g.x * h.z) / (slope * slope * slope) : 0; - float rho = abs(kappa) > 1e-12 ? 1.0 / abs(kappa) : _RhoMax; - _SampleOut[id.xy] = float4(g, d, clamp(rho, Texel(), _RhoMax)); + gravitySample(_Origin + float2(id.xy) * _PerTexel, d, g); + _SampleOut[id.xy] = float4(g, d, length(g)); } // One cell's corners, in the order (x, y), (x+1, y), (x+1, y+1), (x, y+1); edges 0..3 join corners 0-1, 1-2, 3-2, 0-3. static float2 gPos[4]; static float gVal[4]; // the scalar being contoured: d for contours, the cell-unwrapped theta for rays -static float gS[4]; static float gSlope[4]; static float gDepth[4]; static uint gCell; @@ -68,14 +58,13 @@ static const uint kSegment[16] = { 0xFF, 0x03, 0x10, 0x13, 0x21, 0xFF, 0x20, 0x3 // index to its higher (edges 0 and 2 left to right, 1 and 3 bottom to top), so both cells sharing an edge read the corners // in the same order and compute the same floats bit for bit. Reordering kEdge breaks that; the closure check in // IsolineExtractSmoke is the guard. -void Crossing(uint edge, float level, out float2 p, out float s, out float slope, out float depth) +void Crossing(uint edge, float level, out float2 p, out float slope, out float depth) { uint a = kEdge[edge].x; uint b = kEdge[edge].y; precise float t = saturate((level - gVal[a]) / (gVal[b] - gVal[a])); precise float2 q = gPos[a] + (gPos[b] - gPos[a]) * t; p = q; - s = lerp(gS[a], gS[b], t); slope = lerp(gSlope[a], gSlope[b], t); depth = lerp(gDepth[a], gDepth[b], t); } @@ -83,8 +72,10 @@ void Crossing(uint edge, float level, out float2 p, out float s, out float slope void Emit(uint e0, uint e1, float level, uint key) { IsoSegment seg; - Crossing(e0, level, seg.a, seg.sA, seg.slopeA, seg.depthA); - Crossing(e1, level, seg.b, seg.sB, seg.slopeB, seg.depthB); + Crossing(e0, level, seg.a, seg.slopeA, seg.depthA); + Crossing(e1, level, seg.b, seg.slopeB, seg.depthB); + seg.sA = 0; + seg.sB = 0; if (all(seg.a == seg.b)) return; seg.key = key; seg.cell = gCell; @@ -118,22 +109,17 @@ void March(uint3 id : SV_DispatchThreadID) { if (any(int2(id.xy) + 1 >= _Size)) return; int2 p0 = int2(id.xy); - float rhoMin = Texel() * 1.0001; - float rhoMaxTest = _RhoMax * 0.9999; float dMin = 1e30, dMax = -1e30, slopeMin = 1e30; - float theta[4], rho[4]; - bool clamped = false; + float theta[4]; [unroll] for (uint i = 0; i < 4; i++) { int2 q = p0 + int2((i == 1 || i == 2) ? 1 : 0, i >= 2 ? 1 : 0); gPos[i] = _Origin + float2(q) * _PerTexel; float4 g = _SampleIn.Load(int3(q, 0)); - float slope = length(g.xy); + float slope = g.w; gSlope[i] = slope; gDepth[i] = g.z; theta[i] = slope > 0 ? atan2(-g.y, -g.x) : 0; - rho[i] = g.w; - clamped = clamped || g.w <= rhoMin || g.w >= rhoMaxTest; dMin = min(dMin, g.z); dMax = max(dMax, g.z); slopeMin = min(slopeMin, slope); @@ -142,39 +128,37 @@ void March(uint3 id : SV_DispatchThreadID) // Angles unwrapped to corner 0: a cell never crosses the branch cut inside an interpolation. float tu[4]; - bool seam = false; float tMin = 1e30, tMax = -1e30; [unroll] for (uint j = 0; j < 4; j++) { tu[j] = theta[0] + WrapPi(theta[j] - theta[0]); - seam = seam || abs(tu[j] - theta[j]) > 1.0; tMin = min(tMin, tu[j]); tMax = max(tMax, tu[j]); } - // Contours: s is the arclength around the well, theta_unwrapped * rho. + // Contours. if (_Range > 0 && _ContourCount > 1) { float spacing = _Range / (_ContourCount - 1); int lo = (int)clamp(floor((dMin - _Start) / spacing), 1, _ContourCount); int hi = (int)clamp(ceil((dMax - _Start) / spacing), 0, _ContourCount); - [unroll] for (uint k = 0; k < 4; k++) { gVal[k] = gDepth[k]; gS[k] = tu[k] * rho[k]; } + [unroll] for (uint k = 0; k < 4; k++) { gVal[k] = gDepth[k]; } for (int n = lo; n <= hi; n++) - March1(_Start + n * spacing, IsoKey((uint)(n - 1), ISO_FAMILY_CONTOUR, seam, clamped)); + March1(_Start + n * spacing, IsoKey((uint)(n - 1), ISO_FAMILY_CONTOUR)); } - // Rays: s is the distance along the ray, rho. Singular cells (a well centre, a saddle) have no angle: skipped. + // Rays. Singular cells (a well centre, a saddle) have no angle: skipped. if (_RayCount > 0 && slopeMin >= _SlopeEpsilon && tMax - tMin <= PI * 0.5 && dMax >= _Start && dMin <= _Start + _Range) { float step = TWO_PI / _RayCount; - [unroll] for (uint m = 0; m < 4; m++) { gVal[m] = tu[m]; gS[m] = rho[m]; } + [unroll] for (uint m = 0; m < 4; m++) { gVal[m] = tu[m]; } int lo = (int)floor((tMin + PI) / step - 0.5); int hi = (int)ceil((tMax + PI) / step - 0.5); for (int r = lo; r <= hi; r++) { int level = ((r % _RayCount) + _RayCount) % _RayCount; - March1((r + 0.5) * step - PI, IsoKey((uint)level, ISO_FAMILY_RAY, false, clamped)); + March1((r + 0.5) * step - PI, IsoKey((uint)level, ISO_FAMILY_RAY)); } } } diff --git a/Assets/Shaders/IsolineSegment.hlsl b/Assets/Shaders/IsolineSegment.hlsl index 45da08073..d17365e4e 100644 --- a/Assets/Shaders/IsolineSegment.hlsl +++ b/Assets/Shaders/IsolineSegment.hlsl @@ -10,10 +10,10 @@ struct IsoSegment { float2 a, b; // endpoints, world xz - float sA, sB; // along-line parameter at each endpoint, world units + float sA, sB; // along-line parameter at each endpoint, world units: chain arclength from the tail on rays, 0 on contours float slopeA, slopeB; // |grad d| at each endpoint, world units of depth per world unit float depthA, depthB; // d at each endpoint (the field value; deeper is larger) - uint key; // bits 0-7 level index, 8 family, 9 seam, 10 rho clamped + uint key; // bits 0-7 level index, 8 family, 9-31 reserved (0) uint cell; // linear index of the cell (y * field width + x): tile-binning locality and a deterministic sort key }; @@ -22,13 +22,9 @@ struct IsoSegment uint IsoLevel(uint key) { return key & 0xFFu; } uint IsoFamily(uint key) { return (key >> 8) & 1u; } -// The segment sits where the unwrapped angle is cut: s jumps by a full turn between this segment and its neighbour. -bool IsoSeam(uint key) { return (key & (1u << 9)) != 0u; } -// An endpoint's curvature radius hit a clamp (one texel or RhoMax): s is not trustworthy there. -bool IsoRhoClamped(uint key) { return (key & (1u << 10)) != 0u; } -uint IsoKey(uint level, uint family, bool seam, bool clamped) +uint IsoKey(uint level, uint family) { - return (level & 0xFFu) | (family << 8) | (seam ? (1u << 9) : 0u) | (clamped ? (1u << 10) : 0u); + return (level & 0xFFu) | (family << 8); } #endif diff --git a/tests/Aetheria.Shared.Tests/GravityShaderTests.cs b/tests/Aetheria.Shared.Tests/GravityShaderTests.cs index 8116e8f26..963e6b1a7 100644 --- a/tests/Aetheria.Shared.Tests/GravityShaderTests.cs +++ b/tests/Aetheria.Shared.Tests/GravityShaderTests.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using System.Linq; using Xunit; // potential-owns-gravity (aetheria-gravity, cut grid-lowering): Assets/Shaders/Gravity.cginc is the output of @@ -21,25 +20,4 @@ public sealed class GravityShaderTests Assert.Contains("static const float GravityS[8] = { 0, 0, 0, 0, 35, -84, 70, -20 };", generated); Assert.Equal(generated, File.ReadAllText(path).Replace("\r\n", "\n")); } - - // PullSlope is dPull/dr: against a central difference of Pull (float, step 0.05 u) over radii that cross the softened core, - // the band's inner edge, its interior and its outer edge, for a banded term and the global one. Errors are normalised by the - // largest |dPull/dr| of the sweep. Margin rule (lodur:ruling:deterministic-bound-margin): shipped worst BOUND_SHIPPED, - // the least claimed mutant (PullSlope = 0) reads 1 by construction; bound 1.0. - [Theory] - [InlineData(5f, 20f, 100f)] - [InlineData(2f, 0f, 60f)] - [InlineData(8f, 30f, float.PositiveInfinity)] - public void PullSlopeIsThePullsDerivative(float softening, float inner, float outer) - { - var radii = new System.Collections.Generic.List(); - for (var r = 0.5f; r < (float.IsPositiveInfinity(outer) ? 150f : outer + 10f); r += 0.37f) radii.Add(r); - const float h = 0.05f; - var truth = radii.Select(r => (GravityField.Pull(softening, inner, outer, r + h) - GravityField.Pull(softening, inner, outer, r - h)) / (2f * h)).ToArray(); - var scale = truth.Max(Math.Abs); - var worst = 0.0; - for (var i = 0; i < radii.Count; i++) - worst = Math.Max(worst, Math.Abs(GravityField.PullSlope(softening, inner, outer, radii[i]) - truth[i]) / scale); - Assert.True(worst < 0.0193, $"worst normalised error {worst:G4}"); - } }