Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add retained spline supports for fitted garment authoring
Yuechen Li2b3abbbf893a
diff --git a/Aetheris.Kernel.Firmament.Tests/GarmentSplineAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/GarmentSplineAuthoringTests.csnew file mode 100644index 00000000..4b01ea84--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/GarmentSplineAuthoringTests.cs@@ -0,0 +1,86 @@+using System.Numerics;+using Aetheris.Cloth3D;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.Garment;+using Aetheris.Surfacing;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class GarmentSplineAuthoringTests+{+ [Fact]+ public void EditableSplineRoundTripsAndLowersToWeldedStressFreeQuads()+ {+ var body = HumanoidPoseAuthoringTests.Body();+ var fit = GarmentSplineAuthoring.FitTubeTop(new("tube"), body);+ var garment = GarmentSplineAuthoring.Lower(fit.Source, new());+ var restored = GarmentSplineAuthoring.Lower(GarmentSplineAuthoring.ParseSource(+ GarmentSplineAuthoring.SerializeSource(fit.Source)), new());+ Assert.Equal(garment.SourceHash, restored.SourceHash);+ Assert.Equal(garment.Cloth.ContentKey, restored.Cloth.ContentKey);+ Assert.True(fit.FittedRmsMm < fit.SeedRmsMm);+ var definition = garment.Cloth.Definition;+ Assert.Equal(624, definition.Positions.Length);+ Assert.Equal(576, definition.Surface!.Quads.Length);+ Assert.Equal(48, definition.Pins.Length);+ Assert.Equal(ClothSurfaceRest3D.FittedSurface, definition.Surface.Rest);+ Assert.Equal(new[] { 47, 0, 48, 95 }, definition.Surface.Quads[47].Vertices);+ Assert.All(garment.Cloth.Constraints, constraint => Assert.InRange(+ Math.Abs(ClothSurfaceMechanics3D.Evaluate(constraint, definition.Positions).Residual), 0, .0001f));+ using var solver = new ClothSolver3D(garment.Cloth);+ var options = new ClothStepOptions3D { Gravity = new(0, 0, -9.81f), Substeps = 2, Iterations = 4 };+ solver.Step(options, new());+ var retained = ClothGarmentArtifact3D.Parse(garment.Artifact(solver.Capture()));+ using var resumed = retained.CreateSolver();+ solver.Step(options, new());+ resumed.Step(options, new());+ Assert.True(solver.Capture().Positions.SequenceEqual(resumed.Capture().Positions));+ Assert.True(solver.Capture().Velocities.SequenceEqual(resumed.Capture().Velocities));+ }++ [Fact]+ public void LocalControlEditChangesOnlyItsSupportAndRetainsSeams()+ {+ var source = GarmentSplineAuthoring.FitTubeTop(new("editable"), HumanoidPoseAuthoringTests.Body()).Source;+ var controls = source.Patches[0].Surface.ControlPoints.Select(row => row.ToArray()).ToArray();+ controls[3][1] += new Vector3D(0, 8, 0);+ var editedPatch = source.Patches[0] with+ {+ Surface = BSplineControlNetFitting.Copy(source.Patches[0].Surface, controls),+ };+ var edited = source with { Patches = new[] { editedPatch, source.Patches[1] } };+ var before = GarmentSplineAuthoring.Lower(source, new());+ var after = GarmentSplineAuthoring.Lower(edited, new());+ Assert.NotEqual(before.SourceHash, after.SourceHash);+ Assert.NotEqual(before.Cloth.ContentKey, after.Cloth.ContentKey);+ Assert.NotEqual(source.Patches[0].Surface.Evaluate(.5, .4), edited.Patches[0].Surface.Evaluate(.5, .4));+ Assert.Equal(source.Patches[1].Surface.Evaluate(.5, .4), edited.Patches[1].Surface.Evaluate(.5, .4));+ Assert.Equal(before.Cloth.Definition.Positions.Skip(24).Take(24), after.Cloth.Definition.Positions.Skip(24).Take(24));+ }++ [Fact]+ public void BreakingASharedBoundaryFailsBeforeMeshCompilation()+ {+ var source = GarmentSplineAuthoring.FitTubeTop(new("bad-seam"), HumanoidPoseAuthoringTests.Body()).Source;+ var controls = source.Patches[0].Surface.ControlPoints.Select(row => row.ToArray()).ToArray();+ controls[0][0] += new Vector3D(1, 0, 0);+ var edited = source with+ {+ Patches = new[] { source.Patches[0] with+ { Surface = BSplineControlNetFitting.Copy(source.Patches[0].Surface, controls) }, source.Patches[1] },+ };+ Assert.StartsWith("garment-spline-seam:", Assert.Throws<ArgumentException>(() =>+ GarmentSplineAuthoring.Lower(edited, new())).Message);+ }++ [Theory]+ [InlineData(47, .08f)]+ [InlineData(48, float.NaN)]+ [InlineData(48, .3f)]+ public void InvalidGuideDefinitionsHaveNamedDiagnostics(int columns, float underarmDrop)+ {+ Assert.StartsWith("garment-spline-guides:", Assert.Throws<ArgumentException>(() =>+ GarmentSplineAuthoring.FitTubeTop(new("invalid", Columns: columns, UnderarmDrop: underarmDrop),+ HumanoidPoseAuthoringTests.Body())).Message);+ }+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentSplineAuthoring.cs b/Aetheris.Kernel.Firmament/Garment/GarmentSplineAuthoring.csnew file mode 100644index 00000000..787acf13--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentSplineAuthoring.cs@@ -0,0 +1,275 @@+using System.Collections.Immutable;+using System.Numerics;+using System.Security.Cryptography;+using System.Text;+using System.Text.Json;+using Aetheris.Cloth3D;+using Aetheris.Humanoid;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Surfacing;++namespace Aetheris.Kernel.Firmament.Garment;++/// <summary>Metre dimensions; guides identify body section heights, not garment vertices.+/// This bounded experiment authors two shared-boundary bicubic midsurfaces.</summary>+public sealed record GarmentTubeTopSurface(string Id, float UpperHeight = 1.38f, float LowerHeight = 1.10f,+ float Ease = .025f, int Columns = 48, int Rows = 13, float ChestHeight = 1.28f, float HipHeight = .96f,+ float UnderarmDrop = .08f);++/// <summary>Retained editable source. Controls and kernel supports are millimetres.+/// Shared control IDs express positional continuity; tangent continuity is not assumed.</summary>+public sealed record GarmentSplineSource(GarmentTubeTopSurface Guides, HumanoidFigureFit Figure,+ IReadOnlyList<SplineFitPatch> Patches);++public sealed record GarmentSplineFit(GarmentSplineSource Source, double SeedRmsMm, double FittedRmsMm,+ double MaximumTargetErrorMm, int TargetCount);++public sealed record GarmentSplineClearance(double MinimumMm, double MaximumMm, int SampleCount,+ int WorstPatch, double WorstU, double WorstV);++public sealed record CompiledSplineGarment(GarmentSplineSource Source, string SourceHash, CompiledCloth3D Cloth)+{+ public string Artifact(ClothSnapshot3D? settled = null)+ {+ if (settled is not null)+ {+ ClothState3D.ValidateSnapshot(Cloth, settled);+ }+ return JsonSerializer.Serialize(new+ {+ schema = "aetheris.garment.v1", units = "m", upAxis = "Z", sourceHash = SourceHash,+ sourceIdentity = "spline/tube-top/" + Source.Guides.Id, source = Source,+ contentKey = Cloth.ContentKey, definition = Cloth.Definition, settled,+ }, GarmentSplineAuthoring.JsonOptions);+ }++ public string Obj(ClothSnapshot3D? snapshot = null)+ {+ if (snapshot is not null)+ {+ ClothState3D.ValidateSnapshot(Cloth, snapshot);+ }+ var result = new StringBuilder("# Aetheris spline-lowered quads; metres; Z up\n");+ foreach (var point in snapshot?.Positions ?? Cloth.Definition.Positions)+ {+ result.AppendLine(FormattableString.Invariant($"v {point.X:R} {point.Y:R} {point.Z:R}"));+ }+ foreach (var quad in Cloth.Definition.Surface!.Quads)+ {+ result.AppendLine("f " + string.Join(" ", quad.Vertices.Select(index => index + 1)));+ }+ return result.ToString();+ }+}++public static class GarmentSplineAuthoring+{+ internal static readonly JsonSerializerOptions JsonOptions = new() { IncludeFields = true, WriteIndented = true };++ public static GarmentSplineFit FitTubeTop(GarmentTubeTopSurface guides, HumanoidGameplayBody body)+ {+ Validate(guides);+ var figure = HumanoidFigureFitting.Measure(body, guides.ChestHeight * 1000, guides.HipHeight * 1000);+ var chest = body.Skeleton.Joints.Single(joint => joint.Kind == HumanoidJointKind.Chest).GlobalBind;+ var center = new Point3D(chest.M41, chest.M42, chest.M43);+ var contours = Enumerable.Range(0, 13).Select(row => HumanoidFigureFitting.Contour(body,+ 1000 * (guides.UpperHeight + (guides.LowerHeight - guides.UpperHeight) * row / 12d), center)).ToArray();+ var shared = new Point3D[12, 4];+ for (int column = 0; column < 12; column++)+ {+ for (int row = 0; row < 4; row++)+ {+ shared[column, row] = Target(row / 3d, Math.PI - 2 * Math.PI * column / 12);+ }+ }+ var patches = new List<SplineFitPatch>();+ var samples = new List<SplineFitSample>();+ double squaredSeed = 0;+ for (int patch = 0; patch < 2; patch++)+ {+ var controls = new List<IReadOnlyList<Point3D>>();+ var ids = new List<int>();+ for (int column = 0; column < 7; column++)+ {+ int global = (patch * 6 + column) % 12;+ controls.Add(Enumerable.Range(0, 4).Select(row => shared[global, row]).ToArray());+ ids.AddRange(Enumerable.Range(0, 4).Select(row => global * 4 + row));+ }+ var surface = new BSplineSurfaceWithKnots(3, 3, controls, "UNSPECIFIED", false, false, false,+ [4, 1, 1, 1, 4], [4, 4], [0, .25, .5, .75, 1], [0, 1], "UNSPECIFIED");+ patches.Add(new(patch == 0 ? "front" : "back", surface, ids));+ for (int row = 0; row < contours.Length; row++)+ {+ for (int column = 0; column <= 24; column++)+ {+ double u = column / 24d;+ double v = row / 12d;+ var target = Target(v, Math.PI - Math.PI * (patch + u));+ samples.Add(new(patch, u, v, target));+ double error = (surface.Evaluate(u, v) - target).Length;+ squaredSeed += error * error;+ }+ }+ }+ var fit = BSplineControlNetFitting.Fit(patches, samples);+ return new(new(guides, figure, fit.Patches), Math.Sqrt(squaredSeed / samples.Count),+ fit.RmsError, fit.MaximumError, samples.Count);++ Point3D Target(double v, double angle)+ {+ double side = Math.Cos(angle);+ double top = guides.UpperHeight - guides.UnderarmDrop * side * side;+ double height = top * (1 - v) + guides.LowerHeight * v;+ double section = (guides.UpperHeight - height) / (guides.UpperHeight - guides.LowerHeight) * 12;+ int low = Math.Clamp((int)Math.Floor(section), 0, 11);+ double fraction = Math.Clamp(section - low, 0, 1);+ double radius = GarmentSurfaceAuthoring.Radius(contours[low].Points, center, angle) * (1 - fraction)+ + GarmentSurfaceAuthoring.Radius(contours[low + 1].Points, center, angle) * fraction + guides.Ease * 1000;+ return new(center.X + radius * Math.Cos(angle), center.Y + radius * Math.Sin(angle), height * 1000);+ }+ }++ /// <summary>Lower the retained support itself. There is no vertex projection or renderer deformation.</summary>+ public static CompiledSplineGarment Lower(GarmentSplineSource source, ClothMaterial3D material)+ {+ Validate(source.Guides);+ ValidatePatches(source.Patches);+ var guides = source.Guides;+ int half = guides.Columns / 2;+ float height = guides.UpperHeight - guides.LowerHeight;+ // Metre-valued chart scale; fitted rest derives its material metric from each physical cell.+ float circumference = (float)(source.Figure.Chest.CircumferenceMm / 1000);+ var positions = ImmutableArray.CreateBuilder<Vector3>(guides.Columns * guides.Rows);+ var coordinates = ImmutableArray.CreateBuilder<Vector2>(positions.Capacity);+ var cells = ImmutableArray.CreateBuilder<ClothQuad3D>(guides.Columns * (guides.Rows - 1));+ for (int row = 0; row < guides.Rows; row++)+ {+ float v = (float)row / (guides.Rows - 1);+ for (int column = 0; column < guides.Columns; column++)+ {+ int patch = column / half;+ double u = (column % half) / (double)half;+ positions.Add(Metres(source.Patches[patch].Surface.Evaluate(u, v)));+ coordinates.Add(new(circumference * column / guides.Columns, height * v));+ if (row == guides.Rows - 1)+ {+ continue;+ }+ int top = row * guides.Columns;+ int next = (column + 1) % guides.Columns;+ float u0 = circumference * column / guides.Columns;+ float u1 = circumference * (column + 1) / guides.Columns;+ float v0 = height * v;+ float v1 = height * (row + 1) / (guides.Rows - 1);+ cells.Add(new([top + column, top + next, top + guides.Columns + next, top + guides.Columns + column],+ [new(u0, v0), new(u1, v0), new(u1, v1), new(u0, v1)]));+ }+ }+ var surface = new ClothQuadSurface3D(cells.MoveToImmutable(), ClothSurfaceRest3D.FittedSurface);+ var definition = new ClothDefinition3D(guides.Id, positions.MoveToImmutable(), coordinates.MoveToImmutable(),+ surface.Triangulate())+ {+ Surface = surface, Material = material,+ // Explicit authoring support: this does not claim strapless cloth friction.+ Pins = Enumerable.Range((guides.Rows - 1) * guides.Columns, guides.Columns).ToImmutableArray(),+ };+ string identity = JsonSerializer.Serialize(new { source, material }, JsonOptions);+ string hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(identity)));+ return new(source, hash, definition.Compile());+ }++ public static GarmentSplineClearance Clearance(GarmentSplineSource source, IClothBodySurface3D body,+ int samplesU = 49, int samplesV = 25)+ {+ ValidatePatches(source.Patches);+ if (samplesU is < 3 or > 256 || samplesV is < 3 or > 256)+ {+ throw new ArgumentException("garment-spline-sampling: Require 3..256 samples per parameter axis.");+ }+ double minimum = double.PositiveInfinity;+ double maximum = double.NegativeInfinity;+ int worstPatch = 0;+ double worstU = 0;+ double worstV = 0;+ for (int patch = 0; patch < source.Patches.Count; patch++)+ {+ for (int row = 0; row < samplesV; row++)+ {+ for (int column = 0; column < samplesU; column++)+ {+ double u = column / (double)(samplesU - 1);+ double v = row / (double)(samplesV - 1);+ double distance = body.Query(Metres(source.Patches[patch].Surface.Evaluate(u, v))).SignedDistance * 1000;+ if (!double.IsFinite(distance))+ {+ throw new InvalidOperationException("garment-spline-clearance: Nonfinite body query.");+ }+ if (distance < minimum)+ {+ minimum = distance;+ worstPatch = patch;+ worstU = u;+ worstV = v;+ }+ maximum = Math.Max(maximum, distance);+ }+ }+ }+ return new(minimum, maximum, source.Patches.Count * samplesU * samplesV, worstPatch, worstU, worstV);+ }++ public static string SerializeSource(GarmentSplineSource source) => JsonSerializer.Serialize(source, JsonOptions);++ public static GarmentSplineSource ParseSource(string json)+ {+ var source = JsonSerializer.Deserialize<GarmentSplineSource>(json, JsonOptions)+ ?? throw new InvalidDataException("garment-spline-source: Empty source.");+ Validate(source.Guides);+ ValidatePatches(source.Patches);+ return source;+ }++ internal static Vector3 Metres(Point3D point) => new((float)(point.X / 1000), (float)(point.Y / 1000), (float)(point.Z / 1000));++ private static void Validate(GarmentTubeTopSurface guides)+ {+ ArgumentNullException.ThrowIfNull(guides);+ if (string.IsNullOrWhiteSpace(guides.Id) || guides.Columns is < 16 or > 128 || guides.Columns % 2 != 0+ || guides.Rows is < 3 or > 64 || !float.IsFinite(guides.UpperHeight) || !float.IsFinite(guides.LowerHeight)+ || guides.LowerHeight <= 0 || guides.UpperHeight <= guides.LowerHeight+ || guides.UpperHeight - guides.LowerHeight > .6f || !float.IsFinite(guides.Ease) || guides.Ease is <= 0 or > .1f+ || !float.IsFinite(guides.UnderarmDrop) || guides.UnderarmDrop < 0+ || guides.UnderarmDrop >= guides.UpperHeight - guides.LowerHeight+ || !float.IsFinite(guides.ChestHeight) || !float.IsFinite(guides.HipHeight))+ {+ throw new ArgumentException("garment-spline-guides: Require bounded, finite body guides, ease and even circumferential resolution.");+ }+ }++ private static void ValidatePatches(IReadOnlyList<SplineFitPatch> patches)+ {+ if (patches.Count != 2 || patches.Any(patch => patch.Surface.IsRational+ || patch.Surface.ControlPoints.Count != 7 || patch.Surface.ControlPoints[0].Count != 4+ || patch.Surface.DegreeU != 3 || patch.Surface.DegreeV != 3 || patch.ControlIds.Count != 28+ || patch.Surface.KnotMultiplicitiesU[0] != 4 || patch.Surface.KnotMultiplicitiesU[^1] != 4+ || patch.Surface.KnotMultiplicitiesV[0] != 4 || patch.Surface.KnotMultiplicitiesV[^1] != 4+ || patch.Surface.DomainStartU != 0 || patch.Surface.DomainEndU != 1+ || patch.Surface.DomainStartV != 0 || patch.Surface.DomainEndV != 1)+ || !patches[0].Surface.KnotValuesV.SequenceEqual(patches[1].Surface.KnotValuesV)+ || !patches[0].Surface.KnotMultiplicitiesV.SequenceEqual(patches[1].Surface.KnotMultiplicitiesV))+ {+ throw new ArgumentException("garment-spline-patches: Require two compatible 7x4 bicubic polynomial unit-domain patches.");+ }+ for (int row = 0; row < 4; row++)+ {+ if (patches[0].ControlIds[row] != patches[1].ControlIds[24 + row]+ || patches[0].ControlIds[24 + row] != patches[1].ControlIds[row]+ || patches[0].Surface.ControlPoints[0][row] != patches[1].Surface.ControlPoints[6][row]+ || patches[0].Surface.ControlPoints[6][row] != patches[1].Surface.ControlPoints[0][row])+ {+ throw new ArgumentException("garment-spline-seam: Edited side boundaries must retain shared IDs and identical controls.");+ }+ }+ }+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentSurfaceAuthoring.cs b/Aetheris.Kernel.Firmament/Garment/GarmentSurfaceAuthoring.csindex 0c2c055f..e9ce42dc 100644--- a/Aetheris.Kernel.Firmament/Garment/GarmentSurfaceAuthoring.cs+++ b/Aetheris.Kernel.Firmament/Garment/GarmentSurfaceAuthoring.cs@@ -124,7 +124,7 @@ public static class GarmentSurfaceAuthoringreturn new(source, figure, hash, definition.Compile(), waist, hem);}- private static double Radius(IReadOnlyList<Point3D> contour, Point3D center, double angle)+ internal static double Radius(IReadOnlyList<Point3D> contour, Point3D center, double angle){double dx = Math.Cos(angle);double dy = Math.Sin(angle);diff --git a/Aetheris.Modules.Tests/BSplineControlNetFittingTests.cs b/Aetheris.Modules.Tests/BSplineControlNetFittingTests.csnew file mode 100644index 00000000..5ac636b8--- /dev/null+++ b/Aetheris.Modules.Tests/BSplineControlNetFittingTests.cs@@ -0,0 +1,105 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Visualization;+using Aetheris.Surfacing;+using Xunit;++namespace Aetheris.Modules.Tests;++public sealed class BSplineControlNetFittingTests+{+ [Fact]+ public void RecoverPolynomialSupportFromIndependentSamplesDeterministically()+ {+ var expected = Surface(0);+ var seed = BSplineControlNetFitting.Copy(expected, expected.ControlPoints.Select(row =>+ (IReadOnlyList<Point3D>)row.Select(point => new Point3D(point.X + 5, point.Y - 8, point.Z + 11)).ToArray()).ToArray());+ var patch = new SplineFitPatch("patch", seed, Enumerable.Range(0, 16).ToArray());+ var samples = Samples(expected, 0);+ var options = new SplineFitOptions(SeedWeight: 1e-10, FairnessWeight: 0);+ var result = BSplineControlNetFitting.Fit([patch], samples, options);+ var repeated = BSplineControlNetFitting.Fit([patch], samples, options);+ Assert.InRange(result.MaximumError, 0, .00001);+ Assert.Equal(result.Patches[0].Surface.ControlPoints.SelectMany(row => row),+ repeated.Patches[0].Surface.ControlPoints.SelectMany(row => row));+ // Independent samples do not coincide with the fitting grid.+ Assert.InRange((result.Patches[0].Surface.Evaluate(2.73, 5.19) - expected.Evaluate(2.73, 5.19)).Length, 0, .00001);+ }++ [Fact]+ public void SharedControlsKeepTheWholeBoundaryExact()+ {+ var first = Surface(0);+ var second = Surface(60);+ var firstIds = Enumerable.Range(0, 16).ToArray();+ var secondIds = Enumerable.Range(12, 16).ToArray();+ var result = BSplineControlNetFitting.Fit(+ [new("first", first, firstIds), new("second", second, secondIds)],+ Samples(first, 0).Concat(Samples(second, 1)).ToArray());+ Assert.Equal(28, result.SharedControlCount);+ for (int index = 0; index <= 100; index++)+ {+ double v = 4 + 2 * index / 100d;+ Assert.Equal(result.Patches[0].Surface.Evaluate(3, v), result.Patches[1].Surface.Evaluate(2, v));+ }+ }++ [Fact]+ public void OpenSheetUsesExactBoundaryCurvesAndPcurvesOnNonUnitDomains()+ {+ var sheet = SurfacePatchBrepMaterializer.MaterializeSheet(Surface(0));+ Assert.Single(sheet.Topology.Faces);+ Assert.Equal(4, sheet.Topology.Edges.Count());+ Assert.True(BrepBindingValidator.Validate(sheet, true).IsSuccess);+ var evidence = BrepPcurveValidator.Validate(sheet, requireEveryCoedge: true);+ Assert.True(evidence.IsValid, string.Join("\n", evidence.Diagnostics));+ Assert.InRange(evidence.MaximumReconstructionDeviation, 0, 1e-8);+ var wire = BrepWireframeSvgRenderer.Render(sheet);+ Assert.Equal(1, wire.Evidence.FacesWithTrimmedIsolines);+ Assert.True(wire.Evidence.IsoPolylineCount > 0);+ }++ [Fact]+ public void ContradictorySharedSeedsAndOutOfDomainSamplesFailByName()+ {+ var first = new SplineFitPatch("first", Surface(0), Enumerable.Range(0, 16).ToArray());+ var second = new SplineFitPatch("second", Surface(60), Enumerable.Range(0, 16).ToArray());+ Assert.StartsWith("spline-fit-shared-control:", Assert.Throws<ArgumentException>(() =>+ BSplineControlNetFitting.Fit([first, second], Samples(first.Surface, 0))).Message);+ Assert.StartsWith("spline-fit-domain:", Assert.Throws<ArgumentException>(() =>+ BSplineControlNetFitting.Fit([first], [new(0, 1.99, 4, new(0, 0, 0))])).Message);+ }++ [Fact]+ public void RationalSupportsFailInsteadOfUsingPolynomialBasisWeights()+ {+ var polynomial = Surface(0);+ var weights = Enumerable.Range(0, 4).Select(row => (IReadOnlyList<double>)+ Enumerable.Range(0, 4).Select(column => 1 + .1 * row * column).ToArray()).ToArray();+ var rational = new BSplineSurfaceWithKnots(3, 3, polynomial.ControlPoints, "UNSPECIFIED", false, false, false,+ [4, 4], [4, 4], [2, 3], [4, 6], "UNSPECIFIED", weights);+ Assert.StartsWith("spline-fit-patch:", Assert.Throws<ArgumentException>(() => BSplineControlNetFitting.Fit(+ [new("rational", rational, Enumerable.Range(0, 16).ToArray())], Samples(rational, 0))).Message);+ Assert.StartsWith("spline-sheet-support:", Assert.Throws<ArgumentException>(() =>+ SurfacePatchBrepMaterializer.MaterializeSheet(rational)).Message);+ }++ private static BSplineSurfaceWithKnots Surface(double offset)+ {+ var controls = Enumerable.Range(0, 4).Select(row => (IReadOnlyList<Point3D>)+ Enumerable.Range(0, 4).Select(column => new Point3D(offset + row * 20, column * 15,+ column * column * 2)).ToArray()).ToArray();+ return new(3, 3, controls, "UNSPECIFIED", false, false, false, [4, 4], [4, 4], [2, 3], [4, 6], "UNSPECIFIED");+ }++ private static SplineFitSample[] Samples(BSplineSurfaceWithKnots surface, int patch)+ {+ return Enumerable.Range(0, 9).SelectMany(row => Enumerable.Range(0, 9).Select(column =>+ {+ double u = 2 + row / 8d;+ double v = 4 + column / 4d;+ return new SplineFitSample(patch, u, v, surface.Evaluate(u, v));+ })).ToArray();+ }+}diff --git a/Aetheris.Surfacing/BSplineControlNetFitting.cs b/Aetheris.Surfacing/BSplineControlNetFitting.csnew file mode 100644index 00000000..efb15188--- /dev/null+++ b/Aetheris.Surfacing/BSplineControlNetFitting.cs@@ -0,0 +1,227 @@+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Surfacing;++/// <summary>Shared IDs are exact positional constraints between polynomial patch control nets.</summary>+public sealed record SplineFitPatch(string Id, BSplineSurfaceWithKnots Surface, IReadOnlyList<int> ControlIds);+public sealed record SplineFitSample(int Patch, double U, double V, Point3D Target, double Weight = 1);+public sealed record SplineFitOptions(double SeedWeight = .000001, double FairnessWeight = .01);+public sealed record SplineFitResult(IReadOnlyList<SplineFitPatch> Patches, double RmsError, double MaximumError,+ int SharedControlCount, int SampleCount);++/// <summary>Bounded linear least squares in control positions, using the kernel evaluator for+/// basis weights. Fairness is a parameter-space authoring regularizer, not fabric mechanics.</summary>+public static class BSplineControlNetFitting+{+ public static SplineFitResult Fit(IReadOnlyList<SplineFitPatch> patches,+ IReadOnlyList<SplineFitSample> samples, SplineFitOptions? options = null)+ {+ options ??= new();+ if (patches.Count is < 1 or > 8 || samples.Count is < 1 or > 8192+ || !double.IsFinite(options.SeedWeight) || options.SeedWeight <= 0+ || !double.IsFinite(options.FairnessWeight) || options.FairnessWeight < 0)+ {+ throw new ArgumentException("spline-fit-budget: Require bounded patches/samples and finite positive seed regularization.");+ }+ var initial = new SortedDictionary<int, Point3D>();+ foreach (var patch in patches)+ {+ var surface = patch.Surface;+ int count = surface.ControlPoints.Count * surface.ControlPoints[0].Count;+ if (surface.IsRational || count > 128 || patch.ControlIds.Count != count || string.IsNullOrWhiteSpace(patch.Id))+ {+ throw new ArgumentException("spline-fit-patch: Require polynomial patches with one shared ID per control.");+ }+ int local = 0;+ foreach (var row in surface.ControlPoints)+ {+ foreach (var point in row)+ {+ int id = patch.ControlIds[local++];+ if (initial.TryGetValue(id, out var existing) && (existing - point).Length > 1e-8)+ {+ throw new ArgumentException("spline-fit-shared-control: Shared controls need identical seed positions.");+ }+ initial[id] = point;+ }+ }+ }+ if (initial.Count > 128)+ {+ throw new ArgumentException("spline-fit-controls: Maximum 128 independent controls.");+ }+ var ids = initial.Keys.ToArray();+ var indices = ids.Select((id, index) => (id, index)).ToDictionary(pair => pair.id, pair => pair.index);+ var matrix = new double[ids.Length, ids.Length];+ var rhs = new double[ids.Length, 3];+ var basis = patches.Select(patch => BasisSurfaces(patch.Surface)).ToArray();+ foreach (var sample in samples)+ {+ if (sample.Patch < 0 || sample.Patch >= patches.Count || !double.IsFinite(sample.Weight) || sample.Weight <= 0+ || !Finite(sample.Target))+ {+ throw new ArgumentException("spline-fit-sample: Invalid patch, weight or target.");+ }+ var patch = patches[sample.Patch];+ if (!double.IsFinite(sample.U) || !double.IsFinite(sample.V)+ || sample.U < patch.Surface.DomainStartU || sample.U > patch.Surface.DomainEndU+ || sample.V < patch.Surface.DomainStartV || sample.V > patch.Surface.DomainEndV)+ {+ throw new ArgumentException("spline-fit-domain: Sample lies outside the source domain.");+ }+ var weights = new double[ids.Length];+ for (int control = 0; control < patch.ControlIds.Count; control++)+ {+ weights[indices[patch.ControlIds[control]]] += basis[sample.Patch][control].Evaluate(sample.U, sample.V).X;+ }+ AddRow(weights, sample.Target, sample.Weight);+ }+ for (int index = 0; index < ids.Length; index++)+ {+ var weights = new double[ids.Length];+ weights[index] = 1;+ AddRow(weights, initial[ids[index]], options.SeedWeight);+ }+ foreach (var patch in patches)+ {+ int rows = patch.Surface.ControlPoints.Count;+ int columns = patch.Surface.ControlPoints[0].Count;+ for (int row = 0; row < rows; row++)+ {+ for (int column = 0; column < columns; column++)+ {+ if (row > 0 && row < rows - 1)+ {+ Fair((row - 1) * columns + column, row * columns + column, (row + 1) * columns + column);+ }+ if (column > 0 && column < columns - 1)+ {+ Fair(row * columns + column - 1, row * columns + column, row * columns + column + 1);+ }+ }+ }+ void Fair(int a, int b, int c)+ {+ var weights = new double[ids.Length];+ weights[indices[patch.ControlIds[a]]] += 1;+ weights[indices[patch.ControlIds[b]]] -= 2;+ weights[indices[patch.ControlIds[c]]] += 1;+ AddRow(weights, new(0, 0, 0), options.FairnessWeight);+ }+ }+ var solution = Solve(matrix, rhs);+ var fitted = patches.Select(patch => patch with+ {+ Surface = Copy(patch.Surface, Enumerable.Range(0, patch.Surface.ControlPoints.Count)+ .Select(row => (IReadOnlyList<Point3D>)Enumerable.Range(0, patch.Surface.ControlPoints[0].Count)+ .Select(column =>+ {+ int index = indices[patch.ControlIds[row * patch.Surface.ControlPoints[0].Count + column]];+ return new Point3D(solution[index, 0], solution[index, 1], solution[index, 2]);+ }).ToArray()).ToArray()),+ }).ToArray();+ double squared = 0;+ double maximum = 0;+ foreach (var sample in samples)+ {+ double error = (fitted[sample.Patch].Surface.Evaluate(sample.U, sample.V) - sample.Target).Length;+ squared += error * error;+ maximum = Math.Max(maximum, error);+ }+ return new(fitted, Math.Sqrt(squared / samples.Count), maximum, ids.Length, samples.Count);++ void AddRow(double[] weights, Point3D target, double weight)+ {+ for (int row = 0; row < ids.Length; row++)+ {+ if (weights[row] == 0)+ {+ continue;+ }+ double scaled = weights[row] * weight;+ rhs[row, 0] += scaled * target.X;+ rhs[row, 1] += scaled * target.Y;+ rhs[row, 2] += scaled * target.Z;+ for (int column = 0; column < ids.Length; column++)+ {+ matrix[row, column] += scaled * weights[column];+ }+ }+ }+ }++ public static BSplineSurfaceWithKnots Copy(BSplineSurfaceWithKnots source, IReadOnlyList<IReadOnlyList<Point3D>> controls)+ {+ return new(source.DegreeU, source.DegreeV, controls, source.SurfaceForm, source.UClosed, source.VClosed,+ source.SelfIntersect, source.KnotMultiplicitiesU, source.KnotMultiplicitiesV,+ source.KnotValuesU, source.KnotValuesV, source.KnotSpec, source.Weights);+ }++ private static BSplineSurfaceWithKnots[] BasisSurfaces(BSplineSurfaceWithKnots source)+ {+ int columns = source.ControlPoints[0].Count;+ return Enumerable.Range(0, source.ControlPoints.Count * columns).Select(active => Copy(source,+ Enumerable.Range(0, source.ControlPoints.Count).Select(row => (IReadOnlyList<Point3D>)+ Enumerable.Range(0, columns).Select(column => new Point3D(row * columns + column == active ? 1 : 0, 0, 0))+ .ToArray()).ToArray())).ToArray();+ }++ private static bool Finite(Point3D point) => double.IsFinite(point.X) && double.IsFinite(point.Y) && double.IsFinite(point.Z);++ private static double[,] Solve(double[,] matrix, double[,] rhs)+ {+ int count = matrix.GetLength(0);+ var factor = new double[count, count];+ for (int row = 0; row < count; row++)+ {+ for (int column = 0; column <= row; column++)+ {+ double value = matrix[row, column];+ for (int inner = 0; inner < column; inner++)+ {+ value -= factor[row, inner] * factor[column, inner];+ }+ if (row == column)+ {+ if (!double.IsFinite(value) || value <= 0)+ {+ throw new InvalidOperationException("spline-fit-conditioning: Normal system is not positive definite.");+ }+ factor[row, column] = Math.Sqrt(value);+ }+ else+ {+ factor[row, column] = value / factor[column, column];+ }+ }+ }+ var result = new double[count, 3];+ for (int axis = 0; axis < 3; axis++)+ {+ for (int row = 0; row < count; row++)+ {+ double value = rhs[row, axis];+ for (int inner = 0; inner < row; inner++)+ {+ value -= factor[row, inner] * result[inner, axis];+ }+ result[row, axis] = value / factor[row, row];+ }+ for (int row = count - 1; row >= 0; row--)+ {+ double value = result[row, axis];+ for (int inner = row + 1; inner < count; inner++)+ {+ value -= factor[inner, row] * result[inner, axis];+ }+ result[row, axis] = value / factor[row, row];+ if (!double.IsFinite(result[row, axis]))+ {+ throw new InvalidOperationException("spline-fit-conditioning: Nonfinite fitted control.");+ }+ }+ }+ return result;+ }+}diff --git a/Aetheris.Surfacing/SurfacePatchBrepMaterializer.cs b/Aetheris.Surfacing/SurfacePatchBrepMaterializer.csindex ab790bdd..62e84b2f 100644--- a/Aetheris.Surfacing/SurfacePatchBrepMaterializer.cs+++ b/Aetheris.Surfacing/SurfacePatchBrepMaterializer.cs@@ -8,9 +8,58 @@ using Aetheris.Kernel.Core.Topology;namespace Aetheris.Surfacing;-/// <summary>Builds a thin closed panel whose authoritative lower face is a bounded rectangular non-rational support.</summary>+/// <summary>Materializes bounded polynomial supports as open midsurfaces or thin closed CAD panels.</summary>public static class SurfacePatchBrepMaterializer{+ /// <summary>One open, exactly bound midsurface face. This is not a closed solid or+ /// a qualified STEP solid export. Clamped full-domain polynomial supports only.</summary>+ public static BrepBody MaterializeSheet(BSplineSurfaceWithKnots spline)+ {+ if (spline.IsRational || spline.KnotMultiplicitiesU[0] != spline.DegreeU + 1+ || spline.KnotMultiplicitiesU[^1] != spline.DegreeU + 1+ || spline.KnotMultiplicitiesV[0] != spline.DegreeV + 1+ || spline.KnotMultiplicitiesV[^1] != spline.DegreeV + 1)+ {+ throw new ArgumentException("spline-sheet-support: Require a clamped polynomial support.");+ }+ var builder = new TopologyBuilder();+ var corners = new[] { spline.Evaluate(spline.DomainStartU, spline.DomainStartV),+ spline.Evaluate(spline.DomainEndU, spline.DomainStartV),+ spline.Evaluate(spline.DomainEndU, spline.DomainEndV),+ spline.Evaluate(spline.DomainStartU, spline.DomainEndV) };+ var vertices = corners.Select(_ => builder.AddVertex()).ToArray();+ var edges = Enumerable.Range(0, 4).Select(index => builder.AddEdge(vertices[index], vertices[(index + 1) % 4])).ToArray();+ var loop = builder.AllocateLoopId();+ var uses = Enumerable.Range(0, 4).Select(_ => builder.AllocateCoedgeId()).ToArray();+ for (int index = 0; index < 4; index++)+ {+ builder.AddCoedge(new(uses[index], edges[index], loop, uses[(index + 1) % 4], uses[(index + 3) % 4], false));+ }+ builder.AddLoop(new Loop(loop, uses));+ var face = builder.AddFace([loop]);+ builder.AddBody([builder.AddShell([face])]);+ var geometry = new BrepGeometryStore();+ var bindings = new BrepBindingModel();+ var supportId = new SurfaceGeometryId(1);+ geometry.AddSurface(supportId, SurfaceGeometry.FromBSplineSurfaceWithKnots(spline));+ bindings.AddFaceBinding(new(face, supportId));+ var curves = Boundaries(spline);+ var uv = new SurfaceParameterPoint[] { new(spline.DomainStartU, spline.DomainStartV), new(spline.DomainEndU, spline.DomainStartV),+ new(spline.DomainEndU, spline.DomainEndV), new(spline.DomainStartU, spline.DomainEndV) };+ for (int index = 0; index < 4; index++)+ {+ var curve = curves[index];+ var id = new CurveGeometryId(index + 1);+ var interval = new ParameterInterval(curve.DomainStart, curve.DomainEnd);+ geometry.AddCurve(id, CurveGeometry.FromBSpline(curve));+ bindings.AddEdgeBinding(new(edges[index], id, interval));+ bindings.AddPcurveBinding(new(uses[index], face, supportId,+ PcurveGeometry.Line(interval, uv[index], uv[(index + 1) % 4])));+ }+ return new(builder.Model, geometry, bindings, vertices.Select((id, index) => (id, index))+ .ToDictionary(pair => pair.id, pair => corners[pair.index]));+ }+public static (BrepBody? Body,IReadOnlyList<SurfacingDiagnostic> Diagnostics) Materialize(SurfaceGeometry support,Func<double,double,Point3D> evaluate,double thickness=1d){diff --git a/docs/public/firmament/garment-spline-experiment.md b/docs/public/firmament/garment-spline-experiment.mdnew file mode 100644index 00000000..cf322755--- /dev/null+++ b/docs/public/firmament/garment-spline-experiment.md@@ -0,0 +1,161 @@+# Body-fitted spline garment experiment++This bounded experiment authors a tube top as two editable bicubic B-spline+midsurfaces fitted to the actual Anatolia gameplay body. The retained control+nets own the shape. Structured quads sample those supports directly, then enter+the existing cloth solver and `aetheris.garment.v1` runtime artifact path.+Blender only presents exported geometry. No commercial reference geometry is+used or shipped.++The typed API lives in Firmament's garment authoring owner. Like the preceding+surface skirt experiment, this pass does not introduce document syntax. These+proven contracts should inform a future `schema Garment` Surface declaration;+the C# guide records are not claimed to be erased Firmament Concept Structs.++```csharp+var body = HumanoidGameplayBody.Load("antonia.gameplay-body.json");+var fitting = GarmentSplineAuthoring.FitTubeTop(+ new GarmentTubeTopSurface("tube-top", UnderarmDrop: .08f), body);+var source = fitting.Source;+var garment = GarmentSplineAuthoring.Lower(source, new ClothMaterial3D+{+ WarpCompliance = .001f,+ WeftCompliance = .004f,+ DiagonalCompliance = .002f,+ BendCompliance = .01f,+});+File.WriteAllText("source.json", GarmentSplineAuthoring.SerializeSource(source));+File.WriteAllText("tube-top.garment.json", garment.Artifact());+```++## Source, fitting and inspection++Guides declare upper/lower heights, ease and underarm drop in metres. These+defaults describe this Anatolia specimen, not universal anatomical landmarks.+The fitting owner uses the existing closed torso-section query at 13 heights,+interpolates radial envelopes between sections and samples targets for a shaped+upper edge. The underarm height varies with squared side direction. It lowers+the edge at the sides while retaining front/back coverage.++`BSplineControlNetFitting` is a bounded, polynomial shared-control least-squares+fit in Aetheris.Surfacing. Kernel evaluation supplies basis weights. Seed+regularization makes the bounded linear system positive definite; control-net+second differences regularize shape in parameter space. This authoring penalty+is not a cloth stiffness model. The fitter rejects rational supports, invalid+samples, inconsistent shared seeds and exceeded budgets with named diagnostics.+It neither guesses the body geometry nor performs cloth simulation.++Two 7x4 control nets share their side control columns: 56 logical controls,+48 independent positions. This gives exact positional side continuity, not a+tangent-continuity certificate. Source edits must preserve shared boundary IDs+and positions. The tests edit a front interior control with an 8 mm displacement,+verify changed source/mesh identity and unchanged back support, and reject a+broken side boundary before lowering. Sources round-trip with identical hashes+and compiled cloth keys. Geometry, material and body provenance enter identity;+machine paths and commercial assets do not.++`SurfacePatchBrepMaterializer.MaterializeSheet` retains each support as a single+open BRep face with exact four boundary curves and pcurves. The existing binding,+pcurve and wireframe owners validate and inspect it. It is not a closed CAD+solid and no STEP solid-export claim is made.++The runner exports `front-support.svg`, `back-support.svg`, `control-cage.obj`+and `clearance.svg` alongside the source and meshes. Clearance uses 2,450+independent nearest-triangle queries on the actual spline supports. The SVG+locates samples in each parameter chart and marks clearance below 5 mm in red,+5..10 mm in amber and at least 10 mm in green. It is sampled feedback, not a+global intersection certificate. Control-cage rendering presents source+positions; the cage is not the garment mesh and is not simulated.++## Quad material path and measured result++The garment has 624 vertices, 576 welded material quads and 48 explicit+lower-band attachments. Cells have metre-valued material coordinates and+`FittedSurface` rest. Unit spline parameters are never treated as textile+metres. The existing Q1 membrane and rest-angle bending operators own mechanics;+display triangles do not become diagonal structural springs.++The motivating level-upper-edge specimen remains an intentional failure:+minimum sampled clearance was **-36.22 mm**, and frame-eight maximum stretch+was **46.30%**. Contact response pushed its back edge outward. Giving the source+an explicit 80 mm underarm drop fixed the geometrical conflict without changing+acceptance limits or projecting simulation vertices out of the body.++For the accepted specimen, seed RMS target error fell from **26.38 to 3.66 mm**+(maximum target error 17.25 mm). Independent clearance was **6.71..32.10 mm**.+All four eight-frame checkpoints in the 32-frame gravity run were finite,+with maximum tensile stretch at most **4.32%**, zero attachment error and zero+sampled body-clearance violation. Maximum frame-32 displacement was 20.61 mm.+Eight zero-gravity frames drifted by 0.00126 mm. Source reload, solver checkpoint+rewind and settled runtime-artifact continuation reproduced exactly.++Aurelian's existing `ClothAgentDefinition3D.FromGarment` imports the actual+settled artifact and converts it to Y-up world state. The extended native+`--cloth-systems --garment` probe runs this 624-vertex garment through both CPU+and Vulkan solvers for eight additional gravity steps. On the local RTX 3070,+maximum CPU/GPU position difference was **0.00289 mm**, with exact same-device+rewind. This GPU probe has no body contact; the 32-frame body-contact experiment+uses the existing CPU body surface. The agent retains its existing material+assignment API for Aurelian presentation.++## Reproduce++```powershell+dotnet run -c Release scripts/experiment-garment-spline.cs -- `+ artifacts/local/humanoid-production/antonia.gameplay-body.json `+ artifacts/local/garment/spline-tube-top++& 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe' `+ --background --python scripts/render-garment.py -- `+ --garment spline-tube-top --input-dir artifacts/local/garment/spline-tube-top `+ --torso --engine workbench++# Inspect the retained rest and its source cage before simulation.+& 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe' `+ --background --python scripts/render-garment.py -- `+ --garment spline-tube-top --input-dir artifacts/local/garment/spline-tube-top `+ --initial --control-cage artifacts/local/garment/spline-tube-top/control-cage.obj `+ --torso --engine workbench+```++An optional third runner argument loads `GarmentTubeTopSurface` JSON guides.+For the invalid control specimen, use `{"Id":"level-edge","UnderarmDrop":0}`+and a separate output directory. It deliberately returns a nonzero status.+All generated output belongs under ignored `artifacts/local/`; the body input+is a local prerequisite. Renderer evidence hashes every imported OBJ.++From Copeland:++```powershell+dotnet run --project tools/Aurelian.GraphicsProof -c Release -- `+ --cloth-systems --garment `+ ../Aetheris/artifacts/local/garment/spline-tube-top/garment.json `+ --output artifacts/local/garment-spline-gpu+```++## Qualification boundaries++This establishes editable spline fitting, open BRep inspection, quad lowering,+stationary-body simulation and real runtime/GPU consumption. The cloth response+is an experimental fitted-rest model, not calibrated textile behavior. The+lower-band pins are permanent authored support; strapless friction is absent.+The paired supports are position-continuous, and side creases remain visible.+Animated bodies, quad self-contact, inversion barriers, free strapless support,+flat sewing-pattern recovery, automatic flattening and general garment fitting+are unqualified. This experiment does not certify the earlier panel dress.++Eleven new regression cases cover independent polynomial recovery, deterministic+fitting, exact shared boundaries, non-unit-domain BRep reconstruction, rational+and invalid sample rejection, garment source reload, local control edits,+broken seams, welded topology and runtime continuation. Full solution gate+results are recorded in the experiment's local build/test logs.++The Aetheris Release solution build and full configured solution suite passed+**4,543 tests**, including all eleven new cases, with serial collection settings.+The test-generated STEP specimen was restored after validation.++The Aurelian Release solution build and full 1,220-test consumer suite passed.+The browser shader lane used the already installed Naga selected through+`AURELIAN_NAGA`; an initial run without that setting failed to locate Naga.+The native cloth proof passed through the real compiled Visual TypeScript+shader on the RTX 3070.diff --git a/docs/public/firmament/garment-surface-experiment.md b/docs/public/firmament/garment-surface-experiment.mdindex 9f1e3a4c..4e128e81 100644--- a/docs/public/firmament/garment-surface-experiment.md+++ b/docs/public/firmament/garment-surface-experiment.md@@ -109,8 +109,10 @@ Animated legs, quad self-contact, inversion prevention, friction and calibratedmaterial response need separate qualification. Degenerate runtime hinges skiptheir bending update; there is no barrier preventing collapsed/inverted cells.The bend diagnostic is a sum of squared angular residuals, not physical energy.-The next bounded authoring step is explicit surface cuts and flattening with-distortion reports, followed by animated-body validation. A Firmament Surface+The [spline tube-top follow-up](garment-spline-experiment.md) adds retained+editable supports and fit feedback before quad lowering. Explicit surface cuts,+flattening with distortion reports and animated-body validation remain future+experiments. A Firmament Surfacedeclaration should be designed around these proven typed contracts rather thansilently treating fitted rest as flat fabric.diff --git a/docs/public/firmament/garments.md b/docs/public/firmament/garments.mdindex 5e0fdc68..31e63c91 100644--- a/docs/public/firmament/garments.md+++ b/docs/public/firmament/garments.md@@ -467,3 +467,8 @@ typed body-contour authoring, explicit flat/fitted rest conventions and theshared CPU/Vulkan quad material path. The stationary skirt is qualifiedseparately from the earlier panel dress; flattening and animated-body fit remainfuture experiments.++See [the body-fitted spline tube-top experiment](garment-spline-experiment.md)+for retained editable bicubic supports, exact open-sheet BRep inspection,+control-cage and clearance feedback, quad lowering and actual Aurelian/Vulkan+artifact consumption.diff --git a/scripts/experiment-garment-spline.cs b/scripts/experiment-garment-spline.csnew file mode 100644index 00000000..053d11d4--- /dev/null+++ b/scripts/experiment-garment-spline.cs@@ -0,0 +1,177 @@+#:project ../Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj+#:property PublishAot=false+#:property JsonSerializerIsReflectionEnabledByDefault=true+using System.Diagnostics;+using System.Numerics;+using System.Text;+using System.Text.Json;+using Aetheris.Cloth3D;+using Aetheris.Humanoid;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Visualization;+using Aetheris.Kernel.Firmament.Garment;+using Aetheris.Surfacing;++if (args.Length is < 2 or > 3)+{+ throw new ArgumentException("dotnet run -c Release scripts/experiment-garment-spline.cs -- body.json output-directory [guides.json]");+}+var body = HumanoidGameplayBody.Load(Path.GetFullPath(args[0]));+string output = Path.GetFullPath(args[1]);+Directory.CreateDirectory(output);+var json = new JsonSerializerOptions { IncludeFields = true, WriteIndented = true };+var watch = Stopwatch.StartNew();+var guides = args.Length == 3+ ? JsonSerializer.Deserialize<GarmentTubeTopSurface>(File.ReadAllText(args[2]), json)+ ?? throw new InvalidDataException("Empty tube-top guides.")+ : new GarmentTubeTopSurface("spline-tube-top");+var fit = GarmentSplineAuthoring.FitTubeTop(guides, body);+Console.Error.WriteLine($"Spline fitting: seed RMS {fit.SeedRmsMm:F2} -> {fit.FittedRmsMm:F2} mm, max {fit.MaximumTargetErrorMm:F2} mm");+var material = new ClothMaterial3D+{+ WarpCompliance = .001f, WeftCompliance = .004f, DiagonalCompliance = .002f, BendCompliance = .01f,+};+var garment = GarmentSplineAuthoring.Lower(fit.Source, material);+string sourceJson = GarmentSplineAuthoring.SerializeSource(fit.Source);+var restoredSource = GarmentSplineAuthoring.ParseSource(sourceJson);+var restoredGarment = GarmentSplineAuthoring.Lower(restoredSource, material);+bool sourceReplay = restoredGarment.SourceHash == garment.SourceHash && restoredGarment.Cloth.ContentKey == garment.Cloth.ContentKey;+var contacts = new ClothContacts3D { BodySurface = GarmentDraping.BodySurface(body), BodyClearance = .004f };+var clearance = GarmentSplineAuthoring.Clearance(fit.Source, contacts.BodySurface);+Console.Error.WriteLine($"Independent spline clearance: {clearance.MinimumMm:F2}..{clearance.MaximumMm:F2} mm");+File.WriteAllText(Path.Combine(output, "source.json"), sourceJson);+File.WriteAllText(Path.Combine(output, "body.obj"), GarmentExport.BodyObj(body));+File.WriteAllText(Path.Combine(output, "control-cage.obj"), Cage(fit.Source));+File.WriteAllText(Path.Combine(output, "clearance.svg"), ClearanceMap(fit.Source, contacts.BodySurface));+var patchEvidence = new List<object>();+foreach (var patch in fit.Source.Patches)+{+ var sheet = SurfacePatchBrepMaterializer.MaterializeSheet(patch.Surface);+ var binding = BrepBindingValidator.Validate(sheet, true);+ var pcurve = BrepPcurveValidator.Validate(sheet, requireEveryCoedge: true);+ var wire = BrepWireframeSvgRenderer.Render(sheet, new(View: WireframeView.IsometricZUp));+ File.WriteAllText(Path.Combine(output, patch.Id + "-support.svg"), wire.Svg);+ patchEvidence.Add(new { patch.Id, binding.IsSuccess, pcurve, wire.Evidence });+ if (!binding.IsSuccess || !pcurve.IsValid || wire.Evidence.FacesWithTrimmedIsolines != 1)+ {+ throw new InvalidOperationException("GARMENT_SPLINE_BREP_NOT_QUALIFIED: Invalid open sheet binding or pcurve.");+ }+}+using var solver = new ClothSolver3D(garment.Cloth);+var initial = solver.Capture();+File.WriteAllText(Path.Combine(output, "initial-garment.obj"), garment.Obj(initial));+float residual = garment.Cloth.Constraints.Max(constraint => Math.Abs(ClothSurfaceMechanics3D.Evaluate(constraint, initial.Positions).Residual));+var zeroGravity = new ClothStepOptions3D { Gravity = Vector3.Zero, Substeps = 2, Iterations = 8 };+for (int frame = 0; frame < 8; frame++)+{+ solver.Step(zeroGravity, new());+}+float restDrift = initial.Positions.Zip(solver.Capture().Positions, Vector3.Distance).Max();+solver.Restore(initial);+var options = new ClothStepOptions3D+{+ Gravity = new(0, 0, -9.81f), Substeps = 2, Iterations = 8, ContactIterations = 1, VelocityDamping = 4,+};+var frames = new List<ClothMetrics3D>();+for (int frame = 0; frame < 32; frame++)+{+ solver.Step(options, contacts);+ if (frame % 8 == 7)+ {+ var metrics = ClothState3D.Measure(garment.Cloth, solver.Capture(), contacts);+ frames.Add(metrics);+ Console.Error.WriteLine($"Spline frame {frame + 1}: stretch {metrics.MaximumStretch:P2}, penetration {metrics.MaximumSurfacePenetration * 1000:F2} mm");+ }+}+var settled = solver.Capture();+solver.Step(options, contacts);+var expected = solver.Capture();+solver.Restore(settled);+solver.Step(options, contacts);+var replay = solver.Capture();+bool replayExact = expected.Positions.SequenceEqual(replay.Positions) && expected.Velocities.SequenceEqual(replay.Velocities);+var retained = ClothGarmentArtifact3D.Parse(garment.Artifact(settled));+using var resumed = retained.CreateSolver();+resumed.Step(options, contacts);+bool artifactReplay = resumed.Capture().Positions.SequenceEqual(expected.Positions)+ && resumed.Capture().Velocities.SequenceEqual(expected.Velocities);+float displacement = initial.Positions.Zip(settled.Positions, Vector3.Distance).Max();+bool accepted = fit.FittedRmsMm < fit.SeedRmsMm && clearance.MinimumMm >= 5+ && residual < .0001f && restDrift < .0001f && sourceReplay && replayExact && artifactReplay+ && frames.All(metrics => metrics.Finite && metrics.MaximumStretch <= .15f+ && metrics.MaximumSurfacePenetration <= .005f && metrics.MaximumPinError < .0001f);+File.WriteAllText(Path.Combine(output, "garment.obj"), garment.Obj(settled));+File.WriteAllText(Path.Combine(output, "garment.json"), garment.Artifact(settled));+File.WriteAllText(Path.Combine(output, "evidence.json"), JsonSerializer.Serialize(new+{+ accepted, fit.SeedRmsMm, fit.FittedRmsMm, fit.MaximumTargetErrorMm, fit.TargetCount, clearance,+ garment.SourceHash, garment.Cloth.ContentKey, sourceReplay, replayExact, artifactReplay,+ vertices = initial.Positions.Length, quads = garment.Cloth.Definition.Surface!.Quads.Length,+ bottomBandPins = garment.Cloth.Definition.Pins.Length, residual, restDrift, displacement,+ frames, patchEvidence, elapsedSeconds = watch.Elapsed.TotalSeconds,+ qualified = "Body-fitted editable bicubic midsurfaces, welded quads, stationary body, lower-band attachments, 32 gravity frames",+ frictionQualified = false, animatedBodyQualified = false, selfContactQualified = false,+ flatPatternQualified = false, closedSolidQualified = false, globalClearanceQualified = false,+}, json));+Console.WriteLine(accepted ? "GARMENT_SPLINE_TUBE_TOP_PASSED" : "GARMENT_SPLINE_TUBE_TOP_NOT_QUALIFIED");+return accepted ? 0 : 1;++static string Cage(GarmentSplineSource source)+{+ var result = new StringBuilder("# Retained spline controls; diagnostic lines; metres; Z up\n");+ int offset = 1;+ foreach (var patch in source.Patches)+ {+ foreach (var row in patch.Surface.ControlPoints)+ {+ foreach (var point in row)+ {+ result.AppendLine(FormattableString.Invariant($"v {point.X / 1000:R} {point.Y / 1000:R} {point.Z / 1000:R}"));+ }+ }+ for (int column = 0; column < 7; column++)+ {+ result.AppendLine("l " + string.Join(" ", Enumerable.Range(0, 4).Select(row => offset + column * 4 + row)));+ }+ for (int row = 0; row < 4; row++)+ {+ result.AppendLine("l " + string.Join(" ", Enumerable.Range(0, 7).Select(column => offset + column * 4 + row)));+ }+ offset += 28;+ }+ return result.ToString();+}++static string ClearanceMap(GarmentSplineSource source, IClothBodySurface3D body)+{+ var svg = new StringBuilder("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1040\" height=\"370\" viewBox=\"0 0 1040 370\">\n");+ svg.AppendLine("<rect width=\"1040\" height=\"370\" fill=\"#10151d\"/>");+ svg.AppendLine("<g fill=\"#ffffff\" font-family=\"sans-serif\" font-size=\"17\"><text x=\"25\" y=\"27\">Spline/body sampled clearance: red < 5 mm; amber 5..10 mm; green >= 10 mm</text>");+ svg.AppendLine("<text x=\"25\" y=\"54\">Front support (u horizontal, v downward)</text><text x=\"545\" y=\"54\">Back support</text></g>");+ for (int patch = 0; patch < 2; patch++)+ {+ for (int row = 0; row < 25; row++)+ {+ for (int column = 0; column < 49; column++)+ {+ double u = column / 48d;+ double v = row / 24d;+ var point = source.Patches[patch].Surface.Evaluate(u, v);+ double distance = body.Query(new((float)(point.X / 1000), (float)(point.Y / 1000),+ (float)(point.Z / 1000))).SignedDistance * 1000;+ string color = "#43a979";+ if (distance < 5)+ {+ color = "#e05252";+ }+ else if (distance < 10)+ {+ color = "#efb94f";+ }+ svg.AppendLine(FormattableString.Invariant($"<rect x=\"{25 + patch * 520 + column * 10}\" y=\"{70 + row * 10}\" width=\"9\" height=\"9\" fill=\"{color}\"><title>u={u:F4}, v={v:F4}: {distance:F3} mm</title></rect>"));+ }+ }+ }+ svg.AppendLine("<text x=\"25\" y=\"350\" fill=\"#dbeafe\" font-family=\"sans-serif\" font-size=\"15\">2450 discrete nearest-triangle queries; no global collision-free certificate.</text></svg>");+ return svg.ToString();+}diff --git a/scripts/render-garment.py b/scripts/render-garment.pyindex fffa8d80..053962df 100644--- a/scripts/render-garment.py+++ b/scripts/render-garment.py@@ -42,12 +42,38 @@ def load_obj(path, surface):return result+def load_control_cage(path):+ """Present the retained control positions; these lines do not modify the garment."""+ vertices = []+ lines = []+ for line in path.read_text(encoding="utf-8").splitlines():+ if line.startswith("v "):+ vertices.append(tuple(float(value) for value in line.split()[1:4]))+ elif line.startswith("l "):+ lines.append([int(value) - 1 for value in line.split()[1:]])+ curve = bpy.data.curves.new("retained control cage", "CURVE")+ curve.dimensions = "3D"+ curve.bevel_depth = .0012+ curve.bevel_resolution = 2+ for indices in lines:+ spline = curve.splines.new("POLY")+ spline.points.add(len(indices) - 1)+ for point, index in zip(spline.points, indices):+ point.co = (*vertices[index], 1)+ obj = bpy.data.objects.new("retained control cage", curve)+ bpy.context.collection.objects.link(obj)+ curve.materials.append(material("control cage orange", (.95, .35, .03), .7))++def main():parser = argparse.ArgumentParser()parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])parser.add_argument("--bottom", choices=("shorts", "skirt", "flared-skirt"), default="skirt")parser.add_argument("--garment", help="Render one garment instead of composing a tunic and bottom.")parser.add_argument("--input-dir", type=Path, help="Directory containing the actual garment.obj and body.obj exports.")+ parser.add_argument("--control-cage", type=Path, help="Optional retained OBJ polylines for source inspection.")+ parser.add_argument("--torso", action="store_true", help="Frame the fitted upper garment for inspection.")+ parser.add_argument("--initial", action="store_true", help="Render the exported rest mesh before simulation.")parser.add_argument("--samples", type=int, default=32)parser.add_argument("--engine", choices=("cycles", "workbench"), default="cycles",help="Workbench gives a quick neutral geometry diagnostic; Cycles remains the default.")@@ -59,6 +85,10 @@ def main():if not options.garment:parser.error("--frame requires --garment")output = output / options.frame+ if options.initial:+ output = output / "initial"+ if options.control_cage:+ output = output / "cage"output.mkdir(parents=True, exist_ok=True)bpy.ops.object.select_all(action="SELECT")bpy.ops.object.delete(use_global=False)@@ -67,6 +97,10 @@ def main():prefix = options.frame + "-" if options.frame else ""body_path = inputs / (prefix + "body.obj")garment_path = inputs / (prefix + "garment.obj")+ if options.initial:+ if options.frame:+ parser.error("--initial and --frame select different checkpoints")+ garment_path = inputs / "initial-garment.obj"garment_inputs = [body_path, garment_path]else:body_path = source / options.bottom / "body.obj"@@ -79,6 +113,9 @@ def main():else:load_obj(tunic_path, material("untextured tunic", (.08, .24, .31), .8))load_obj(bottom_path, material("untextured bottom", (.11, .14, .22), .8))+ if options.control_cage:+ load_control_cage(options.control_cage)+ garment_inputs.append(options.control_cage)bpy.ops.mesh.primitive_plane_add(size=200, location=(0, 0, -.005))bpy.context.object.data.materials.append(material("floor", (.24, .26, .29), .9))scene = bpy.context.scene@@ -119,6 +156,10 @@ def main():bpy.context.collection.objects.link(camera)camera.data.type = "ORTHO"camera.data.ortho_scale = 2.05+ target = Vector((0, -.035, .9))+ if options.torso:+ camera.data.ortho_scale = .68+ target = Vector((0, -.035, 1.31))scene.camera = camerafor name, location in (("front", (0, 4, 1.2)),@@ -126,7 +167,7 @@ def main():("back", (0, -4, 1.2)),):camera.location = location- camera.rotation_euler = (Vector((0, -.035, .9)) - camera.location).to_track_quat("-Z", "Y").to_euler()+ camera.rotation_euler = (target - camera.location).to_track_quat("-Z", "Y").to_euler()scene.render.filepath = str(output / (name + ".png"))bpy.ops.render.render(write_still=True)bpy.ops.wm.save_as_mainfile(filepath=str(output / "garment-preview.blend"))@@ -135,6 +176,8 @@ def main():"inputs": {str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in garment_inputs},"garment": options.garment or options.bottom,"frame": options.frame,+ "initial": options.initial,+ "controlCage": str(options.control_cage) if options.control_cage else None,"textures": False,"renderer": options.engine,}