Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Bound SDF volume with affine cell enclosures
Yuechen Li4feb05276b93
diff --git a/Aetheris.CLI.Tests/FirmamentMeasureCliTests.cs b/Aetheris.CLI.Tests/FirmamentMeasureCliTests.csindex 136aa8aa..27d6be6d 100644--- a/Aetheris.CLI.Tests/FirmamentMeasureCliTests.cs+++ b/Aetheris.CLI.Tests/FirmamentMeasureCliTests.cs@@ -106,6 +106,10 @@ public sealed class FirmamentMeasureCliTestsAssert.InRange(expected, volume.GetProperty("lowerBoundMm3").GetDouble(), volume.GetProperty("upperBoundMm3").GetDouble());Assert.True(volume.GetProperty("authoritative").GetBoolean());Assert.Equal("SdfAdaptiveOccupiedVolumeInterval", volume.GetProperty("method").GetString());+ Assert.False(volume.GetProperty("budgetExhausted").GetBoolean());+ Assert.InRange(volume.GetProperty("errorBoundMm3").GetDouble(), 0, 50);+ Assert.True(volume.GetProperty("regionsVisited").GetInt32() < 100_001);+ Assert.True(volume.GetProperty("affineCutRegions").GetInt32() > 0);Assert.True(root.TryGetProperty("meshComparison", out _));}}diff --git a/Aetheris.Continuum.Tests/Backends/Sdf/AffineVolumeTests.cs b/Aetheris.Continuum.Tests/Backends/Sdf/AffineVolumeTests.csnew file mode 100644index 00000000..8028434b--- /dev/null+++ b/Aetheris.Continuum.Tests/Backends/Sdf/AffineVolumeTests.cs@@ -0,0 +1,139 @@+using Aetheris.Continuum.Backends.Sdf;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Continuum.Tests.Backends.Sdf;++public sealed class AffineVolumeTests+{+ [Theory]+ [InlineData(1, 0, 0, .3, .3)]+ [InlineData(1, 1, 0, 1, .5)]+ [InlineData(1, 2, 3, 1, 1d / 36)]+ [InlineData(1, 1e-7, 0, .3, .3 - .5e-7)]+ [InlineData(1, 1e-5, 2e-5, .3, .3 - 1.5e-5)]+ public void AxisTriangleAndSkinnyPlaneCutsEncloseIndependentIntegrals(double x, double y, double z, double offset, double expected)+ {+ var normal = new Vector3D(x, y, z);+ var length = normal.Length; normal /= length;+ var tangent = new Vector3D(-normal.Y, normal.X, 0);+ tangent /= tangent.Length;+ var other = normal.Cross(tangent);+ var shift = normal * (offset / length - 50);+ var transform = Transform3D.FromRowMajor([normal.X, normal.Y, normal.Z, 0,+ tangent.X, tangent.Y, tangent.Z, 0, other.X, other.Y, other.Z, 0, shift.X, shift.Y, shift.Z, 1]);+ var node = new SdfTransformNode(new SdfBoxNode(100, 100, 100), transform);+ var result = SdfAdaptiveVolumeEstimator.EstimateBounded(SdfTapeLowerer.Lower(node), new(new(0, 0, 0), new(1, 1, 1)), 1e-6, 1);+ Assert.InRange(expected, result.LowerBound, result.UpperBound);+ Assert.False(result.BudgetExhausted);+ Assert.Equal(1, result.AffineCutRegions);+ }++ [Theory]+ [InlineData(false)]+ [InlineData(true)]+ public void ObliquePlaneCutHasIndependentTetrahedralVolumeInOneRegion(bool complement)+ {+ var n = 1 / Math.Sqrt(3); var u = 1 / Math.Sqrt(2); var v = 1 / Math.Sqrt(6);+ var shift = (n - 50) * n;+ var transform = Transform3D.FromRowMajor([n, n, n, 0, -u, u, 0, 0, -v, -v, 2 * v, 0, shift, shift, shift, 1]);+ SdfNode node = new SdfTransformNode(new SdfBoxNode(100, 100, 100), transform);+ if (complement) node = new SdfSubtractNode(new SdfBoxNode(20, 20, 20), node);+ var result = SdfAdaptiveVolumeEstimator.EstimateBounded(SdfTapeLowerer.Lower(node), new(new(0, 0, 0), new(1, 1, 1)), 1e-8, 1);+ var expected = complement ? 5d / 6 : 1d / 6;+ Assert.InRange(expected, result.LowerBound, result.UpperBound);+ Assert.InRange(result.ErrorBound, 0, 1e-8);+ Assert.False(result.BudgetExhausted);+ Assert.Equal(1, result.AffineCutRegions);+ }++ [Fact]+ public void RegionAffineEnclosuresContainActualFieldValuesAcrossPrimitiveAndCsgBranches()+ {+ var random = new Random(20261028);+ var transform = Transform3D.CreateScale(new Vector3D(1.7, .6, 1.2))+ * Transform3D.CreateRotationY(.47) * Transform3D.CreateTranslation(new(17, -23, 4));+ var nodes = new List<(SdfNode Node, Func<double, double, Point3D> Surface)>+ {+ (new SdfSphereNode(10), (a,z) => new(10*Math.Cos(a)*Math.Sqrt(1-z*z),10*Math.Sin(a)*Math.Sqrt(1-z*z),10*z)),+ (new SdfCylinderNode(5,12), (a,z) => new(5*Math.Cos(a),5*Math.Sin(a),5*z)),+ (new SdfCylinderNode(5,12), (a,z) => new(2*Math.Cos(a),2*Math.Sin(a),6)),+ (new SdfCylinderNode(5,12), (a,z) => new(2*Math.Cos(a),2*Math.Sin(a),-6)),+ (new SdfBoxNode(12,14,16), (a,z) => new(6,5*Math.Sin(a),6*z)),+ (new SdfConeNode(6,2,12), (a,z) => new((4-5*z/3)*Math.Cos(a),(4-5*z/3)*Math.Sin(a),5*z)),+ (new SdfConeNode(2,6,12), (a,z) => new((4+5*z/3)*Math.Cos(a),(4+5*z/3)*Math.Sin(a),5*z)),+ (new SdfConeNode(6,2,12), (a,z) => new(Math.Cos(a),Math.Sin(a),6)),+ (new SdfConeNode(6,2,12), (a,z) => new(Math.Cos(a),Math.Sin(a),-6)),+ (new SdfTorusNode(10,2), (a,z) => new((10+2*Math.Cos(z*Math.PI))*Math.Cos(a),(10+2*Math.Cos(z*Math.PI))*Math.Sin(a),2*Math.Sin(z*Math.PI)))+ };+ nodes.Add((new SdfSubtractNode(new SdfSphereNode(10), new SdfSphereNode(5)), nodes[0].Surface));+ nodes.Add((new SdfSubtractNode(new SdfSphereNode(10), new SdfSphereNode(5)),+ (a,z) => new(5*Math.Cos(a)*Math.Sqrt(1-z*z),5*Math.Sin(a)*Math.Sqrt(1-z*z),5*z)));+ var checkedCount = 0;+ foreach (var item in nodes)+ foreach (var placement in new[] { Transform3D.Identity, transform, Transform3D.CreateScale(new Vector3D(-1, 1, 1)) * transform })+ {+ var tape = SdfTapeLowerer.Lower(new SdfTransformNode(item.Node, placement));+ var admitted = 0;+ for (var iteration = 0; iteration < 120; iteration++)+ {+ var center = item.Surface(random.NextDouble()*2*Math.PI, random.NextDouble()*1.8-.9);+ center = placement.Apply(center);+ var extent = new Vector3D(.02+random.NextDouble()*.35,.02+random.NextDouble()*.35,.02+random.NextDouble()*.35);+ var region = new SdfBounds(center - extent, center + extent);+ var affine = tape.EvaluateRegionEnclosure(region).Affine;+ if (affine is not {} e) continue;+ admitted++;+ for (var sample = 0; sample < 24; sample++)+ {+ var delta = sample < 8 ? new Vector3D((sample&1)==0?-extent.X:extent.X,(sample&2)==0?-extent.Y:extent.Y,(sample&4)==0?-extent.Z:extent.Z)+ : new Vector3D((2*random.NextDouble()-1)*extent.X,(2*random.NextDouble()-1)*extent.Y,(2*random.NextDouble()-1)*extent.Z);+ var value = tape.Evaluate(center + delta);+ var linear = e.Value + e.Gradient.Dot(delta);+ Assert.InRange(value, linear - e.LowerError - 1e-10, linear + e.UpperError + 1e-10);+ checkedCount++;+ }+ }+ Assert.True(admitted >= 10, $"Too few admitted {item.Node.Kind} enclosures: {admitted}.");+ }+ Assert.True(checkedCount > 10_000);+ }++ [Fact]+ public void SphereAndCylinderReachTightBoundsWithoutTheOldMillionCellBoundaryBand()+ {+ foreach (var (node, expected) in new (SdfNode, double)[] { (new SdfSphereNode(10), 4*Math.PI*1000/3), (new SdfCylinderNode(5,20),Math.PI*25*20) })+ {+ var result = SdfAdaptiveVolumeEstimator.EstimateBounded(SdfTapeLowerer.Lower(node), node.Bounds, expected*.001, 100001);+ Assert.InRange(expected, result.LowerBound, result.UpperBound);+ Assert.False(result.BudgetExhausted);+ Assert.True(result.AffineCutRegions > 0);+ Assert.True(result.RegionsVisited < 100001);+ }+ }++ [Fact]+ public void ADiscontinuousLegacyConeDistanceCannotCertifyBoundedVolume()+ {+ var cone = new SdfConeNode(6, 6, 1e-10);+ var tape = SdfTapeLowerer.Lower(cone);+ // The scalar projection shortcut jumps across this wall; a small+ // interval around the positive center value would omit negative values.+ var inside = tape.Evaluate(new(6 - 1e-12, 0, 0));+ var outside = tape.Evaluate(new(6 + 1e-12, 0, 0));+ Assert.True(outside - inside > 2e-12);+ var error = Assert.Throws<InvalidOperationException>(() =>+ SdfAdaptiveVolumeEstimator.EstimateBounded(tape, cone.Bounds, 1e-12));+ Assert.StartsWith("sdf-volume-cone-scale-unsupported:", error.Message);+ }++ [Fact]+ public void ThinShellWithNoInsideCornersCannotDisappearWhenBudgetIsSmall()+ {+ var shell = new SdfSubtractNode(new SdfSphereNode(10), new SdfSphereNode(9.99));+ var result = SdfAdaptiveVolumeEstimator.EstimateBounded(SdfTapeLowerer.Lower(shell), shell.Bounds, .001, 31);+ var expected = 4*Math.PI*(1000-Math.Pow(9.99,3))/3;+ Assert.InRange(expected, result.LowerBound, result.UpperBound);+ Assert.True(result.BudgetExhausted);+ Assert.True(result.IntervalFallbackRegions > 0);+ }+}diff --git a/Aetheris.Continuum/Backends/Sdf/SdfAdaptiveVolumeEstimator.cs b/Aetheris.Continuum/Backends/Sdf/SdfAdaptiveVolumeEstimator.csindex 5a6cc0dc..9a52db85 100644--- a/Aetheris.Continuum/Backends/Sdf/SdfAdaptiveVolumeEstimator.cs+++ b/Aetheris.Continuum/Backends/Sdf/SdfAdaptiveVolumeEstimator.cs@@ -37,14 +37,17 @@ public sealed record SdfAdaptiveVolumeResult(public sealed record SdfBoundedVolumeResult(double LowerBound, double UpperBound, int RegionsVisited, bool BudgetExhausted){+ public int AffineCutRegions { get; init; }+ public int IntervalFallbackRegions { get; init; }public double EstimatedVolume => (LowerBound + UpperBound) * .5;public double ErrorBound => (UpperBound - LowerBound) * .5;}public static class SdfAdaptiveVolumeEstimator{- /// <summary>Occupied-volume enclosure. Mixed cells contribute [0, cell volume],- /// never a sampling-based error claim. Refine the largest uncertainty first.+ /// <summary>Occupied-volume enclosure. Analytic affine field envelopes bound+ /// partial cells; unresolved cells retain [0, cell volume]. Refine the largest+ /// remaining uncertainty first; no sampling-based error claim is made./// Bounds assume the tape's supported analytic interval contract and finite/// enclosing input bounds; roundoff guards are included, not formal interval arithmetic.</summary>public static SdfBoundedVolumeResult EstimateBounded(SdfTape tape, SdfBounds bounds, double absoluteError,@@ -56,35 +59,60 @@ public static class SdfAdaptiveVolumeEstimator|| !double.IsFinite(enclosingVolume) || enclosingVolume <= 0|| bounds.SizeX <= 0 || bounds.SizeY <= 0 || bounds.SizeZ <= 0)throw new ArgumentException("Bounded volume requires finite positive bounds, a nonnegative error and a positive region budget.");- var queue = new PriorityQueue<(SdfBounds Region, int Depth), (double Volume, int Order)>();- double inside = 0, uncertain = 0;- var visited = 0;+ // The existing scalar cone evaluator clamps its generator projection+ // below this threshold. Its sign can then jump at the wall, so the+ // distance/Lipschitz interval contract is not valid at that local scale.+ if (tape.ConePayloads.Any(cone => cone.Height * cone.Height+ + (cone.TopRadius - cone.BottomRadius) * (cone.TopRadius - cone.BottomRadius) <= 1e-18))+ throw new InvalidOperationException("sdf-volume-cone-scale-unsupported: The cone's local generator is below the scalar distance evaluator's supported scale. Rescale the analytic definition before requesting bounded SDF volume.");+ var queue = new PriorityQueue<(SdfBounds Region, int Depth, double Lower, double Upper), (double Uncertainty, int Order)>();+ double lower = 0, upper = 0;+ double lowerCorrection = 0, upperCorrection = 0;+ void Accumulate(double lo, double hi)+ {+ var adjusted = lo - lowerCorrection; var next = lower + adjusted;+ lowerCorrection = (next - lower) - adjusted; lower = next;+ adjusted = hi - upperCorrection; next = upper + adjusted;+ upperCorrection = (next - upper) - adjusted; upper = next;+ }+ var visited = 0; var affineRegions = 0; var fallbackRegions = 0;var padding = 1e-12 * Math.Max(1, new[] { bounds.Min.X, bounds.Min.Y, bounds.Min.Z, bounds.Max.X, bounds.Max.Y, bounds.Max.Z }.Max(Math.Abs));void Admit(SdfBounds region, int depth){- var interval = tape.EvaluateInterval(region);+ var enclosure = tape.EvaluateRegionEnclosure(region);+ var interval = enclosure.Interval;var volume = RegionVolume(region);visited++;if (!double.IsFinite(interval.MinValue) || !double.IsFinite(interval.MaxValue) || interval.MinValue > interval.MaxValue)throw new InvalidOperationException("sdf-volume-interval-invalid: The field returned no finite conservative interval.");- if (interval.MaxValue < -padding) inside += volume;- else if (interval.MinValue <= padding)+ double lo = 0, hi = volume;+ if (interval.MaxValue < -padding) lo = volume;+ else if (interval.MinValue > padding) hi = 0;+ else if (enclosure.Affine is { } affine){- uncertain += volume;- if (depth < maximumDepth) queue.Enqueue((region, depth), (-volume, visited));+ if (!double.IsFinite(affine.Value + affine.Gradient.X + affine.Gradient.Y + affine.Gradient.Z + affine.LowerError + affine.UpperError)+ || affine.LowerError < 0 || affine.UpperError < 0)+ throw new InvalidOperationException("sdf-volume-affine-invalid: The field returned no finite conservative affine enclosure.");+ var fraction = SdfAffineCellVolume.Enclose(affine, region, padding);+ lo = fraction.Lower * volume; hi = fraction.Upper * volume; affineRegions++;}+ else fallbackRegions++;+ Accumulate(lo, hi);+ if (hi > lo && depth < maximumDepth) queue.Enqueue((region, depth, lo, hi), (lo - hi, visited));}Admit(bounds, 0);- while (uncertain > 2 * absoluteError && queue.Count > 0 && visited + 2 <= maximumRegions)+ var roundoff = enclosingVolume * 1e-12;+ var targetWidth = Math.Max(0, 2 * absoluteError - 2 * roundoff);+ while (upper - lower > targetWidth && queue.Count > 0 && visited + 2 <= maximumRegions){var item = queue.Dequeue();- uncertain -= RegionVolume(item.Region);+ Accumulate(-item.Lower, -item.Upper);foreach (var child in SplitLongestAxis(item.Region)) Admit(child, item.Depth + 1);}- var roundoff = enclosingVolume * 1e-12;- var lower = Math.Max(0, inside - roundoff);- var upper = Math.Min(enclosingVolume, inside + Math.Max(0, uncertain) + roundoff);- return new(lower, upper, visited, upper - lower > 2 * absoluteError);+ lower = Math.Max(0, lower - roundoff);+ upper = Math.Min(enclosingVolume, upper + roundoff);+ return new(lower, upper, visited, upper - lower > 2 * absoluteError)+ { AffineCutRegions = affineRegions, IntervalFallbackRegions = fallbackRegions };}public static SdfAdaptiveVolumeResult EstimateVolume(SdfTape tape, SdfBounds bounds, SdfAdaptiveVolumeOptions? options = null, ToleranceContext? tolerance = null)diff --git a/Aetheris.Continuum/Backends/Sdf/SdfAffineCellVolume.cs b/Aetheris.Continuum/Backends/Sdf/SdfAffineCellVolume.csnew file mode 100644index 00000000..967d9f7c--- /dev/null+++ b/Aetheris.Continuum/Backends/Sdf/SdfAffineCellVolume.cs@@ -0,0 +1,63 @@+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Continuum.Backends.Sdf;++/// <summary>Encloses the occupied fraction of a box between two affine level+/// sets. The plane/box integral is analytic; curvature remains an uncertainty+/// band, never an empirically sampled error estimate.</summary>+internal static class SdfAffineCellVolume+{+ internal static (double Lower, double Upper) Enclose(SdfAffineEnclosure field, SdfBounds box, double padding)+ {+ double[] weights = [double.Abs(field.Gradient.X) * box.SizeX,+ double.Abs(field.Gradient.Y) * box.SizeY, double.Abs(field.Gradient.Z) * box.SizeZ];+ var max = weights.Max();+ // Tiny coefficients cause cancellation in the inclusion-exclusion+ // formula. Carry their FULL variation into the uncertainty instead.+ var dropped = weights.Where(w => w < max * 1e-5).Sum() / 2;+ var active = weights.Where(w => w > 0 && w >= max * 1e-5).Select(w => w / max).ToArray();+ if (active.Length == 0)+ return (field.Value + field.UpperError + padding <= 0 ? 1 : 0,+ field.Value - field.LowerError - padding <= 0 ? 1 : 0);+ var halfWidth = active.Sum() / 2;+ var lower = Fraction(active, halfWidth - (field.Value + field.UpperError + padding + dropped) / max);+ var upper = Fraction(active, halfWidth - (field.Value - field.LowerError - padding - dropped) / max);+ return (lower.Lower, upper.Upper);+ }++ private static (double Lower, double Upper) Fraction(double[] widths, double threshold)+ {+ var total = widths.Sum();+ if (threshold <= 0) return (0, 0);+ if (threshold >= total) return (1, 1);+ // Complement symmetry reduces subtraction near a full cell.+ if (threshold > total / 2)+ {+ var other = Fraction(widths, total - threshold);+ return (1 - other.Upper, 1 - other.Lower);+ }+ var longest = widths.Max();+ var remainder = total - longest;+ // In the central slab, integrate the longest uniform axis first.+ // This is linear and avoids subtracting nearly equal cubic terms+ // for cuts with two tiny normal components.+ if (threshold >= remainder && threshold <= longest)+ {+ var value = (threshold - remainder / 2) / longest;+ const double guard = 64 * 2.2204460492503131e-16;+ return (double.Clamp(value - guard, 0, 1), double.Clamp(value + guard, 0, 1));+ }+ var n = widths.Length; double sum = 0, absoluteSum = 0;+ for (var subset = 0; subset < 1 << n; subset++)+ {+ var t = threshold; var sign = 1;+ for (var axis = 0; axis < n; axis++) if ((subset & (1 << axis)) != 0) { t -= widths[axis]; sign = -sign; }+ var term = n == 1 ? double.Max(t, 0) : n == 2 ? double.Pow(double.Max(t, 0), 2) : double.Pow(double.Max(t, 0), 3);+ sum += sign * term; absoluteSum += term;+ }+ var denominator = widths.Aggregate(n == 3 ? 6d : n == 2 ? 2d : 1d, (p, w) => p * w);+ var fraction = sum / denominator;+ var roundoff = 64 * 2.2204460492503131e-16 * (absoluteSum / denominator + 1);+ return (double.Clamp(fraction - roundoff, 0, 1), double.Clamp(fraction + roundoff, 0, 1));+ }+}diff --git a/Aetheris.Fields/SdfAffineEnclosure.cs b/Aetheris.Fields/SdfAffineEnclosure.csnew file mode 100644index 00000000..c29f4974--- /dev/null+++ b/Aetheris.Fields/SdfAffineEnclosure.cs@@ -0,0 +1,191 @@+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Continuum.Backends.Sdf;++/// <summary>For x in the queried box, f(x) lies between+/// Value + Gradient.(x-center) - LowerError and the same affine term + UpperError.+/// Analytic curvature bounds, not fitted samples, supply the remainder.</summary>+public readonly record struct SdfAffineEnclosure(double Value, Vector3D Gradient, double LowerError, double UpperError);+public readonly record struct SdfRegionEnclosure(FieldInterval Interval, SdfAffineEnclosure? Affine);++public sealed partial class SdfTape+{+ public SdfRegionEnclosure EvaluateRegionEnclosure(SdfBounds region)+ {+ var ranges = new FieldInterval[SlotCount];+ EvaluateIntervalSlots(region, ranges);+ var root = ranges[OutputSlot];+ if (root.MinValue > 0 || root.MaxValue < 0) return new(root, null);+ var affine = new SdfAffineEnclosure?[SlotCount];+ foreach (var instruction in Instructions)+ {+ var a = instruction.InputA; var b = instruction.InputB;+ affine[instruction.DestSlot] = instruction.OpCode switch+ {+ SdfTapeOpCode.EvalSphere => SphereEnclosure(region, SpherePayloads[instruction.PayloadIndex]),+ SdfTapeOpCode.EvalCylinder => CylinderEnclosure(region, CylinderPayloads[instruction.PayloadIndex]),+ SdfTapeOpCode.EvalBox => BoxEnclosure(region, BoxPayloads[instruction.PayloadIndex]),+ SdfTapeOpCode.EvalTorus => TorusEnclosure(region, TorusPayloads[instruction.PayloadIndex]),+ SdfTapeOpCode.EvalCone => ConeEnclosure(region, ConePayloads[instruction.PayloadIndex]),+ SdfTapeOpCode.Min => ranges[a].MaxValue <= ranges[b].MinValue ? affine[a]+ : ranges[b].MaxValue <= ranges[a].MinValue ? affine[b] : null,+ SdfTapeOpCode.Max => ranges[a].MinValue >= ranges[b].MaxValue ? affine[a]+ : ranges[b].MinValue >= ranges[a].MaxValue ? affine[b] : null,+ SdfTapeOpCode.Neg when affine[a] is { } value => new(-value.Value, -value.Gradient, value.UpperError, value.LowerError),+ _ => null // Unsupported/singular branches retain the interval fallback.+ };+ }+ return new(root, affine[OutputSlot]);+ }++ private static Point3D Center(SdfBounds box) => box.Min + (box.Max - box.Min) * .5;+ private static double HalfDiagonalSquared(SdfBounds box) => (box.SizeX * box.SizeX + box.SizeY * box.SizeY + box.SizeZ * box.SizeZ) * .25;+ private static Vector3D PullGradient(Transform3D inverse, Vector3D local) => new(+ local.Dot(inverse.Apply(new Vector3D(1, 0, 0))), local.Dot(inverse.Apply(new Vector3D(0, 1, 0))),+ local.Dot(inverse.Apply(new Vector3D(0, 0, 1))));++ private static double NormRemainder(SdfBounds region, Transform3D inverse, Vector3D unit,+ double length, double fallback, bool radial = false)+ {+ var x = inverse.Apply(new Vector3D(region.SizeX / 2, 0, 0));+ var y = inverse.Apply(new Vector3D(0, region.SizeY / 2, 0));+ var z = inverse.Apply(new Vector3D(0, 0, region.SizeZ / 2));+ if (radial) { x = new(x.X, x.Y, 0); y = new(y.X, y.Y, 0); z = new(z.X, z.Y, 0); }+ var minProjection = length - double.Abs(unit.Dot(x)) - double.Abs(unit.Dot(y)) - double.Abs(unit.Dot(z));+ if (minProjection <= 0) return fallback;+ double perpendicularSquared = 0;+ // A convex quadratic reaches its maximum at a box corner. Opposite+ // corners have the same value, so four transformed deltas suffice.+ for (var corner = 0; corner < 4; corner++)+ {+ var delta = x + ((corner & 1) == 0 ? y : -y) + ((corner & 2) == 0 ? z : -z);+ var parallel = unit.Dot(delta);+ perpendicularSquared = double.Max(perpendicularSquared, delta.LengthSquared - parallel * parallel);+ }+ // ||q+d|| - (||q|| + unit.d) = |d_perp|^2 /+ // (||q+d|| + ||q|| + unit.d). The denominator is >= 2*minProjection.+ return double.Min(fallback, perpendicularSquared / (2 * minProjection));+ }++ private static SdfAffineEnclosure? SphereEnclosure(SdfBounds region, SdfTapeSpherePayload payload)+ {+ var local = TransformBounds(region, payload.InverseTransform);+ var minRadius = MinDistanceToAabbOrigin(local);+ if (minRadius <= 0) return null; // Norm Hessian is singular at its center.+ var p = payload.InverseTransform.Apply(Center(region));+ var v = new Vector3D(p.X, p.Y, p.Z); var length = v.Length;+ var unit = v / length;+ return new(length - payload.Radius, PullGradient(payload.InverseTransform, unit),+ 0, NormRemainder(region, payload.InverseTransform, unit, length, HalfDiagonalSquared(local) / (2 * minRadius)));+ }++ private static SdfAffineEnclosure? CylinderEnclosure(SdfBounds region, SdfTapeCylinderPayload payload)+ {+ var local = TransformBounds(region, payload.InverseTransform);+ var radial = RadiusInterval(local, payload.Radius);+ var axial = AxisAbsDistanceInterval(local.Min.Z, local.Max.Z, payload.Height / 2);+ var p = payload.InverseTransform.Apply(Center(region));+ // With the other extrusion component inside, the finite-cylinder SDF+ // equals its dominant radial or planar-cap distance over this whole box.+ if (axial.MaxValue <= 0 && radial.MinValue >= axial.MaxValue)+ {+ var minRadius = radial.MinValue + payload.Radius;+ if (minRadius <= 0) return null;+ var length = double.Sqrt(p.X * p.X + p.Y * p.Y);+ var unit = new Vector3D(p.X / length, p.Y / length, 0);+ return new(length - payload.Radius, PullGradient(payload.InverseTransform, unit),+ 0, NormRemainder(region, payload.InverseTransform, unit, length,+ (local.SizeX * local.SizeX + local.SizeY * local.SizeY) / (8 * minRadius), radial: true));+ }+ if (radial.MaxValue <= 0 && axial.MinValue >= radial.MaxValue && (local.Min.Z >= 0 || local.Max.Z <= 0))+ {+ var sign = p.Z >= 0 ? 1 : -1;+ return new(double.Abs(p.Z) - payload.Height / 2, PullGradient(payload.InverseTransform, new(0, 0, sign)), 0, 0);+ }+ return null;+ }++ private static SdfAffineEnclosure? BoxEnclosure(SdfBounds region, SdfTapeBoxPayload payload)+ {+ var local = TransformBounds(region, payload.InverseTransform);+ var p = payload.InverseTransform.Apply(Center(region));+ double[] min = [local.Min.X, local.Min.Y, local.Min.Z];+ double[] max = [local.Max.X, local.Max.Y, local.Max.Z];+ double[] half = [payload.Width / 2, payload.Height / 2, payload.Depth / 2];+ double[] center = [p.X, p.Y, p.Z];+ var ranges = Enumerable.Range(0, 3).Select(i => AxisAbsDistanceInterval(min[i], max[i], half[i])).ToArray();+ for (var axis = 0; axis < 3; axis++)+ {+ if (min[axis] < 0 && max[axis] > 0) continue;+ if (Enumerable.Range(0, 3).Any(i => i != axis && (ranges[i].MaxValue > 0 || ranges[axis].MinValue < ranges[i].MaxValue))) continue;+ var sign = center[axis] >= 0 ? 1 : -1;+ var normal = axis == 0 ? new Vector3D(sign, 0, 0) : axis == 1 ? new Vector3D(0, sign, 0) : new Vector3D(0, 0, sign);+ return new(double.Abs(center[axis]) - half[axis], PullGradient(payload.InverseTransform, normal), 0, 0);+ }+ return null;+ }++ private static SdfAffineEnclosure? TorusEnclosure(SdfBounds region, SdfTapeTorusPayload payload)+ {+ var local = TransformBounds(region, payload.InverseTransform);+ var radial = RadiusInterval(local, payload.MajorRadius);+ var minRadius = radial.MinValue + payload.MajorRadius;+ var minTube = MinDistanceToRectOrigin(radial.MinValue, radial.MaxValue, local.Min.Z, local.Max.Z);+ if (minRadius <= 0 || minTube <= 0) return null;+ var p = payload.InverseTransform.Apply(Center(region));+ var radius = double.Sqrt(p.X * p.X + p.Y * p.Y);+ var d = radius - payload.MajorRadius;+ var tube = double.Sqrt(d * d + p.Z * p.Z);+ var gradient = new Vector3D(d * p.X / (tube * radius), d * p.Y / (tube * radius), p.Z / tube);+ // H(norm(rho-R,z)) <= 1/minTube + 1/minRadius. This bound+ // holds across both convex and concave tube quadrants.+ var error = .5 * HalfDiagonalSquared(local) * (1 / minTube + 1 / minRadius);+ return new(tube - payload.MinorRadius, PullGradient(payload.InverseTransform, gradient), error, error);+ }++ private static SdfAffineEnclosure? ConeEnclosure(SdfBounds region, SdfTapeConePayload payload)+ {+ var local = TransformBounds(region, payload.InverseTransform);+ var radial = RadiusInterval(local, 0);+ var p = payload.InverseTransform.Apply(Center(region));+ var slope = (payload.TopRadius - payload.BottomRadius) / payload.Height;+ var intercept = (payload.TopRadius + payload.BottomRadius) / 2;+ var norm = double.Sqrt(1 + slope * slope);+ var z0 = slope * local.Min.Z; var z1 = slope * local.Max.Z;+ var wall = new FieldInterval((radial.MinValue - double.Max(z0, z1) - intercept) / norm,+ (radial.MaxValue - double.Min(z0, z1) - intercept) / norm);+ var capGap = payload.Height / 2 - MaxAbsInInterval(local.Min.Z, local.Max.Z);+ var deltaRadius = payload.TopRadius - payload.BottomRadius;+ var denominator = deltaRadius * deltaRadius + payload.Height * payload.Height;+ if (denominator <= 1e-18) return null; // Scalar evaluator uses a degenerate projection, not this wall distance.+ var projections = new[]+ {+ ((payload.TopRadius - radial.MinValue) * deltaRadius + (payload.Height / 2 - local.Min.Z) * payload.Height) / denominator,+ ((payload.TopRadius - radial.MinValue) * deltaRadius + (payload.Height / 2 - local.Max.Z) * payload.Height) / denominator,+ ((payload.TopRadius - radial.MaxValue) * deltaRadius + (payload.Height / 2 - local.Min.Z) * payload.Height) / denominator,+ ((payload.TopRadius - radial.MaxValue) * deltaRadius + (payload.Height / 2 - local.Max.Z) * payload.Height) / denominator+ };+ // The nearest point lies inside the finite generator, and is closer+ // than either cap throughout the box: the SDF equals the wall distance.+ if (capGap > 0 && MaxAbsInInterval(wall.MinValue, wall.MaxValue) <= capGap+ && projections.Min() >= 0 && projections.Max() <= 1 && radial.MinValue > 0)+ {+ var radius = double.Sqrt(p.X * p.X + p.Y * p.Y);+ var unit = new Vector3D(p.X / radius, p.Y / radius, 0);+ return new((radius - slope * p.Z - intercept) / norm,+ PullGradient(payload.InverseTransform, new(p.X / (radius * norm), p.Y / (radius * norm), -slope / norm)),+ 0, NormRemainder(region, payload.InverseTransform, unit, radius,+ (local.SizeX * local.SizeX + local.SizeY * local.SizeY) / (8 * radial.MinValue), radial: true) / norm);+ }+ if (local.Min.Z >= 0 || local.Max.Z <= 0)+ {+ var sign = p.Z >= 0 ? 1 : -1;+ var cap = AxisAbsDistanceInterval(local.Min.Z, local.Max.Z, payload.Height / 2);+ var endRadius = sign > 0 ? payload.TopRadius : payload.BottomRadius;+ if (radial.MaxValue <= endRadius && (wall.MaxValue <= 0 || cap.MinValue >= 0)+ && MinAbsInInterval(wall.MinValue, wall.MaxValue) >= MaxAbsInInterval(cap.MinValue, cap.MaxValue))+ return new(double.Abs(p.Z) - payload.Height / 2, PullGradient(payload.InverseTransform, new(0, 0, sign)), 0, 0);+ }+ return null;+ }+}diff --git a/Aetheris.Fields/SdfTape.cs b/Aetheris.Fields/SdfTape.csindex b9e050d3..92fb7473 100644--- a/Aetheris.Fields/SdfTape.cs+++ b/Aetheris.Fields/SdfTape.cs@@ -48,7 +48,7 @@ public enum SdfRegionClassification/// Linear MIR/runtime representation for CIR point evaluation./// During transition, this is the intended execution form while <see cref="SdfNode"/> remains the semantic builder/oracle./// </summary>-public sealed class SdfTape+public sealed partial class SdfTape{public SdfTape(IReadOnlyList<SdfTapeInstruction> instructions,@@ -137,7 +137,12 @@ public sealed class SdfTapepublic FieldInterval EvaluateInterval(SdfBounds region){var slots = new FieldInterval[SlotCount];+ EvaluateIntervalSlots(region, slots);+ return slots[OutputSlot];+ }+ private void EvaluateIntervalSlots(SdfBounds region, FieldInterval[] slots)+ {foreach (var instruction in Instructions){switch (instruction.OpCode)@@ -182,7 +187,6 @@ public sealed class SdfTape}}- return slots[OutputSlot];}public SdfRegionClassification ClassifyRegion(SdfBounds region, ToleranceContext tolerance)diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentAssertionsTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentAssertionsTests.csindex 681e4713..8082b82c 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentAssertionsTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentAssertionsTests.cs@@ -98,10 +98,27 @@ public sealed class FirmamentAssertionsTests{var built = FirmamentBuildAndExport.CompileSource(Source("sphere"));Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));- var field = new FirmamentMeasurements(built.Value).Volume(50, forceSdf: true);+ var field = new FirmamentMeasurements(built.Value).Volume(4, forceSdf: true);Assert.Equal("SdfAdaptiveOccupiedVolumeInterval", field.Method);Assert.InRange(4 * Math.PI * 1000 / 3, field.LowerBoundMm3!.Value, field.UpperBoundMm3!.Value);Assert.True(field.RegionsVisited > 1);+ Assert.True(field.RegionsVisited < 100_001);+ Assert.False(field.BudgetExhausted);+ Assert.InRange(field.ErrorBoundMm3!.Value, 0, 4);+ Assert.True(field.AffineCutRegions > 0);+ }++ [Fact]+ public void TightSdfAssertionGatesCompilationAndLeavesStepGeometryUnchanged()+ {+ var source = Source("sphere-tight");+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ var assertion = Assert.Single(built.Value.Assertions!);+ Assert.True(assertion.Passed);+ Assert.Equal("SdfAdaptiveOccupiedVolumeInterval", assertion.MeasurementMethod);+ Assert.InRange(assertion.MeasurementErrorBoundMm3!.Value, 0, 1);+ Assert.Equal(FirmamentBuildAndExport.CompileForMeasurement(source).Value.StepText, built.Value.StepText);}[Fact]diff --git a/Aetheris.Kernel.Firmament/Analysis/FirmamentMeasurements.cs b/Aetheris.Kernel.Firmament/Analysis/FirmamentMeasurements.csindex 7606865c..d083d217 100644--- a/Aetheris.Kernel.Firmament/Analysis/FirmamentMeasurements.cs+++ b/Aetheris.Kernel.Firmament/Analysis/FirmamentMeasurements.cs@@ -12,6 +12,8 @@ namespace Aetheris.Kernel.Firmament.Analysis;public sealed record FirmamentVolumeMeasurement(double? ValueMm3, double? LowerBoundMm3, double? UpperBoundMm3,string Method, bool Authoritative, int? RegionsVisited = null, bool BudgetExhausted = false, string? Diagnostic = null){+ public int? AffineCutRegions { get; init; }+ public int? IntervalFallbackRegions { get; init; }public double? ErrorBoundMm3 => LowerBoundMm3 is { } lo && UpperBoundMm3 is { } hi ? (hi - lo) * .5 : null;}public sealed record FirmamentBoundsMeasurement(double[] MinimumMm, double[] MaximumMm, string Method);@@ -91,6 +93,7 @@ public sealed class FirmamentMeasurementsvar bounds = root!.Bounds;var error = absoluteErrorMm3 ?? bounds.SizeX * bounds.SizeY * bounds.SizeZ * .005;var result = SdfAdaptiveVolumeEstimator.EstimateBounded(SdfTapeLowerer.Lower(root), bounds, error, maximumRegions);- return new(result.EstimatedVolume, result.LowerBound, result.UpperBound, "SdfAdaptiveOccupiedVolumeInterval", true, result.RegionsVisited, result.BudgetExhausted);+ return new(result.EstimatedVolume, result.LowerBound, result.UpperBound, "SdfAdaptiveOccupiedVolumeInterval", true, result.RegionsVisited, result.BudgetExhausted)+ { AffineCutRegions = result.AffineCutRegions, IntervalFallbackRegions = result.IntervalFallbackRegions };}}diff --git a/Aetheris.slnx b/Aetheris.slnxindex 7bba91ef..a98f2d91 100644--- a/Aetheris.slnx+++ b/Aetheris.slnx@@ -76,6 +76,7 @@<Deploy /></Project><Project Path="Aetheris.CLI/Aetheris.CLI.csproj" />+ <Project Path="tools/Aetheris.SdfVolumeQualification/Aetheris.SdfVolumeQualification.csproj" /><Folder Name="/demos/"><Project Path="demos/Aetheris.CodeNativeBracket/Aetheris.CodeNativeBracket.csproj" /><Project Path="demos/Aetheris.DifferenceEngine.Showcase/Aetheris.DifferenceEngine.Showcase.csproj" />diff --git a/docs/development/reports/2026-10/sdf-volume-viability.md b/docs/development/reports/2026-10/sdf-volume-viability.mdnew file mode 100644index 00000000..1205d879--- /dev/null+++ b/docs/development/reports/2026-10/sdf-volume-viability.md@@ -0,0 +1,181 @@+# SDF volume viability — 2026-10-28++The existing bounded estimator is now useful at 0.1% occupied-volume uncertainty+for the ten constructive analytic reference fields below. This improves numerical+integration without changing geometry, broadening field admission or treating a+display mesh as volume authority.++## What changed++Previously every mixed boundary cell contributed `[0, cell volume]`. Refinement+reduced cell size but spent most of its budget on a thick uncertain boundary band.+The radius-10 sphere could not meet even ±50 mm³ within one million regions.++`SdfTape.EvaluateRegionEnclosure` now reuses the existing interval instruction+evaluation and supplies a local affine envelope where analytic primitive branches+permit it. Sphere and cylindrical/frustum walls use convex norm remainder bounds;+box and cap branches are planar; torus branches use a two-sided Hessian bound.+Inverse transforms pull gradients back into world coordinates, including nonuniform+scale and reflection. CSG propagates an envelope only when interval dominance+proves which branch is active. Negation swaps the two remainder bounds.++For a cell centered at `c`, the contract is+`L(x) - lowerError <= field(x) <= L(x) + upperError`, with+`L(x) = value + gradient·(x-c)`. Consequently:++- `L(x) + upperError <= 0` defines a subset of occupied material.+- `L(x) - lowerError <= 0` defines a superset of occupied material.++Integrating those two plane cuts through the box bounds occupied volume. The+normalized weighted-uniform integral uses inclusion/exclusion, complement symmetry+and an exact central-slab branch to avoid cancellation near axis-aligned cuts.+Very small normal components contribute their full variation to uncertainty.+This is analytic integration of field envelopes, not fitting an empirical error+bar to sampled points. Primitive volume formulas appear only in qualification.++Analytic plane/cube volume fractions have established numerical literature; see+[Scardovelli and Zaleski, JCP 164 (2000), 228–237](https://www.sciencedirect.com/science/article/pii/S0021999100965677).+Here the two enclosing planes carry the curvature uncertainty explicitly, rather+than treating one reconstructed plane as the exact curved interface.++The estimator refines the largest remaining volume uncertainty, uses compensated+global sums, and retains the existing strict inside/outside classification,+region/depth budgets and roundoff guards. Unsupported/singular envelopes and+unresolved CSG seams keep `[0, cell volume]`. A thin shell is not removed merely+because its cell corners are outside. No new JudgmentEngine policy is needed for+these deterministic transformations; the existing measurement owner still chooses+exact BRep versus admitted SDF.++## Controlled evidence++Release, .NET 10.0.401, Windows x64, Ryzen 7 7700X. Each path receives full-workload+warmup; three timed repetitions alternate execution order; tiered compilation is+disabled. Same bounds, fields, 0.1% requested half-width, 1,000,001-region cap and+depth 30. `tools/Aetheris.SdfVolumeQualification` freezes the former estimator from+`e1310ce2` as a qualification-only control, sharing the unchanged interval math.+Times are local warmed medians, not cold CLI latency or portable benchmarks.++All references lie in every measured interval. All ten new intervals meet the+target; all ten interval-only controls exhaust their budgets without meeting it.++| Field | New half-width mm³ | Old half-width mm³ | New regions | New ms | Old ms |+|---|---:|---:|---:|---:|---:|+| Sphere, r=10 | 4.188 | 78.936 | 35,805 | 46 | 572 |+| Scaled/rotated/translated sphere | 6.283 | 214.627 | 81,797 | 104 | 618 |+| Cylinder | 1.571 | 26.457 | 42,453 | 56 | 705 |+| Frustum | 0.653 | 18.216 | 52,707 | 62 | 621 |+| Torus | 0.790 | 36.827 | 861,033 | 1,302 | 627 |+| Plate with three through holes | 13.890 | 509.607 | 68,833 | 321 | 2,536 |+| Crossed ribs | 5.736 | 195.052 | 248,921 | 889 | 1,967 |+| Thin spherical shell, r=9.5–10 | 0.597 | 213.287 | 929,655 | 2,360 | 1,144 |+| Overlapping-sphere union | 0.938 | 19.972 | 72,593 | 166 | 1,129 |+| Overlapping-sphere intersection | 0.109 | 2.707 | 77,035 | 175 | 1,127 |++The difficult torus/shell cases cost more time than the old *inconclusive* result.+This is not a universal speedup claim. Temporary allocation also remains material:+about 85 MiB for the sphere, 620 MiB for the plate, and 3.75 GiB cumulatively for+the thin shell in a run. These are allocated bytes over the call, not simultaneous+resident memory or a leak. Per-cell interval/envelope scratch allocation is a+worthwhile next optimization before repeatedly integrating such cases interactively.++A second probe requests **0.01%** with the same work cap. Six cases meet it; four+truthfully report exhaustion. All ten still contain their independent references.+This probe uses one timed repetition; its timing is not used in the comparison.++| Exhausted field | Requested half-width mm³ | Actual half-width mm³ |+|---|---:|---:|+| Torus | 0.078957 | 0.657370 |+| Crossed ribs | 0.573600 | 1.856746 |+| Thin shell | 0.059743 | 0.551188 |+| Sphere intersection | 0.010891 | 0.012296 |++The single-region and thin-feature regressions additionally retain inconclusive+results at deliberately insufficient budgets. No increase in the default work+budget or relaxation of admission was used to make the target pass.++## Real compiler behavior and boundaries++`aetheris measure fixtures/Regression/Assertions/sphere.firmament --sdf --error 50+--json` now meets its target in 2,809 regions (actual half-width 49.964 mm³), versus+the previous exhausted million-region result. At `--error 4`, it meets the target+in 36,985 regions. `sphere-tight.firmament` passes both CLI validate and build with+a ±4 mm³ volume assertion; the assertion requests ±1 mm³ integration uncertainty.+The test also proves measurement/assertion evaluation leaves STEP text unchanged.++The CLI adds `affineCutRegions` and `intervalFallbackRegions`, counting visited+cells including subsequently refined parents. Existing method/authority fields and+the assertion rule requiring the **entire** interval to lie within tolerance remain.+Exact admitted measurements still take precedence unless `--sdf` is requested.++This qualifies the integrator for the supported analytic tape operations. It does+not promote every existing Boolean/display CIR mirror to final-material authority.+The production admission flag still covers qualified exported primitives. Imported+CTC-01 still lacks a qualified field for its complete trimmed solid. Deriving one+from its suspect STL would destroy independence, so no such fallback was added.+The actual CLI probe of `fixtures/Canonical/PMI/nist-ctc01-passthrough.firmament`+confirms `geometryBuilt: true`, volume `Unavailable`, `authoritative: false` and+exit 1, with the missing qualified CIR field explained in the diagnostic.+Extending final-operation CIR and independently qualified imported-body occupancy+is the next coverage task, separate from this numerical integration repair.++The enclosure contract assumes supported analytic field intervals/envelopes and+finite enclosing bounds. Floating-point padding is included, but this is not+formally outward-rounded interval arithmetic. Volume uncertainty is not a positional+tolerance, and correct field volume does not certify a watertight STL or correct+local geometry. Tighter targets may still exhaust the explicit work budget.++Code review also isolated an existing scalar cone projection shortcut at local+generator squared length ≤1e-18. At that scale its signed value can jump across+the wall, invalidating the distance/Lipschitz interval premise. Bounded measurement+now rejects it explicitly with `sdf-volume-cone-scale-unsupported`, and the affine+API declines that wall envelope. A regression demonstrates the discontinuity.+Ordinary engineering cones and their geometry are unchanged; repairing that+legacy scalar shortcut itself is outside this integration pass.++## Qualification++Focused tests cover independent axis/triangle/tetrahedron integrals, complementary+cuts, nearly axis-aligned cuts, transformed/reflected fields, both cylinder caps,+both frustum caps, expanding/contracting frusta, inner cavity negation, thin-feature+fallback, deterministic budgets, tight convergence and compiler/CLI propagation.+The sampled field-envelope tests check implementation behavior at corners and+interior points; the inequalities above, rather than sampling, motivate the bounds.++Final qualification:++- Release solution build: zero errors; existing nullable/analyzer/WASM trimming+ warnings remain (38 reported on the final build).+- Focused interval/envelope/bounded-volume lane: 25 passed.+- Focused compiler assertion lane: 17 passed; actual tight-assertion CLI validate+ and build both exit 0. CLI measurement JSON carries the new counters.+- Fast Core lane: 1,168 passed. Final full Core corpus lane: 1,356 passed.+- Final full solution gate: **6,316 passed, zero failed, two optional external+ PDF-renderer skips**, across twenty test assemblies. The full gate also covers+ canonical geometry/interchange and the editable V8.+- Managed/WASM SDK rebuilt; all nineteen JavaScript SDK tests passed.+- `git diff --check` passed; task-owned build/test/benchmark hosts exited.++Commands used the serial Release lane (`-m:1 -nr:false`, shared compilation off+for builds). The full gate used `--no-build -- RunConfiguration.MaxCpuCount=1`.+An initial complete green run is retained as `full-tests-initial.log`; the final+run includes the additional discontinuous-cone rejection regression.++Generated baseline/comparison JSON, actual CLI JSON/STEP and build/test logs are+under ignored `artifacts/local/sdf-volume/`. Public behavior is documented in+`docs/public/reference/language/checks.md`.++Code-quality review kept interval dispatch shared, primitive envelopes in the+field owner, plane integration in Continuum, and admission in the existing+measurement owner. There are no new dependencies, sampled authority, global+mutable caches or production strategy routes. Point evaluation and geometry+generation remain unchanged. The frozen old estimator exists only in the+qualification executable.++**Verdict: Meaningful progression.** The uncertainty-reduction bottleneck is+removed for the tested analytic field families, and the actual compiler/CLI can+use tight numerical intervals. The next blocker is precisely the final-body+field qualification seam: `RuntimeRootIsExportedPrimitive` currently admits+qualified primitives, while imported trimmed BReps lack a qualified occupancy+field. Extending those lowerers/queries is required before making SDF the general+volume check for CTC-01 or every edited engineering body. This pass establishes+the integrator's viability without bypassing that correctness boundary.diff --git a/docs/public/reference/language/checks.md b/docs/public/reference/language/checks.mdindex 77739503..e7b87345 100644--- a/docs/public/reference/language/checks.md+++ b/docs/public/reference/language/checks.md@@ -129,6 +129,21 @@ for stock before holes or edits is insufficient. STEP imports without such afield report volume unavailable; display meshes and sampled point-cloud fieldsdo not silently become volume authority.+The integrator bounds partially occupied cells using analytic local field envelopes+and plane/box volume integrals. Curvature contributes to the uncertainty; it is not+estimated from a few sample points. Cells crossing unresolved CSG branches, primitive+singularities or unsupported envelope branches retain conservative whole-cell bounds+and subdivide. Thin features cannot disappear merely because their cell corners are+outside. JSON `affineCutRegions` and `intervalFallbackRegions` count visited cells+using each approach, including parents subsequently refined.++These numerical bounds depend on the supported field interval/envelope contract and+finite enclosing bounds. They include floating-point guards, rather than formally+outward-rounded interval arithmetic. They bound occupied volume, not surface-distance+error or manufacturing tolerance.+Cones below the scalar evaluator's supported local generator scale reject bounded+measurement with `sdf-volume-cone-scale-unsupported`; rescale the analytic definition.+SDF integration may be substantially more expensive and less precise than anavailable exact formula. Use the returned interval and `budgetExhausted`, ratherthan treating the midpoint as an exact value. Mesh export integrity remains adiff --git a/fixtures/Regression/Assertions/sphere-tight.firmament b/fixtures/Regression/Assertions/sphere-tight.firmamentnew file mode 100644index 00000000..9f72820a--- /dev/null+++ b/fixtures/Regression/Assertions/sphere-tight.firmament@@ -0,0 +1,6 @@+Model TightVolumeSphere {+ units: mm+ Sphere Body { radius: 10mm }+ Assert Volume Body { expected: 4188.8mm^3; tolerance: 4mm^3 }+ Assert Topology Body { shells: 1 }+}diff --git a/tools/Aetheris.SdfVolumeQualification/Aetheris.SdfVolumeQualification.csproj b/tools/Aetheris.SdfVolumeQualification/Aetheris.SdfVolumeQualification.csprojnew file mode 100644index 00000000..4df3ea0f--- /dev/null+++ b/tools/Aetheris.SdfVolumeQualification/Aetheris.SdfVolumeQualification.csproj@@ -0,0 +1,10 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <OutputType>Exe</OutputType>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <IsPackable>false</IsPackable>+ </PropertyGroup>+ <ItemGroup><ProjectReference Include="../../Aetheris.Continuum/Aetheris.Continuum.csproj" /></ItemGroup>+</Project>diff --git a/tools/Aetheris.SdfVolumeQualification/IntervalOnlyControl.cs b/tools/Aetheris.SdfVolumeQualification/IntervalOnlyControl.csnew file mode 100644index 00000000..23caedfd--- /dev/null+++ b/tools/Aetheris.SdfVolumeQualification/IntervalOnlyControl.cs@@ -0,0 +1,84 @@+using Aetheris.Continuum.Backends.Sdf;+using Aetheris.Kernel.Core.Math;++// Frozen interval-only control from e1310ce2. Qualification only; never production dispatch.+internal static class IntervalOnlyControl+{+ public static SdfBoundedVolumeResult EstimateBounded(SdfTape tape, SdfBounds bounds, double absoluteError,+ int maximumRegions = 100_001, int maximumDepth = 30)+ {+ ArgumentNullException.ThrowIfNull(tape);+ var enclosingVolume = RegionVolume(bounds);+ if (!double.IsFinite(absoluteError) || absoluteError < 0 || maximumRegions < 1 || maximumDepth < 0+ || !double.IsFinite(enclosingVolume) || enclosingVolume <= 0+ || bounds.SizeX <= 0 || bounds.SizeY <= 0 || bounds.SizeZ <= 0)+ throw new ArgumentException("Bounded volume requires finite positive bounds, a nonnegative error and a positive region budget.");+ var queue = new PriorityQueue<(SdfBounds Region, int Depth), (double Volume, int Order)>();+ double inside = 0, uncertain = 0;+ var visited = 0;+ var padding = 1e-12 * Math.Max(1, new[] { bounds.Min.X, bounds.Min.Y, bounds.Min.Z, bounds.Max.X, bounds.Max.Y, bounds.Max.Z }.Max(Math.Abs));+ void Admit(SdfBounds region, int depth)+ {+ var interval = tape.EvaluateInterval(region);+ var volume = RegionVolume(region);+ visited++;+ if (!double.IsFinite(interval.MinValue) || !double.IsFinite(interval.MaxValue) || interval.MinValue > interval.MaxValue)+ throw new InvalidOperationException("sdf-volume-interval-invalid: The field returned no finite conservative interval.");+ if (interval.MaxValue < -padding) inside += volume;+ else if (interval.MinValue <= padding)+ {+ uncertain += volume;+ if (depth < maximumDepth) queue.Enqueue((region, depth), (-volume, visited));+ }+ }+ Admit(bounds, 0);+ while (uncertain > 2 * absoluteError && queue.Count > 0 && visited + 2 <= maximumRegions)+ {+ var item = queue.Dequeue();+ uncertain -= RegionVolume(item.Region);+ foreach (var child in SplitLongestAxis(item.Region)) Admit(child, item.Depth + 1);+ }+ var roundoff = enclosingVolume * 1e-12;+ var lower = Math.Max(0, inside - roundoff);+ var upper = Math.Min(enclosingVolume, inside + Math.Max(0, uncertain) + roundoff);+ return new(lower, upper, visited, upper - lower > 2 * absoluteError);+ }++ private static double RegionVolume(SdfBounds region) => double.Max(region.SizeX, 0d) * double.Max(region.SizeY, 0d) * double.Max(region.SizeZ, 0d);++ private static IReadOnlyList<SdfBounds> SplitLongestAxis(SdfBounds region)+ {+ var sizeX = region.SizeX;+ var sizeY = region.SizeY;+ var sizeZ = region.SizeZ;++ if (sizeX >= sizeY && sizeX >= sizeZ)+ {+ var mid = (region.Min.X + region.Max.X) * 0.5d;+ return+ [+ new SdfBounds(region.Min, new Point3D(mid, region.Max.Y, region.Max.Z)),+ new SdfBounds(new Point3D(mid, region.Min.Y, region.Min.Z), region.Max),+ ];+ }++ if (sizeY >= sizeX && sizeY >= sizeZ)+ {+ var mid = (region.Min.Y + region.Max.Y) * 0.5d;+ return+ [+ new SdfBounds(region.Min, new Point3D(region.Max.X, mid, region.Max.Z)),+ new SdfBounds(new Point3D(region.Min.X, mid, region.Min.Z), region.Max),+ ];+ }++ var midZ = (region.Min.Z + region.Max.Z) * 0.5d;+ return+ [+ new SdfBounds(region.Min, new Point3D(region.Max.X, region.Max.Y, midZ)),+ new SdfBounds(new Point3D(region.Min.X, region.Min.Y, midZ), region.Max),+ ];+ }++}+diff --git a/tools/Aetheris.SdfVolumeQualification/Program.cs b/tools/Aetheris.SdfVolumeQualification/Program.csnew file mode 100644index 00000000..090f9154--- /dev/null+++ b/tools/Aetheris.SdfVolumeQualification/Program.cs@@ -0,0 +1,65 @@+using System.Diagnostics;+using System.Text.Json;+using Aetheris.Continuum.Backends.Sdf;+using Aetheris.Kernel.Core.Math;++var budget = args.Length > 0 ? int.Parse(args[0]) : 100001;+var relativeError = args.Length > 1 ? double.Parse(args[1], System.Globalization.CultureInfo.InvariantCulture) : .001;+var repetitions = args.Length > 2 ? int.Parse(args[2]) : 3;+if (budget < 1 || !double.IsFinite(relativeError) || relativeError <= 0 || repetitions < 1)+ throw new ArgumentException("Expected positive region budget, relative error and repetition count.");+var cases = new List<(string Name, SdfNode Node, double Expected)>();+cases.Add(("sphere", new SdfSphereNode(10), 4 * Math.PI * 1000 / 3));+cases.Add(("scaled-rotated-translated-sphere", new SdfTransformNode(new SdfSphereNode(10),+ Transform3D.CreateScale(new Vector3D(2, .5, 1.5)) * Transform3D.CreateRotationY(.37) * Transform3D.CreateTranslation(new(53, -21, 12))), 4 * Math.PI * 1000 / 3 * 1.5));+cases.Add(("cylinder", new SdfCylinderNode(5, 20), Math.PI * 25 * 20));+cases.Add(("frustum", new SdfConeNode(6, 2, 12), Math.PI * 12 * (36 + 12 + 4) / 3));+cases.Add(("torus", new SdfTorusNode(10, 2), 2 * Math.PI * Math.PI * 10 * 4));+SdfNode plate = new SdfBoxNode(60, 40, 6);+foreach (var x in new[] { -15, 0, 15 }) plate = new SdfSubtractNode(plate, new SdfTransformNode(new SdfCylinderNode(3, 8), Transform3D.CreateTranslation(new(x, 0, 0))));+cases.Add(("three-through-hole-plate", plate, 60 * 40 * 6 - 3 * Math.PI * 9 * 6));+var ribs = new SdfUnionNode(new SdfBoxNode(40, 30, 4), new SdfUnionNode(+ new SdfTransformNode(new SdfBoxNode(24, 3, 8), Transform3D.CreateTranslation(new(0, 0, 6))),+ new SdfTransformNode(new SdfBoxNode(3, 18, 8), Transform3D.CreateTranslation(new(0, 0, 6)))));+cases.Add(("crossed-ribs", ribs, 40 * 30 * 4 + 8 * (24 * 3 + 3 * 18 - 3 * 3)));+cases.Add(("thin-sphere-shell", new SdfSubtractNode(new SdfSphereNode(10), new SdfSphereNode(9.5)), 4 * Math.PI * (1000 - Math.Pow(9.5, 3)) / 3));+var left = new SdfTransformNode(new SdfSphereNode(5), Transform3D.CreateTranslation(new(-3, 0, 0)));+var right = new SdfTransformNode(new SdfSphereNode(5), Transform3D.CreateTranslation(new(3, 0, 0)));+var lens = Math.PI * (20 + 6) * 16 / 12;+cases.Add(("sphere-union", new SdfUnionNode(left, right), 2 * 4 * Math.PI * 125 / 3 - lens));+cases.Add(("sphere-intersection", new SdfIntersectNode(left, right), lens));+var results = new List<object>();+var success = true;+foreach (var item in cases)+{+ var tape = SdfTapeLowerer.Lower(item.Node);+ var error = item.Expected * relativeError;+ SdfBoundedVolumeResult Run(bool control) => control+ ? IntervalOnlyControl.EstimateBounded(tape, item.Node.Bounds, error, budget)+ : SdfAdaptiveVolumeEstimator.EstimateBounded(tape, item.Node.Bounds, error, budget);+ // Full-workload warmup for each path. Alternate timed order to reduce drift.+ _ = Run(true); _ = Run(false);+ var measurements = new List<(bool Control, double Milliseconds, long AllocatedBytes, SdfBoundedVolumeResult Result)>();+ for (var repeat = 0; repeat < repetitions; repeat++)+ foreach (var control in repeat % 2 == 0 ? new[] { true, false } : new[] { false, true })+ {+ var allocated = GC.GetAllocatedBytesForCurrentThread();+ var watch = Stopwatch.StartNew(); var measured = Run(control); watch.Stop();+ measurements.Add((control, watch.Elapsed.TotalMilliseconds, GC.GetAllocatedBytesForCurrentThread() - allocated, measured));+ success &= measured.LowerBound <= item.Expected && item.Expected <= measured.UpperBound;+ }+ object Summarize(bool control)+ {+ var runs = measurements.Where(m => m.Control == control).OrderBy(m => m.Milliseconds).ToArray();+ var result = runs[runs.Length / 2].Result;+ return new { result.LowerBound, result.UpperBound, result.EstimatedVolume, result.ErrorBound,+ result.RegionsVisited, result.BudgetExhausted, result.AffineCutRegions, result.IntervalFallbackRegions,+ MedianMilliseconds = runs[runs.Length / 2].Milliseconds,+ AllocatedBytes = runs[runs.Length / 2].AllocatedBytes,+ ReferenceContained = result.LowerBound <= item.Expected && item.Expected <= result.UpperBound };+ }+ results.Add(new { item.Name, ExpectedMm3 = item.Expected, RequestedErrorMm3 = item.Expected * relativeError,+ IntervalOnly = Summarize(true), Affine = Summarize(false) });+}+Console.WriteLine(JsonSerializer.Serialize(new { budget, relativeError, repetitions, ControlRevision = "e1310ce2", success, results }, new JsonSerializerOptions { WriteIndented = true }));+return success ? 0 : 1;diff --git a/tools/Aetheris.SdfVolumeQualification/README.md b/tools/Aetheris.SdfVolumeQualification/README.mdnew file mode 100644index 00000000..1b66be0f--- /dev/null+++ b/tools/Aetheris.SdfVolumeQualification/README.md@@ -0,0 +1,28 @@+# SDF occupied-volume qualification++Exercises the public bounded estimator on ten independent analytic volume references:+primitives, a nonuniformly transformed sphere, through holes, intersecting ribs,+a thin shell, and overlapping-sphere union/intersection. Expected volumes set the+requested absolute uncertainty and check containment; the estimator receives no+reference volume or primitive-specific volume formula.++The standard probe requests 0.1%; use `.0001` for a 0.01% precision-limit probe.+An honest exhausted result is expected on some of the harder cases at that target.++```powershell+dotnet build tools/Aetheris.SdfVolumeQualification -c Release -m:1 -nr:false -p:UseSharedCompilation=false+$env:DOTNET_TieredCompilation = '0'+dotnet tools/Aetheris.SdfVolumeQualification/bin/Release/net10.0/Aetheris.SdfVolumeQualification.dll 1000001 .001 3 > artifacts/local/sdf-volume/qualification.json+Remove-Item Env:DOTNET_TieredCompilation+```++Arguments are maximum visited regions, relative uncertainty and timed repetitions.+Both paths receive a full-workload warmup, followed by alternating execution order;+JSON reports median elapsed time and managed allocations for that run. Timing is+evidence, not a portable performance assertion. Exit code 1 means a computed interval+excluded its reference. `BudgetExhausted` is reported separately: an inconclusive+enclosure is not silently counted as meeting the requested uncertainty.++`IntervalOnlyControl.cs` freezes the former production estimator from `e1310ce2`+for a controlled comparison with identical tape intervals, bounds, error and budget.+It is executable qualification evidence, not another selectable production strategy.