Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add garment authoring support to Firmament CLI and language services
Yuechen Li1cd817f0a311
diff --git a/Aetheris.CLI.Tests/GarmentCommandTests.cs b/Aetheris.CLI.Tests/GarmentCommandTests.csnew file mode 100644index 00000000..3b915cc6--- /dev/null+++ b/Aetheris.CLI.Tests/GarmentCommandTests.cs@@ -0,0 +1,39 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class GarmentCommandTests+{+ [Fact]+ public void RealSchemaRoutesThroughValidateInspectBuildAndLanguageFormatting()+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx")))+ {+ root = root.Parent;+ }+ Assert.NotNull(root);+ string input = Path.Combine(root!.FullName, "fixtures/Canonical/Garment/skirt.firmament");+ string output = Path.Combine(root.FullName, "artifacts/local/tests/garment", Guid.NewGuid().ToString("N"));+ foreach (string command in new[] { "validate", "inspect" })+ {+ var stdout = new StringWriter();+ var stderr = new StringWriter();+ Assert.True(CliRunner.Run([command, input, "--json"], stdout, stderr) == 0, stderr.ToString());+ using var report = JsonDocument.Parse(stdout.ToString());+ Assert.True(report.RootElement.GetProperty("success").GetBoolean());+ Assert.Equal("Garment", report.RootElement.GetProperty("domain").GetString());+ }+ var buildOutput = new StringWriter();+ var errors = new StringWriter();+ Assert.True(CliRunner.Run(["garment", "build", input, "--out-dir", output, "--json"], buildOutput, errors) == 0, errors.ToString());+ foreach (string file in new[] { "garment.json", "garment.obj", "garment.usda", "patterns.svg", "evidence.json" })+ Assert.True(new FileInfo(Path.Combine(output, file)).Length > 0, file);+ using var artifact = JsonDocument.Parse(File.ReadAllText(Path.Combine(output, "garment.json")));+ Assert.Equal("aetheris.garment.v1", artifact.RootElement.GetProperty("schema").GetString());+ Assert.NotEqual(0, CliRunner.Run(["build", input], new StringWriter(), errors));+ Assert.Contains("garment-step-export-unsupported", errors.ToString());+ Assert.NotEqual(0, CliRunner.Run(["garment", "drape", input], new StringWriter(), errors));+ Assert.Contains("garment-body-required", errors.ToString());+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 89f4ccc1..215faaf1 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -237,6 +237,7 @@ public static class CliRunner"trace" => RunTrace(args.Skip(1).ToArray(), stdout, stderr),"canon" => RunCanon(args.Skip(1).ToArray(), stdout, stderr),"asm" => RunAsm(args.Skip(1).ToArray(), stdout, stderr),+ "garment" => GarmentCommand.Run(args.Skip(1).ToArray(), stdout, stderr),"scene" => SceneCommand.Run(args.Skip(1).ToArray(), stdout, stderr),"experimental" => RunExperimental(args.Skip(1).ToArray(), stdout, stderr),"modules" => RunModules(args.Skip(1).ToArray(), stdout, stderr),@@ -489,6 +490,8 @@ public static class CliRunnerif (File.Exists(sourcePath)){var source = File.ReadAllText(sourcePath);+ if (Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(source))+ { stderr.WriteLine("garment-step-export-unsupported: Fabric is a material-space surface; use garment build or garment drape."); return 1; }if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(source)){ stderr.WriteLine("scene-step-export-unsupported: Scene is a spatial product; use scene export-usd or scene export-glb."); return 1; }if (Path.GetExtension(sourcePath).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(source))@@ -1405,6 +1408,8 @@ Model CanonicalPanel {}var input = args[0];+ if (File.Exists(input) && Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(File.ReadAllText(input)))+ return GarmentCommand.Run(["inspect", .. args], stdout, stderr);if (File.Exists(input) && Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(File.ReadAllText(input)))return SceneCommand.Run(["inspect", .. args], stdout, stderr);if (File.Exists(input) && (Path.GetExtension(input).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(File.ReadAllText(input))))@@ -2324,6 +2329,9 @@ Model CanonicalPanel {}var validationSource=File.ReadAllText(sourcePath);+ if (Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(validationSource)+ || FirmamentFrontendSchemas.Select(validationSource).Schema == FirmamentFrontendSchema.Garment)+ return GarmentCommand.Run(["inspect", sourcePath, .. (json ? new[] { "--json" } : Array.Empty<string>())], stdout, stderr);if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(validationSource)){var scene = Aetheris.Kernel.Firmament.Scene.SceneAuthoring.Parse(validationSource,Path.GetFullPath(sourcePath));@@ -5047,6 +5055,7 @@ Model CanonicalPanel {stdout.WriteLine(" drawing Compile production drawings or inspect/highlight PDFs with source-linked Drawing Notes.");stdout.WriteLine(" asm Inspect, execute, import, and export Firmament V2 assemblies.");stdout.WriteLine(" scene Inspect spatial scenes and export OpenUSD or GLB.");+ stdout.WriteLine(" garment Compile panels and stitches, export patterns, and drape on a humanoid.");stdout.WriteLine(" modules Inspect built-in engineering Modules and capabilities.");stdout.WriteLine(" sheetmetal Inspect/recover sheet semantics and generate manufacturing flat-pattern SVG.");stdout.WriteLine(" sculpture Build bounded non-manufacturing virtual sculpture artifacts.");diff --git a/Aetheris.CLI/GarmentCommand.cs b/Aetheris.CLI/GarmentCommand.csnew file mode 100644index 00000000..ec9af2ee--- /dev/null+++ b/Aetheris.CLI/GarmentCommand.cs@@ -0,0 +1,128 @@+using System.Diagnostics;+using System.Text;+using System.Text.Json;+using Aetheris.Humanoid;+using Aetheris.Kernel.Firmament.Garment;++namespace Aetheris.CLI;++internal static class GarmentCommand+{+ internal const string Usage = "aetheris garment <inspect|build|drape> <garment.firmament> [--body gameplay-body.json] [--ticks 1..600] [--out-dir directory] [--json]";++ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0 || args[0] is "--help" or "-h")+ {+ stdout.WriteLine(Usage);+ return args.Length == 0 ? 1 : 0;+ }+ try+ {+ if (args.Length < 2 || args[0] is not ("inspect" or "build" or "drape")) throw new ArgumentException(Usage);+ string operation = args[0];+ string input = Path.GetFullPath(args[1]);+ bool json = false;+ string? bodyPath = null;+ string? outputDirectory = null;+ int ticks = 60;+ for (int i = 2; i < args.Length; i++)+ {+ switch (args[i])+ {+ case "--json": json = true; break;+ case "--body" when i + 1 < args.Length: bodyPath = Path.GetFullPath(args[++i]); break;+ case "--out-dir" when i + 1 < args.Length: outputDirectory = Path.GetFullPath(args[++i]); break;+ case "--ticks" when i + 1 < args.Length && int.TryParse(args[++i], out ticks) && ticks is >= 1 and <= 600: break;+ default: throw new ArgumentException("Unknown or incomplete garment option: " + args[i]);+ }+ }+ if (operation != "drape" && (bodyPath is not null || ticks != 60)) throw new ArgumentException("--body and --ticks belong to garment drape.");+ if (operation == "inspect" && outputDirectory is not null) throw new ArgumentException("inspect does not write output.");+ var watch = Stopwatch.StartNew();+ var compiled = GarmentCompiler.Compile(File.ReadAllText(input), input);+ if (!compiled.IsSuccess)+ {+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, domain = "Garment", diagnostics = compiled.Diagnostics }, CliRunner.JsonOptions));+ else foreach (var diagnostic in compiled.Diagnostics) stderr.WriteLine(diagnostic.Code + ": " + diagnostic.Message);+ return 1;+ }+ var garment = compiled.Garment!;+ GarmentDrapeResult? drape = null;+ HumanoidGameplayBody? body = null;+ if (operation == "drape")+ {+ if (bodyPath is null) throw new ArgumentException("garment-body-required: Bind the declared figure with --body gameplay-body.json.");+ body = HumanoidGameplayBody.Load(bodyPath);+ drape = GarmentDraping.Settle(garment, body, ticks);+ }+ if (operation != "inspect")+ {+ outputDirectory ??= Path.GetFullPath(Path.Combine("artifacts", "local", "garment", Path.GetFileNameWithoutExtension(input)));+ string[] names = ["garment.json", "garment.obj", "garment.usda", "patterns.svg", "body.obj", "evidence.json"];+ if (names.Select(name => Path.Combine(outputDirectory, name)).Any(path => path.Equals(input, StringComparison.OrdinalIgnoreCase)+ || path.Equals(bodyPath, StringComparison.OrdinalIgnoreCase)))+ {+ throw new ArgumentException("Garment output must not replace an input artifact.");+ }+ Directory.CreateDirectory(outputDirectory);+ Write("garment.json", GarmentExport.Artifact(garment, drape?.Snapshot));+ Write("garment.obj", GarmentExport.Obj(garment, drape?.Snapshot));+ Write("garment.usda", GarmentExport.Usd(garment, drape?.Snapshot));+ Write("patterns.svg", GarmentExport.PatternsSvg(garment));+ if (body is not null) Write("body.obj", GarmentExport.BodyObj(body));+ }+ bool qualified = drape is null || (drape.Metrics.Finite && drape.ReplayExact+ && drape.MaximumSeamGap <= .01f && drape.Metrics.MaximumSurfacePenetration <= .005f+ && drape.Metrics.MaximumStretch <= .15f);+ var report = new+ {+ success = qualified,+ domain = "Garment",+ name = garment.Source.Name,+ garment.Source.SourceHash,+ garment.Cloth.ContentKey,+ units = "m",+ upAxis = "Z",+ vertices = garment.Cloth.Definition.Positions.Length,+ triangles = garment.Cloth.Definition.Indices.Length / 3,+ pins = garment.Cloth.Definition.Pins.Length,+ seamConstraints = garment.Cloth.Definition.Stitches.Length,+ panels = garment.Panels.Select(panel => new { panel.Identity, panel.VertexCount, edges = panel.Edges.Keys }),+ features = garment.Source.Features,+ patterns = garment.Source.Patterns,+ drape = drape is null ? null : new+ {+ settleTicks = ticks,+ sewingTicks = 30,+ snapshotTick = drape.Snapshot.Tick,+ bodyArtifactHash = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(bodyPath!))),+ drape.BodyId,+ drape.BodyTopology,+ drape.InitialSeamGap,+ drape.MaximumSeamGap,+ drape.Metrics,+ drape.ReplayExact,+ drape.ContactOutliers,+ drape.StretchOutliers,+ qualification = qualified ? "passed" : "failed; inspect the retained geometry and metrics",+ limits = new[] { "Static Rest pose", "Explicit authored supports", "Discrete oriented body contact", "No CCD, friction or garment self-contact", "CPU body-contact backend" },+ },+ outputDirectory,+ elapsedMilliseconds = watch.Elapsed.TotalMilliseconds,+ };+ string evidence = JsonSerializer.Serialize(report, CliRunner.JsonOptions);+ if (outputDirectory is not null) Write("evidence.json", evidence);+ stdout.WriteLine(json ? evidence : $"Garment {garment.Source.Name}: {report.vertices} vertices, {report.triangles} triangles, {report.seamConstraints} seam constraints; "+ + (qualified ? "passed" : "drape qualification failed") + (outputDirectory is null ? "." : "; artifacts: " + outputDirectory));+ return qualified ? 0 : 2;++ void Write(string name, string text) => File.WriteAllText(Path.Combine(outputDirectory!, name), text, new UTF8Encoding(false));+ }+ catch (Exception exception) when (exception is IOException or ArgumentException or InvalidOperationException or NotSupportedException)+ {+ stderr.WriteLine("garment-command-failed: " + exception.Message);+ return 1;+ }+ }+}diff --git a/Aetheris.Cloth3D/Aetheris.Cloth3D.csproj b/Aetheris.Cloth3D/Aetheris.Cloth3D.csprojnew file mode 100644index 00000000..45966fb6--- /dev/null+++ b/Aetheris.Cloth3D/Aetheris.Cloth3D.csproj@@ -0,0 +1,11 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <Description>Shared deterministic cloth topology, constraints and CPU reference solver.</Description>+ </PropertyGroup>+ <ItemGroup>+ <ProjectReference Include="../Aetheris.Kernel.Core/Aetheris.Kernel.Core.csproj" />+ </ItemGroup>+</Project>diff --git a/Aetheris.Cloth3D/ClothBodyContact3D.cs b/Aetheris.Cloth3D/ClothBodyContact3D.csnew file mode 100644index 00000000..dc8aaae3--- /dev/null+++ b/Aetheris.Cloth3D/ClothBodyContact3D.cs@@ -0,0 +1,16 @@+using System.Collections.Immutable;+using System.Numerics;++namespace Aetheris.Cloth3D;++/// <summary>Bounded barycentric surface contacts. These include edge midpoints and+/// triangle interiors, but remain discrete samples rather than a CCD/intersection certificate.</summary>+public static class ClothBodyContact3D+{+ public static ImmutableArray<Vector3> Samples { get; } =+ [+ new(.5f, .5f, 0), new(0, .5f, .5f), new(.5f, 0, .5f),+ new(1f / 3, 1f / 3, 1f / 3),+ new(2f / 3, 1f / 6, 1f / 6), new(1f / 6, 2f / 3, 1f / 6), new(1f / 6, 1f / 6, 2f / 3),+ ];+}diff --git a/Aetheris.Cloth3D/ClothBodySurface3D.cs b/Aetheris.Cloth3D/ClothBodySurface3D.csnew file mode 100644index 00000000..aa994138--- /dev/null+++ b/Aetheris.Cloth3D/ClothBodySurface3D.cs@@ -0,0 +1,186 @@+using System.Collections.Immutable;+using System.Numerics;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Cloth3D;++public readonly record struct ClothBodySample3D(Vector3 Point, Vector3 Normal, float SignedDistance);++public interface IClothBodySurface3D+{+ ClothBodySample3D Query(Vector3 position);+}++/// <summary>Immutable pose snapshot with a nearest-triangle BVH. Outward triangle winding+/// is a caller contract. This is a discrete oriented surface query, not a watertight SDF or CCD.</summary>+public sealed class ClothTriangleBody3D : IClothBodySurface3D+{+ private readonly Vector3[] positions;+ private readonly Vector3[] normals;+ private readonly int[] indices;+ private readonly int[] triangles;+ private readonly List<Node> nodes = [];++ private sealed record Node(Vector3 Minimum, Vector3 Maximum, int Start, int Count, int Left, int Right);++ public ClothTriangleBody3D(ImmutableArray<Vector3> positions, ImmutableArray<int> indices)+ {+ if (positions.IsDefaultOrEmpty || indices.IsDefaultOrEmpty || indices.Length % 3 != 0+ || indices.Any(index => index < 0 || index >= positions.Length))+ {+ throw new ArgumentException("Body surface requires finite vertices and indexed outward triangles.");+ }+ foreach (var position in positions)+ {+ ClothValidation3D.Finite(position);+ }+ this.positions = positions.ToArray();+ this.indices = indices.ToArray();+ normals = new Vector3[positions.Length];+ for (int face = 0; face < indices.Length; face += 3)+ {+ int a = indices[face];+ int b = indices[face + 1];+ int c = indices[face + 2];+ Vector3 normal = Vector3.Cross(positions[b] - positions[a], positions[c] - positions[a]);+ if (normal.LengthSquared() <= 1e-20f)+ {+ throw new ArgumentException("Body surface has a degenerate triangle.");+ }+ normals[a] += normal;+ normals[b] += normal;+ normals[c] += normal;+ }+ for (int vertex = 0; vertex < normals.Length; vertex++)+ {+ if (normals[vertex].LengthSquared() > 1e-20f)+ {+ normals[vertex] = Vector3.Normalize(normals[vertex]);+ }+ }+ triangles = Enumerable.Range(0, indices.Length / 3).ToArray();+ Build(0, triangles.Length);+ }++ public ClothBodySample3D Query(Vector3 position)+ {+ ClothValidation3D.Finite(position);+ float bestDistance = float.PositiveInfinity;+ int bestTriangle = -1;+ TriangleProximity3D closest = default;+ Visit(0);+ int offset = bestTriangle * 3;+ Vector3 normal = normals[indices[offset]] * closest.Barycentric.X+ + normals[indices[offset + 1]] * closest.Barycentric.Y+ + normals[indices[offset + 2]] * closest.Barycentric.Z;+ if (normal.LengthSquared() <= 1e-20f)+ {+ normal = Vector3.Cross(positions[indices[offset + 1]] - positions[indices[offset]],+ positions[indices[offset + 2]] - positions[indices[offset]]);+ }+ normal = Vector3.Normalize(normal);+ Vector3 delta = position - closest.Point;+ float distance = MathF.Sqrt(bestDistance);+ float sign = Vector3.Dot(delta, normal) < 0 ? -1 : 1;+ // The oriented pseudonormal chooses the side; the geometric nearest-point+ // direction resolves contact. Interpolated normals are not distance gradients.+ if (distance > 1e-10f)+ {+ normal = delta * (sign / distance);+ }+ return new(closest.Point, normal, distance * sign);++ void Visit(int nodeIndex)+ {+ var node = nodes[nodeIndex];+ if (DistanceToBox(position, node.Minimum, node.Maximum) > bestDistance)+ {+ return;+ }+ if (node.Count > 0)+ {+ for (int i = node.Start; i < node.Start + node.Count; i++)+ {+ int triangle = triangles[i];+ int face = triangle * 3;+ var candidate = TriangleSurface3D.ClosestPoint(position, positions[indices[face]],+ positions[indices[face + 1]], positions[indices[face + 2]]);+ float distance = Vector3.DistanceSquared(position, candidate.Point);+ if (distance < bestDistance || (distance == bestDistance && triangle < bestTriangle))+ {+ bestDistance = distance;+ bestTriangle = triangle;+ closest = candidate;+ }+ }+ return;+ }+ var left = nodes[node.Left];+ var right = nodes[node.Right];+ if (DistanceToBox(position, left.Minimum, left.Maximum)+ <= DistanceToBox(position, right.Minimum, right.Maximum))+ {+ Visit(node.Left);+ Visit(node.Right);+ }+ else+ {+ Visit(node.Right);+ Visit(node.Left);+ }+ }+ }++ private int Build(int start, int count)+ {+ Vector3 minimum = new(float.PositiveInfinity);+ Vector3 maximum = new(float.NegativeInfinity);+ for (int i = start; i < start + count; i++)+ {+ for (int corner = 0; corner < 3; corner++)+ {+ var point = positions[indices[triangles[i] * 3 + corner]];+ minimum = Vector3.Min(minimum, point);+ maximum = Vector3.Max(maximum, point);+ }+ }+ int nodeIndex = nodes.Count;+ nodes.Add(new(minimum, maximum, start, count, -1, -1));+ if (count <= 8)+ {+ return nodeIndex;+ }+ Vector3 size = maximum - minimum;+ int axis = 0;+ if (size.Y > size.X)+ {+ axis = 1;+ }+ if (size.Z > size[axis])+ {+ axis = 2;+ }+ Array.Sort(triangles, start, count, Comparer<int>.Create((a, b) =>+ {+ float ca = Center(a)[axis];+ float cb = Center(b)[axis];+ int comparison = ca.CompareTo(cb);+ return comparison == 0 ? a.CompareTo(b) : comparison;+ }));+ int left = Build(start, count / 2);+ int right = Build(start + count / 2, count - count / 2);+ nodes[nodeIndex] = new(minimum, maximum, start, 0, left, right);+ return nodeIndex;+ }++ private Vector3 Center(int triangle)+ {+ int face = triangle * 3;+ return (positions[indices[face]] + positions[indices[face + 1]] + positions[indices[face + 2]]) / 3;+ }++ private static float DistanceToBox(Vector3 point, Vector3 minimum, Vector3 maximum)+ {+ return Vector3.DistanceSquared(point, Vector3.Clamp(point, minimum, maximum));+ }+}diff --git a/Aetheris.Cloth3D/ClothContactTopology3D.cs b/Aetheris.Cloth3D/ClothContactTopology3D.csnew file mode 100644index 00000000..e1f29126--- /dev/null+++ b/Aetheris.Cloth3D/ClothContactTopology3D.cs@@ -0,0 +1,172 @@+using System.Collections.Immutable;++namespace Aetheris.Cloth3D;++public enum ClothContactFeature3D+{+ Face,+ Edge,+ Vertex,+ EdgePair,+}++public sealed record ClothContactPair3D(ClothContactFeature3D Kind,+ ImmutableArray<int> Vertices, int Feature);++public sealed record ClothContactEdge3D(int A, int B, ImmutableArray<int> Opposite);++/// <summary>Complete candidate set and conflict-free contact tape compiled from topology.+/// Exhaustive candidates deliberately avoid a broadphase omission. This foundation is+/// bounded to 128 vertices; spatial acceleration belongs above the same narrowphase.</summary>+public sealed class ClothContactTopology3D+{+ public ImmutableArray<ClothContactEdge3D> Edges { get; }+ public ImmutableArray<ImmutableArray<int>> Neighbors { get; }+ public ImmutableArray<ImmutableArray<int>> IncidentFaces { get; }+ public ImmutableArray<ClothContactPair3D> Pairs { get; }+ public ImmutableArray<ImmutableArray<int>> Colors { get; }+ public ImmutableArray<(int Left, int Right)> ReductionNodes { get; }+ public ImmutableArray<ImmutableArray<int>> ReductionLevels { get; }+ public ImmutableArray<int> Roots { get; }++ private ClothContactTopology3D(ClothDefinition3D definition)+ {+ int count = definition.Positions.Length;+ if (count > 128)+ {+ throw new NotSupportedException("AUR-CLOTH-004: Exhaustive offset contact supports at most 128 vertices; accelerated candidate search is not implemented.");+ }+ var neighbors = Enumerable.Range(0, count).Select(_ => new SortedSet<int>()).ToArray();+ var faces = Enumerable.Range(0, count).Select(_ => new List<int>()).ToArray();+ var edges = new SortedDictionary<(int A, int B), List<int>>();+ for (int face = 0; face < definition.Indices.Length / 3; face++)+ {+ int a = definition.Indices[face * 3];+ int b = definition.Indices[face * 3 + 1];+ int c = definition.Indices[face * 3 + 2];+ faces[a].Add(face);+ faces[b].Add(face);+ faces[c].Add(face);+ AddEdge(a, b, c);+ AddEdge(b, c, a);+ AddEdge(c, a, b);+ }+ if (neighbors.Any(row => row.Count > 32) || faces.Any(row => row.Count > 32))+ {+ throw new NotSupportedException("AUR-CLOTH-005: Offset contact supports at most 32 adjacent features per vertex.");+ }+ Edges = edges.Select(entry => new ClothContactEdge3D(entry.Key.A, entry.Key.B,+ entry.Value.ToImmutableArray())).ToImmutableArray();+ Neighbors = neighbors.Select(row => row.ToImmutableArray()).ToImmutableArray();+ IncidentFaces = faces.Select(row => row.ToImmutableArray()).ToImmutableArray();+ var pairs = new List<ClothContactPair3D>();+ for (int vertex = 0; vertex < count; vertex++)+ {+ for (int face = 0; face < definition.Indices.Length / 3; face++)+ {+ int a = definition.Indices[face * 3];+ int b = definition.Indices[face * 3 + 1];+ int c = definition.Indices[face * 3 + 2];+ if (vertex != a && vertex != b && vertex != c)+ {+ pairs.Add(new(ClothContactFeature3D.Face, [vertex, a, b, c], face));+ }+ }+ for (int edge = 0; edge < Edges.Length; edge++)+ {+ var segment = Edges[edge];+ if (vertex != segment.A && vertex != segment.B)+ {+ pairs.Add(new(ClothContactFeature3D.Edge, [vertex, segment.A, segment.B], edge));+ }+ }+ for (int other = vertex + 1; other < count; other++)+ {+ pairs.Add(new(ClothContactFeature3D.Vertex, [vertex, other], other));+ }+ }+ for (int first = 0; first < Edges.Length; first++)+ {+ var a = Edges[first];+ for (int second = first + 1; second < Edges.Length; second++)+ {+ var b = Edges[second];+ if (a.A != b.A && a.A != b.B && a.B != b.A && a.B != b.B)+ {+ pairs.Add(new(ClothContactFeature3D.EdgePair, [a.A, a.B, b.A, b.B], second));+ }+ }+ }+ Pairs = pairs.ToImmutableArray();+ // Normal-block tests read one-rings outside the four written vertices.+ // Include those reads in coloring so another lane cannot mutate them.+ Colors = ClothCompiler3D.Color(Pairs.Select(pair => pair.Vertices+ .Concat(pair.Kind is ClothContactFeature3D.Vertex or ClothContactFeature3D.EdgePair+ ? pair.Vertices.SelectMany(vertex => Neighbors[vertex]) : [])+ .Concat(pair.Kind == ClothContactFeature3D.Edge ? Edges[pair.Feature].Opposite : [])+ .Distinct().Order().ToImmutableArray()));++ // Parallel reduction levels contain no dynamic nested traversal. Every leaf+ // is a candidate distance, each vertex root gathers ALL participating features.+ var leaves = Enumerable.Range(0, count).Select(_ => new List<int>()).ToArray();+ for (int pair = 0; pair < pairs.Count; pair++)+ {+ if (pairs[pair].Kind is ClothContactFeature3D.Face or ClothContactFeature3D.EdgePair)+ {+ foreach (int vertex in pairs[pair].Vertices)+ {+ leaves[vertex].Add(pair);+ }+ }+ }+ var nodes = new List<(int Left, int Right)>();+ var levels = new List<List<int>>();+ var roots = new List<int>();+ foreach (var leaf in leaves)+ {+ var current = leaf;+ int level = 0;+ while (current.Count > 1)+ {+ if (levels.Count == level)+ {+ levels.Add([]);+ }+ var next = new List<int>();+ for (int index = 0; index < current.Count; index += 2)+ {+ if (index + 1 == current.Count)+ {+ next.Add(current[index]);+ continue;+ }+ int node = nodes.Count;+ nodes.Add((current[index], current[index + 1]));+ levels[level].Add(node);+ next.Add(pairs.Count + node);+ }+ current = next;+ level++;+ }+ roots.Add(current.Count == 0 ? -1 : current[0]);+ }+ ReductionNodes = nodes.ToImmutableArray();+ ReductionLevels = levels.Select(level => level.ToImmutableArray()).ToImmutableArray();+ Roots = roots.ToImmutableArray();++ void AddEdge(int a, int b, int opposite)+ {+ neighbors[a].Add(b);+ neighbors[b].Add(a);+ var key = (Math.Min(a, b), Math.Max(a, b));+ if (!edges.TryGetValue(key, out var list))+ {+ list = [];+ edges.Add(key, list);+ }+ list.Add(opposite);+ }+ }++ internal static ClothContactTopology3D Compile(ClothDefinition3D definition) => new(definition);+}diff --git a/Aetheris.Cloth3D/ClothDefinition3D.cs b/Aetheris.Cloth3D/ClothDefinition3D.csnew file mode 100644index 00000000..d3e1d5cc--- /dev/null+++ b/Aetheris.Cloth3D/ClothDefinition3D.cs@@ -0,0 +1,410 @@+using System.Collections.Immutable;+using System.Numerics;+using System.Security.Cryptography;+using System.Text;++namespace Aetheris.Cloth3D;++public enum ClothBendingModel3D+{+ BoundaryCorrectedVertex,+ QuadraticHinge,+}++/// <summary>Metres, kilograms and seconds. Link compliance is an authoring control,+/// not a measured continuum fabric modulus. Diagonal links approximate shear.</summary>+public sealed record ClothMaterial3D+{+ public float ArealDensity { get; init; } = .2f;+ public float Thickness { get; init; } = .004f;+ public float WarpCompliance { get; init; } = .000001f;+ public float WeftCompliance { get; init; } = .000001f;+ public float DiagonalCompliance { get; init; } = .000004f;+ public float BendCompliance { get; init; } = 1000f;+}++public sealed record ClothDefinition3D(string Id, ImmutableArray<Vector3> Positions,+ ImmutableArray<Vector2> Coordinates, ImmutableArray<int> Indices)+{+ /// <summary>Optional initial arrangement. Positions remains the undeformed rest surface.</summary>+ public ImmutableArray<Vector3> InitialPositions { get; init; } = [];+ /// <summary>Weighted equality constraints between material boundary samples.</summary>+ public ImmutableArray<ClothStitch3D> Stitches { get; init; } = [];+ public ClothMaterial3D Material { get; init; } = new();+ 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>+ public bool OffsetContact { get; init; }++ /// <summary>A flat pattern in XZ. Coordinates retain the material warp/weft axes.</summary>+ public static ClothDefinition3D Grid(string id, int columns, int rows, Vector2 size, Vector3 origin)+ {+ if (columns is < 2 or > 256 || rows is < 2 or > 256 || !float.IsFinite(size.X)+ || !float.IsFinite(size.Y) || size.X <= 0 || size.Y <= 0)+ {+ throw new ArgumentException("Cloth grid requires 2..256 vertices per axis and positive metre dimensions.");+ }+ var positions = ImmutableArray.CreateBuilder<Vector3>(columns * rows);+ var coordinates = ImmutableArray.CreateBuilder<Vector2>(columns * rows);+ var indices = ImmutableArray.CreateBuilder<int>((columns - 1) * (rows - 1) * 6);+ for (int row = 0; row < rows; row++)+ {+ for (int column = 0; column < columns; column++)+ {+ Vector2 uv = new(size.X * column / (columns - 1), size.Y * row / (rows - 1));+ coordinates.Add(uv);+ positions.Add(origin + new Vector3(uv.X, 0, uv.Y));+ if (row < rows - 1 && column < columns - 1)+ {+ int a = row * columns + column;+ indices.AddRange(new int[] { a, a + columns, a + 1, a + 1, a + columns, a + columns + 1 });+ }+ }+ }+ return new(id, positions.MoveToImmutable(), coordinates.MoveToImmutable(), indices.MoveToImmutable());+ }++ public CompiledCloth3D Compile() => ClothCompiler3D.Compile(this);+}++public 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 ClothConstraint3D(ClothConstraintKind3D Kind, ImmutableArray<int> Vertices,+ ImmutableArray<float> Weights, float RestLength, float Compliance);++/// <summary>Immutable topology and conflict-free schedules. A color contains disjoint vertex writes.</summary>+public sealed class CompiledCloth3D+{+ public string ContentKey { get; }+ public ClothDefinition3D Definition { get; }+ public ImmutableArray<float> InverseMasses { get; }+ public ImmutableArray<ClothConstraint3D> Constraints { get; }+ public ImmutableArray<ImmutableArray<int>> ConstraintColors { get; }+ public ImmutableArray<ImmutableArray<int>> TriangleColors { get; }+ public ClothContactTopology3D? ContactTopology { get; }++ internal CompiledCloth3D(string contentKey, ClothDefinition3D definition,+ ImmutableArray<float> inverseMasses, ImmutableArray<ClothConstraint3D> constraints,+ ImmutableArray<ImmutableArray<int>> constraintColors,+ ImmutableArray<ImmutableArray<int>> triangleColors)+ {+ ContentKey = contentKey;+ Definition = definition;+ InverseMasses = inverseMasses;+ Constraints = constraints;+ ConstraintColors = constraintColors;+ TriangleColors = triangleColors;+ ContactTopology = definition.OffsetContact ? ClothContactTopology3D.Compile(definition) : null;+ }+}++internal static class ClothCompiler3D+{+ public static CompiledCloth3D Compile(ClothDefinition3D definition)+ {+ ArgumentNullException.ThrowIfNull(definition);+ ArgumentException.ThrowIfNullOrWhiteSpace(definition.Id);+ var positions = definition.Positions;+ var indices = definition.Indices;+ var material = definition.Material;+ ArgumentNullException.ThrowIfNull(material);+ if (!Enum.IsDefined(definition.BendingModel))+ {+ throw new ArgumentException("Unknown cloth bending model.");+ }+ if (positions.IsDefault || positions.Length is < 3 or > 65536 || definition.Coordinates.IsDefault+ || positions.Length != definition.Coordinates.Length || indices.IsDefaultOrEmpty || indices.Length % 3 != 0)+ {+ throw new ArgumentException("Cloth requires positions, matching material coordinates and indexed triangles.");+ }+ if (definition.InitialPositions.IsDefault || (!definition.InitialPositions.IsEmpty+ && definition.InitialPositions.Length != positions.Length) || definition.Stitches.IsDefault)+ {+ throw new ArgumentException("Initial arrangement must match rest vertices; stitches cannot be default.");+ }+ foreach (Vector3 position in definition.InitialPositions)+ {+ ClothValidation3D.Finite(position);+ }+ var stitchIds = new HashSet<string>(StringComparer.Ordinal);+ foreach (var stitch in definition.Stitches)+ {+ if (string.IsNullOrWhiteSpace(stitch.Id) || !stitchIds.Add(stitch.Id)+ || stitch.Vertices.IsDefault || stitch.Weights.IsDefault+ || stitch.Vertices.Length is < 2 or > 4 || stitch.Vertices.Length != stitch.Weights.Length+ || stitch.Vertices.Distinct().Count() != stitch.Vertices.Length+ || stitch.Vertices.Any(vertex => vertex < 0 || vertex >= positions.Length)+ || stitch.Weights.Any(weight => !float.IsFinite(weight))+ || MathF.Abs(stitch.Weights.Sum()) > 1e-6f+ || MathF.Abs(stitch.Weights.Where(weight => weight > 0).Sum() - 1) > 1e-6f+ || !float.IsFinite(stitch.Compliance) || stitch.Compliance < 0)+ {+ throw new ArgumentException("Invalid stitch identity, stencil, barycentric weights or compliance.");+ }+ }+ foreach (Vector3 position in positions)+ {+ ClothValidation3D.Finite(position);+ }+ foreach (Vector2 uv in definition.Coordinates)+ {+ if (!float.IsFinite(uv.X) || !float.IsFinite(uv.Y))+ {+ throw new ArgumentException("Nonfinite cloth coordinates.");+ }+ }+ foreach (float value in new[] { material.ArealDensity, material.Thickness, material.WarpCompliance,+ material.WeftCompliance, material.DiagonalCompliance, material.BendCompliance })+ {+ if (!float.IsFinite(value) || value < 0)+ {+ throw new ArgumentException("Cloth material must be finite and nonnegative.");+ }+ }+ if (material.ArealDensity <= 0 || material.Thickness <= 0)+ {+ throw new ArgumentException("Density and thickness must be positive.");+ }+ if (definition.Pins.IsDefault || definition.Pins.Distinct().Count() != definition.Pins.Length+ || definition.Pins.Any(pin => pin < 0 || pin >= positions.Length))+ {+ throw new ArgumentException("Invalid or repeated cloth pin.");+ }+ float[] masses = new float[positions.Length];+ var edges = new SortedDictionary<(int A, int B), List<int>>();+ var uniqueTriangles = new HashSet<(int, int, int)>();+ var triangleVertices = new List<ImmutableArray<int>>();+ for (int triangle = 0; triangle < indices.Length; triangle += 3)+ {+ int a = indices[triangle];+ int b = indices[triangle + 1];+ int c = indices[triangle + 2];+ if (a < 0 || b < 0 || c < 0 || a >= positions.Length || b >= positions.Length || c >= positions.Length+ || a == b || a == c || b == c)+ {+ throw new ArgumentException("Invalid cloth triangle index.");+ }+ int[] sorted = [a, b, c];+ Array.Sort(sorted);+ if (!uniqueTriangles.Add((sorted[0], sorted[1], sorted[2])))+ {+ throw new ArgumentException("Duplicate cloth triangle.");+ }+ float area = Vector3.Cross(positions[b] - positions[a], positions[c] - positions[a]).Length() * .5f;+ if (!float.IsFinite(area) || area <= 1e-10f)+ {+ throw new ArgumentException("Degenerate cloth rest triangle.");+ }+ Vector2 materialAb = definition.Coordinates[b] - definition.Coordinates[a];+ Vector2 materialAc = definition.Coordinates[c] - definition.Coordinates[a];+ float materialArea = materialAb.X * materialAc.Y - materialAb.Y * materialAc.X;+ if (!float.IsFinite(materialArea) || MathF.Abs(materialArea) <= 1e-12f)+ {+ throw new ArgumentException("Degenerate cloth material-coordinate triangle.");+ }+ float mass = area * material.ArealDensity / 3;+ masses[a] += mass;+ masses[b] += mass;+ masses[c] += mass;+ triangleVertices.Add([a, b, c]);+ Edge(a, b, c);+ Edge(b, c, a);+ Edge(c, a, b);+ }+ if (masses.Any(mass => !float.IsFinite(mass) || mass <= 0 || !float.IsFinite(1 / mass)))+ {+ throw new ArgumentException("Cloth has unused or numerically massless vertices.");+ }+ var constraints = new List<ClothConstraint3D>();+ foreach (var (edge, opposite) in edges)+ {+ 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)+ {+ 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));+ }+ foreach (var stitch in definition.Stitches)+ {+ constraints.Add(new(ClothConstraintKind3D.Stitch, stitch.Vertices, stitch.Weights, 0, stitch.Compliance));+ }+ var pinned = definition.Pins.ToHashSet();+ var inverseMasses = masses.Select((mass, index) => pinned.Contains(index) ? 0 : 1 / mass).ToImmutableArray();+ string key = Identity();+ return new(key, definition, inverseMasses, constraints.ToImmutableArray(),+ Color(constraints.Select(constraint => constraint.Vertices)), Color(triangleVertices));++ void Edge(int a, int b, int opposite)+ {+ var key = (Math.Min(a, b), Math.Max(a, b));+ if (!edges.TryGetValue(key, out var neighbors))+ {+ edges.Add(key, neighbors = []);+ }+ neighbors.Add(opposite);+ if (neighbors.Count > 2)+ {+ throw new ArgumentException("Nonmanifold cloth edge.");+ }+ }++ ClothConstraint3D Bend(int a, int b, int c, int d)+ {+ Vector3 pa = positions[a];+ Vector3 pb = positions[b];+ Vector3 pc = positions[c];+ Vector3 pd = positions[d];+ float doubleArea1 = Vector3.Cross(pa - pc, pb - pc).Length();+ float doubleArea2 = Vector3.Cross(pa - pd, pb - pd).Length();+ float ac = Vector3.Dot(pb - pa, pc - pa) / doubleArea1;+ float bc = Vector3.Dot(pa - pb, pc - pb) / doubleArea1;+ float ad = Vector3.Dot(pb - pa, pd - pa) / doubleArea2;+ float bd = Vector3.Dot(pa - pb, pd - pb) / doubleArea2;+ float factor = MathF.Sqrt(6 / (doubleArea1 + doubleArea2));+ // Flat-rest quadratic hinge: E = 1/2 |sum(k_i * x_i)|^2.+ // Its vector components are solved directly, preserving quadratic energy+ // rather than squaring that energy into another constraint potential.+ float[] weights = [-(bc + bd) * factor, -(ac + ad) * factor,+ (ac + bc) * factor, (ad + bd) * factor];+ if (weights.Any(weight => !float.IsFinite(weight)))+ {+ throw new ArgumentException("Numerically ill-conditioned cloth rest hinge.");+ }+ // Classify rest planarity geometrically. The weighted residual scales with+ // inverse edge length and can suffer cancellation even on a planar mesh.+ Vector3 normal1 = Vector3.Cross(pb - pa, pc - pa) / doubleArea1;+ Vector3 normal2 = Vector3.Cross(pb - pa, pd - pa) / doubleArea2;+ // Opposite vertices must lie on opposite sides of the shared edge.+ // Parallel normals alone would also admit a fully folded-back, overlapping hinge.+ if ((normal1 + normal2).Length() > .0001f)+ {+ throw new NotSupportedException("AUR-CLOTH-001: The quadratic baseline requires locally flat rest hinges; shaped garments need a rest-curvature model.");+ }+ return new(ClothConstraintKind3D.FlatBend, [a, b, c, d], weights.ToImmutableArray(), 0, material.BendCompliance);+ }++ string Identity()+ {+ using var bytes = new MemoryStream();+ using var writer = new BinaryWriter(bytes, Encoding.UTF8, true);+ writer.Write("cloth/material-rest-xpbd/v3");+ writer.Write((int)definition.BendingModel);+ writer.Write(definition.OffsetContact);+ writer.Write(definition.Id);+ writer.Write(positions.Length);+ foreach (Vector3 p in positions)+ {+ writer.Write(p.X);+ writer.Write(p.Y);+ writer.Write(p.Z);+ }+ foreach (Vector2 uv in definition.Coordinates)+ {+ writer.Write(uv.X);+ writer.Write(uv.Y);+ }+ writer.Write(indices.Length);+ foreach (int index in indices)+ {+ writer.Write(index);+ }+ writer.Write(definition.Pins.Length);+ foreach (int pin in definition.Pins)+ {+ writer.Write(pin);+ }+ writer.Write(definition.InitialPositions.Length);+ foreach (Vector3 p in definition.InitialPositions)+ {+ writer.Write(p.X);+ writer.Write(p.Y);+ writer.Write(p.Z);+ }+ writer.Write(definition.Stitches.Length);+ foreach (var stitch in definition.Stitches)+ {+ writer.Write(stitch.Id);+ writer.Write(stitch.Compliance);+ writer.Write(stitch.Vertices.Length);+ for (int i = 0; i < stitch.Vertices.Length; i++)+ {+ writer.Write(stitch.Vertices[i]);+ writer.Write(stitch.Weights[i]);+ }+ }+ writer.Write(material.ArealDensity);+ writer.Write(material.Thickness);+ writer.Write(material.WarpCompliance);+ writer.Write(material.WeftCompliance);+ writer.Write(material.DiagonalCompliance);+ writer.Write(material.BendCompliance);+ writer.Flush();+ return Convert.ToHexString(SHA256.HashData(bytes.ToArray()));+ }+ }++ internal static ImmutableArray<ImmutableArray<int>> Color(IEnumerable<ImmutableArray<int>> stencils)+ {+ var vertices = new List<HashSet<int>>();+ var colors = new List<List<int>>();+ int index = 0;+ foreach (var stencil in stencils)+ {+ int color = 0;+ for (; color < colors.Count; color++)+ {+ if (!stencil.Any(vertices[color].Contains))+ {+ break;+ }+ }+ if (color == colors.Count)+ {+ colors.Add([]);+ vertices.Add([]);+ }+ colors[color].Add(index++);+ vertices[color].UnionWith(stencil);+ }+ return colors.Select(color => color.ToImmutableArray()).ToImmutableArray();+ }+}++internal static class ClothValidation3D+{+ public static void Finite(Vector3 value)+ {+ if (!float.IsFinite(value.X) || !float.IsFinite(value.Y) || !float.IsFinite(value.Z))+ {+ throw new ArgumentException("Nonfinite cloth vector.");+ }+ }+}diff --git a/Aetheris.Cloth3D/ClothGarmentArtifact3D.cs b/Aetheris.Cloth3D/ClothGarmentArtifact3D.csnew file mode 100644index 00000000..c1ff5271--- /dev/null+++ b/Aetheris.Cloth3D/ClothGarmentArtifact3D.cs@@ -0,0 +1,63 @@+using System.Text.Json;++namespace Aetheris.Cloth3D;++/// <summary>A runtime garment needs the compiled cloth, not the Firmament authoring compiler.+/// Panel names and seam provenance remain in the transport document for inspection.</summary>+public sealed record ClothGarmentArtifact3D(CompiledCloth3D Cloth, ClothSnapshot3D? Settled,+ string SourceHash, string SourceIdentity)+{+ private static readonly JsonSerializerOptions Options = new() { IncludeFields = true };++ public static ClothGarmentArtifact3D Load(string path)+ {+ ArgumentException.ThrowIfNullOrWhiteSpace(path);+ if (new FileInfo(path).Length > 32 * 1024 * 1024)+ {+ throw new InvalidDataException("garment-artifact-budget: Maximum document size is 32 MiB.");+ }+ return Parse(File.ReadAllText(path));+ }++ public static ClothGarmentArtifact3D Parse(string json)+ {+ ArgumentNullException.ThrowIfNull(json);+ using var document = JsonDocument.Parse(json);+ var root = document.RootElement;+ if (root.GetProperty("schema").GetString() != "aetheris.garment.v1"+ || root.GetProperty("units").GetString() != "m"+ || root.GetProperty("upAxis").GetString() != "Z")+ {+ throw new InvalidDataException("garment-artifact-schema: Expected aetheris.garment.v1, metres, Z up.");+ }+ var definition = root.GetProperty("definition").Deserialize<ClothDefinition3D>(Options)+ ?? throw new InvalidDataException("garment-artifact-definition: Missing cloth definition.");+ var cloth = definition.Compile();+ if (root.GetProperty("contentKey").GetString() != cloth.ContentKey)+ {+ throw new InvalidDataException("garment-artifact-content-key: Definition does not match its retained key.");+ }+ ClothSnapshot3D? settled = root.GetProperty("settled").Deserialize<ClothSnapshot3D>(Options);+ if (settled is not null)+ {+ ClothState3D.ValidateSnapshot(cloth, settled);+ }+ string hash = root.GetProperty("sourceHash").GetString() ?? "";+ string identity = root.GetProperty("sourceIdentity").GetString() ?? "";+ if (hash.Length != 64 || hash.Any(character => !Uri.IsHexDigit(character)) || string.IsNullOrWhiteSpace(identity))+ {+ throw new InvalidDataException("garment-artifact-provenance: Source identity and SHA-256 are required.");+ }+ return new(cloth, settled, hash, identity);+ }++ public ClothSolver3D CreateSolver()+ {+ var solver = new ClothSolver3D(Cloth);+ if (Settled is not null)+ {+ solver.Restore(Settled);+ }+ return solver;+ }+}diff --git a/Aetheris.Cloth3D/ClothGpuData3D.cs b/Aetheris.Cloth3D/ClothGpuData3D.csnew file mode 100644index 00000000..61ba316a--- /dev/null+++ b/Aetheris.Cloth3D/ClothGpuData3D.cs@@ -0,0 +1,242 @@+using System.Collections.Immutable;+using System.Numerics;++namespace Aetheris.Cloth3D;++// Stable scalar phase codes, extended by the version 2 contact tape.+public enum ClothPhase3D+{+ Predict = 0,+ Constraints = 1,+ VertexContact = 2,+ TriangleContact = 3,+ Velocity = 4,+ CapturePins = 5,+ OffsetDistances = 6,+ OffsetReduce = 7,+ OffsetBounds = 8,+ OffsetContacts = 9,+}++public 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>+public sealed class ClothGpuData3D+{+ public CompiledCloth3D Plan { get; }+ public float[] Source { get; }+ public ImmutableArray<ClothDispatch3D> Constraints { get; }+ public ImmutableArray<ClothDispatch3D> Triangles { get; }+ public ImmutableArray<ClothDispatch3D> OffsetColors { get; }+ public ImmutableArray<ClothDispatch3D> OffsetReductions { get; }+ public int ContactSourceOffset { get; }+ public int AnchorOffset => Plan.Definition.Positions.Length * 16 + Plan.Constraints.Length * 3;+ public int DistanceOffset => AnchorOffset + Plan.Definition.Positions.Length * 4;+ public int ContactLambdaOffset => DistanceOffset + (Plan.ContactTopology?.Pairs.Length ?? 0)+ + (Plan.ContactTopology?.ReductionNodes.Length ?? 0);++ public ClothGpuData3D(CompiledCloth3D plan)+ {+ 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)];+ var constraints = ImmutableArray.CreateBuilder<ClothDispatch3D>();+ var triangles = ImmutableArray.CreateBuilder<ClothDispatch3D>();+ int index = 0;+ foreach (var color in plan.ConstraintColors)+ {+ constraints.Add(new(ClothPhase3D.Constraints, index, color.Length));+ foreach (int original in color)+ {+ var constraint = plan.Constraints[original];+ int offset = index++ * 12;+ Source[offset] = (int)constraint.Kind;+ for (int local = 0; local < Math.Min(4, constraint.Vertices.Length); local++)+ {+ Source[offset + 1 + local] = constraint.Vertices[local];+ }+ Source[offset + 5] = constraint.RestLength;+ Source[offset + 6] = constraint.Compliance;+ Source[offset + 7] = stencilOffset;+ Source[offset + 11] = constraint.Vertices.Length;+ for (int local = 0; local < constraint.Vertices.Length; local++)+ {+ Source[stencilOffset++] = constraint.Vertices[local];+ Source[stencilOffset++] = constraint.Weights.IsEmpty ? 0 : constraint.Weights[local];+ }+ }+ }+ foreach (var color in plan.TriangleColors)+ {+ triangles.Add(new(ClothPhase3D.TriangleContact, index, color.Length));+ foreach (int triangle in color)+ {+ int offset = index++ * 12;+ Source[offset] = 4;+ for (int local = 0; local < 3; local++)+ {+ Source[offset + 1 + local] = plan.Definition.Indices[triangle * 3 + local];+ }+ }+ }+ Constraints = constraints.ToImmutable();+ Triangles = triangles.ToImmutable();+ var source = Source.ToList();+ var contactColors = ImmutableArray.CreateBuilder<ClothDispatch3D>();+ var reductions = ImmutableArray.CreateBuilder<ClothDispatch3D>();+ if (plan.ContactTopology is { } topology)+ {+ ContactSourceOffset = source.Count;+ source.AddRange(new float[8]);+ int table = ContactSourceOffset;+ source[table] = source.Count;+ foreach (var edge in topology.Edges)+ {+ source.AddRange(new float[] { edge.A, edge.B, edge.Opposite.Length,+ edge.Opposite[0], edge.Opposite.Length == 2 ? edge.Opposite[1] : 0 });+ }+ source[table + 1] = source.Count;+ int vertexTable = source.Count;+ source.AddRange(new float[plan.Definition.Positions.Length * 4]);+ for (int vertex = 0; vertex < plan.Definition.Positions.Length; vertex++)+ {+ source[vertexTable + vertex * 4] = source.Count;+ source[vertexTable + vertex * 4 + 1] = topology.Neighbors[vertex].Length;+ source.AddRange(topology.Neighbors[vertex].Select(index => (float)index));+ source[vertexTable + vertex * 4 + 2] = source.Count;+ source[vertexTable + vertex * 4 + 3] = topology.IncidentFaces[vertex].Length;+ source.AddRange(topology.IncidentFaces[vertex].Select(index => (float)index));+ }+ source[table + 2] = source.Count;+ source.AddRange(plan.Definition.Indices.Select(index => (float)index));+ source[table + 3] = source.Count;+ foreach (var pair in topology.Pairs)+ {+ source.Add((int)pair.Kind);+ source.Add(pair.Vertices.Length);+ for (int local = 0; local < 4; local++)+ {+ source.Add(local < pair.Vertices.Length ? pair.Vertices[local] : 0);+ }+ source.Add(pair.Feature);+ source.Add(0);+ }+ source[table + 4] = source.Count;+ foreach (var node in topology.ReductionNodes)+ {+ source.Add(node.Left);+ source.Add(node.Right);+ }+ source[table + 5] = source.Count;+ source.AddRange(topology.Roots.Select(index => (float)index));+ source[table + 6] = source.Count;+ foreach (var level in topology.ReductionLevels)+ {+ reductions.Add(new(ClothPhase3D.OffsetReduce, source.Count, level.Length));+ source.AddRange(level.Select(index => (float)index));+ }+ source[table + 7] = source.Count;+ foreach (var color in topology.Colors)+ {+ contactColors.Add(new(ClothPhase3D.OffsetContacts, source.Count, color.Length));+ source.AddRange(color.Select(index => (float)index));+ }+ }+ OffsetColors = contactColors.ToImmutable();+ OffsetReductions = reductions.ToImmutable();+ Source = source.ToArray();+ }++ public float[] State(ClothSnapshot3D snapshot)+ {+ ClothState3D.ValidateSnapshot(Plan, snapshot);+ float[] state = new float[Plan.ContactTopology is null ? AnchorOffset+ : ContactLambdaOffset + Plan.ContactTopology.Pairs.Length];+ for (int vertex = 0; vertex < snapshot.Positions.Length; vertex++)+ {+ int offset = vertex * 16;+ WriteVector(state, offset, snapshot.Positions[vertex]);+ WriteVector(state, offset + 6, snapshot.Velocities[vertex]);+ state[offset + 9] = Plan.InverseMasses[vertex];+ WriteVector(state, offset + 10, snapshot.PinTargets[vertex]);+ }+ return state;+ }++ public ClothSnapshot3D Snapshot(ReadOnlySpan<float> state, long tick)+ {+ int count = Plan.Definition.Positions.Length;+ if (state.Length < count * 16)+ {+ throw new ArgumentException("Truncated cloth GPU state.");+ }+ var positions = ImmutableArray.CreateBuilder<Vector3>(count);+ var velocities = ImmutableArray.CreateBuilder<Vector3>(count);+ var targets = ImmutableArray.CreateBuilder<Vector3>(count);+ for (int vertex = 0; vertex < count; vertex++)+ {+ positions.Add(ReadVector(state, vertex * 16));+ velocities.Add(ReadVector(state, vertex * 16 + 6));+ targets.Add(ReadVector(state, vertex * 16 + 10));+ }+ var snapshot = new ClothSnapshot3D(Plan.ContentKey, tick, positions.MoveToImmutable(),+ velocities.MoveToImmutable(), targets.MoveToImmutable());+ ClothState3D.ValidateSnapshot(Plan, snapshot);+ return snapshot;+ }++ public float[] Header(ClothStepOptions3D options, ClothContacts3D contacts, ClothDispatch3D dispatch, float fraction)+ {+ float h = options.DeltaSeconds / options.Substeps;+ float[] header = new float[32];+ if (!Enum.IsDefined(dispatch.Phase))+ {+ throw new ArgumentOutOfRangeException(nameof(dispatch));+ }+ header[0] = (int)dispatch.Phase;+ header[1] = dispatch.Count;+ header[2] = dispatch.Start;+ header[3] = Plan.Definition.Positions.Length;+ header[4] = h;+ WriteVector(header, 5, options.Gravity);+ header[8] = MathF.Exp(-options.VelocityDamping * h);+ header[9] = dispatch.ResetLambda ? 1 : 0;+ header[10] = fraction;+ header[31] = options.StitchComplianceScale;+ header[11] = Plan.Definition.Material.Thickness * .5f;+ if (contacts.PlaneNormal is { } normal)+ {+ header[12] = 1;+ WriteVector(header, 13, normal);+ header[16] = contacts.PlaneOffset;+ }+ if (contacts.SphereCenter is { } sphere)+ {+ header[17] = 1;+ WriteVector(header, 18, sphere);+ header[21] = contacts.SphereRadius;+ }+ if (Plan.ContactTopology is { } topology)+ {+ header[22] = topology.Pairs.Length;+ header[23] = ContactSourceOffset;+ header[24] = AnchorOffset;+ header[25] = DistanceOffset;+ header[26] = ContactLambdaOffset;+ header[27] = Plan.Definition.Material.Thickness;+ header[28] = options.ContactSafetyFactor;+ header[29] = options.OffsetContactCompliance;+ header[30] = 1;+ }+ return header;+ }++ private static Vector3 ReadVector(ReadOnlySpan<float> values, int offset) => new(values[offset], values[offset + 1], values[offset + 2]);+ private static void WriteVector(float[] values, int offset, Vector3 vector)+ {+ values[offset] = vector.X;+ values[offset + 1] = vector.Y;+ values[offset + 2] = vector.Z;+ }+}diff --git a/Aetheris.Cloth3D/ClothOffsetContact3D.cs b/Aetheris.Cloth3D/ClothOffsetContact3D.csnew file mode 100644index 00000000..8f1dfe2b--- /dev/null+++ b/Aetheris.Cloth3D/ClothOffsetContact3D.cs@@ -0,0 +1,270 @@+using System.Numerics;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Cloth3D;++public readonly record struct ClothContactQuery3D(float Distance, Vector3 Normal,+ Vector4 Weights, bool Active);++/// <summary>OGC feature blocks, complete clearance queries and conservative trust regions.+/// Normal response uses a C2 matched quadratic/logarithmic distance potential in XPBD.+/// Friction and two-way rigid-body coupling are separate, unimplemented capabilities.</summary>+public static class ClothOffsetContact3D+{+ public const float ClearanceFloor = .000001f;++ public static ClothContactQuery3D Query(ClothContactTopology3D topology,+ ClothContactPair3D pair, IReadOnlyList<Vector3> positions)+ {+ var vertices = pair.Vertices;+ Vector3 a = positions[vertices[0]];+ Vector3 b = positions[vertices[1]];+ Vector3 difference;+ Vector4 weights;+ bool active;+ switch (pair.Kind)+ {+ case ClothContactFeature3D.Face:+ var closest = TriangleSurface3D.ClosestPoint(a, b,+ positions[vertices[2]], positions[vertices[3]]);+ var barycentric = closest.Barycentric;+ difference = a - closest.Point;+ weights = new(1, -barycentric.X, -barycentric.Y, -barycentric.Z);+ active = barycentric.X > 0 && barycentric.Y > 0 && barycentric.Z > 0;+ break;+ case ClothContactFeature3D.Edge:+ Vector3 c = positions[vertices[2]];+ float t = SegmentParameter(a, b, c);+ Vector3 point = Vector3.Lerp(b, c, t);+ difference = a - point;+ weights = new(1, t - 1, -t, 0);+ active = t > 0 && t < 1;+ foreach (int opposite in topology.Edges[pair.Feature].Opposite)+ {+ Vector3 foot = b + (c - b) * LineParameter(positions[opposite], b, c);+ active &= Vector3.Dot(a - foot, foot - positions[opposite]) >= 0;+ }+ break;+ case ClothContactFeature3D.Vertex:+ difference = a - b;+ weights = new(1, -1, 0, 0);+ active = VertexBlock(vertices[1], a, topology, positions)+ && VertexBlock(vertices[0], b, topology, positions);+ break;+ case ClothContactFeature3D.EdgePair:+ Vector3 d = positions[vertices[3]];+ Vector3 third = positions[vertices[2]];+ var parameters = SegmentParameters(a, b, third, d);+ Vector3 firstPoint = Vector3.Lerp(a, b, parameters.X);+ Vector3 secondPoint = Vector3.Lerp(third, d, parameters.Y);+ difference = firstPoint - secondPoint;+ weights = new(1 - parameters.X, parameters.X, parameters.Y - 1, -parameters.Y);+ active = EndpointBlock(vertices[0], vertices[1], parameters.X, secondPoint, topology, positions)+ && EndpointBlock(vertices[2], vertices[3], parameters.Y, firstPoint, topology, positions);+ float cross = Vector3.Cross(b - a, d - third).LengthSquared();+ active &= cross > 1e-8f * (b - a).LengthSquared() * (d - third).LengthSquared();+ break;+ default:+ throw new ArgumentOutOfRangeException(nameof(pair));+ }+ float distance = difference.Length();+ Vector3 normal = distance > 0 ? difference / distance : Vector3.Zero;+ return new(distance, normal, weights, active);+ }++ public static Vector2 SegmentParameters(Vector3 a, Vector3 b, Vector3 c, Vector3 d)+ {+ Vector3 first = b - a;+ Vector3 second = d - c;+ Vector3 offset = a - c;+ float aa = first.LengthSquared();+ float bb = Vector3.Dot(first, second);+ float cc = second.LengthSquared();+ float dd = Vector3.Dot(first, offset);+ float ee = Vector3.Dot(second, offset);+ float determinant = aa * cc - bb * bb;+ float s = 0;+ if (aa <= 1e-20f)+ {+ return new(0, SegmentParameter(a, c, d));+ }+ if (cc <= 1e-20f)+ {+ return new(SegmentParameter(c, a, b), 0);+ }+ if (determinant > 1e-8f * aa * cc)+ {+ s = Math.Clamp((bb * ee - cc * dd) / determinant, 0, 1);+ }+ float t = (bb * s + ee) / cc;+ if (t < 0)+ {+ t = 0;+ s = Math.Clamp(-dd / aa, 0, 1);+ }+ else if (t > 1)+ {+ t = 1;+ s = Math.Clamp((bb - dd) / aa, 0, 1);+ }+ return new(s, t);+ }++ public static Vector2 Potential(float distance, float radius)+ {+ if (distance >= radius)+ {+ return Vector2.Zero;+ }+ if (distance <= 0)+ {+ throw new ArgumentException("Offset potential requires positive separation.");+ }+ float threshold = radius * .5f;+ if (distance >= threshold)+ {+ float residual = radius - distance;+ return new(residual, -1);+ }+ // Match value, slope AND curvature at r/2. The logarithmic coefficient+ // is r^2/4; using the printed Eq.19 literally would not match its Eq.18.+ float coefficient = radius * radius * .25f;+ float energy = coefficient * (.5f - MathF.Log(distance / threshold));+ float constraint = MathF.Sqrt(2 * energy);+ return new(constraint, -coefficient / (distance * constraint));+ }++ public static float[] Bounds(CompiledCloth3D plan, IReadOnlyList<Vector3> anchor,+ ClothContacts3D contacts, float safetyFactor)+ {+ var topology = plan.ContactTopology ?? throw new ArgumentException("Offset contact was not compiled.");+ float[] clearances = Enumerable.Repeat(1e6f, anchor.Count).ToArray();+ foreach (var pair in topology.Pairs)+ {+ if (pair.Kind is not (ClothContactFeature3D.Face or ClothContactFeature3D.EdgePair))+ {+ continue;+ }+ float distance = Query(topology, pair, anchor).Distance;+ foreach (int vertex in pair.Vertices)+ {+ clearances[vertex] = MathF.Min(clearances[vertex], distance);+ }+ }+ float halfThickness = plan.Definition.Material.Thickness * .5f;+ for (int vertex = 0; vertex < anchor.Count; vertex++)+ {+ if (contacts.PlaneNormal is { } normal)+ {+ float gap = Vector3.Dot(normal, anchor[vertex]) - contacts.PlaneOffset - halfThickness;+ clearances[vertex] = MathF.Min(clearances[vertex], gap);+ }+ if (contacts.SphereCenter is { } sphere)+ {+ foreach (int face in topology.IncidentFaces[vertex])+ {+ var indices = plan.Definition.Indices;+ var closest = TriangleSurface3D.ClosestPoint(sphere, anchor[indices[face * 3]],+ anchor[indices[face * 3 + 1]], anchor[indices[face * 3 + 2]]);+ float gap = Vector3.Distance(sphere, closest.Point) - contacts.SphereRadius - halfThickness;+ clearances[vertex] = MathF.Min(clearances[vertex], gap);+ }+ }+ clearances[vertex] = safetyFactor * MathF.Max(0, clearances[vertex] - ClearanceFloor);+ }+ return clearances;+ }++ public static Vector3 Clip(Vector3 proposed, Vector3 anchor, float bound)+ {+ Vector3 movement = proposed - anchor;+ float length = movement.Length();+ if (length > bound)+ {+ return anchor + movement * (bound / length);+ }+ return proposed;+ }++ public static void ValidateInitial(CompiledCloth3D plan, ClothSnapshot3D state, ClothContacts3D contacts)+ {+ var topology = plan.ContactTopology ?? throw new ArgumentException("Offset contact was not compiled.");+ var positions = state.Positions;+ foreach (var pair in topology.Pairs)+ {+ if (pair.Kind is ClothContactFeature3D.Face or ClothContactFeature3D.EdgePair+ && Query(topology, pair, positions).Distance <= ClearanceFloor * 2)+ {+ throw new ArgumentException("AUR-CLOTH-006: Offset contact needs an intersection-free initial state with positive clearance.");+ }+ }+ // Distances at isolated VF/EE features do not detect an edge already piercing+ // a face interior. Test every nonincident segment/facet before trusting bounds.+ foreach (var edge in topology.Edges)+ {+ for (int face = 0; face < plan.Definition.Indices.Length; face += 3)+ {+ int a = plan.Definition.Indices[face];+ int b = plan.Definition.Indices[face + 1];+ int c = plan.Definition.Indices[face + 2];+ if (edge.A == a || edge.A == b || edge.A == c || edge.B == a || edge.B == b || edge.B == c)+ {+ continue;+ }+ Vector3 normal = Vector3.Cross(positions[b] - positions[a], positions[c] - positions[a]);+ float start = Vector3.Dot(positions[edge.A] - positions[a], normal);+ float end = Vector3.Dot(positions[edge.B] - positions[a], normal);+ if (start * end < 0)+ {+ Vector3 point = Vector3.Lerp(positions[edge.A], positions[edge.B], start / (start - end));+ var closest = TriangleSurface3D.ClosestPoint(point, positions[a], positions[b], positions[c]);+ if (Vector3.Distance(point, closest.Point) <= ClearanceFloor)+ {+ throw new ArgumentException("AUR-CLOTH-006: An initial cloth edge pierces a nonincident face.");+ }+ }+ }+ }+ if (Bounds(plan, positions, contacts, .4f).Any(bound => bound <= 0))+ {+ throw new ArgumentException("AUR-CLOTH-006: Initial cloth overlaps a collider or lacks positive clearance.");+ }+ }++ private static bool EndpointBlock(int a, int b, float t, Vector3 other,+ ClothContactTopology3D topology, IReadOnlyList<Vector3> positions)+ {+ if (t <= 0)+ {+ return VertexBlock(a, other, topology, positions);+ }+ if (t >= 1)+ {+ return VertexBlock(b, other, topology, positions);+ }+ return true;+ }++ private static bool VertexBlock(int vertex, Vector3 point,+ ClothContactTopology3D topology, IReadOnlyList<Vector3> positions)+ {+ foreach (int neighbor in topology.Neighbors[vertex])+ {+ if (Vector3.Dot(point - positions[vertex], positions[vertex] - positions[neighbor]) < 0)+ {+ return false;+ }+ }+ return true;+ }++ private static float SegmentParameter(Vector3 point, Vector3 a, Vector3 b)+ => Math.Clamp(LineParameter(point, a, b), 0, 1);++ private static float LineParameter(Vector3 point, Vector3 a, Vector3 b)+ {+ Vector3 edge = b - a;+ float length = edge.LengthSquared();+ return length > 1e-20f ? Vector3.Dot(point - a, edge) / length : 0;+ }+}diff --git a/Aetheris.Cloth3D/ClothSimulation3D.cs b/Aetheris.Cloth3D/ClothSimulation3D.csnew file mode 100644index 00000000..b8901812--- /dev/null+++ b/Aetheris.Cloth3D/ClothSimulation3D.cs@@ -0,0 +1,580 @@+using System.Collections.Immutable;+using System.Numerics;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Cloth3D;++public sealed record ClothStepOptions3D+{+ public float DeltaSeconds { get; init; } = 1f / 60;+ public int Substeps { get; init; } = 8;+ public int Iterations { get; init; } = 4;+ public int ContactIterations { get; init; } = 2;+ public Vector3 Gravity { get; init; } = new(0, -9.81f, 0);+ public float VelocityDamping { get; init; } = 1.5f;+ public float ContactSafetyFactor { get; init; } = .4f;+ public float StitchComplianceScale { get; init; } = 1;+ public float OffsetContactCompliance { get; init; } = .000001f;++ public void Validate()+ {+ ClothValidation3D.Finite(Gravity);+ if (!float.IsFinite(DeltaSeconds) || DeltaSeconds is < .00001f or > .1f+ || Substeps is < 1 or > 64 || Iterations is < 1 or > 64 || ContactIterations is < 1 or > 32+ || !float.IsFinite(VelocityDamping) || VelocityDamping < 0+ || !float.IsFinite(ContactSafetyFactor) || ContactSafetyFactor <= 0 || ContactSafetyFactor >= .5f+ || !float.IsFinite(StitchComplianceScale) || StitchComplianceScale is < 1 or > 100000000+ || !float.IsFinite(OffsetContactCompliance) || OffsetContactCompliance < 0)+ {+ throw new ArgumentException("Invalid bounded cloth step options.");+ }+ }+}++/// <summary>One-way, discrete contact baseline. Plane equation dot(normal,p) >= offset;+/// sphere contact covers vertices AND triangle interiors. No CCD or self-contact claim.</summary>+public sealed record ClothContacts3D+{+ public IClothBodySurface3D? BodySurface { get; init; }+ public float BodyClearance { get; init; }+ public Vector3? PlaneNormal { get; init; }+ public float PlaneOffset { get; init; }+ public Vector3? SphereCenter { get; init; }+ public float SphereRadius { get; init; }++ public void Validate()+ {+ if (PlaneNormal is { } normal)+ {+ ClothValidation3D.Finite(normal);+ if (MathF.Abs(normal.LengthSquared() - 1) > .0001f)+ {+ throw new ArgumentException("Cloth plane requires a unit normal.");+ }+ }+ if (SphereCenter is { } center)+ {+ ClothValidation3D.Finite(center);+ if (!float.IsFinite(SphereRadius) || SphereRadius <= 0)+ {+ throw new ArgumentException("Cloth sphere radius must be positive.");+ }+ }+ if (!float.IsFinite(BodyClearance) || BodyClearance is < 0 or > .03f)+ {+ throw new ArgumentException("Body clearance must be finite and between zero and 30mm.");+ }+ if (!float.IsFinite(PlaneOffset))+ {+ throw new ArgumentException("Nonfinite plane offset.");+ }+ }+}++public sealed record ClothSnapshot3D(string ContentKey, long Tick, ImmutableArray<Vector3> Positions,+ ImmutableArray<Vector3> Velocities, ImmutableArray<Vector3> PinTargets);++public sealed record ClothMetrics3D(float MaximumStretch, float MaximumPinError,+ float MaximumSurfacePenetration, float BendEnergy, bool Finite)+{+ public ClothOffsetMetrics3D? OffsetContact { get; init; }+}++public sealed record ClothOffsetMetrics3D(float MinimumFeatureClearance,+ float MaximumActiveOffsetOverlap, int ActivePairs);++public interface IClothSolver3D : IDisposable+{+ CompiledCloth3D Plan { get; }+ long Tick { get; }+ void SetPin(int vertex, Vector3 target);+ void Step(ClothStepOptions3D options, ClothContacts3D contacts);+ ClothSnapshot3D Capture();+ void Restore(ClothSnapshot3D snapshot);+}++/// <summary>Deterministic CPU reference for the same colored schedule used by Vulkan.+/// Multipliers reset per substep, accumulate across iterations, and are not warm-started.</summary>+public sealed class ClothSolver3D : IClothSolver3D+{+ private readonly Vector3[] positions;+ private readonly Vector3[] velocities;+ private readonly Vector3[] previous;+ private readonly Vector3[] targets;+ private readonly Vector3[] pinStarts;+ private readonly Vector3[] lambda;+ private readonly Vector3[] contactAnchor;+ private float[]? contactBounds;+ private readonly float[] contactLambda;++ public CompiledCloth3D Plan { get; }+ public long Tick { get; private set; }++ public ClothSolver3D(CompiledCloth3D plan)+ {+ ArgumentNullException.ThrowIfNull(plan);+ Plan = plan;+ positions = (plan.Definition.InitialPositions.IsEmpty+ ? plan.Definition.Positions : plan.Definition.InitialPositions).ToArray();+ previous = new Vector3[positions.Length];+ velocities = new Vector3[positions.Length];+ targets = positions.ToArray();+ pinStarts = new Vector3[positions.Length];+ lambda = new Vector3[plan.Constraints.Length];+ contactAnchor = new Vector3[positions.Length];+ contactLambda = new float[plan.ContactTopology?.Pairs.Length ?? 0];+ }++ public void SetPin(int vertex, Vector3 target)+ {+ ClothState3D.ValidatePin(Plan, vertex, target);+ targets[vertex] = target;+ }++ public void Step(ClothStepOptions3D options, ClothContacts3D contacts)+ {+ ClothState3D.ValidateStep(Plan, options, contacts);+ if (Plan.ContactTopology is not null)+ {+ ClothOffsetContact3D.ValidateInitial(Plan, Capture(), contacts);+ }+ float h = options.DeltaSeconds / options.Substeps;+ float damping = MathF.Exp(-options.VelocityDamping * h);+ positions.CopyTo(pinStarts, 0);+ for (int substep = 0; substep < options.Substeps; substep++)+ {+ Array.Clear(lambda);+ Array.Clear(contactLambda);+ RefreshBounds(options, contacts);+ float fraction = (substep + 1f) / options.Substeps;+ for (int vertex = 0; vertex < positions.Length; vertex++)+ {+ previous[vertex] = positions[vertex];+ if (Plan.InverseMasses[vertex] == 0)+ {+ positions[vertex] = Vector3.Lerp(pinStarts[vertex], targets[vertex], fraction);+ }+ else+ {+ velocities[vertex] += options.Gravity * h;+ positions[vertex] += velocities[vertex] * h;+ }+ }+ LimitPositions();+ for (int iteration = 0; iteration < options.Iterations; iteration++)+ {+ RefreshBounds(options, contacts);+ foreach (var color in Plan.ConstraintColors)+ {+ foreach (int index in color)+ {+ ProjectConstraint(index, h, options.StitchComplianceScale);+ }+ }+ for (int contact = 0; contact < options.ContactIterations; contact++)+ {+ ProjectContacts(contacts);+ ProjectOffsetContacts(options, h);+ }+ }+ for (int vertex = 0; vertex < positions.Length; vertex++)+ {+ velocities[vertex] = (positions[vertex] - previous[vertex]) * (damping / h);+ }+ }+ Tick++;+ }++ private void RefreshBounds(ClothStepOptions3D options, ClothContacts3D contacts)+ {+ if (Plan.ContactTopology is null)+ {+ return;+ }+ positions.CopyTo(contactAnchor, 0);+ contactBounds = ClothOffsetContact3D.Bounds(Plan, contactAnchor, contacts, options.ContactSafetyFactor);+ }++ private void LimitPositions()+ {+ if (contactBounds is null)+ {+ return;+ }+ for (int vertex = 0; vertex < positions.Length; vertex++)+ {+ positions[vertex] = ClothOffsetContact3D.Clip(positions[vertex], contactAnchor[vertex], contactBounds[vertex]);+ }+ }++ private void Move(int vertex, Vector3 correction)+ {+ Vector3 proposed = positions[vertex] + correction;+ positions[vertex] = contactBounds is null ? proposed+ : ClothOffsetContact3D.Clip(proposed, contactAnchor[vertex], contactBounds[vertex]);+ }++ private void ProjectOffsetContacts(ClothStepOptions3D options, float h)+ {+ if (Plan.ContactTopology is not { } topology)+ {+ return;+ }+ float alpha = options.OffsetContactCompliance / (h * h);+ foreach (var color in topology.Colors)+ {+ foreach (int index in color)+ {+ var pair = topology.Pairs[index];+ var query = ClothOffsetContact3D.Query(topology, pair, positions);+ if (!query.Active || query.Distance >= Plan.Definition.Material.Thickness)+ {+ contactLambda[index] = 0;+ continue;+ }+ Vector2 potential = ClothOffsetContact3D.Potential(query.Distance, Plan.Definition.Material.Thickness);+ float movable = 0;+ for (int local = 0; local < pair.Vertices.Length; local++)+ {+ float weight = query.Weights[local] * potential.Y;+ movable += Plan.InverseMasses[pair.Vertices[local]] * weight * weight;+ }+ if (movable <= 1e-20f)+ {+ continue;+ }+ float increment = (-potential.X - alpha * contactLambda[index]) / (movable + alpha);+ contactLambda[index] += increment;+ for (int local = 0; local < pair.Vertices.Length; local++)+ {+ int vertex = pair.Vertices[local];+ Move(vertex, query.Normal * (Plan.InverseMasses[vertex] * query.Weights[local] * potential.Y * increment));+ }+ }+ }+ }++ private void ProjectConstraint(int index, float h, float stitchComplianceScale)+ {+ var constraint = Plan.Constraints[index];+ float compliance = constraint.Kind == ClothConstraintKind3D.Stitch+ ? constraint.Compliance * stitchComplianceScale : constraint.Compliance;+ float alpha = compliance / (h * h);+ if (constraint.Kind is not (ClothConstraintKind3D.FlatBend or ClothConstraintKind3D.VertexBend or ClothConstraintKind3D.Stitch))+ {+ int a = constraint.Vertices[0];+ int b = constraint.Vertices[1];+ float wa = Plan.InverseMasses[a];+ float wb = Plan.InverseMasses[b];+ Vector3 difference = positions[a] - positions[b];+ float length = difference.Length();+ if (length < 1e-10f || wa + wb == 0)+ {+ return;+ }+ float delta = (-(length - constraint.RestLength) - alpha * lambda[index].X) / (wa + wb + alpha);+ lambda[index].X += delta;+ Vector3 correction = difference * (delta / length);+ Move(a, correction * wa);+ Move(b, -correction * wb);+ return;+ }+ Vector3 curvature = Vector3.Zero;+ float denominator = alpha;+ float movable = 0;+ for (int local = 0; local < constraint.Vertices.Length; local++)+ {+ int vertex = constraint.Vertices[local];+ float weight = constraint.Weights[local];+ curvature += positions[vertex] * weight;+ float term = Plan.InverseMasses[vertex] * weight * weight;+ denominator += term;+ movable += term;+ }+ if (movable <= 1e-20f)+ {+ return;+ }+ Vector3 increment = (-curvature - alpha * lambda[index]) / denominator;+ lambda[index] += increment;+ for (int local = 0; local < constraint.Vertices.Length; local++)+ {+ int vertex = constraint.Vertices[local];+ Move(vertex, increment * (Plan.InverseMasses[vertex] * constraint.Weights[local]));+ }+ }++ private void ProjectContacts(ClothContacts3D contacts)+ {+ float thickness = Plan.Definition.Material.Thickness * .5f;+ for (int vertex = 0; vertex < positions.Length; vertex++)+ {+ if (Plan.InverseMasses[vertex] == 0)+ {+ continue;+ }+ if (contacts.BodySurface is { } body)+ {+ var sample = body.Query(positions[vertex]);+ float clearance = thickness + contacts.BodyClearance;+ if (sample.SignedDistance < clearance)+ {+ Move(vertex, sample.Normal * (clearance - sample.SignedDistance));+ }+ }+ if (contacts.PlaneNormal is { } normal)+ {+ float gap = Vector3.Dot(normal, positions[vertex]) - contacts.PlaneOffset - thickness;+ if (gap < 0)+ {+ Move(vertex, -normal * gap);+ }+ }+ if (contacts.SphereCenter is { } center)+ {+ Vector3 delta = positions[vertex] - center;+ float distance = delta.Length();+ float radius = contacts.SphereRadius + thickness;+ if (distance < radius)+ {+ Vector3 outward = distance > 1e-10f ? delta / distance : Vector3.UnitY;+ Move(vertex, center + outward * radius - positions[vertex]);+ }+ }+ }+ if (contacts.BodySurface is { } bodySurface)+ {+ foreach (var color in Plan.TriangleColors)+ {+ foreach (int triangle in color)+ {+ int a = Plan.Definition.Indices[triangle * 3];+ int b = Plan.Definition.Indices[triangle * 3 + 1];+ int c = Plan.Definition.Indices[triangle * 3 + 2];+ Vector3 center = (positions[a] + positions[b] + positions[c]) / 3;+ float radius = MathF.Max(Vector3.Distance(center, positions[a]),+ MathF.Max(Vector3.Distance(center, positions[b]), Vector3.Distance(center, positions[c])));+ // A positive nearest-surface distance beyond the containing sphere+ // certifies this triangle is outside the static contact neighborhood.+ if (bodySurface.Query(center).SignedDistance > radius + thickness + contacts.BodyClearance) continue;+ foreach (Vector3 barycentric in ClothBodyContact3D.Samples)+ {+ Vector3 point = positions[a] * barycentric.X + positions[b] * barycentric.Y + positions[c] * barycentric.Z;+ var sample = bodySurface.Query(point);+ float penetration = thickness + contacts.BodyClearance - sample.SignedDistance;+ if (penetration <= 0) continue;+ float denominator = Plan.InverseMasses[a] * barycentric.X * barycentric.X+ + Plan.InverseMasses[b] * barycentric.Y * barycentric.Y+ + Plan.InverseMasses[c] * barycentric.Z * barycentric.Z;+ if (denominator <= 1e-20f) continue;+ Vector3 correction = sample.Normal * (penetration / denominator);+ Move(a, correction * (Plan.InverseMasses[a] * barycentric.X));+ Move(b, correction * (Plan.InverseMasses[b] * barycentric.Y));+ Move(c, correction * (Plan.InverseMasses[c] * barycentric.Z));+ }+ }+ }+ }+ if (contacts.SphereCenter is not { } sphere)+ {+ return;+ }+ foreach (var color in Plan.TriangleColors)+ {+ foreach (int triangle in color)+ {+ int a = Plan.Definition.Indices[triangle * 3];+ int b = Plan.Definition.Indices[triangle * 3 + 1];+ int c = Plan.Definition.Indices[triangle * 3 + 2];+ var closest = TriangleSurface3D.ClosestPoint(sphere, positions[a], positions[b], positions[c]);+ Vector3 delta = closest.Point - sphere;+ float distance = delta.Length();+ float penetration = contacts.SphereRadius + thickness - distance;+ if (penetration <= 0)+ {+ continue;+ }+ Vector3 barycentric = closest.Barycentric;+ float denominator = Plan.InverseMasses[a] * barycentric.X * barycentric.X+ + Plan.InverseMasses[b] * barycentric.Y * barycentric.Y+ + Plan.InverseMasses[c] * barycentric.Z * barycentric.Z;+ if (denominator <= 1e-20f)+ {+ continue;+ }+ Vector3 normal = distance > 1e-10f ? delta / distance : Vector3.UnitY;+ Vector3 correction = normal * (penetration / denominator);+ Move(a, correction * (Plan.InverseMasses[a] * barycentric.X));+ Move(b, correction * (Plan.InverseMasses[b] * barycentric.Y));+ Move(c, correction * (Plan.InverseMasses[c] * barycentric.Z));+ }+ }+ }++ public ClothSnapshot3D Capture() => new(Plan.ContentKey, Tick, positions.ToImmutableArray(),+ velocities.ToImmutableArray(), targets.ToImmutableArray());++ public void Restore(ClothSnapshot3D snapshot)+ {+ ClothState3D.ValidateSnapshot(Plan, snapshot);+ if (Plan.ContactTopology is not null)+ {+ ClothOffsetContact3D.ValidateInitial(Plan, snapshot, new());+ }+ snapshot.Positions.CopyTo(positions);+ snapshot.Velocities.CopyTo(velocities);+ snapshot.PinTargets.CopyTo(targets);+ Tick = snapshot.Tick;+ }++ public void Dispose() { }+}++public static class ClothState3D+{+ public static void ValidateStep(CompiledCloth3D plan, ClothStepOptions3D options, ClothContacts3D contacts)+ {+ ArgumentNullException.ThrowIfNull(options);+ ArgumentNullException.ThrowIfNull(contacts);+ options.Validate();+ contacts.Validate();+ float h = options.DeltaSeconds / options.Substeps;+ if (plan.Constraints.Any(constraint => !float.IsFinite(constraint.Compliance / (h * h))))+ {+ throw new ArgumentException("Cloth compliance and timestep exceed finite solver arithmetic.");+ }+ if (!float.IsFinite(options.OffsetContactCompliance / (h * h)))+ {+ throw new ArgumentException("Offset contact compliance exceeds finite solver arithmetic.");+ }+ }++ public static void ValidatePin(CompiledCloth3D plan, int vertex, Vector3 target)+ {+ ClothValidation3D.Finite(target);+ if (vertex < 0 || vertex >= plan.InverseMasses.Length || plan.InverseMasses[vertex] != 0)+ {+ throw new ArgumentException("Pin commands require an authored pinned vertex.");+ }+ }++ public static void ValidateSnapshot(CompiledCloth3D plan, ClothSnapshot3D snapshot)+ {+ ArgumentNullException.ThrowIfNull(snapshot);+ int count = plan.Definition.Positions.Length;+ if (snapshot.ContentKey != plan.ContentKey || snapshot.Tick < 0 || snapshot.Positions.IsDefault+ || snapshot.Velocities.IsDefault || snapshot.PinTargets.IsDefault || snapshot.Positions.Length != count+ || snapshot.Velocities.Length != count || snapshot.PinTargets.Length != count)+ {+ throw new ArgumentException("Cloth snapshot belongs to another topology/material or has invalid state dimensions.");+ }+ foreach (Vector3 value in snapshot.Positions)+ {+ ValidateVector(value);+ }+ foreach (Vector3 value in snapshot.Velocities)+ {+ ValidateVector(value);+ }+ foreach (Vector3 value in snapshot.PinTargets)+ {+ ValidateVector(value);+ }+ }++ private static void ValidateVector(Vector3 value) => ClothValidation3D.Finite(value);++ public static ClothMetrics3D Measure(CompiledCloth3D plan, ClothSnapshot3D snapshot, ClothContacts3D contacts)+ {+ ValidateSnapshot(plan, snapshot);+ contacts.Validate();+ var positions = snapshot.Positions;+ float stretch = 0;+ float bending = 0;+ foreach (var constraint in plan.Constraints)+ {+ 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]]);+ stretch = MathF.Max(stretch, length / constraint.RestLength - 1);+ }+ else+ {+ Vector3 curvature = Vector3.Zero;+ for (int local = 0; local < constraint.Vertices.Length; local++)+ {+ curvature += positions[constraint.Vertices[local]] * constraint.Weights[local];+ }+ if (constraint.Kind != ClothConstraintKind3D.Stitch)+ {+ bending += .5f * curvature.LengthSquared();+ }+ }+ }+ float pinError = 0;+ foreach (int vertex in plan.Definition.Pins)+ {+ pinError = MathF.Max(pinError, Vector3.Distance(positions[vertex], snapshot.PinTargets[vertex]));+ }+ float penetration = 0;+ float halfThickness = plan.Definition.Material.Thickness * .5f;+ if (contacts.PlaneNormal is { } normal)+ {+ foreach (Vector3 position in positions)+ {+ penetration = MathF.Max(penetration, contacts.PlaneOffset + halfThickness - Vector3.Dot(normal, position));+ }+ }+ if (contacts.SphereCenter is { } sphere)+ {+ for (int triangle = 0; triangle < plan.Definition.Indices.Length; triangle += 3)+ {+ var indices = plan.Definition.Indices;+ var closest = TriangleSurface3D.ClosestPoint(sphere, positions[indices[triangle]],+ positions[indices[triangle + 1]], positions[indices[triangle + 2]]);+ penetration = MathF.Max(penetration, contacts.SphereRadius + halfThickness - Vector3.Distance(sphere, closest.Point));+ }+ }+ if (contacts.BodySurface is { } body)+ {+ foreach (Vector3 position in positions)+ {+ penetration = MathF.Max(penetration, halfThickness + contacts.BodyClearance - body.Query(position).SignedDistance);+ }+ for (int face = 0; face < plan.Definition.Indices.Length; face += 3)+ {+ int a = plan.Definition.Indices[face];+ int b = plan.Definition.Indices[face + 1];+ int c = plan.Definition.Indices[face + 2];+ foreach (Vector3 barycentric in ClothBodyContact3D.Samples)+ {+ Vector3 point = positions[a] * barycentric.X + positions[b] * barycentric.Y + positions[c] * barycentric.Z;+ penetration = MathF.Max(penetration, halfThickness + contacts.BodyClearance - body.Query(point).SignedDistance);+ }+ }+ }+ ClothOffsetMetrics3D? offsetMetrics = null;+ if (plan.ContactTopology is { } topology)+ {+ float clearance = 1e6f;+ float overlap = 0;+ int active = 0;+ foreach (var pair in topology.Pairs)+ {+ var query = ClothOffsetContact3D.Query(topology, pair, positions);+ if (pair.Kind is ClothContactFeature3D.Face or ClothContactFeature3D.EdgePair)+ {+ clearance = MathF.Min(clearance, query.Distance);+ }+ if (query.Active && query.Distance < plan.Definition.Material.Thickness)+ {+ overlap = MathF.Max(overlap, plan.Definition.Material.Thickness - query.Distance);+ active++;+ }+ }+ offsetMetrics = new(clearance, overlap, active);+ }+ return new(stretch, pinError, penetration, bending,+ float.IsFinite(stretch) && float.IsFinite(bending)) { OffsetContact = offsetMetrics };+ }+}diff --git a/Aetheris.Cloth3D/ClothVertexBending3D.cs b/Aetheris.Cloth3D/ClothVertexBending3D.csnew file mode 100644index 00000000..3e82f82c--- /dev/null+++ b/Aetheris.Cloth3D/ClothVertexBending3D.cs@@ -0,0 +1,97 @@+using System.Collections.Immutable;+using System.Numerics;++namespace Aetheris.Cloth3D;++/// <summary>Better Bending Eq.39-40: each row of (L + N) / sqrt(barycentric area).+/// The normal derivative N cancels the spurious membrane force on free boundaries.+/// Rest-flat QB(PL), not an intrinsic triangulation or a director shell.</summary>+internal static class ClothVertexBending3D+{+ public static IEnumerable<ClothConstraint3D> Compile(ClothDefinition3D definition)+ {+ int count = definition.Positions.Length;+ var rows = Enumerable.Range(0, count).Select(_ => new SortedDictionary<int, double>()).ToArray();+ double[] areas = new double[count];+ var edges = new SortedDictionary<(int A, int B), List<int>>();+ for (int face = 0; face < definition.Indices.Length; face += 3)+ {+ int a = definition.Indices[face];+ int b = definition.Indices[face + 1];+ int c = definition.Indices[face + 2];+ double area = Vector3.Cross(definition.Positions[b] - definition.Positions[a],+ definition.Positions[c] - definition.Positions[a]).Length() * .5;+ areas[a] += area / 3;+ areas[b] += area / 3;+ areas[c] += area / 3;+ AddEdge(a, b, c);+ AddEdge(b, c, a);+ AddEdge(c, a, b);+ }+ foreach (var (edge, opposite) in edges)+ {+ double cotangent = opposite.Sum(vertex => Cotangent(edge.A, vertex, edge.B));+ Add(edge.A, edge.B, cotangent * .5);+ Add(edge.A, edge.A, -cotangent * .5);+ Add(edge.B, edge.A, cotangent * .5);+ Add(edge.B, edge.B, -cotangent * .5);+ if (opposite.Count == 1)+ {+ int interior = opposite[0];+ double atA = Cotangent(interior, edge.A, edge.B) * .5;+ double atB = Cotangent(edge.A, edge.B, interior) * .5;+ foreach (int boundary in new[] { edge.A, edge.B })+ {+ Add(boundary, edge.B, atA);+ Add(boundary, edge.A, atB);+ Add(boundary, interior, -atA - atB);+ }+ }+ }+ for (int vertex = 0; vertex < count; vertex++)+ {+ var entries = rows[vertex].Where(entry => Math.Abs(entry.Value) > 1e-12).ToArray();+ if (entries.Length == 0)+ {+ continue;+ }+ if (entries.Length > 32)+ {+ throw new NotSupportedException("AUR-CLOTH-003: Bending supports at most 32 vertices per compiled row; remesh high-valence vertices.");+ }+ double scale = 1 / Math.Sqrt(areas[vertex]);+ var weights = entries.Select(entry => (float)(entry.Value * scale)).ToImmutableArray();+ if (weights.Any(weight => !float.IsFinite(weight)))+ {+ throw new ArgumentException("Nonfinite vertex bending operator.");+ }+ yield return new(ClothConstraintKind3D.VertexBend,+ entries.Select(entry => entry.Key).ToImmutableArray(), weights, 0,+ definition.Material.BendCompliance);+ }++ void Add(int row, int column, double value)+ {+ rows[row].TryGetValue(column, out double current);+ rows[row][column] = current + value;+ }++ void AddEdge(int a, int b, int opposite)+ {+ var key = (Math.Min(a, b), Math.Max(a, b));+ if (!edges.TryGetValue(key, out var vertices))+ {+ vertices = [];+ edges.Add(key, vertices);+ }+ vertices.Add(opposite);+ }++ double Cotangent(int a, int center, int b)+ {+ Vector3 first = definition.Positions[a] - definition.Positions[center];+ Vector3 second = definition.Positions[b] - definition.Positions[center];+ return Vector3.Dot(first, second) / (double)Vector3.Cross(first, second).Length();+ }+ }+}diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/PlanarMeshQualityTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/PlanarMeshQualityTests.csnew file mode 100644index 00000000..fb3bd790--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/PlanarMeshQualityTests.cs@@ -0,0 +1,49 @@+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;++public sealed class PlanarMeshQualityTests+{+ [Fact]+ public void SkewQuadrilateralFlipsItsBadDiagonalWithoutChangingBoundaryOrArea()+ {+ Point3D[] points = [new(0, 0, 0), new(2, 0, 0), new(2, 1, 0), new(0, 3, 0)];+ int[] original = [0, 1, 3, 1, 2, 3];+ var improved = PlanarMeshQuality.Improve(points, original);+ Assert.Equal(improved.ToArray(), PlanarMeshQuality.Improve(points, original).ToArray());+ Assert.Equal(improved.ToArray(), PlanarMeshQuality.Improve(points, improved).ToArray());+ var counts = new Dictionary<(int, int), int>();+ double area = 0;+ for (int face = 0; face < improved.Count; face += 3)+ {+ var a = points[improved[face]];+ var b = points[improved[face + 1]];+ var c = points[improved[face + 2]];+ double twiceArea = (b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X);+ Assert.True(twiceArea > 0);+ area += twiceArea * .5;+ for (int edge = 0; edge < 3; edge++)+ {+ int first = improved[face + edge];+ int second = improved[face + (edge + 1) % 3];+ var key = (System.Math.Min(first, second), System.Math.Max(first, second));+ counts[key] = counts.GetValueOrDefault(key) + 1;+ }+ }+ Assert.Equal(4, area);+ Assert.Equal(2, counts[(0, 2)]);+ Assert.False(counts.ContainsKey((1, 3)));+ Assert.All(new[] { (0, 1), (1, 2), (2, 3), (0, 3) }, edge => Assert.Equal(1, counts[edge]));+ }++ [Fact]+ public void InvalidMeshStopsRatherThanPretendingToImprove()+ {+ Point3D[] points = [new(0, 0, 0), new(1, 0, 0), new(0, 1, 0)];+ Assert.Throws<ArgumentException>(() => PlanarMeshQuality.Improve(points, [0, 2, 1]));+ Assert.Throws<ArgumentException>(() => PlanarMeshQuality.Improve(points, [0, 0, 1]));+ points[2] = new(double.NaN, 1, 0);+ Assert.Throws<ArgumentException>(() => PlanarMeshQuality.Improve(points, [0, 1, 2]));+ }+}diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/PlanarMeshQuality.cs b/Aetheris.Kernel.Core/Brep/Tessellation/PlanarMeshQuality.csnew file mode 100644index 00000000..acffc187--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/Tessellation/PlanarMeshQuality.cs@@ -0,0 +1,103 @@+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Kernel.Core.Brep.Tessellation;++/// <summary>Bounded Lawson flips on a counterclockwise XY triangulation. Boundary+/// edges and vertex identities remain unchanged. This does not insert or move geometry.</summary>+public static class PlanarMeshQuality+{+ public static IReadOnlyList<int> Improve(IReadOnlyList<Point3D> points, IReadOnlyList<int> source)+ {+ ArgumentNullException.ThrowIfNull(points);+ ArgumentNullException.ThrowIfNull(source);+ if (source.Count % 3 != 0 || source.Any(index => index < 0 || index >= points.Count)+ || points.Any(point => !double.IsFinite(point.X) || !double.IsFinite(point.Y) || !double.IsFinite(point.Z)))+ {+ throw new ArgumentException("Expected valid indexed XY triangles.");+ }+ var indices = source.ToArray();+ for (int face = 0; face < indices.Length; face += 3)+ {+ if (Cross(indices[face], indices[face + 1], indices[face + 2]) <= 0)+ {+ throw new ArgumentException("Expected nondegenerate counterclockwise XY triangles.");+ }+ }+ for (int pass = 0; pass < 128; pass++)+ {+ var edges = new Dictionary<(int, int), List<(int Face, int Opposite)>>();+ for (int face = 0; face < indices.Length; face += 3)+ {+ for (int edge = 0; edge < 3; edge++)+ {+ int a = indices[face + edge];+ int b = indices[face + (edge + 1) % 3];+ var key = (System.Math.Min(a, b), System.Math.Max(a, b));+ if (!edges.TryGetValue(key, out var neighbors))+ {+ edges.Add(key, neighbors = []);+ }+ neighbors.Add((face, indices[face + (edge + 2) % 3]));+ }+ }+ var changed = new HashSet<int>();+ foreach (var (edge, neighbors) in edges.OrderBy(entry => entry.Key))+ {+ if (neighbors.Count != 2 || neighbors.Any(neighbor => changed.Contains(neighbor.Face)))+ {+ continue;+ }+ int a = edge.Item1;+ int b = edge.Item2;+ int c = neighbors[0].Opposite;+ int d = neighbors[1].Opposite;+ if (c == d || Cross(a, b, c) * Cross(a, b, d) >= 0 || Cross(c, d, a) * Cross(c, d, b) >= 0)+ {+ continue;+ }+ double cotangents = Cotangent(a, c, b) + Cotangent(a, d, b);+ if (cotangents >= -1e-8)+ {+ continue;+ }+ Set(neighbors[0].Face, c, d, a);+ Set(neighbors[1].Face, d, c, b);+ changed.Add(neighbors[0].Face);+ changed.Add(neighbors[1].Face);+ }+ if (changed.Count == 0)+ {+ return indices;+ }+ }+ throw new InvalidOperationException("planar-mesh-quality-budget: Delaunay flips exceeded 128 passes.");++ double Cross(int a, int b, int c)+ {+ return (points[b].X - points[a].X) * (points[c].Y - points[a].Y)+ - (points[b].Y - points[a].Y) * (points[c].X - points[a].X);+ }+ double Cotangent(int a, int center, int b)+ {+ double ax = points[a].X - points[center].X;+ double ay = points[a].Y - points[center].Y;+ double bx = points[b].X - points[center].X;+ double by = points[b].Y - points[center].Y;+ return (ax * bx + ay * by) / System.Math.Abs(ax * by - ay * bx);+ }+ void Set(int face, int a, int b, int c)+ {+ indices[face] = a;+ if (Cross(a, b, c) > 0)+ {+ indices[face + 1] = b;+ indices[face + 2] = c;+ }+ else+ {+ indices[face + 1] = c;+ indices[face + 2] = b;+ }+ }+ }+}diff --git a/Aetheris.Kernel.Core/Math/TriangleSurface3D.cs b/Aetheris.Kernel.Core/Math/TriangleSurface3D.csnew file mode 100644index 00000000..29f1c9dc--- /dev/null+++ b/Aetheris.Kernel.Core/Math/TriangleSurface3D.cs@@ -0,0 +1,74 @@+using System.Numerics;++namespace Aetheris.Kernel.Core.Math;++public readonly record struct TriangleProximity3D(Vector3 Point, Vector3 Barycentric);++/// <summary>Shared closest-surface query. Degenerate triangles reduce to their longest edge.</summary>+public static class TriangleSurface3D+{+ public static TriangleProximity3D ClosestPoint(Vector3 point, Vector3 a, Vector3 b, Vector3 c)+ {+ Vector3 ab = b - a;+ Vector3 ac = c - a;+ float aa = Vector3.Dot(ab, ab);+ float bb = Vector3.Dot(ab, ac);+ float cc = Vector3.Dot(ac, ac);+ float determinant = aa * cc - bb * bb;+ if (determinant <= 1e-8f * aa * cc || aa * cc < 1e-24f)+ {+ float bc = Vector3.DistanceSquared(b, c);+ if (aa >= cc && aa >= bc)+ {+ return Segment(point, a, b, Vector3.UnitX, Vector3.UnitY);+ }+ if (cc >= bc)+ {+ return Segment(point, a, c, Vector3.UnitX, Vector3.UnitZ);+ }+ return Segment(point, b, c, Vector3.UnitY, Vector3.UnitZ);+ }+ Vector3 closest = ClosestOnTriangle(point, a, b, c);+ Vector3 delta = closest - a;+ float x = Vector3.Dot(delta, ab);+ float y = Vector3.Dot(delta, ac);+ float v = (cc * x - bb * y) / determinant;+ float w = (aa * y - bb * x) / determinant;+ return new(closest, new(1 - v - w, v, w));+ }++ private static Vector3 ClosestOnTriangle(Vector3 p, Vector3 a, Vector3 b, Vector3 c)+ {+ Vector3 ab = b - a;+ Vector3 ac = c - a;+ Vector3 ap = p - a;+ float d1 = Vector3.Dot(ab, ap);+ float d2 = Vector3.Dot(ac, ap);+ if (d1 <= 0 && d2 <= 0) return a;+ Vector3 bp = p - b;+ float d3 = Vector3.Dot(ab, bp);+ float d4 = Vector3.Dot(ac, bp);+ if (d3 >= 0 && d4 <= d3) return b;+ float vc = d1 * d4 - d3 * d2;+ if (vc <= 0 && d1 >= 0 && d3 <= 0) return a + ab * (d1 / (d1 - d3));+ Vector3 cp = p - c;+ float d5 = Vector3.Dot(ab, cp);+ float d6 = Vector3.Dot(ac, cp);+ if (d6 >= 0 && d5 <= d6) return c;+ float vb = d5 * d2 - d1 * d6;+ if (vb <= 0 && d2 >= 0 && d6 <= 0) return a + ac * (d2 / (d2 - d6));+ float va = d3 * d6 - d5 * d4;+ if (va <= 0 && d4 >= d3 && d5 >= d6) return b + (c - b) * ((d4 - d3) / (d4 - d3 + d5 - d6));+ float inverse = 1 / (va + vb + vc);+ return a + ab * (vb * inverse) + ac * (vc * inverse);+ }++ private static TriangleProximity3D Segment(Vector3 point, Vector3 start, Vector3 end,+ Vector3 startWeight, Vector3 endWeight)+ {+ Vector3 edge = end - start;+ float length = edge.LengthSquared();+ float t = length > 1e-20f ? System.Math.Clamp(Vector3.Dot(point - start, edge) / length, 0, 1) : 0;+ return new(start + edge * t, startWeight * (1 - t) + endWeight * t);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.csindex 90e37a2a..b973b7c1 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs@@ -8,7 +8,7 @@ public sealed class FirmamentSemanticSchemaTestspublic void GeneratedRegistry_IsStableOptInAndCoversFirstConstructs(){Assert.Equal("firmament-semantic-schema/1", FirmamentSemanticSchemas.Version);- Assert.Equal(["Appearance", "FrameTransform", "Placement", "Pmi", "Note", "Provenance", "Box", "Concept", "Points", "Door", "Helix", "Hole", "Interface<Fixed>", "Interface<Prismatic>", "Interface<Revolute>", "Loft", "Perforation", "Material", "Linear", "Series", "Room", "Scene", "Camera", "Section", "Thread", "Window", "Follow", "WireRoute"], FirmamentSemanticSchemas.All.Select(s => s.Name));+ Assert.Equal(["Appearance", "FrameTransform", "Placement", "Pmi", "Note", "Provenance", "Box", "Concept", "Points", "Door", "Drape", "Fabric", "Garment", "Helix", "Hole", "Interface<Fixed>", "Interface<Prismatic>", "Interface<Revolute>", "Interface<Stitch>", "Loft", "Panel", "Perforation", "Material", "Linear", "Series", "Room", "Scene", "Camera", "Section", "Thread", "Window", "Follow", "WireRoute"], FirmamentSemanticSchemas.All.Select(s => s.Name));var hole = Assert.IsType<FirmamentConstructSchema>(FirmamentSemanticSchemas.Get("Hole"));var diameter = Assert.Single(hole.Fields, f => f.Name == "Diameter");Assert.Equal("Hole.Diameter", diameter.Id.Value);diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2NamedSetTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2NamedSetTests.csindex 5b952bcf..d3355a96 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2NamedSetTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2NamedSetTests.cs@@ -4,6 +4,20 @@ namespace Aetheris.Kernel.Firmament.Tests;public sealed class FirmamentV2NamedSetTests{+ [Theory]+ [InlineData("// No entries yet\n", true)]+ [InlineData("broken: Point2(0mm, 0mm)\nvalid => Point2(1mm, 1mm)", false)]+ public void SetPrefixAdmitsCommentsButDoesNotSilentlyDropMalformedEntries(string body, bool accepted)+ {+ var diagnostics = new List<string>();+ var expanded = CanonicalStaticAuthoring.Expand("Static Points: Set<Point2> { " + body + " }", diagnostics);+ Assert.Equal(accepted, expanded is not null && diagnostics.Count == 0);+ if (!accepted)+ {+ Assert.Contains(diagnostics, diagnostic => diagnostic.StartsWith("firmament-v2-static-set-entry-malformed", StringComparison.Ordinal));+ }+ }+[Fact]public void PointSet_PreservesNamesOrderValuesAndNamedAccess(){diff --git a/Aetheris.Kernel.Firmament.Tests/GarmentAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/GarmentAuthoringTests.csnew file mode 100644index 00000000..7a2098d9--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/GarmentAuthoringTests.cs@@ -0,0 +1,209 @@+using System.Collections.Immutable;+using System.Numerics;+using Aetheris.Cloth3D;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Garment;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class GarmentAuthoringTests+{+ [Theory]+ [InlineData("tunic", 2, 4)]+ [InlineData("shorts", 4, 8)]+ [InlineData("skirt", 2, 2)]+ [InlineData("flared-skirt", 2, 2)]+ public void RealGarmentsCompileThroughSharedRecipesAndRetainRestPatterns(string name, int panels, int seams)+ {+ var first = Compile(name);+ var second = Compile(name);+ Assert.Equal(panels, first.Panels.Length);+ Assert.Equal(seams, first.Source.Stitches.Length);+ Assert.NotEmpty(first.Source.Features);+ Assert.Equal("Profile", first.Source.Features[0].ReturnType);+ Assert.Equal(first.Cloth.ContentKey, second.Cloth.ContentKey);+ Assert.Equal(first.Cloth.Definition.Indices.ToArray(), second.Cloth.Definition.Indices.ToArray());+ Assert.All(first.Cloth.Definition.Positions, point => Assert.Equal(0, point.Z));+ Assert.NotEqual(first.Cloth.Definition.Positions, first.Cloth.Definition.InitialPositions);+ Assert.All(first.Cloth.Definition.Stitches, stitch =>+ {+ Assert.InRange(MathF.Abs(stitch.Weights.Sum()), 0, 1e-6f);+ Assert.InRange(stitch.Vertices.Length, 2, 4);+ });+ Assert.All(first.Cloth.ConstraintColors, color =>+ {+ var vertices = color.SelectMany(index => first.Cloth.Constraints[index].Vertices).ToArray();+ Assert.Equal(vertices.Length, vertices.Distinct().Count());+ });+ }++ [Fact]+ public void RemeshingKeepsSemanticEdgesAndUsesBarycentricStitches()+ {+ var coarse = Compile("shorts");+ var fine = GarmentCompiler.Compile(Source("shorts").Replace("meshSize: 60mm", "meshSize: 35mm"));+ Assert.True(fine.IsSuccess, string.Join("; ", fine.Diagnostics));+ Assert.True(fine.Garment!.Cloth.Definition.Positions.Length > coarse.Cloth.Definition.Positions.Length);+ Assert.Equal(coarse.Source.Stitches.ToArray(), fine.Garment.Source.Stitches.ToArray());+ Assert.All(coarse.Panels, panel => Assert.Equal(panel.Edges.Keys.Order(), fine.Garment.Panels.Single(p => p.Identity == panel.Identity).Edges.Keys.Order()));+ Assert.Contains(coarse.Cloth.Definition.Stitches, stitch => stitch.Vertices.Length > 2);+ }++ [Theory]+ [InlineData("schema Garment", "schema Mechanical", "firmament-schema-mismatch")]+ [InlineData("schema Garment", "", "garment-schema-required")]+ [InlineData("profile: skirtCut", "profile: missing", "garment-profile-invalid")]+ [InlineData("panels.front.edges.Left", "panels.front.edges.missing", "garment-stitch-edge-unknown")]+ [InlineData("orientation: Reversed", "orientation: Twisted", "garment-stitch-orientation")]+ [InlineData("grain: [0, 1]", "grain: [0, 2]", "garment-grain-invalid")]+ [InlineData("v: [0, 0, 1]", "v: [0, 0, 2]", "garment-panel-frame-invalid")]+ [InlineData("meshSize: 65mm", "meshSize: 1mm", "garment-mesh-budget")]+ [InlineData("pose: Rest", "pose: Walk", "garment-pose-unsupported")]+ [InlineData("front => SidePlacement", "front: SidePlacement", "firmament-v2-static-set-entry")]+ public void InvalidAuthoringStopsWithAnOwnedDiagnostic(string before, string after, string code)+ {+ var compiled = GarmentCompiler.Compile(Source("skirt").Replace(before, after));+ Assert.False(compiled.IsSuccess);+ Assert.Contains(compiled.Diagnostics, diagnostic => diagnostic.Code.StartsWith(code, StringComparison.Ordinal));+ }++ [Fact]+ public void FormatterPreservesAuthoredNamesAndProducesTheSameGarment()+ {+ string source = Source("skirt");+ string historical = source.Replace("meshSize:", "MeshSize:").Replace("profile:", "Profile:")+ .Replace("origin: side.origin;", "Origin: side.origin;").Replace("orientation:", "Orientation:");+ var preferred = FirmamentSourceSpelling.Prefer(historical);+ Assert.Contains("Interface<Stitch> leftSide", preferred);+ Assert.Contains("panels.front.edges.Left", preferred);+ Assert.Contains("meshSize:", preferred);+ preferred = FirmamentLanguageAnalysisService.Format(historical, "skirt.firmament", "1").Text;+ var formatted = GarmentCompiler.Compile(preferred);+ Assert.True(formatted.IsSuccess, string.Join("; ", formatted.Diagnostics) + "\n" + preferred);+ Assert.Equal(GarmentCompiler.Compile(source).Garment!.Cloth.ContentKey, formatted.Garment!.Cloth.ContentKey);+ Assert.Empty(FirmamentLanguageAnalysisService.Analyze(source, "skirt.firmament", "1").Diagnostics);+ }++ [Fact]+ public void InitialPlacementCannotRedefineRestLengthsOrMass()+ {+ var original = Compile("skirt").Cloth;+ var moved = (original.Definition with+ {+ InitialPositions = original.Definition.InitialPositions.Select(point => point * 2 + Vector3.One).ToImmutableArray(),+ }).Compile();+ Assert.Equal(original.InverseMasses.ToArray(), moved.InverseMasses.ToArray());+ Assert.Equal(original.Constraints.Select(constraint => constraint.RestLength), moved.Constraints.Select(constraint => constraint.RestLength));+ Assert.NotEqual(original.ContentKey, moved.ContentKey);+ using var solver = new ClothSolver3D(moved);+ Assert.Equal(moved.Definition.InitialPositions.ToArray(), solver.Capture().Positions.ToArray());+ }++ [Fact]+ public void InteriorContactDetectsPenetrationThatVertexChecksMiss()+ {+ var definition = ClothDefinition3D.Grid("interior-contact", 2, 2, new(.4f, .4f), new(-.2f, 0, -.2f));+ var plan = definition.Compile();+ using var solver = new ClothSolver3D(plan);+ var contacts = new ClothContacts3D { BodySurface = new SphereSurface() };+ var initial = solver.Capture();+ Assert.All(initial.Positions, point => Assert.True(contacts.BodySurface.Query(point).SignedDistance > 0));+ float before = ClothState3D.Measure(plan, initial, contacts).MaximumSurfacePenetration;+ Assert.True(before > .09f);+ solver.Step(new() { Gravity = Vector3.Zero, Substeps = 1, Iterations = 8 }, contacts);+ float after = ClothState3D.Measure(plan, solver.Capture(), contacts).MaximumSurfacePenetration;+ Assert.True(after < before * .1f, $"Interior contact did not improve: {before} -> {after}");+ }++ [Fact]+ public void StitchSolverClosesSeparatedEdgesAndReplaysExactly()+ {+ var compiled = Compile("skirt");+ var panel = compiled.Panels[1];+ var definition = compiled.Cloth.Definition with+ {+ Pins = [],+ InitialPositions = compiled.Cloth.Definition.InitialPositions.Select((point, index) =>+ index >= panel.VertexStart ? point + new Vector3(0, .05f, 0) : point).ToImmutableArray(),+ };+ var garment = compiled with { Cloth = definition.Compile() };+ using var solver = new ClothSolver3D(garment.Cloth);+ float before = garment.MaximumSeamGap(solver.Capture());+ var options = new ClothStepOptions3D { Gravity = Vector3.Zero, Substeps = 4, Iterations = 12 };+ for (int tick = 0; tick < 20; tick++)+ {+ solver.Step(options, new());+ }+ Assert.True(garment.MaximumSeamGap(solver.Capture()) < before * .1f);+ var saved = solver.Capture();+ solver.Step(options, new());+ var expected = solver.Capture();+ solver.Restore(saved);+ solver.Step(options, new());+ Assert.Equal(expected.Positions.ToArray(), solver.Capture().Positions.ToArray());+ Assert.Equal(expected.Velocities.ToArray(), solver.Capture().Velocities.ToArray());+ }++ [Fact]+ public void RuntimeArtifactRebuildsThePlanAndRejectsTampering()+ {+ var garment = Compile("skirt");+ using var original = new ClothSolver3D(garment.Cloth);+ original.Step(new() { Gravity = Vector3.Zero }, new());+ string json = GarmentExport.Artifact(garment, original.Capture());+ var loaded = ClothGarmentArtifact3D.Parse(json);+ using var restored = loaded.CreateSolver();+ Assert.Equal(garment.Cloth.ContentKey, loaded.Cloth.ContentKey);+ Assert.Equal(original.Capture().Positions.ToArray(), restored.Capture().Positions.ToArray());+ Assert.Equal(original.Tick, restored.Tick);+ Assert.Throws<InvalidDataException>(() => ClothGarmentArtifact3D.Parse(json.Replace(garment.Cloth.ContentKey, new string('0', 64))));+ Assert.Throws<InvalidDataException>(() => ClothGarmentArtifact3D.Parse(json.Replace("\"Z\"", "\"Y\"")));+ }++ [Fact]+ public void GeneratedGarmentEntryAndNestedCompletionUseTheOwnerSchemas()+ {+ string source = FirmamentSemanticSchemas.Get("Garment")!.Entry!;+ var compiled = GarmentCompiler.Compile(source);+ Assert.True(compiled.IsSuccess, string.Join("; ", compiled.Diagnostics));+ string panel = "schema Garment\nGarment Outfit { Panel front {\n ";+ var fields = FirmamentLanguageService.Complete(panel, "draft.firmament", "1", panel.Length);+ Assert.Equal("Panel", fields.Context);+ Assert.Contains(fields.Fields, field => field.Name == "Profile");+ string seam = "schema Garment\nGarment Outfit { Interface<Stitch> side {\n orientation: ";+ var choices = FirmamentLanguageService.Complete(seam, "draft.firmament", "1", seam.Length);+ Assert.Equal("Value", choices.Context);+ Assert.Contains("Reversed", choices.Values!);+ string root = "schema Garment\nGarment Outfit {\n ";+ var entries = FirmamentLanguageService.Complete(root, "draft.firmament", "1", root.Length);+ Assert.Contains(entries.Entries!, entry => entry.Name == "Panel");+ }++ private static CompiledGarment Compile(string name)+ {+ var result = GarmentCompiler.Compile(Source(name));+ Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics));+ return result.Garment!;+ }++ private static string Source(string name)+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx")))+ {+ root = root.Parent;+ }+ Assert.NotNull(root);+ return File.ReadAllText(Path.Combine(root!.FullName, "fixtures", "Canonical", "Garment", name + ".firmament"));+ }++ private sealed class SphereSurface : IClothBodySurface3D+ {+ public ClothBodySample3D Query(Vector3 point)+ {+ float distance = point.Length();+ Vector3 normal = distance > 1e-8f ? point / distance : Vector3.UnitY;+ return new(normal * .1f, normal, distance - .1f);+ }+ }+}diff --git a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csprojindex b3047132..97948b7f 100644--- a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj+++ b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj@@ -12,6 +12,8 @@<PackageReference Include="Copeland.TS.Backend.Wgsl" Version="0.1.0-preview.1-a3.16c0ce996358af80" /><PackageReference Include="Machina.Typography.OpenFont" Version="1.0.0" /><ProjectReference Include="..\Aetheris.Firmament.SchemaGenerator\Aetheris.Firmament.SchemaGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />+ <ProjectReference Include="../Aetheris.Cloth3D/Aetheris.Cloth3D.csproj" />+ <ProjectReference Include="../Aetheris.Humanoid/Aetheris.Humanoid.csproj" /><ProjectReference Include="..\Aetheris.Continuum\Aetheris.Continuum.csproj" /><ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" /><ProjectReference Include="..\Aetheris.Semantics\Aetheris.Semantics.csproj" />diff --git a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.csindex a1cdab57..c204714b 100644--- a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs+++ b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs@@ -6,7 +6,7 @@ namespace Aetheris.Kernel.Firmament;/// <summary>Program-level selection of an existing Firmament frontend. This is deliberately/// not a second parser or semantic IR: it only makes the current parser boundary explicit.</summary>-public enum FirmamentFrontendSchema { Mechanical, WireForm, Sweep, SectionChain }+public enum FirmamentFrontendSchema { Mechanical, WireForm, Sweep, SectionChain, Garment }public sealed record FirmamentFrontendSelection(FirmamentFrontendSchema? Schema, string Source, IReadOnlyList<string> Diagnostics){@@ -17,7 +17,7 @@ public sealed record FirmamentFrontendSelection(FirmamentFrontendSchema? Schema,public static class FirmamentFrontendSchemas{private static readonly Regex Declaration = new(@"(?m)^\s*schema\s+(?<name>[A-Za-z_]\w*)\s*;?\s*$", RegexOptions.CultureInvariant);- public static readonly IReadOnlyList<string> Names = ["Mechanical", "WireForm", "Sweep", "SectionChain"];+ public static readonly IReadOnlyList<string> Names = ["Mechanical", "WireForm", "Sweep", "SectionChain", "Garment"];public static FirmamentFrontendSelection Select(string source){@@ -33,7 +33,7 @@ public static class FirmamentFrontendSchemasif (!Enum.TryParse<FirmamentFrontendSchema>(name, false, out var schema))return new(null, source, [$"firmament-schema-unknown:{name}:available={string.Join(',', Names)}"]);var normalized = source.Remove(declaration.Index, declaration.Length);- if (schema != FirmamentFrontendSchema.Mechanical+ if (schema != FirmamentFrontendSchema.Mechanical && schema != FirmamentFrontendSchema.Garment&& Regex.IsMatch(normalized, @"\bFeature\s+[A-Za-z_]\w*\s*\(", RegexOptions.CultureInvariant))return new(schema, normalized, [$"firmament-feature-schema-unsupported:{schema}"]);var detected = DetectDistinctFrontend(normalized);@@ -43,6 +43,7 @@ public static class FirmamentFrontendSchemas}private static FirmamentFrontendSchema? DetectDistinctFrontend(string source) =>+ Garment.GarmentAuthoring.HasRoot(source) ? FirmamentFrontendSchema.Garment :WireFormAuthoring.IsWireFormSource(source) ? FirmamentFrontendSchema.WireForm :CircularSweepAuthoring.IsSweepSource(source) ? FirmamentFrontendSchema.Sweep :SectionChainAuthoringParser.IsSectionChainSource(source) ? FirmamentFrontendSchema.SectionChain : null;diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.csindex 6d298519..528d5b38 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs@@ -385,6 +385,11 @@ internal static class CanonicalStaticAuthoring{var body = source[start..end];var headers = Regex.Matches(body, @"(?<![A-Za-z0-9_])(?<name>[A-Za-z_]\w*)\s*=>", RegexOptions.CultureInvariant).Cast<Match>().ToArray();+ if (FirmamentLanguageAnalysisService.Lex(headers.Length == 0 ? body : body[..headers[0].Index])+ .Any(token => token.Shape != "comment"))+ {+ diagnostics.Add(Prefix + "set-entry-malformed:" + setName + ":use-name-arrow-value");+ }var result = new List<FirmamentV2StaticSetEntry>(); var names = new HashSet<string>(StringComparer.Ordinal);for (var index = 0; index < headers.Length; index++){@@ -449,7 +454,7 @@ internal static class CanonicalStaticAuthoringassociations.Add(new(semanticId, set.Name, entry.Name, entry.Value, entry.SourceOrder, entry.Provenance));continue;}- var construction = Regex.Match(declaration, @"\b(?:Hole\s*<\s*(?:Shaft|Counterbore|Countersink)\s*>|Slot\s*<\s*(?:Capsule|RoundedRectangle)\s*>|Boss|Pocket|EdgeFinish)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);+ var construction = Regex.Match(declaration, @"\b(?:Hole\s*<\s*(?:Shaft|Counterbore|Countersink)\s*>|Slot\s*<\s*(?:Capsule|RoundedRectangle)\s*>|Boss|Pocket|EdgeFinish|Panel)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);if (!construction.Success) { diagnostics.Add(Prefix + "pattern-body-invalid:" + patternName); return; }declaration = declaration.Remove(construction.Groups["name"].Index, construction.Groups["name"].Length).Insert(construction.Groups["name"].Index, materializedId);var openingBrace = declaration.IndexOf('{', construction.Index);@@ -543,7 +548,7 @@ internal static class CanonicalStaticAuthoring: id.Replace("[", "_", StringComparison.Ordinal).Replace("]", string.Empty, StringComparison.Ordinal);return $"{kind} {outputName}{declaration.Groups["tail"].Value} {{{body}}}";}- private static Dictionary<string, string> Fields(string body) => Regex.Matches(body, "\\b(?<name>[A-Za-z_]\\w*)\\s*:\\s*(?<value>\"[^\"]*\"|(?:Point2|Vector2|PlusMinus)\\s*\\([^)]*\\)|\\d+\\.\\d+\\.\\d+|\\d{4}-\\d{2}-\\d{2}|[A-Za-z_]\\w*|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?)", RegexOptions.CultureInvariant)+ private static Dictionary<string, string> Fields(string body) => Regex.Matches(body, "\\b(?<name>[A-Za-z_]\\w*)\\s*:\\s*(?<value>\"[^\"]*\"|(?:Point2|Point3|Vector2|PlusMinus)\\s*\\([^)]*\\)|\\d+\\.\\d+\\.\\d+|\\d{4}-\\d{2}-\\d{2}|[A-Za-z_]\\w*|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?)", RegexOptions.CultureInvariant).Cast<Match>().ToDictionary(m => m.Groups["name"].Value, m => m.Groups["value"].Value, StringComparer.Ordinal);private static IReadOnlyDictionary<string, IReadOnlyList<string>> TableColumns(string source, int start, int end){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.csindex 9a363846..4055dec1 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs@@ -32,6 +32,12 @@ public static class FirmamentLanguageAnalysisServicevar lexemes = Lex(FirmamentSourceSpelling.Normalize(source));var tokens = lexemes.Select((lexeme, index) => new FirmamentLanguageToken(lexeme.Start, lexeme.Length, Classify(lexemes, index))).ToArray();+ if (Garment.GarmentAuthoring.HasRoot(source))+ {+ var garment = Garment.GarmentCompiler.Compile(source, document);+ return new(document, revision, tokens, garment.Diagnostics.Select(diagnostic =>+ new FirmamentLanguageDiagnostic("error", diagnostic.Code, diagnostic.Message, 0, 0)).ToArray());+ }if (SceneAuthoring.HasRoot(source)){var scene = SceneAuthoring.Parse(source, document);@@ -109,7 +115,7 @@ public static class FirmamentLanguageAnalysisServicepublic static FirmamentLanguageAnalysis Analyze(FirmamentProjectSnapshot project, string document, string revision){if (!project.TryResolve(document, out var source)) throw new ArgumentException("Document is absent from the snapshot.", nameof(document));- if (SceneAuthoring.HasRoot(source)) return Analyze(source,document,revision);+ if (SceneAuthoring.HasRoot(source) || Garment.GarmentAuthoring.HasRoot(source)) return Analyze(source,document,revision);var tokens = Lex(FirmamentSourceSpelling.Normalize(source));var parsed = new AssemblyM0Parser().ParseProject(project);return new(document, revision, tokens.Select((t, i) => new FirmamentLanguageToken(t.Start, t.Length, Classify(tokens, i))).ToArray(),@@ -156,6 +162,21 @@ public static class FirmamentLanguageAnalysisServicepublic static FirmamentLanguageFormat Format(string source, string document, string revision){+ if (Garment.GarmentAuthoring.HasRoot(source))+ {+ var before = Garment.GarmentCompiler.Compile(source, document);+ if (!before.IsSuccess)+ {+ throw new InvalidOperationException("Format Document requires valid Garment source. Fix syntax errors first.");+ }+ var garmentFormat = FormatConventions(source, document, revision);+ var after = Garment.GarmentCompiler.Compile(garmentFormat.Text, document);+ if (!after.IsSuccess || before.Garment!.Cloth.ContentKey != after.Garment!.Cloth.ContentKey)+ {+ throw new InvalidOperationException("Garment formatting changed compilation.");+ }+ return garmentFormat;+ }if (SceneAuthoring.HasRoot(source)){if (!SceneAuthoring.Parse(source,document).IsSuccess)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.csindex 3707411f..5c75aa4b 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs@@ -94,9 +94,9 @@ public static class FirmamentLanguageServiceif (!present.Contains("Members")) missing.Add("Members");}if (context == "Helix" && !present.Contains("Pitch") && !present.Contains("Height")) missing.Add("Pitch or Height");- if (context == "Scene")+ if (context is "Scene" or "Garment"){- var entries = FirmamentSemanticSchemas.All.Where(item => item.Context == "Scene" && item.Entry is not null+ var entries = FirmamentSemanticSchemas.All.Where(item => item.Context == context && item.Entry is not null&& item.Name.StartsWith(prefix,StringComparison.OrdinalIgnoreCase)).Select(item => new FirmamentLanguageEntry(item.Id.Value,item.Name,item.Context!,FirmamentSourceSpelling.Prefer(item.Entry!))).ToArray();return new(document,revision,context,prefixStart,prefix.Length,candidates,missing,entries);@@ -139,8 +139,8 @@ public static class FirmamentLanguageService{// Ignore comments/strings and balance nested blocks in incomplete drafts.var prefix = Regex.Replace(source[..offset], @"//[^\r\n]*|/\*[\s\S]*?\*/|""(?:\\.|[^""\\])*""", m => new string(' ', m.Length));- var names = "Scene|Room|Door|Window|Camera|WireRoute|Follow|Section|Points|Linear|Series|Appearance|Material|Placement|FrameTransform";- var matches = Regex.Matches(prefix, $@"\b(?<kind>{names})(?:\s*<[^>]+>)?(?:\s+[A-Za-z_]\w*)?\s*\{{");+ var names = "Scene|Room|Door|Window|Camera|WireRoute|Follow|Section|Points|Linear|Series|Appearance|Material|Placement|FrameTransform|Garment|Panel|Fabric|Drape|Interface";+ var matches = Regex.Matches(prefix, $@"\b(?<kind>{names})(?:\s*<(?<family>[^>]+)>)?(?:\s+[A-Za-z_]\w*)?\s*\{{");foreach (Match header in matches.Cast<Match>().Reverse()){var depth = 1;@@ -150,7 +150,12 @@ public static class FirmamentLanguageServiceelse if (c == '}') depth--;if (depth == 0) break;}- if (depth > 0) return (header.Groups["kind"].Value, header.Index + header.Length - 1);+ if (depth > 0)+ {+ string name = header.Groups["kind"].Value;+ if (name == "Interface") name += "<" + header.Groups["family"].Value.Trim() + ">";+ return (name, header.Index + header.Length - 1);+ }}return null;}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.csindex 83bbb3e7..0bc89cf3 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs@@ -183,6 +183,11 @@ public static class FirmamentSourceSpelling// Bounded owner vocabularies not yet projected through generated schema.Add("Model", "Units Material");Add("Scene", "Units");+ Add("Garment", "Fabric MeshSize");+ Add("Panel", "Profile Origin U V Grain Pin PatternIdentity WrapRadius WrapAngle WrapTopRadius WrapTopOrigin WrapTopAngle");+ Add("Fabric", "ArealDensity Thickness WarpCompliance WeftCompliance DiagonalCompliance BendCompliance");+ Add("Interface", "A B Orientation Ease Compliance");+ Add("Drape", "Figure Pose Clearance");Add("Assembly Subassembly", "Anchor Provenance Appearance");Add("Part Occurrence", "Material Appearance");Add("Plane DatumPlane", "Origin Normal Up From Offset RotateLocal Clocking");@@ -194,6 +199,7 @@ public static class FirmamentSourceSpellingAdd("Polygon2", "Vertices");Add("Curve2", "From On Scale Pivot Translate Rotate");Add("CubicBezier2", "From Control1 Control2 To");+ Add("Line2", "From To");Add("Profile", "From");Add("Replace", "On Through Derivatives");Add("Path", "Start Heading");diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.csindex 5f8f6aaf..11d13a19 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs@@ -113,7 +113,7 @@ internal static class FirmamentV2FeatureExpansionelse{var constructor = Regex.Match(returned,- @"^(?<kind>Hole\s*<\s*(?:Shaft|Counterbore|Countersink)\s*>|Boss|Pocket|EdgeFinish)\s*\{",+ @"^(?<kind>Hole\s*<\s*(?:Shaft|Counterbore|Countersink)\s*>|Boss|Pocket|EdgeFinish|Profile)\s*\{",RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);if (!constructor.Success){@@ -183,11 +183,11 @@ internal static class FirmamentV2FeatureExpansionRegexOptions.CultureInvariant)){var returnType = NormalizeType(header.Groups["return"].Value);- if (!Regex.IsMatch(returnType, @"^(?:Hole<(?:Shaft|Counterbore|Countersink)>|Boss|Pocket|EdgeFinish)$", RegexOptions.CultureInvariant))+ if (!Regex.IsMatch(returnType, @"^(?:Hole<(?:Shaft|Counterbore|Countersink)>|Boss|Pocket|EdgeFinish|Profile)$", RegexOptions.CultureInvariant))diagnostics.Add(ReturnType + $":{header.Groups["name"].Value}:unsupported-{returnType}");}foreach (Match header in Regex.Matches(source,- @"\bFeature\s+(?<name>[A-Za-z_]\w*)\s*\((?<parameters>[^()]*)\)\s*->\s*(?<return>Hole\s*<\s*[A-Za-z_]\w*\s*>|Boss|Pocket|EdgeFinish)\s*\{",+ @"\bFeature\s+(?<name>[A-Za-z_]\w*)\s*\((?<parameters>[^()]*)\)\s*->\s*(?<return>Hole\s*<\s*[A-Za-z_]\w*\s*>|Boss|Pocket|EdgeFinish|Profile)\s*\{",RegexOptions.CultureInvariant)){var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}');@@ -216,7 +216,7 @@ internal static class FirmamentV2FeatureExpansion}var constructionNames = ImmutableArray.CreateBuilder<string>();var constructions = new List<string>();- foreach (Match local in Regex.Matches(beforeReturn, @"\b(?:Point2|Circle2|RoundedRect2|Rect2|Profile)\s+(?<name>[A-Za-z_]\w*)\s*\{"))+ foreach (Match local in Regex.Matches(beforeReturn, @"\b(?:Point2|Line2|CubicBezier2|Circle2|RoundedRect2|Rect2|Profile)\s+(?<name>[A-Za-z_]\w*)\s*\{")){var localClose = Matching(beforeReturn, beforeReturn.IndexOf('{', local.Index), '{', '}');if (localClose < 0) { diagnostics.Add(UnsupportedBody + ":" + name); continue; }diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.cs b/Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.csnew file mode 100644index 00000000..31cf5bd3--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.cs@@ -0,0 +1,511 @@+using System.Collections.Immutable;+using System.Globalization;+using System.Numerics;+using System.Security.Cryptography;+using System.Text;+using System.Text.RegularExpressions;+using Aetheris.Cloth3D;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Garment;++public sealed record GarmentDiagnostic(string Code, string Message, string SourceIdentity);+public sealed record GarmentPanel(string Name, string Identity, ResolvedProfile2D Profile,+ Vector3 Origin, Vector3 U, Vector3 V, Vector2 Grain, ImmutableArray<string> Pins,+ float? WrapRadius, float WrapAngle, float? WrapTopRadius, Vector3? WrapTopOrigin, float WrapTopAngle);+public sealed record GarmentStitch(string Name, string A, string B, bool Reversed, float Ease, float Compliance);+public sealed record GarmentSource(string Name, string SourceIdentity, string SourceHash,+ ClothMaterial3D Fabric, float MeshSize, ImmutableArray<GarmentPanel> Panels,+ ImmutableArray<GarmentStitch> Stitches, string? Figure, string? Pose,+ IReadOnlyList<FirmamentV2FeatureInvocation> Features,+ IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, float BodyClearance);+public sealed record GarmentParseResult(GarmentSource? Source, IReadOnlyList<GarmentDiagnostic> Diagnostics)+{+ public bool IsSuccess => Source is not null && Diagnostics.Count == 0;+}++/// <summary>Garment owns panel arrangement and distributed stitch semantics. Profiles,+/// pure Feature recipes, finite Pattern expansion and lexical analysis retain their existing owners.</summary>+public static class GarmentAuthoring+{+ public static bool HasRoot(string source)+ {+ var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape != "comment").ToArray();+ int depth = 0;+ for (int i = 0; i + 1 < tokens.Length; i++)+ {+ if (depth == 0 && tokens[i].Text == "Garment" && tokens[i + 1].Shape == "identifier")+ {+ return true;+ }+ if (tokens[i].Text == "{")+ {+ depth++;+ }+ if (tokens[i].Text == "}")+ {+ depth--;+ }+ }+ return false;+ }++ public static GarmentParseResult Parse(string source, string sourceIdentity = "<memory>")+ {+ try+ {+ return ParseCore(source, sourceIdentity);+ }+ catch (GarmentAuthoringException exception)+ {+ return new(null, [new(exception.Code, exception.Message, sourceIdentity)]);+ }+ catch (Exception exception) when (exception is FormatException or OverflowException or ArgumentException)+ {+ return new(null, [new("garment-value-invalid", exception.Message, sourceIdentity)]);+ }+ }++ private static GarmentParseResult ParseCore(string original, string identity)+ {+ var selection = FirmamentFrontendSchemas.Select(original);+ if (!selection.IsSuccess)+ {+ return new(null, selection.Diagnostics.Select(message => new GarmentDiagnostic(+ message.Split(':')[0], message, identity)).ToArray());+ }+ if (selection.Schema != FirmamentFrontendSchema.Garment)+ {+ Fail("garment-schema-required", "Begin this document with schema Garment.");+ }+ string source = FirmamentSourceSpelling.Normalize(selection.Source);+ var characters = source.ToCharArray();+ foreach (var token in FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape == "comment"))+ {+ Array.Fill(characters, ' ', token.Start, token.Length);+ }+ source = new string(characters);+ var expansionDiagnostics = new List<string>();+ var features = FirmamentV2FeatureExpansion.Expand(source, expansionDiagnostics);+ if (features is null || expansionDiagnostics.Count > 0)+ {+ return ExpansionFailure(expansionDiagnostics, identity);+ }+ var patterns = CanonicalStaticAuthoring.Expand(features.Source, expansionDiagnostics);+ if (patterns is null || expansionDiagnostics.Count > 0)+ {+ return ExpansionFailure(expansionDiagnostics, identity);+ }+ source = patterns.Source;+ var reader = new Reader(source);+ while (!reader.End && reader.Peek != "Garment")+ {+ if (reader.Optional(";"))+ {+ continue;+ }+ if (reader.Peek is not ("Point2" or "Line2" or "CubicBezier2" or "Circle2" or "Rect2"+ or "RoundedRect2" or "Polygon2" or "Profile" or "Curve2" or "Ellipse2Guide"))+ {+ Fail("garment-declaration-unsupported", "Unsupported garment module declaration: " + reader.Peek);+ }+ reader.SkipDeclaration();+ }+ reader.Expect("Garment");+ string name = reader.Identifier();+ string bodyText = reader.Block();+ reader.Optional(";");+ if (!reader.End)+ {+ Fail("garment-multiple-roots", "One Garment root is required, with geometry recipes before it.");+ }+ var body = new Reader(bodyText);+ var panels = ImmutableArray.CreateBuilder<GarmentPanel>();+ var stitches = ImmutableArray.CreateBuilder<GarmentStitch>();+ var names = new HashSet<string>(StringComparer.Ordinal);+ ClothMaterial3D? fabric = null;+ float meshSize = .06f;+ bool hasMeshSize = false;+ string? figure = null;+ string? pose = null;+ float bodyClearance = .004f;+ while (!body.End)+ {+ if (body.Optional(";"))+ {+ continue;+ }+ string kind = body.Take();+ if (kind == "MeshSize")+ {+ if (hasMeshSize)+ {+ Fail("garment-duplicate-field", "meshSize is repeated.");+ }+ hasMeshSize = true;+ body.Expect(":");+ meshSize = Length(body.Value());+ if (meshSize is < .015f or > .15f)+ {+ Fail("garment-mesh-budget", "meshSize must be between 15mm and 150mm.");+ }+ continue;+ }+ if (kind == "Drape")+ {+ if (figure is not null)+ {+ Fail("garment-duplicate-drape", "Declare only one Drape binding.");+ }+ var fields = Fields(body.Block(), ["Figure", "Pose", "Clearance"]);+ figure = Required(fields, "Figure");+ pose = fields.GetValueOrDefault("Pose", "Rest");+ bodyClearance = Length(fields.GetValueOrDefault("Clearance", "4mm"));+ if (bodyClearance is < 0 or > .03f)+ {+ Fail("garment-body-clearance", "clearance must be between 0mm and 30mm.");+ }+ if (pose != "Rest")+ {+ Fail("garment-pose-unsupported", "This drape milestone admits the loaded figure's Rest pose only.");+ }+ continue;+ }+ if (kind == "Interface")+ {+ body.Expect("<");+ body.Expect("Stitch");+ body.Expect(">");+ }+ string declarationName = body.Identifier();+ if (!names.Add(declarationName))+ {+ Fail("garment-duplicate-name", "Repeated garment declaration: " + declarationName);+ }+ string declarationBody = body.Block();+ switch (kind)+ {+ case "Fabric":+ {+ if (fabric is not null)+ {+ Fail("garment-fabric-unsupported", "This milestone admits one shared fabric per garment.");+ }+ var fields = Fields(declarationBody, ["ArealDensity", "Thickness", "WarpCompliance", "WeftCompliance", "DiagonalCompliance", "BendCompliance"]);+ fabric = new()+ {+ ArealDensity = Scalar(fields.GetValueOrDefault("ArealDensity", "0.2")),+ Thickness = Length(fields.GetValueOrDefault("Thickness", "2mm")),+ WarpCompliance = Scalar(fields.GetValueOrDefault("WarpCompliance", "0.000001")),+ WeftCompliance = Scalar(fields.GetValueOrDefault("WeftCompliance", "0.000001")),+ DiagonalCompliance = Scalar(fields.GetValueOrDefault("DiagonalCompliance", "0.000004")),+ BendCompliance = Scalar(fields.GetValueOrDefault("BendCompliance", "1000")),+ };+ break;+ }+ case "Panel":+ {+ var fields = Fields(declarationBody, ["Profile", "Origin", "U", "V", "Grain", "Pin", "PatternIdentity", "WrapRadius",+ "WrapAngle", "WrapTopRadius", "WrapTopOrigin", "WrapTopAngle"]);+ string profileName = Required(fields, "Profile");+ var profile = ProfileAuthoringParser.ResolveNamedProfile(source, profileName, out var diagnostics);+ if (profile is null || diagnostics.Count > 0)+ {+ Fail("garment-profile-invalid", profileName + ": " + string.Join("; ", diagnostics));+ }+ var validation = ResolvedProfile2DValidator.Validate(profile!);+ if (!validation.IsValid)+ {+ Fail("garment-profile-invalid", string.Join("; ", validation.Diagnostics));+ }+ Vector3 u = Vector(fields.GetValueOrDefault("U", "[1, 0, 0]"), false);+ Vector3 v = Vector(fields.GetValueOrDefault("V", "[0, 0, 1]"), false);+ if (MathF.Abs(u.LengthSquared() - 1) > 1e-5f || MathF.Abs(v.LengthSquared() - 1) > 1e-5f+ || MathF.Abs(Vector3.Dot(u, v)) > 1e-5f)+ {+ Fail("garment-panel-frame-invalid", "Panel u and v must be orthonormal; placement cannot scale the rest pattern.");+ }+ float[] grainValues = List(fields.GetValueOrDefault("Grain", "[0, 1]")).Select(Scalar).ToArray();+ if (grainValues.Length != 2)+ {+ Fail("garment-grain-invalid", "grain requires a unit material-space Vector2.");+ }+ Vector2 grain = new(grainValues[0], grainValues[1]);+ if (MathF.Abs(grain.LengthSquared() - 1) > 1e-5f)+ {+ Fail("garment-grain-invalid", "grain must be unit length.");+ }+ float? wrapRadius = fields.TryGetValue("WrapRadius", out string? radius) ? Length(radius) : null;+ if (wrapRadius is <= 0)+ {+ Fail("garment-wrap-invalid", "wrapRadius must be positive.");+ }+ float wrapAngle = Angle(fields.GetValueOrDefault("WrapAngle", "0deg"));+ float? topRadius = fields.TryGetValue("WrapTopRadius", out string? top) ? Length(top) : null;+ Vector3? topOrigin = fields.TryGetValue("WrapTopOrigin", out string? topPosition) ? Vector(topPosition, true) : null;+ float topAngle = Angle(fields.GetValueOrDefault("WrapTopAngle", fields.GetValueOrDefault("WrapAngle", "0deg")));+ if (topRadius is <= 0 || (wrapRadius is null && (topRadius is not null || topOrigin is not null)))+ Fail("garment-wrap-invalid", "Lofted wrap placement requires a positive base wrapRadius.");+ panels.Add(new(declarationName, fields.GetValueOrDefault("PatternIdentity", declarationName), profile!,+ Vector(Required(fields, "Origin"), true), u, v, grain,+ fields.TryGetValue("Pin", out string? pin) ? List(pin).ToImmutableArray() : [], wrapRadius,+ wrapAngle, topRadius, topOrigin, topAngle));+ break;+ }+ case "Interface":+ {+ var fields = Fields(declarationBody, ["A", "B", "Orientation", "Ease", "Compliance"]);+ string orientation = fields.GetValueOrDefault("Orientation", "Reversed");+ if (orientation is not ("Same" or "Reversed"))+ {+ Fail("garment-stitch-orientation", "orientation is Same or Reversed.");+ }+ float ease = Scalar(fields.GetValueOrDefault("Ease", "0"));+ float compliance = Scalar(fields.GetValueOrDefault("Compliance", "0.00000001"));+ if (ease is < 0 or > .25f || compliance < 0)+ {+ Fail("garment-stitch-properties", "ease is a 0..0.25 length mismatch allowance; compliance is nonnegative.");+ }+ stitches.Add(new(declarationName, Required(fields, "A"), Required(fields, "B"), orientation == "Reversed", ease, compliance));+ break;+ }+ default:+ Fail("garment-construct-unsupported", "Unsupported garment construct: " + kind);+ break;+ }+ }+ if (panels.Count == 0)+ {+ Fail("garment-panel-missing", "A garment needs at least one Panel.");+ }+ if (fabric is null)+ {+ Fail("garment-fabric-missing", "Declare one Fabric with explicit authoring properties.");+ }+ string hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(original)));+ return new(new(name, identity, hash, fabric!, meshSize, panels.ToImmutable(), stitches.ToImmutable(),+ figure, pose, features.Invocations, patterns.Document?.Patterns ?? [], bodyClearance), []);+ }++ private static GarmentParseResult ExpansionFailure(IEnumerable<string> diagnostics, string identity)+ {+ return new(null, diagnostics.Select(message => new GarmentDiagnostic(message.Split(':')[0], message, identity)).ToArray());+ }++ private static Dictionary<string, string> Fields(string text, string[] admitted)+ {+ var result = new Dictionary<string, string>(StringComparer.Ordinal);+ var reader = new Reader(text);+ while (!reader.End)+ {+ if (reader.Optional(";"))+ {+ continue;+ }+ string name = reader.Identifier();+ if (!admitted.Contains(name))+ {+ Fail("garment-field-unknown", "Unknown field: " + name);+ }+ reader.Expect(":");+ if (!result.TryAdd(name, reader.Value()))+ {+ Fail("garment-duplicate-field", "Repeated field: " + name);+ }+ }+ return result;+ }++ private static string Required(Dictionary<string, string> fields, string key)+ {+ if (!fields.TryGetValue(key, out string? value))+ {+ Fail("garment-field-required", "Missing field: " + key);+ }+ return value!;+ }++ private static float Scalar(string value)+ {+ float result = float.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture);+ if (!float.IsFinite(result))+ {+ Fail("garment-nonfinite", "All garment values must be finite.");+ }+ return result;+ }++ private static float Length(string value)+ {+ var match = Regex.Match(value, @"^\s*(?<number>[-+\d.eE]+)\s*(?<unit>mm|m)\s*$", RegexOptions.CultureInvariant);+ if (!match.Success)+ {+ Fail("garment-length-unit", "Length requires an explicit mm or m suffix: " + value);+ }+ return Scalar(match.Groups["number"].Value) * (match.Groups["unit"].Value == "mm" ? .001f : 1);+ }++ private static float Angle(string value)+ {+ if (!value.EndsWith("deg", StringComparison.Ordinal))+ {+ Fail("garment-angle-unit", "Wrap angles require a deg suffix.");+ }+ return Scalar(value[..^3]) * MathF.PI / 180;+ }++ private static Vector3 Vector(string value, bool length)+ {+ if (value.StartsWith("Point3(", StringComparison.Ordinal) && value.EndsWith(')'))+ {+ value = "[" + value[7..^1] + "]";+ }+ float[] coordinates = List(value).Select(item => length ? Length(item) : Scalar(item)).ToArray();+ if (coordinates.Length != 3)+ {+ Fail("garment-vector-invalid", "Expected three vector coordinates.");+ }+ return new(coordinates[0], coordinates[1], coordinates[2]);+ }++ private static string[] List(string value)+ {+ if (!value.StartsWith('[') || !value.EndsWith(']'))+ {+ Fail("garment-list-invalid", "Expected a bracketed list.");+ }+ return value[1..^1].Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);+ }++ internal static void Fail(string code, string message) => throw new GarmentAuthoringException(code, message);++ private sealed class Reader+ {+ private readonly string source;+ private readonly (string Text, string Shape, int Start, int Length)[] tokens;+ private int position;++ public Reader(string source)+ {+ this.source = source;+ tokens = FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape != "comment")+ .Select(token => (token.Text, token.Shape, token.Start, token.Length)).ToArray();+ }++ public bool End => position >= tokens.Length;+ public string Peek => End ? "<end>" : tokens[position].Text;+ public string Take()+ {+ if (End)+ {+ Fail("garment-syntax", "Unexpected end of garment document.");+ }+ return tokens[position++].Text;+ }+ public bool Optional(string text)+ {+ if (Peek != text)+ {+ return false;+ }+ position++;+ return true;+ }+ public void Expect(string text)+ {+ if (!Optional(text))+ {+ Fail("garment-syntax", "Expected '" + text + "', found '" + Peek + "'.");+ }+ }+ public string Identifier()+ {+ if (End || tokens[position].Shape != "identifier")+ {+ Fail("garment-syntax", "Expected an identifier, found " + Peek);+ }+ return Take();+ }+ public string Block()+ {+ Expect("{");+ int start = tokens[position - 1].Start + 1;+ int depth = 1;+ while (!End)+ {+ var token = tokens[position++];+ if (token.Text == "{")+ {+ depth++;+ }+ if (token.Text == "}")+ {+ depth--;+ }+ if (depth == 0)+ {+ return source[start..token.Start];+ }+ }+ Fail("garment-syntax", "Unclosed garment block.");+ return "";+ }+ public void SkipDeclaration()+ {+ while (!End && Peek != "{")+ {+ Take();+ }+ Block();+ Optional(";");+ }+ public string Value()+ {+ if (End)+ {+ Fail("garment-syntax", "Missing field value.");+ }+ int start = tokens[position].Start;+ int end = start;+ int depth = 0;+ while (!End)+ {+ var token = tokens[position];+ if (depth == 0 && (token.Text == ";" || (position + 1 < tokens.Length && tokens[position + 1].Text == ":")))+ {+ break;+ }+ if (depth == 0 && end > start && token.Text is "Panel" or "Fabric" or "Interface" or "Drape")+ {+ break;+ }+ if (token.Text is "[" or "(")+ {+ depth++;+ }+ if (token.Text is "]" or ")")+ {+ depth--;+ }+ if (depth < 0)+ {+ Fail("garment-syntax", "Unbalanced field value.");+ }+ end = token.Start + token.Length;+ position++;+ }+ if (depth != 0 || end == start)+ {+ Fail("garment-syntax", "Missing or unbalanced field value.");+ }+ Optional(";");+ return source[start..end].Trim();+ }+ }+}++internal sealed class GarmentAuthoringException(string code, string message) : Exception(message)+{+ public string Code { get; } = code;+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentCompiler.cs b/Aetheris.Kernel.Firmament/Garment/GarmentCompiler.csnew file mode 100644index 00000000..74921908--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentCompiler.cs@@ -0,0 +1,199 @@+using System.Collections.Immutable;+using System.Numerics;+using Aetheris.Cloth3D;++namespace Aetheris.Kernel.Firmament.Garment;++public sealed record CompiledGarment(GarmentSource Source, CompiledCloth3D Cloth, ImmutableArray<GarmentMeshPanel> Panels)+{+ public float MaximumSeamGap(ClothSnapshot3D snapshot)+ {+ ClothState3D.ValidateSnapshot(Cloth, snapshot);+ float maximum = 0;+ foreach (var stitch in Cloth.Definition.Stitches)+ {+ Vector3 gap = Vector3.Zero;+ for (int i = 0; i < stitch.Vertices.Length; i++)+ {+ gap += snapshot.Positions[stitch.Vertices[i]] * stitch.Weights[i];+ }+ maximum = MathF.Max(maximum, gap.Length());+ }+ return maximum;+ }+}++public sealed record GarmentCompilationResult(CompiledGarment? Garment, IReadOnlyList<GarmentDiagnostic> Diagnostics)+{+ public bool IsSuccess => Garment is not null && Diagnostics.Count == 0;+}++public static class GarmentCompiler+{+ public static GarmentCompilationResult Compile(string source, string sourceIdentity = "<memory>")+ {+ var parsed = GarmentAuthoring.Parse(source, sourceIdentity);+ if (!parsed.IsSuccess)+ {+ return new(null, parsed.Diagnostics);+ }+ try+ {+ return new(Compile(parsed.Source!), []);+ }+ catch (GarmentAuthoringException exception)+ {+ return new(null, [new(exception.Code, exception.Message, sourceIdentity)]);+ }+ catch (Exception exception) when (exception is ArgumentException or NotSupportedException)+ {+ return new(null, [new("garment-cloth-invalid", exception.Message, sourceIdentity)]);+ }+ }++ private static CompiledGarment Compile(GarmentSource source)+ {+ var rest = new List<Vector3>();+ var initial = new List<Vector3>();+ var coordinates = new List<Vector2>();+ var indices = new List<int>();+ var pins = new HashSet<int>();+ var panels = ImmutableArray.CreateBuilder<GarmentMeshPanel>();+ foreach (var panel in source.Panels)+ {+ var mesh = GarmentPanelMesher.Mesh(panel, source.MeshSize);+ int offset = rest.Count;+ float minimumY = mesh.Points.Min(point => point.Y);+ float maximumY = mesh.Points.Max(point => point.Y);+ var edges = mesh.Edges.ToDictionary(entry => entry.Key,+ entry => entry.Value.Select(vertex => vertex + offset).ToImmutableArray(), StringComparer.Ordinal);+ panels.Add(new(panel.Name, panel.Identity, offset, mesh.Points.Count, indices.Count, mesh.Indices.Count, edges));+ foreach (Vector2 point in mesh.Points)+ {+ rest.Add(new(point.X, point.Y, 0));+ Vector3 placed = panel.Origin + panel.U * point.X + panel.V * point.Y;+ if (panel.WrapRadius is { } radius)+ {+ float fraction = (point.Y - minimumY) / (maximumY - minimumY);+ float arrangedRadius = radius + ((panel.WrapTopRadius ?? radius) - radius) * fraction;+ float offsetAngle = panel.WrapAngle + (panel.WrapTopAngle - panel.WrapAngle) * fraction;+ float angle = point.X / arrangedRadius + offsetAngle;+ Vector3 topOrigin = panel.WrapTopOrigin ?? (panel.Origin + panel.V * (maximumY - minimumY));+ Vector3 center = Vector3.Lerp(panel.Origin, topOrigin, fraction);+ Vector3 outward = -Vector3.Cross(panel.U, panel.V);+ placed = center + panel.U * (arrangedRadius * MathF.Sin(angle))+ + outward * (arrangedRadius * MathF.Cos(angle)) + panel.V * minimumY;+ }+ initial.Add(placed);+ Vector2 across = new(panel.Grain.Y, -panel.Grain.X);+ coordinates.Add(new(Vector2.Dot(point, panel.Grain), Vector2.Dot(point, across)));+ }+ indices.AddRange(mesh.Indices.Select(index => index + offset));+ foreach (string edge in panel.Pins)+ {+ if (!edges.TryGetValue(edge, out var boundary))+ {+ GarmentAuthoring.Fail("garment-pin-edge-unknown", panel.Name + ".edges." + edge);+ }+ pins.UnionWith(boundary);+ }+ }+ var compiledPanels = panels.ToImmutable();+ var stitches = ImmutableArray.CreateBuilder<ClothStitch3D>();+ var usedEdges = new HashSet<string>(StringComparer.Ordinal);+ foreach (var seam in source.Stitches)+ {+ var a = Boundary(seam.A);+ var b = Boundary(seam.B);+ if (a.SequenceEqual(b))+ {+ GarmentAuthoring.Fail("garment-stitch-self", seam.Name + " cannot stitch an edge to itself.");+ }+ float[] distancesA = Distances(a);+ float[] distancesB = Distances(b);+ float lengthA = distancesA[^1];+ float lengthB = distancesB[^1];+ float mismatch = MathF.Abs(lengthA - lengthB) / MathF.Max(lengthA, lengthB);+ if (mismatch > seam.Ease + .001f)+ {+ GarmentAuthoring.Fail("garment-stitch-length-mismatch", seam.Name + $": edge lengths {lengthA:R}m and {lengthB:R}m require explicit ease >= {mismatch:R}.");+ }+ var samples = distancesA.Select(distance => distance / lengthA)+ .Concat(distancesB.Select(distance => seam.Reversed ? 1 - distance / lengthB : distance / lengthB))+ .Order().Aggregate(new List<float>(), (list, value) =>+ {+ if (list.Count == 0 || value - list[^1] > 1e-5f)+ {+ list.Add(value);+ }+ return list;+ });+ for (int sample = 0; sample < samples.Count; sample++)+ {+ var weights = new SortedDictionary<int, float>();+ Bind(a, distancesA, samples[sample], 1, weights);+ Bind(b, distancesB, seam.Reversed ? 1 - samples[sample] : samples[sample], -1, weights);+ var nonzero = weights.Where(entry => MathF.Abs(entry.Value) > 1e-7f).ToArray();+ stitches.Add(new(seam.Name + "/" + sample, nonzero.Select(entry => entry.Key).ToImmutableArray(),+ nonzero.Select(entry => entry.Value).ToImmutableArray(), seam.Compliance));+ }+ }+ var definition = new ClothDefinition3D(source.Name, rest.ToImmutableArray(), coordinates.ToImmutableArray(), indices.ToImmutableArray())+ {+ InitialPositions = initial.ToImmutableArray(),+ Stitches = stitches.ToImmutable(),+ Pins = pins.Order().ToImmutableArray(),+ Material = source.Fabric,+ };+ return new(source, definition.Compile(), compiledPanels);++ ImmutableArray<int> Boundary(string reference)+ {+ int separator = reference.IndexOf(".edges.", StringComparison.Ordinal);+ if (separator < 1)+ {+ GarmentAuthoring.Fail("garment-stitch-reference", "Use panel.edges.namedSpan: " + reference);+ }+ string panelName = reference[..separator];+ string edgeName = reference[(separator + 7)..];+ var panel = compiledPanels.SingleOrDefault(panel => panel.Name == panelName || panel.Identity == panelName);+ if (panel is null || !panel.Edges.ContainsKey(edgeName))+ {+ GarmentAuthoring.Fail("garment-stitch-edge-unknown", reference);+ }+ string canonical = panel!.Identity + ".edges." + edgeName;+ if (!usedEdges.Add(canonical))+ {+ GarmentAuthoring.Fail("garment-stitch-edge-reused", canonical + " already has a seam.");+ }+ return panel.Edges[edgeName];+ }+ float[] Distances(ImmutableArray<int> boundary)+ {+ float[] distances = new float[boundary.Length];+ for (int i = 1; i < boundary.Length; i++)+ {+ distances[i] = distances[i - 1] + Vector3.Distance(rest[boundary[i - 1]], rest[boundary[i]]);+ }+ return distances;+ }+ }++ private static void Bind(ImmutableArray<int> boundary, float[] distances, float fraction, float sign, SortedDictionary<int, float> weights)+ {+ float target = Math.Clamp(fraction, 0, 1) * distances[^1];+ int segment = 0;+ while (segment + 2 < distances.Length && distances[segment + 1] < target)+ {+ segment++;+ }+ float t = Math.Clamp((target - distances[segment]) / (distances[segment + 1] - distances[segment]), 0, 1);+ Add(boundary[segment], sign * (1 - t));+ Add(boundary[segment + 1], sign * t);+ void Add(int vertex, float weight)+ {+ weights.TryGetValue(vertex, out float existing);+ weights[vertex] = existing + weight;+ }+ }+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentDraping.cs b/Aetheris.Kernel.Firmament/Garment/GarmentDraping.csnew file mode 100644index 00000000..0d5f5a9a--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentDraping.cs@@ -0,0 +1,93 @@+using System.Collections.Immutable;+using System.Numerics;+using Aetheris.Cloth3D;+using Aetheris.Humanoid;++namespace Aetheris.Kernel.Firmament.Garment;++public sealed record GarmentDrapeResult(ClothSnapshot3D Snapshot, ClothMetrics3D Metrics,+ float MaximumSeamGap, float InitialSeamGap, bool ReplayExact, string BodyId, string BodyTopology,+ IReadOnlyList<GarmentContactOutlier> ContactOutliers, IReadOnlyList<GarmentStretchOutlier> StretchOutliers);++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);++public static class GarmentDraping+{+ public static ClothTriangleBody3D BodySurface(HumanoidGameplayBody body)+ {+ ArgumentNullException.ThrowIfNull(body);+ var positions = body.Surface.Vertices.Select(vertex => new Vector3(+ (float)vertex.Position.X, (float)vertex.Position.Y, (float)vertex.Position.Z) * .001f).ToImmutableArray();+ var outer = body.Surface.Components.Where(component => component.Kind == HumanoidComponentKind.OuterSkin)+ .SelectMany(component => component.FaceIndices).Distinct().Order().ToArray();+ if (outer.Length == 0)+ {+ throw new InvalidDataException("garment-body-skin-missing: Body needs its declared OuterSkin component.");+ }+ var indices = outer.SelectMany(index =>+ {+ var face = body.Surface.Faces[index];+ return new[] { face.A, face.B, face.C };+ }).ToImmutableArray();+ return new(positions, indices);+ }++ /// <summary>Static Rest-pose authoring qualification on the shared CPU solver.+ /// Explicit pins are retained garment supports. No animation, friction, CCD or self-contact claim.</summary>+ public static GarmentDrapeResult Settle(CompiledGarment garment, HumanoidGameplayBody body, int ticks = 60)+ {+ if (ticks is < 1 or > 600)+ {+ throw new ArgumentOutOfRangeException(nameof(ticks));+ }+ if (garment.Source.Figure is null || garment.Source.Pose != "Rest")+ {+ throw new InvalidOperationException("garment-drape-binding-required: Declare Drape { figure: Anatolia; pose: Rest; } and supply its body artifact.");+ }+ var contacts = new ClothContacts3D { BodySurface = BodySurface(body), BodyClearance = garment.Source.BodyClearance };+ var options = new ClothStepOptions3D+ {+ Gravity = new(0, 0, -9.81f),+ Substeps = 8,+ Iterations = 24,+ ContactIterations = 1,+ VelocityDamping = 8,+ };+ using var solver = new ClothSolver3D(garment.Cloth);+ var initial = solver.Capture();+ float initialGap = garment.MaximumSeamGap(initial);+ // Sew with gravity disabled and a decreasing compliance, then settle.+ // This keeps the initial closing impulse from dominating garment motion.+ for (int stage = 0; stage < 30; stage++)+ {+ float scale = MathF.Pow(10, 6 * (1 - stage / 29f));+ solver.Step(options with { Gravity = Vector3.Zero, StitchComplianceScale = scale }, contacts);+ }+ for (int tick = 0; tick < ticks; tick++)+ {+ solver.Step(options, contacts);+ }+ var final = solver.Capture();+ var beforeReplay = final;+ solver.Step(options, contacts);+ var expected = solver.Capture();+ solver.Restore(beforeReplay);+ solver.Step(options, contacts);+ var replayed = solver.Capture();+ bool replay = expected.Positions.SequenceEqual(replayed.Positions)+ && expected.Velocities.SequenceEqual(replayed.Velocities) && expected.Tick == replayed.Tick;+ var pins = garment.Cloth.Definition.Pins.ToHashSet();+ var contactOutliers = final.Positions.Select((position, index) => new GarmentContactOutlier(index,+ garment.Panels.Single(panel => index >= panel.VertexStart && index < panel.VertexStart + panel.VertexCount).Identity,+ pins.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)).OrderByDescending(item => item.Stretch).Take(8).ToArray();+ return new(final, ClothState3D.Measure(garment.Cloth, final, contacts), garment.MaximumSeamGap(final),+ initialGap, replay, body.Id, body.Surface.ConnectivityHash, contactOutliers, stretchOutliers);+ }+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentExport.cs b/Aetheris.Kernel.Firmament/Garment/GarmentExport.csnew file mode 100644index 00000000..3eafc4ae--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentExport.cs@@ -0,0 +1,147 @@+using System.Globalization;+using System.Numerics;+using System.Security;+using System.Text;+using System.Text.Json;+using Aetheris.Cloth3D;+using Aetheris.Humanoid;++namespace Aetheris.Kernel.Firmament.Garment;++public static class GarmentExport+{+ private static readonly JsonSerializerOptions JsonOptions = new()+ {+ WriteIndented = true,+ IncludeFields = true,+ };++ public static string Artifact(CompiledGarment garment, ClothSnapshot3D? settled = null)+ {+ if (settled is not null)+ {+ ClothState3D.ValidateSnapshot(garment.Cloth, settled);+ }+ return JsonSerializer.Serialize(new+ {+ schema = "aetheris.garment.v1",+ units = "m",+ upAxis = "Z",+ sourceHash = garment.Source.SourceHash,+ sourceIdentity = garment.Source.SourceIdentity,+ contentKey = garment.Cloth.ContentKey,+ definition = garment.Cloth.Definition,+ panels = garment.Panels,+ seams = garment.Source.Stitches,+ settled,+ }, JsonOptions);+ }++ public static string Obj(CompiledGarment garment, ClothSnapshot3D? settled = null)+ {+ if (settled is not null)+ {+ ClothState3D.ValidateSnapshot(garment.Cloth, settled);+ }+ var positions = settled?.Positions ?? garment.Cloth.Definition.InitialPositions;+ var result = new StringBuilder("# Aetheris garment; metres; Z up; source=" + garment.Source.SourceHash + "\n");+ foreach (var point in positions)+ {+ result.AppendLine(FormattableString.Invariant($"v {point.X:R} {point.Y:R} {point.Z:R}"));+ }+ foreach (var point in garment.Cloth.Definition.Coordinates)+ {+ result.AppendLine(FormattableString.Invariant($"vt {point.X:R} {point.Y:R}"));+ }+ foreach (var panel in garment.Panels)+ {+ result.AppendLine("g " + panel.Identity.Replace('.', '_'));+ for (int face = panel.IndexStart; face < panel.IndexStart + panel.IndexCount; face += 3)+ {+ int a = garment.Cloth.Definition.Indices[face] + 1;+ int b = garment.Cloth.Definition.Indices[face + 1] + 1;+ int c = garment.Cloth.Definition.Indices[face + 2] + 1;+ result.AppendLine($"f {a}/{a} {b}/{b} {c}/{c}");+ }+ }+ return result.ToString();+ }++ public static string BodyObj(HumanoidGameplayBody body)+ {+ var result = new StringBuilder("# Antonia gameplay body; metres; Z up. Preserve its source attribution.\n");+ foreach (var vertex in body.Surface.Vertices)+ {+ var point = vertex.Position;+ result.AppendLine(FormattableString.Invariant($"v {point.X / 1000:R} {point.Y / 1000:R} {point.Z / 1000:R}"));+ }+ foreach (var face in body.Surface.Faces)+ {+ result.AppendLine($"f {face.A + 1} {face.B + 1} {face.C + 1}");+ }+ return result.ToString();+ }++ public static string PatternsSvg(CompiledGarment garment)+ {+ var result = new StringBuilder("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1200\" height=\"900\" viewBox=\"0 0 1200 900\">\n");+ result.AppendLine("<rect width=\"1200\" height=\"900\" fill=\"#f5f3ee\"/><g font-family=\"sans-serif\" fill=\"#24344c\">");+ result.AppendLine("<text x=\"24\" y=\"36\" font-size=\"24\">" + Escape(garment.Source.Name) + " — material patterns (mm)</text>");+ result.AppendLine("<text x=\"24\" y=\"64\" font-size=\"14\">Blue: open edge · orange: stitch · green: explicit support. Cut boundary; no seam allowance added.</text>");+ int panelNumber = 0;+ foreach (var panel in garment.Panels)+ {+ var points = garment.Cloth.Definition.Positions.Skip(panel.VertexStart).Take(panel.VertexCount).ToArray();+ float minX = points.Min(point => point.X);+ float minY = points.Min(point => point.Y);+ float width = points.Max(point => point.X) - minX;+ float height = points.Max(point => point.Y) - minY;+ float scale = MathF.Min(490 / width, 300 / height);+ float originX = 40 + panelNumber % 2 * 590;+ float originY = 140 + panelNumber / 2 * 370;+ panelNumber++;+ result.AppendLine(FormattableString.Invariant($"<text x=\"{originX}\" y=\"{originY - 30}\" font-size=\"18\">{Escape(panel.Identity)}</text>"));+ foreach (var edge in panel.Edges)+ {+ string reference = panel.Identity + ".edges." + edge.Key;+ var seam = garment.Source.Stitches.FirstOrDefault(stitch => stitch.A == reference || stitch.B == reference+ || stitch.A == panel.Name + ".edges." + edge.Key || stitch.B == panel.Name + ".edges." + edge.Key);+ bool pinned = garment.Source.Panels.Single(source => source.Name == panel.Name).Pins.Contains(edge.Key);+ string color = pinned ? "#16835b" : seam is null ? "#3274a0" : "#c76925";+ var line = edge.Value.Select(index => garment.Cloth.Definition.Positions[index]).ToArray();+ string coordinates = string.Join(" ", line.Select(point => FormattableString.Invariant($"{originX + (point.X - minX) * scale},{originY + (height - point.Y + minY) * scale}")));+ result.AppendLine($"<polyline points=\"{coordinates}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"2\"/>");+ var middle = line[line.Length / 2];+ string label = edge.Key + (seam is null ? "" : " / " + seam.Name);+ result.AppendLine(FormattableString.Invariant($"<text x=\"{originX + (middle.X - minX) * scale + 3}\" y=\"{originY + (height - middle.Y + minY) * scale - 4}\" font-size=\"10\">{Escape(label)}</text>"));+ }+ }+ result.AppendLine("</g></svg>");+ return result.ToString();+ }++ public static string Usd(CompiledGarment garment, ClothSnapshot3D? settled = null)+ {+ if (settled is not null)+ {+ ClothState3D.ValidateSnapshot(garment.Cloth, settled);+ }+ var positions = settled?.Positions ?? garment.Cloth.Definition.InitialPositions;+ var result = new StringBuilder("#usda 1.0\n(\n upAxis = \"Z\"\n metersPerUnit = 1\n)\n");+ result.AppendLine("def Xform \"Garment\" {\n custom string sourceHash = \"" + garment.Source.SourceHash + "\"");+ foreach (var panel in garment.Panels)+ {+ result.AppendLine(" def Mesh \"" + panel.Identity.Replace('.', '_') + "\" {");+ result.AppendLine(" uniform token subdivisionScheme = \"none\"\n uniform bool doubleSided = true");+ result.AppendLine(" point3f[] points = [" + string.Join(", ", positions.Skip(panel.VertexStart).Take(panel.VertexCount).Select(Point)) + "]");+ result.AppendLine(" int[] faceVertexCounts = [" + string.Join(", ", Enumerable.Repeat(3, panel.IndexCount / 3)) + "]");+ result.AppendLine(" int[] faceVertexIndices = [" + string.Join(", ", garment.Cloth.Definition.Indices.Skip(panel.IndexStart).Take(panel.IndexCount).Select(index => index - panel.VertexStart)) + "]");+ result.AppendLine(" color3f[] primvars:displayColor = [(0.1, 0.22, 0.38)]\n }");+ }+ result.AppendLine("}");+ return result.ToString();+ }++ private static string Point(Vector3 point) => FormattableString.Invariant($"({point.X:R}, {point.Y:R}, {point.Z:R})");+ private static string Escape(string value) => SecurityElement.Escape(value) ?? "";+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentPanelMesher.cs b/Aetheris.Kernel.Firmament/Garment/GarmentPanelMesher.csnew file mode 100644index 00000000..8da03a8b--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentPanelMesher.cs@@ -0,0 +1,225 @@+using System.Collections.Immutable;+using System.Numerics;+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Garment;++public sealed record GarmentMeshPanel(string Name, string Identity, int VertexStart, int VertexCount,+ int IndexStart, int IndexCount, IReadOnlyDictionary<string, ImmutableArray<int>> Edges);++internal sealed record PanelMesh(List<Vector2> Points, List<int> Indices, Dictionary<string, List<int>> Edges);++/// <summary>Projection of resolved Profile boundaries through the kernel's polygon triangulator.+/// Conforming edge refinement preserves directed source spans; no garment-specific sketch kernel.</summary>+internal static class GarmentPanelMesher+{+ public static PanelMesh Mesh(GarmentPanel panel, float meshSize)+ {+ if (panel.Profile.Loops.Count != 1)+ {+ GarmentAuthoring.Fail("garment-profile-holes-unsupported", "This panel mesher currently requires one outer loop; cutouts must meet the outer boundary.");+ }+ var points = new List<Vector2>();+ var edges = new Dictionary<string, List<int>>(StringComparer.Ordinal);+ foreach (var segment in panel.Profile.Loops[0].Segments)+ {+ var sampled = Sample(segment.Geometry, meshSize);+ var boundary = new List<int>();+ for (int sample = 0; sample < sampled.Count - 1; sample++)+ {+ boundary.Add(points.Count);+ points.Add(sampled[sample]);+ }+ // The endpoint is the next segment's first vertex (wrapped below).+ boundary.Add(points.Count);+ edges.Add(segment.Name, boundary);+ }+ foreach (var boundary in edges.Values)+ {+ if (boundary[^1] == points.Count)+ {+ boundary[^1] = 0;+ }+ }+ var polygon = points.Select(point => new Point3D(point.X * 1000d, point.Y * 1000d, 0)).ToArray();+ if (!PlanarPolygonTriangulator.TryTriangulate(polygon, new Vector3D(0, 0, 1), out var seed, out var failure))+ {+ GarmentAuthoring.Fail("garment-triangulation-failed", panel.Name + ": " + failure);+ }+ var indices = seed.ToList();+ // The kernel may elide collinear boundary samples. Reinsert them into their+ // containing triangle edge before refinement, retaining seam correspondence.+ for (int point = 0; point < points.Count; point++)+ {+ if (!indices.Contains(point))+ {+ InsertBoundaryPoint(point, points, indices);+ }+ }+ for (int pass = 0; pass < 12; pass++)+ {+ indices = PlanarMeshQuality.Improve(points.Select(point =>+ new Point3D(point.X * 1000d, point.Y * 1000d, 0)).ToArray(), indices).ToList();+ var split = new Dictionary<(int, int), int>();+ for (int face = 0; face < indices.Count; face += 3)+ {+ Mark(indices[face], indices[face + 1]);+ Mark(indices[face + 1], indices[face + 2]);+ Mark(indices[face + 2], indices[face]);+ }+ if (split.Count == 0)+ {+ return new(points, indices, edges);+ }+ if (points.Count > 8192)+ {+ GarmentAuthoring.Fail("garment-mesh-budget", panel.Name + " exceeds 8192 vertices; increase meshSize.");+ }+ var refined = new List<int>();+ for (int face = 0; face < indices.Count; face += 3)+ {+ int a = indices[face];+ int b = indices[face + 1];+ int c = indices[face + 2];+ bool ab = split.TryGetValue(Key(a, b), out int x);+ bool bc = split.TryGetValue(Key(b, c), out int y);+ bool ca = split.TryGetValue(Key(c, a), out int z);+ int mask = (ab ? 1 : 0) | (bc ? 2 : 0) | (ca ? 4 : 0);+ switch (mask)+ {+ case 0:+ Triangle(a, b, c);+ break;+ case 1:+ Triangle(a, x, c);+ Triangle(x, b, c);+ break;+ case 2:+ Triangle(b, y, a);+ Triangle(y, c, a);+ break;+ case 4:+ Triangle(c, z, b);+ Triangle(z, a, b);+ break;+ case 3:+ Triangle(b, y, x);+ Triangle(a, x, c);+ Triangle(x, y, c);+ break;+ case 5:+ Triangle(a, x, z);+ Triangle(x, b, c);+ Triangle(x, c, z);+ break;+ case 6:+ Triangle(c, z, y);+ Triangle(b, y, a);+ Triangle(y, z, a);+ break;+ case 7:+ Triangle(a, x, z);+ Triangle(x, b, y);+ Triangle(z, y, c);+ Triangle(x, y, z);+ break;+ }+ }+ foreach (string name in edges.Keys.ToArray())+ {+ var boundary = edges[name];+ var refinedBoundary = new List<int>();+ for (int i = 0; i < boundary.Count - 1; i++)+ {+ refinedBoundary.Add(boundary[i]);+ if (split.TryGetValue(Key(boundary[i], boundary[i + 1]), out int midpoint))+ {+ refinedBoundary.Add(midpoint);+ }+ }+ refinedBoundary.Add(boundary[^1]);+ edges[name] = refinedBoundary;+ }+ indices = refined;++ void Mark(int a, int b)+ {+ var key = Key(a, b);+ if (!split.ContainsKey(key) && Vector2.Distance(points[a], points[b]) > meshSize * 1.001f)+ {+ split.Add(key, points.Count);+ points.Add((points[a] + points[b]) * .5f);+ }+ }+ void Triangle(int a, int b, int c) => refined.AddRange([a, b, c]);+ }+ GarmentAuthoring.Fail("garment-mesh-budget", "Panel refinement did not converge within 12 passes.");+ return null!;+ }++ private static List<Vector2> Sample(LineArcProfileCurve2D curve, float meshSize)+ {+ switch (curve)+ {+ case LineArcLineSegment2D line:+ return [Point(line.Start), Point(line.End)];+ case LineArcCircularArc2D arc:+ {+ int count = Math.Clamp((int)Math.Ceiling(Math.Abs(arc.SweepAngleRadians) * arc.Radius / (meshSize * 1000)), 4, 128);+ return Enumerable.Range(0, count + 1).Select(i =>+ {+ double angle = arc.StartAngleRadians + arc.SweepAngleRadians * i / count;+ return Point((arc.Center.X + arc.Radius * Math.Cos(angle), arc.Center.Y + arc.Radius * Math.Sin(angle)));+ }).ToList();+ }+ case LineArcCubicBezier2D cubic:+ {+ float length = Vector2.Distance(Point(cubic.Start), Point(cubic.Control1))+ + Vector2.Distance(Point(cubic.Control1), Point(cubic.Control2))+ + Vector2.Distance(Point(cubic.Control2), Point(cubic.End));+ int count = Math.Clamp((int)Math.Ceiling(length / meshSize), 8, 128);+ return Enumerable.Range(0, count + 1).Select(i =>+ {+ float t = (float)i / count;+ float u = 1 - t;+ return Point(cubic.Start) * (u * u * u) + Point(cubic.Control1) * (3 * u * u * t)+ + Point(cubic.Control2) * (3 * u * t * t) + Point(cubic.End) * (t * t * t);+ }).ToList();+ }+ default:+ GarmentAuthoring.Fail("garment-curve-unsupported", "Panels currently admit directed lines, circular arcs and cubic Beziers.");+ return null!;+ }+ }++ private static void InsertBoundaryPoint(int vertex, List<Vector2> points, List<int> indices)+ {+ Vector2 point = points[vertex];+ for (int face = 0; face < indices.Count; face += 3)+ {+ for (int edge = 0; edge < 3; edge++)+ {+ int a = indices[face + edge];+ int b = indices[face + (edge + 1) % 3];+ int c = indices[face + (edge + 2) % 3];+ Vector2 direction = points[b] - points[a];+ float t = Vector2.Dot(point - points[a], direction) / direction.LengthSquared();+ if (t <= 0 || t >= 1 || Vector2.DistanceSquared(point, points[a] + direction * t) > 1e-12f)+ {+ continue;+ }+ indices[face] = a;+ indices[face + 1] = vertex;+ indices[face + 2] = c;+ indices.AddRange([vertex, b, c]);+ return;+ }+ }+ GarmentAuthoring.Fail("garment-boundary-lost", "Kernel triangulation did not retain an addressable boundary point.");+ }++ private static Vector2 Point((double X, double Y) value) => new((float)value.X * .001f, (float)value.Y * .001f);+ private static (int, int) Key(int a, int b) => (Math.Min(a, b), Math.Max(a, b));+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentSchema.cs b/Aetheris.Kernel.Firmament/Garment/GarmentSchema.csnew file mode 100644index 00000000..edb29a3c--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentSchema.cs@@ -0,0 +1,44 @@+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Garment;++[FirmamentConstruct("Garment", "Garment", Context = "Document", Entry = "schema Garment\nRect2 cut { center: [0mm, 100mm]; size: [200mm, 200mm] }\nProfile pattern { Loop Outer { cut |> TraceLoop } }\nGarment Outfit {\n meshSize: 60mm;\n Fabric cotton { thickness: 2mm; arealDensity: 0.2; }\n Panel front { profile: pattern; origin: [0mm, 160mm, 1000mm]; }\n}", Description = "An assembly of material-space panels and distributed stitch interfaces, compiled for cloth simulation.")]+[FirmamentField("MeshSize", "MeshSize", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Default = "60mm")]+public static class GarmentDeclaration { }++[FirmamentConstruct("Panel", "Panel", Context = "Garment", Entry = "Panel front { profile: cut; origin: [0mm, 160mm, 1000mm]; u: [1, 0, 0]; v: [0, 0, 1]; }", Description = "Resolved 2D Profile plus a separate initial 3D arrangement. Named profile boundary spans remain addressable as panel.edges.name.")]+[FirmamentField("Profile", "Profile", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("Origin", "Origin", FirmamentSchemaValueKind.Vector, Required = true, Unit = FirmamentUnitKind.Length)]+[FirmamentField("U", "U", FirmamentSchemaValueKind.Vector)]+[FirmamentField("V", "V", FirmamentSchemaValueKind.Vector)]+[FirmamentField("Grain", "Grain", FirmamentSchemaValueKind.Vector)]+[FirmamentField("Pin", "Pin", FirmamentSchemaValueKind.ConstructReference)]+[FirmamentField("WrapRadius", "WrapRadius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length)]+[FirmamentField("WrapAngle", "WrapAngle", FirmamentSchemaValueKind.Angle, Unit = FirmamentUnitKind.Angle)]+[FirmamentField("WrapTopRadius", "WrapTopRadius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length)]+[FirmamentField("WrapTopOrigin", "WrapTopOrigin", FirmamentSchemaValueKind.Vector, Unit = FirmamentUnitKind.Length)]+[FirmamentField("WrapTopAngle", "WrapTopAngle", FirmamentSchemaValueKind.Angle, Unit = FirmamentUnitKind.Angle)]+public static class GarmentPanelDeclaration { }++[FirmamentConstruct("InterfaceStitch", "Interface<Stitch>", Context = "Garment", Entry = "Interface<Stitch> side { a: front.edges.leftSide; b: back.edges.rightSide; orientation: Reversed; }", Description = "Distributed material-boundary correspondence, lowered to weighted cloth constraints rather than rigid frame mates.")]+[FirmamentField("A", "A", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("B", "B", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("Orientation", "Orientation", FirmamentSchemaValueKind.Choice, Choices = ["Same", "Reversed"], Default = "Reversed")]+[FirmamentField("Ease", "Ease", FirmamentSchemaValueKind.Scalar, Default = "0")]+[FirmamentField("Compliance", "Compliance", FirmamentSchemaValueKind.Scalar, Default = "0.00000001")]+public static class GarmentStitchDeclaration { }++[FirmamentConstruct("Fabric", "Fabric", Context = "Garment", Entry = "Fabric cotton { arealDensity: 0.2; thickness: 2mm; }", Description = "One shared fabric per garment. Density is kg/m2; compliance controls are authoring parameters, not calibrated textile moduli.")]+[FirmamentField("ArealDensity", "ArealDensity", FirmamentSchemaValueKind.Scalar)]+[FirmamentField("Thickness", "Thickness", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length)]+[FirmamentField("WarpCompliance", "WarpCompliance", FirmamentSchemaValueKind.Scalar)]+[FirmamentField("WeftCompliance", "WeftCompliance", FirmamentSchemaValueKind.Scalar)]+[FirmamentField("DiagonalCompliance", "DiagonalCompliance", FirmamentSchemaValueKind.Scalar)]+[FirmamentField("BendCompliance", "BendCompliance", FirmamentSchemaValueKind.Scalar)]+public static class GarmentFabricDeclaration { }++[FirmamentConstruct("Drape", "Drape", Context = "Garment", Entry = "Drape { figure: Anatolia; pose: Rest; clearance: 4mm; }", Description = "A named figure binding supplied by the host. The first lane sews and settles on the loaded static Rest-pose body.")]+[FirmamentField("Figure", "Figure", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("Pose", "Pose", FirmamentSchemaValueKind.Choice, Choices = ["Rest"])]+[FirmamentField("Clearance", "Clearance", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length)]+public static class GarmentDrapeDeclaration { }diff --git a/Aetheris.slnx b/Aetheris.slnxindex 96034d1b..47d6ded9 100644--- a/Aetheris.slnx+++ b/Aetheris.slnx@@ -1,4 +1,5 @@<Solution>+ <Project Path="Aetheris.Cloth3D/Aetheris.Cloth3D.csproj" /><Project Path="test-support/Aetheris.StepLegacyCorpus/Aetheris.StepLegacyCorpus.csproj" /><Project Path="Aetheris.Cadmata.Desktop/Aetheris.Cadmata.Desktop.csproj" /><Project Path="Aetheris.Server/Aetheris.Server.csproj" />diff --git a/docs/public/firmament/garments.md b/docs/public/firmament/garments.mdnew file mode 100644index 00000000..ddcedd60--- /dev/null+++ b/docs/public/firmament/garments.md@@ -0,0 +1,178 @@+# Garment authoring foundation++`schema Garment` composes resolved 2D Profiles into material panels, distributed+stitches and an initial arrangement. Firmament owns the pattern and seam truth;+the shared `Aetheris.Cloth3D` runtime owns constraints and simulation. Blender is+an optional viewer of exported meshes, not a second fitting or simulation path.++## Source workflow++Start with the examples in `fixtures/Canonical/Garment`: a two-panel skirt, a+sleeveless tunic, a flared-skirt variation and four-panel shorts. Reuse `Feature (...) -> Profile`, named+Profile boundary spans, `Mirrored Profile` and finite `Pattern ... over Set`+instead of copying per-instance coordinates.++```firmament+schema Garment++Rect2 cut { center: [0mm, 225mm]; size: [612.61057mm, 450mm] }+Profile skirtCut { Loop Outer { cut |> TraceLoop } }++Garment BasicSkirt {+ meshSize: 65mm;+ Fabric cotton { thickness: 2mm; arealDensity: 0.2; }+ Panel front {+ profile: skirtCut;+ origin: [0mm, -35mm, 650mm];+ u: [1, 0, 0]; v: [0, 0, 1];+ wrapRadius: 195mm;+ grain: [0, 1]; pin: [Top];+ }+ Panel back {+ profile: skirtCut;+ origin: [0mm, -35mm, 650mm];+ u: [-1, 0, 0]; v: [0, 0, 1];+ wrapRadius: 195mm;+ grain: [0, 1]; pin: [Top];+ }+ Interface<Stitch> leftSide {+ a: front.edges.Left; b: back.edges.Right; orientation: Reversed;+ }+ Interface<Stitch> rightSide {+ a: front.edges.Right; b: back.edges.Left; orientation: Reversed;+ }+ Drape { figure: Anatolia; pose: Rest; clearance: 4mm; }+}+```++`Panel.profile` resolves through the existing Profile parser and validator.+`u`/`v` are orthonormal initial-placement axes. `grain` is a material-space unit+direction; its perpendicular supplies the second cloth axis. Rest lengths and+mass come from the flat pattern, never from the arranged or settled mesh.++`wrapRadius` provides a cylindrical initial arrangement. Optional+`wrapTopRadius`, `wrapTopOrigin` and `wrapTopAngle` interpolate to another ring+at the panel's top. These are placement controls, not a change to material rest+geometry. `pin` names boundary spans retained as explicit supports, such as a+skirt waistband. The tunic deliberately has no pins and rests on the shoulders.++`Interface<Stitch>` addresses directed spans as `panel.edges.name`, including+stable Pattern identities (`panels.front.edges.Left`). `Same` or `Reversed`+selects correspondence. The compiler merges normalized arc-length samples and+emits weighted constraints; opposing boundaries need not have the same vertex+count. Each edge admits one stitch interface. Length mismatch requires an+explicit fractional `ease` tolerance. This is distributed cloth sewing, not a+rigid Assembly mate. Open boundaries remain open.++## Casing++Use PascalCase for constructs, schema names and enum values; camelCase for+fields, instances and authored edges. Feature names describe reusable recipes+(`TunicPanel`); instances describe occurrences (`tunicCut`, `rightFront`).+Historical PascalCase field aliases remain supported. The source spelling tool+preserves authored Record/Set field names and references exactly. The generated+Rect2 boundary names `Top`, `Left`, `Bottom`, `Right` remain their existing+case-sensitive identities; user-defined spans can use camelCase.++## Real CLI and artifacts++From the repository root, use the repository CLI DLL:++```powershell+dotnet build Aetheris.CLI -c Release -m:1+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll validate fixtures/Canonical/Garment/skirt.firmament --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment build fixtures/Canonical/Garment/skirt.firmament+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment drape fixtures/Canonical/Garment/skirt.firmament --body artifacts/local/humanoid-production/antonia.gameplay-body.json --ticks 30 --json+```++The gameplay body is an existing local humanoid artifact, not checked into these+fixtures. `Anatolia` is the source's figure binding; the loaded artifact retains+its actual Antonia model ID and topology hash. Preserve the humanoid asset's+existing attribution and provenance. No additional model or garment downloads+are required.++Outputs under `artifacts/local/garment/<source-name>`:++- `garment.json`: versioned definition, rest/initial positions, material+ coordinates, pins, stitches, source hash, panel/span identities and optional+ settled snapshot. Runtime load recompiles and checks the retained content key.+- `garment.obj` / `garment.usda`: exact arranged or settled garment mesh in+ metres, Z up. OBJ texture coordinates are material-space metres; texture atlas+ packing and texturing are later work. USD is transport, not solver authority.+- `patterns.svg`: named material boundaries, stitches and supports in mm.+ These are cut boundaries; no seam allowances are silently added.+- `body.obj` on drape: the actual loaded body for inspection.+- `evidence.json`: source/content/body hashes, seam gap, sampled penetration,+ stretch, replay, elapsed time and largest contact/stretch outliers. A failed+ drape retains geometry and returns exit code 2; it does not report success.++The static drape baseline uses 30 sewing ticks with decreasing stitch compliance,+then the requested number of gravity ticks. Default settlement is 60 ticks at the+shared solver's fixed timestep. Qualification requires finite state, exact+capture/restore replay, seam gap <= 10mm, sampled penetration <= 5mm and stretch+<= 15%. These are explicit authoring checks, not textile calibration or a+collision-free certificate. Inspect front, side and back views too:++```powershell+& 'C:\Program Files\Blender Foundation\Blender 5.2\blender.exe' --background --python scripts/render-garment.py -- --bottom skirt+```++## Runtime consumption and ownership++```csharp+using Aetheris.Cloth3D;++var garment = ClothGarmentArtifact3D.Load("garment.json");+using var solver = garment.CreateSolver(); // Restores a settled snapshot when supplied.+var snapshot = solver.Capture();+// Use garment.Cloth.Definition.Indices and snapshot.Positions for presentation.+```++For Aurelian, `ClothAgentDefinition3D.FromGarment(garment)` creates the reusable+scene agent and maps the artifact's Z-up frame into Aurelian's Y-up world. Its+typed state retains the baked snapshot, velocities and support targets. Ordinary+scene placements can then translate or rotate it without redefining rest lengths.++`Aetheris.Cloth3D` contains the existing Aurelian cloth foundation, extracted+rather than duplicated. The Aurelian project forwards a dependency to it;+Aurelian retains the Vulkan backend and agent/presentation integration.+Firmament and the humanoid authoring pipeline have no dependency on Aurelian.+Shared nearest-triangle geometry lives in Aetheris.Kernel.Core.++The native Vulkan regression proof covers existing cloth behavior and new+weighted stitches. Static humanoid body contact currently uses the CPU BVH+backend. The Vulkan backend explicitly rejects that unsupported contact input,+rather than silently ignoring the body.++## Current bounds++One outer Profile loop per panel; lines, circular arcs and cubic Beziers;+15..150mm mesh spacing with bounded conforming refinement. Holes and ellipse+boundaries stop with diagnostics. One fabric per garment. One static Rest-pose+body binding. No seam allowances, darts, zippers, graded sizes, textile material+calibration, animated-body fitting, continuous collision detection, body+friction or garment self-contact are qualified in this foundation.++Body contact queries an oriented triangle surface and includes vertex, edge and+triangle-interior probes. It is not a watertight signed distance field. Sparse+probes cannot prove absence of every triangle intersection. Tight crotch and+armhole fits need especially careful inspection; failed fits stay failed.++## Local authoring witnesses++The supplied static Antonia gameplay candidate produced these retained results+with 30 sewing ticks followed by 60 gravity ticks for the skirts. Tunic and shorts+used 30 gravity ticks. Values are sample-based and specific to this body and cut.++| Source | Maximum stretch | Sampled penetration | Maximum seam gap | Qualification |+| --- | ---: | ---: | ---: | --- |+| `skirt.firmament` | 0.276% | 0mm | <0.001mm | Pass |+| `flared-skirt.firmament` | 4.66% | <0.001mm | 0.254mm | Pass |+| `tunic.firmament` | 21.3% | 4.41mm | 3.19mm | Fail: stretch |+| `shorts.firmament` | 45.7% | 5.36mm | 6.00mm | Fail: stretch and contact |++All four runs were finite and replayed exactly. The tighter fits are diagnostic+experiments, not accepted garment baselines. Use the flared skirt as the first+clothing starter and the straight skirt as a simple solver control. Preserve the+per-run evidence JSON and inspect the actual front/side/back meshes. Combining+the tunic and skirt in a viewer does not simulate garment-to-garment contact.diff --git a/fixtures/Canonical/Garment/README.md b/fixtures/Canonical/Garment/README.mdnew file mode 100644index 00000000..a685b46f--- /dev/null+++ b/fixtures/Canonical/Garment/README.md@@ -0,0 +1,17 @@+# Garment specimens++These are authoring sources for `schema Garment`, not finished textile patterns.+See `docs/public/firmament/garments.md` for commands, ownership and bounds.++- `skirt.firmament`: reusable Rect2/Profile Feature, typed Set/Pattern, two seam+ interfaces, explicit waistband support. The first lower-body coverage starter.+- `flared-skirt.firmament`: the same composition with a tapered material cut and+ interpolated waist/hem rings, for a closer waist and a wider free hem.+- `tunic.firmament`: named line spans, arm/neck openings, side/shoulder stitches,+ no supports; the garment rests on the loaded humanoid.+- `shorts.firmament`: mirrored Profile, four independently arranged panels,+ interpolated waist/leg rings and eight stitch interfaces. A tighter fit+ experiment; consult retained drape evidence before using it as a baseline.++`qualification.json` validates language/compilation. It does not certify a body+fit. The actual local humanoid is supplied to `garment drape --body ...`.diff --git a/fixtures/Canonical/Garment/flared-skirt.firmament b/fixtures/Canonical/Garment/flared-skirt.firmamentnew file mode 100644index 00000000..28b3b6fe--- /dev/null+++ b/fixtures/Canonical/Garment/flared-skirt.firmament@@ -0,0 +1,68 @@+schema Garment++// Two matching trapezoid panels. The flat cut remains the material rest surface.+Feature SkirtPanel(topWidth: Length = 502.654825mm, bottomWidth: Length = 738.274274mm, height: Length = 450mm) -> Profile {+ let halfTop: Length = topWidth / 2;+ let halfBottom: Length = bottomWidth / 2;+ Point2 lowerLeft { position: [-halfBottom, 0mm] }+ Point2 lowerRight { position: [halfBottom, 0mm] }+ Point2 upperRight { position: [halfTop, height] }+ Point2 upperLeft { position: [-halfTop, height] }+ Line2 hemGuide { from: lowerLeft; to: lowerRight }+ Line2 rightGuide { from: lowerRight; to: upperRight }+ Line2 waistGuide { from: upperRight; to: upperLeft }+ Line2 leftGuide { from: upperLeft; to: lowerLeft }+ return Profile {+ Loop Outer {+ Segment Bottom { Trace: hemGuide; From: lowerLeft; To: lowerRight }+ Segment Right { Trace: rightGuide; From: lowerRight; To: upperRight }+ Segment Top { Trace: waistGuide; From: upperRight; To: upperLeft }+ Segment Left { Trace: leftGuide; From: upperLeft; To: lowerLeft }+ }+ }+}+Feature skirtCut = SkirtPanel();++Record SidePlacement { origin: Point3; direction: Float; }+Static sides: Set<SidePlacement> {+ front => SidePlacement { origin: Point3(0mm, -35mm, 650mm); direction: 1; }+ back => SidePlacement { origin: Point3(0mm, -35mm, 650mm); direction: -1; }+}++Garment FlaredSkirt {+ meshSize: 65mm;+ Fabric cotton {+ arealDensity: 0.2;+ thickness: 2mm;+ warpCompliance: 0.000001;+ weftCompliance: 0.000001;+ diagonalCompliance: 0.000004;+ bendCompliance: 1000;+ }++ Pattern panels over sides {+ side => Panel sheet {+ profile: skirtCut;+ origin: side.origin;+ u: [side.direction, 0, 0];+ v: [0, 0, 1];+ wrapRadius: 235mm;+ wrapTopRadius: 160mm;+ wrapTopOrigin: [0mm, -35mm, 1100mm];+ grain: [0, 1];+ pin: [Top];+ }+ }++ Interface<Stitch> leftSide {+ a: panels.front.edges.Left;+ b: panels.back.edges.Right;+ orientation: Reversed;+ }+ Interface<Stitch> rightSide {+ a: panels.front.edges.Right;+ b: panels.back.edges.Left;+ orientation: Reversed;+ }+ Drape { figure: Anatolia; pose: Rest; }+}diff --git a/fixtures/Canonical/Garment/shorts.firmament b/fixtures/Canonical/Garment/shorts.firmamentnew file mode 100644index 00000000..678aa963--- /dev/null+++ b/fixtures/Canonical/Garment/shorts.firmament@@ -0,0 +1,126 @@+schema Garment++// Four cut panels; center-rise seams connect the two leg assemblies.+Feature ShortsPanel(length: Length = 400mm) -> Profile {+ let crotchHeight: Length = length - 290mm;+ let hipHeight: Length = length - 50mm;+ Point2 hemInner { position: [-125mm, 0mm] }+ Point2 hemOuter { position: [175mm, 0mm] }+ Point2 hipOuter { position: [175mm, hipHeight] }+ Point2 waistOuter { position: [153.15264mm, length] }+ Point2 waistInner { position: [-153.15264mm, length] }+ Point2 crotch { position: [-175mm, crotchHeight] }+ Line2 hemGuide { from: hemInner; to: hemOuter }+ Line2 outerLegGuide { from: hemOuter; to: hipOuter }+ Line2 outerHipGuide { from: hipOuter; to: waistOuter }+ Line2 waistGuide { from: waistOuter; to: waistInner }+ Line2 riseGuide { from: waistInner; to: crotch }+ Line2 innerLegGuide { from: crotch; to: hemInner }+ return Profile {+ Loop Outer {+ Segment hem { Trace: hemGuide; From: hemInner; To: hemOuter }+ Segment outerLeg { Trace: outerLegGuide; From: hemOuter; To: hipOuter }+ Segment outerHip { Trace: outerHipGuide; From: hipOuter; To: waistOuter }+ Segment waist { Trace: waistGuide; From: waistOuter; To: waistInner }+ Segment rise { Trace: riseGuide; From: waistInner; To: crotch }+ Segment innerLeg { Trace: innerLegGuide; From: crotch; To: hemInner }+ }+ }+}+Feature frontCut = ShortsPanel();+Plane center { origin: [0mm, 0mm, 0mm]; normal: [1, 0, 0]; up: [0, 0, 1] }+Mirrored Profile backCut From frontCut { Across: center }++Garment BasicShorts {+ meshSize: 60mm;+ Fabric cotton { thickness: 2mm; arealDensity: 0.2; }+ Panel rightFront {+ profile: frontCut;+ origin: [90mm, -40mm, 700mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ wrapRadius: 110mm;+ wrapTopRadius: 195mm;+ wrapTopOrigin: [0mm, -35mm, 1100mm];+ wrapTopAngle: 45deg;+ grain: [0, 1];+ pin: [waist];+ }+ Panel rightBack {+ profile: backCut;+ origin: [90mm, -40mm, 700mm];+ u: [-1, 0, 0];+ v: [0, 0, 1];+ wrapRadius: 110mm;+ wrapTopRadius: 195mm;+ wrapTopOrigin: [0mm, -35mm, 1100mm];+ wrapTopAngle: -45deg;+ grain: [0, 1];+ pin: [waist];+ }+ Panel leftFront {+ profile: backCut;+ origin: [-90mm, -40mm, 700mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ wrapRadius: 110mm;+ wrapTopRadius: 195mm;+ wrapTopOrigin: [0mm, -35mm, 1100mm];+ wrapTopAngle: -45deg;+ grain: [0, 1];+ pin: [waist];+ }+ Panel leftBack {+ profile: frontCut;+ origin: [-90mm, -40mm, 700mm];+ u: [-1, 0, 0];+ v: [0, 0, 1];+ wrapRadius: 110mm;+ wrapTopRadius: 195mm;+ wrapTopOrigin: [0mm, -35mm, 1100mm];+ wrapTopAngle: 45deg;+ grain: [0, 1];+ pin: [waist];+ }+ Interface<Stitch> rightOuterLeg {+ a: rightFront.edges.outerLeg;+ b: rightBack.edges.outerLeg;+ orientation: Reversed;+ }+ Interface<Stitch> rightOuterHip {+ a: rightFront.edges.outerHip;+ b: rightBack.edges.outerHip;+ orientation: Reversed;+ }+ Interface<Stitch> rightInnerLeg {+ a: rightFront.edges.innerLeg;+ b: rightBack.edges.innerLeg;+ orientation: Reversed;+ }+ Interface<Stitch> leftOuterLeg {+ a: leftFront.edges.outerLeg;+ b: leftBack.edges.outerLeg;+ orientation: Reversed;+ }+ Interface<Stitch> leftOuterHip {+ a: leftFront.edges.outerHip;+ b: leftBack.edges.outerHip;+ orientation: Reversed;+ }+ Interface<Stitch> leftInnerLeg {+ a: leftFront.edges.innerLeg;+ b: leftBack.edges.innerLeg;+ orientation: Reversed;+ }+ Interface<Stitch> centerFront {+ a: rightFront.edges.rise;+ b: leftFront.edges.rise;+ orientation: Reversed;+ }+ Interface<Stitch> centerBack {+ a: rightBack.edges.rise;+ b: leftBack.edges.rise;+ orientation: Reversed;+ }+ Drape { figure: Anatolia; pose: Rest; }+}diff --git a/fixtures/Canonical/Garment/skirt.firmament b/fixtures/Canonical/Garment/skirt.firmamentnew file mode 100644index 00000000..a9e49743--- /dev/null+++ b/fixtures/Canonical/Garment/skirt.firmament@@ -0,0 +1,51 @@+schema Garment++// A straight two-panel skirt. Pattern width equals a half-cylinder circumference.+Feature SkirtPanel(width: Length = 612.61057mm, height: Length = 450mm) -> Profile {+ let halfHeight: Length = height / 2;+ Rect2 cut { center: [0mm, halfHeight]; size: [width, height] }+ return Profile { Loop Outer { cut |> TraceLoop } }+}+Feature skirtCut = SkirtPanel();++Record SidePlacement { origin: Point3; direction: Float; }+Static sides: Set<SidePlacement> {+ front => SidePlacement { origin: Point3(0mm, -35mm, 650mm); direction: 1; }+ back => SidePlacement { origin: Point3(0mm, -35mm, 650mm); direction: -1; }+}++Garment BasicSkirt {+ meshSize: 65mm;+ Fabric cotton {+ arealDensity: 0.2;+ thickness: 2mm;+ warpCompliance: 0.000001;+ weftCompliance: 0.000001;+ diagonalCompliance: 0.000004;+ bendCompliance: 1000;+ }++ Pattern panels over sides {+ side => Panel sheet {+ profile: skirtCut;+ origin: side.origin;+ u: [side.direction, 0, 0];+ v: [0, 0, 1];+ wrapRadius: 195mm;+ grain: [0, 1];+ pin: [Top];+ }+ }++ Interface<Stitch> leftSide {+ a: panels.front.edges.Left;+ b: panels.back.edges.Right;+ orientation: Reversed;+ }+ Interface<Stitch> rightSide {+ a: panels.front.edges.Right;+ b: panels.back.edges.Left;+ orientation: Reversed;+ }+ Drape { figure: Anatolia; pose: Rest; }+}diff --git a/fixtures/Canonical/Garment/tunic.firmament b/fixtures/Canonical/Garment/tunic.firmamentnew file mode 100644index 00000000..d3327c67--- /dev/null+++ b/fixtures/Canonical/Garment/tunic.firmament@@ -0,0 +1,92 @@+schema Garment++Feature TunicPanel(height: Length = 560mm) -> Profile {+ let pitHeight: Length = height - 160mm;+ let innerPitHeight: Length = height - 120mm;+ let neckHeight: Length = height - 60mm;+ Point2 hemLeft { position: [-260mm, 0mm] }+ Point2 hemRight { position: [260mm, 0mm] }+ Point2 pitRight { position: [260mm, pitHeight] }+ Point2 innerPitRight { position: [180mm, innerPitHeight] }+ Point2 shoulderRight { position: [160mm, height] }+ Point2 neckRightPoint { position: [70mm, height] }+ Point2 neckBottom { position: [0mm, neckHeight] }+ Point2 neckLeftPoint { position: [-70mm, height] }+ Point2 shoulderLeft { position: [-160mm, height] }+ Point2 innerPitLeft { position: [-180mm, innerPitHeight] }+ Point2 pitLeft { position: [-260mm, pitHeight] }+ Line2 hemGuide { from: hemLeft; to: hemRight }+ Line2 rightSideGuide { from: hemRight; to: pitRight }+ Line2 rightArmLowerGuide { from: pitRight; to: innerPitRight }+ Line2 rightArmUpperGuide { from: innerPitRight; to: shoulderRight }+ Line2 rightShoulderGuide { from: shoulderRight; to: neckRightPoint }+ Line2 neckRightGuide { from: neckRightPoint; to: neckBottom }+ Line2 neckLeftGuide { from: neckBottom; to: neckLeftPoint }+ Line2 leftShoulderGuide { from: neckLeftPoint; to: shoulderLeft }+ Line2 leftArmUpperGuide { from: shoulderLeft; to: innerPitLeft }+ Line2 leftArmLowerGuide { from: innerPitLeft; to: pitLeft }+ Line2 leftSideGuide { from: pitLeft; to: hemLeft }+ return Profile {+ Loop Outer {+ Segment hem { Trace: hemGuide; From: hemLeft; To: hemRight }+ Segment rightSide { Trace: rightSideGuide; From: hemRight; To: pitRight }+ Segment rightArmLower { Trace: rightArmLowerGuide; From: pitRight; To: innerPitRight }+ Segment rightArmUpper { Trace: rightArmUpperGuide; From: innerPitRight; To: shoulderRight }+ Segment rightShoulder { Trace: rightShoulderGuide; From: shoulderRight; To: neckRightPoint }+ Segment neckRight { Trace: neckRightGuide; From: neckRightPoint; To: neckBottom }+ Segment neckLeft { Trace: neckLeftGuide; From: neckBottom; To: neckLeftPoint }+ Segment leftShoulder { Trace: leftShoulderGuide; From: neckLeftPoint; To: shoulderLeft }+ Segment leftArmUpper { Trace: leftArmUpperGuide; From: shoulderLeft; To: innerPitLeft }+ Segment leftArmLower { Trace: leftArmLowerGuide; From: innerPitLeft; To: pitLeft }+ Segment leftSide { Trace: leftSideGuide; From: pitLeft; To: hemLeft }+ }+ }+}+Feature tunicCut = TunicPanel();++Record SidePlacement { origin: Point3; direction: Float; }+Static sides: Set<SidePlacement> {+ front => SidePlacement { origin: Point3(0mm, 160mm, 1000mm); direction: 1; }+ back => SidePlacement { origin: Point3(0mm, -190mm, 1000mm); direction: -1; }+}++Garment SleevelessTunic {+ meshSize: 60mm;+ Fabric cotton {+ thickness: 2mm;+ arealDensity: 0.2;+ warpCompliance: 0.00000001;+ weftCompliance: 0.00000001;+ diagonalCompliance: 0.00000004;+ }+ Pattern panels over sides {+ side => Panel sheet {+ profile: tunicCut;+ origin: side.origin;+ u: [side.direction, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ }+ Interface<Stitch> leftSide {+ a: panels.front.edges.leftSide;+ b: panels.back.edges.rightSide;+ orientation: Reversed;+ }+ Interface<Stitch> rightSide {+ a: panels.front.edges.rightSide;+ b: panels.back.edges.leftSide;+ orientation: Reversed;+ }+ Interface<Stitch> leftShoulder {+ a: panels.front.edges.leftShoulder;+ b: panels.back.edges.rightShoulder;+ orientation: Reversed;+ }+ Interface<Stitch> rightShoulder {+ a: panels.front.edges.rightShoulder;+ b: panels.back.edges.leftShoulder;+ orientation: Reversed;+ }+ Drape { figure: Anatolia; pose: Rest; }+}diff --git a/fixtures/Canonical/qualification.json b/fixtures/Canonical/qualification.jsonindex b8eff0ca..447e1e1e 100644--- a/fixtures/Canonical/qualification.json+++ b/fixtures/Canonical/qualification.json@@ -9,6 +9,7 @@{ "path": "PlasticShell/plastic-shell-rib-standoff-junction.firmament", "codes": ["plastic-shell-constant-section-feature-zero-draft"] }],"actions": [+ { "path": "Garment", "operation": "validate" },{ "path": "Assembly", "operation": "assembly-inspect" },{ "path": "AssemblyInterfaces", "operation": "assembly-inspect" },{ "path": "Drawings", "operation": "drawing-compile" },diff --git a/scripts/render-garment.py b/scripts/render-garment.pynew file mode 100644index 00000000..07bbf4c1--- /dev/null+++ b/scripts/render-garment.py@@ -0,0 +1,111 @@+"""Render the real CLI garment OBJ artifacts; no geometry fitting or simulation in Blender.++Run Blender with --background --python scripts/render-garment.py -- --bottom shorts.+"""++import argparse+import hashlib+import json+from pathlib import Path+import sys++import bpy+from mathutils import Vector+++def material(name, color, roughness):+ result = bpy.data.materials.new(name)+ result.use_nodes = True+ shader = result.node_tree.nodes.get("Principled BSDF")+ shader.inputs["Base Color"].default_value = (*color, 1)+ shader.inputs["Roughness"].default_value = roughness+ return result+++def load_obj(path, surface):+ vertices = []+ faces = []+ for line in path.read_text(encoding="utf-8").splitlines():+ if line.startswith("v "):+ vertices.append(tuple(float(value) for value in line.split()[1:4]))+ elif line.startswith("f "):+ faces.append(tuple(int(value.split("/")[0]) - 1 for value in line.split()[1:]))+ mesh = bpy.data.meshes.new(path.stem)+ mesh.from_pydata(vertices, [], faces)+ mesh.update()+ result = bpy.data.objects.new(path.parent.name + "_" + path.stem, mesh)+ bpy.context.collection.objects.link(result)+ result.data.materials.append(surface)+ for face in result.data.polygons:+ face.use_smooth = True+ return result+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])+ parser.add_argument("--bottom", choices=("shorts", "skirt", "flared-skirt"), default="skirt")+ parser.add_argument("--samples", type=int, default=32)+ options = parser.parse_args(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])+ source = options.root / "artifacts/local/garment"+ output = source / "renders" / options.bottom+ output.mkdir(parents=True, exist_ok=True)+ bpy.ops.object.select_all(action="SELECT")+ bpy.ops.object.delete(use_global=False)+ body_path = source / options.bottom / "body.obj"+ tunic_path = source / "tunic/garment.obj"+ bottom_path = source / options.bottom / "garment.obj"+ load_obj(body_path, material("neutral mannequin", (.48, .47, .43), .65))+ load_obj(tunic_path, material("untextured tunic", (.08, .24, .31), .8))+ load_obj(bottom_path, material("untextured bottom", (.11, .14, .22), .8))+ 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+ scene.render.resolution_x = 800+ scene.render.resolution_y = 1000+ scene.render.resolution_percentage = 100+ scene.world.use_nodes = True+ scene.world.node_tree.nodes["Background"].inputs["Color"].default_value = (.35, .38, .44, 1)+ scene.world.node_tree.nodes["Background"].inputs["Strength"].default_value = .35+ for name, location, power, size in (+ ("key", (2, 3, 4), 650, 3),+ ("fill", (-3, 1, 2), 300, 3),+ ("rim", (0, -3, 3), 500, 2),+ ):+ light = bpy.data.lights.new(name, "AREA")+ light.energy = power+ light.shape = "DISK"+ light.size = size+ obj = bpy.data.objects.new(name, light)+ bpy.context.collection.objects.link(obj)+ obj.location = location+ obj.rotation_euler = (Vector((0, 0, 1)) - obj.location).to_track_quat("-Z", "Y").to_euler()+ camera = bpy.data.objects.new("camera", bpy.data.cameras.new("camera"))+ bpy.context.collection.objects.link(camera)+ camera.data.type = "ORTHO"+ camera.data.ortho_scale = 2.05+ scene.camera = camera+ for name, location in (+ ("front", (2.6, 4, 2)),+ ("side", (4, .3, 1.8)),+ ("back", (2.6, -4, 2)),+ ):+ camera.location = location+ camera.rotation_euler = (Vector((0, -.035, .9)) - camera.location).to_track_quat("-Z", "Y").to_euler()+ scene.render.filepath = str(output / (name + ".png"))+ bpy.ops.render.render(write_still=True)+ bpy.ops.wm.save_as_mainfile(filepath=str(output / "garment-preview.blend"))+ evidence = {+ "geometryAuthority": "Aetheris.CLI garment drape; Blender only presents retained OBJ meshes",+ "inputs": {str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in (body_path, tunic_path, bottom_path)},+ "bottom": options.bottom,+ "textures": False,+ }+ (output / "render-evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")+++if __name__ == "__main__":+ main()