Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add quad cloth mechanics and garment stretch diagnostics
Yuechen Li12f56a25c3e7
diff --git a/Aetheris.CLI/GarmentCommand.cs b/Aetheris.CLI/GarmentCommand.csindex 9fcd9855..25f92d81 100644--- a/Aetheris.CLI/GarmentCommand.cs+++ b/Aetheris.CLI/GarmentCommand.cs@@ -259,6 +259,7 @@ internal static class GarmentCommandtick = frame.Snapshot.Tick,frame.Metrics,frame.MaximumSeamGap,+ frame.StretchOutliers,frame.BodyEvidence,frame.Joints,}),diff --git a/Aetheris.Cloth3D/ClothDefinition3D.cs b/Aetheris.Cloth3D/ClothDefinition3D.csindex d3e1d5cc..24c427b0 100644--- a/Aetheris.Cloth3D/ClothDefinition3D.cs+++ b/Aetheris.Cloth3D/ClothDefinition3D.cs@@ -31,6 +31,12 @@ public sealed record ClothDefinition3D(string Id, ImmutableArray<Vector3> Positi/// <summary>Weighted equality constraints between material boundary samples.</summary>public ImmutableArray<ClothStitch3D> Stitches { get; init; } = [];public ClothMaterial3D Material { get; init; } = new();+ /// <summary>Optional authoritative quad cells and explicit material rest convention.+ /// Indices is then a rendering/contact triangulation, not the membrane topology.</summary>+ public ClothQuadSurface3D? Surface { get; init; }+ /// <summary>Optional disjoint vertex regions. Only wholly contained structural stencils+ /// receive the declared compliance scales; seam compliance and masses remain unchanged.</summary>+ public ImmutableArray<ClothMaterialRegion3D> MaterialRegions { get; init; } = [];public ImmutableArray<int> Pins { get; init; } = [];public ClothBendingModel3D BendingModel { get; init; } = ClothBendingModel3D.BoundaryCorrectedVertex;/// <summary>Opt-in exhaustive offset self-contact foundation. The discrete control stays available.</summary>@@ -70,10 +76,20 @@ public sealed record ClothDefinition3D(string Id, ImmutableArray<Vector3> Positipublic sealed record ClothStitch3D(string Id, ImmutableArray<int> Vertices,ImmutableArray<float> Weights, float Compliance = .00000001f);-public enum ClothConstraintKind3D { Warp, Weft, Diagonal, FlatBend, VertexBend, Stitch }+public sealed record ClothMaterialRegion3D(string Id, ImmutableArray<int> Vertices,+ float StretchComplianceScale = 1, float BendComplianceScale = 1);++public enum ClothConstraintKind3D+{+ Warp, Weft, Diagonal, FlatBend, VertexBend, Stitch,+ SurfaceWarp, SurfaceWeft, SurfaceShear, SurfaceBend,+}public sealed record ClothConstraint3D(ClothConstraintKind3D Kind, ImmutableArray<int> Vertices,- ImmutableArray<float> Weights, float RestLength, float Compliance);+ ImmutableArray<float> Weights, float RestLength, float Compliance)+{+ public ImmutableArray<float> TransverseWeights { get; init; } = [];+}/// <summary>Immutable topology and conflict-free schedules. A color contains disjoint vertex writes.</summary>public sealed class CompiledCloth3D@@ -173,6 +189,7 @@ internal static class ClothCompiler3D{throw new ArgumentException("Invalid or repeated cloth pin.");}+ int[] regionOfVertex = ClothMaterialRegions3D.Validate(definition);float[] masses = new float[positions.Length];var edges = new SortedDictionary<(int A, int B), List<int>>();var uniqueTriangles = new HashSet<(int, int, int)>();@@ -219,43 +236,51 @@ internal static class ClothCompiler3Dthrow new ArgumentException("Cloth has unused or numerically massless vertices.");}var constraints = new List<ClothConstraint3D>();- foreach (var (edge, opposite) in edges)+ if (definition.Surface is not null){- Vector2 direction = definition.Coordinates[edge.B] - definition.Coordinates[edge.A];- if (direction.LengthSquared() < 1e-14f)- {- throw new ArgumentException("Coincident material coordinates on cloth edge.");- }- ClothConstraintKind3D kind = ClothConstraintKind3D.Diagonal;- float compliance = material.DiagonalCompliance;- if (MathF.Abs(direction.Y) <= 1e-6f * direction.Length())- {- kind = ClothConstraintKind3D.Warp;- compliance = material.WarpCompliance;- }- else if (MathF.Abs(direction.X) <= 1e-6f * direction.Length())- {- kind = ClothConstraintKind3D.Weft;- compliance = material.WeftCompliance;- }- constraints.Add(new(kind, [edge.A, edge.B], [], Vector3.Distance(positions[edge.A], positions[edge.B]), compliance));- if (opposite.Count == 2)+ constraints.AddRange(ClothQuadCompiler3D.Compile(definition, masses));+ }+ else+ {+ foreach (var (edge, opposite) in edges){- var hinge = Bend(edge.A, edge.B, opposite[0], opposite[1]);- if (definition.BendingModel == ClothBendingModel3D.QuadraticHinge)+ Vector2 direction = definition.Coordinates[edge.B] - definition.Coordinates[edge.A];+ if (direction.LengthSquared() < 1e-14f)+ {+ throw new ArgumentException("Coincident material coordinates on cloth edge.");+ }+ ClothConstraintKind3D kind = ClothConstraintKind3D.Diagonal;+ float compliance = material.DiagonalCompliance;+ if (MathF.Abs(direction.Y) <= 1e-6f * direction.Length()){- constraints.Add(hinge);+ kind = ClothConstraintKind3D.Warp;+ compliance = material.WarpCompliance;+ }+ else if (MathF.Abs(direction.X) <= 1e-6f * direction.Length())+ {+ kind = ClothConstraintKind3D.Weft;+ compliance = material.WeftCompliance;+ }+ constraints.Add(new(kind, [edge.A, edge.B], [], Vector3.Distance(positions[edge.A], positions[edge.B]), compliance));+ if (opposite.Count == 2)+ {+ var hinge = Bend(edge.A, edge.B, opposite[0], opposite[1]);+ if (definition.BendingModel == ClothBendingModel3D.QuadraticHinge)+ {+ constraints.Add(hinge);+ }}}- }- if (definition.BendingModel == ClothBendingModel3D.BoundaryCorrectedVertex)- {- constraints.AddRange(ClothVertexBending3D.Compile(definition));+ if (definition.BendingModel == ClothBendingModel3D.BoundaryCorrectedVertex)+ {+ constraints.AddRange(ClothVertexBending3D.Compile(definition));+ }}foreach (var stitch in definition.Stitches){constraints.Add(new(ClothConstraintKind3D.Stitch, stitch.Vertices, stitch.Weights, 0, stitch.Compliance));}+ ClothMaterialRegions3D.Apply(definition.MaterialRegions, regionOfVertex, constraints);var pinned = definition.Pins.ToHashSet();var inverseMasses = masses.Select((mass, index) => pinned.Contains(index) ? 0 : 1 / mass).ToImmutableArray();string key = Identity();@@ -366,6 +391,27 @@ internal static class ClothCompiler3Dwriter.Write(material.WeftCompliance);writer.Write(material.DiagonalCompliance);writer.Write(material.BendCompliance);+ if (definition.Surface is not null)+ {+ ClothQuadCompiler3D.WriteIdentity(writer, definition.Surface);+ }+ // Preserve the established keys for definitions without regional tuning.+ if (!definition.MaterialRegions.IsEmpty)+ {+ writer.Write("cloth/material-regions/v1");+ writer.Write(definition.MaterialRegions.Length);+ foreach (var region in definition.MaterialRegions)+ {+ writer.Write(region.Id);+ writer.Write(region.StretchComplianceScale);+ writer.Write(region.BendComplianceScale);+ writer.Write(region.Vertices.Length);+ foreach (int vertex in region.Vertices)+ {+ writer.Write(vertex);+ }+ }+ }writer.Flush();return Convert.ToHexString(SHA256.HashData(bytes.ToArray()));}diff --git a/Aetheris.Cloth3D/ClothGpuData3D.cs b/Aetheris.Cloth3D/ClothGpuData3D.csindex 210f01e5..55bf7ebb 100644--- a/Aetheris.Cloth3D/ClothGpuData3D.cs+++ b/Aetheris.Cloth3D/ClothGpuData3D.cs@@ -21,7 +21,9 @@ public enum ClothPhase3Dpublic readonly record struct ClothDispatch3D(ClothPhase3D Phase, int Start, int Count, bool ResetLambda = false);/// <summary>Version 2 scalar storage ABI: 16 floats/vertex, then 3 multiplier floats/constraint;-/// 12-float stencil headers plus variable vertex/weight pairs; 32 floats/dispatch header.</summary>+/// 12-float stencil headers plus variable vertex/weight pairs; 32 floats/dispatch header.+/// Header word 8 optionally points to transverse material weights for quad membrane stencils;+/// legacy stencils retain zero in this previously reserved word.</summary>public sealed class ClothGpuData3D{public CompiledCloth3D Plan { get; }@@ -40,7 +42,8 @@ public sealed class ClothGpuData3D{Plan = plan;int stencilOffset = (plan.Constraints.Length + plan.Definition.Indices.Length / 3) * 12;- Source = new float[stencilOffset + plan.Constraints.Sum(constraint => constraint.Vertices.Length * 2)];+ Source = new float[stencilOffset + plan.Constraints.Sum(constraint =>+ constraint.Vertices.Length * 2 + constraint.TransverseWeights.Length)];var constraints = ImmutableArray.CreateBuilder<ClothDispatch3D>();var triangles = ImmutableArray.CreateBuilder<ClothDispatch3D>();int index = 0;@@ -65,6 +68,14 @@ public sealed class ClothGpuData3DSource[stencilOffset++] = constraint.Vertices[local];Source[stencilOffset++] = constraint.Weights.IsEmpty ? 0 : constraint.Weights[local];}+ if (!constraint.TransverseWeights.IsEmpty)+ {+ Source[offset + 8] = stencilOffset;+ foreach (float weight in constraint.TransverseWeights)+ {+ Source[stencilOffset++] = weight;+ }+ }}}foreach (var color in plan.TriangleColors)diff --git a/Aetheris.Cloth3D/ClothMaterialRegions3D.cs b/Aetheris.Cloth3D/ClothMaterialRegions3D.csnew file mode 100644index 00000000..277d6e9c--- /dev/null+++ b/Aetheris.Cloth3D/ClothMaterialRegions3D.cs@@ -0,0 +1,68 @@+using System.Collections.Immutable;++namespace Aetheris.Cloth3D;++internal static class ClothMaterialRegions3D+{+ public static int[] Validate(ClothDefinition3D definition)+ {+ if (definition.MaterialRegions.IsDefault || definition.MaterialRegions.Length > 256)+ {+ throw new ArgumentException("cloth-material-regions: Supply at most 256 explicit regions.");+ }+ int[] owners = Enumerable.Repeat(-1, definition.Positions.Length).ToArray();+ var identities = new HashSet<string>(StringComparer.Ordinal);+ for (int index = 0; index < definition.MaterialRegions.Length; index++)+ {+ var region = definition.MaterialRegions[index];+ if (region is null || string.IsNullOrWhiteSpace(region.Id) || !identities.Add(region.Id)+ || region.Vertices.IsDefaultOrEmpty+ || !ValidScale(region.StretchComplianceScale) || !ValidScale(region.BendComplianceScale))+ {+ throw new ArgumentException("cloth-material-region: Require unique names, vertices and finite scales in (0, 1000].");+ }+ foreach (int vertex in region.Vertices)+ {+ if (vertex < 0 || vertex >= owners.Length || owners[vertex] != -1)+ {+ throw new ArgumentException("cloth-material-region-overlap: Vertices must be valid, unique and disjoint across regions.");+ }+ owners[vertex] = index;+ }+ }+ return owners;+ }++ public static void Apply(ImmutableArray<ClothMaterialRegion3D> regions, int[] owners,+ List<ClothConstraint3D> constraints)+ {+ for (int index = 0; index < constraints.Count; index++)+ {+ var constraint = constraints[index];+ if (constraint.Kind == ClothConstraintKind3D.Stitch)+ {+ continue;+ }+ int owner = owners[constraint.Vertices[0]];+ if (owner < 0 || constraint.Vertices.Any(vertex => owners[vertex] != owner))+ {+ continue;+ }+ var region = regions[owner];+ bool bend = constraint.Kind is ClothConstraintKind3D.FlatBend+ or ClothConstraintKind3D.VertexBend or ClothConstraintKind3D.SurfaceBend;+ float scale = bend ? region.BendComplianceScale : region.StretchComplianceScale;+ float compliance = constraint.Compliance * scale;+ if (!float.IsFinite(compliance))+ {+ throw new ArgumentException("cloth-material-region-overflow: Scaled compliance must remain finite.");+ }+ constraints[index] = constraint with { Compliance = compliance };+ }+ }++ private static bool ValidScale(float value)+ {+ return float.IsFinite(value) && value > 0 && value <= 1000;+ }+}diff --git a/Aetheris.Cloth3D/ClothPresentationBinding3D.cs b/Aetheris.Cloth3D/ClothPresentationBinding3D.csnew file mode 100644index 00000000..0e4bc846--- /dev/null+++ b/Aetheris.Cloth3D/ClothPresentationBinding3D.cs@@ -0,0 +1,171 @@+using System.Collections.Immutable;+using System.Numerics;++namespace Aetheris.Cloth3D;++public sealed record ClothPresentationStencil3D(ImmutableArray<int> Vertices, ImmutableArray<float> Weights);+public sealed record ClothPresentationMesh3D(ImmutableArray<Vector3> Positions, ImmutableArray<int> Indices);++/// <summary>Author-time Loop subdivision stencils bound to one simulation topology.+/// Every material boundary is retained exactly as a piecewise linear curve, including+/// sewn boundaries. This is presentation only: it neither corrects nor certifies contact.</summary>+public sealed class ClothPresentationBinding3D+{+ private readonly CompiledCloth3D plan;+ public string SourceContentKey => plan.ContentKey;+ public ImmutableArray<ClothPresentationStencil3D> Stencils { get; }+ public ImmutableArray<int> Indices { get; }+ public ImmutableArray<Vector2> Coordinates { get; }+ public int Levels { get; }++ private ClothPresentationBinding3D(CompiledCloth3D plan, int levels,+ ImmutableArray<ClothPresentationStencil3D> stencils, ImmutableArray<int> indices)+ {+ this.plan = plan;+ Stencils = stencils;+ Indices = indices;+ Levels = levels;+ Coordinates = stencils.Select(stencil =>+ {+ Vector2 coordinate = Vector2.Zero;+ for (int index = 0; index < stencil.Vertices.Length; index++)+ {+ coordinate += plan.Definition.Coordinates[stencil.Vertices[index]] * stencil.Weights[index];+ }+ return coordinate;+ }).ToImmutableArray();+ }++ public static ClothPresentationBinding3D Compile(CompiledCloth3D plan, int levels = 2)+ {+ ArgumentNullException.ThrowIfNull(plan);+ if (levels is < 0 or > 2)+ {+ throw new ArgumentOutOfRangeException(nameof(levels), "cloth-presentation-levels: Use 0..2 bounded levels.");+ }+ var stencils = Enumerable.Range(0, plan.Definition.Positions.Length)+ .Select(vertex => new ClothPresentationStencil3D([vertex], [1])).ToImmutableArray();+ var indices = plan.Definition.Indices;+ for (int level = 0; level < levels; level++)+ {+ var edges = new SortedDictionary<(int A, int B), List<int>>();+ var neighbors = Enumerable.Range(0, stencils.Length).Select(_ => new SortedSet<int>()).ToArray();+ for (int face = 0; face < indices.Length; face += 3)+ {+ int a = indices[face];+ int b = indices[face + 1];+ int c = indices[face + 2];+ Edge(a, b, c);+ Edge(b, c, a);+ Edge(c, a, b);+ }+ if (stencils.Length + edges.Count > 65536 || indices.Length > 3 * 65536)+ {+ throw new ArgumentException("cloth-presentation-budget: Refinement exceeds 65536 vertices or 262144 triangles.");+ }+ var boundary = edges.Where(edge => edge.Value.Count == 1)+ .SelectMany(edge => new[] { edge.Key.A, edge.Key.B }).ToHashSet();+ var next = ImmutableArray.CreateBuilder<ClothPresentationStencil3D>(stencils.Length + edges.Count);+ for (int vertex = 0; vertex < stencils.Length; vertex++)+ {+ if (boundary.Contains(vertex))+ {+ next.Add(stencils[vertex]);+ continue;+ }+ int valence = neighbors[vertex].Count;+ if (valence < 3)+ {+ throw new ArgumentException("cloth-presentation-topology: An interior vertex needs at least three neighbors.");+ }+ float inner = .375f + .25f * MathF.Cos(2 * MathF.PI / valence);+ float beta = (.625f - inner * inner) / valence;+ var terms = new List<(int Vertex, float Weight)> { (vertex, 1 - valence * beta) };+ terms.AddRange(neighbors[vertex].Select(other => (other, beta)));+ next.Add(Blend(stencils, terms));+ }+ var midpoints = new Dictionary<(int A, int B), int>();+ foreach (var (edge, opposite) in edges)+ {+ midpoints.Add(edge, next.Count);+ if (opposite.Count == 1)+ {+ next.Add(Blend(stencils, [(edge.A, .5f), (edge.B, .5f)]));+ }+ else+ {+ next.Add(Blend(stencils, [(edge.A, .375f), (edge.B, .375f),+ (opposite[0], .125f), (opposite[1], .125f)]));+ }+ }+ var refined = ImmutableArray.CreateBuilder<int>(indices.Length * 4);+ for (int face = 0; face < indices.Length; face += 3)+ {+ int a = indices[face];+ int b = indices[face + 1];+ int c = indices[face + 2];+ int ab = Midpoint(a, b);+ int bc = Midpoint(b, c);+ int ca = Midpoint(c, a);+ refined.AddRange(new[] { a, ab, ca, b, bc, ab, c, ca, bc, ab, bc, ca });+ }+ stencils = next.MoveToImmutable();+ indices = refined.MoveToImmutable();++ void Edge(int a, int b, int opposite)+ {+ var key = (Math.Min(a, b), Math.Max(a, b));+ if (!edges.TryGetValue(key, out var adjacent))+ {+ edges.Add(key, adjacent = []);+ }+ adjacent.Add(opposite);+ if (adjacent.Count > 2)+ {+ throw new ArgumentException("cloth-presentation-topology: Nonmanifold edge.");+ }+ neighbors[a].Add(b);+ neighbors[b].Add(a);+ }++ int Midpoint(int a, int b)+ {+ return midpoints[(Math.Min(a, b), Math.Max(a, b))];+ }+ }+ return new(plan, levels, stencils, indices);+ }++ public ClothPresentationMesh3D Evaluate(ClothSnapshot3D snapshot)+ {+ ClothState3D.ValidateSnapshot(plan, snapshot);+ var positions = ImmutableArray.CreateBuilder<Vector3>(Stencils.Length);+ foreach (var stencil in Stencils)+ {+ Vector3 point = Vector3.Zero;+ for (int index = 0; index < stencil.Vertices.Length; index++)+ {+ point += snapshot.Positions[stencil.Vertices[index]] * stencil.Weights[index];+ }+ ClothValidation3D.Finite(point);+ positions.Add(point);+ }+ return new(positions.MoveToImmutable(), Indices);+ }++ private static ClothPresentationStencil3D Blend(ImmutableArray<ClothPresentationStencil3D> source,+ IEnumerable<(int Vertex, float Weight)> terms)+ {+ var weights = new SortedDictionary<int, float>();+ foreach (var (vertex, weight) in terms)+ {+ var stencil = source[vertex];+ for (int index = 0; index < stencil.Vertices.Length; index++)+ {+ int original = stencil.Vertices[index];+ weights[original] = weights.GetValueOrDefault(original) + weight * stencil.Weights[index];+ }+ }+ return new(weights.Keys.ToImmutableArray(), weights.Values.ToImmutableArray());+ }+}diff --git a/Aetheris.Cloth3D/ClothQuadSurface3D.cs b/Aetheris.Cloth3D/ClothQuadSurface3D.csnew file mode 100644index 00000000..af1567b8--- /dev/null+++ b/Aetheris.Cloth3D/ClothQuadSurface3D.cs@@ -0,0 +1,254 @@+using System.Collections.Immutable;+using System.Numerics;++namespace Aetheris.Cloth3D;++public enum ClothSurfaceRest3D+{+ FlatFabric,+ FittedSurface,+}++/// <summary>Counterclockwise four-corner cell. Local metre coordinates allow a welded+/// periodic surface without duplicating physical vertices at its material chart cut.</summary>+public sealed record ClothQuad3D(ImmutableArray<int> Vertices, ImmutableArray<Vector2> Coordinates);++/// <summary>Q1 membrane with 2x2 Gauss integration and objective rest-angle bending.+/// Material compliance is inverse surface stiffness, divided by quadrature area at compile time.+/// This experimental constitutive model is not a calibrated textile material.</summary>+public sealed record ClothQuadSurface3D(ImmutableArray<ClothQuad3D> Quads,+ ClothSurfaceRest3D Rest = ClothSurfaceRest3D.FlatFabric, float GrainRadians = 0)+{+ public static ClothDefinition3D Grid(string id, int columns, int rows, Vector2 size, Vector3 origin)+ {+ var definition = ClothDefinition3D.Grid(id, columns, rows, size, origin);+ var quads = ImmutableArray.CreateBuilder<ClothQuad3D>((columns - 1) * (rows - 1));+ for (int row = 0; row < rows - 1; row++)+ {+ for (int column = 0; column < columns - 1; column++)+ {+ int a = row * columns + column;+ ImmutableArray<int> vertices = [a, a + 1, a + columns + 1, a + columns];+ quads.Add(new(vertices, vertices.Select(index => definition.Coordinates[index]).ToImmutableArray()));+ }+ }+ var surface = new ClothQuadSurface3D(quads.MoveToImmutable());+ return definition with { Surface = surface, Indices = surface.Triangulate() };+ }++ public ImmutableArray<int> Triangulate(bool alternateDiagonal = false)+ {+ var indices = ImmutableArray.CreateBuilder<int>(Quads.Length * 6);+ foreach (var quad in Quads)+ {+ if (quad.Vertices.Length != 4)+ {+ throw new ArgumentException("cloth-quad-arity: A quad needs four vertices.");+ }+ var v = quad.Vertices;+ if (alternateDiagonal)+ {+ indices.AddRange(new int[] { v[0], v[1], v[3], v[1], v[2], v[3] });+ }+ else+ {+ indices.AddRange(new int[] { v[0], v[1], v[2], v[0], v[2], v[3] });+ }+ }+ return indices.MoveToImmutable();+ }+}++internal static class ClothQuadCompiler3D+{+ public static List<ClothConstraint3D> Compile(ClothDefinition3D definition, float[] masses)+ {+ var surface = definition.Surface!;+ if (!Enum.IsDefined(surface.Rest) || !float.IsFinite(surface.GrainRadians)+ || surface.Quads.IsDefaultOrEmpty || surface.Quads.Length > 16384 || definition.OffsetContact)+ {+ throw new ArgumentException("cloth-quad-surface: Require bounded cells, valid rest/grain and no offset self-contact.");+ }+ ValidateTriangles(definition, surface);+ Array.Clear(masses);+ var constraints = new List<ClothConstraint3D>();+ var edges = new SortedDictionary<(int A, int B), List<(int A, int B, int C, int D)>>();+ float gauss = 1 / MathF.Sqrt(3);+ float cosine = MathF.Cos(surface.GrainRadians);+ float sine = MathF.Sin(surface.GrainRadians);+ foreach (var quad in surface.Quads)+ {+ var v = quad.Vertices;+ for (int side = 0; side < 4; side++)+ {+ int a = v[side];+ int b = v[(side + 1) % 4];+ var key = (Math.Min(a, b), Math.Max(a, b));+ if (!edges.TryGetValue(key, out var uses))+ {+ edges.Add(key, uses = []);+ }+ uses.Add((a, b, v[(side + 2) % 4], v[(side + 3) % 4]));+ if (uses.Count > 2 || (uses.Count == 2 && uses[0].A != b))+ {+ throw new ArgumentException("cloth-quad-topology: Nonmanifold or inconsistent winding.");+ }+ }+ Vector3 firstNormal = Vector3.Zero;+ foreach (float eta in new[] { -gauss, gauss })+ {+ foreach (float xi in new[] { -gauss, gauss })+ {+ float[] r = [-(1 - eta) / 4, (1 - eta) / 4, (1 + eta) / 4, -(1 + eta) / 4];+ float[] s = [-(1 - xi) / 4, -(1 + xi) / 4, (1 + xi) / 4, (1 - xi) / 4];+ Vector2 ur = Vector2.Zero;+ Vector2 us = Vector2.Zero;+ Vector3 xr = Vector3.Zero;+ Vector3 xs = Vector3.Zero;+ for (int local = 0; local < 4; local++)+ {+ ur += quad.Coordinates[local] * r[local];+ us += quad.Coordinates[local] * s[local];+ xr += definition.Positions[v[local]] * r[local];+ xs += definition.Positions[v[local]] * s[local];+ }+ float determinant = ur.X * us.Y - ur.Y * us.X;+ Vector3 normal = Vector3.Cross(xr, xs);+ float area = surface.Rest == ClothSurfaceRest3D.FlatFabric ? determinant : normal.Length();+ if (!float.IsFinite(determinant) || determinant <= 1e-10f || !float.IsFinite(area)+ || area <= 1e-10f || normal.LengthSquared() <= 1e-20f+ || (firstNormal != Vector3.Zero && Vector3.Dot(firstNormal, normal) <= 0))+ {+ throw new ArgumentException("cloth-quad-jacobian: Singular, inverted or folded rest/material cell.");+ }+ firstNormal = normal;+ float[] u = new float[4];+ float[] w = new float[4];+ for (int local = 0; local < 4; local++)+ {+ u[local] = (r[local] * us.Y - s[local] * ur.Y) / determinant;+ w[local] = (-r[local] * us.X + s[local] * ur.X) / determinant;+ }+ if (surface.Rest == ClothSurfaceRest3D.FittedSurface)+ {+ Vector3 fu = Sum(u);+ Vector3 fv = Sum(w);+ float a = fu.Length();+ float b = Vector3.Dot(fu, fv) / a;+ float c = Vector3.Cross(fu, fv).Length() / a;+ for (int local = 0; local < 4; local++)+ {+ w[local] = (w[local] - u[local] * b / a) / c;+ u[local] /= a;+ }+ }+ float[] shape = [(1 - xi) * (1 - eta) / 4, (1 + xi) * (1 - eta) / 4,+ (1 + xi) * (1 + eta) / 4, (1 - xi) * (1 + eta) / 4];+ for (int local = 0; local < 4; local++)+ {+ float old = u[local];+ u[local] = cosine * old + sine * w[local];+ w[local] = -sine * old + cosine * w[local];+ masses[v[local]] += area * definition.Material.ArealDensity * shape[local];+ }+ Add(ClothConstraintKind3D.SurfaceWarp, definition.Material.WarpCompliance);+ Add(ClothConstraintKind3D.SurfaceWeft, definition.Material.WeftCompliance);+ Add(ClothConstraintKind3D.SurfaceShear, definition.Material.DiagonalCompliance);++ Vector3 Sum(float[] weights)+ {+ Vector3 value = Vector3.Zero;+ for (int local = 0; local < 4; local++)+ {+ value += definition.Positions[v[local]] * weights[local];+ }+ return value;+ }++ void Add(ClothConstraintKind3D kind, float compliance)+ {+ if (!float.IsFinite(compliance / area) || u.Any(value => !float.IsFinite(value))+ || w.Any(value => !float.IsFinite(value)))+ {+ throw new ArgumentException("cloth-quad-conditioning: Nonfinite material operator.");+ }+ constraints.Add(new(kind, v, u.ToImmutableArray(), 0, compliance / area)+ {+ TransverseWeights = w.ToImmutableArray(),+ });+ }+ }+ }+ }+ foreach (var uses in edges.Values.Where(uses => uses.Count == 2))+ {+ var first = uses[0];+ var second = uses[1];+ ImmutableArray<int> vertices = [first.A, first.B, first.C, first.D, second.C, second.D];+ Vector3 a = definition.Positions[first.A];+ Vector3 b = definition.Positions[first.B];+ Vector3 c = (definition.Positions[first.C] + definition.Positions[first.D]) * .5f;+ Vector3 d = (definition.Positions[second.C] + definition.Positions[second.D]) * .5f;+ float rest = surface.Rest == ClothSurfaceRest3D.FittedSurface+ ? ClothSurfaceMechanics3D.Angle(a, b, c, d) : 0;+ Vector3 edge = b - a;+ float width = (Vector3.Cross(c - a, edge).Length() + Vector3.Cross(d - a, edge).Length()) / edge.Length();+ float compliance = definition.Material.BendCompliance * width / edge.Length();+ if (!float.IsFinite(rest) || !float.IsFinite(width) || width <= 0 || !float.IsFinite(compliance))+ {+ throw new ArgumentException("cloth-quad-bend: Singular hinge or nonfinite rest/compliance.");+ }+ constraints.Add(new(ClothConstraintKind3D.SurfaceBend, vertices, [], rest, compliance));+ }+ if (masses.Any(mass => !float.IsFinite(mass) || mass <= 0 || !float.IsFinite(1 / mass)))+ {+ throw new ArgumentException("cloth-quad-mass: Unused or numerically massless vertices.");+ }+ return constraints;+ }++ private static void ValidateTriangles(ClothDefinition3D definition, ClothQuadSurface3D surface)+ {+ if (definition.Indices.Length != surface.Quads.Length * 6)+ {+ throw new ArgumentException("cloth-quad-triangulation: Require two display triangles per cell.");+ }+ for (int cell = 0; cell < surface.Quads.Length; cell++)+ {+ var quad = surface.Quads[cell];+ if (quad is null || quad.Vertices.IsDefault || quad.Coordinates.IsDefault+ || quad.Vertices.Length != 4 || quad.Coordinates.Length != 4+ || quad.Vertices.Distinct().Count() != 4+ || quad.Vertices.Any(index => index < 0 || index >= definition.Positions.Length)+ || quad.Coordinates.Any(point => !float.IsFinite(point.X) || !float.IsFinite(point.Y)))+ {+ throw new ArgumentException("cloth-quad-cell: Require four distinct valid vertices and finite coordinates.");+ }+ var v = quad.Vertices;+ int[] first = [v[0], v[1], v[2], v[0], v[2], v[3]];+ int[] second = [v[0], v[1], v[3], v[1], v[2], v[3]];+ var actual = definition.Indices.AsSpan(cell * 6, 6);+ if (!actual.SequenceEqual(first) && !actual.SequenceEqual(second))+ {+ throw new ArgumentException("cloth-quad-triangulation: Display triangles must lower their corresponding cell.");+ }+ }+ }++ public static void WriteIdentity(BinaryWriter writer, ClothQuadSurface3D surface)+ {+ writer.Write("cloth/quad-metric/v1");+ writer.Write((int)surface.Rest);+ writer.Write(surface.GrainRadians);+ writer.Write(surface.Quads.Length);+ foreach (var quad in surface.Quads)+ {+ for (int local = 0; local < 4; local++)+ {+ writer.Write(quad.Vertices[local]);+ writer.Write(quad.Coordinates[local].X);+ writer.Write(quad.Coordinates[local].Y);+ }+ }+ }+}diff --git a/Aetheris.Cloth3D/ClothSimulation3D.cs b/Aetheris.Cloth3D/ClothSimulation3D.csindex 16ab8036..406799fb 100644--- a/Aetheris.Cloth3D/ClothSimulation3D.cs+++ b/Aetheris.Cloth3D/ClothSimulation3D.cs@@ -105,6 +105,7 @@ public sealed record ClothMetrics3D(float MaximumStretch, float MaximumPinError,float MaximumSurfacePenetration, float BendEnergy, bool Finite){public ClothOffsetMetrics3D? OffsetContact { get; init; }+ public float MaximumMaterialShear { get; init; }}public sealed record ClothOffsetMetrics3D(float MinimumFeatureClearance,@@ -324,6 +325,28 @@ public sealed class ClothSolver3D : IClothSolver3Dfloat compliance = constraint.Kind == ClothConstraintKind3D.Stitch? constraint.Compliance * stitchComplianceScale : constraint.Compliance;float alpha = compliance / (h * h);+ if (ClothSurfaceMechanics3D.IsSurface(constraint.Kind))+ {+ Span<Vector3> gradients = stackalloc Vector3[6];+ float residual = ClothSurfaceMechanics3D.Evaluate(constraint, positions, gradients);+ float surfaceMovable = 0;+ for (int local = 0; local < constraint.Vertices.Length; local++)+ {+ surfaceMovable += Plan.InverseMasses[constraint.Vertices[local]] * gradients[local].LengthSquared();+ }+ if (surfaceMovable <= 1e-20f)+ {+ return;+ }+ float delta = (-residual - alpha * lambda[index].X) / (surfaceMovable + alpha);+ lambda[index].X += delta;+ for (int local = 0; local < constraint.Vertices.Length; local++)+ {+ int vertex = constraint.Vertices[local];+ Move(vertex, gradients[local] * (Plan.InverseMasses[vertex] * delta));+ }+ return;+ }if (constraint.Kind is not (ClothConstraintKind3D.FlatBend or ClothConstraintKind3D.VertexBend or ClothConstraintKind3D.Stitch)){int a = constraint.Vertices[0];@@ -563,8 +586,27 @@ public static class ClothState3Dvar positions = snapshot.Positions;float stretch = 0;float bending = 0;+ float shear = 0;+ Span<Vector3> surfaceGradients = stackalloc Vector3[6];foreach (var constraint in plan.Constraints){+ if (ClothSurfaceMechanics3D.IsSurface(constraint.Kind))+ {+ float residual = ClothSurfaceMechanics3D.Evaluate(constraint, positions.AsSpan(), surfaceGradients);+ if (constraint.Kind == ClothConstraintKind3D.SurfaceBend)+ {+ bending += .5f * residual * residual;+ }+ else if (constraint.Kind == ClothConstraintKind3D.SurfaceShear)+ {+ shear = MathF.Max(shear, MathF.Abs(residual));+ }+ else+ {+ stretch = MathF.Max(stretch, MathF.Sqrt(MathF.Max(0, 1 + 2 * residual)) - 1);+ }+ continue;+ }if (constraint.Kind is not (ClothConstraintKind3D.FlatBend or ClothConstraintKind3D.VertexBend or ClothConstraintKind3D.Stitch)){float length = Vector3.Distance(positions[constraint.Vertices[0]], positions[constraint.Vertices[1]]);@@ -647,6 +689,10 @@ public static class ClothState3DoffsetMetrics = new(clearance, overlap, active);}return new(stretch, pinError, penetration, bending,- float.IsFinite(stretch) && float.IsFinite(bending)) { OffsetContact = offsetMetrics };+ float.IsFinite(stretch) && float.IsFinite(bending) && float.IsFinite(shear))+ {+ OffsetContact = offsetMetrics,+ MaximumMaterialShear = shear,+ };}}diff --git a/Aetheris.Cloth3D/ClothSurfaceMechanics3D.cs b/Aetheris.Cloth3D/ClothSurfaceMechanics3D.csnew file mode 100644index 00000000..d73a121e--- /dev/null+++ b/Aetheris.Cloth3D/ClothSurfaceMechanics3D.cs@@ -0,0 +1,102 @@+using System.Collections.Immutable;+using System.Numerics;++namespace Aetheris.Cloth3D;++public sealed record ClothSurfaceEvaluation3D(float Residual, ImmutableArray<Vector3> Gradients);++public static class ClothSurfaceMechanics3D+{+ public static ClothSurfaceEvaluation3D Evaluate(ClothConstraint3D constraint, ImmutableArray<Vector3> positions)+ {+ if (!IsSurface(constraint.Kind))+ {+ throw new ArgumentException("Require a compiled surface constraint.");+ }+ Span<Vector3> gradients = stackalloc Vector3[6];+ float residual = Evaluate(constraint, positions.AsSpan(), gradients);+ return new(residual, gradients[..constraint.Vertices.Length].ToArray().ToImmutableArray());+ }++ internal static bool IsSurface(ClothConstraintKind3D kind)+ {+ return kind is ClothConstraintKind3D.SurfaceWarp or ClothConstraintKind3D.SurfaceWeft+ or ClothConstraintKind3D.SurfaceShear or ClothConstraintKind3D.SurfaceBend;+ }++ internal static float Evaluate(ClothConstraint3D constraint, ReadOnlySpan<Vector3> positions,+ Span<Vector3> gradients)+ {+ gradients.Clear();+ var vertices = constraint.Vertices;+ if (constraint.Kind == ClothConstraintKind3D.SurfaceBend)+ {+ Vector3 a = positions[vertices[0]];+ Vector3 b = positions[vertices[1]];+ Vector3 c = (positions[vertices[2]] + positions[vertices[3]]) * .5f;+ Vector3 d = (positions[vertices[4]] + positions[vertices[5]]) * .5f;+ Vector3 edge = b - a;+ Vector3 first = Vector3.Cross(edge, c - a);+ Vector3 second = Vector3.Cross(d - a, edge);+ float length = edge.Length();+ if (length < 1e-8f || first.LengthSquared() < 1e-16f || second.LengthSquared() < 1e-16f)+ {+ return 0;+ }+ Vector3 gc = -first * (length / first.LengthSquared());+ Vector3 gd = -second * (length / second.LengthSquared());+ float tc = Vector3.Dot(c - a, edge) / edge.LengthSquared();+ float td = Vector3.Dot(d - a, edge) / edge.LengthSquared();+ gradients[0] = -(1 - tc) * gc - (1 - td) * gd;+ gradients[1] = -tc * gc - td * gd;+ gradients[2] = gradients[3] = gc * .5f;+ gradients[4] = gradients[5] = gd * .5f;+ return Wrap(Angle(a, b, c, d) - constraint.RestLength);+ }+ Vector3 u = Vector3.Zero;+ Vector3 v = Vector3.Zero;+ for (int local = 0; local < 4; local++)+ {+ u += positions[vertices[local]] * constraint.Weights[local];+ v += positions[vertices[local]] * constraint.TransverseWeights[local];+ }+ for (int local = 0; local < 4; local++)+ {+ gradients[local] = constraint.Kind switch+ {+ ClothConstraintKind3D.SurfaceWarp => u * constraint.Weights[local],+ ClothConstraintKind3D.SurfaceWeft => v * constraint.TransverseWeights[local],+ ClothConstraintKind3D.SurfaceShear => v * constraint.Weights[local] + u * constraint.TransverseWeights[local],+ _ => throw new ArgumentException("Unknown surface constraint."),+ };+ }+ return constraint.Kind switch+ {+ ClothConstraintKind3D.SurfaceWarp => .5f * (u.LengthSquared() - 1),+ ClothConstraintKind3D.SurfaceWeft => .5f * (v.LengthSquared() - 1),+ ClothConstraintKind3D.SurfaceShear => Vector3.Dot(u, v),+ _ => throw new ArgumentException("Unknown surface constraint."),+ };+ }++ internal static float Angle(Vector3 a, Vector3 b, Vector3 c, Vector3 d)+ {+ Vector3 edge = Vector3.Normalize(b - a);+ Vector3 first = Vector3.Normalize(Vector3.Cross(b - a, c - a));+ Vector3 second = Vector3.Normalize(Vector3.Cross(d - a, b - a));+ return MathF.Atan2(Vector3.Dot(edge, Vector3.Cross(first, second)), Vector3.Dot(first, second));+ }++ private static float Wrap(float angle)+ {+ if (angle > MathF.PI)+ {+ return angle - 2 * MathF.PI;+ }+ if (angle < -MathF.PI)+ {+ return angle + 2 * MathF.PI;+ }+ return angle;+ }+}diff --git a/Aetheris.Humanoid/HumanoidFigureFit.cs b/Aetheris.Humanoid/HumanoidFigureFit.csindex 1419f3eb..3656b16e 100644--- a/Aetheris.Humanoid/HumanoidFigureFit.cs+++ b/Aetheris.Humanoid/HumanoidFigureFit.cs@@ -5,6 +5,7 @@ namespace Aetheris.Humanoid;public sealed record HumanoidFitSection(double HeightMm, double CircumferenceMm,double MinimumX, double MaximumX, double MinimumY, double MaximumY, int Segments);+public sealed record HumanoidFitContour(HumanoidFitSection Measurements, IReadOnlyList<Point3D> Points);public sealed record HumanoidFigureFit(string BodyId, string TopologyHash, string SkeletonId, string RestPoseId,Point3D LeftShoulder, Point3D RightShoulder, Point3D Neck, HumanoidFitSection Chest, HumanoidFitSection Hip,string RestSurfaceHash)@@ -72,6 +73,22 @@ public static class HumanoidFigureFittingprivate static HumanoidFitSection Section(HumanoidSurface surface, IReadOnlyList<Point3D> positions,double heightMm, Point3D torsoProbe)+ {+ return Contour(surface, positions, heightMm, torsoProbe).Measurements;+ }++ public static HumanoidFitContour Contour(HumanoidGameplayBody body, double heightMm,+ Point3D torsoProbe, SolvedHumanoidPose? pose = null)+ {+ ArgumentNullException.ThrowIfNull(body);+ var positions = pose is null+ ? body.Surface.Vertices.Select(vertex => vertex.Position).ToArray()+ : body.EvaluatePositions(pose);+ return Contour(body.Surface, positions, heightMm, torsoProbe);+ }++ private static HumanoidFitContour Contour(HumanoidSurface surface, IReadOnlyList<Point3D> positions,+ double heightMm, Point3D torsoProbe){if (!double.IsFinite(heightMm)){@@ -172,8 +189,9 @@ public static class HumanoidFigureFitting{circumference += (contour[(index + 1) % contour.Count] - contour[index]).Length;}- return new(heightMm, circumference, contour.Min(point => point.X), contour.Max(point => point.X),- contour.Min(point => point.Y), contour.Max(point => point.Y), contour.Count);+ var measurements = new HumanoidFitSection(heightMm, circumference, contour.Min(point => point.X),+ contour.Max(point => point.X), contour.Min(point => point.Y), contour.Max(point => point.Y), contour.Count);+ return new(measurements, contour.ToArray());int PointId(Point3D point){diff --git a/Aetheris.Kernel.Firmament.Tests/ClothMaterialRegionTests.cs b/Aetheris.Kernel.Firmament.Tests/ClothMaterialRegionTests.csnew file mode 100644index 00000000..bceac233--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/ClothMaterialRegionTests.cs@@ -0,0 +1,79 @@+using System.Collections.Immutable;+using System.Numerics;+using System.Text.Json;+using Aetheris.Cloth3D;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class ClothMaterialRegionTests+{+ [Fact]+ public void RegionalCompliancePreservesRestMetricsMassesAndSeamsAndRoundTrips()+ {+ var definition = ClothDefinition3D.Grid("regions", 4, 4, new(1, 1), Vector3.Zero) with+ {+ Stitches = [new("test-seam", [0, 15], [1, -1], .0001f)],+ };+ var baseline = definition.Compile();+ int[] selected = Enumerable.Range(0, 12).ToArray();+ var regionalDefinition = definition with+ {+ MaterialRegions = [new("collar", selected.ToImmutableArray(), .25f, 4)],+ };+ var regional = regionalDefinition.Compile();+ Assert.NotEqual(baseline.ContentKey, regional.ContentKey);+ Assert.True(baseline.InverseMasses.SequenceEqual(regional.InverseMasses));+ Assert.Equal(baseline.Constraints.Length, regional.Constraints.Length);+ int changed = 0;+ for (int index = 0; index < baseline.Constraints.Length; index++)+ {+ var before = baseline.Constraints[index];+ var after = regional.Constraints[index];+ Assert.Equal(before.RestLength, after.RestLength);+ Assert.True(before.Vertices.SequenceEqual(after.Vertices));+ Assert.True(before.Weights.SequenceEqual(after.Weights));+ bool contained = before.Kind != ClothConstraintKind3D.Stitch+ && before.Vertices.All(selected.Contains);+ bool bend = before.Kind is ClothConstraintKind3D.FlatBend or ClothConstraintKind3D.VertexBend;+ float scale = contained ? (bend ? 4 : .25f) : 1;+ Assert.Equal(before.Compliance * scale, after.Compliance);+ changed += after.Compliance != before.Compliance ? 1 : 0;+ }+ Assert.True(changed > 0);+ var json = new JsonSerializerOptions { IncludeFields = true };+ var restored = JsonSerializer.Deserialize<ClothDefinition3D>(JsonSerializer.Serialize(regionalDefinition, json), json)!;+ Assert.Equal(regional.ContentKey, restored.Compile().ContentKey);+ // Region compilation feeds the existing scalar GPU stencil ABI.+ var gpu = new ClothGpuData3D(regional);+ int packed = 0;+ foreach (var color in regional.ConstraintColors)+ {+ foreach (int original in color)+ {+ Assert.Equal(regional.Constraints[original].Compliance, gpu.Source[packed++ * 12 + 6]);+ }+ }+ }++ [Fact]+ public void InvalidOrOverlappingRegionsAreRejectedBeforeSimulation()+ {+ var definition = ClothDefinition3D.Grid("invalid", 3, 3, new(1, 1), Vector3.Zero);+ Assert.Throws<ArgumentException>(() => (definition with+ {+ MaterialRegions = [new("one", [0, 1]), new("two", [1, 2])],+ }).Compile());+ foreach (var region in new[]+ {+ new ClothMaterialRegion3D("", [0]),+ new ClothMaterialRegion3D("bad", [9]),+ new ClothMaterialRegion3D("bad", [0, 0]),+ new ClothMaterialRegion3D("bad", [], 1, 1),+ new ClothMaterialRegion3D("bad", [0], float.NaN, 1),+ new ClothMaterialRegion3D("bad", [0], 0, 1),+ })+ {+ Assert.Throws<ArgumentException>(() => (definition with { MaterialRegions = [region] }).Compile());+ }+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/ClothPresentationTests.cs b/Aetheris.Kernel.Firmament.Tests/ClothPresentationTests.csnew file mode 100644index 00000000..fc828bff--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/ClothPresentationTests.cs@@ -0,0 +1,63 @@+using System.Collections.Immutable;+using System.Numerics;+using Aetheris.Cloth3D;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class ClothPresentationTests+{+ [Fact]+ public void RefinementPreservesCutBoundariesAndDoesNotChangeSimulation()+ {+ var plan = ClothDefinition3D.Grid("display", 3, 3, new(1, 1), Vector3.Zero).Compile();+ using var solver = new ClothSolver3D(plan);+ var snapshot = solver.Capture();+ snapshot = snapshot with { Positions = snapshot.Positions.SetItem(4, new(.5f, .2f, .5f)) };+ var presentation = ClothPresentationBinding3D.Compile(plan, 2);+ var originalPositions = snapshot.Positions;+ var mesh = presentation.Evaluate(snapshot);+ Assert.Equal(plan.Definition.Indices.Length * 16, mesh.Indices.Length);+ Assert.Equal(9, snapshot.Positions.Length);+ Assert.Equal(24, plan.Definition.Indices.Length);+ Assert.InRange(mesh.Positions[4].Y, 0, .199f);+ foreach (int vertex in new[] { 0, 1, 2, 3, 5, 6, 7, 8 })+ {+ Assert.Equal(snapshot.Positions[vertex], mesh.Positions[vertex]);+ }+ // No refined vertex can move beyond the convex hull of its simulation support.+ foreach (var stencil in presentation.Stencils)+ {+ Assert.InRange(MathF.Abs(stencil.Weights.Sum() - 1), 0, 1e-6f);+ Assert.All(stencil.Weights, weight => Assert.InRange(weight, 0, 1));+ }+ Assert.Equal(originalPositions, snapshot.Positions);+ Assert.Equal(plan.ContentKey, presentation.SourceContentKey);+ }++ [Fact]+ public void PresentationCommutesWithRigidMotionAndRejectsAnotherTopology()+ {+ var plan = ClothDefinition3D.Grid("motion", 4, 4, new(1, 1), Vector3.Zero).Compile();+ using var solver = new ClothSolver3D(plan);+ var snapshot = solver.Capture();+ var presentation = ClothPresentationBinding3D.Compile(plan, 1);+ var first = presentation.Evaluate(snapshot);+ var rotation = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, .7f);+ Vector3 translation = new(.3f, -.2f, .8f);+ var moved = snapshot with+ {+ Positions = snapshot.Positions.Select(point => Vector3.Transform(point, rotation) + translation).ToImmutableArray(),+ };+ var second = presentation.Evaluate(moved);+ for (int vertex = 0; vertex < first.Positions.Length; vertex++)+ {+ Vector3 expected = Vector3.Transform(first.Positions[vertex], rotation) + translation;+ Assert.InRange(Vector3.Distance(expected, second.Positions[vertex]), 0, 1e-6f);+ }+ Assert.Throws<ArgumentException>(() => presentation.Evaluate(snapshot with { ContentKey = "other" }));+ Assert.Throws<ArgumentOutOfRangeException>(() => ClothPresentationBinding3D.Compile(plan, 3));+ var large = ClothDefinition3D.Grid("budget", 100, 100, new(1, 1), Vector3.Zero).Compile();+ Assert.Contains("cloth-presentation-budget", Assert.Throws<ArgumentException>(+ () => ClothPresentationBinding3D.Compile(large, 2)).Message);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/ClothQuadSurfaceTests.cs b/Aetheris.Kernel.Firmament.Tests/ClothQuadSurfaceTests.csnew file mode 100644index 00000000..5903d47e--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/ClothQuadSurfaceTests.cs@@ -0,0 +1,169 @@+using System.Collections.Immutable;+using System.Numerics;+using System.Text.Json;+using Aetheris.Cloth3D;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class ClothQuadSurfaceTests+{+ [Fact]+ public void GrainResponseIsContinuousAndAffineEnergyIsResolutionIndependent()+ {+ var baseline = Patch(3);+ var deformed = Deform(baseline.Positions);+ float energy = Energy(baseline.Compile(), deformed);+ Assert.True(energy > 0);+ var rotated = baseline with { Surface = baseline.Surface! with { GrainRadians = .01f * MathF.PI / 180 } };+ float rotatedEnergy = Energy(rotated.Compile(), deformed);+ Assert.InRange(MathF.Abs(rotatedEnergy / energy - 1), 0, .001f);+ foreach (int side in new[] { 5, 9 })+ {+ var refined = Patch(side);+ Assert.InRange(MathF.Abs(Energy(refined.Compile(), Deform(refined.Positions)) / energy - 1), 0, .0001f);+ var plan = refined.Compile();+ Assert.InRange(MathF.Abs(plan.InverseMasses.Sum(mass => 1 / mass) - .2f), 0, 1e-6f);+ }+ var halfTurn = baseline with { Surface = baseline.Surface! with { GrainRadians = MathF.PI / 2 } };+ Assert.True(MathF.Abs(Energy(halfTurn.Compile(), deformed) / energy - 1) > .1f);+ Assert.DoesNotContain(baseline.Compile().Constraints, item => item.Kind is+ ClothConstraintKind3D.Warp or ClothConstraintKind3D.Weft or ClothConstraintKind3D.Diagonal);+ }++ [Fact]+ public void RenderingDiagonalDoesNotChangeMassesConstraintsOrSolverEvolution()+ {+ var definition = Patch(4);+ var alternate = definition with { Indices = definition.Surface!.Triangulate(true) };+ var first = definition.Compile();+ var second = alternate.Compile();+ Assert.True(first.InverseMasses.SequenceEqual(second.InverseMasses));+ Assert.Equal(first.Constraints.Length, second.Constraints.Length);+ for (int index = 0; index < first.Constraints.Length; index++)+ {+ var a = first.Constraints[index];+ var b = second.Constraints[index];+ Assert.Equal(a.Kind, b.Kind);+ Assert.Equal(a.Compliance, b.Compliance);+ Assert.Equal(a.RestLength, b.RestLength);+ Assert.True(a.Vertices.SequenceEqual(b.Vertices));+ Assert.True(a.Weights.SequenceEqual(b.Weights));+ Assert.True(a.TransverseWeights.SequenceEqual(b.TransverseWeights));+ }+ using var solverA = new ClothSolver3D(first);+ using var solverB = new ClothSolver3D(second);+ solverA.Restore(solverA.Capture() with { Positions = Deform(definition.Positions) });+ solverB.Restore(solverB.Capture() with { Positions = Deform(definition.Positions) });+ for (int tick = 0; tick < 8; tick++)+ {+ solverA.Step(new() { Gravity = Vector3.Zero }, new());+ solverB.Step(new() { Gravity = Vector3.Zero }, new());+ }+ Assert.True(solverA.Capture().Positions.SequenceEqual(solverB.Capture().Positions));+ Assert.True(solverA.Capture().Velocities.SequenceEqual(solverB.Capture().Velocities));+ }++ [Fact]+ public void FittedCurvedRestIsStressFreeAndCommutesWithRigidMotion()+ {+ var definition = Curved();+ var plan = definition.Compile();+ foreach (var constraint in plan.Constraints)+ {+ Assert.InRange(MathF.Abs(ClothSurfaceMechanics3D.Evaluate(constraint, definition.Positions).Residual), 0, 2e-6f);+ }+ var rotation = Quaternion.CreateFromAxisAngle(Vector3.Normalize(new(1, 2, 3)), .8f);+ var moved = definition.Positions.Select(point => Vector3.Transform(point, rotation) + new Vector3(.4f, -.2f, .3f)).ToImmutableArray();+ foreach (var constraint in plan.Constraints)+ {+ Assert.InRange(MathF.Abs(ClothSurfaceMechanics3D.Evaluate(constraint, moved).Residual), 0, 1e-5f);+ }+ using var solver = new ClothSolver3D(plan);+ for (int tick = 0; tick < 8; tick++)+ {+ solver.Step(new() { Gravity = Vector3.Zero }, new());+ }+ float drift = solver.Capture().Positions.Zip(definition.Positions, Vector3.Distance).Max();+ Assert.InRange(drift, 0, 1e-5f);+ var flat = definition with { Surface = definition.Surface! with { Rest = ClothSurfaceRest3D.FlatFabric } };+ Assert.True(Energy(flat.Compile(), definition.Positions) > .01f);+ }++ [Fact]+ public void AnalyticalGradientsMatchFiniteDifferencesForEverySurfaceConstraintKind()+ {+ var definition = Curved();+ var positions = Deform(definition.Positions).SetItem(3, definition.Positions[3] + new Vector3(.01f, .03f, -.02f));+ var plan = definition.Compile();+ foreach (var constraint in plan.Constraints.GroupBy(item => item.Kind).Select(group => group.First()))+ {+ var evaluation = ClothSurfaceMechanics3D.Evaluate(constraint, positions);+ for (int local = 0; local < constraint.Vertices.Length; local++)+ {+ int vertex = constraint.Vertices[local];+ for (int axis = 0; axis < 3; axis++)+ {+ Vector3 offset = axis switch { 0 => Vector3.UnitX, 1 => Vector3.UnitY, _ => Vector3.UnitZ };+ const float epsilon = .0001f;+ float plus = ClothSurfaceMechanics3D.Evaluate(constraint,+ positions.SetItem(vertex, positions[vertex] + offset * epsilon)).Residual;+ float minus = ClothSurfaceMechanics3D.Evaluate(constraint,+ positions.SetItem(vertex, positions[vertex] - offset * epsilon)).Residual;+ float numeric = (plus - minus) / (2 * epsilon);+ float analytical = Vector3.Dot(evaluation.Gradients[local], offset);+ Assert.True(MathF.Abs(numeric - analytical) < .003f,+ $"{constraint.Kind} vertex {vertex} axis {axis}: analytic {analytical}, numeric {numeric}");+ }+ }+ }+ }++ [Fact]+ public void SurfaceTransportAndInvalidGeometryAreExplicit()+ {+ var definition = Curved();+ var json = new JsonSerializerOptions { IncludeFields = true };+ var restored = JsonSerializer.Deserialize<ClothDefinition3D>(JsonSerializer.Serialize(definition, json), json)!;+ Assert.Equal(definition.Compile().ContentKey, restored.Compile().ContentKey);+ Assert.Throws<ArgumentException>(() => (definition with { OffsetContact = true }).Compile());+ Assert.Throws<ArgumentException>(() => (definition with { Surface = definition.Surface! with { GrainRadians = float.NaN } }).Compile());+ var invalid = definition.Surface!.Quads[0] with { Coordinates = [new(0, 0), new(0, 1), new(1, 1), new(1, 0)] };+ Assert.Throws<ArgumentException>(() => (definition with+ {+ Surface = definition.Surface with { Quads = definition.Surface.Quads.SetItem(0, invalid) },+ }).Compile());+ Assert.Throws<ArgumentException>(() => (definition with { Indices = definition.Indices.SetItem(0, 10) }).Compile());+ }++ private static ClothDefinition3D Patch(int side)+ {+ return ClothQuadSurface3D.Grid("patch", side, side, new(1, 1), Vector3.Zero) with+ {+ Material = new() { WarpCompliance = .001f, WeftCompliance = .004f, DiagonalCompliance = .002f, BendCompliance = .01f },+ };+ }++ private static ClothDefinition3D Curved()+ {+ var definition = Patch(5);+ return definition with+ {+ Positions = definition.Positions.Select(point => point with { Y = .1f * MathF.Sin(MathF.PI * point.X) }).ToImmutableArray(),+ Surface = definition.Surface! with { Rest = ClothSurfaceRest3D.FittedSurface },+ };+ }++ private static ImmutableArray<Vector3> Deform(ImmutableArray<Vector3> positions)+ {+ return positions.Select(point => new Vector3(point.X * 1.1f + .03f * point.Z, point.Y, point.Z * .98f)).ToImmutableArray();+ }++ private static float Energy(CompiledCloth3D plan, ImmutableArray<Vector3> positions)+ {+ return plan.Constraints.Sum(constraint =>+ {+ float residual = ClothSurfaceMechanics3D.Evaluate(constraint, positions).Residual;+ return .5f * residual * residual / constraint.Compliance;+ });+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/GarmentSettlingTests.cs b/Aetheris.Kernel.Firmament.Tests/GarmentSettlingTests.csindex b8f3bdf5..77fe91e4 100644--- a/Aetheris.Kernel.Firmament.Tests/GarmentSettlingTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/GarmentSettlingTests.cs@@ -39,6 +39,9 @@ public sealed class GarmentSettlingTestsAssert.Equal(40, result.CompletedSettlingTicks);Assert.Equal("FrameBudget", result.StopReason);Assert.InRange(result.Metrics.MaximumStretch, .99f, 1.01f);+ Assert.Equal(result.Metrics.MaximumStretch, result.StretchOutliers[0].Stretch);+ Assert.Equal("sheet", result.StretchOutliers[0].Panel);+ Assert.Equal(2, result.StretchOutliers[0].MaterialA.Length);Assert.False(GarmentDrapeLimits.Accept(result.Metrics, result.MaximumSeamGap));Assert.All(result.Samples, sample =>{diff --git a/Aetheris.Kernel.Firmament.Tests/GarmentSurfaceAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/GarmentSurfaceAuthoringTests.csnew file mode 100644index 00000000..f2938103--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/GarmentSurfaceAuthoringTests.cs@@ -0,0 +1,72 @@+using System.Numerics;+using Aetheris.Cloth3D;+using Aetheris.Humanoid;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.Garment;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class GarmentSurfaceAuthoringTests+{+ [Fact]+ public void BodyContourSkirtHasWeldedQuadTopologyAndRuntimeArtifactReplay()+ {+ var body = HumanoidPoseAuthoringTests.Body();+ var source = new GarmentSkirtSurface("test-skirt", HipHeight: .96f, ChestHeight: 1.28f);+ var garment = GarmentSurfaceAuthoring.Skirt(source, body, new()+ {+ WarpCompliance = .001f, WeftCompliance = .004f, DiagonalCompliance = .002f, BendCompliance = .01f,+ });+ var definition = garment.Cloth.Definition;+ Assert.Equal(288, definition.Positions.Length);+ Assert.Equal(256, definition.Surface!.Quads.Length);+ Assert.Equal(ClothSurfaceRest3D.FittedSurface, definition.Surface.Rest);+ Assert.Equal(32, definition.Pins.Length);+ Assert.Empty(definition.Stitches);+ Assert.Equal(new[] { 31, 0, 32, 63 }, definition.Surface.Quads[31].Vertices);+ Assert.All(garment.Cloth.Constraints, constraint =>+ Assert.InRange(Math.Abs(ClothSurfaceMechanics3D.Evaluate(constraint, definition.Positions).Residual), 0, .0001f));+ Assert.Equal(256, garment.Obj().Split('\n').Count(line => line.StartsWith("f ")));+ using var solver = new ClothSolver3D(garment.Cloth);+ var options = new ClothStepOptions3D { Gravity = new(0, 0, -9.81f), Substeps = 2, Iterations = 8 };+ 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));+ Assert.Equal(garment.SourceHash, retained.SourceHash);+ Assert.Equal(garment.Cloth.ContentKey, retained.Cloth.ContentKey);+ var variant = GarmentSurfaceAuthoring.Skirt(source with { HemFlare = .15f }, body, definition.Material);+ Assert.NotEqual(garment.SourceHash, variant.SourceHash);+ Assert.NotEqual(garment.Cloth.ContentKey, variant.Cloth.ContentKey);+ }++ [Fact]+ public void ContourExposesTheSameClosedSectionUsedByFigureMeasurements()+ {+ var body = HumanoidPoseAuthoringTests.Body();+ var contour = HumanoidFigureFitting.Contour(body, 960, new Point3D(0, 0, 960));+ Assert.Equal(HumanoidFigureFitting.Section(body, 960, new Point3D(0, 0, 960)), contour.Measurements);+ Assert.Equal(contour.Measurements.Segments, contour.Points.Count);+ double length = 0;+ for (int index = 0; index < contour.Points.Count; index++)+ {+ length += (contour.Points[(index + 1) % contour.Points.Count] - contour.Points[index]).Length;+ }+ Assert.Equal(contour.Measurements.CircumferenceMm, length, 8);+ Assert.All(contour.Points, point => Assert.Equal(960, point.Z));+ }++ [Theory]+ [InlineData(0, .02f)]+ [InlineData(.48f, 0)]+ [InlineData(float.NaN, .02f)]+ public void InvalidDimensionsAreRejectedBeforeFitting(float length, float ease)+ {+ var exception = Assert.Throws<ArgumentException>(() => GarmentSurfaceAuthoring.Skirt(+ new("invalid", Length: length, Ease: ease), HumanoidPoseAuthoringTests.Body(), new()));+ Assert.StartsWith("garment-surface-skirt:", exception.Message);+ }+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentDraping.cs b/Aetheris.Kernel.Firmament/Garment/GarmentDraping.csindex 555a9c49..df6b548d 100644--- a/Aetheris.Kernel.Firmament/Garment/GarmentDraping.cs+++ b/Aetheris.Kernel.Firmament/Garment/GarmentDraping.cs@@ -67,7 +67,10 @@ public sealed record GarmentDrapeResult(ClothSnapshot3D Snapshot, ClothMetrics3Dpublic sealed record GarmentDrapeFrame(string Name, double MotionSeconds, ClothSnapshot3D Snapshot,IReadOnlyList<Point3D> BodyPositions, ClothMetrics3D Metrics, float MaximumSeamGap,- ConstrainedSurfaceEvidence BodyEvidence, IReadOnlyList<AnatomicalJointRequest> Joints);+ ConstrainedSurfaceEvidence BodyEvidence, IReadOnlyList<AnatomicalJointRequest> Joints)+{+ public IReadOnlyList<GarmentStretchOutlier> StretchOutliers { get; init; } = [];+}public sealed record GarmentContactOutlier(int Vertex, string Panel, bool Pinned, float Penetration, float[] Position);public sealed record GarmentStretchOutlier(int A, int B, float Stretch, float RestLength)@@ -282,16 +285,7 @@ public static class GarmentDrapingpins.Contains(index), garment.Cloth.Definition.Material.Thickness * .5f + contacts.BodyClearance - contacts.BodySurface!.Query(position).SignedDistance,[position.X, position.Y, position.Z])).Where(item => item.Penetration > .001f).OrderByDescending(item => item.Penetration).Take(8).ToArray();- var stretchOutliers = garment.Cloth.Constraints.Where(constraint => constraint.Vertices.Length == 2- && constraint.Weights.IsEmpty).Select(constraint => new GarmentStretchOutlier(constraint.Vertices[0], constraint.Vertices[1],- Vector3.Distance(final.Positions[constraint.Vertices[0]], final.Positions[constraint.Vertices[1]]) / constraint.RestLength - 1,- constraint.RestLength)- {- Panel = PanelOfVertex(constraint.Vertices[0]),- Kind = constraint.Kind.ToString(),- MaterialA = MaterialPoint(constraint.Vertices[0]),- MaterialB = MaterialPoint(constraint.Vertices[1]),- }).OrderByDescending(item => item.Stretch).Take(8).ToArray();+ var stretchOutliers = GarmentMeshInspection.StretchOutliers(garment, final);var surfaceOutliers = new List<GarmentSurfaceContactOutlier>();var indices = garment.Cloth.Definition.Indices;for (int face = 0; face < indices.Length; face += 3)@@ -348,18 +342,16 @@ public static class GarmentDraping{var snapshot = solver.Capture();frames.Add(new(name, seconds, snapshot, motion!.Positions.ToArray(), ClothState3D.Measure(garment.Cloth, snapshot, contacts),- garment.MaximumSeamGap(snapshot), motion.Inspect(), motion.CurrentPose.Joints));+ garment.MaximumSeamGap(snapshot), motion.Inspect(), motion.CurrentPose.Joints)+ {+ StretchOutliers = GarmentMeshInspection.StretchOutliers(garment, snapshot),+ });}string PanelOfVertex(int vertex){return garment.Panels.Single(panel => vertex >= panel.VertexStart && vertex < panel.VertexStart + panel.VertexCount).Identity;}- float[] MaterialPoint(int vertex)- {- var point = garment.Cloth.Definition.Positions[vertex];- return [point.X, point.Y];- }}private static bool SameSnapshot(ClothSnapshot3D expected, ClothSnapshot3D actual)diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentMeshInspection.cs b/Aetheris.Kernel.Firmament/Garment/GarmentMeshInspection.csindex 56e93859..d164ff06 100644--- a/Aetheris.Kernel.Firmament/Garment/GarmentMeshInspection.cs+++ b/Aetheris.Kernel.Firmament/Garment/GarmentMeshInspection.cs@@ -1,4 +1,5 @@using System.Numerics;+using Aetheris.Cloth3D;namespace Aetheris.Kernel.Firmament.Garment;@@ -10,6 +11,34 @@ public sealed record GarmentMeshQuality(int UniqueEdges, double MinimumEdgeLengtpublic static class GarmentMeshInspection{+ public static IReadOnlyList<GarmentStretchOutlier> StretchOutliers(CompiledGarment garment,+ ClothSnapshot3D snapshot, int count = 8)+ {+ ClothState3D.ValidateSnapshot(garment.Cloth, snapshot);+ if (count is < 1 or > 64)+ {+ throw new ArgumentOutOfRangeException(nameof(count));+ }+ return garment.Cloth.Constraints.Where(constraint => constraint.Vertices.Length == 2+ && constraint.Weights.IsEmpty).Select(constraint =>+ {+ int a = constraint.Vertices[0];+ int b = constraint.Vertices[1];+ Vector3 materialA = garment.Cloth.Definition.Positions[a];+ Vector3 materialB = garment.Cloth.Definition.Positions[b];+ return new GarmentStretchOutlier(a, b,+ Vector3.Distance(snapshot.Positions[a], snapshot.Positions[b]) / constraint.RestLength - 1,+ constraint.RestLength)+ {+ Panel = garment.Panels.Single(panel => a >= panel.VertexStart+ && a < panel.VertexStart + panel.VertexCount).Identity,+ Kind = constraint.Kind.ToString(),+ MaterialA = [materialA.X, materialA.Y],+ MaterialB = [materialB.X, materialB.Y],+ };+ }).OrderByDescending(item => item.Stretch).Take(count).ToArray();+ }+public static GarmentMeshQuality Measure(CompiledGarment garment){ArgumentNullException.ThrowIfNull(garment);diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentSurfaceAuthoring.cs b/Aetheris.Kernel.Firmament/Garment/GarmentSurfaceAuthoring.csnew file mode 100644index 00000000..0c2c055f--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentSurfaceAuthoring.cs@@ -0,0 +1,158 @@+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.Math;++namespace Aetheris.Kernel.Firmament.Garment;++/// <summary>Metre dimensions. This experimental fitted surface is not a flat sewing pattern.</summary>+public sealed record GarmentSkirtSurface(string Id, int Columns = 32, int Rows = 9,+ float WaistAboveHip = .13f, float Length = .48f, float Ease = .02f, float HemFlare = .10f,+ float? HipHeight = null, float? ChestHeight = null);++public sealed record CompiledGarmentSurface(GarmentSkirtSurface Source, HumanoidFigureFit Figure,+ string SourceHash, CompiledCloth3D Cloth, ImmutableArray<int> Waist, ImmutableArray<int> Hem)+{+ private static readonly JsonSerializerOptions JsonOptions = new() { IncludeFields = true, WriteIndented = true };++ 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 = "surface/skirt/" + Source.Id,+ source = Source, figure = Figure, waist = Waist, hem = Hem,+ contentKey = Cloth.ContentKey, definition = Cloth.Definition, settled,+ }, JsonOptions);+ }++ public string Obj(ClothSnapshot3D? snapshot = null)+ {+ if (snapshot is not null)+ {+ ClothState3D.ValidateSnapshot(Cloth, snapshot);+ }+ var positions = snapshot?.Positions ?? Cloth.Definition.Positions;+ var result = new StringBuilder("# Aetheris fitted quad surface; metres; Z up\n");+ foreach (var point in 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();+ }+}++/// <summary>Body contours own the fitting geometry; the author declares ease and silhouette.+/// Material cells remain quads. Triangles only lower the surface for rendering/body contact.</summary>+public static class GarmentSurfaceAuthoring+{+ public static CompiledGarmentSurface Skirt(GarmentSkirtSurface source, HumanoidGameplayBody body,+ ClothMaterial3D material)+ {+ ArgumentNullException.ThrowIfNull(source);+ ArgumentNullException.ThrowIfNull(body);+ ArgumentNullException.ThrowIfNull(material);+ if (string.IsNullOrWhiteSpace(source.Id) || source.Columns is < 16 or > 128+ || source.Rows is < 3 or > 64 || !float.IsFinite(source.WaistAboveHip)+ || !float.IsFinite(source.Length) || !float.IsFinite(source.Ease) || !float.IsFinite(source.HemFlare)+ || source.WaistAboveHip <= 0 || source.WaistAboveHip >= source.Length+ || source.Length > 1.5f || source.Ease <= 0 || source.Ease > .2f+ || source.HemFlare < 0 || source.HemFlare > .5f+ || (source.HipHeight is { } hipHeight && !float.IsFinite(hipHeight))+ || (source.ChestHeight is { } chestHeight && !float.IsFinite(chestHeight)))+ {+ throw new ArgumentException("garment-surface-skirt: Require bounded resolution and positive finite fitting dimensions.");+ }+ var figure = HumanoidFigureFitting.Measure(body, source.ChestHeight * 1000, source.HipHeight * 1000);+ var pelvis = body.Skeleton.Joints.Single(joint => joint.Kind == HumanoidJointKind.Pelvis).GlobalBind;+ var center = new Point3D(pelvis.M41, pelvis.M42, pelvis.M43);+ double waistHeight = figure.Hip.HeightMm + source.WaistAboveHip * 1000;+ var waistContour = HumanoidFigureFitting.Contour(body, waistHeight, center);+ var hipContour = HumanoidFigureFitting.Contour(body, figure.Hip.HeightMm, center);+ float circumference = (float)(waistContour.Measurements.CircumferenceMm / 1000);+ var positions = ImmutableArray.CreateBuilder<Vector3>(source.Columns * source.Rows);+ var coordinates = ImmutableArray.CreateBuilder<Vector2>(positions.Capacity);+ var cells = ImmutableArray.CreateBuilder<ClothQuad3D>(source.Columns * (source.Rows - 1));+ for (int row = 0; row < source.Rows; row++)+ {+ float depth = source.Length * row / (source.Rows - 1);+ float hipFraction = Math.Clamp(depth / source.WaistAboveHip, 0, 1);+ float flareFraction = Math.Max(0, depth - source.WaistAboveHip) / (source.Length - source.WaistAboveHip);+ for (int column = 0; column < source.Columns; column++)+ {+ double angle = -2 * Math.PI * column / source.Columns;+ double waistRadius = Radius(waistContour.Points, center, angle);+ double hipRadius = Radius(hipContour.Points, center, angle);+ double radius = (waistRadius * (1 - hipFraction) + hipRadius * hipFraction) / 1000+ + source.Ease + source.HemFlare * flareFraction;+ positions.Add(new((float)(center.X / 1000 + radius * Math.Cos(angle)),+ (float)(center.Y / 1000 + radius * Math.Sin(angle)), (float)(waistHeight / 1000 - depth)));+ coordinates.Add(new(circumference * column / source.Columns, depth));+ if (row == source.Rows - 1)+ {+ continue;+ }+ int next = (column + 1) % source.Columns;+ int top = row * source.Columns;+ float u0 = circumference * column / source.Columns;+ float u1 = circumference * (column + 1) / source.Columns;+ float v1 = source.Length * (row + 1) / (source.Rows - 1);+ cells.Add(new([top + column, top + next, top + source.Columns + next, top + source.Columns + column],+ [new(u0, depth), new(u1, depth), new(u1, v1), new(u0, v1)]));+ }+ }+ var surface = new ClothQuadSurface3D(cells.MoveToImmutable(), ClothSurfaceRest3D.FittedSurface);+ var waist = Enumerable.Range(0, source.Columns).ToImmutableArray();+ var hem = Enumerable.Range((source.Rows - 1) * source.Columns, source.Columns).ToImmutableArray();+ var definition = new ClothDefinition3D(source.Id, positions.MoveToImmutable(), coordinates.MoveToImmutable(),+ surface.Triangulate()) { Surface = surface, Material = material, Pins = waist };+ // Includes material and body provenance, not machine paths or private reference geometry.+ string identity = JsonSerializer.Serialize(new { source, material, figure }, new JsonSerializerOptions { IncludeFields = true });+ string hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(identity)));+ return new(source, figure, hash, definition.Compile(), waist, hem);+ }++ private static double Radius(IReadOnlyList<Point3D> contour, Point3D center, double angle)+ {+ double dx = Math.Cos(angle);+ double dy = Math.Sin(angle);+ double radius = 0;+ for (int index = 0; index < contour.Count; index++)+ {+ var a = contour[index];+ var b = contour[(index + 1) % contour.Count];+ double ex = b.X - a.X;+ double ey = b.Y - a.Y;+ double denominator = dx * ey - dy * ex;+ if (Math.Abs(denominator) < 1e-10)+ {+ continue;+ }+ double ax = a.X - center.X;+ double ay = a.Y - center.Y;+ double distance = (ax * ey - ay * ex) / denominator;+ double fraction = (ax * dy - ay * dx) / denominator;+ if (distance > 0 && fraction >= 0 && fraction <= 1)+ {+ radius = Math.Max(radius, distance);+ }+ }+ if (radius <= 0 || !double.IsFinite(radius))+ {+ throw new InvalidOperationException("garment-surface-contour: No radial intersection; choose an interior fitting axis.");+ }+ return radius;+ }+}diff --git a/docs/public/firmament/garment-fit-resolution-experiment.md b/docs/public/firmament/garment-fit-resolution-experiment.mdnew file mode 100644index 00000000..ef9f09d7--- /dev/null+++ b/docs/public/firmament/garment-fit-resolution-experiment.md@@ -0,0 +1,197 @@+# Garment fit, resolution and presentation experiments++Date: 2026-10-11. This continues the [armhole experiment](garment-armhole-experiment.md)+with the same MIT-credited GarmentCode cut, Anatolia body, fabric and sewing/motion+schedule. These are bounded experiments, not an accepted production garment.+Detailed run data and meshes remain under ignored+`artifacts/local/garment/fit-resolution-round/`.++## Controlled fit and regional trials++All complete runs use 30 sewing frames, 60 fitting frames, a half-second T-to-A+transition, 60 wearing frames, eight substeps and 24 structural iterations.+Temporary supports release after 20 fitting frames. There are no permanent pins.+The acceptance limits remain 15% tensile strain, 10mm seam gap and 5mm sampled+body-clearance violation. Qualified checkpoints do not certify every intervening+surface or motion.++| Trial | Fitting strain | Midpoint strain | Wearing strain | Complete sequence |+| --- | ---: | ---: | ---: | --- |+| Retained control, 60mm mesh request | 22.309% | 22.372% | 9.228% | Fails |+| Collar plane lowered from shoulder +45mm to +15mm | 64.887% | 77.871% | 53.519% | Fails |+| Support sewn shoulder edges at the original height | 21.789% | 22.511% | 9.227% | Fails |+| Collar material region, original support | 22.596% | 22.960% | 9.201% | Fails |+| 30mm mesh request, original support | 19.558% | 19.666% | 20.450% | Fails |++The first row is the retained, source-bound control from the previous round. New+support trials change only the erased Concept guide or its named edge selection.+The shared rest/arrangement content key for the 60mm trials remains+`42C204F0BE495216B6CB3C2C3087EC8C786135D3EE71FE2D465BCFB4D468BA8B`.+Source hashes differ because guides, pose declarations and comments are separate+authoring context. Body artifact SHA-256 remains+`0a0ad03e86447fc56448940c7aa56b54ea6683e8a874f833e01fd56a65a2d0e5`.++The collar region selects a 48mm material-space band around the named collar+curves: 56 vertices and 121 modified structural stencils. Stretch compliance is+scaled by 0.25 and bending compliance by 4. Rest lengths, masses, seam compliance+and cross-region stencils remain unchanged. The complete regional run has exact+static/midpoint replay and releases all temporary guides. It is still rejected:+right-back armhole link 331/332, rest length 10.770mm, dominates fitting and motion.+No regional settings or support changes become defaults.++Denser geometry moves the dominant failure. At 30mm, link 54/55 on the left-back+armhole adjacent to the shoulder seam has rest length 19.736mm and reaches+20.450% wearing strain. Seam gap improves to 0.353mm, while sampled clearance+violation remains below 0.001mm. Improved sewing accuracy does not establish an+accepted material fit. More density is not a substitute for resolving that+local strain failure. Its concentration beside the shoulder seam suggests a+contact/structural conflict, but these trials do not isolate that causal mechanism.++`GarmentMeshInspection.StretchOutliers` now owns the shared structural diagnostic.+CLI evidence records named-panel/material-coordinate outliers at fitting,+midpoint and wearing checkpoints, rather than reporting only the final frame.++## Mesh quality and bounded startup cost++The mesher's interior lattice pitch is 80% of `meshSize`. Requests of 60, 30 and+15mm therefore produce median edges near 48, 24 and 12mm. The same analytic cut+is resampled, not resized; small rest-area differences come from curved boundary+chord approximation.++| Request | Vertices / triangles | Median edge | Minimum angle | Triangles below 10 degrees | Lumped area ratio | Five startup frames |+| --- | ---: | ---: | ---: | ---: | ---: | ---: |+| 60mm | 611 / 992 | 48mm | 10.33 degrees | 0 | 26.32 | 9.17s |+| 30mm | 1,944 / 3,486 | 24mm | 19.02 degrees | 0 | 15.32 | 20.55s |+| 15mm | 7,224 / 13,672 | 12mm | 19.01 degrees | 0 | 11.74 | 61.40s |++All have zero unused vertices. Rest areas are 0.804074, 0.803821 and 0.803607m².+The prefix probe uses the real T-pose body, temporary guide, solver, contact+queries and first five sewing compliance values. It is not a completed drape or+convergence test. Position/velocity replay agrees exactly. Fifth-frame strain is+51.54%, 93.70% and 98.28% respectively; these early sewing transients are not+qualification checkpoints.++Timing is a local observation including diagnostic samples, not a hardware or+continuum-material benchmark. Link compliance is an uncalibrated discrete+authoring control; keeping it fixed across resolutions does not establish equal+physical fabric stiffness. The complete 30mm run took about 641 seconds and+overlapped the independent regional trial. The 15mm complete sequence is not run:+its prefix costs roughly 6.7 times the coarse prefix, and the completed medium+trial worsens final strain. A longer, denser repetition has no established benefit.++## Optional presentation binding++`Aetheris.Cloth3D.ClothPresentationBinding3D.Compile(plan, levels)` constructs+deterministic sparse Loop interior stencils for zero, one or two refinement+levels. Material boundaries are fixed; inserted boundary vertices remain exact+linear samples. This includes sewn panel boundaries: the operation does not+weld them or hide measured seam gaps. Compiled weights retain original simulation+vertex correspondence and material coordinates. Budgets stop before exceeding+65,536 display vertices or 262,144 display triangles.++Evaluation accepts only a snapshot belonging to that compiled cloth key. It+produces a finer surface without changing physics, stored vertices, rest lengths,+constraints, contact geometry or qualification. In Aurelian:++```csharp+var artifact = ClothGarmentArtifact3D.Load("dress.garment.json");+var agent = ClothAgentDefinition3D.FromGarment(artifact).WithPresentation(2);+```++Compilation occurs in the explicit authoring call. Scene projection evaluates the+binding and normals without stepping the agent. It has a distinct presentation+identity, so display topology does not alias the original mesh. The current+presentation evaluator is CPU-based.++| Display levels | Vertices / triangles | Maximum sampled clearance violation | Sampled body penetration |+| --- | ---: | ---: | ---: |+| 0 | 611 / 992 | below 0.001mm | 0 |+| 1 | 2,210 / 3,968 | 1.648mm | 0 |+| 2 | 8,384 / 15,872 | 2.041mm | 0 |++Here clearance includes the authored body margin plus half cloth thickness;+body penetration uses half thickness only. The refined surface spends some of+that margin but does not enter the sampled body. This is a sampled diagnostic,+not an exhaustive intersection proof. On all three displays, simulation strain+remains 9.228% and seam gap remains 1.1325mm.++Front/side/back renders show a modest smoothing benefit. They still show the+projecting neckline, stiff silhouette and visible center seam. Refinement cannot+invent textile construction or fix the remaining physical fit. Blender presents+the engine-generated meshes with no additional fitting, subdivision or simulation.++## Regional material capability++`ClothDefinition3D.MaterialRegions` supplies disjoint named vertex sets with+finite stretch/bend compliance scales in `(0,1000]`. A structural constraint is+modified only when its whole stencil belongs to one region. Stitches retain+their own authored compliance. Empty, invalid, duplicate or overlapping regions+stop before simulation. Regional data enters the content key and garment+transport; definitions without regions preserve their established keys.++This is a typed C# capability. `schema Garment` still authors one shared Fabric;+no speculative regional Firmament syntax is introduced. The existing Vulkan+storage ABI receives the compiled compliance values without another shader path.++## Reproduction++Use the repository CLI and actual gameplay body. `control-30.firmament` is the+canonical guided source with only `meshSize: 60mm` replaced by `meshSize: 30mm`.+The lower collar trial replaces `shoulderHeight + 45mm` with `+15mm`. The shoulder+trial selects `left_ftorso.edges.edge3`, `right_ftorso.edges.edge2`,+`left_btorso.edges.edge2`, and `right_btorso.edges.edge3` instead of collar edges.++```powershell+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment drape `+ artifacts/local/garment/fit-resolution-round/control-30.firmament `+ --body artifacts/local/humanoid-production/antonia.gameplay-body.json `+ --ticks 60 --out-dir artifacts/local/garment/fit-resolution-round/control-30 --json++dotnet run -c Release scripts/experiment-garment-fit.cs -- prefix `+ fixtures/Canonical/Garment/garmentcode-dress-guided.firmament `+ artifacts/local/humanoid-production/antonia.gameplay-body.json `+ artifacts/local/garment/fit-resolution-round/prefix++dotnet run -c Release scripts/experiment-garment-fit.cs -- regions `+ fixtures/Canonical/Garment/garmentcode-dress-guided.firmament `+ artifacts/local/humanoid-production/antonia.gameplay-body.json `+ artifacts/local/garment/fit-resolution-round/regions-60+```++Presentation mode takes a matching source/body/output directory and reads+`input-garment.json` in that directory. It rejects a source-hash mismatch instead+of accepting a superficially similar source. The retained control uses its+original `armhole-round/anatolia-guided-transition.firmament` source, not the+later canonical source with different comments.++The tested scene projection remains distinct from native GPU body draping.+Fitting guides and triangle-body contacts remain CPU-only; no friction, CCD,+garment self-contact or physical fabric calibration is newly qualified.++## Validation++Both Release solution builds succeed. The complete Aetheris solution test run+passes 4,522 tests with test collections serialized; the complete Aurelian+solution passes 1,219 tests, including 28 cloth tests. Presentation tests exercise+actual scene compilation, mounting and projection without advancing simulation.+Regional tests cover transport round-trip, content identity, preserved rest+metrics and masses, seam exclusion, invalid selections and scalar GPU packing.++The first Aetheris run encountered the existing five-second CAD display deadline+in `MissingDisplayPatch_IsSeparateFromEngineering_WithSourceFaceIdentity`.+That test passes alone and in the serialized complete rerun. No CAD geometry,+test budgets or qualification limits were changed. The test-generated tracked+STEP witness was restored after validation.++The actual `Aurelian.GraphicsProof --cloth-systems` path compiles+`Cloth3D.v.ts` and runs Vulkan compute on NVIDIA GeForce RTX 3070. Its added+25-vertex regional case runs eight steps with a deformed initial surface;+maximum CPU/GPU position disagreement is 0.004554mm. Same-device position and+velocity replay agrees exactly. The full proof emits+`AURELIAN_CLOTH_SYSTEMS_PASSED`; detailed evidence remains in Copeland's ignored+`artifacts/local/garment-fit-round-vulkan/`.++This GPU result qualifies regional constraint execution, not Anatolia triangle-body+draping or GPU evaluation of the new presentation stencils. The complete garment+experiments all remain rejected by their unchanged fit gates. No commercial+geometry, textures, morphs or extracted assets are inputs to these experiments.diff --git a/docs/public/firmament/garment-surface-experiment.md b/docs/public/firmament/garment-surface-experiment.mdnew file mode 100644index 00000000..9f1e3a4c--- /dev/null+++ b/docs/public/firmament/garment-surface-experiment.md@@ -0,0 +1,128 @@+# Body-referenced quad garment experiment++The first surface-first specimen is a fitted skirt around the repository's+Anatolia gameplay body. It is authored in typed C# through+`GarmentSurfaceAuthoring.Skirt`, above the existing body-section and cloth+owners. This experiment does not introduce Firmament syntax yet.++```csharp+var body = HumanoidGameplayBody.Load("antonia.gameplay-body.json");+var skirt = GarmentSurfaceAuthoring.Skirt(+ new GarmentSkirtSurface("skirt", HipHeight: .96f, ChestHeight: 1.28f),+ body,+ new ClothMaterial3D+ {+ WarpCompliance = .001f,+ WeftCompliance = .004f,+ DiagonalCompliance = .002f,+ BendCompliance = .01f,+ });+File.WriteAllText("skirt.garment.json", skirt.Artifact());+```++Dimensions are metres. The declared section heights are the same as the+canonical Anatolia fitting specimen, not universal anatomical defaults.+Anatolia's pelvis joint height does not intersect one closed torso contour;+the section query rejects it. Callers may override section heights explicitly.+`HumanoidFigureFitting.Contour` exposes the ordered closed contour already+used by FigureFit, preserving open/ambiguous-section diagnostics.++The author declares waist height relative to the hip section, length, ease,+hem flare and resolution. The skirt interpolates radial envelopes of waist and+hip sections, then extends a flared envelope below the hip. This bridges the+legs rather than copying the body's surface. It uses no commercial geometry.+The waistband is an explicit ring of permanent attachments; there is no sewing+stage or hidden temporary fitting support.++## Material cells and rest conventions++`ClothDefinition3D.Surface` opts into authoritative four-corner cells:++- Each cell has its own metre material coordinates. The periodic skirt welds+ physical vertices while retaining material coordinates across the chart cut.+- A Q1 membrane uses 2x2 Gauss quadrature for lumped mass, warp/weft strain and+ shear. Compliance is inverse surface stiffness divided by quadrature area.+- Shared quad edges use objective signed rest-angle bending. There are no+ structural springs along the rendering diagonal.+- `FlatFabric` retains the flat material metric and zero rest hinge angles.+ `FittedSurface` derives a stress-free intrinsic metric and rest hinge angles+ from the supplied 3D shape. These are deliberately different physical models.+- Grain is a continuous rotation of material derivative operators. Rotating+ grain by a tiny angle does not relabel every edge as a diagonal spring.++Existing triangle/edge definitions remain available with their existing+content keys. Quad definitions append a versioned material-cell identity and+travel through `aetheris.garment.v1`; its runtime loader needs no Firmament+compiler. Invalid cells, inverted material Jacobians, inconsistent winding,+singular rest hinges and unsupported offset self-contact fail explicitly.++Triangles still lower the cells for rendering and existing sampled body+contact. Changing the display diagonal leaves quad masses, structural+constraints and contact-free simulation unchanged. Body-contact sampling and+presentation subdivision can still depend on that triangulation.++## Reproduce and inspect++```powershell+dotnet run -c Release scripts/experiment-garment-surface.cs -- `+ artifacts/local/humanoid-production/antonia.gameplay-body.json `+ artifacts/local/garment/surface-skirt++& 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe' `+ --background --python scripts/render-garment.py -- `+ --garment surface-skirt --input-dir artifacts/local/garment/surface-skirt `+ --engine workbench+```++The script writes the original quad OBJ, settled quad OBJ, runtime artifact,+body OBJ and numeric evidence under ignored `artifacts/local`. Blender presents+those exact exports without fitting, smoothing modifiers or simulation; render+evidence hashes its inputs.++The local 32x9 skirt has 288 vertices, 256 quads, 512 rendering triangles,+32 waistband attachments and no stitches. At frame 32 of the stationary-body+gravity experiment, maximum tensile stretch was 2.087%, maximum sampled+clearance violation was 0.040 mm, and attachment error was zero. Rest residual+was below 0.000004; eight zero-gravity frames drifted by 0.000362 mm. Both+checkpoint replay and runtime-artifact continuation were exact. The experiment+took approximately 2.3 seconds on this host; this is not a general performance+benchmark. Clearance includes cloth half-thickness plus the declared body gap;+it is a sampled diagnostic, not a global intersection proof.++The shared CPU/Vulkan patch proof exercises deformed flat and curved-rest quad+surfaces. On the local RTX 3070 the maximum CPU/GPU position differences were+0.00326 mm and 0.00405 mm respectively, with exact same-device rewind replay.+Body-surface contact remains CPU only. The GPU extension uses the existing+colored dispatch tape and source/state buffers, with transverse derivatives in+the previously reserved stencil-header word. Visual TypeScript's compute+`Atan2` intrinsic supplies the signed-angle calculation.++## What this result does and does not establish++This is a successful stationary fitted-skirt foundation and a useful+surface-authoring witness. It does not certify the earlier panel-authored dress.+It is not a recovered sewing pattern, measured textile model or production+garment. A stress-free fitted surface can have intrinsic curvature that no+single flat panel can reproduce without strain or cuts.++Animated legs, quad self-contact, inversion prevention, friction and calibrated+material response need separate qualification. Degenerate runtime hinges skip+their 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+declaration should be designed around these proven typed contracts rather than+silently treating fitted rest as flat fabric.++## Validation++Both Release solution builds passed. The full Aetheris suite passed 4,532 tests+with serial collection settings, the full Aurelian suite passed 1,220 tests,+and Copeland TS passed 1,497 tests. Ten new Aetheris cases cover grain continuity,+affine energy across resolution, triangulation independence, stress-free curved+rest, rigid transforms, finite-difference gradients, invalid inputs, body+contours, periodic garment topology and runtime artifact continuation. The+Aurelian scene test additionally covers curved rest through axis conversion,+placement, agent stepping and projection. The actual Vulkan proof passed on the+RTX 3070; its retained evidence is in Copeland's ignored+`artifacts/local/quad-cloth-systems` directory.diff --git a/docs/public/firmament/garments.md b/docs/public/firmament/garments.mdindex 739b9dab..5e0fdc68 100644--- a/docs/public/firmament/garments.md+++ b/docs/public/firmament/garments.md@@ -452,3 +452,18 @@ diagnostic specimen.See [GarmentCode import and templates](garmentcode.md) for the MIT-creditedshirt/dress reference, editable Firmament import, native hem customization andseparate pattern-versus-drape qualification.++## Fit, resolution and presentation experiments++See [the controlled fit/resolution round](garment-fit-resolution-experiment.md)+for named checkpoint strain diagnostics, opt-in presentation bindings and typed+regional compliance. The canonical cut and acceptance limits remain unchanged;+the complete garment dressing sequence is still unqualified.++## Body-referenced quad surfaces++See [the surface-first skirt experiment](garment-surface-experiment.md) for+typed body-contour authoring, explicit flat/fitted rest conventions and the+shared CPU/Vulkan quad material path. The stationary skirt is qualified+separately from the earlier panel dress; flattening and animated-body fit remain+future experiments.diff --git a/scripts/experiment-garment-fit.cs b/scripts/experiment-garment-fit.csnew file mode 100644index 00000000..2d448b35--- /dev/null+++ b/scripts/experiment-garment-fit.cs@@ -0,0 +1,268 @@+#:project ../Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj+#:property PublishAot=false+#:property JsonSerializerIsReflectionEnabledByDefault=true+// Experiments use the real authoring compiler, cloth compiler, solver and body queries.+// No commercial inputs. Rest lengths, masses, seams and qualification limits are retained.+using System.Collections.Immutable;+using System.Diagnostics;+using System.Numerics;+using System.Security.Cryptography;+using System.Text;+using System.Text.Json;+using Aetheris.Cloth3D;+using Aetheris.Humanoid;+using Aetheris.Kernel.Firmament.Garment;+using Aetheris.Kernel.Firmament.Humanoid;++if (args.Length != 4 || args[0] is not ("prefix" or "presentation" or "regions"))+{+ throw new ArgumentException("dotnet run -c Release scripts/experiment-garment-fit.cs -- prefix|presentation|regions source.firmament body.json output-directory");+}+string mode = args[0];+string sourcePath = Path.GetFullPath(args[1]);+string bodyPath = Path.GetFullPath(args[2]);+string output = Path.GetFullPath(args[3]);+Directory.CreateDirectory(output);+var json = new JsonSerializerOptions { IncludeFields = true, WriteIndented = true };+string source = File.ReadAllText(sourcePath);+string bodyHash = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(bodyPath)));+var body = HumanoidGameplayBody.Load(bodyPath);+var binding = new GarmentFigureBinding("Anatolia", body, bodyHash);+var garment = Compile(source, sourcePath);++if (mode == "prefix")+{+ if (!source.Contains("meshSize: 60mm;", StringComparison.Ordinal))+ {+ throw new ArgumentException("The controlled prefix comparison requires an explicit 60mm baseline meshSize.");+ }+ var results = new List<object>();+ foreach (int size in new[] { 60, 30, 15 })+ {+ var variant = Compile(source.Replace("meshSize: 60mm;", $"meshSize: {size}mm;"), sourcePath + "/mesh-" + size);+ var surface = PosedSurface(variant.Source.Pose!);+ var contacts = new ClothContacts3D+ {+ BodySurface = surface,+ BodyClearance = variant.Source.BodyClearance,+ Guides = variant.FittingGuides.Select(guide => guide.Constraint).ToImmutableArray(),+ };+ using var solver = new ClothSolver3D(variant.Cloth);+ var watch = Stopwatch.StartNew();+ Console.Error.WriteLine($"meshSize={size}mm: {variant.Cloth.Definition.Positions.Length} vertices, five sewing frames");+ var frames = new List<object>();+ for (int stage = 0; stage < 5; stage++)+ {+ solver.Step(new()+ {+ Gravity = Vector3.Zero, Substeps = 8, Iterations = 24, ContactIterations = 1,+ VelocityDamping = 8, StitchComplianceScale = MathF.Pow(10, 6 * (1 - stage / 29f)),+ }, contacts);+ var snapshot = solver.Capture();+ frames.Add(new { frame = stage + 1, metrics = ClothState3D.Measure(variant.Cloth, snapshot, contacts),+ seamGap = variant.MaximumSeamGap(snapshot), elapsedSeconds = watch.Elapsed.TotalSeconds });+ }+ var final = solver.Capture();+ var options = new ClothStepOptions3D { Gravity = Vector3.Zero, Substeps = 8, Iterations = 24, ContactIterations = 1 };+ solver.Step(options, contacts);+ var expected = solver.Capture();+ solver.Restore(final);+ solver.Step(options, contacts);+ var actual = solver.Capture();+ bool replay = expected.Positions.SequenceEqual(actual.Positions) && expected.Velocities.SequenceEqual(actual.Velocities);+ File.WriteAllText(Path.Combine(output, $"prefix-{size}.obj"), GarmentExport.Obj(variant, final));+ results.Add(new { meshSizeMm = size, vertices = variant.Cloth.Definition.Positions.Length,+ triangles = variant.Cloth.Definition.Indices.Length / 3, variant.Cloth.ContentKey,+ meshQuality = GarmentMeshInspection.Measure(variant), restAreaM2 = RestArea(variant.Cloth.Definition),+ frames, replayExact = replay, qualifiedDrape = false,+ reason = "Five-frame startup/cost probe, not a completed sewing or wearing sequence" });+ WriteJson("prefix-results.json", new { bodyHash, sourceHash = garment.Source.SourceHash, results });+ }+}+else if (mode == "regions")+{+ int[] vertices = BoundaryBand(garment, "collar", .048f);+ var definition = garment.Cloth.Definition with+ {+ MaterialRegions = [new("collar-band-48mm", vertices.ToImmutableArray(), .25f, 4)],+ };+ var tuned = garment with { Cloth = definition.Compile() };+ int changed = garment.Cloth.Constraints.Zip(tuned.Cloth.Constraints)+ .Count(pair => pair.First.Compliance != pair.Second.Compliance);+ if (changed == 0)+ {+ throw new InvalidOperationException("Experiment region selected no structural stencils.");+ }+ var drape = GarmentDraping.Settle(tuned, body, 60,+ progress => Console.Error.WriteLine($"regional {progress.Phase}: {progress.Completed}/{progress.Total} ({progress.ElapsedSeconds:F1}s)"));+ Export(tuned, drape);+ WriteJson("region-results.json", new+ {+ bodyHash, sourceHash = garment.Source.SourceHash, baselineKey = garment.Cloth.ContentKey,+ tunedKey = tuned.Cloth.ContentKey, selectedVertices = vertices.Length, changedConstraints = changed,+ overrides = definition.MaterialRegions, drape.Metrics, drape.MaximumSeamGap,+ drape.ReplayExact, drape.TransitionReplayExact, drape.GuidesReleased,+ frames = drape.Frames.Select(frame => new { frame.Name, frame.Metrics, frame.MaximumSeamGap, frame.StretchOutliers }),+ accepted = drape.ReplayExact && drape.TransitionReplayExact && drape.GuidesReleased+ && GarmentDrapeLimits.Accept(drape.Metrics, drape.MaximumSeamGap)+ && drape.Frames.All(frame => frame.BodyEvidence.IsAdmissible+ && GarmentDrapeLimits.Accept(frame.Metrics, frame.MaximumSeamGap)),+ });+}+else+{+ string retainedPath = Path.Combine(output, "input-garment.json");+ var retained = ClothGarmentArtifact3D.Load(retainedPath);+ if (retained.SourceHash != garment.Source.SourceHash || retained.Cloth.ContentKey != garment.Cloth.ContentKey)+ {+ throw new InvalidDataException("Presentation input must match the supplied source and cloth definition.");+ }+ var snapshot = retained.Settled ?? throw new InvalidDataException("Presentation needs a retained solver snapshot.");+ string finalPose = garment.Source.Transition is { } transition+ ? garment.Source.Posing!.Transitions[transition].To : garment.Source.Pose!;+ var finalRecipe = garment.Source.Posing!.Resolve(finalPose, "Anatolia");+ var finalPositions = body.EvaluatePositions(HumanoidPoseAuthoring.Solve(finalRecipe, body));+ var surface = GarmentDraping.BodySurface(body, finalPositions);+ File.WriteAllText(Path.Combine(output, "body.obj"), GarmentExport.BodyObj(body, finalPositions));+ var contacts = new ClothContacts3D { BodySurface = surface, BodyClearance = garment.Source.BodyClearance };+ var results = new List<object>();+ foreach (int levels in new[] { 0, 1, 2 })+ {+ var watch = Stopwatch.StartNew();+ var presentation = ClothPresentationBinding3D.Compile(garment.Cloth, levels);+ double compileMs = watch.Elapsed.TotalMilliseconds;+ watch.Restart();+ var mesh = presentation.Evaluate(snapshot);+ double evaluateMs = watch.Elapsed.TotalMilliseconds;+ float maximumClearanceViolation = 0;+ float maximumBodyPenetration = 0;+ float halfThickness = garment.Cloth.Definition.Material.Thickness * .5f;+ float clearance = halfThickness + contacts.BodyClearance;+ foreach (Vector3 point in mesh.Positions)+ {+ MeasurePoint(point);+ }+ for (int face = 0; face < mesh.Indices.Length; face += 3)+ {+ foreach (Vector3 barycentric in ClothBodyContact3D.Samples)+ {+ Vector3 point = mesh.Positions[mesh.Indices[face]] * barycentric.X+ + mesh.Positions[mesh.Indices[face + 1]] * barycentric.Y+ + mesh.Positions[mesh.Indices[face + 2]] * barycentric.Z;+ MeasurePoint(point);+ }+ }+ File.WriteAllText(Path.Combine(output, $"presentation-{levels}.obj"), MeshObj(mesh));+ results.Add(new { levels, vertices = mesh.Positions.Length, triangles = mesh.Indices.Length / 3,+ compileMs, evaluateMs, maximumSampledPresentationClearanceViolation = maximumClearanceViolation,+ maximumSampledPresentationBodyPenetration = maximumBodyPenetration,+ simulationMetrics = ClothState3D.Measure(garment.Cloth, snapshot, contacts),+ simulationSeamGap = garment.MaximumSeamGap(snapshot), simulationKey = presentation.SourceContentKey });++ void MeasurePoint(Vector3 point)+ {+ float distance = surface.Query(point).SignedDistance;+ maximumClearanceViolation = MathF.Max(maximumClearanceViolation, clearance - distance);+ maximumBodyPenetration = MathF.Max(maximumBodyPenetration, halfThickness - distance);+ }+ }+ WriteJson("presentation-results.json", new { bodyHash, sourceHash = garment.Source.SourceHash,+ inputHash = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(retainedPath))), results,+ limits = new[] { "Presentation stencils only", "Original material boundaries preserved",+ "Sampled visible contact is diagnostic, not exhaustive certification", "No changes to solver state" } });+}++CompiledGarment Compile(string text, string identity)+{+ var result = GarmentCompiler.Compile(text, identity, binding);+ if (!result.IsSuccess)+ {+ throw new InvalidDataException(string.Join("; ", result.Diagnostics));+ }+ return result.Garment!;+}++ClothTriangleBody3D PosedSurface(string name)+{+ var recipe = garment.Source.Posing!.Resolve(name, "Anatolia");+ var pose = HumanoidPoseAuthoring.Solve(recipe, body);+ return GarmentDraping.BodySurface(body, body.EvaluatePositions(pose));+}++void WriteJson(string name, object value)+{+ File.WriteAllText(Path.Combine(output, name), JsonSerializer.Serialize(value, json));+}++void Export(CompiledGarment compiled, GarmentDrapeResult drape)+{+ File.WriteAllText(Path.Combine(output, "garment.json"), GarmentExport.Artifact(compiled, drape.Snapshot));+ File.WriteAllText(Path.Combine(output, "garment.obj"), GarmentExport.Obj(compiled, drape.Snapshot));+ File.WriteAllText(Path.Combine(output, "body.obj"), GarmentExport.BodyObj(body, drape.BodyPositions));+}++static double RestArea(ClothDefinition3D definition)+{+ double area = 0;+ for (int face = 0; face < definition.Indices.Length; face += 3)+ {+ Vector3 a = definition.Positions[definition.Indices[face]];+ Vector3 b = definition.Positions[definition.Indices[face + 1]];+ Vector3 c = definition.Positions[definition.Indices[face + 2]];+ area += Vector3.Cross(b - a, c - a).Length() * .5;+ }+ return area;+}++static int[] BoundaryBand(CompiledGarment compiled, string name, float width)+{+ var definition = compiled.Cloth.Definition;+ var selected = new List<int>();+ foreach (var panel in compiled.Panels)+ {+ var edges = panel.Edges.Where(entry => entry.Key.Contains(name, StringComparison.Ordinal)).ToArray();+ for (int vertex = panel.VertexStart; vertex < panel.VertexStart + panel.VertexCount; vertex++)+ {+ Vector3 point = definition.Positions[vertex];+ bool inside = false;+ foreach (var edge in edges)+ {+ for (int index = 0; index + 1 < edge.Value.Length; index++)+ {+ Vector3 a = definition.Positions[edge.Value[index]];+ Vector3 b = definition.Positions[edge.Value[index + 1]];+ Vector3 ab = b - a;+ float fraction = Math.Clamp(Vector3.Dot(point - a, ab) / ab.LengthSquared(), 0, 1);+ if (Vector3.Distance(point, a + ab * fraction) <= width)+ {+ inside = true;+ break;+ }+ }+ if (inside)+ {+ break;+ }+ }+ if (inside)+ {+ selected.Add(vertex);+ }+ }+ }+ return selected.ToArray();+}++static string MeshObj(ClothPresentationMesh3D mesh)+{+ var text = new StringBuilder("# Aetheris compiled presentation stencils; not a simulated collision mesh\n");+ foreach (Vector3 point in mesh.Positions)+ {+ text.AppendLine(FormattableString.Invariant($"v {point.X:R} {point.Y:R} {point.Z:R}"));+ }+ for (int face = 0; face < mesh.Indices.Length; face += 3)+ {+ text.AppendLine($"f {mesh.Indices[face] + 1} {mesh.Indices[face + 1] + 1} {mesh.Indices[face + 2] + 1}");+ }+ return text.ToString();+}diff --git a/scripts/experiment-garment-surface.cs b/scripts/experiment-garment-surface.csnew file mode 100644index 00000000..134a39e6--- /dev/null+++ b/scripts/experiment-garment-surface.cs@@ -0,0 +1,91 @@+#:project ../Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj+#:property PublishAot=false+#:property JsonSerializerIsReflectionEnabledByDefault=true+using System.Collections.Immutable;+using System.Diagnostics;+using System.Numerics;+using System.Text.Json;+using Aetheris.Cloth3D;+using Aetheris.Humanoid;+using Aetheris.Kernel.Firmament.Garment;++if (args.Length != 2)+{+ throw new ArgumentException("dotnet run -c Release scripts/experiment-garment-surface.cs -- body.json output-directory");+}+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 };+// Same declared body section heights as the canonical Anatolia fitting specimen.+var garment = GarmentSurfaceAuthoring.Skirt(new("surface-skirt", HipHeight: .96f, ChestHeight: 1.28f), body, new()+{+ WarpCompliance = .001f, WeftCompliance = .004f, DiagonalCompliance = .002f, BendCompliance = .01f,+});+var contacts = new ClothContacts3D+{+ BodySurface = GarmentDraping.BodySurface(body), BodyClearance = .004f,+};+using var solver = new ClothSolver3D(garment.Cloth);+var initial = solver.Capture();+var initialMetrics = ClothState3D.Measure(garment.Cloth, initial, contacts);+File.WriteAllText(Path.Combine(output, "initial-garment.obj"), garment.Obj(initial));+File.WriteAllText(Path.Combine(output, "body.obj"), GarmentExport.BodyObj(body));+float initialResidual = garment.Cloth.Constraints+ .Where(constraint => constraint.Kind is ClothConstraintKind3D.SurfaceWarp or ClothConstraintKind3D.SurfaceWeft+ or ClothConstraintKind3D.SurfaceShear or ClothConstraintKind3D.SurfaceBend)+ .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 watch = Stopwatch.StartNew();+var frames = new List<object>();+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(new { frame = frame + 1, metrics });+ Console.Error.WriteLine($"surface frame {frame + 1}: {watch.Elapsed.TotalSeconds:F1}s, stretch {metrics.MaximumStretch:P2}");+ }+}+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 finalMetrics = ClothState3D.Measure(garment.Cloth, settled, contacts);+string artifact = garment.Artifact(settled);+var retained = ClothGarmentArtifact3D.Parse(artifact);+using var resumed = retained.CreateSolver();+resumed.Step(options, contacts);+bool artifactReplay = resumed.Capture().Positions.SequenceEqual(expected.Positions);+bool accepted = initialResidual < .0001f && restDrift < .0001f && replayExact && artifactReplay+ && finalMetrics.Finite && finalMetrics.MaximumStretch <= .15f+ && finalMetrics.MaximumSurfacePenetration <= .005f && finalMetrics.MaximumPinError < .0001f;+File.WriteAllText(Path.Combine(output, "garment.obj"), garment.Obj(settled));+File.WriteAllText(Path.Combine(output, "garment.json"), artifact);+File.WriteAllText(Path.Combine(output, "evidence.json"), JsonSerializer.Serialize(new+{+ accepted, source = garment.Source, figure = garment.Figure, garment.SourceHash, garment.Cloth.ContentKey,+ vertices = garment.Cloth.Definition.Positions.Length, quads = garment.Cloth.Definition.Surface!.Quads.Length,+ rendererTriangles = garment.Cloth.Definition.Indices.Length / 3, waistbandPins = garment.Waist.Length,+ stitches = garment.Cloth.Definition.Stitches.Length, initialResidual, restDrift, initialMetrics, finalMetrics,+ replayExact, artifactReplay, elapsedSeconds = watch.Elapsed.TotalSeconds, frames,+ qualified = "Stationary body, fitted skirt rest, explicit waistband attachments, 32 gravity frames",+ selfCollisionQualified = false, flatPatternQualified = false, animatedBodyQualified = false,+}, json));+Console.WriteLine(accepted ? "GARMENT_SURFACE_SKIRT_PASSED" : "GARMENT_SURFACE_SKIRT_NOT_QUALIFIED");+return accepted ? 0 : 1;+diff --git a/scripts/render-garment.py b/scripts/render-garment.pyindex eff457a7..fffa8d80 100644--- a/scripts/render-garment.py+++ b/scripts/render-garment.py@@ -15,6 +15,7 @@ from mathutils import Vectordef material(name, color, roughness):result = bpy.data.materials.new(name)+ result.diffuse_color = (*color, 1)result.use_nodes = Trueshader = result.node_tree.nodes.get("Principled BSDF")shader.inputs["Base Color"].default_value = (*color, 1)@@ -48,6 +49,8 @@ def main():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("--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.")parser.add_argument("--frame", choices=("guided", "fitting", "midway", "wearing"), help="Render a retained solver checkpoint.")options = parser.parse_args(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])source = options.root / "artifacts/local/garment"@@ -79,9 +82,20 @@ def main():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- scene.render.engine = "CYCLES"- scene.cycles.samples = options.samples- scene.cycles.use_denoising = True+ if options.engine == "workbench":+ scene.render.engine = "BLENDER_WORKBENCH"+ scene.display.render_aa = "32"+ shading = scene.display.shading+ shading.light = "STUDIO"+ shading.color_type = "MATERIAL"+ shading.show_shadows = False+ shading.show_cavity = False+ shading.background_type = "WORLD"+ scene.world.color = (.24, .26, .29)+ else:+ scene.render.engine = "CYCLES"+ scene.cycles.samples = options.samples+ scene.cycles.use_denoising = Truescene.render.resolution_x = 800scene.render.resolution_y = 1000scene.render.resolution_percentage = 100@@ -122,6 +136,7 @@ def main():"garment": options.garment or options.bottom,"frame": options.frame,"textures": False,+ "renderer": options.engine,}(output / "render-evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")