Flow parity: FlowParity.compute, FlowFieldParityVerify (Unity batchmode, GPU) and its mutation harness

The probe steps a Zone, lowers its flow through VolumeSampling.LowerFlow, dispatches the HLSL
globalFlow and slopeFlow, and compares with FlowField (max error 1.0e-4 of amplitude, tolerance
1e-3). All commits build; the Unity side was verified from this tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-13 20:49:22 +02:00
commit 53a13675d5
6 changed files with 338 additions and 0 deletions

View file

@ -0,0 +1,201 @@
using System;
using System.IO;
using GameCult.Caching;
using UnityEditor;
using UnityEngine;
namespace Aetheria.EditorTools
{
/// <summary>
/// Batchmode check for flow-shader-parity (campaign aetheria-fauna, cut fauna-flow-field): the HLSL globalFlow and
/// slopeFlow of Assets/Shaders/Volumetric.cginc give the values of FlowField (ServerShared) for the same position,
/// scroll, settings and gradient. It drives the real lowering: a Zone is stepped, VolumeSampling.LowerFlow sets the
/// shader globals from the zone's Settings.Flow and FlowScroll, FlowParity.compute reads those globals, and the
/// results are compared with FlowField. It also checks that Settings.asset carries the authored flow under
/// PlanetSettings and that the shader got the zone's scroll (speed times zone time).
///
/// Dispatches a compute kernel, so it needs a graphics device: run WITHOUT -nographics (as ShieldPanelCut3Verify).
/// Unity -batchmode -projectPath &lt;repo&gt; -executeMethod Aetheria.EditorTools.FlowFieldParityVerify.Run -logFile &lt;path&gt;
/// Do not pass -quit: Run exits the Editor itself, 0 on success and 1 on any failure.
/// </summary>
public static class FlowFieldParityVerify
{
const string Tag = "[FlowFieldParityVerify]";
const float RelativeTolerance = 1e-3f;
static float _maxError;
static bool _ok = true;
static void Fail(string check, string detail)
{
Debug.LogError($"{Tag} FAIL {check}: {detail}");
_ok = false;
}
public static void Run()
{
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Null)
{
Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics.");
EditorApplication.Exit(1);
return;
}
var work = Path.Combine(Path.GetTempPath(), "flow-parity-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(work);
try
{
var settings = AssetDatabase.LoadAssetAtPath<GameSettings>("Assets/Resources/Settings.asset")
?? throw new InvalidOperationException("No Settings.asset.");
var compute = AssetDatabase.LoadAssetAtPath<ComputeShader>("Assets/Shaders/Compute/FlowParity.compute")
?? throw new InvalidOperationException("No FlowParity.compute.");
CheckAuthoredFlow(settings.PlanetSettings.Flow);
// The authored flow (global term only: its slope amplitudes are authored zero), then a flow with every
// term live and a scroll speed that reaches scrolls up to 100.
var authored = settings.PlanetSettings.Flow;
CheckParity("authored", settings, work, compute, authored, new[] { 0.0, 3.1, 40.0, 100.0 });
var wide = new FlowSettings
{
GlobalScale = authored.GlobalScale, GlobalAmplitude = authored.GlobalAmplitude, Period = authored.Period,
GlobalScrollSpeed = 1f, SlopeAmplitude = 3f, SwirlAmplitude = 5f
};
CheckParity("wide", settings, work, compute, wide, new[] { 0.0, 1.0, 17.0, 60.0, 100.0 });
Debug.Log($"{Tag} max error {_maxError:G4} of amplitude (tolerance {RelativeTolerance:G4})");
Debug.Log(_ok ? $"{Tag} PASS" : $"{Tag} FAIL: see errors above");
}
catch (Exception e)
{
Debug.LogError($"{Tag} FAIL exception: {e}");
_ok = false;
}
finally
{
try { Directory.Delete(work, true); } catch { }
}
EditorApplication.Exit(_ok ? 0 : 1);
}
// Settings.asset carries the authored flow under PlanetSettings (it moved from DefaultEnvironment unchanged).
static void CheckAuthoredFlow(FlowSettings flow)
{
if (flow == null) { Fail("authored-flow", "PlanetSettings.Flow is null"); return; }
if (flow.GlobalScale != 512f || flow.GlobalAmplitude != 15f || flow.GlobalScrollSpeed != .025f ||
flow.Period != 8f || flow.SlopeAmplitude != 0f || flow.SwirlAmplitude != 0f)
Fail("authored-flow", $"PlanetSettings.Flow is {flow.GlobalScale}/{flow.GlobalAmplitude}/{flow.GlobalScrollSpeed}/" +
$"{flow.Period}/{flow.SlopeAmplitude}/{flow.SwirlAmplitude}, authored 512/15/0.025/8/0/0");
}
static Zone BuildZone(GameSettings settings, string work, FlowSettings flow)
{
var cache = AetheriaStores.Open(Path.Combine(work, Guid.NewGuid().ToString("N") + ".cc"), catalogWritable: true);
cache.Upsert(new VerseGrammar { Revision = 1 });
cache.FlushAsync().Wait();
var items = new ItemManager(cache, new ProvenanceLedger(), settings.GameplaySettings, _ => { });
return new Zone(items, new PlanetSettings { Flow = flow }, new ZonePack(), new GalaxyZone { Name = "Parity", Owner = null }, null);
}
static void CheckParity(string label, GameSettings settings, string work, ComputeShader compute, FlowSettings flow,
double[] zoneTimes)
{
var zone = BuildZone(settings, work, flow);
var kernel = compute.FindKernel("Evaluate");
var rng = new System.Random(label.Length * 7919);
const int positionCount = 256, gradientCount = 64;
const int count = positionCount;
var positions = new Vector3[count];
for (var i = 0; i < positionCount; i++)
positions[i] = new Vector3((float) (rng.NextDouble() * 20000 - 10000), (float) (rng.NextDouble() * 200 - 100),
(float) (rng.NextDouble() * 20000 - 10000));
// Gradients of any direction and magnitude, plus one zero gradient.
var gradients = new Vector2[count];
for (var i = 1; i < gradientCount; i++)
{
var angle = rng.NextDouble() * Math.PI * 2;
var magnitude = (float) Math.Exp(rng.NextDouble() * 8 - 4);
gradients[i] = new Vector2((float) Math.Cos(angle) * magnitude, (float) Math.Sin(angle) * magnitude);
}
gradients[0] = Vector2.zero;
var positionBuffer = new ComputeBuffer(count, 12);
var gradientBuffer = new ComputeBuffer(count, 8);
var globalBuffer = new ComputeBuffer(count, 12);
var slopeBuffer = new ComputeBuffer(count, 12);
try
{
positionBuffer.SetData(positions);
gradientBuffer.SetData(gradients);
compute.SetBuffer(kernel, "positions", positionBuffer);
compute.SetBuffer(kernel, "gradients", gradientBuffer);
compute.SetBuffer(kernel, "globalOut", globalBuffer);
compute.SetBuffer(kernel, "slopeOut", slopeBuffer);
compute.SetInt("count", count);
var elapsed = 0.0;
foreach (var target in zoneTimes)
{
// Step the zone to the target by an awkward step; the sum is the zone's time.
while (elapsed < target - 1e-9)
{
var dt = (float) Math.Min(0.37, target - elapsed);
zone.Update(dt);
elapsed += dt;
}
var expectedScroll = flow.GlobalScrollSpeed * elapsed;
var scrollTolerance = 1e-4 * Math.Max(1.0, expectedScroll);
if (Math.Abs(zone.FlowScroll - expectedScroll) > scrollTolerance)
Fail($"{label}-zone-scroll", $"at zone time {elapsed:F3} FlowScroll {zone.FlowScroll} but speed x time is {expectedScroll}");
VolumeSampling.LowerFlow(zone.Settings.Flow, zone.FlowScroll);
var lowered = Shader.GetGlobalFloat("_FlowScroll");
if (Math.Abs(lowered - expectedScroll) > scrollTolerance)
Fail($"{label}-lowered-scroll", $"at zone time {elapsed:F3} the shader got _FlowScroll {lowered}, speed x time is {expectedScroll}");
if (Shader.GetGlobalFloat("_FlowScale") != flow.GlobalScale || Shader.GetGlobalFloat("_FlowAmplitude") != flow.GlobalAmplitude ||
Shader.GetGlobalFloat("_FlowSlopeAmplitude") != flow.SlopeAmplitude ||
Shader.GetGlobalFloat("_FlowSwirlAmplitude") != flow.SwirlAmplitude || Shader.GetGlobalFloat("_FlowPeriod") != flow.Period)
Fail($"{label}-lowered-settings", "a flow uniform does not equal the zone's FlowSettings");
compute.Dispatch(kernel, (count + 63) / 64, 1, 1);
var globalOut = new Vector3[count];
var slopeOut = new Vector3[count];
globalBuffer.GetData(globalOut);
slopeBuffer.GetData(slopeOut);
var zoneScroll = zone.FlowScroll;
var at = $"{label} zone time {elapsed:F2} scroll {zoneScroll:F4}";
for (var i = 0; i < positionCount; i++)
{
var p = positions[i];
var expected = FlowField.Global(flow, new CultMath.float3(p.x, p.y, p.z), zoneScroll);
Compare($"{label}-global", at, i, new Vector3(expected.x, expected.y, expected.z), globalOut[i], flow.GlobalAmplitude);
}
var slopeScale = Math.Max(Math.Abs(flow.SlopeAmplitude), Math.Abs(flow.SwirlAmplitude));
for (var i = 0; i < gradientCount; i++)
{
var g = gradients[i];
var expected = FlowField.Slope(flow, new CultMath.float2(g.x, g.y));
Compare($"{label}-slope", at, i, new Vector3(expected.x, expected.y, expected.z), slopeOut[i], slopeScale);
}
}
}
finally
{
positionBuffer.Release(); gradientBuffer.Release(); globalBuffer.Release(); slopeBuffer.Release();
}
}
// Error is measured against the term's amplitude; a term with no amplitude must be exactly zero and never NaN.
static void Compare(string check, string at, int index, Vector3 expected, Vector3 actual, float amplitude)
{
var error = (expected - actual).magnitude;
if (float.IsNaN(error)) { Fail(check, $"{at} sample {index}: NaN (expected {expected}, shader {actual})"); return; }
if (amplitude != 0f) _maxError = Math.Max(_maxError, error / Math.Abs(amplitude));
var tolerance = RelativeTolerance * Math.Abs(amplitude);
if (error > tolerance)
Fail(check, $"{at} sample {index}: expected {expected}, shader {actual}, error {error:G4} > {tolerance:G4}");
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8fae18f5f32f10f43ba892a097f18caa

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8105a45840c4552459aaf44e6c0e19ce

View file

@ -0,0 +1,20 @@
// Evaluates the shader flow functions for a buffer of positions and gradients, so that
// Aetheria.EditorTools.FlowFieldParityVerify can compare them with FlowField (ServerShared). Reads the same global
// _Flow* uniforms the nebula and stardust read, set by VolumeSampling.LowerFlow.
#pragma kernel Evaluate
#include "Assets/Shaders/Volumetric.cginc"
StructuredBuffer<float3> positions;
StructuredBuffer<float2> gradients;
RWStructuredBuffer<float3> globalOut;
RWStructuredBuffer<float3> slopeOut;
uint count;
[numthreads(64, 1, 1)]
void Evaluate(uint3 id : SV_DispatchThreadID)
{
if (id.x >= count) return;
globalOut[id.x] = globalFlow(positions[id.x]);
slopeOut[id.x] = slopeFlow(gradients[id.x]);
}

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: fd5f95c7d7c63b243aadd16f6e9dc702
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""Mutation tests for the flow-shader-parity rule (campaign aetheria-fauna, cut fauna-flow-field).
Assets/Scripts/Editor/FlowFieldParityVerify.cs evaluates the HLSL globalFlow and slopeFlow
(Assets/Shaders/Volumetric.cginc, through FlowParity.compute) and FlowField (ServerShared) for the
same positions, scrolls, settings and gradients, after VolumeSampling.LowerFlow has lowered a stepped
Zone's flow into the shader globals. Tests.asmdef cannot see Assembly-CSharp and the check needs a GPU,
so it runs here, in Unity batchmode WITHOUT -nographics (see ShieldPanelCut3Verify.cs).
A control run proves the unmutated tree passes. Then each mutant edits the real source in one way a
rule of the cut forbids, runs the check, asserts it goes red naming the check that owns the rule, and
restores the file byte for byte. A mutant that fails for the wrong reason (a broken harness) cannot
hide behind the control.
Run from the repo root: py -3 tests/mutation_tests_flow_parity.py [--only <label>[,<label>]]
Exit code 0 only if the control passed and every mutant was caught for its reason. Run one Unity at a
time: never start this while another Unity process is running.
"""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
UNITY_EXE = r"C:\Program Files\Unity\Hub\Editor\6000.3.24f1\Editor\Unity.exe"
CGINC = "Assets/Shaders/Volumetric.cginc"
VOLUME_SAMPLING = "Assets/Scripts/Zone Display/VolumeSampling.cs"
FLOW_FIELD = "Assets/Scripts/ServerShared/FlowField.cs"
ZONE = "Assets/Scripts/ServerShared/Zone.cs"
SETTINGS_ASSET = "Assets/Resources/Settings.asset"
# (label, file, before, after, the failing check the probe must name)
MUTANTS = [
("hlsl-y-halving", CGINC, "flowSample.y *= .5;", "flowSample.y *= .6;", "global"),
("hlsl-scroll-sign", CGINC, "pos / _FlowScale - float3(0,_FlowScroll,0)", "pos / _FlowScale + float3(0,_FlowScroll,0)", "global"),
("hlsl-swirl-flipped", CGINC, "float3(ngrad.y, 0, -ngrad.x)", "float3(-ngrad.y, 0, ngrad.x)", "slope"),
("hlsl-zero-gradient-guard", CGINC, " if (dot(grad, grad) == 0) return 0;\n", "", "slope"),
("lower-scroll-doubled", VOLUME_SAMPLING, 'Shader.SetGlobalFloat("_FlowScroll", scroll);', 'Shader.SetGlobalFloat("_FlowScroll", scroll * 2f);', "lowered-scroll"),
("lower-scale-halved", VOLUME_SAMPLING, 'Shader.SetGlobalFloat("_FlowScale", flow.GlobalScale);', 'Shader.SetGlobalFloat("_FlowScale", flow.GlobalScale * .5f);', "lowered-settings"),
("lower-frame-clock", VOLUME_SAMPLING, 'Shader.SetGlobalFloat("_FlowScroll", scroll);', 'Shader.SetGlobalFloat("_FlowScroll", scroll + Time.realtimeSinceStartup);', "lowered-scroll"),
("csharp-scale-doubled", FLOW_FIELD, "position / settings.GlobalScale", "position / (settings.GlobalScale * 2f)", "global"),
("csharp-scroll-offset", FLOW_FIELD, "(float) (settings.GlobalScrollSpeed * zoneTime)", "(float) (settings.GlobalScrollSpeed * (zoneTime + 1.0))", "zone-scroll"),
("zone-scroll-scaled", ZONE, "public float FlowScroll => FlowField.Scroll(Settings.Flow, _time);", "public float FlowScroll => FlowField.Scroll(Settings.Flow, _time * 2);", "zone-scroll"),
("asset-amplitude", SETTINGS_ASSET, " GlobalAmplitude: 15\n", " GlobalAmplitude: 14\n", "authored-flow"),
]
def run_probe(log: Path) -> tuple[int, str]:
log.unlink(missing_ok=True)
proc = subprocess.run(
[UNITY_EXE, "-batchmode", "-projectPath", str(REPO_ROOT),
"-executeMethod", "Aetheria.EditorTools.FlowFieldParityVerify.Run", "-logFile", str(log)],
timeout=1800,
)
return proc.returncode, log.read_text(encoding="utf-8", errors="replace")
def main() -> int:
only = set()
if "--only" in sys.argv:
only = set(sys.argv[sys.argv.index("--only") + 1].split(","))
scratch = REPO_ROOT / "tests" / "_scratch_flow_parity"
scratch.mkdir(parents=True, exist_ok=True)
failures: list[str] = []
print("\n=== control: unmutated tree ===")
code, text = run_probe(scratch / "control.log")
if code != 0 or "[FlowFieldParityVerify] PASS" not in text:
print("control FAILED: expected exit 0 and PASS on the unmutated tree")
return 1
print("control OK: exit 0, PASS")
for label, rel, before, after, check in MUTANTS:
if only and label not in only:
continue
path = REPO_ROOT / rel
original = path.read_bytes()
text_in = original.decode("utf-8")
newline = "\r\n" if "\r\n" in text_in else "\n"
b, a = before.replace("\n", newline), after.replace("\n", newline)
if text_in.count(b) != 1:
failures.append(f"{label}: anchor occurs {text_in.count(b)} times in {rel}, expected exactly once")
continue
print(f"\n=== mutant {label} ({rel}) ===")
try:
path.write_bytes(text_in.replace(b, a).encode("utf-8"))
code, text = run_probe(scratch / f"{label}.log")
finally:
path.write_bytes(original)
named = f"FAIL {check}" in text or f"-{check}:" in text
if code != 0 and named:
print(f"OK: caught, the probe named {check}")
elif code != 0:
failures.append(f"{label}: red, but not for {check} (compile error or another check)")
else:
failures.append(f"{label}: SURVIVED")
for f in failures:
print("FAIL:", f)
return 1 if failures else 0
if __name__ == "__main__":
sys.exit(main())