From fca9c9bb50b645afa3aedff32700f56e578df79d Mon Sep 17 00:00:00 2001 From: soul Date: Tue, 1 Dec 2026 00:55:03 +0100 Subject: [PATCH] Isoline chains: GPU hash linking and pointer jumping make a ray's s the arclength from its chain's tail; junction rule; ChainStats ChainClear, ChainInsert, ChainLink, ChainJump (J = clamp(ceil(log2(4 (w + h))), 8, 20) passes) and ChainEmit run after Finish through indirect args Finish writes; the extractor owns the table, ping-pong, args and ChainStats buffers. Segments link only through a point exactly two ray endpoints share, one an end and one a start. Smokes: 'chains are arclength' (CPU BuildChains reference, first-found and J = 8 mutants emulated), 'orientation' on every case, ray s on the log wells, 'dashes match true arclength', chain cost. Bounds are set from the first readings in the next commit. Co-Authored-By: Claude Sonnet 5.5 --- Assets/Scripts/Editor/IsolineExtractSmoke.cs | 235 +++++++++++++++++- Assets/Scripts/Editor/IsolineRenderSmoke.cs | 141 ++++++++++- .../Scripts/Zone Display/IsolineExtractor.cs | 80 +++++- Assets/Shaders/IsolineExtract.compute | 170 ++++++++++++- 4 files changed, 604 insertions(+), 22 deletions(-) diff --git a/Assets/Scripts/Editor/IsolineExtractSmoke.cs b/Assets/Scripts/Editor/IsolineExtractSmoke.cs index deb6b15e7..a9eaa95cf 100644 --- a/Assets/Scripts/Editor/IsolineExtractSmoke.cs +++ b/Assets/Scripts/Editor/IsolineExtractSmoke.cs @@ -32,6 +32,9 @@ namespace Aetheria.EditorTools { const string Tag = "[IsolineExtractSmoke]"; const float SlopeEpsilon = 1e-3f; + // PROVISIONAL, set by the first reading: the chain bounds below. + const float EdgeBound = 1e-4f, PositionBound = 1e9f, JointBound = 1e9f; + const float RaySBound = 1e9f; const int Contours = 21; // Margin rule (lodur:ruling:deterministic-bound-margin): a bound sits at the geometric mean of the shipped worst and @@ -67,6 +70,7 @@ namespace Aetheria.EditorTools public IsolineExtractor.IsoSegment[] Segments; // the written ones public IsolineExtractor.IsoSegment[] Backing; // the whole buffer public uint Written, Requested; + public uint[] ChainStats; // heads, orientation conflicts, unterminated, table overflow public Vector4[] Samples; // (gx, gy, d, |g|) per sample, row-major } @@ -141,11 +145,14 @@ namespace Aetheria.EditorTools Graphics.ExecuteCommandBuffer(command); var count = new uint[2]; extractor.Count.GetData(count); + var chainStats = new uint[4]; + extractor.ChainStats.GetData(chainStats); var all = new IsolineExtractor.IsoSegment[extractor.Segments.count]; extractor.Segments.GetData(all); return new Result { Segments = all.Take((int)count[0]).ToArray(), Backing = all, Written = count[0], Requested = count[1], + ChainStats = chainStats, Samples = ReadSamples(extractor.Samples) }; } @@ -214,6 +221,122 @@ namespace Aetheria.EditorTools return (rayConflicts, joints); } + // ---- chains are arclength ------------------------------------------------------------------------------------------- + + // Worst readings over every case, as a fraction of the chain's length: the shipped GPU chains' s against the CPU truth, + // and the same for two mutants emulated on the CPU from the same segments: linking at a junction through the first + // segment found (Soul's replica links through any point that has a start) and pointer jumping stopped at J = 8. + // Position is |s - truth|; joint is |sB_i - sA_next| over the truth's links. + static double _positionShipped, _positionFirst, _positionJ8, _jointShipped, _jointFirst, _jointJ8; + + // The GPU's chains against IsolineRenderSmoke.BuildChains, the junction rule on the CPU: the same heads (ChainStats[0]), + // the same conflicts (ChainStats[1], Orientation's count), no unterminated segment and no table overflow, and every ray + // segment's s the arclength from its chain's tail, taken from the CPU in double: sA = -(length from this segment's start to + // the tail's start), sB = sA + |b - a|. A chain that BuildChains walks b to a throughout is reversed first; one that mixes + // directions holds an orientation conflict and is skipped here (Orientation fails it). + static void ChainsAreArclength(string what, Result result, int rayConflicts) + { + var segs = result.Segments; + var chains = IsolineRenderSmoke.BuildChains(segs, 1u); + var truth = new double[segs.Length]; // sA of the truth + var total = new double[segs.Length]; // length of the segment's chain + var link = new int[segs.Length]; // the segment the truth links this one to, -1 for a tail + var position8 = new double[segs.Length]; // the J = 8 mutant's error in s, in length + Array.Fill(truth, double.NaN); + Array.Fill(link, -1); + double Len(int i) => Math.Sqrt(Math.Pow((double)segs[i].b.x - segs[i].a.x, 2) + Math.Pow((double)segs[i].b.y - segs[i].a.y, 2)); + int mixed = 0, longest = 0; + double jointJ8Worst = 0; + foreach (var chain in chains) + { + List order; + if (chain.Rev.All(r => !r)) order = chain.Seg; + else if (chain.Rev.All(r => r)) order = chain.Seg.AsEnumerable().Reverse().ToList(); + else { mixed++; continue; } + var n = order.Count; + longest = Math.Max(longest, n); + var prefix = new double[n + 1]; + for (var k = 0; k < n; k++) prefix[k + 1] = prefix[k] + Len(order[k]); + var length = prefix[n]; + var tailStart = prefix[n - 1]; + for (var k = 0; k < n; k++) + { + truth[order[k]] = prefix[k] - tailStart; + total[order[k]] = length; + if (k + 1 < n) link[order[k]] = order[k + 1]; + // J = 8: only 256 segments of the length to the tail are summed + var reach = Math.Min(k + 256, n - 1); + position8[order[k]] = prefix[n - 1] - prefix[reach]; + if (k + 256 <= n - 2) jointJ8Worst = Math.Max(jointJ8Worst, Len(order[k + 256]) / length); + } + } + + // first-found linking: every ray segment links through the lowest-numbered segment that starts at its end + var firstStart = new Dictionary<(int, int), int>(); + for (var i = 0; i < segs.Length; i++) + if (IsRay(segs[i].key) && !firstStart.ContainsKey(PointKey(segs[i].a))) firstStart[PointKey(segs[i].a)] = i; + var nextFirst = new int[segs.Length]; + for (var i = 0; i < segs.Length; i++) + nextFirst[i] = IsRay(segs[i].key) && firstStart.TryGetValue(PointKey(segs[i].b), out var j) && j != i ? j : -1; + var rankFirst = new double[segs.Length]; + var state = new byte[segs.Length]; + var stack = new Stack(); + for (var i = 0; i < segs.Length; i++) + { + if (state[i] != 0 || !IsRay(segs[i].key)) continue; + for (var at = i; at >= 0 && state[at] == 0; at = nextFirst[at]) { state[at] = 1; stack.Push(at); } + while (stack.Count > 0) + { + var at = stack.Pop(); + var next = nextFirst[at]; + rankFirst[at] = next >= 0 && state[next] == 2 ? Len(at) + rankFirst[next] : next >= 0 ? Len(at) : 0; // a cycle stops where it closes + state[at] = 2; + } + } + + double positionShipped = 0, positionFirst = 0, positionJ8 = 0, jointShipped = 0, jointFirst = 0, edgeWorst = 0; + int compared = 0, firstWrong = 0; + for (var i = 0; i < segs.Length; i++) + { + if (!IsRay(segs[i].key) || double.IsNaN(truth[i])) continue; + compared++; + var s = segs[i]; + var length = total[i]; + positionShipped = Math.Max(positionShipped, Math.Max(Math.Abs(s.sA - truth[i]), Math.Abs(s.sB - (truth[i] + Len(i)))) / length); + positionJ8 = Math.Max(positionJ8, position8[i] / length); + var first = Math.Abs(-rankFirst[i] - truth[i]) / length; + positionFirst = Math.Max(positionFirst, first); + if (first > 1e-3) firstWrong++; + edgeWorst = Math.Max(edgeWorst, Math.Abs(Math.Abs(s.sB - s.sA) - Len(i)) / (Math.Abs(s.sA) + Math.Abs(s.sB) + Len(i))); + if (link[i] < 0) continue; + jointShipped = Math.Max(jointShipped, Math.Abs(s.sB - segs[link[i]].sA) / length); + // the first-found mutant's own s at this joint: its sB of i against its sA of the true next + jointFirst = Math.Max(jointFirst, Math.Abs((-rankFirst[i] + Len(i)) - (-rankFirst[link[i]])) / length); + } + _positionShipped = Math.Max(_positionShipped, positionShipped); _positionFirst = Math.Max(_positionFirst, positionFirst); _positionJ8 = Math.Max(_positionJ8, positionJ8); + _jointShipped = Math.Max(_jointShipped, jointShipped); _jointFirst = Math.Max(_jointFirst, jointFirst); _jointJ8 = Math.Max(_jointJ8, jointJ8Worst); + + var stats = result.ChainStats; + Info($"chains {what}: {segs.Count(s => IsRay(s.key))} ray segments, {chains.Count} chains (longest {longest} segments), {mixed} mixed-direction; GPU stats heads {stats[0]} conflicts {stats[1]} unterminated {stats[2]} overflow {stats[3]}; " + + $"s error / chain length: position worst {positionShipped:G3} (mutants first-found {positionFirst:G3} on {firstWrong} segments, J = 8 {positionJ8:G3}), joint worst {jointShipped:G3} (mutants {jointFirst:G3}, {jointJ8Worst:G3}); |sB - sA| = |b - a| worst relative {edgeWorst:G3}"); + if (compared < 100) Fail("chains", $"{what}: only {compared} ray segments compared, the check is vacuous"); + if (mixed != 0) Fail("chains", $"{what}: {mixed} chains run both ways"); + if (stats[0] != chains.Count) Fail("chains", $"{what}: the GPU counted {stats[0]} chain heads, the CPU {chains.Count} chains"); + if (stats[1] != rayConflicts) Fail("chains", $"{what}: the GPU counted {stats[1]} orientation conflicts, the CPU {rayConflicts}"); + if (stats[2] != 0) Fail("chains", $"{what}: {stats[2]} segments are unterminated"); + if (stats[3] != 0) Fail("chains", $"{what}: the hash table overflowed {stats[3]} times"); + if (edgeWorst > EdgeBound) Fail("chains", $"{what}: |sB - sA| is off |b - a| by {edgeWorst:G3} > {EdgeBound:G3}"); + } + + // Called once, after every case: the readings against the margin-rule bounds (each constant's comment gives the shipped + // worst, the least claimed mutant and their separation). + static void ChainBounds() + { + Info($"chain readings over every case: position shipped {_positionShipped:G3}, first-found {_positionFirst:G3}, J = 8 {_positionJ8:G3}; joint shipped {_jointShipped:G3}, first-found {_jointFirst:G3}, J = 8 {_jointJ8:G3}"); + if (_positionShipped > PositionBound) Fail("chains", $"s is off the CPU arclength by {_positionShipped:G3} of a chain > {PositionBound:G3}"); + if (_jointShipped > JointBound) Fail("chains", $"s jumps by {_jointShipped:G3} of a chain at a joint > {JointBound:G3}"); + } + // ---- entry ------------------------------------------------------------------------------------------------------- public static void Run() @@ -251,7 +374,9 @@ namespace Aetheria.EditorTools var terms = GravityLowering.Lower(zone, 0f, ref wells); field = GravityLowering.CreateField(material); Guarded("real zone", () => RealZone(zone, orbits, terms)); + Guarded("chains are arclength", () => ChainCases(zone, orbits, terms)); Guarded("captures and cost", () => CapturesAndCost(zone, orbits, terms)); + Guarded("chain cost", () => ChainCostCases(zone, orbits, terms)); Info(_ok ? "PASS" : "FAIL: see errors above"); } catch (Exception e) @@ -437,6 +562,17 @@ namespace Aetheria.EditorTools angleWorst = Math.Max(angleWorst, Off((LevelOf(s.key) + .5) * step - Math.PI)); angleMutant = Math.Max(angleMutant, Off(LevelOf(s.key) * step - Math.PI)); } + // s: a ray is a radial line, so along an edge s changes by the change of the distance to the centre; the mutant takes + // the change of d / |grad d| (the curvature radius this cut deleted) for it. A contour's s is 0. + double sWorst = 0, sMutant = 0; + foreach (var s in rays) + { + if (!InBand(s.a - centre) || !InBand(s.b - centre) || Length(s) < 1e-3f) continue; + var radial = Math.Abs((s.b - centre).magnitude - (s.a - centre).magnitude); + sWorst = Math.Max(sWorst, Math.Abs(Math.Abs(s.sB - s.sA) - radial) / Length(s)); + sMutant = Math.Max(sMutant, Math.Abs(Math.Abs(s.depthB / s.slopeB - s.depthA / s.slopeA) - radial) / Length(s)); + } + ContoursAreNotRanked(profile.Name, contours); // 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); var holding = (uint)((int)texel.y * GridSize + (int)texel.x); @@ -446,7 +582,8 @@ namespace Aetheria.EditorTools SamplesMatchTheLaw("radial " + profile.Name, result, terms, origin, perTexel, new Vector2Int(GridSize, GridSize), null); Orientation("radial " + profile.Name, result.Segments); 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; ray angle error worst {angleWorst:G4} rad (mutant levels half a step off {angleMutant: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}); ray s off the radial distance worst {sWorst:G3} of an edge (mutant d / |g| {sMutant:G3})"); + if (sWorst > RaySBound) Fail("along-line", $"{profile.Name}: a ray's s changes off the distance to the centre by {sWorst:G3} of an edge > {RaySBound:G3}"); 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); } @@ -671,10 +808,104 @@ namespace Aetheria.EditorTools open++; Info($"real zone: {open} contour endpoints off the border without exactly one partner"); CellBoxes("real zone", result.Segments, origin, perTexel, 256); - Orientation("real zone", result.Segments); + var (zoneConflicts, _) = Orientation("real zone", result.Segments); + ChainsAreArclength("real zone 256 x 256", result, zoneConflicts); if (open != 0) Fail("contours close", $"{open} endpoints are not shared with exactly one other endpoint"); } + // The chain cases the spec names beyond the 256 x 256 real zone: the real zone at the map pose (1920 x 1080 over 2200 u) and at + // 3840 x 2160, and the 60-well stress set (1920 x 1080 at 1 u per sample). Each runs the extractor as shipped, then the + // orientation and chain checks; the bounds follow once every case has read. + const int ChainCapacity = 1 << 20; + + static void ChainCases(Zone zone, Orbit[] orbits, GravityLowering.GravityTerms terms) + { + var range = Math.Max(1f, orbits.Max(o => -zone.GetHeight(new float2(o.Position.x, o.Position.y)))); + var levels = new IsolineExtractor.IsolineLevels(0f, range, SlopeEpsilon); + foreach (var (what, w, h) in new[] { ("real zone 1920 x 1080", 1920, 1080), ("real zone 3840 x 2160", 3840, 2160) }) + { + TopFrame(ZoneCentre, 1100f, w, h, out var origin, out var perTexel); + var result = Extract(terms, origin, perTexel, new Vector2Int(w, h), levels, ChainCapacity); + if (result.Written != result.Requested) Fail("chains", $"{what}: {result.Requested} requested, only {result.Written} written"); + var (conflicts, _) = Orientation(what, result.Segments); + ChainsAreArclength(what, result, conflicts); + ContoursAreNotRanked(what, result.Segments); + } + var stress = WellsFrom(IsolineRenderSmoke.StressWells(out var stressRange)); + try + { + var result = Extract(stress, new Vector2(.5f, .5f), Vector2.one, new Vector2Int(1920, 1080), new IsolineExtractor.IsolineLevels(0f, stressRange, SlopeEpsilon), ChainCapacity); + if (result.Written != result.Requested) Fail("chains", $"stress: {result.Requested} requested, only {result.Written} written"); + var (conflicts, _) = Orientation("stress 60 wells", result.Segments); + ChainsAreArclength("stress 60 wells", result, conflicts); + ContoursAreNotRanked("stress 60 wells", result.Segments); + } + finally { Free(stress); } + ChainBounds(); + } + + // Contours are not ranked: their s is 0 (they are solid by ruling isoline-rays-flow). + static void ContoursAreNotRanked(string what, IsolineExtractor.IsoSegment[] segments) + { + var ranked = segments.Count(s => !IsRay(s.key) && (s.sA != 0f || s.sB != 0f)); + if (ranked != 0) Fail("contours", $"{what}: {ranked} contour segments carry an s other than 0"); + } + + // ---- chain cost (reported, not gated) --------------------------------------------------------------------------------- + + // The chain kernels' cost (ChainClear through ChainEmit, J passes): per iteration, Extract recorded 8 times through Finish and + // 8 times through the chains, each timed on the wall clock to a fence (the count read back); the chain cost is the median + // over 31 interleaved iterations of the paired difference (the fence and the extraction cancel), beside the median of Extract + // alone. Soul's replica (r2, GTX 1070): 0.16-0.18 ms at the map pose, 0.75-0.77 ms on the stress set. + static void ChainCost(string what, GravityLowering.GravityTerms terms, Vector2 origin, Vector2 perTexel, Vector2Int size, IsolineExtractor.IsolineLevels levels) + { + const int reps = 8, iterations = 31; + var extractor = new IsolineExtractor(Shader, ChainCapacity); + try + { + double Time(IsolineExtractor.Stage stage) + { + var command = new CommandBuffer { name = "IsolineChainCost" }; + for (var r = 0; r < reps; r++) extractor.Extract(command, terms, origin, perTexel, size, levels, stage); + var clock = Stopwatch.StartNew(); + Graphics.ExecuteCommandBuffer(command); + extractor.Count.GetData(new uint[2]); + clock.Stop(); + command.Release(); + return clock.Elapsed.TotalMilliseconds / reps; + } + Time(IsolineExtractor.Stage.Segments); Time(IsolineExtractor.Stage.Chains); // warm up + var alone = new List(); + var delta = new List(); + var full = new List(); + for (var i = 0; i < iterations; i++) + { + var a = Time(IsolineExtractor.Stage.Segments); + var b = Time(IsolineExtractor.Stage.Chains); + alone.Add(a); full.Add(b); delta.Add(b - a); + } + double Median(List v) { v.Sort(); return v[v.Count / 2]; } + var counts = new uint[2]; + extractor.Count.GetData(counts); + var stats = new uint[4]; + extractor.ChainStats.GetData(stats); + Info($"chain cost {what}: {counts[0]} segments; Extract through Finish {Median(alone):F3} ms, through the chains {Median(full):F3} ms, chain kernels (paired difference, median of {iterations} x {reps} reps) {Median(delta):F3} ms; ChainStats heads {stats[0]} conflicts {stats[1]} unterminated {stats[2]} overflow {stats[3]}"); + } + finally { extractor.Release(); } + } + + static void ChainCostCases(Zone zone, Orbit[] orbits, GravityLowering.GravityTerms terms) + { + var levels = new IsolineExtractor.IsolineLevels(0f, Math.Max(1f, orbits.Max(o => -zone.GetHeight(new float2(o.Position.x, o.Position.y)))), SlopeEpsilon); + TopFrame(ZoneCentre, 1100f, 1920, 1080, out var origin, out var perTexel); + ChainCost("real zone 1920 x 1080", terms, origin, perTexel, new Vector2Int(1920, 1080), levels); + var stress = WellsFrom(IsolineRenderSmoke.StressWells(out var stressRange)); + try { ChainCost("stress 60 wells", stress, new Vector2(.5f, .5f), Vector2.one, new Vector2Int(1920, 1080), new IsolineExtractor.IsolineLevels(0f, stressRange, SlopeEpsilon)); } + finally { Free(stress); } + TopFrame(ZoneCentre, 1100f, 3840, 2160, out var bigOrigin, out var bigPerTexel); + ChainCost("real zone 3840 x 2160", terms, bigOrigin, bigPerTexel, new Vector2Int(3840, 2160), levels); + } + // ---- captures and cost ------------------------------------------------------------------------------------------- const int CaptureSize = 512; diff --git a/Assets/Scripts/Editor/IsolineRenderSmoke.cs b/Assets/Scripts/Editor/IsolineRenderSmoke.cs index 2b1a94f6a..f9f49bf80 100644 --- a/Assets/Scripts/Editor/IsolineRenderSmoke.cs +++ b/Assets/Scripts/Editor/IsolineRenderSmoke.cs @@ -123,7 +123,8 @@ namespace Aetheria.EditorTools // Draws hand-made segments through the renderer's own Draw: raw writes float4(D, h, s, dir) of one family into a float // target; otherwise the composite lands in an ARGBHalf target, as in the shipped path. static Frame Draw(View view, Seg[] segments, IsolineLook look, bool raw, int family = 0, float time = 0f, int count = -1, - int pool = 1 << 20, float dilation = -1f, int bufferLength = 0, Action prepare = null, Action inspect = null) + int pool = 1 << 20, float dilation = -1f, int bufferLength = 0, Action prepare = null, Action inspect = null, + IsolineExtractor.IsolineLevels? levels = null) { var capacity = Math.Max(Math.Max(segments.Length, bufferLength), 16); var renderer = new IsolineRenderer(ExtractShader, RenderShader, capacity, pool) { DilationOverride = dilation }; @@ -141,7 +142,7 @@ namespace Aetheria.EditorTools var written = (uint)(count < 0 ? segments.Length : count); counts.SetData(new[] { written, written }); prepare?.Invoke(renderer); - renderer.Draw(command, buffer, counts, Levels, view.ViewProjection, target, look, time, raw, family); + renderer.Draw(command, buffer, counts, levels ?? Levels, view.ViewProjection, target, look, time, raw, family); Graphics.ExecuteCommandBuffer(command); var frame = new Frame { W = view.W, H = view.H, Px = Read(target), Stats = new uint[6] }; renderer.Stats.GetData(frame.Stats); @@ -279,6 +280,7 @@ 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("dashes match true arclength", () => DashesMatchTrueArclength(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"); @@ -473,13 +475,13 @@ namespace Aetheria.EditorTools // ---- s quality on the map pose (verdict cut-isoline-renderer.s1, findings ray-dashes-alias-from-s-jitter and // ray-noise-grows-as-texel-shrinks) -------------------------------------------------------------------------------- - sealed class Chain + internal sealed class Chain { public List Seg = new List(); public List Rev = new List(); } - sealed class Edge + internal sealed class Edge { public Vector2 P0, P1; public float S0, S1, L; @@ -491,7 +493,7 @@ namespace Aetheria.EditorTools static (int, int) PointKey(Vector2 p) => (BitConverter.SingleToInt32Bits(p.x), BitConverter.SingleToInt32Bits(p.y)); // The polylines of one family: segments joined where exactly two endpoints share a bit-equal point. - static List BuildChains(Seg[] segs, uint family) + internal static List BuildChains(Seg[] segs, uint family) { var ends = new Dictionary<(int, int), List<(int seg, int end)>>(); void Add(Vector2 p, int seg, int end) @@ -538,7 +540,7 @@ namespace Aetheria.EditorTools return chains; } - static List EdgesOf(Seg[] segs, Chain c) + internal static List EdgesOf(Seg[] segs, Chain c) { var list = new List(); for (var i = 0; i < c.Seg.Count; i++) @@ -597,6 +599,121 @@ namespace Aetheria.EditorTools } } + // ---- dashes match true arclength (the look gate; cut isoline-chain-arclength) --------------------------------------------- + + // Dash run lengths along the ray chains: over every chain longer than 150 px, the 3 x 3 maximum of the frame's alpha sampled + // once per pixel along the chain, taken as on where it exceeds half the chain's peak; the lengths of the runs of on and + // of off, in px. + static List DashRuns(Seg[] segs, List chains, View view, Frame frame, float ppx) + { + var runs = new List(); + foreach (var chain in chains) + { + var e = EdgesOf(segs, 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(view, p, p, out var pa, out _, out _, out _); + var ix = Mathf.Clamp((int)pa.x, 0, view.W - 1); + var iy = Mathf.Clamp((int)pa.y, 0, view.H - 1); + var m = 0f; + for (var dy = -1; dy <= 1; dy++) + for (var dx = -1; dx <= 1; dx++) m = Mathf.Max(m, frame.At(Mathf.Clamp(ix + dx, 0, view.W - 1), Mathf.Clamp(iy + dy, 0, view.H - 1)).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++; + } + } + return runs; + } + + // The reference: the same segments with s replaced by the cumulative arclength along BuildChains' chain, from its first + // edge (the dash phase differs from the shipped one, the spacing does not). + static Seg[] WithChainArclength(Seg[] segs, List chains) + { + var copy = (Seg[])segs.Clone(); + foreach (var chain in chains) + { + var cumulative = 0f; + for (var i = 0; i < chain.Seg.Count; i++) + { + var k = chain.Seg[i]; + var length = (segs[k].b - segs[k].a).magnitude; + if (!chain.Rev[i]) { copy[k].sA = cumulative; copy[k].sB = cumulative + length; } + else { copy[k].sB = cumulative; copy[k].sA = cumulative + length; } + cumulative += length; + } + } + return copy; + } + + // Margin rule against the s = rho mutant (3d8a0d1d3, Soul's readings in unity-mut.log's base run): its run lengths at the map + // pose read p5 2, p25 10 and p50 46 px against the true arclength's 28, 45 and 51, that is |ln(mutant / reference)| 2.64, + // 1.50 and 0.103. Each bound sits at the geometric mean of that and the shipped reading below (the shipped |ln| per + // percentile, worst of the two poses). The flow frame's mutant readings were not taken at 3d8a0d1d3; the same bounds + // apply to it. + const double DashP5Bound = 1e9, DashP25Bound = 1e9, DashP50Bound = 1e9; + + // The map pose (Period 160 u, 78.5 px) and Soul's flow pose (Period 60 u at 1.17 u/px), rays only: the dash run lengths of + // the frame drawn from the extractor's segments against the frame drawn from the same segments with s replaced by the CPU + // arclength. Writes e1-after.png (the map pose, rays only), flow-after.png and flow-reference.png (the flow pose in the + // default look, beside Soul's flow-arclen.png). + static void DashesMatchTrueArclength(Zone zone, Orbit[] orbits, GravityLowering.GravityTerms terms) + { + var levels = new IsolineExtractor.IsolineLevels(0f, ContourRange(zone, orbits), SlopeEpsilon); + foreach (var (name, centre, half, w, h, period, speed) in new[] { ("map", ZoneCentre, 1100f, 1920, 1080, 160f, .35f), ("flow", Saddle, 300f, 512, 512, 60f, 1f) }) + { + var view = Ortho(centre, half, w, h); + try + { + var ppx = 2f * half / h; + IsolineExtractSmoke.TopFrame(centre, half, w, h, out var origin, out var perTexel); + var segs = ExtractThrough(terms, origin, perTexel, new Vector2Int(w, h), levels); + var chains = BuildChains(segs, 1u); + var reference = WithChainArclength(segs, chains); + var rayLook = IsolineLook.Default; + rayLook.Contour.W = 0f; rayLook.Contour.G = 0f; rayLook.Contour.Bloom = 0f; rayLook.Ray.Bloom = 0f; + rayLook.Ray.Period = period; rayLook.Ray.Speed = speed; + var shippedFrame = Draw(view, segs, rayLook, false, levels: levels, pool: ShippedPool); + var referenceFrame = Draw(view, reference, rayLook, false, levels: levels, pool: ShippedPool); + var shippedRuns = DashRuns(segs, chains, view, shippedFrame, ppx); + var referenceRuns = DashRuns(segs, chains, view, referenceFrame, ppx); + if (shippedRuns.Count < 40 || referenceRuns.Count < 40) { Fail("dashes", $"{name}: {shippedRuns.Count} and {referenceRuns.Count} dash runs, the check would be vacuous"); continue; } + Info($"dashes {name} pose: {segs.Count(s => ((s.key >> 8) & 1u) != 0)} ray segments, {chains.Count} chains; run length px shipped {Pcts(shippedRuns)} ({shippedRuns.Count} runs); reference (CPU arclength) {Pcts(referenceRuns)} ({referenceRuns.Count} runs)"); + foreach (var (label, q, bound) in new[] { ("p5", .05, DashP5Bound), ("p25", .25, DashP25Bound), ("p50", .5, DashP50Bound) }) + { + var gap = Math.Abs(Math.Log(Pct(shippedRuns, q) / Pct(referenceRuns, q))); + Info($"dashes {name} {label}: shipped {Pct(shippedRuns, q):G3} reference {Pct(referenceRuns, q):G3} |ln(shipped/reference)| {gap:G3} (bound {bound:G3})"); + if (gap > bound) Fail("dashes", $"{name} {label}: shipped run length {Pct(shippedRuns, q):G3} px against the arclength reference's {Pct(referenceRuns, q):G3}: |ln| {gap:G3} > {bound:G3}"); + } + if (name == "map") SaveFrame("e1-after.png", shippedFrame); + else + { + // the operator's pictures: Soul's flow pose in the default look, shipped and reference + var flowLook = IsolineLook.Default; + flowLook.Ray.Period = period; flowLook.Ray.Speed = speed; + SaveFrame("flow-after.png", Draw(view, segs, flowLook, false, levels: levels, pool: ShippedPool)); + SaveFrame("flow-reference.png", Draw(view, reference, flowLook, false, levels: levels, pool: ShippedPool)); + } + } + finally { view.Dispose(); } + } + } + static void Guarded(string name, Action check) { try { check(); } @@ -1097,7 +1214,7 @@ namespace Aetheria.EditorTools // 60 deep, close wells over 1920 x 1080 units at 1 u per sample, steep enough that the contour levels crowd below a pixel: // band terms (inner 15..40, outer 120..260) of strength 300..1200 and softening 6..20, summed. - static GravityLowering.TermRecord[] StressWells(out float range) + internal static GravityLowering.TermRecord[] StressWells(out float range) { var rng = new System.Random(11); var wells = Enumerable.Range(0, 60).Select(_ => @@ -1148,9 +1265,13 @@ namespace Aetheria.EditorTools } // The target as an sRGB PNG over black (straight alpha, linear colour). - static void Save(string name, RenderTexture target, int w, int h) + static void Save(string name, RenderTexture target, int w, int h) => SaveFrame(name, new Frame { W = w, H = h, Px = Read(target) }); + + static void SaveFrame(string name, Frame frame) { - var pixels = Read(target); + var w = frame.W; + var h = frame.H; + var pixels = frame.Px; var png = new Texture2D(w, h, TextureFormat.RGBA32, false, true); var colours = new Color32[w * h]; for (var i = 0; i < colours.Length; i++) @@ -1388,7 +1509,7 @@ namespace Aetheria.EditorTools if (iteration >= 0) prefixes[k].Add(t); } // Sample alone first: it clears Count, so the full Extract after it leaves the segments the next prefixes draw - var sa = Time(c => renderer.Extractor.Extract(c, terms, origin, perTexel, size, levels, sampleOnly: true), () => renderer.Extractor.Count.GetData(new uint[2])); + var sa = Time(c => renderer.Extractor.Extract(c, terms, origin, perTexel, size, levels, IsolineExtractor.Stage.Sample), () => renderer.Extractor.Count.GetData(new uint[2])); var e = Time(c => renderer.Extractor.Extract(c, terms, origin, perTexel, size, levels), () => renderer.Extractor.Count.GetData(new uint[2])); var b = Time(c => c.Blit(Texture2D.whiteTexture, blitTarget, lines), PixelFence); if (iteration >= 0) { extract.Add(e); blit.Add(b); sampleAlone.Add(sa); } diff --git a/Assets/Scripts/Zone Display/IsolineExtractor.cs b/Assets/Scripts/Zone Display/IsolineExtractor.cs index 20ceab319..4f78a9b2e 100644 --- a/Assets/Scripts/Zone Display/IsolineExtractor.cs +++ b/Assets/Scripts/Zone Display/IsolineExtractor.cs @@ -4,11 +4,11 @@ using UnityEngine.Experimental.Rendering; using UnityEngine.Rendering; /// -/// The C# side of isoline extraction (campaign aetheria-release, cut isoline-extraction): the one owner of the segment +/// The C# side of isoline extraction (campaign aetheria-release, cuts isoline-extraction and isoline-chain-arclength): 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, and its gradient 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. +/// carry. The chain kernels, recorded after Finish, rank each ray chain in place and leave s as arclength from its tail. Nothing here reads a result back or edits a segment, and no texture is a source of d. /// public sealed class IsolineExtractor { @@ -48,10 +48,21 @@ public sealed class IsolineExtractor static readonly int ExaggerationId = Shader.PropertyToID("_HeightExaggeration"); static readonly int SegmentsId = Shader.PropertyToID("_Segments"); static readonly int CountId = Shader.PropertyToID("_Count"); + static readonly int ArgsId = Shader.PropertyToID("_Args"); + static readonly int TableId = Shader.PropertyToID("_Table"); + static readonly int ChainStatsId = Shader.PropertyToID("_ChainStats"); + static readonly int LinkInId = Shader.PropertyToID("_LinkIn"); + static readonly int LinkOutId = Shader.PropertyToID("_LinkOut"); static readonly uint[] Zero = new uint[2]; + static readonly uint[] ZeroStats = new uint[4]; + + /// How far Extract records: the Sample kernel alone, through the segments (March and Finish), or through the chains + /// (the shipped path). The shorter ones are cost probes. + public enum Stage { Sample, Segments, Chains } readonly ComputeShader _shader; - readonly int _sample, _march, _finish; + readonly int _sample, _march, _finish, _chainClear, _chainInsert, _chainLink, _chainJump, _chainEmit; + readonly GraphicsBuffer _table, _linkA, _linkB, _args; RenderTexture _samples; /// The last grid's (gx, gy, d, |g|) per sample: per-frame scratch, exposed for the smokes' reads. @@ -63,6 +74,10 @@ public sealed class IsolineExtractor /// uint[2]: [0] segments written (at most Capacity), [1] segments requested (overflow when above Capacity). public GraphicsBuffer Count { get; } + /// uint[4]: [0] chain heads, [1] orientation conflicts, [2] unterminated segments, [3] hash table overflows. Never read + /// back by runtime code. + public GraphicsBuffer ChainStats { get; } + /// The most segments Extract writes. public int Capacity { get; } @@ -70,22 +85,37 @@ public sealed class IsolineExtractor /// Larger only where a check needs room past the guard. public IsolineExtractor(ComputeShader shader, int capacity, int backing = 0) { + // the chain kernels dispatch one thread per segment indirectly: 64 to a group, at most 65535 groups + if (capacity > 65535 * 64) throw new System.ArgumentOutOfRangeException(nameof(capacity), capacity, "more segments than one indirect dispatch covers"); _shader = shader; Capacity = capacity; _sample = shader.FindKernel("Sample"); _march = shader.FindKernel("March"); _finish = shader.FindKernel("Finish"); + _chainClear = shader.FindKernel("ChainClear"); + _chainInsert = shader.FindKernel("ChainInsert"); + _chainLink = shader.FindKernel("ChainLink"); + _chainJump = shader.FindKernel("ChainJump"); + _chainEmit = shader.FindKernel("ChainEmit"); Segments = new GraphicsBuffer(GraphicsBuffer.Target.Structured, Mathf.Max(capacity, backing), Marshal.SizeOf()); Count = new GraphicsBuffer(GraphicsBuffer.Target.Structured, 2, sizeof(uint)); + ChainStats = new GraphicsBuffer(GraphicsBuffer.Target.Structured, 4, sizeof(uint)); + // per-frame scratch of the chain kernels: a table of at least four slots per segment, three words each; ping-pong links; args + var slots = 64; + while (slots < 4L * Capacity) slots *= 2; + _table = new GraphicsBuffer(GraphicsBuffer.Target.Structured, 3 * slots, sizeof(uint)); + _linkA = new GraphicsBuffer(GraphicsBuffer.Target.Structured, Mathf.Max(capacity, 1), 2 * sizeof(uint)); + _linkB = new GraphicsBuffer(GraphicsBuffer.Target.Structured, Mathf.Max(capacity, 1), 2 * sizeof(uint)); + _args = new GraphicsBuffer(GraphicsBuffer.Target.IndirectArguments, 8, sizeof(uint)); } /// /// Records the extraction of the zone field on a sample grid of size.x * size.y points: sample (x, y) sits at /// worldOrigin + (x, y) * worldPerTexel in world xz, the step signed per axis. The grid is the caller's, chosen per view. - /// sampleOnly records the Sample kernel alone (cost probes). + /// upTo cuts the recording short for cost probes. /// public void Extract(CommandBuffer cmd, in GravityLowering.GravityTerms terms, Vector2 worldOrigin, Vector2 worldPerTexel, - Vector2Int size, IsolineLevels levels, bool sampleOnly = false) + Vector2Int size, IsolineLevels levels, Stage upTo = Stage.Chains) { if (_samples == null || _samples.width != size.x || _samples.height != size.y) { @@ -94,6 +124,7 @@ public sealed class IsolineExtractor } cmd.SetBufferData(Count, Zero); + cmd.SetBufferData(ChainStats, ZeroStats); cmd.SetComputeIntParams(_shader, "_Size", size.x, size.y); cmd.SetComputeVectorParam(_shader, "_Origin", worldOrigin); cmd.SetComputeVectorParam(_shader, "_PerTexel", worldPerTexel); @@ -111,7 +142,7 @@ public sealed class IsolineExtractor cmd.SetComputeFloatParam(_shader, ExaggerationId, terms.Exaggeration); cmd.SetComputeTextureParam(_shader, _sample, SampleOut, _samples); cmd.DispatchCompute(_shader, _sample, groupsX, groupsY, 1); - if (sampleOnly) return; // cost probes only + if (upTo == Stage.Sample) return; cmd.SetComputeTextureParam(_shader, _march, SampleIn, _samples); cmd.SetComputeBufferParam(_shader, _march, SegmentsId, Segments); @@ -119,7 +150,37 @@ public sealed class IsolineExtractor cmd.DispatchCompute(_shader, _march, groupsX, groupsY, 1); cmd.SetComputeBufferParam(_shader, _finish, CountId, Count); + cmd.SetComputeBufferParam(_shader, _finish, ArgsId, _args); cmd.DispatchCompute(_shader, _finish, 1, 1, 1); + if (upTo == Stage.Segments) return; + + // Chains: s on the rays is the arclength from each chain's tail, J passes of pointer jumping reaching 2^J segments. + var jumps = Mathf.Clamp(Mathf.CeilToInt(Mathf.Log(4f * (size.x + size.y), 2f)), 8, 20); + void Bind(int kernel) + { + cmd.SetComputeBufferParam(_shader, kernel, SegmentsId, Segments); + cmd.SetComputeBufferParam(_shader, kernel, CountId, Count); + cmd.SetComputeBufferParam(_shader, kernel, ArgsId, _args); + cmd.SetComputeBufferParam(_shader, kernel, TableId, _table); + cmd.SetComputeBufferParam(_shader, kernel, ChainStatsId, ChainStats); + } + Bind(_chainClear); + cmd.DispatchCompute(_shader, _chainClear, _args, 12); + Bind(_chainInsert); + cmd.DispatchCompute(_shader, _chainInsert, _args, 0); + Bind(_chainLink); + cmd.SetComputeBufferParam(_shader, _chainLink, LinkOutId, _linkA); + cmd.DispatchCompute(_shader, _chainLink, _args, 0); + for (var pass = 0; pass < jumps; pass++) + { + Bind(_chainJump); + cmd.SetComputeBufferParam(_shader, _chainJump, LinkInId, pass % 2 == 0 ? _linkA : _linkB); + cmd.SetComputeBufferParam(_shader, _chainJump, LinkOutId, pass % 2 == 0 ? _linkB : _linkA); + cmd.DispatchCompute(_shader, _chainJump, _args, 0); + } + Bind(_chainEmit); + cmd.SetComputeBufferParam(_shader, _chainEmit, LinkInId, jumps % 2 == 0 ? _linkA : _linkB); + cmd.DispatchCompute(_shader, _chainEmit, _args, 0); } public void Release() @@ -127,6 +188,11 @@ public sealed class IsolineExtractor Release(ref _samples); Segments.Release(); Count.Release(); + ChainStats.Release(); + _table.Release(); + _linkA.Release(); + _linkB.Release(); + _args.Release(); } static RenderTexture Scratch(int width, int height, GraphicsFormat format) diff --git a/Assets/Shaders/IsolineExtract.compute b/Assets/Shaders/IsolineExtract.compute index 129185cdc..899213911 100644 --- a/Assets/Shaders/IsolineExtract.compute +++ b/Assets/Shaders/IsolineExtract.compute @@ -5,11 +5,26 @@ // 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 and gradient), March (marching squares), Finish. -// The count buffer is cleared by the recorded command list before March (IsolineExtractor). +// Kernels, in dispatch order: Sample (d and gradient), March (marching squares), Finish, then the chain kernels over the ray +// segments: ChainClear, ChainInsert, ChainLink, ChainJump (J passes), ChainEmit. The count buffer is cleared by the recorded +// command list before March (IsolineExtractor). +// +// Chains (cut isoline-chain-arclength): a ray segment's s is the true arclength along its chain, from the chain's tail. Every +// segment is oriented a to b by Emit, so a chain is a run of segments each ending where the next starts. Junction rule: segments +// link only through a point that exactly two ray endpoints share bit for bit, one an end (b) and one a start (a). Any other point +// (one endpoint: a chain end; three or more: a corner crossing; two starts or two ends: an orientation conflict) ends every chain +// touching it: next(i) is the one segment starting at b_i when that point has exactly one start and one end, else i is a tail. +// The rule reads counts, not arrival order, so it is deterministic whatever order the threads run in. Ranking is Wyllie pointer +// jumping (rank = length of the segment while it has a next, else 0), then sA = -rank and sB = sA + |b - a|. Contours are not +// ranked: Emit writes their s as 0. #pragma kernel Sample #pragma kernel March #pragma kernel Finish +#pragma kernel ChainClear +#pragma kernel ChainInsert +#pragma kernel ChainLink +#pragma kernel ChainJump +#pragma kernel ChainEmit #include "IsolineSegment.hlsl" #include "Gravity.cginc" @@ -21,6 +36,11 @@ RWTexture2D _SampleOut; // Sample: (gx, gy, d, |g|), gradient of d in Texture2D _SampleIn; // March RWStructuredBuffer _Segments; RWStructuredBuffer _Count; +RWByteAddressBuffer _Args; // Finish: 7 words, dispatch groups of the per-segment kernels (0), of ChainClear (3), the table mask (6) +RWStructuredBuffer _Table; // 3 words per slot: owner (segment << 1 | end), counts (starts | ends << 16), index of a start +RWStructuredBuffer _ChainStats; // [0] chain heads, [1] orientation conflicts, [2] unterminated, [3] table overflow +StructuredBuffer _LinkIn; // (next, asuint(rank)) per segment, the ping-pong source +RWStructuredBuffer _LinkOut; // the ping-pong target int2 _Size; // sample grid size float2 _Origin; // world xz of sample (0, 0) @@ -185,8 +205,152 @@ void March(uint3 id : SV_DispatchThreadID) } } +// Finish publishes the written count and sizes the chain kernels' dispatches from it: groups of 64 segments, a table of at least +// four slots per segment (a power of two, at least 64), cleared by one thread per slot, 256 to a group. [numthreads(1, 1, 1)] void Finish(uint3 id : SV_DispatchThreadID) { - _Count[0] = min(_Count[1], _Capacity); + uint n = min(_Count[1], _Capacity); + _Count[0] = n; + uint size = 1u << (firstbithigh(max(4u * n, 64u) - 1u) + 1u); + _Args.Store3(0, uint3((n + 63u) / 64u, 1u, 1u)); + _Args.Store3(12, uint3((size + 255u) / 256u, 1u, 1u)); + _Args.Store(24, size - 1u); +} + +#define EMPTY 0xFFFFFFFFu +#define PROBE_LIMIT 256 +#define ONE_START_ONE_END 0x00010001u +#define TWO_STARTS 0x00000002u +#define TWO_ENDS 0x00020000u + +uint HashPoint(float2 p) +{ + uint2 u = asuint(p); + uint h = u.x * 0x9E3779B1u ^ (u.y * 0x85EBCA77u); + h ^= h >> 15; h *= 0x2C1B3C6Du; h ^= h >> 12; + return h; +} + +bool SamePoint(float2 p, float2 q) { return all(asuint(p) == asuint(q)); } + +// The endpoint an owner word names: segment << 1 | end, end 0 the start a and 1 the end b. +float2 OwnerPoint(uint owner) +{ + IsoSegment s = _Segments[owner >> 1]; + return (owner & 1u) != 0u ? s.b : s.a; +} + +// The table slot holding point p, or EMPTY when p was not inserted (or its probe ran past the limit). +uint Lookup(float2 p, uint mask) +{ + uint slot = HashPoint(p) & mask; + for (uint probe = 0; probe < PROBE_LIMIT; probe++) + { + uint owner = _Table[3u * slot]; + if (owner == EMPTY) return EMPTY; + if (SamePoint(OwnerPoint(owner), p)) return slot; + slot = (slot + 1u) & mask; + } + return EMPTY; +} + +[numthreads(256, 1, 1)] +void ChainClear(uint3 id : SV_DispatchThreadID) +{ + if (id.x > _Args.Load(24)) return; + _Table[3u * id.x] = EMPTY; + _Table[3u * id.x + 1u] = 0u; + _Table[3u * id.x + 2u] = 0u; +} + +// Each ray endpoint claims or finds the slot of its point (the owner is whichever endpoint arrives first; only the point it +// names matters) and counts itself there: starts in the low half of the counts word, ends in the high half. A start also +// records its segment, which is the answer when the point holds exactly one start. A probe that runs out leaves the endpoint +// uncounted and the overflow counted. +[numthreads(64, 1, 1)] +void ChainInsert(uint3 id : SV_DispatchThreadID) +{ + uint i = id.x; + if (i >= _Count[0]) return; + IsoSegment seg = _Segments[i]; + if (IsoFamily(seg.key) != ISO_FAMILY_RAY) return; + uint mask = _Args.Load(24); + for (uint e = 0; e < 2; e++) + { + float2 p = e == 0 ? seg.a : seg.b; + uint slot = HashPoint(p) & mask; + bool placed = false; + for (uint probe = 0; probe < PROBE_LIMIT; probe++) + { + uint owner; + InterlockedCompareExchange(_Table[3u * slot], EMPTY, (i << 1) | e, owner); + if (owner == EMPTY || SamePoint(OwnerPoint(owner), p)) { placed = true; break; } + slot = (slot + 1u) & mask; + } + if (!placed) { InterlockedAdd(_ChainStats[3], 1u); continue; } + if (e == 0) { InterlockedAdd(_Table[3u * slot + 1u], 1u); _Table[3u * slot + 2u] = i; } + else InterlockedAdd(_Table[3u * slot + 1u], 0x10000u); + } +} + +// next(i) is the one segment starting at b_i when b_i has exactly one start and one end, else i itself (a tail). The rank starts +// as the segment's own length while it has a next. Heads (a_i not joined to an end) and orientation conflicts (a point of +// exactly two endpoints that are both starts or both ends, counted per endpoint) are tallied here. +[numthreads(64, 1, 1)] +void ChainLink(uint3 id : SV_DispatchThreadID) +{ + uint i = id.x; + if (i >= _Count[0]) return; + IsoSegment seg = _Segments[i]; + uint next = i; + float rank = 0; + if (IsoFamily(seg.key) == ISO_FAMILY_RAY) + { + uint mask = _Args.Load(24); + uint slotA = Lookup(seg.a, mask); + uint slotB = Lookup(seg.b, mask); + uint countA = slotA == EMPTY ? 0u : _Table[3u * slotA + 1u]; + uint countB = slotB == EMPTY ? 0u : _Table[3u * slotB + 1u]; + if (countA != ONE_START_ONE_END) InterlockedAdd(_ChainStats[0], 1u); + if (countA == TWO_STARTS) InterlockedAdd(_ChainStats[1], 1u); + if (countB == TWO_ENDS) InterlockedAdd(_ChainStats[1], 1u); + if (countB == ONE_START_ONE_END) + { + next = _Table[3u * slotB + 2u]; + rank = length(seg.b - seg.a); + } + } + _LinkOut[i] = uint2(next, asuint(rank)); +} + +// One Wyllie pass: next' = next[next], rank' = rank + rank[next], a tail (next = itself) unchanged. +[numthreads(64, 1, 1)] +void ChainJump(uint3 id : SV_DispatchThreadID) +{ + uint i = id.x; + if (i >= _Count[0]) return; + uint2 mine = _LinkIn[i]; + if (mine.x != i) + { + uint2 theirs = _LinkIn[mine.x]; + mine = uint2(theirs.x, asuint(asfloat(mine.y) + asfloat(theirs.y))); + } + _LinkOut[i] = mine; +} + +// The ranked chain's s: sA = -rank, sB = sA + |b - a|, the arclength from the tail. A segment whose final next is not a tail +// (a chain longer than 2^J, or a cycle) is counted unterminated; its s stays as ranked. +[numthreads(64, 1, 1)] +void ChainEmit(uint3 id : SV_DispatchThreadID) +{ + uint i = id.x; + if (i >= _Count[0]) return; + IsoSegment seg = _Segments[i]; + if (IsoFamily(seg.key) != ISO_FAMILY_RAY) return; + uint2 link = _LinkIn[i]; + if (_LinkIn[link.x].x != link.x) InterlockedAdd(_ChainStats[2], 1u); + float rank = asfloat(link.y); + _Segments[i].sA = -rank; + _Segments[i].sB = -rank + length(seg.b - seg.a); }