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 <noreply@anthropic.com>
This commit is contained in:
soul 2026-12-01 00:55:03 +01:00
commit fca9c9bb50
4 changed files with 604 additions and 22 deletions

View file

@ -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<int> 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<int>();
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<double>();
var delta = new List<double>();
var full = new List<double>();
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<double> 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;

View file

@ -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<IsolineRenderer> prepare = null, Action<IsolineRenderer> inspect = null)
int pool = 1 << 20, float dilation = -1f, int bufferLength = 0, Action<IsolineRenderer> prepare = null, Action<IsolineRenderer> 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<int> Seg = new List<int>();
public List<bool> Rev = new List<bool>();
}
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<Chain> BuildChains(Seg[] segs, uint family)
internal static List<Chain> 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<Edge> EdgesOf(Seg[] segs, Chain c)
internal static List<Edge> EdgesOf(Seg[] segs, Chain c)
{
var list = new List<Edge>();
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<double> DashRuns(Seg[] segs, List<Chain> chains, View view, Frame frame, float ppx)
{
var runs = new List<double>();
foreach (var chain in chains)
{
var e = EdgesOf(segs, chain);
if (e.Sum(x => x.L) / ppx < 150f) continue;
var samples = new List<float>();
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<Chain> 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); }