diff --git a/Assets/Scripts/Editor/GravityFieldParityVerify.cs b/Assets/Scripts/Editor/GravityFieldParityVerify.cs
index d996d3227..279d9b16b 100644
--- a/Assets/Scripts/Editor/GravityFieldParityVerify.cs
+++ b/Assets/Scripts/Editor/GravityFieldParityVerify.cs
@@ -32,11 +32,11 @@ namespace Aetheria.EditorTools
// single-precision floor of 1.5e-5 per unit strength against the CPU's, the quad's interpolated world position). The
// tolerance is 2.9x that. A band whose terms were drawn from the wrong edge (reference, inner or outer) moves the
// drawn height by whole units.
- const float Tolerance = 0.03f;
+ internal const float Tolerance = 0.03f;
// The worst angle between the texture's central difference and GetForce (B28: 1.0 degrees median zone, 2.9 worst).
- const float GradientDegrees = 3f;
+ internal const float GradientDegrees = 3f;
// Below this force (u/s^2) the drawn height differs between neighbouring texels by less than float32 resolves.
- const float FlatForce = 1e-3f;
+ internal const float FlatForce = 1e-3f;
static float _maxError, _maxAngle, _maxTau;
static bool _ok = true;
diff --git a/Assets/Scripts/Editor/IsolineExtractSmoke.cs b/Assets/Scripts/Editor/IsolineExtractSmoke.cs
index cfb9fb0d2..5a126913c 100644
--- a/Assets/Scripts/Editor/IsolineExtractSmoke.cs
+++ b/Assets/Scripts/Editor/IsolineExtractSmoke.cs
@@ -15,12 +15,13 @@ using Debug = UnityEngine.Debug;
namespace Aetheria.EditorTools
{
///
- /// Batchmode check for campaign aetheria-release, cut isoline-extraction: IsolineExtract.compute writes the segments of
- /// a gravity field's 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 field, rendered as
- /// the Gravity Field pass renders it and judged by Zone.GetHeight, and synthetic fields whose answer is a formula.
- /// It also writes before.png and segments.png (the minimap field through today's line shader, and the extracted
- /// segments over the same frame) and reports the cost of an extraction; neither is gated.
+ /// Batchmode check for campaign aetheria-release, cuts isoline-extraction and isoline-s-from-exact-curvature:
+ /// 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,
+ /// and synthetic well sets whose answer is a formula over the same records (GravityField on the records read back from
+ /// the buffer). It also writes before.png and segments.png (the minimap field through today's line shader, and the
+ /// extracted segments over the same frame) and reports the cost of an extraction; neither is gated.
///
/// Renders and dispatches compute, so it needs a graphics device: run WITHOUT -nographics.
/// Unity -batchmode -projectPath <repo> -executeMethod Aetheria.EditorTools.IsolineExtractSmoke.Run -logFile <path>
@@ -38,26 +39,30 @@ namespace Aetheria.EditorTools
// the least claimed mutant's reading, and the two readings must be at least 1.2 apart. Each constant's comment
// gives its two readings from the run that set it, and the mutant is emulated from the shipped output on the CPU.
// 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.
+ // (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: shipped worst 0.0100; least mutant
- // (rho = d / |grad d|, soft-core profile) 0.273, separation 27; the raw-theta mutant reads 0.99.
- const float ArcRatioBound = 0.0523f;
- // Ray endpoint |s / r - 1|: shipped worst 0.0112; least mutant (rho = d / |grad d|, soft-core profile) 0.287, separation 25.6.
- const float RayRhoBound = 0.0566f;
- // Ray endpoint's angle off its level, rad: shipped worst 0.00187; least mutant (levels half a step off) 0.263, separation 140.
- const float RayAngleBound = 0.0222f;
-
- // Endpoint depth |depth / d(r) - 1| on the radial wells: shipped worst 0.00064; least mutant (depth ends swapped, offset well)
- // 0.0373, separation 58. Slope |slope / |d'(r)| - 1|: shipped worst 0.0031; least mutant (slope not interpolated, offset well)
- // 0.0580, separation 18.9 (slope ends swapped reads 0.074).
+ // 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: shipped worst 3.3%;
- // the same zone at RhoMax 500 (a fixture-sized value) reads 49.6%, separation 15.
+ // 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: shipped 5.4%; the mutant (s negated) 94.6%, separation 17.5.
+ // 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;
static bool _ok = true;
@@ -78,13 +83,76 @@ 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
}
static ComputeShader Shader => AssetDatabase.LoadAssetAtPath("Assets/Shaders/IsolineExtract.compute")
?? throw new InvalidOperationException("No IsolineExtract.compute.");
- static Result Extract(RenderTexture field, Vector2 origin, Vector2 perTexel, IsolineExtractor.IsolineLevels levels,
- int capacity, int backing = 0)
+ sealed class Wells
+ {
+ public GravityLowering.GravityTerms Terms;
+ public GravityLowering.TermRecord[] Records; // read back from the buffer: CPU and GPU share one input
+ }
+
+ static GravityLowering.TermRecord Well(Vector2 at, float strength, float softening, float inner, float outer, float reference = 0f) =>
+ new GravityLowering.TermRecord { Position = at, Strength = strength, Softening = softening, Inner = inner, Outer = outer, Reference = reference };
+
+ // Uploads term records straight into a compute buffer: the synthetic fixtures' wells, as GravityLowering.Lower would.
+ internal static GravityLowering.GravityTerms WellsFrom(GravityLowering.TermRecord[] records, float exaggeration = 1f)
+ {
+ var buffer = new ComputeBuffer(records.Length, Marshal.SizeOf());
+ buffer.SetData(records);
+ return new GravityLowering.GravityTerms(buffer, records.Length, exaggeration);
+ }
+
+ static void Free(GravityLowering.GravityTerms terms) => terms.Buffer.Release();
+
+ static GravityLowering.TermRecord[] ReadRecords(GravityLowering.GravityTerms terms)
+ {
+ var records = new GravityLowering.TermRecord[terms.Buffer.count];
+ terms.Buffer.GetData(records);
+ 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)
+ {
+ double height = 0;
+ gx = gy = hxx = hxy = hyy = 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));
+ }
+ d = -height / exaggeration;
+ }
+
+ // The sample grid of a downward orthographic view of half height halfHeight centred on a world point: square samples,
+ // sample (0, 0) at the corner's centre, +x east and +y toward +z as the camera sees them.
+ internal static void TopFrame(Vector2 centre, float halfHeight, int width, int height, out Vector2 origin, out Vector2 perTexel)
+ {
+ var step = 2f * halfHeight / height;
+ perTexel = new Vector2(step, step);
+ origin = centre - new Vector2(width, height) * (.5f * step) + perTexel * .5f;
+ }
+
+ static Result Extract(GravityLowering.GravityTerms terms, Vector2 origin, Vector2 perTexel, Vector2Int size,
+ IsolineExtractor.IsolineLevels levels, int capacity, int backing = 0)
{
var extractor = new IsolineExtractor(Shader, capacity, backing);
var command = new CommandBuffer { name = "IsolineExtract" };
@@ -93,13 +161,17 @@ namespace Aetheria.EditorTools
var sentinel = new IsolineExtractor.IsoSegment[extractor.Segments.count];
for (var i = 0; i < sentinel.Length; i++) sentinel[i] = Sentinel();
extractor.Segments.SetData(sentinel);
- extractor.Extract(command, field, origin, perTexel, levels);
+ extractor.Extract(command, terms, origin, perTexel, size, levels);
Graphics.ExecuteCommandBuffer(command);
var count = new uint[2];
extractor.Count.GetData(count);
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] };
+ return new Result
+ {
+ Segments = all.Take((int)count[0]).ToArray(), Backing = all, Written = count[0], Requested = count[1],
+ Samples = ReadSamples(extractor.Samples)
+ };
}
finally
{
@@ -108,24 +180,24 @@ namespace Aetheria.EditorTools
}
}
+ static Vector4[] ReadSamples(RenderTexture samples)
+ {
+ var texture = new Texture2D(samples.width, samples.height, TextureFormat.RGBAFloat, false, true);
+ var previous = RenderTexture.active;
+ RenderTexture.active = samples;
+ texture.ReadPixels(new Rect(0, 0, samples.width, samples.height), 0, 0);
+ RenderTexture.active = previous;
+ var read = texture.GetPixelData(0).ToArray();
+ UnityEngine.Object.DestroyImmediate(texture);
+ return read;
+ }
+
static IsolineExtractor.IsoSegment Sentinel() => new IsolineExtractor.IsoSegment
{
a = new Vector2(-7e7f, -7e7f), b = new Vector2(-7e7f, -7e7f), key = 0xDEADBEEF, cell = 0xFEEDFACE,
sA = -7e7f, sB = -7e7f, slopeA = -7e7f, slopeB = -7e7f, depthA = -7e7f, depthB = -7e7f
};
- static RenderTexture FieldFrom(float[] values, int width, int height)
- {
- var texture = new Texture2D(width, height, TextureFormat.RFloat, false);
- texture.SetPixelData(values, 0);
- texture.Apply(false);
- var target = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat) { filterMode = FilterMode.Point };
- target.Create();
- Graphics.CopyTexture(texture, target);
- UnityEngine.Object.DestroyImmediate(texture);
- return target;
- }
-
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;
@@ -166,10 +238,10 @@ namespace Aetheria.EditorTools
var material = AssetDatabase.LoadAssetAtPath("Assets/Materials/Brushes/Gravity Field.mat")
?? throw new InvalidOperationException("No Gravity Field.mat.");
var zone = GravityFieldParityVerify.BuildZone(settings, work, out var orbits, multiRoot: true);
- GravityLowering.Lower(zone, 0f, ref wells);
+ var terms = GravityLowering.Lower(zone, 0f, ref wells);
field = GravityLowering.CreateField(material);
- Guarded("real zone", () => RealZone(zone, orbits));
- Guarded("captures and cost", () => CapturesAndCost(zone, orbits));
+ Guarded("real zone", () => RealZone(zone, orbits, terms));
+ Guarded("captures and cost", () => CapturesAndCost(zone, orbits, terms));
Info(_ok ? "PASS" : "FAIL: see errors above");
}
catch (Exception e)
@@ -194,62 +266,76 @@ namespace Aetheria.EditorTools
// ---- layout ------------------------------------------------------------------------------------------------------
- // A 2 x 2 field whose single cell holds exactly one contour segment, with every field of it known in advance: the
- // C# struct is 48 bytes and each field the shader wrote lands in the field the C# side reads.
+ // 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.
static void Layout()
{
var size = Marshal.SizeOf();
if (size != 48) Fail("layout", $"IsoSegment is {size} bytes, not 48");
- var field = FieldFrom(new[] { .2f, .2f, .8f, .8f }, 2, 2);
+ var records = new[] { Well(new Vector2(11f, 40f), 50f, 4f, 1e4f, 2e4f) };
+ var terms = WellsFrom(records);
try
{
- var levels = new IsolineExtractor.IsolineLevels(0f, 10f, RhoMax, SlopeEpsilon);
- var result = Extract(field, new Vector2(10f, 20f), new Vector2(2f, 3f), levels, 16);
+ var origin = new Vector2(10f, 20f);
+ 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 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 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) { if (Math.Abs(got - want) > 1e-4f) Fail("layout", $"{what}: {got:G8}, expected {want:G8}"); }
- Near("a.x", s.a.x, 10f); Near("a.y", s.a.y, 21.5f); Near("b.x", s.b.x, 12f); Near("b.y", s.b.y, 21.5f);
- var sWant = -Mathf.PI / 2f * RhoMax; // the field is linear in y: kappa is 0, rho clamps to RhoMax, theta (the height gradient) is -pi/2
- Near("sA", s.sA, sWant); Near("sB", s.sB, sWant);
- Near("slopeA", s.slopeA, .2f); Near("slopeB", s.slopeB, .2f);
- Near("depthA", s.depthA, .5f); Near("depthB", s.depthB, .5f);
+ 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;
+ 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("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.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}");
}
- finally { field.Release(); UnityEngine.Object.DestroyImmediate(field); }
+ finally { Free(terms); }
}
// ---- saddle ------------------------------------------------------------------------------------------------------
- // Two wells on a diagonal with the saddle between them inside one cell: that cell's corners alternate (the case 5
+ // Two equal wells on a diagonal with the saddle between them inside one cell: that cell's corners alternate (the case 5
// pattern). At a level just below the cell's centre value the high corners connect, so each segment cuts off a low
// corner; just above, the high corners are cut off instead.
static void Saddle()
{
const int n = 32;
const int cx = 15;
- var values = new float[n * n];
- for (var y = 0; y < n; y++)
- for (var x = 0; x < n; x++)
- {
- double Well(double wx, double wy) => Math.Exp(-((x - wx) * (x - wx) + (y - wy) * (y - wy)) / 50.0);
- values[y * n + x] = (float)(10.0 * (Well(cx + .5 - 6, cx + .5 - 6) + Well(cx + .5 + 6, cx + .5 + 6)));
- }
- var corner = new[] { values[cx * n + cx], values[cx * n + cx + 1], values[(cx + 1) * n + cx + 1], values[(cx + 1) * n + cx] };
- var mean = .25f * (corner[0] + corner[1] + corner[2] + corner[3]);
- var high = Math.Min(corner[0], corner[2]);
- var low = Math.Max(corner[1], corner[3]);
- if (!(high > low + .05f)) { Fail("saddle", $"the fixture's cell does not alternate: corners {string.Join(", ", corner)}"); return; }
- 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 origin = new Vector2(-10f, 5f);
var perTexel = new Vector2(2f, 2f);
- var field = FieldFrom(values, n, n);
+ Vector2 Texel(float x, float y) => origin + new Vector2(x * perTexel.x, y * perTexel.y);
+ var records = new[]
+ {
+ Well(Texel(cx + .5f - 6f, cx + .5f - 6f), 200f, 3f, 1e4f, 2e4f),
+ Well(Texel(cx + .5f + 6f, cx + .5f + 6f), 200f, 3f, 1e4f, 2e4f)
+ };
+ var terms = WellsFrom(records);
try
{
- var result = Extract(field, origin, perTexel, new IsolineExtractor.IsolineLevels(start, 20f * spacing, RhoMax, SlopeEpsilon), 1 << 16);
+ 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; }
+ 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]);
+ var low = Math.Max(corner[1], corner[3]);
+ if (!(high > low + .05f)) { Fail("saddle", $"the fixture's cell does not alternate: corners {string.Join(", ", corner)}"); return; }
+ 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 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) })
@@ -270,8 +356,9 @@ 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);
}
- finally { field.Release(); UnityEngine.Object.DestroyImmediate(field); }
+ finally { Free(terms); }
}
// ---- along-line parameter, rays ----------------------------------------------------------------------------------
@@ -279,51 +366,52 @@ namespace Aetheria.EditorTools
sealed class Radial
{
public string Name;
+ public float Softening;
public Func D; // the profile, d(r)
public Func Slope; // |d'(r)|
}
- // Radial wells on a 128 x 128 field at 2 u per texel: d = K / (r + r0) (a reference offset) and
- // d = K / sqrt(r^2 + c^2) (a soft core). Either way the curvature radius of a contour is r, so the along-line
- // parameter is arclength on a contour and distance on a ray. The well centre sits inside a cell.
- static (RenderTexture field, Vector2 origin, Vector2 perTexel, Vector2 centre, float start, float range) RadialField(Radial profile)
+ // One softened log well on a 128 x 128 grid at 2 u per texel, its band edges far beyond the grid (inner 1e4, outer 2e4):
+ // d(r) = K (P(150) - P(r)) = K/2 ln((150^2 + e^2) / (r^2 + e^2)) up to the potential's float rounding, |d'(r)| = K Pull(r)
+ // = K r / (r^2 + e^2). Its level sets are circles, so a contour's curvature radius is r: the along-line parameter is
+ // arclength on a contour and distance on a ray. The well centre sits inside a cell.
+ const float WellStrength = 60f, WellInner = 1e4f, WellOuter = 2e4f;
+ const int GridSize = 128;
+
+ static Radial LogWell(string name, float softening) => new Radial
+ {
+ Name = name,
+ Softening = softening,
+ D = r => WellStrength * ((double)GravityField.Potential(softening, WellInner, WellOuter, 150f) - GravityField.Potential(softening, WellInner, WellOuter, (float)r)),
+ Slope = r => WellStrength * (double)GravityField.Pull(softening, WellInner, WellOuter, (float)r)
+ };
+
+ static (GravityLowering.GravityTerms terms, Vector2 origin, Vector2 perTexel, Vector2 centre, float start, float range) RadialField(Radial profile)
{
- const int n = 128;
var origin = new Vector2(-127f, -127f);
var perTexel = new Vector2(2f, 2f);
var centre = new Vector2(3.3f, -7.1f);
- var values = new float[n * n];
- for (var y = 0; y < n; y++)
- for (var x = 0; x < n; x++)
- {
- var dx = origin.x + x * perTexel.x - (double)centre.x;
- var dy = origin.y + y * perTexel.y - (double)centre.y;
- values[y * n + x] = (float)profile.D(Math.Sqrt(dx * dx + dy * dy));
- }
// the contour window: from the field's value at r = 150 (near the edge) up to its value at r = 30
var start = (float)profile.D(150);
var range = (float)(profile.D(30) - profile.D(150));
- return (FieldFrom(values, n, n), origin, perTexel, centre, start, range);
+ var reference = WellStrength * GravityField.Potential(profile.Softening, WellInner, WellOuter, 150f);
+ return (WellsFrom(new[] { Well(centre, WellStrength, profile.Softening, WellInner, WellOuter, reference) }), origin, perTexel, centre, start, range);
}
- static readonly Radial[] Profiles =
- {
- new Radial { Name = "offset", D = r => 2000.0 / (r + 40.0), Slope = r => 2000.0 / ((r + 40.0) * (r + 40.0)) },
- new Radial { Name = "soft-core", D = r => 2000.0 / Math.Sqrt(r * r + 15.0 * 15.0), Slope = r => 2000.0 * r / Math.Pow(r * r + 15.0 * 15.0, 1.5) }
- };
+ static readonly Radial[] Profiles = { LogWell("tight", 4f), LogWell("soft-core", 15f) };
- // The wells' radii the checks read: far enough from the centre to be off the core and from the field's edge to be off the
- // clamped one-sided differences (the field reaches 127 u from the origin; the well sits 3 u off centre).
+ // The radii the checks read: far enough from the centre to be off the core and inside the grid (the grid reaches 127 u
+ // from the origin; the well sits 3 u off centre).
static bool InBand(Vector2 fromCentre) => fromCentre.magnitude >= 25f && fromCentre.magnitude <= 110f;
static void AlongLine()
{
foreach (var profile in Profiles)
{
- var (field, origin, perTexel, centre, start, range) = RadialField(profile);
+ var (terms, origin, perTexel, centre, start, range) = RadialField(profile);
try
{
- var result = Extract(field, origin, perTexel, new IsolineExtractor.IsolineLevels(start, range, RhoMax, SlopeEpsilon), 1 << 18);
+ var result = Extract(terms, origin, perTexel, new Vector2Int(GridSize, GridSize), new IsolineExtractor.IsolineLevels(start, range, RhoMax, 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; }
@@ -375,10 +463,11 @@ namespace Aetheria.EditorTools
}
// 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 * 128 + (int)texel.x);
+ var holding = (uint)((int)texel.y * GridSize + (int)texel.x);
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, 128);
+ 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);
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})");
@@ -388,7 +477,7 @@ namespace Aetheria.EditorTools
if (angleWorst > RayAngleBound) Fail("rays", $"{profile.Name}: a ray endpoint's angle is off its level by {angleWorst:G4} rad > {RayAngleBound:G4}");
}
}
- finally { field.Release(); UnityEngine.Object.DestroyImmediate(field); }
+ finally { Free(terms); }
}
}
@@ -480,12 +569,12 @@ namespace Aetheria.EditorTools
static void RayWindow()
{
var profile = Profiles[0];
- var (field, origin, perTexel, centre, _, _) = RadialField(profile);
+ var (terms, origin, perTexel, centre, _, _) = RadialField(profile);
try
{
var start = (float)profile.D(90);
var range = (float)(profile.D(50) - profile.D(90));
- var result = Extract(field, origin, perTexel, new IsolineExtractor.IsolineLevels(start, range, RhoMax, SlopeEpsilon), 1 << 18);
+ var result = Extract(terms, origin, perTexel, new Vector2Int(GridSize, GridSize), new IsolineExtractor.IsolineLevels(start, range, RhoMax, 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);
@@ -493,22 +582,23 @@ namespace Aetheria.EditorTools
if (outside != 0) Fail("ray depth gate", $"{outside} ray segments lie outside the contour window");
if (inside < 20) Fail("ray depth gate", $"only {inside} ray segments inside the contour window");
}
- finally { field.Release(); UnityEngine.Object.DestroyImmediate(field); }
+ finally { Free(terms); }
}
// ---- overflow ----------------------------------------------------------------------------------------------------
static void Overflow()
{
- var (field, origin, perTexel, _, start, range) = RadialField(Profiles[0]);
+ var (terms, origin, perTexel, _, start, range) = RadialField(Profiles[0]);
try
{
var levels = new IsolineExtractor.IsolineLevels(start, range, RhoMax, SlopeEpsilon);
- var full = Extract(field, origin, perTexel, levels, 1 << 18);
+ var size = new Vector2Int(GridSize, GridSize);
+ var full = Extract(terms, origin, perTexel, size, levels, 1 << 18);
var needed = (int)full.Requested;
var capacity = needed / 2;
var guard = 32;
- var small = Extract(field, origin, perTexel, levels, capacity, backing: needed + guard);
+ var small = Extract(terms, origin, perTexel, size, levels, capacity, backing: needed + guard);
if (small.Written != capacity) Fail("overflow", $"written {small.Written}, expected the capacity {capacity}");
if (small.Requested != needed) Fail("overflow", $"requested {small.Requested}, expected {needed}");
var sentinel = Sentinel();
@@ -523,7 +613,50 @@ namespace Aetheria.EditorTools
}
Info($"overflow: needed {needed}, capacity {capacity}, written {small.Written}, requested {small.Requested}");
}
- finally { field.Release(); UnityEngine.Object.DestroyImmediate(field); }
+ finally { Free(terms); }
+ }
+
+ // ---- 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.
+ static void SamplesMatchTheLaw(string what, Result result, GravityLowering.GravityTerms terms, Vector2 origin, Vector2 perTexel,
+ Vector2Int size, float rhoMax, 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;
+ 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);
+ 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})");
+ 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 -----------------------------------------------------------------------------------------------
@@ -561,115 +694,81 @@ namespace Aetheria.EditorTools
return target;
}
- static Camera TopCamera(Vector2 centre, float halfHeight, float aspect, out GameObject owner)
- {
- owner = new GameObject("Isoline Smoke Camera");
- var camera = owner.AddComponent();
- camera.orthographic = true;
- camera.orthographicSize = halfHeight;
- camera.aspect = aspect;
- camera.nearClipPlane = .3f;
- camera.farClipPlane = 1000f;
- owner.transform.SetPositionAndRotation(new Vector3(centre.x, 100f, centre.y), Quaternion.Euler(90f, 0f, 0f));
- return camera;
- }
-
- static float MaxOf(RenderTexture target)
- {
- var previous = RenderTexture.active;
- var read = new Texture2D(target.width, target.height, TextureFormat.RFloat, false);
- RenderTexture.active = target;
- read.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0);
- read.Apply();
- RenderTexture.active = previous;
- var max = read.GetPixelData(0).ToArray().Max();
- UnityEngine.Object.DestroyImmediate(read);
- return max;
- }
-
// The planet's family: sun, planet and planetoid in one 256 x 256 window; contours from depth 0 to the deepest body's
// depth, as MapPresenter.Draw sets the map's range.
static readonly Vector2 ZoneCentre = new Vector2(300f, -50f);
const float ZoneHalf = 1600f;
- static void RealZone(Zone zone, Orbit[] orbits)
+ static void RealZone(Zone zone, Orbit[] orbits, GravityLowering.GravityTerms terms)
{
- var camera = TopCamera(ZoneCentre, ZoneHalf, 1f, out var owner);
- RenderTexture field = null;
- try
+ 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 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)));
+ 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");
+ if (contours.Length < 500) { Fail("real zone", $"only {contours.Length} contour segments: the check is vacuous"); return; }
+
+ // contours lie on their level: judged by the sim's own height
+ double shipped = 0, mutant = 0;
+ foreach (var s in contours)
{
- field = RenderField(camera, 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 result = Extract(field, origin, perTexel, levels, 1 << 20);
- 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");
- if (contours.Length < 500) { Fail("real zone", $"only {contours.Length} contour segments: the check is vacuous"); return; }
-
- // contours lie on their level: judged by the sim's own height
- double shipped = 0, mutant = 0;
- foreach (var s in contours)
- {
- var level = (LevelOf(s.key) + 1) * spacing;
- foreach (var p in new[] { s.a, s.b })
- {
- shipped = Math.Max(shipped, Math.Abs(-zone.GetHeight(new float2(p.x, p.y)) - level) / spacing);
- var tx = (p.x - origin.x) / perTexel.x;
- var ty = (p.y - origin.y) / perTexel.y;
- var onX = Math.Abs(tx - Math.Round(tx)) < 1e-3; // on a vertical grid line: the edge runs in y
- var onY = Math.Abs(ty - Math.Round(ty)) < 1e-3;
- if (onX == onY) continue;
- // the mutant: the crossing at the edge's midpoint instead of interpolated
- var q = onX ? new Vector2(p.x, origin.y + (Mathf.Floor((float)ty) + .5f) * perTexel.y)
- : new Vector2(origin.x + (Mathf.Floor((float)tx) + .5f) * perTexel.x, p.y);
- mutant = Math.Max(mutant, Math.Abs(-zone.GetHeight(new float2(q.x, q.y)) - level) / spacing);
- }
- }
- Info($"ray segments per level, real zone: {string.Join(" ", Enumerable.Range(0, 12).Select(k => result.Segments.Count(r => IsRay(r.key) && LevelOf(r.key) == k)))}");
- Info($"real zone: {contours.Length} contours, {result.Segments.Length - contours.Length} rays; level error worst {shipped:G4} spacing (mutant midpoint {mutant:G4}, ratio {mutant / shipped:G3})");
- if (shipped > LevelErrorBound) Fail("contours lie on their level", $"worst {shipped:G4} spacings > {LevelErrorBound:G4}");
-
- // contours close: every endpoint off the field border is shared by exactly one other endpoint of its level
- var minX = Math.Min(origin.x, origin.x + 255 * perTexel.x);
- var maxX = Math.Max(origin.x, origin.x + 255 * perTexel.x);
- var minY = Math.Min(origin.y, origin.y + 255 * perTexel.y);
- var maxY = Math.Max(origin.y, origin.y + 255 * perTexel.y);
- var tolerance = Math.Abs(perTexel.x) * 1e-3f;
- bool Border(Vector2 p) => Math.Abs(p.x - minX) < tolerance || Math.Abs(p.x - maxX) < tolerance
- || Math.Abs(p.y - minY) < tolerance || Math.Abs(p.y - maxY) < tolerance;
- var seen = new Dictionary<(int, int, int), int>();
- foreach (var s in contours)
+ var level = (LevelOf(s.key) + 1) * spacing;
foreach (var p in new[] { s.a, s.b })
{
- var key = (LevelOf(s.key), BitConverter.SingleToInt32Bits(p.x), BitConverter.SingleToInt32Bits(p.y));
- seen[key] = seen.TryGetValue(key, out var c) ? c + 1 : 1;
+ shipped = Math.Max(shipped, Math.Abs(-zone.GetHeight(new float2(p.x, p.y)) - level) / spacing);
+ var tx = (p.x - origin.x) / perTexel.x;
+ var ty = (p.y - origin.y) / perTexel.y;
+ var onX = Math.Abs(tx - Math.Round(tx)) < 1e-3; // on a vertical grid line: the edge runs in y
+ var onY = Math.Abs(ty - Math.Round(ty)) < 1e-3;
+ if (onX == onY) continue;
+ // the mutant: the crossing at the edge's midpoint instead of interpolated
+ var q = onX ? new Vector2(p.x, origin.y + (Mathf.Floor((float)ty) + .5f) * perTexel.y)
+ : new Vector2(origin.x + (Mathf.Floor((float)tx) + .5f) * perTexel.x, p.y);
+ mutant = Math.Max(mutant, Math.Abs(-zone.GetHeight(new float2(q.x, q.y)) - level) / spacing);
}
- var open = 0;
- foreach (var s in contours)
- foreach (var p in new[] { s.a, s.b })
- 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");
}
- finally
+ Info($"ray segments per level, real zone: {string.Join(" ", Enumerable.Range(0, 12).Select(k => result.Segments.Count(r => IsRay(r.key) && LevelOf(r.key) == k)))}");
+ Info($"real zone: {contours.Length} contours, {result.Segments.Length - contours.Length} rays; level error worst {shipped:G4} spacing (mutant midpoint {mutant:G4}, ratio {mutant / shipped:G3})");
+ if (shipped > LevelErrorBound) Fail("contours lie on their level", $"worst {shipped:G4} spacings > {LevelErrorBound:G4}");
+
+ // contours close: every endpoint off the field border is shared by exactly one other endpoint of its level
+ var minX = Math.Min(origin.x, origin.x + 255 * perTexel.x);
+ var maxX = Math.Max(origin.x, origin.x + 255 * perTexel.x);
+ var minY = Math.Min(origin.y, origin.y + 255 * perTexel.y);
+ var maxY = Math.Max(origin.y, origin.y + 255 * perTexel.y);
+ var tolerance = Math.Abs(perTexel.x) * 1e-3f;
+ bool Border(Vector2 p) => Math.Abs(p.x - minX) < tolerance || Math.Abs(p.x - maxX) < tolerance
+ || Math.Abs(p.y - minY) < tolerance || Math.Abs(p.y - maxY) < tolerance;
+ var seen = new Dictionary<(int, int, int), int>();
+ foreach (var s in contours)
+ foreach (var p in new[] { s.a, s.b })
{
- if (field != null) { field.Release(); UnityEngine.Object.DestroyImmediate(field); }
- UnityEngine.Object.DestroyImmediate(owner);
+ var key = (LevelOf(s.key), BitConverter.SingleToInt32Bits(p.x), BitConverter.SingleToInt32Bits(p.y));
+ seen[key] = seen.TryGetValue(key, out var c) ? c + 1 : 1;
}
+ var open = 0;
+ foreach (var s in contours)
+ foreach (var p in new[] { s.a, s.b })
+ 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");
}
// ---- captures and cost -------------------------------------------------------------------------------------------
const int CaptureSize = 512;
- static void CapturesAndCost(Zone zone, Orbit[] orbits)
+ static void CapturesAndCost(Zone zone, Orbit[] orbits, GravityLowering.GravityTerms terms)
{
// before.png: the ARPG scene's own Map Gravity camera draws the minimap field (as authored, 128 x 128, here over
// the fixture zone), and Minimap Gravity Lines.mat draws it as it does today.
@@ -698,7 +797,7 @@ namespace Aetheria.EditorTools
// 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 result = Extract(field, origin, perTexel, levels, 1 << 18);
+ 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());
Vector2 Pixel(Vector2 p) => new Vector2(((p.x - origin.x) / perTexel.x + .5f) / 128f * CaptureSize, ((p.y - origin.y) / perTexel.y + .5f) / 128f * CaptureSize);
@@ -716,20 +815,18 @@ namespace Aetheria.EditorTools
// cost: paired interleaved medians of one Extract at 128 x 128 and at 1920 x 1080, each timed to a fence (the
// count read back). Wall clock around the recorded dispatches and the fence; the GPU recorder only advances
// with a frame loop, which batchmode has none of, so its reading is reported as it comes.
- var bigOwner = default(GameObject);
- var bigCamera = TopCamera(ZoneCentre, ZoneHalf, 1920f / 1080f, out bigOwner);
- var big = RenderField(bigCamera, 1920, 1080, out var bigOrigin, out var bigPerTexel);
+ TopFrame(ZoneCentre, ZoneHalf, 1920, 1080, out var bigOrigin, out var bigPerTexel);
var small = new IsolineExtractor(Shader, 1 << 18);
var large = new IsolineExtractor(Shader, 1 << 20);
var recorder = Recorder.Get("IsolineExtract");
recorder.enabled = true;
try
{
- double Measure(IsolineExtractor extractor, RenderTexture target, Vector2 o, Vector2 p)
+ double Measure(IsolineExtractor extractor, Vector2 o, Vector2 p, Vector2Int grid)
{
var command = new CommandBuffer { name = "IsolineExtract" };
command.BeginSample("IsolineExtract");
- extractor.Extract(command, target, o, p, levels);
+ extractor.Extract(command, terms, o, p, grid, levels);
command.EndSample("IsolineExtract");
var clock = Stopwatch.StartNew();
Graphics.ExecuteCommandBuffer(command);
@@ -738,13 +835,13 @@ namespace Aetheria.EditorTools
command.Release();
return clock.Elapsed.TotalMilliseconds;
}
- Measure(small, field, origin, perTexel); Measure(large, big, bigOrigin, bigPerTexel); // warm up
+ Measure(small, origin, perTexel, new Vector2Int(128, 128)); Measure(large, bigOrigin, bigPerTexel, new Vector2Int(1920, 1080)); // warm up
var a = new List();
var b = new List();
for (var i = 0; i < 21; i++)
{
- a.Add(Measure(small, field, origin, perTexel));
- b.Add(Measure(large, big, bigOrigin, bigPerTexel));
+ a.Add(Measure(small, origin, perTexel, new Vector2Int(128, 128)));
+ b.Add(Measure(large, bigOrigin, bigPerTexel, new Vector2Int(1920, 1080)));
}
a.Sort(); b.Sort();
var counts = new uint[2];
@@ -756,9 +853,6 @@ namespace Aetheria.EditorTools
recorder.enabled = false;
small.Release();
large.Release();
- big.Release();
- UnityEngine.Object.DestroyImmediate(big);
- UnityEngine.Object.DestroyImmediate(bigOwner);
field.Release();
UnityEngine.Object.DestroyImmediate(field);
}
diff --git a/Assets/Scripts/Editor/IsolineRenderSmoke.cs b/Assets/Scripts/Editor/IsolineRenderSmoke.cs
index 6b1e9cc29..01e029eef 100644
--- a/Assets/Scripts/Editor/IsolineRenderSmoke.cs
+++ b/Assets/Scripts/Editor/IsolineRenderSmoke.cs
@@ -277,11 +277,11 @@ namespace Aetheria.EditorTools
var material = AssetDatabase.LoadAssetAtPath("Assets/Materials/Brushes/Gravity Field.mat")
?? throw new InvalidOperationException("No Gravity Field.mat.");
var zone = GravityFieldParityVerify.BuildZone(settings, work, out var orbits, multiRoot: true);
- GravityLowering.Lower(zone, 0f, ref wells);
+ var terms = GravityLowering.Lower(zone, 0f, ref wells);
field = GravityLowering.CreateField(material);
- Guarded("flow follows depth near the real-zone saddle", () => FlowOnRealZone(zone, orbits));
- Guarded("stress field and the shipped pool", () => StressAndPool(zone, orbits));
- Guarded("captures and cost", () => CapturesAndCost(zone, orbits));
+ Guarded("flow follows depth near the real-zone saddle", () => FlowOnRealZone(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");
}
catch (Exception e)
@@ -896,10 +896,8 @@ namespace Aetheria.EditorTools
static float ContourRange(Zone zone, Orbit[] orbits) => Math.Max(1f, orbits.Max(o => -zone.GetHeight(new float2(o.Position.x, o.Position.y))));
// Rays only, over the real zone's saddle: raw dir against the depth change along +s judged by Zone.GetHeight.
- static void FlowOnRealZone(Zone zone, Orbit[] orbits)
+ static void FlowOnRealZone(Zone zone, Orbit[] orbits, GravityLowering.GravityTerms terms)
{
- var fieldCamera = Ortho(ZoneCentre, ZoneHalf, 256, 256);
- RenderTexture field = null;
var renderer = new IsolineRenderer(ExtractShader, RenderShader, ShippedSegments, ShippedPool);
var view = Ortho(Saddle, 240f, 512, 512);
var target = new RenderTexture(512, 512, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear) { enableRandomWrite = true, filterMode = FilterMode.Point };
@@ -907,10 +905,10 @@ namespace Aetheria.EditorTools
var command = new CommandBuffer { name = "IsolineFlowProbe" };
try
{
- field = RenderField(fieldCamera.Camera, 256, 256, out var origin, out var perTexel);
+ 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);
- renderer.Extractor.Extract(command, field, origin, perTexel, levels);
+ 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);
var (segments, _) = ReadExtraction(renderer.Extractor);
@@ -966,53 +964,33 @@ namespace Aetheria.EditorTools
target.Release();
UnityEngine.Object.DestroyImmediate(target);
renderer.Release();
- if (field != null) { field.Release(); UnityEngine.Object.DestroyImmediate(field); }
view.Dispose();
- fieldCamera.Dispose();
}
}
// ---- stress, captures and cost ------------------------------------------------------------------------------------
- // 60 soft-core wells over 1920 x 1080 units at 1 u per texel, steep enough that the contour levels crowd below a pixel.
- static float[] StressValues(out float range)
+ // 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)
{
- const int W = 1920, H = 1080;
var rng = new System.Random(11);
- var wells = Enumerable.Range(0, 60).Select(_ => (x: (float)rng.NextDouble() * W, y: (float)rng.NextDouble() * H,
- k: 800f + (float)rng.NextDouble() * 3200f, c: 6f + (float)rng.NextDouble() * 14f)).ToArray();
- var values = new float[W * H];
- for (var y = 0; y < H; y++)
- for (var x = 0; x < W; x++)
+ var wells = Enumerable.Range(0, 60).Select(_ =>
{
- var d = 0f;
- foreach (var w in wells)
- {
- var dx = x + .5f - w.x; var dy = y + .5f - w.y;
- d += w.k / Mathf.Sqrt(dx * dx + dy * dy + w.c * w.c);
- }
- values[y * W + x] = d;
- }
+ var at = new Vector2((float)rng.NextDouble() * 1920f, (float)rng.NextDouble() * 1080f);
+ var strength = 300f + (float)rng.NextDouble() * 900f;
+ var softening = 6f + (float)rng.NextDouble() * 14f;
+ var inner = 15f + (float)rng.NextDouble() * 25f;
+ var outer = 120f + (float)rng.NextDouble() * 140f;
+ return new GravityLowering.TermRecord { Position = at, Strength = strength, Softening = softening, Inner = inner, Outer = outer, Reference = 0f };
+ }).ToArray();
range = 900f;
- return values;
+ return wells;
}
- static RenderTexture FieldFrom(float[] values, int width, int height)
+ static void StressAndPool()
{
- var texture = new Texture2D(width, height, TextureFormat.RFloat, false);
- texture.SetPixelData(values, 0);
- texture.Apply(false);
- var target = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat) { filterMode = FilterMode.Point };
- target.Create();
- Graphics.CopyTexture(texture, target);
- UnityEngine.Object.DestroyImmediate(texture);
- return target;
- }
-
- static void StressAndPool(Zone zone, Orbit[] orbits)
- {
- var values = StressValues(out var range);
- var field = FieldFrom(values, 1920, 1080);
+ var terms = IsolineExtractSmoke.WellsFrom(StressWells(out var range));
var view = Ortho(new Vector2(960f, 540f), 540f, 1920, 1080);
var renderer = new IsolineRenderer(ExtractShader, RenderShader, ShippedSegments, ShippedPool);
var target = new RenderTexture(1920, 1080, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear) { enableRandomWrite = true };
@@ -1022,7 +1000,7 @@ namespace Aetheria.EditorTools
{
var levels = new IsolineExtractor.IsolineLevels(0f, range, 1000f, SlopeEpsilon);
// texel (x, y) sits at world (x, y) + .5: origin (.5, .5), step 1
- renderer.Record(command, field, new Vector2(.5f, .5f), Vector2.one, levels, view.ViewProjection, target, IsolineLook.Default, 0f);
+ renderer.Record(command, terms, new Vector2(.5f, .5f), Vector2.one, new Vector2Int(1920, 1080), levels, view.ViewProjection, target, IsolineLook.Default, 0f);
Graphics.ExecuteCommandBuffer(command);
var stats = new uint[6];
renderer.Stats.GetData(stats);
@@ -1039,8 +1017,7 @@ namespace Aetheria.EditorTools
target.Release();
UnityEngine.Object.DestroyImmediate(target);
renderer.Release();
- field.Release();
- UnityEngine.Object.DestroyImmediate(field);
+ terms.Buffer.Release();
view.Dispose();
}
}
@@ -1088,7 +1065,7 @@ namespace Aetheria.EditorTools
return t;
}
- static void CapturesAndCost(Zone zone, Orbit[] orbits)
+ 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);
@@ -1106,7 +1083,7 @@ namespace Aetheria.EditorTools
var miniRenderer = new IsolineRenderer(ExtractShader, RenderShader, ShippedSegments, ShippedPool);
var miniTarget = HalfTarget(256, 256);
var miniVp = GL.GetGPUProjectionMatrix(sceneCamera.projectionMatrix, true) * sceneCamera.worldToCameraMatrix;
- RecordAndSave(miniRenderer, minimapField, miniOrigin, miniPerTexel, levels, miniVp, miniTarget, look, "minimap-after.png");
+ RecordAndSave(miniRenderer, terms, miniOrigin, miniPerTexel, new Vector2Int(128, 128), levels, miniVp, miniTarget, look, "minimap-after.png");
// map screen: a screen-sized field over the same zone, ortho size = height * Scale / 2, material _Scale = Scale / 2
var mapView = Ortho(ZoneCentre, 1100f, 1920, 1080);
@@ -1115,7 +1092,7 @@ namespace Aetheria.EditorTools
Blit(mapMaterial, mapField, 1920, 1080, range, mapScale / 2f, "map-before.png");
var mapRenderer = new IsolineRenderer(ExtractShader, RenderShader, ShippedSegments, ShippedPool);
var mapTarget = HalfTarget(1920, 1080);
- RecordAndSave(mapRenderer, mapField, mapOrigin, mapPerTexel, levels, mapView.ViewProjection, mapTarget, look, "map-after.png");
+ RecordAndSave(mapRenderer, terms, mapOrigin, mapPerTexel, new Vector2Int(1920, 1080), levels, mapView.ViewProjection, mapTarget, look, "map-after.png");
var (mapSegments, mapCounts) = ReadExtraction(mapRenderer.Extractor);
var mapStats = new uint[6];
mapRenderer.Stats.GetData(mapStats);
@@ -1128,7 +1105,7 @@ namespace Aetheria.EditorTools
var tacticalField = RenderField(tacticalCamera.Camera, 1024, 1024, out var tOrigin, out var tPerTexel);
var tacticalView = Tactical(new Vector2(380f, -100f), 900f, 55f, 20f, 1280, 720);
var tacticalTarget = HalfTarget(1280, 720);
- RecordAndSave(mapRenderer, tacticalField, tOrigin, tPerTexel, levels, tacticalView.ViewProjection, tacticalTarget, look, "tactical.png");
+ RecordAndSave(mapRenderer, terms, tOrigin, tPerTexel, new Vector2Int(1024, 1024), levels, tacticalView.ViewProjection, tacticalTarget, look, "tactical.png");
// flowing rays: six phases of one dash period around the saddle, from a 512 x 512 field
var flowView = Ortho(Saddle, 300f, 512, 512);
@@ -1139,15 +1116,16 @@ namespace Aetheria.EditorTools
var flowTarget = HalfTarget(512, 512);
var flowRenderer = new IsolineRenderer(ExtractShader, RenderShader, ShippedSegments, ShippedPool);
for (var phase = 0; phase < 6; phase++)
- RecordAndSave(flowRenderer, flowField, fOrigin, fPerTexel, levels, flowView.ViewProjection, flowTarget, flowLook, $"flow-{phase}.png", phase / 6f);
+ RecordAndSave(flowRenderer, terms, fOrigin, fPerTexel, new Vector2Int(512, 512), levels, flowView.ViewProjection, flowTarget, flowLook, $"flow-{phase}.png", phase / 6f);
- Cost("256 x 256 (minimap)", miniRenderer, minimapField, miniOrigin, miniPerTexel, levels, miniVp, miniTarget, look, minimapMaterial, 10f, range);
- Cost("1920 x 1080 (map)", mapRenderer, mapField, mapOrigin, mapPerTexel, levels, mapView.ViewProjection, mapTarget, look, mapMaterial, mapScale / 2f, range);
- var stressValues = StressValues(out var stressRange);
- var stressField = FieldFrom(stressValues, 1920, 1080);
+ Cost("256 x 256 (minimap)", miniRenderer, terms, new Vector2Int(128, 128), minimapField, miniOrigin, miniPerTexel, levels, miniVp, miniTarget, look, minimapMaterial, 10f, range);
+ Cost("1920 x 1080 (map)", mapRenderer, terms, new Vector2Int(1920, 1080), mapField, mapOrigin, mapPerTexel, levels, mapView.ViewProjection, mapTarget, look, mapMaterial, mapScale / 2f, range);
+ var stressTerms = IsolineExtractSmoke.WellsFrom(StressWells(out var stressRange));
+ 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, stressField, new Vector2(.5f, .5f), Vector2.one,
+ 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);
+ stressTerms.Buffer.Release();
Info("captures:\n" + _wrote);
foreach (var r in new[] { miniRenderer, mapRenderer, flowRenderer }) r.Release();
@@ -1179,11 +1157,11 @@ namespace Aetheria.EditorTools
UnityEngine.Object.DestroyImmediate(lines);
}
- static void RecordAndSave(IsolineRenderer renderer, RenderTexture field, Vector2 origin, Vector2 perTexel,
+ static void RecordAndSave(IsolineRenderer renderer, in GravityLowering.GravityTerms terms, Vector2 origin, Vector2 perTexel, Vector2Int size,
IsolineExtractor.IsolineLevels levels, Matrix4x4 viewProjection, RenderTexture target, IsolineLook look, string name, float time = 0f)
{
var command = new CommandBuffer { name = "IsolineCapture" };
- renderer.Record(command, field, origin, perTexel, levels, viewProjection, target, look, time);
+ renderer.Record(command, terms, origin, perTexel, size, levels, viewProjection, target, look, time);
Graphics.ExecuteCommandBuffer(command);
command.Release();
Save(name, target, target.width, target.height);
@@ -1194,7 +1172,7 @@ namespace Aetheria.EditorTools
// each prefix repeated Reps times in one command buffer, and a kernel's cost is the paired difference of two
// neighbouring prefixes in the same iteration. Median of 31 interleaved iterations, ms per pass; the old material blit
// at the same size is timed beside them through a 1 pixel readback.
- static void Cost(string label, IsolineRenderer renderer, RenderTexture field, Vector2 origin, Vector2 perTexel,
+ static void Cost(string label, IsolineRenderer renderer, GravityLowering.GravityTerms terms, Vector2Int size, RenderTexture field, Vector2 origin, Vector2 perTexel,
IsolineExtractor.IsolineLevels levels, Matrix4x4 viewProjection, RenderTexture target, IsolineLook look,
Material oldMaterial, float oldScale, float oldRange)
{
@@ -1211,7 +1189,7 @@ namespace Aetheria.EditorTools
var scratch = new uint[6];
// fill the buffers once so the kernel prefixes have segments
var fill = new CommandBuffer();
- renderer.Extractor.Extract(fill, field, origin, perTexel, levels);
+ renderer.Extractor.Extract(fill, terms, origin, perTexel, size, levels);
Graphics.ExecuteCommandBuffer(fill);
fill.Release();
@@ -1237,6 +1215,7 @@ namespace Aetheria.EditorTools
var prefixes = Enumerable.Range(0, 7).Select(_ => new List()).ToArray();
var extract = new List();
var blit = new List();
+ var sampleAlone = new List();
for (var iteration = -2; iteration < Iterations; iteration++)
{
for (var k = 0; k <= 6; k++)
@@ -1245,9 +1224,11 @@ namespace Aetheria.EditorTools
var t = Time(c => renderer.Draw(c, renderer.Extractor.Segments, renderer.Extractor.Count, levels, viewProjection, target, look, 0f, false, 0, stop), StatsFence);
if (iteration >= 0) prefixes[k].Add(t);
}
- var e = Time(c => renderer.Extractor.Extract(c, field, origin, perTexel, levels), () => renderer.Extractor.Count.GetData(new uint[2]));
+ // 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 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); }
+ if (iteration >= 0) { extract.Add(e); blit.Add(b); sampleAlone.Add(sa); }
}
var names = new[] { "Args", "Clear", "Bin", "Scan", "Scatter", "Shade" };
var parts = new List();
@@ -1260,7 +1241,7 @@ namespace Aetheria.EditorTools
parts.Add($"{names[k - 1]} {m:F3}");
}
var total = Median(prefixes[6].Select((v, i) => v - prefixes[0][i]).ToList());
- Info($"cost {label}: ms per pass, median of {Iterations} interleaved iterations x {Reps} reps, wall clock to a fence, kernel = paired difference of prefixes: {string.Join(", ", parts)}; renderer total {total:F3} (kernel sum {sum:F3}); Extract {Median(extract):F3}; old material blit {Median(blit):F3}; fence alone {Median(prefixes[0]):F3}; recorder {(recorder.isValid ? recorder.gpuElapsedNanoseconds / 1e6 + " ms" : "unmeasured (no frame loop)")}");
+ Info($"cost {label}: ms per pass, median of {Iterations} interleaved iterations x {Reps} reps, wall clock to a fence, kernel = paired difference of prefixes: {string.Join(", ", parts)}; renderer total {total:F3} (kernel sum {sum:F3}); Extract {Median(extract):F3} (Sample alone {Median(sampleAlone):F3}); old material blit {Median(blit):F3}; fence alone {Median(prefixes[0]):F3}; recorder {(recorder.isValid ? recorder.gpuElapsedNanoseconds / 1e6 + " ms" : "unmeasured (no frame loop)")}");
recorder.enabled = false;
blitTarget.Release();
UnityEngine.Object.DestroyImmediate(blitTarget);
diff --git a/Assets/Scripts/Zone Display/GravityLowering.cs b/Assets/Scripts/Zone Display/GravityLowering.cs
index 2c0a0c2b3..18b6f1eab 100644
--- a/Assets/Scripts/Zone Display/GravityLowering.cs
+++ b/Assets/Scripts/Zone Display/GravityLowering.cs
@@ -14,9 +14,25 @@ public static class GravityLowering
/// The quad's side in u: larger than any zone (10000) plus any view (4096); texels outside a camera cost nothing.
public const float FieldExtent = 100000f;
+ /// What Lower just lowered: the buffer of term records (Gravity.cginc GravityTerm), how many it holds and the
+ /// height exaggeration, for a compute shader that binds them itself rather than reading the globals Lower also sets.
+ public readonly struct GravityTerms
+ {
+ public readonly ComputeBuffer Buffer;
+ public readonly int Count;
+ public readonly float Exaggeration;
+
+ public GravityTerms(ComputeBuffer buffer, int count, float exaggeration)
+ {
+ Buffer = buffer;
+ Count = count;
+ Exaggeration = exaggeration;
+ }
+ }
+
// Mirrors the term record of Gravity.cginc: float2 position, strength, softening, inner, outer, reference.
[StructLayout(LayoutKind.Sequential)]
- struct TermRecord
+ public struct TermRecord
{
public Vector2 Position;
public float Strength;
@@ -37,7 +53,7 @@ public static class GravityLowering
/// the caller's, (re)allocated to the term count (at least one, so the global is always bound). Terms are lowered at
/// their node's rail at the drawn time (DrawAhead.Time), the same T the planets and a ship's ride height use.
///
- public static void Lower(Zone zone, float lead, ref ComputeBuffer wells)
+ public static GravityTerms Lower(Zone zone, float lead, ref ComputeBuffer wells)
{
var count = zone?.Wells.Terms.Count ?? 0;
var capacity = Mathf.Max(count, 1);
@@ -66,7 +82,9 @@ public static class GravityLowering
Shader.SetGlobalBuffer(WellsId, wells);
Shader.SetGlobalInt(CountId, count);
- Shader.SetGlobalFloat(ExaggerationId, zone?.Settings.HeightExaggeration ?? 1f);
+ var exaggeration = zone?.Settings.HeightExaggeration ?? 1f;
+ Shader.SetGlobalFloat(ExaggerationId, exaggeration);
+ return new GravityTerms(wells, count, exaggeration);
}
/// The one quad of the field: flat in xz at y 0 on layer 9, drawn with the Gravity Field material.
diff --git a/Assets/Scripts/Zone Display/IsolineExtractor.cs b/Assets/Scripts/Zone Display/IsolineExtractor.cs
index 4e216168c..6a77e5ced 100644
--- a/Assets/Scripts/Zone Display/IsolineExtractor.cs
+++ b/Assets/Scripts/Zone Display/IsolineExtractor.cs
@@ -6,8 +6,9 @@ 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 decides which segments exist and every attribute they carry. Nothing here reads a result back or edits a
-/// segment, and nothing in the frame calls it yet: the renderer that consumes Segments and Count is a later cut.
+/// shader evaluates d, its gradient and its Hessian 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.
///
public sealed class IsolineExtractor
{
@@ -41,18 +42,21 @@ public sealed class IsolineExtractor
}
}
- static readonly int Field = Shader.PropertyToID("_Field");
- static readonly int GradOut = Shader.PropertyToID("_GradOut");
- static readonly int GradIn = Shader.PropertyToID("_GradIn");
- static readonly int CurveOut = Shader.PropertyToID("_CurveOut");
- static readonly int CurveIn = Shader.PropertyToID("_CurveIn");
+ static readonly int SampleOut = Shader.PropertyToID("_SampleOut");
+ static readonly int SampleIn = Shader.PropertyToID("_SampleIn");
+ static readonly int WellsId = Shader.PropertyToID("_GravityWells");
+ static readonly int WellCountId = Shader.PropertyToID("_GravityWellCount");
+ static readonly int ExaggerationId = Shader.PropertyToID("_HeightExaggeration");
static readonly int SegmentsId = Shader.PropertyToID("_Segments");
static readonly int CountId = Shader.PropertyToID("_Count");
static readonly uint[] Zero = new uint[2];
readonly ComputeShader _shader;
- readonly int _derive, _curve, _march, _finish;
- RenderTexture _grad, _curvature;
+ 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.
+ public RenderTexture Samples => _samples;
/// The segment buffer, IsoSegment[backing]; overwritten by each Extract.
public GraphicsBuffer Segments { get; }
@@ -69,8 +73,7 @@ public sealed class IsolineExtractor
{
_shader = shader;
Capacity = capacity;
- _derive = shader.FindKernel("Derive");
- _curve = shader.FindKernel("Curve");
+ _sample = shader.FindKernel("Sample");
_march = shader.FindKernel("March");
_finish = shader.FindKernel("Finish");
Segments = new GraphicsBuffer(GraphicsBuffer.Target.Structured, Mathf.Max(capacity, backing), Marshal.SizeOf());
@@ -78,21 +81,21 @@ public sealed class IsolineExtractor
}
///
- /// Records the extraction of one field texture. The field is d per texel (deeper is larger); texel (x, y)'s centre sits
- /// at worldOrigin + (x, y) * worldPerTexel in world xz, the step signed per axis as the camera that drew it has it.
+ /// 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).
///
- public void Extract(CommandBuffer cmd, RenderTexture field, Vector2 worldOrigin, Vector2 worldPerTexel, IsolineLevels levels)
+ public void Extract(CommandBuffer cmd, in GravityLowering.GravityTerms terms, Vector2 worldOrigin, Vector2 worldPerTexel,
+ Vector2Int size, IsolineLevels levels, bool sampleOnly = false)
{
- if (_grad == null || _grad.width != field.width || _grad.height != field.height)
+ if (_samples == null || _samples.width != size.x || _samples.height != size.y)
{
- Release(ref _grad);
- Release(ref _curvature);
- _grad = Scratch(field, GraphicsFormat.R32G32B32A32_SFloat);
- _curvature = Scratch(field, GraphicsFormat.R32G32_SFloat);
+ Release(ref _samples);
+ _samples = Scratch(size.x, size.y, GraphicsFormat.R32G32B32A32_SFloat);
}
cmd.SetBufferData(Count, Zero);
- cmd.SetComputeIntParams(_shader, "_Size", field.width, field.height);
+ cmd.SetComputeIntParams(_shader, "_Size", size.x, size.y);
cmd.SetComputeVectorParam(_shader, "_Origin", worldOrigin);
cmd.SetComputeVectorParam(_shader, "_PerTexel", worldPerTexel);
cmd.SetComputeFloatParam(_shader, "_Start", levels.Start);
@@ -103,18 +106,16 @@ public sealed class IsolineExtractor
cmd.SetComputeFloatParam(_shader, "_SlopeEpsilon", levels.SlopeEpsilon);
cmd.SetComputeIntParam(_shader, "_Capacity", Capacity);
- var groupsX = (field.width + 7) / 8;
- var groupsY = (field.height + 7) / 8;
- cmd.SetComputeTextureParam(_shader, _derive, Field, field);
- cmd.SetComputeTextureParam(_shader, _derive, GradOut, _grad);
- cmd.DispatchCompute(_shader, _derive, groupsX, groupsY, 1);
+ var groupsX = (size.x + 7) / 8;
+ var groupsY = (size.y + 7) / 8;
+ cmd.SetComputeBufferParam(_shader, _sample, WellsId, terms.Buffer);
+ cmd.SetComputeIntParam(_shader, WellCountId, terms.Count);
+ 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
- cmd.SetComputeTextureParam(_shader, _curve, GradIn, _grad);
- cmd.SetComputeTextureParam(_shader, _curve, CurveOut, _curvature);
- cmd.DispatchCompute(_shader, _curve, groupsX, groupsY, 1);
-
- cmd.SetComputeTextureParam(_shader, _march, GradIn, _grad);
- cmd.SetComputeTextureParam(_shader, _march, CurveIn, _curvature);
+ cmd.SetComputeTextureParam(_shader, _march, SampleIn, _samples);
cmd.SetComputeBufferParam(_shader, _march, SegmentsId, Segments);
cmd.SetComputeBufferParam(_shader, _march, CountId, Count);
cmd.DispatchCompute(_shader, _march, groupsX, groupsY, 1);
@@ -125,15 +126,14 @@ public sealed class IsolineExtractor
public void Release()
{
- Release(ref _grad);
- Release(ref _curvature);
+ Release(ref _samples);
Segments.Release();
Count.Release();
}
- static RenderTexture Scratch(RenderTexture like, GraphicsFormat format)
+ static RenderTexture Scratch(int width, int height, GraphicsFormat format)
{
- var texture = new RenderTexture(like.width, like.height, 0, format)
+ var texture = new RenderTexture(width, height, 0, format)
{ enableRandomWrite = true, filterMode = FilterMode.Point, hideFlags = HideFlags.HideAndDontSave };
texture.Create();
return texture;
diff --git a/Assets/Scripts/Zone Display/IsolineRenderer.cs b/Assets/Scripts/Zone Display/IsolineRenderer.cs
index f9c5e9982..c598a90b4 100644
--- a/Assets/Scripts/Zone Display/IsolineRenderer.cs
+++ b/Assets/Scripts/Zone Display/IsolineRenderer.cs
@@ -136,14 +136,14 @@ public sealed class IsolineRenderer
}
///
- /// Records the extraction of the field and the drawing of its segments. viewProjection is
+ /// Records the extraction of the zone field on the caller sample grid (terms, origin, step, size) and the drawing of its segments. viewProjection is
/// GL.GetGPUProjectionMatrix(camera.projectionMatrix, true) * camera.worldToCameraMatrix; target is an ARGBHalf
/// enableRandomWrite texture in linear colour. Camera-general: orthographic or perspective.
///
- public void Record(CommandBuffer cmd, RenderTexture field, Vector2 worldOrigin, Vector2 worldPerTexel, IsolineLevels levels,
- Matrix4x4 viewProjection, RenderTexture target, in IsolineLook look, float time)
+ public void Record(CommandBuffer cmd, in GravityLowering.GravityTerms terms, Vector2 worldOrigin, Vector2 worldPerTexel, Vector2Int size,
+ IsolineLevels levels, Matrix4x4 viewProjection, RenderTexture target, in IsolineLook look, float time)
{
- _extractor.Extract(cmd, field, worldOrigin, worldPerTexel, levels);
+ _extractor.Extract(cmd, terms, worldOrigin, worldPerTexel, size, levels);
Draw(cmd, _extractor.Segments, _extractor.Count, levels, viewProjection, target, look, time);
}
diff --git a/Assets/Shaders/IsolineExtract.compute b/Assets/Shaders/IsolineExtract.compute
index 9de68fcf0..fbeafcf8e 100644
--- a/Assets/Shaders/IsolineExtract.compute
+++ b/Assets/Shaders/IsolineExtract.compute
@@ -1,32 +1,30 @@
-// Isoline extraction on the GPU (campaign aetheria-release, cut isoline-extraction). Reads one gravity field texture
-// (d = -Zone.GetHeight per texel, written only by Brushes/Gravity Field) and writes world-space line segments of two
-// isoline families into a segment buffer, with no readback:
+// 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
+// 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: Derive (gradient), Curve (level-set curvature radius), March (marching squares), Finish.
+// Kernels, in dispatch order: Sample (d, gradient and the level set's curvature radius), March (marching squares), Finish.
// The count buffer is cleared by the recorded command list before March (IsolineExtractor).
-#pragma kernel Derive
-#pragma kernel Curve
+#pragma kernel Sample
#pragma kernel March
#pragma kernel Finish
#include "IsolineSegment.hlsl"
+#include "Gravity.cginc"
#define PI 3.14159265358979
#define TWO_PI 6.28318530717959
-Texture2D _Field;
-RWTexture2D _GradOut; // Derive: (gx, gy, |g|, d), gradient of d in world units per world unit
-Texture2D _GradIn; // Curve, March
-RWTexture2D _CurveOut; // Curve: (theta, rho)
-Texture2D _CurveIn; // March
+RWTexture2D _SampleOut; // Sample: (gx, gy, d, rho), gradient of d in world units per world unit
+Texture2D _SampleIn; // March
RWStructuredBuffer _Segments;
RWStructuredBuffer _Count;
-int2 _Size; // field size in texels
-float2 _Origin; // world xz of texel (0, 0)'s centre
-float2 _PerTexel; // world xz step per texel; signed per axis
+int2 _Size; // sample grid size
+float2 _Origin; // world xz of sample (0, 0)
+float2 _PerTexel; // world xz step per sample; signed per axis
float _Start;
float _Range;
int _ContourCount;
@@ -37,42 +35,22 @@ uint _Capacity;
float Texel() { return max(abs(_PerTexel.x), abs(_PerTexel.y)); }
float WrapPi(float x) { return x - TWO_PI * round(x / TWO_PI); }
-float FieldAt(int2 p) { return _Field.Load(int3(p, 0)); }
+// 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 Derive(uint3 id : SV_DispatchThreadID)
+void Sample(uint3 id : SV_DispatchThreadID)
{
if (any(int2(id.xy) >= _Size)) return;
- int2 p = int2(id.xy);
- int2 lo = max(p - 1, 0);
- int2 hi = min(p + 1, _Size - 1);
- float gx = (FieldAt(int2(hi.x, p.y)) - FieldAt(int2(lo.x, p.y))) / ((hi.x - lo.x) * _PerTexel.x);
- float gy = (FieldAt(int2(p.x, hi.y)) - FieldAt(int2(p.x, lo.y))) / ((hi.y - lo.y) * _PerTexel.y);
- _GradOut[p] = float4(gx, gy, sqrt(gx * gx + gy * gy), FieldAt(p));
-}
-
-float2 UnitGrad(int2 p)
-{
- float3 g = _GradIn.Load(int3(p, 0)).xyz;
- return g.z > 1e-20 ? g.xy / g.z : float2(0, 0);
-}
-
-// kappa = div(grad d / |grad d|), the level set's curvature; rho = 1 / |kappa|, the radius of the contour through the
-// texel (the distance to the centre for any radial well, whatever its profile). theta is the angle of -grad d.
-[numthreads(8, 8, 1)]
-void Curve(uint3 id : SV_DispatchThreadID)
-{
- if (any(int2(id.xy) >= _Size)) return;
- int2 p = int2(id.xy);
- int2 lo = max(p - 1, 0);
- int2 hi = min(p + 1, _Size - 1);
- float kappa = (UnitGrad(int2(hi.x, p.y)).x - UnitGrad(int2(lo.x, p.y)).x) / ((hi.x - lo.x) * _PerTexel.x)
- + (UnitGrad(int2(p.x, hi.y)).y - UnitGrad(int2(p.x, lo.y)).y) / ((hi.y - lo.y) * _PerTexel.y);
+ 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;
- rho = clamp(rho, Texel(), _RhoMax);
- float3 g = _GradIn.Load(int3(p, 0)).xyz;
- float theta = g.z > 0 ? atan2(-g.y, -g.x) : 0;
- _CurveOut[p] = float2(theta, rho);
+ _SampleOut[id.xy] = float4(g, d, clamp(rho, Texel(), _RhoMax));
}
// 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.
@@ -149,16 +127,16 @@ void March(uint3 id : SV_DispatchThreadID)
{
int2 q = p0 + int2((i == 1 || i == 2) ? 1 : 0, i >= 2 ? 1 : 0);
gPos[i] = _Origin + float2(q) * _PerTexel;
- float4 g = _GradIn.Load(int3(q, 0));
- float2 c = _CurveIn.Load(int3(q, 0));
- gSlope[i] = g.z;
- gDepth[i] = g.w;
- theta[i] = c.x;
- rho[i] = c.y;
- clamped = clamped || c.y <= rhoMin || c.y >= rhoMaxTest;
- dMin = min(dMin, g.w);
- dMax = max(dMax, g.w);
- slopeMin = min(slopeMin, g.z);
+ float4 g = _SampleIn.Load(int3(q, 0));
+ float slope = length(g.xy);
+ 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);
}
gCell = (uint)(p0.y * _Size.x + p0.x);