IsolineExtractSmoke: layout, level, closure, saddle, along-line, rays, overflow
Batchmode GPU check of the extraction against the real zone's own field (Zone.GetHeight as ground truth) and synthetic fields with closed-form answers; writes before.png and segments.png and reports extraction cost. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a65628d873
commit
788113a344
2 changed files with 656 additions and 0 deletions
654
Assets/Scripts/Editor/IsolineExtractSmoke.cs
Normal file
654
Assets/Scripts/Editor/IsolineExtractSmoke.cs
Normal file
|
|
@ -0,0 +1,654 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using float2 = CultMath.float2;
|
||||
using UnityEditor;
|
||||
using UnityEditor.SceneManagement;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Profiling;
|
||||
using UnityEngine.Rendering;
|
||||
using Debug = UnityEngine.Debug;
|
||||
|
||||
namespace Aetheria.EditorTools
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
///
|
||||
/// Renders and dispatches compute, so it needs a graphics device: run WITHOUT -nographics.
|
||||
/// Unity -batchmode -projectPath <repo> -executeMethod Aetheria.EditorTools.IsolineExtractSmoke.Run -logFile <path>
|
||||
/// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure. Captures go to the directory in
|
||||
/// the environment variable ISOLINE_SMOKE_OUT when it is set, else to a fresh directory under the temp path; the path is logged.
|
||||
/// </summary>
|
||||
public static class IsolineExtractSmoke
|
||||
{
|
||||
const string Tag = "[IsolineExtractSmoke]";
|
||||
const float RhoMax = 500f;
|
||||
const float SlopeEpsilon = 1e-3f;
|
||||
const int Contours = 21;
|
||||
|
||||
// Margin rule (lodur:ruling:deterministic-bound-margin): a bound sits at the geometric mean of the shipped worst and
|
||||
// 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.
|
||||
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;
|
||||
|
||||
static bool _ok = true;
|
||||
static string _out;
|
||||
|
||||
static void Fail(string check, string detail)
|
||||
{
|
||||
Debug.LogError($"{Tag} FAIL {check}: {detail}");
|
||||
_ok = false;
|
||||
}
|
||||
|
||||
static void Info(string message) => Debug.Log($"{Tag} {message}");
|
||||
|
||||
// ---- plumbing ----------------------------------------------------------------------------------------------------
|
||||
|
||||
sealed class Result
|
||||
{
|
||||
public IsolineExtractor.IsoSegment[] Segments; // the written ones
|
||||
public IsolineExtractor.IsoSegment[] Backing; // the whole buffer
|
||||
public uint Written, Requested;
|
||||
}
|
||||
|
||||
static ComputeShader Shader => AssetDatabase.LoadAssetAtPath<ComputeShader>("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)
|
||||
{
|
||||
var extractor = new IsolineExtractor(Shader, capacity, backing);
|
||||
var command = new CommandBuffer { name = "IsolineExtract" };
|
||||
try
|
||||
{
|
||||
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);
|
||||
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] };
|
||||
}
|
||||
finally
|
||||
{
|
||||
command.Release();
|
||||
extractor.Release();
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
static bool Clamped(uint key) => (key & (1u << 10)) != 0;
|
||||
static float Length(IsolineExtractor.IsoSegment s) => (s.b - s.a).magnitude;
|
||||
|
||||
// ---- entry -------------------------------------------------------------------------------------------------------
|
||||
|
||||
public static void Run()
|
||||
{
|
||||
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null)
|
||||
{
|
||||
Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics.");
|
||||
EditorApplication.Exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
_out = Environment.GetEnvironmentVariable("ISOLINE_SMOKE_OUT");
|
||||
if (string.IsNullOrEmpty(_out)) _out = Path.Combine(Path.GetTempPath(), "isoline-smoke-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(_out);
|
||||
Info($"captures go to {_out}");
|
||||
|
||||
var work = Path.Combine(Path.GetTempPath(), "isoline-smoke-work-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(work);
|
||||
ComputeBuffer wells = null;
|
||||
GameObject field = null;
|
||||
try
|
||||
{
|
||||
Guarded("layout", Layout);
|
||||
Guarded("saddle", Saddle);
|
||||
Guarded("along-line", AlongLine);
|
||||
Guarded("overflow", Overflow);
|
||||
|
||||
EditorSceneManager.OpenScene("Assets/Scenes/ARPG.unity", OpenSceneMode.Single);
|
||||
var settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset")
|
||||
?? throw new InvalidOperationException("No Settings.asset.");
|
||||
var material = AssetDatabase.LoadAssetAtPath<Material>("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);
|
||||
field = GravityLowering.CreateField(material);
|
||||
Guarded("real zone", () => RealZone(zone, orbits));
|
||||
Guarded("captures and cost", () => CapturesAndCost(zone, orbits));
|
||||
Info(_ok ? "PASS" : "FAIL: see errors above");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogError($"{Tag} FAIL exception: {e}");
|
||||
_ok = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (field != null) UnityEngine.Object.DestroyImmediate(field);
|
||||
wells?.Release();
|
||||
try { Directory.Delete(work, true); } catch { }
|
||||
}
|
||||
EditorApplication.Exit(_ok ? 0 : 1);
|
||||
}
|
||||
|
||||
static void Guarded(string name, Action check)
|
||||
{
|
||||
try { check(); }
|
||||
catch (Exception e) { Fail(name, e.ToString()); }
|
||||
}
|
||||
|
||||
// ---- 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.
|
||||
static void Layout()
|
||||
{
|
||||
var size = Marshal.SizeOf<IsolineExtractor.IsoSegment>();
|
||||
if (size != 48) Fail("layout", $"IsoSegment is {size} bytes, not 48");
|
||||
var field = FieldFrom(new[] { .2f, .2f, .8f, .8f }, 2, 2);
|
||||
try
|
||||
{
|
||||
var levels = new IsolineExtractor.IsolineLevels(0f, 10f, RhoMax, SlopeEpsilon);
|
||||
var result = Extract(field, new Vector2(10f, 20f), new Vector2(2f, 3f), 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);
|
||||
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); }
|
||||
}
|
||||
|
||||
// ---- saddle ------------------------------------------------------------------------------------------------------
|
||||
|
||||
// Two 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);
|
||||
try
|
||||
{
|
||||
var result = Extract(field, origin, perTexel, 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) })
|
||||
{
|
||||
var here = result.Segments.Where(s => !IsRay(s.key) && s.cell == cell && LevelOf(s.key) == level).ToArray();
|
||||
if (here.Length != 2) { Fail("saddle", $"level {level}: {here.Length} segments in the saddle cell, expected 2"); continue; }
|
||||
var cutOff = new HashSet<int>();
|
||||
foreach (var s in here)
|
||||
{
|
||||
var m = (s.a + s.b) * .5f;
|
||||
var tx = (m.x - origin.x) / perTexel.x - cx;
|
||||
var ty = (m.y - origin.y) / perTexel.y - cx;
|
||||
var nearest = tx < .5f ? (ty < .5f ? 0 : 3) : (ty < .5f ? 1 : 2);
|
||||
cutOff.Add(nearest);
|
||||
}
|
||||
var want = connected ? new HashSet<int> { 1, 3 } : new HashSet<int> { 0, 2 };
|
||||
if (!cutOff.SetEquals(want))
|
||||
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}");
|
||||
}
|
||||
finally { field.Release(); UnityEngine.Object.DestroyImmediate(field); }
|
||||
}
|
||||
|
||||
// ---- along-line parameter, rays ----------------------------------------------------------------------------------
|
||||
|
||||
sealed class Radial
|
||||
{
|
||||
public string Name;
|
||||
public Func<double, double> D; // the profile, 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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
static readonly Radial[] Profiles =
|
||||
{
|
||||
new Radial { Name = "offset", D = r => 2000.0 / (r + 40.0) },
|
||||
new Radial { Name = "soft-core", D = r => 2000.0 / Math.Sqrt(r * r + 15.0 * 15.0) }
|
||||
};
|
||||
|
||||
// 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).
|
||||
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);
|
||||
try
|
||||
{
|
||||
var result = Extract(field, origin, perTexel, 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; }
|
||||
|
||||
// contours: summed over a level's ring, the change of s over segment length is 1 where s does not wrap (a single
|
||||
// short segment is dominated by the endpoint interpolation, so the ratio is taken over the ring)
|
||||
double arcWorst = 0, arcMutant = 0, arcMutantRho = 0;
|
||||
var arcLevels = 0;
|
||||
foreach (var ring in contours.Where(s => !Seam(s.key) && !Clamped(s.key) && InBand((s.a + s.b) * .5f - centre)).GroupBy(s => LevelOf(s.key)))
|
||||
{
|
||||
double ds = 0, length = 0, rawTheta = 0, dsRho = 0;
|
||||
foreach (var s in ring)
|
||||
{
|
||||
ds += Math.Abs(s.sB - s.sA);
|
||||
length += Length(s);
|
||||
// mutant: s = raw theta (the angle itself, no radius): it grows by 1 / r per unit of length
|
||||
// mutant: rho = d / |grad d|
|
||||
var thA = Math.Atan2(s.a.y - centre.y, s.a.x - centre.x);
|
||||
var thB = thA + Mathf.DeltaAngle((float)(thA * Mathf.Rad2Deg), Mathf.Atan2(s.b.y - centre.y, s.b.x - centre.x) * Mathf.Rad2Deg) * Mathf.Deg2Rad;
|
||||
dsRho += Math.Abs(thB * s.depthB / s.slopeB - thA * s.depthA / s.slopeA);
|
||||
rawTheta += Math.Abs(Mathf.DeltaAngle(Mathf.Atan2(s.a.y - centre.y, s.a.x - centre.x) * Mathf.Rad2Deg, Mathf.Atan2(s.b.y - centre.y, s.b.x - centre.x) * Mathf.Rad2Deg)) * Mathf.Deg2Rad;
|
||||
}
|
||||
arcWorst = Math.Max(arcWorst, Math.Abs(ds / length - 1.0));
|
||||
arcMutant = Math.Max(arcMutant, Math.Abs(rawTheta / length - 1.0));
|
||||
arcMutantRho = Math.Max(arcMutantRho, Math.Abs(dsRho / length - 1.0));
|
||||
arcLevels++;
|
||||
}
|
||||
|
||||
// rays: s is the distance to the centre; the mutants take rho = d / |grad d|, and levels half a step off
|
||||
double rhoWorst = 0, rhoMutant = 0, angleWorst = 0, angleMutant = 0, worstAt = 0;
|
||||
var rayCount = 0;
|
||||
var step = 2 * Math.PI / 12;
|
||||
foreach (var s in rays)
|
||||
{
|
||||
if (Clamped(s.key)) continue;
|
||||
foreach (var (p, sv, slope, depth) in new[] { (s.a, s.sA, s.slopeA, s.depthA), (s.b, s.sB, s.slopeB, s.depthB) })
|
||||
{
|
||||
var r = (p - centre).magnitude;
|
||||
if (!InBand(p - centre)) continue;
|
||||
var error = Math.Abs(sv / r - 1.0);
|
||||
if (error > rhoWorst) { rhoWorst = error; worstAt = r; }
|
||||
rhoMutant = Math.Max(rhoMutant, Math.Abs(depth / slope / r - 1.0));
|
||||
var theta = Math.Atan2(p.y - centre.y, p.x - centre.x);
|
||||
double Off(double level) { var diff = Math.Abs(theta - level); return Math.Min(diff, 2 * Math.PI - diff); }
|
||||
angleWorst = Math.Max(angleWorst, Off((LevelOf(s.key) + .5) * step - Math.PI));
|
||||
angleMutant = Math.Max(angleMutant, Off(LevelOf(s.key) * step - Math.PI));
|
||||
rayCount++;
|
||||
}
|
||||
}
|
||||
// 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);
|
||||
if (rays.Any(s => s.cell == holding)) Fail("rays", $"{profile.Name}: a ray segment lies in the cell holding the well centre");
|
||||
|
||||
Info($"ray segments per level, {profile.Name}: {string.Join(" ", Enumerable.Range(0, 12).Select(k => rays.Count(r => LevelOf(r.key) == k)))}");
|
||||
Info($"along-line {profile.Name}: {contours.Length} contour / {rays.Length} ray segments; arc ratio error worst over {arcLevels} rings {arcWorst:G4} (mutants: raw theta {arcMutant:G4}, rho = d/|g| {arcMutantRho:G4}); ray rho error worst {rhoWorst:G4} at r={worstAt:F1} (mutant d/|g| worst {rhoMutant:G4}, {rayCount} endpoints); ray angle error worst {angleWorst:G4} rad (mutant half-step levels {angleMutant:G4})");
|
||||
{
|
||||
if (arcWorst > ArcRatioBound) Fail("along-line", $"{profile.Name}: contour |ds|/length is off by {arcWorst:G4} > {ArcRatioBound:G4}");
|
||||
if (rhoWorst > RayRhoBound) Fail("along-line", $"{profile.Name}: ray s is off the distance by {rhoWorst:G4} > {RayRhoBound:G4}");
|
||||
if (angleWorst > RayAngleBound) Fail("rays", $"{profile.Name}: a ray endpoint's angle is off its level by {angleWorst:G4} rad > {RayAngleBound:G4}");
|
||||
}
|
||||
}
|
||||
finally { field.Release(); UnityEngine.Object.DestroyImmediate(field); }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- overflow ----------------------------------------------------------------------------------------------------
|
||||
|
||||
static void Overflow()
|
||||
{
|
||||
var (field, 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 needed = (int)full.Requested;
|
||||
var capacity = needed / 2;
|
||||
var guard = 32;
|
||||
var small = Extract(field, origin, perTexel, 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();
|
||||
for (var i = capacity; i < small.Backing.Length; i++)
|
||||
{
|
||||
var s = small.Backing[i];
|
||||
if (s.key != sentinel.key || s.cell != sentinel.cell || s.a != sentinel.a || s.sA != sentinel.sA)
|
||||
{
|
||||
Fail("overflow", $"slot {i} past the capacity {capacity} was written");
|
||||
break;
|
||||
}
|
||||
}
|
||||
Info($"overflow: needed {needed}, capacity {capacity}, written {small.Written}, requested {small.Requested}");
|
||||
}
|
||||
finally { field.Release(); UnityEngine.Object.DestroyImmediate(field); }
|
||||
}
|
||||
|
||||
// ---- the real zone -----------------------------------------------------------------------------------------------
|
||||
|
||||
static Vector2 At(Orbit orbit) => new Vector2(orbit.Position.x, orbit.Position.y);
|
||||
|
||||
// Renders the field through a downward orthographic camera that culls layer 9 only; the world frame of the texels is
|
||||
// asked of the camera, as GravityFieldParityVerify does.
|
||||
static RenderTexture RenderField(Camera camera, int width, int height, out Vector2 origin, out Vector2 perTexel)
|
||||
{
|
||||
var target = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat) { filterMode = FilterMode.Point };
|
||||
target.Create();
|
||||
var previousTarget = camera.targetTexture;
|
||||
var previousMask = camera.cullingMask;
|
||||
var previousClear = camera.clearFlags;
|
||||
var previousColor = camera.backgroundColor;
|
||||
camera.targetTexture = target;
|
||||
camera.cullingMask = 1 << GravityLowering.FieldLayer;
|
||||
camera.clearFlags = CameraClearFlags.SolidColor;
|
||||
camera.backgroundColor = Color.black;
|
||||
camera.allowHDR = false;
|
||||
camera.allowMSAA = false;
|
||||
camera.Render();
|
||||
Vector2 Texel(float x, float y)
|
||||
{
|
||||
var p = camera.ViewportToWorldPoint(new Vector3((x + .5f) / width, (y + .5f) / height, 100f));
|
||||
return new Vector2(p.x, p.z);
|
||||
}
|
||||
origin = Texel(0, 0);
|
||||
perTexel = new Vector2(Texel(1, 0).x - origin.x, Texel(0, 1).y - origin.y);
|
||||
camera.targetTexture = previousTarget;
|
||||
camera.cullingMask = previousMask;
|
||||
camera.clearFlags = previousClear;
|
||||
camera.backgroundColor = previousColor;
|
||||
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>();
|
||||
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<float>(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)
|
||||
{
|
||||
var camera = TopCamera(ZoneCentre, ZoneHalf, 1f, out var owner);
|
||||
RenderTexture field = null;
|
||||
try
|
||||
{
|
||||
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))));
|
||||
var levels = new IsolineExtractor.IsolineLevels(0f, range, RhoMax, 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)
|
||||
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;
|
||||
}
|
||||
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");
|
||||
if (open != 0) Fail("contours close", $"{open} endpoints are not shared with exactly one other endpoint");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (field != null) { field.Release(); UnityEngine.Object.DestroyImmediate(field); }
|
||||
UnityEngine.Object.DestroyImmediate(owner);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- captures and cost -------------------------------------------------------------------------------------------
|
||||
|
||||
const int CaptureSize = 512;
|
||||
|
||||
static void CapturesAndCost(Zone zone, Orbit[] orbits)
|
||||
{
|
||||
// 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.
|
||||
var mapCamera = UnityEngine.Object.FindObjectsByType<Camera>(FindObjectsInactive.Include, FindObjectsSortMode.None)
|
||||
.FirstOrDefault(c => c.name == "Map Gravity") ?? throw new InvalidOperationException("No camera named Map Gravity in ARPG.unity.");
|
||||
var camera = mapCamera;
|
||||
camera.transform.position = new Vector3(ZoneCentre.x, camera.transform.position.y, ZoneCentre.y);
|
||||
var field = RenderField(camera, 128, 128, out var origin, out var perTexel);
|
||||
var linesAsset = AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/UI/Minimap Gravity Lines.mat")
|
||||
?? throw new InvalidOperationException("No Minimap Gravity Lines.mat.");
|
||||
var range = Math.Max(1f, orbits.Max(o => -zone.GetHeight(new float2(o.Position.x, o.Position.y))));
|
||||
var lines = new Material(linesAsset);
|
||||
lines.SetTexture("_DetailTex", field);
|
||||
lines.SetFloat("_StartDepth", 0f);
|
||||
lines.SetFloat("_DepthRange", range);
|
||||
var picture = new RenderTexture(CaptureSize, CaptureSize, 0, RenderTextureFormat.ARGB32);
|
||||
var previous = RenderTexture.active;
|
||||
RenderTexture.active = picture;
|
||||
GL.Clear(true, true, Color.black);
|
||||
Graphics.Blit(Texture2D.whiteTexture, picture, lines);
|
||||
var before = new Texture2D(CaptureSize, CaptureSize, TextureFormat.RGBA32, false);
|
||||
before.ReadPixels(new Rect(0, 0, CaptureSize, CaptureSize), 0, 0);
|
||||
before.Apply();
|
||||
RenderTexture.active = previous;
|
||||
File.WriteAllBytes(Path.Combine(_out, "before.png"), before.EncodeToPNG());
|
||||
|
||||
// segments.png: the extracted segments over the same frame, contours cyan and rays magenta.
|
||||
var levels = new IsolineExtractor.IsolineLevels(0f, range, RhoMax, SlopeEpsilon);
|
||||
var result = Extract(field, origin, perTexel, 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);
|
||||
foreach (var s in result.Segments)
|
||||
Line(raster, Pixel(s.a), Pixel(s.b), IsRay(s.key) ? new Color32(255, 0, 220, 255) : new Color32(0, 170, 255, 255));
|
||||
raster.Apply();
|
||||
File.WriteAllBytes(Path.Combine(_out, "segments.png"), raster.EncodeToPNG());
|
||||
Info($"captures: {Path.Combine(_out, "before.png")}, {Path.Combine(_out, "segments.png")}; 128 x 128 field extracted {result.Written} segments (requested {result.Requested}), frame centre {ZoneCentre}, half {camera.orthographicSize}, range {range:G6}");
|
||||
UnityEngine.Object.DestroyImmediate(before);
|
||||
UnityEngine.Object.DestroyImmediate(raster);
|
||||
UnityEngine.Object.DestroyImmediate(lines);
|
||||
picture.Release();
|
||||
UnityEngine.Object.DestroyImmediate(picture);
|
||||
|
||||
// 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);
|
||||
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)
|
||||
{
|
||||
var command = new CommandBuffer { name = "IsolineExtract" };
|
||||
command.BeginSample("IsolineExtract");
|
||||
extractor.Extract(command, target, o, p, levels);
|
||||
command.EndSample("IsolineExtract");
|
||||
var clock = Stopwatch.StartNew();
|
||||
Graphics.ExecuteCommandBuffer(command);
|
||||
extractor.Count.GetData(new uint[2]);
|
||||
clock.Stop();
|
||||
command.Release();
|
||||
return clock.Elapsed.TotalMilliseconds;
|
||||
}
|
||||
Measure(small, field, origin, perTexel); Measure(large, big, bigOrigin, bigPerTexel); // warm up
|
||||
var a = new List<double>();
|
||||
var b = new List<double>();
|
||||
for (var i = 0; i < 21; i++)
|
||||
{
|
||||
a.Add(Measure(small, field, origin, perTexel));
|
||||
b.Add(Measure(large, big, bigOrigin, bigPerTexel));
|
||||
}
|
||||
a.Sort(); b.Sort();
|
||||
var counts = new uint[2];
|
||||
large.Count.GetData(counts);
|
||||
Info($"cost (wall clock to a fence, median of 21 interleaved pairs): 128 x 128 {a[10]:F3} ms; 1920 x 1080 {b[10]:F3} ms; 1920 x 1080 wrote {counts[0]} of {counts[1]} requested; GPU recorder {(recorder.isValid ? recorder.gpuElapsedNanoseconds / 1e6 + " ms" : "unmeasured (no frame loop)")}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
recorder.enabled = false;
|
||||
small.Release();
|
||||
large.Release();
|
||||
big.Release();
|
||||
UnityEngine.Object.DestroyImmediate(big);
|
||||
UnityEngine.Object.DestroyImmediate(bigOwner);
|
||||
field.Release();
|
||||
UnityEngine.Object.DestroyImmediate(field);
|
||||
}
|
||||
}
|
||||
|
||||
static void Line(Texture2D target, Vector2 from, Vector2 to, Color32 colour)
|
||||
{
|
||||
var steps = Mathf.CeilToInt(Mathf.Max(Mathf.Abs(to.x - from.x), Mathf.Abs(to.y - from.y)));
|
||||
for (var i = 0; i <= steps; i++)
|
||||
{
|
||||
var p = steps == 0 ? from : Vector2.Lerp(from, to, i / (float)steps);
|
||||
var x = Mathf.RoundToInt(p.x);
|
||||
var y = Mathf.RoundToInt(p.y);
|
||||
if (x >= 0 && y >= 0 && x < target.width && y < target.height) target.SetPixel(x, y, colour);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Editor/IsolineExtractSmoke.cs.meta
Normal file
2
Assets/Scripts/Editor/IsolineExtractSmoke.cs.meta
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 961a55f8990ee804faf3edd6d76b3268
|
||||
Loading…
Reference in a new issue