Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Expose and build bounded replacement surface patches

Yuechen Li228a69861f29
diff --git a/Aetheris.CLI.Tests/SculptingCliTests.cs b/Aetheris.CLI.Tests/SculptingCliTests.cs
index 38965481..1ff230e1 100644
--- a/Aetheris.CLI.Tests/SculptingCliTests.cs
+++ b/Aetheris.CLI.Tests/SculptingCliTests.cs
@@ -26,5 +26,25 @@ public sealed class SculptingCliTests
finally { if (File.Exists(output)) File.Delete(output); var delta = Path.ChangeExtension(output, ".delta.json"); if (File.Exists(delta)) File.Delete(delta); }
}
+ [Fact]
+ public void PatchReplacementBuildAndReinspectionExposeNonRationalSurfaceAndInteriorBounds()
+ {
+ var fixture = Path.Combine(Root(), "fixtures", "Canonical", "Sculpting", "surf-x1-freeform-housing.firmament");
+ var output = Path.Combine(Path.GetTempPath(), "aetheris-surf-x1-" + Guid.NewGuid().ToString("N") + ".step");
+ try
+ {
+ var buildOut = new StringWriter(); Assert.Equal(0, CliRunner.Run(["build", fixture, "--output", output, "--json"], buildOut, new StringWriter()));
+ using var build = JsonDocument.Parse(buildOut.ToString()); var root = build.RootElement;
+ Assert.Equal(1, root.GetProperty("surfaceInventory").GetProperty("nonRationalBSpline").GetInt32()); Assert.Equal(0, root.GetProperty("rationalNurbs").GetInt32());
+ var patch = root.GetProperty("surfacePatches")[0]; Assert.Equal("CrownPatch", patch.GetProperty("patchId").GetString()); Assert.Equal("NonRationalBSpline", patch.GetProperty("exportClass").GetString());
+ Assert.Equal(6, patch.GetProperty("controlCountU").GetInt32()); Assert.Equal(4, patch.GetProperty("continuityContracts").GetArrayLength());
+ var analyzeOut = new StringWriter(); Assert.Equal(0, CliRunner.Run(["analyze", output, "--json"], analyzeOut, new StringWriter()));
+ using var analyze = JsonDocument.Parse(analyzeOut.ToString()); var summary = analyze.RootElement.GetProperty("summary");
+ Assert.Equal("enclosed-manifold", summary.GetProperty("structuralAssessment").GetString()); Assert.Equal(1, summary.GetProperty("surfaceFamilies").GetProperty("bspline").GetInt32());
+ Assert.InRange(summary.GetProperty("boundingBox").GetProperty("max").GetProperty("z").GetDouble(), 26.269, 26.270);
+ }
+ finally { if (File.Exists(output)) File.Delete(output); var delta = Path.ChangeExtension(output, ".delta.json"); if (File.Exists(delta)) File.Delete(delta); }
+ }
+
private static string Root() { var d = new DirectoryInfo(AppContext.BaseDirectory); while (d is not null && !File.Exists(Path.Combine(d.FullName, "Aetheris.slnx"))) d = d.Parent; return d!.FullName; }
}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 63a00e01..539ad28f 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -537,6 +537,7 @@ public static class CliRunner
outputState = compile.OutputState.StateId,
compile.OutputState.Delta,
validationEvidence = compile.OutputState.ValidationEvidence,
+ surfacePatches = compile.OutputState.SurfacePatches,
surfaceInventory = export.Inventory,
productBoundary = new { rationalNurbs = export.Inventory.RationalNurbs, admitted = export.Inventory.RationalNurbs == 0 },
timingsMilliseconds = compile.Timings with { StepExportMilliseconds = exportClock.Elapsed.TotalMilliseconds }
@@ -545,7 +546,7 @@ public static class CliRunner
{
command = "build", success = true, input = Path.GetFullPath(sourcePath), output, domain = "Sculpting", model = compile.ModelName,
state = DescribeSculptState(compile.OutputState), states = compile.States.Values.Select(DescribeSculptState), geometricDelta = compile.OutputState.Delta,
- validationEvidence = compile.OutputState.ValidationEvidence, surfaceInventory = export.Inventory, rationalNurbs = export.Inventory.RationalNurbs,
+ validationEvidence = compile.OutputState.ValidationEvidence, surfacePatches = compile.OutputState.SurfacePatches, surfaceInventory = export.Inventory, rationalNurbs = export.Inventory.RationalNurbs,
deltaArtifact = deltaPath, timingsMilliseconds = compile.Timings with { StepExportMilliseconds = exportClock.Elapsed.TotalMilliseconds }, diagnostics = compile.Diagnostics
}, JsonOptions));
else { stdout.WriteLine($"Built {Path.GetFileName(sourcePath)}"); stdout.WriteLine($"STEP: {output}"); stdout.WriteLine($"State: {compile.OutputState.AuthoredName} ({compile.OutputState.StateId}) <- {compile.OutputState.PredecessorStateId}"); stdout.WriteLine($"Geometric delta: {deltaPath}"); stdout.WriteLine($"STEP surfaces: Plane={export.Inventory.Plane}, Cylinder={export.Inventory.Cylinder}, NonRationalBSpline={export.Inventory.NonRationalBSpline}, RationalNURBS={export.Inventory.RationalNurbs}"); }
@@ -556,7 +557,7 @@ public static class CliRunner
{
state.AuthoredName, state.StateId, state.PredecessorStateId, state.BodyStableId,
construction = new { state.Construction.Width, state.Construction.Depth, state.Construction.BaseHeight, state.Construction.CrownWidth, state.Construction.CrownDepth, state.Construction.CrownOffset, state.Construction.FinalHeight },
- semanticInventory = state.SemanticInventory.Values, hasDelta = state.Delta is not null
+ semanticInventory = state.SemanticInventory.Values, surfacePatches = state.SurfacePatches, hasDelta = state.Delta is not null
};
private static int RunSheetMetalAuthoredBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)
diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.cs
index 233e2ef9..968eb4b8 100644
--- a/Aetheris.CLI/StepAnalyzer.cs
+++ b/Aetheris.CLI/StepAnalyzer.cs
@@ -1899,6 +1899,21 @@ public sealed record VolumeAnalysisResult(
points.Add(new Point3D(torus.Center.X + xExtent, torus.Center.Y + yExtent, torus.Center.Z + zExtent));
}
+ // A bounded polynomial B-spline can reach extrema away from every trim vertex.
+ // Sample its native knot domain deterministically so a freeform crown does not
+ // collapse to the height of its planar boundary in structured inspection.
+ foreach (var surface in body.Geometry.Surfaces.Select(x => x.Value.BSplineSurfaceWithKnots).Where(x => x is not null).Select(x => x!))
+ {
+ const int samples = 33;
+ for (var i = 0; i < samples; i++)
+ for (var j = 0; j < samples; j++)
+ {
+ var u = surface.DomainStartU + (surface.DomainEndU - surface.DomainStartU) * i / (samples - 1d);
+ var v = surface.DomainStartV + (surface.DomainEndV - surface.DomainStartV) * j / (samples - 1d);
+ points.Add(surface.Evaluate(u, v));
+ }
+ }
+
if (points.Count > 0)
{
return ComputeBoundingBox(points);
diff --git a/Aetheris.Modules.Tests/SurfX1PatchSurfacingTests.cs b/Aetheris.Modules.Tests/SurfX1PatchSurfacingTests.cs
new file mode 100644
index 00000000..a8f2e4b3
--- /dev/null
+++ b/Aetheris.Modules.Tests/SurfX1PatchSurfacingTests.cs
@@ -0,0 +1,117 @@
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Surfacing;
+using Xunit;
+
+namespace Aetheris.Modules.Tests;
+
+public sealed class SurfX1PatchSurfacingTests
+{
+ [Fact]
+ public void FlagshipReplacesOnlyCrownWithInspectableNonRationalPatch()
+ {
+ var compile = CompileFlagship();
+ Assert.True(compile.IsSuccess, string.Join(';', compile.Diagnostics.Select(x => $"{x.Code}:{x.Message}")));
+ var state = compile.OutputState!; var patch = Assert.Single(state.SurfacePatches);
+ Assert.Equal(SurfacePatchClass.NonRationalBSpline, patch.SurfaceClass);
+ Assert.Equal((3, 3), (patch.DegreeU, patch.DegreeV)); Assert.Equal((6, 6), (patch.ControlCountU, patch.ControlCountV));
+ Assert.Contains(state.Delta!.Correspondence, x => x.InputEntity == SculptedHousingFactory.CrownRegion && x.OutputEntities.SequenceEqual(["CrownPatch"]));
+ Assert.Contains(state.ValidationEvidence, x => x.Check == "AuthorizedLocality" && x.Satisfied && x.MaximumObservedDeviation == 0d);
+ Assert.Contains(state.ValidationEvidence, x => x.Check == "SharedBoundaryTopology" && x.Satisfied);
+ Assert.Contains(state.ValidationEvidence, x => x.Check == "Boundary:BoundaryEast:G1" && x.Satisfied && x.MaximumObservedDeviation < .001d);
+ Assert.Contains(state.ValidationEvidence, x => x.Check == "Boundary:BoundaryWest:G1" && x.Satisfied && x.MaximumObservedDeviation < .001d);
+ }
+
+ [Fact]
+ public void TrimAndExtendRemainBoundedByExistingNonRationalSupport()
+ {
+ var patch = Assert.IsType<BSplineSurfacePatch>(CompileFlagship().OutputState!.Construction.ReplacementPatch);
+ var trimmed = SurfacePatchOperations.TrimRegion(patch, new(.1, .9, .2, .8));
+ Assert.True(trimmed.IsSuccess); Assert.Equal(new SurfaceParameterDomain(.1, .9, .2, .8), trimmed.Patch!.ParameterDomain);
+ var extended = SurfacePatchOperations.ExtendRegion((BSplineSurfacePatch)trimmed.Patch, new(0, 1, 0, 1));
+ Assert.True(extended.IsSuccess);
+ var rejected = SurfacePatchOperations.ExtendRegion(patch, new(-.1, 1, 0, 1));
+ Assert.False(rejected.IsSuccess); Assert.Contains(rejected.Diagnostics, x => x.Code == "surf-extend-law-unsupported");
+ }
+
+ [Fact]
+ public void FlagshipStepIsEnclosedReimportsAndContainsNoRationalSurface()
+ {
+ var export = SculptStepExporter.Export(CompileFlagship().OutputState!, "SURF-X1");
+ Assert.True(export.IsSuccess, string.Join(';', export.Diagnostics.Select(x => x.Message)));
+ Assert.Equal(1, export.Inventory.NonRationalBSpline); Assert.Equal(0, export.Inventory.RationalNurbs);
+ Assert.DoesNotContain("RATIONAL_B_SPLINE_SURFACE", export.Step!, StringComparison.Ordinal);
+ var imported = Step242Importer.ImportBody(export.Step!);
+ Assert.True(imported.IsSuccess, string.Join(';', imported.Diagnostics.Select(x => x.Message)));
+ Assert.Single(imported.Value!.Geometry.Surfaces, x => x.Value.BSplineSurfaceWithKnots is not null);
+ var incidence = imported.Value.Topology.Coedges.GroupBy(x => x.EdgeId).Select(x => x.Count()).ToArray();
+ Assert.All(incidence, count => Assert.Equal(2, count));
+ }
+
+ [Fact]
+ public void G1ViolationFailsAtomicallyAndLeavesPredecessorAccepted()
+ {
+ var source = File.ReadAllText(FlagshipPath()).Replace("[-20mm, -12mm, 20mm]", "[-20mm, -12mm, 23mm]", StringComparison.Ordinal);
+ var compile = SculptingAuthoring.Compile(source);
+ Assert.False(compile.IsSuccess); Assert.Contains(compile.Diagnostics, x => x.Code == "surf-boundary-g1-violation");
+ Assert.True(compile.States.TryGetValue("Base", out var predecessor)); Assert.Null(predecessor.PredecessorStateId);
+ Assert.False(compile.States.ContainsKey("FreeformCrown"));
+ }
+
+ [Fact]
+ public void ReplacedHistoricalSelectorProducesActionableDiagnostic()
+ {
+ var first = CompileFlagship(); var input = first.OutputState!; var patch = input.Construction.ReplacementPatch!;
+ var operation = new ReplaceRegionOperation("stale.ReplaceRegion", SculptedHousingFactory.CrownRegion, patch,
+ [SculptedHousingFactory.CrownRegion], new(-30, -20, 20, 30, 20, 28), [], []);
+ var result = ReplaceRegionSculptor.Apply(input, "Stale", operation);
+ Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, x => x.Code == "surf-selector-target-replaced" && x.Message.Contains("CrownPatch", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void SafeHoleResolvesCurrentStateAfterReplacementAndPreservesPatchAndExistingHoles()
+ {
+ var compile = CompileFlagship(); var sculpted = compile.States["FreeformCrown"]; var after = compile.States["CrownWithServiceHole"];
+ Assert.Equal(sculpted.StateId, after.PredecessorStateId); Assert.Contains("H5", after.Delta!.Introduces);
+ Assert.Contains("CrownPatch", after.Delta.Preserves);
+ Assert.All(new[] { "CrownPatch", "H1", "H2", "H3", "H4" }, id => Assert.Contains(after.ValidationEvidence, x => x.Check == $"Preserve:{id}" && x.Satisfied));
+ var export = SculptStepExporter.Export(after, "SURF-X1 downstream hole");
+ Assert.True(export.IsSuccess); Assert.Equal(1, export.Inventory.NonRationalBSpline); Assert.Equal(5, export.Inventory.Cylinder); Assert.Equal(0, export.Inventory.RationalNurbs);
+ }
+
+ [Fact]
+ public void IdenticalInputAndPatchAreDeterministic()
+ {
+ var first = CompileFlagship(); var second = CompileFlagship();
+ Assert.Equal(first.OutputState!.StateId, second.OutputState!.StateId);
+ Assert.Equal(SculptStepExporter.Export(first.OutputState, "SURF-X1").Step, SculptStepExporter.Export(second.OutputState, "SURF-X1").Step);
+ }
+
+ [Fact]
+ public void LowAndHighCrownsBranchIndependentlyFromSamePredecessor()
+ {
+ var compile = CompileFlagship(); var predecessor = compile.States["Base"]; var low = compile.States["FreeformCrown"];
+ var source = (BSplineSurfacePatch)low.Construction.ReplacementPatch!; var s = source.Spline;
+ var controls = s.ControlPoints.Select(row => (IReadOnlyList<Aetheris.Kernel.Core.Math.Point3D>)row.Select(p => new Aetheris.Kernel.Core.Math.Point3D(p.X, p.Y, 20d + (p.Z - 20d) * 1.4d)).ToArray()).ToArray();
+ var highSpline = new BSplineSurfaceWithKnots(s.DegreeU, s.DegreeV, controls, s.SurfaceForm, s.UClosed, s.VClosed, s.SelfIntersect, s.KnotMultiplicitiesU, s.KnotMultiplicitiesV, s.KnotValuesU, s.KnotValuesV, s.KnotSpec);
+ var highPatch = new BSplineSurfacePatch("HighCrownPatch", highSpline, source.ParameterDomain, source.BoundaryLoop);
+ var operation = new ReplaceRegionOperation("High.ReplaceRegion", SculptedHousingFactory.CrownRegion, highPatch,
+ [SculptedHousingFactory.CrownRegion, SculptedHousingFactory.TransitionZone], new(-30, -20, 20, 30, 20, 30),
+ [new(SculptedHousingFactory.BottomMountingInterface, PreservationMode.ExactGeometry), new(SculptedHousingFactory.MountingHolePattern, PreservationMode.PatternPlacementAndDiameter)],
+ [SculptRequirement.ClosedManifold, SculptRequirement.OrientationConsistency, SculptRequirement.NoSelfIntersection]);
+ var high = ReplaceRegionSculptor.Apply(predecessor, "HighCrown", operation);
+ Assert.True(high.IsSuccess, string.Join(';', high.Diagnostics.Select(x => x.Message)));
+ Assert.Equal(predecessor.StateId, low.PredecessorStateId); Assert.Equal(predecessor.StateId, high.OutputState!.PredecessorStateId);
+ Assert.NotEqual(low.StateId, high.OutputState.StateId); Assert.Equal(20d, predecessor.Construction.FinalHeight);
+ Assert.True(high.OutputState.Construction.FinalHeight > low.Construction.FinalHeight);
+ }
+
+ private static SculptingCompileResult CompileFlagship() => SculptingAuthoring.CompileFile(FlagshipPath());
+ private static string FlagshipPath() => Path.Combine(RepositoryRoot(), "fixtures", "Canonical", "Sculpting", "surf-x1-freeform-housing.firmament");
+ private static string RepositoryRoot()
+ {
+ var current = new DirectoryInfo(AppContext.BaseDirectory);
+ while (current is not null && !File.Exists(Path.Combine(current.FullName, "Aetheris.slnx"))) current = current.Parent;
+ return current?.FullName ?? throw new DirectoryNotFoundException("Repository root not found.");
+ }
+}
diff --git a/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs b/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs
index 45d77081..26039bce 100644
--- a/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs
+++ b/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs
@@ -15,6 +15,7 @@ internal static class SculptedHousingBrepBuilder
{
var diagnostics = Validate(construction);
if (diagnostics.Count > 0) return new(null, diagnostics);
+ if (construction.ReplacementPatch is not null) return BuildReplacement(construction);
var sections = construction.HasCrown
? new[] { Section(construction.Width, construction.Depth, 0d), Section(construction.Width, construction.Depth, construction.BaseHeight), Section(construction.CrownWidth, construction.CrownDepth, construction.FinalHeight) }
@@ -98,6 +99,104 @@ internal static class SculptedHousingBrepBuilder
return new(body, []);
}
+ private static BuildResult BuildReplacement(HousingConstruction c)
+ {
+ var patch = c.ReplacementPatch!;
+ var patchDiagnostics = patch.Validate();
+ if (patchDiagnostics.Count > 0) return new(null, patchDiagnostics);
+
+ var builder = new TopologyBuilder();
+ var points = new Dictionary<VertexId, Point3D>();
+ var curves = new Dictionary<EdgeId, (CurveGeometry Curve, ParameterInterval Interval)>();
+ var faces = new List<(FaceId Face, SurfaceGeometry Surface, bool Reversed)>();
+ var bottom = Section(c.Width, c.Depth, 0d);
+ var top = Section(c.Width, c.Depth, c.BaseHeight);
+ var vb = bottom.Select(p => { var id = builder.AddVertex(); points[id] = p; return id; }).ToArray();
+ var vt = top.Select(p => { var id = builder.AddVertex(); points[id] = p; return id; }).ToArray();
+ var eb = Enumerable.Range(0, 4).Select(i => AddLine(builder, curves, vb[i], vb[(i + 1) % 4], points)).ToArray();
+ var et = Enumerable.Range(0, 4).Select(i => AddLine(builder, curves, vt[i], vt[(i + 1) % 4], points)).ToArray();
+ var ev = Enumerable.Range(0, 4).Select(i => AddLine(builder, curves, vb[i], vt[i], points)).ToArray();
+
+ var corners = new[]
+ {
+ patch.Evaluate(patch.ParameterDomain.UMin, patch.ParameterDomain.VMin),
+ patch.Evaluate(patch.ParameterDomain.UMax, patch.ParameterDomain.VMin),
+ patch.Evaluate(patch.ParameterDomain.UMax, patch.ParameterDomain.VMax),
+ patch.Evaluate(patch.ParameterDomain.UMin, patch.ParameterDomain.VMax),
+ };
+ var vi = corners.Select(p => { var id = builder.AddVertex(); points[id] = p; return id; }).ToArray();
+ var ei = Enumerable.Range(0, 4).Select(i => AddLine(builder, curves, vi[i], vi[(i + 1) % 4], points)).ToArray();
+
+ var bhv = new VertexId[c.Holes.Count]; var thv = new VertexId[c.Holes.Count];
+ var bhe = new EdgeId[c.Holes.Count]; var the = new EdgeId[c.Holes.Count]; var seams = new EdgeId[c.Holes.Count];
+ for (var i = 0; i < c.Holes.Count; i++)
+ {
+ var h = c.Holes[i]; var seamX = h.CenterX + h.Diameter / 2d;
+ bhv[i] = builder.AddVertex(); thv[i] = builder.AddVertex();
+ points[bhv[i]] = new(seamX, h.CenterY, 0d); points[thv[i]] = new(seamX, h.CenterY, c.BaseHeight);
+ bhe[i] = AddCircle(builder, curves, bhv[i], h, 0d); the[i] = AddCircle(builder, curves, thv[i], h, c.BaseHeight);
+ seams[i] = AddLine(builder, curves, bhv[i], thv[i], points);
+ }
+
+ var bottomLoops = new List<LoopId> { AddLoop(builder, eb.Select(x => new Use(x, false)).ToArray()) };
+ for (var i = 0; i < c.Holes.Count; i++) bottomLoops.Add(AddLoop(builder, [new(bhe[i], true)]));
+ faces.Add((builder.AddFace(bottomLoops), SurfaceGeometry.FromPlane(new PlaneSurface(Point3D.Origin, Dir(0, 0, -1), Dir(1, 0, 0))), false));
+
+ var frameLoops = new List<LoopId>
+ {
+ AddLoop(builder, et.Select(x => new Use(x, true)).Reverse().ToArray()),
+ AddLoop(builder, ei.Select(x => new Use(x, false)).ToArray()),
+ };
+ for (var i = 0; i < c.Holes.Count; i++) frameLoops.Add(AddLoop(builder, [new(the[i], false)]));
+ faces.Add((builder.AddFace(frameLoops), SurfaceGeometry.FromPlane(new PlaneSurface(new(0, 0, c.BaseHeight), Dir(0, 0, 1), Dir(1, 0, 0))), false));
+
+ for (var i = 0; i < 4; i++)
+ {
+ var n = (i + 1) % 4;
+ var loop = AddLoop(builder, [new(eb[i], false), new(ev[n], false), new(et[i], true), new(ev[i], true)]);
+ var edge = bottom[n] - bottom[i]; var rise = top[i] - bottom[i];
+ faces.Add((builder.AddFace([loop]), SurfaceGeometry.FromPlane(new PlaneSurface(bottom[i], Direction3D.Create(edge.Cross(rise)), Direction3D.Create(edge))), false));
+ }
+
+ var patchLoop = AddLoop(builder, ei.Select(x => new Use(x, true)).Reverse().ToArray());
+ faces.Add((builder.AddFace([patchLoop]), patch.Support, patch.ReversedOrientation));
+ for (var i = 0; i < c.Holes.Count; i++)
+ {
+ var loop = AddLoop(builder, [new(bhe[i], false), new(seams[i], false), new(the[i], true), new(seams[i], true)]);
+ var h = c.Holes[i];
+ faces.Add((builder.AddFace([loop]), SurfaceGeometry.FromCylinder(new CylinderSurface(new(h.CenterX, h.CenterY, 0d), Dir(0, 0, 1), h.Diameter / 2d, Dir(1, 0, 0))), false));
+ }
+
+ var shell = builder.AddShell(faces.Select(x => x.Face).ToArray()); builder.AddBody([shell]);
+ var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel(); var curveId = 1;
+ foreach (var pair in curves.OrderBy(x => x.Key.Value))
+ {
+ var id = new CurveGeometryId(curveId++); geometry.AddCurve(id, pair.Value.Curve); bindings.AddEdgeBinding(new(pair.Key, id, pair.Value.Interval));
+ }
+ var surfaceId = 1;
+ foreach (var face in faces)
+ {
+ var id = new SurfaceGeometryId(surfaceId++); geometry.AddSurface(id, face.Surface); bindings.AddFaceBinding(new(face.Face, id, face.Reversed));
+ }
+ var body = new BrepBody(builder.Model, geometry, bindings, points);
+ var validation = BrepBindingValidator.Validate(body, true);
+ return validation.IsSuccess ? new(body, []) : new(null, validation.Diagnostics.Select(x => new SculptDiagnostic("sculpt-brep-binding-invalid", x.Message)).ToArray());
+ }
+
+ private static EdgeId AddLine(TopologyBuilder builder, IDictionary<EdgeId, (CurveGeometry, ParameterInterval)> curves, VertexId start, VertexId end, IReadOnlyDictionary<VertexId, Point3D> points)
+ {
+ var edge = builder.AddEdge(start, end); var vector = points[end] - points[start];
+ curves[edge] = (CurveGeometry.FromLine(new Line3Curve(points[start], Direction3D.Create(vector))), new(0d, vector.Length));
+ return edge;
+ }
+
+ private static EdgeId AddCircle(TopologyBuilder builder, IDictionary<EdgeId, (CurveGeometry, ParameterInterval)> curves, VertexId seam, HousingHole hole, double z)
+ {
+ var edge = builder.AddEdge(seam, seam);
+ curves[edge] = (CurveGeometry.FromCircle(new Circle3Curve(new(hole.CenterX, hole.CenterY, z), Dir(0, 0, 1), hole.Diameter / 2d, Dir(1, 0, 0))), new(0d, 2d * double.Pi));
+ return edge;
+ }
+
private static List<SculptDiagnostic> Validate(HousingConstruction c)
{
var d = new List<SculptDiagnostic>();
@@ -107,8 +206,12 @@ internal static class SculptedHousingBrepBuilder
foreach (var h in c.Holes)
{
var r = h.Diameter / 2d;
- if (!Positive(h.Diameter) || Math.Abs(h.CenterX) + r >= c.CrownWidth / 2d || Math.Abs(h.CenterY) + r >= c.CrownDepth / 2d)
+ if (!Positive(h.Diameter) || Math.Abs(h.CenterX) + r >= c.Width / 2d || Math.Abs(h.CenterY) + r >= c.Depth / 2d)
+ d.Add(new("sculpt-hole-pattern-outside-body", $"Mounting hole '{h.StableId}' must remain inside the housing footprint.", h.StableId));
+ if (c.ReplacementPatch is null && (Math.Abs(h.CenterX) + r >= c.CrownWidth / 2d || Math.Abs(h.CenterY) + r >= c.CrownDepth / 2d))
d.Add(new("sculpt-hole-pattern-outside-crown", $"Mounting hole '{h.StableId}' must remain inside the bounded crown support.", h.StableId));
+ if (c.ReplacementPatch is not null && Math.Abs(h.CenterX) - r < c.CrownWidth / 2d && Math.Abs(h.CenterY) - r < c.CrownDepth / 2d)
+ d.Add(new("surf-patch-intersects-protected-hole", $"Replacement patch intersects protected mounting hole '{h.StableId}'. Move the hole or reduce the patch boundary.", h.StableId));
}
for (var i = 0; i < c.Holes.Count; i++) for (var j = i + 1; j < c.Holes.Count; j++)
{ var a = c.Holes[i]; var h = c.Holes[j]; if (Math.Sqrt(Math.Pow(a.CenterX - h.CenterX, 2) + Math.Pow(a.CenterY - h.CenterY, 2)) <= (a.Diameter + h.Diameter) / 2d) d.Add(new("sculpt-self-intersection", $"Mounting holes '{a.StableId}' and '{h.StableId}' overlap.")); }
diff --git a/Aetheris.Surfacing/SculptingAuthoring.cs b/Aetheris.Surfacing/SculptingAuthoring.cs
index 5b779dcf..ec6ca839 100644
--- a/Aetheris.Surfacing/SculptingAuthoring.cs
+++ b/Aetheris.Surfacing/SculptingAuthoring.cs
@@ -1,6 +1,8 @@
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
namespace Aetheris.Surfacing;
@@ -17,8 +19,30 @@ public static class SculptingAuthoring
public static SculptingCompileResult Compile(string source)
{
var total = Stopwatch.StartNew(); var diagnostics = new List<SculptDiagnostic>(); var states = new Dictionary<string, BodyState>(StringComparer.Ordinal);
+ var patches = new Dictionary<string, BoundedSurfacePatch>(StringComparer.Ordinal);
var model = ModelHeader.Match(source); if (!model.Success) return Fail("<unknown>", "sculpt-source-malformed", "Sculpting source requires 'Model Name { ... }'.");
if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant)) diagnostics.Add(new("sculpt-units-invalid", "SURF-X0 authoring requires millimetres."));
+ foreach (var block in Blocks(source, "SurfacePatch"))
+ {
+ var degree = NumberVector(block.Body, "Degree", 2, diagnostics); var domain = NumberVector(block.Body, "Domain", 4, diagnostics);
+ var knotsU = NumberVectorAny(block.Body, "KnotsU", diagnostics); var knotsV = NumberVectorAny(block.Body, "KnotsV", diagnostics);
+ var rows = ControlRows(block.Body, diagnostics); var boundaries = ParseBoundaries(block.Body, diagnostics);
+ if (degree is null || domain is null || knotsU is null || knotsV is null || rows is null || boundaries is null) continue;
+ try
+ {
+ var du = checked((int)degree[0]); var dv = checked((int)degree[1]);
+ if (degree[0] != du || degree[1] != dv) throw new ArgumentException("Patch degrees must be integers.");
+ var (mu, ku) = CompressKnots(knotsU); var (mv, kv) = CompressKnots(knotsV);
+ var spline = new BSplineSurfaceWithKnots(du, dv, rows, "UNSPECIFIED", false, false, false, mu, mv, ku, kv, "UNSPECIFIED");
+ var patch = new BSplineSurfacePatch(block.Name, spline, new(domain[0], domain[1], domain[2], domain[3]), new(block.Name + ".OuterLoop", boundaries));
+ var patchDiagnostics = patch.Validate(); diagnostics.AddRange(patchDiagnostics);
+ if (patchDiagnostics.Count == 0 && !patches.TryAdd(block.Name, patch)) diagnostics.Add(new("surf-patch-duplicate", $"SurfacePatch '{block.Name}' is declared more than once.", block.Name));
+ }
+ catch (Exception exception) when (exception is ArgumentException or OverflowException)
+ {
+ diagnostics.Add(new("surf-patch-invalid", $"SurfacePatch '{block.Name}' is invalid: {exception.Message}", block.Name));
+ }
+ }
var baseClock = Stopwatch.StartNew();
foreach (var block in Blocks(source, "BodyState"))
{
@@ -35,8 +59,43 @@ public static class SculptingAuthoring
var inputName = ScalarText(block.Body, "Input");
if (inputName is null || !states.TryGetValue(inputName, out var input)) { diagnostics.Add(new("sculpt-predecessor-unresolved", $"SculptState '{block.Name}' must name one previously accepted Input state.")); continue; }
var operationBlock = Blocks(block.Body, "OffsetRegion").SingleOrDefault();
- if (operationBlock is null) { diagnostics.Add(new("sculpt-operation-unsupported", $"SculptState '{block.Name}' requires exactly one OffsetRegion operation.")); continue; }
- var target = ScalarText(operationBlock.Body, "Target") ?? string.Empty;
+ var replaceBlock = Blocks(block.Body, "ReplaceRegion").SingleOrDefault();
+ var holeBlock = Blocks(block.Body, "HoleFeature").SingleOrDefault();
+ if (new[] { operationBlock, replaceBlock, holeBlock }.Count(x => x is not null) != 1) { diagnostics.Add(new("sculpt-operation-unsupported", $"SculptState '{block.Name}' requires exactly one OffsetRegion, ReplaceRegion, or HoleFeature operation.")); continue; }
+ if (holeBlock is not null)
+ {
+ var holeTarget = ScalarText(holeBlock.Body, "Target") ?? string.Empty; var holeId = ScalarText(holeBlock.Body, "Id") ?? string.Empty;
+ var center = Vector(holeBlock.Body, "Center", 2, diagnostics); var diameter = Length(holeBlock.Body, "Diameter", diagnostics); var holeEnvelope = Vector(holeBlock.Body, "InfluenceEnvelope", 6, diagnostics);
+ var preserveCurrent = List(block.Body, "Preserve"); var holeRequirements = ParseRequirements(List(block.Body, "Require"), diagnostics);
+ operationClock.Stop(); opConstruction += operationClock.Elapsed;
+ if (center is null || diameter is null || holeEnvelope is null) continue;
+ var holeOperation = new SafeHoleOperation(block.Name + ".HoleFeature", holeTarget, new(holeId, center[0], center[1], diameter.Value),
+ new(holeEnvelope[0], holeEnvelope[1], holeEnvelope[2], holeEnvelope[3], holeEnvelope[4], holeEnvelope[5]), preserveCurrent.Select(Preservation).ToArray(), holeRequirements);
+ var holeClock = Stopwatch.StartNew(); var holeResult = SafeHoleSculptor.Apply(input, block.Name, holeOperation); holeClock.Stop(); verification += holeClock.Elapsed;
+ if (!holeResult.IsSuccess || holeResult.OutputState is null) diagnostics.AddRange(holeResult.Diagnostics);
+ else if (!states.TryAdd(block.Name, holeResult.OutputState)) diagnostics.Add(new("sculpt-state-duplicate", $"State '{block.Name}' is declared more than once."));
+ continue;
+ }
+ if (replaceBlock is not null)
+ {
+ var replaceTarget = ScalarText(replaceBlock.Body, "Target") ?? string.Empty; var patchName = ScalarText(replaceBlock.Body, "Patch");
+ var replaceEnvelope = Vector(replaceBlock.Body, "InfluenceEnvelope", 6, diagnostics);
+ var replaceMayModify = List(block.Body, "MayModify"); var replacePreserve = List(block.Body, "Preserve"); var replaceRequirements = ParseRequirements(List(block.Body, "Require"), diagnostics);
+ operationClock.Stop(); opConstruction += operationClock.Elapsed;
+ if (replaceEnvelope is null || patchName is null || !patches.TryGetValue(patchName, out var patch))
+ {
+ if (patchName is null || !patches.ContainsKey(patchName ?? string.Empty)) diagnostics.Add(new("surf-patch-unresolved", $"ReplaceRegion in '{block.Name}' must reference a declared SurfacePatch."));
+ continue;
+ }
+ var replaceContracts = replacePreserve.Select(Preservation).ToArray();
+ var replaceOperation = new ReplaceRegionOperation(block.Name + ".ReplaceRegion", replaceTarget, patch, replaceMayModify,
+ new(replaceEnvelope[0], replaceEnvelope[1], replaceEnvelope[2], replaceEnvelope[3], replaceEnvelope[4], replaceEnvelope[5]), replaceContracts, replaceRequirements);
+ var replaceApplyClock = Stopwatch.StartNew(); var replaceResult = ReplaceRegionSculptor.Apply(input, block.Name, replaceOperation); replaceApplyClock.Stop(); verification += replaceApplyClock.Elapsed;
+ if (!replaceResult.IsSuccess || replaceResult.OutputState is null) diagnostics.AddRange(replaceResult.Diagnostics);
+ else if (!states.TryAdd(block.Name, replaceResult.OutputState)) diagnostics.Add(new("sculpt-state-duplicate", $"State '{block.Name}' is declared more than once."));
+ continue;
+ }
+ var target = ScalarText(operationBlock!.Body, "Target") ?? string.Empty;
var offset = Length(operationBlock.Body, "Offset", diagnostics);
var region = Vector(operationBlock.Body, "Region", 2, diagnostics);
var envelope = Vector(operationBlock.Body, "InfluenceEnvelope", 6, diagnostics);
@@ -44,10 +103,8 @@ public static class SculptingAuthoring
var boundary = ScalarText(operationBlock.Body, "Boundary") ?? "G0";
operationClock.Stop(); opConstruction += operationClock.Elapsed;
if (offset is null || region is null || envelope is null) continue;
- var contracts = preserve.Select(x => new PreservationContract(x, x == SculptedHousingFactory.MountingHolePattern ? PreservationMode.PatternPlacementAndDiameter : PreservationMode.ExactGeometry)).ToArray();
- var parsedRequirements = new List<SculptRequirement>();
- foreach (var requirement in requirements)
- if (Enum.TryParse<SculptRequirement>(requirement, out var parsed)) parsedRequirements.Add(parsed); else diagnostics.Add(new("sculpt-requirement-unsupported", $"Requirement '{requirement}' is not supported by SURF-X0."));
+ var contracts = preserve.Select(Preservation).ToArray();
+ var parsedRequirements = ParseRequirements(requirements, diagnostics);
var operation = new OffsetRegionOperation(block.Name + ".OffsetRegion", target, offset.Value, region[0], region[1], mayModify,
new(envelope[0], envelope[1], envelope[2], envelope[3], envelope[4], envelope[5]), contracts, parsedRequirements, boundary);
var applyClock = Stopwatch.StartNew(); var result = OffsetRegionSculptor.Apply(input, block.Name, operation); applyClock.Stop(); verification += applyClock.Elapsed;
@@ -108,5 +165,64 @@ public static class SculptingAuthoring
var m = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(field)}\s*:\s*\[(?<v>[^\]]*)\]\s*$", RegexOptions.CultureInvariant);
return m.Success ? m.Groups["v"].Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) : [];
}
+ private static PreservationContract Preservation(string entity) => new(entity, entity == SculptedHousingFactory.MountingHolePattern ? PreservationMode.PatternPlacementAndDiameter : PreservationMode.ExactGeometry);
+ private static IReadOnlyList<SculptRequirement> ParseRequirements(IReadOnlyList<string> values, List<SculptDiagnostic> diagnostics)
+ {
+ var parsed = new List<SculptRequirement>();
+ foreach (var value in values)
+ if (Enum.TryParse<SculptRequirement>(value, out var requirement)) parsed.Add(requirement); else diagnostics.Add(new("sculpt-requirement-unsupported", $"Requirement '{value}' is not supported."));
+ return parsed;
+ }
+ private static double[]? NumberVector(string body, string field, int count, List<SculptDiagnostic> diagnostics)
+ {
+ var values = NumberVectorAny(body, field, diagnostics); if (values is not null && values.Length == count) return values;
+ if (values is not null) diagnostics.Add(new("sculpt-field-invalid", $"Field '{field}' requires {count} dimensionless numbers.")); return null;
+ }
+ private static double[]? NumberVectorAny(string body, string field, List<SculptDiagnostic> diagnostics)
+ {
+ var match = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(field)}\s*:\s*\[(?<v>[^\]]+)\]\s*$", RegexOptions.CultureInvariant);
+ if (!match.Success) { diagnostics.Add(new("sculpt-field-invalid", $"Field '{field}' requires a dimensionless number list.")); return null; }
+ var tokens = match.Groups["v"].Value.Split(',', StringSplitOptions.TrimEntries); var values = new double[tokens.Length];
+ for (var i = 0; i < tokens.Length; i++) if (!double.TryParse(tokens[i], NumberStyles.Float, CultureInfo.InvariantCulture, out values[i]))
+ { diagnostics.Add(new("sculpt-field-invalid", $"Field '{field}' contains invalid number '{tokens[i]}'.")); return null; }
+ return values;
+ }
+ private static IReadOnlyList<IReadOnlyList<Point3D>>? ControlRows(string body, List<SculptDiagnostic> diagnostics)
+ {
+ var matches = Regex.Matches(body, @"(?m)^\s*ControlRow\s*:\s*\[(?<v>.*)\]\s*$", RegexOptions.CultureInvariant);
+ var rows = new List<IReadOnlyList<Point3D>>();
+ foreach (Match match in matches)
+ {
+ var points = new List<Point3D>();
+ foreach (Match point in Regex.Matches(match.Groups["v"].Value, @"\[\s*(?<x>[-+]?\d+(?:\.\d+)?)mm\s*,\s*(?<y>[-+]?\d+(?:\.\d+)?)mm\s*,\s*(?<z>[-+]?\d+(?:\.\d+)?)mm\s*\]", RegexOptions.CultureInvariant))
+ points.Add(new(double.Parse(point.Groups["x"].Value, CultureInfo.InvariantCulture), double.Parse(point.Groups["y"].Value, CultureInfo.InvariantCulture), double.Parse(point.Groups["z"].Value, CultureInfo.InvariantCulture)));
+ if (points.Count == 0) { diagnostics.Add(new("surf-control-row-invalid", "Each ControlRow requires one or more [xmm, ymm, zmm] points.")); return null; }
+ rows.Add(points);
+ }
+ if (rows.Count == 0) { diagnostics.Add(new("surf-control-net-required", "A non-rational SurfacePatch requires explicit ControlRow entries.")); return null; }
+ return rows;
+ }
+ private static IReadOnlyList<PatchBoundaryCorrespondence>? ParseBoundaries(string body, List<SculptDiagnostic> diagnostics)
+ {
+ var result = new List<PatchBoundaryCorrespondence>();
+ foreach (var block in Blocks(body, "Boundary"))
+ {
+ if (!Enum.TryParse<PatchBoundarySide>(block.Name, true, out var side)) { diagnostics.Add(new("surf-boundary-side-invalid", $"Unknown patch boundary side '{block.Name}'.")); continue; }
+ var existing = ScalarText(block.Body, "Existing") ?? string.Empty; var continuityText = ScalarText(block.Body, "Continuity") ?? "G0";
+ if (!Enum.TryParse<PatchBoundaryContinuity>(continuityText, true, out var continuity)) { diagnostics.Add(new("surf-boundary-continuity-invalid", $"Boundary '{block.Name}' continuity must be G0 or G1.")); continue; }
+ result.Add(new($"Boundary{block.Name}", side, existing, continuity));
+ }
+ return result;
+ }
+ private static (IReadOnlyList<int> Multiplicities, IReadOnlyList<double> Values) CompressKnots(IReadOnlyList<double> expanded)
+ {
+ var multiplicities = new List<int>(); var values = new List<double>();
+ foreach (var knot in expanded)
+ {
+ if (values.Count > 0 && knot == values[^1]) multiplicities[^1]++;
+ else { values.Add(knot); multiplicities.Add(1); }
+ }
+ return (multiplicities, values);
+ }
private sealed record Block(string Name, string Body);
}
diff --git a/Aetheris.Surfacing/SculptingExecution.cs b/Aetheris.Surfacing/SculptingExecution.cs
index 97b886d8..24729d1d 100644
--- a/Aetheris.Surfacing/SculptingExecution.cs
+++ b/Aetheris.Surfacing/SculptingExecution.cs
@@ -16,6 +16,11 @@ public static class SculptedHousingFactory
public const string BottomMountingInterface = "BottomMountingInterface";
public const string MountingHolePattern = "MountingHolePattern";
public const string OuterFootprintBoundary = "OuterFootprintBoundary";
+ public const string SideWallsLower = "SideWallsLower";
+ public const string CrownBoundarySouth = "CrownBoundarySouth";
+ public const string CrownBoundaryEast = "CrownBoundaryEast";
+ public const string CrownBoundaryNorth = "CrownBoundaryNorth";
+ public const string CrownBoundaryWest = "CrownBoundaryWest";
public static SculptResult CreateBase(string stateName, double width, double depth, double height, IReadOnlyList<HousingHole> holes)
{
@@ -32,14 +37,23 @@ public static class SculptedHousingFactory
}
internal static IReadOnlyDictionary<string, SculptSemanticEntity> Inventory(HousingConstruction c)
- => new Dictionary<string, SculptSemanticEntity>(StringComparer.Ordinal)
+ {
+ var inventory = new Dictionary<string, SculptSemanticEntity>(StringComparer.Ordinal)
{
[CrownRegion] = new(CrownRegion, SculptEntityKind.Region, $"rect:{c.CrownWidth:R}x{c.CrownDepth:R}@z={c.FinalHeight:R}", "Bounded top/crown support."),
[TransitionZone] = new(TransitionZone, SculptEntityKind.Region, $"transition:z={c.BaseHeight:R}..{c.FinalHeight:R}", "G0 crown reconnection zone."),
[BottomMountingInterface] = new(BottomMountingInterface, SculptEntityKind.Interface, $"plane:z=0;rect={c.Width:R}x{c.Depth:R};holes={HolePattern(c.Holes)}", "Protected planar mounting interface."),
[MountingHolePattern] = new(MountingHolePattern, SculptEntityKind.Pattern, HolePattern(c.Holes), "Protected mounting-hole axes, centers, and diameters."),
[OuterFootprintBoundary] = new(OuterFootprintBoundary, SculptEntityKind.Region, $"rect:{c.Width:R}x{c.Depth:R}@z=0", "Protected lower outer footprint boundary."),
+ [SideWallsLower] = new(SideWallsLower, SculptEntityKind.Region, $"vertical:rect={c.Width:R}x{c.Depth:R};z=0..{c.BaseHeight:R}", "Protected lower side-wall region."),
+ [CrownBoundarySouth] = new(CrownBoundarySouth, SculptEntityKind.Region, $"south:{c.CrownWidth:R}@y={-c.CrownDepth / 2d:R};z={c.BaseHeight:R}", "South replacement boundary."),
+ [CrownBoundaryEast] = new(CrownBoundaryEast, SculptEntityKind.Region, $"east:{c.CrownDepth:R}@x={c.CrownWidth / 2d:R};z={c.BaseHeight:R}", "East replacement boundary."),
+ [CrownBoundaryNorth] = new(CrownBoundaryNorth, SculptEntityKind.Region, $"north:{c.CrownWidth:R}@y={c.CrownDepth / 2d:R};z={c.BaseHeight:R}", "North replacement boundary."),
+ [CrownBoundaryWest] = new(CrownBoundaryWest, SculptEntityKind.Region, $"west:{c.CrownDepth:R}@x={-c.CrownWidth / 2d:R};z={c.BaseHeight:R}", "West replacement boundary."),
};
+ foreach (var hole in c.Holes) inventory[hole.StableId] = new(hole.StableId, SculptEntityKind.Region, HoleFingerprint(hole), "Stable mounting-hole feature.");
+ return inventory;
+ }
internal static IReadOnlyList<SculptValidationEvidence> ValidateBody(BrepBody body, double localityTolerance)
{
@@ -123,6 +137,190 @@ public static class OffsetRegionSculptor
}
}
+public static class ReplaceRegionSculptor
+{
+ public static SculptResult Apply(BodyState input, string outputName, ReplaceRegionOperation operation)
+ {
+ ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);
+ var diagnostics = operation.ReplacementPatch.Validate().ToList();
+ var evidence = new List<SculptValidationEvidence>();
+ if (!input.SemanticInventory.ContainsKey(operation.TargetRegion))
+ {
+ var replacement = input.Delta?.Correspondence.FirstOrDefault(x => x.InputEntity == operation.TargetRegion && x.Change == GeometricChangeKind.Replaced);
+ diagnostics.Add(replacement is null
+ ? new("sculpt-target-unresolved", $"Target region '{operation.TargetRegion}' does not exist in the input state.", operation.TargetRegion)
+ : new("surf-selector-target-replaced", $"'{operation.TargetRegion}' was replaced in {input.StateId.Value} by {string.Join(", ", replacement.OutputEntities)}; select a current-state entity.", operation.TargetRegion));
+ }
+ if (!operation.MayModify.Contains(operation.TargetRegion, StringComparer.Ordinal))
+ diagnostics.Add(new("sculpt-target-not-authorized", "ReplaceRegion target is not present in MayModify.", operation.TargetRegion));
+ foreach (var contract in operation.Preserves)
+ {
+ if (!input.SemanticInventory.ContainsKey(contract.EntityId)) diagnostics.Add(new("sculpt-preserve-unresolved", $"Preserved entity '{contract.EntityId}' does not exist.", contract.EntityId));
+ if (operation.MayModify.Contains(contract.EntityId, StringComparer.Ordinal)) diagnostics.Add(new("sculpt-breaks-preserved-interface", $"'{contract.EntityId}' cannot be both modified and preserved.", contract.EntityId));
+ }
+ var expected = new Dictionary<PatchBoundarySide, string>
+ {
+ [PatchBoundarySide.South] = SculptedHousingFactory.CrownBoundarySouth,
+ [PatchBoundarySide.East] = SculptedHousingFactory.CrownBoundaryEast,
+ [PatchBoundarySide.North] = SculptedHousingFactory.CrownBoundaryNorth,
+ [PatchBoundarySide.West] = SculptedHousingFactory.CrownBoundaryWest,
+ };
+ foreach (var boundary in operation.ReplacementPatch.BoundaryLoop.Boundaries)
+ if (!string.Equals(boundary.ExistingBoundary, expected[boundary.PatchSide], StringComparison.Ordinal))
+ diagnostics.Add(new("surf-boundary-correspondence-invalid", $"{boundary.PatchSide} must correspond to '{expected[boundary.PatchSide]}', not '{boundary.ExistingBoundary}'.", boundary.StableId));
+ if (diagnostics.Count > 0) return SculptResult.Failure(diagnostics, evidence);
+
+ var domain = operation.ReplacementPatch.ParameterDomain;
+ var corners = new[]
+ {
+ operation.ReplacementPatch.Evaluate(domain.UMin, domain.VMin), operation.ReplacementPatch.Evaluate(domain.UMax, domain.VMin),
+ operation.ReplacementPatch.Evaluate(domain.UMax, domain.VMax), operation.ReplacementPatch.Evaluate(domain.UMin, domain.VMax),
+ };
+ var width = Math.Abs(corners[1].X - corners[0].X); var depth = Math.Abs(corners[3].Y - corners[0].Y);
+ var rectangular = width > operation.GeometricTolerance && depth > operation.GeometricTolerance
+ && corners.All(x => Math.Abs(x.Z - input.Construction.BaseHeight) <= operation.GeometricTolerance)
+ && Math.Abs(corners[0].Y - corners[1].Y) <= operation.GeometricTolerance
+ && Math.Abs(corners[1].X - corners[2].X) <= operation.GeometricTolerance
+ && Math.Abs(corners[2].Y - corners[3].Y) <= operation.GeometricTolerance
+ && Math.Abs(corners[3].X - corners[0].X) <= operation.GeometricTolerance;
+ if (!rectangular) diagnostics.Add(new("surf-boundary-mismatch", "Patch corners must form the declared axis-aligned rectangular boundary on the existing crown plane."));
+ if (width > input.Construction.Width || depth > input.Construction.Depth) diagnostics.Add(new("surf-patch-outside-target", "Replacement patch boundary exceeds the housing top region."));
+
+ var sampled = Sample(operation.ReplacementPatch, 17);
+ var maximumZ = sampled.Max(x => x.Z);
+ var envelopePoints = operation.ReplacementPatch is BSplineSurfacePatch splinePatch
+ ? sampled.Concat(splinePatch.Spline.ControlPoints.SelectMany(x => x)).ToArray() : sampled.ToArray();
+ var actual = new SpatialInfluenceEnvelope(envelopePoints.Min(x => x.X), envelopePoints.Min(x => x.Y), Math.Min(input.Construction.BaseHeight, envelopePoints.Min(x => x.Z)),
+ envelopePoints.Max(x => x.X), envelopePoints.Max(x => x.Y), Math.Max(input.Construction.BaseHeight, envelopePoints.Max(x => x.Z)));
+ if (!operation.InfluenceEnvelope.Contains(actual, operation.GeometricTolerance)) diagnostics.Add(new("sculpt-outside-authorized-region", "The declared influence envelope does not contain the replacement patch."));
+ if (actual.MinZ < input.Construction.BaseHeight - operation.GeometricTolerance) diagnostics.Add(new("surf-patch-self-intersection", "The replacement patch enters the preserved housing volume below the original crown plane."));
+
+ foreach (var boundary in operation.ReplacementPatch.BoundaryLoop.Boundaries.OrderBy(x => x.PatchSide))
+ {
+ var (g0, angle) = MeasureBoundary(operation.ReplacementPatch, boundary.PatchSide, input.Construction.BaseHeight, 33);
+ var g0Ok = g0 <= operation.GeometricTolerance;
+ evidence.Add(new($"Boundary:{boundary.StableId}:G0", g0Ok, LocalityEvidenceLevel.CertifiedBounded, g0, operation.GeometricTolerance, $"Maximum sampled positional error over 33 deterministic parameters is {g0:R} mm."));
+ if (!g0Ok) diagnostics.Add(new("surf-boundary-g0-violation", $"Boundary '{boundary.StableId}' has G0 error {g0:R} mm, exceeding {operation.GeometricTolerance:R} mm.", boundary.StableId));
+ if (boundary.Continuity == PatchBoundaryContinuity.G1)
+ {
+ var g1Ok = angle <= operation.G1AngularToleranceDegrees;
+ evidence.Add(new($"Boundary:{boundary.StableId}:G1", g1Ok, LocalityEvidenceLevel.CertifiedBounded, angle, operation.G1AngularToleranceDegrees, $"Maximum sampled tangent-plane angular error over 33 deterministic parameters is {angle:R} degrees."));
+ if (!g1Ok) diagnostics.Add(new("surf-boundary-g1-violation", $"Boundary '{boundary.StableId}' has tangent-plane error {angle:R} degrees, exceeding {operation.G1AngularToleranceDegrees:R} degrees.", boundary.StableId));
+ }
+ }
+ if (diagnostics.Count > 0) return SculptResult.Failure(diagnostics, evidence);
+
+ var construction = input.Construction with { CrownWidth = width, CrownDepth = depth, CrownOffset = maximumZ - input.Construction.BaseHeight, ReplacementPatch = operation.ReplacementPatch };
+ var built = SculptedHousingBrepBuilder.Build(construction);
+ if (built.Body is null) return SculptResult.Failure(built.Diagnostics, evidence);
+ var inventory = SculptedHousingFactory.Inventory(construction).ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal);
+ inventory.Remove(SculptedHousingFactory.CrownRegion);
+ inventory[operation.ReplacementPatch.PatchId] = new(operation.ReplacementPatch.PatchId, SculptEntityKind.Surface,
+ $"{operation.ReplacementPatch.ExportClass}:{operation.ReplacementPatch.DegreeU}x{operation.ReplacementPatch.DegreeV}:{operation.ReplacementPatch.ControlCountU}x{operation.ReplacementPatch.ControlCountV}", "Accepted bounded replacement patch.");
+ foreach (var contract in operation.Preserves)
+ {
+ var before = input.SemanticInventory[contract.EntityId]; var after = inventory[contract.EntityId];
+ var satisfied = before.StableId == after.StableId && before.GeometryFingerprint == after.GeometryFingerprint;
+ evidence.Add(new($"Preserve:{contract.EntityId}", satisfied, LocalityEvidenceLevel.ExactSemantic, satisfied ? 0d : null, operation.GeometricTolerance,
+ satisfied ? $"Stable identity and {contract.Mode} fingerprint are identical." : "Protected identity or geometry fingerprint changed."));
+ if (!satisfied) diagnostics.Add(new("sculpt-preservation-failed", $"Preservation contract failed for '{contract.EntityId}'.", contract.EntityId));
+ }
+ var locality = SculptLocalityVerifier.CompareOutsideTopEnvelope(input.Body, built.Body, input.Construction.BaseHeight, operation.GeometricTolerance);
+ evidence.Add(locality); if (!locality.Satisfied) diagnostics.Add(new("sculpt-outside-authorized-region", locality.Detail));
+ evidence.AddRange(SculptedHousingFactory.ValidateBody(built.Body, operation.GeometricTolerance));
+ var shared = VerifySharedBoundaryTopology(built.Body);
+ evidence.Add(shared); if (!shared.Satisfied) diagnostics.Add(new("surf-boundary-not-shared", shared.Detail));
+ foreach (var requirement in operation.Requirements)
+ if (!evidence.Any(x => x.Check == requirement.ToString() && x.Satisfied)) diagnostics.Add(new("sculpt-postcondition-failed", $"Required postcondition '{requirement}' was not proven."));
+ if (diagnostics.Count > 0 || evidence.Any(x => !x.Satisfied)) return SculptResult.Failure(diagnostics, evidence);
+
+ var outputId = BodyStateId.Derive($"{input.StateId.Value}|ReplaceRegion|{operation.Canonical}");
+ var correspondence = operation.Preserves.Select(x => new GeometricDeltaEntry(x.EntityId, GeometricChangeKind.Preserved, [x.EntityId], "Exact semantic identity and geometry fingerprint."))
+ .Append(new(SculptedHousingFactory.CrownRegion, GeometricChangeKind.Replaced, [operation.ReplacementPatch.PatchId], "Explicit outer-loop boundary correspondence; G0/G1 contracts verified."))
+ .Concat(operation.ReplacementPatch.BoundaryLoop.Boundaries.Select(x => new GeometricDeltaEntry(x.ExistingBoundary, GeometricChangeKind.Preserved, [x.StableId], $"Shared edge correspondence with {x.Continuity}."))).ToArray();
+ var delta = new GeometricDelta(input.StateId, outputId, [operation.TargetRegion, .. operation.Preserves.Select(x => x.EntityId)], operation.Preserves.Select(x => x.EntityId).ToArray(),
+ [operation.TargetRegion], [], [operation.ReplacementPatch.PatchId], operation.MayModify, operation.InfluenceEnvelope, correspondence);
+ return new(true, new(outputId, input.StateId, input.BodyStableId, outputName, built.Body, construction, inventory, delta, evidence), delta, evidence, []);
+ }
+
+ private static IReadOnlyList<Point3D> Sample(BoundedSurfacePatch patch, int count)
+ {
+ var result = new List<Point3D>(count * count); var d = patch.ParameterDomain;
+ for (var i = 0; i < count; i++) for (var j = 0; j < count; j++)
+ result.Add(patch.Evaluate(d.UMin + (d.UMax - d.UMin) * i / (count - 1d), d.VMin + (d.VMax - d.VMin) * j / (count - 1d)));
+ return result;
+ }
+
+ private static (double G0, double G1Degrees) MeasureBoundary(BoundedSurfacePatch patch, PatchBoundarySide side, double planeZ, int count)
+ {
+ var domain = patch.ParameterDomain; var g0 = 0d; var g1 = 0d;
+ var corners = new[] { patch.Evaluate(domain.UMin, domain.VMin), patch.Evaluate(domain.UMax, domain.VMin), patch.Evaluate(domain.UMax, domain.VMax), patch.Evaluate(domain.UMin, domain.VMax) };
+ var du = (domain.UMax - domain.UMin) * 1e-5; var dv = (domain.VMax - domain.VMin) * 1e-5;
+ for (var i = 0; i < count; i++)
+ {
+ var t = i / (count - 1d); var u = domain.UMin + (domain.UMax - domain.UMin) * t; var v = domain.VMin + (domain.VMax - domain.VMin) * t;
+ (u, v) = side switch { PatchBoundarySide.South => (u, domain.VMin), PatchBoundarySide.East => (domain.UMax, v), PatchBoundarySide.North => (u, domain.VMax), _ => (domain.UMin, v) };
+ var p = patch.Evaluate(u, v);
+ var (a, b) = side switch { PatchBoundarySide.South => (corners[0], corners[1]), PatchBoundarySide.East => (corners[1], corners[2]), PatchBoundarySide.North => (corners[3], corners[2]), _ => (corners[0], corners[3]) };
+ a = new(a.X, a.Y, planeZ); b = new(b.X, b.Y, planeZ);
+ var segment = b - a; var parameter = Math.Clamp((p - a).Dot(segment) / segment.Dot(segment), 0d, 1d); var closest = a + segment * parameter;
+ g0 = Math.Max(g0, (p - closest).Length);
+ var ua = Math.Max(domain.UMin, u - du); var ub = Math.Min(domain.UMax, u + du); var va = Math.Max(domain.VMin, v - dv); var vb = Math.Min(domain.VMax, v + dv);
+ var tu = patch.Evaluate(ub, v) - patch.Evaluate(ua, v); var tv = patch.Evaluate(u, vb) - patch.Evaluate(u, va);
+ var normal = tu.Cross(tv); if (normal.Length <= 1e-14) { g1 = 180d; continue; }
+ var cosine = Math.Clamp(Math.Abs(normal.Z) / normal.Length, 0d, 1d); g1 = Math.Max(g1, Math.Acos(cosine) * 180d / Math.PI);
+ }
+ return (g0, g1);
+ }
+
+ private static SculptValidationEvidence VerifySharedBoundaryTopology(BrepBody body)
+ {
+ var counts = body.Topology.Coedges.GroupBy(x => x.EdgeId).ToDictionary(x => x.Key, x => x.Count());
+ var invalid = counts.Where(x => x.Value != 2).ToArray();
+ return new("SharedBoundaryTopology", invalid.Length == 0, LocalityEvidenceLevel.CertifiedBounded, invalid.Length, 0d,
+ invalid.Length == 0 ? "Every replacement, trim, and preserved-neighbor edge has exactly two coedge uses; vertices are shared topology objects." : $"{invalid.Length} edges do not have exactly two coedge uses.");
+ }
+}
+
+public static class SafeHoleSculptor
+{
+ public static SculptResult Apply(BodyState input, string outputName, SafeHoleOperation operation)
+ {
+ var diagnostics = new List<SculptDiagnostic>(); var evidence = new List<SculptValidationEvidence>();
+ if (!input.SemanticInventory.ContainsKey(operation.TargetRegion))
+ diagnostics.Add(new("sculpt-target-unresolved", $"Hole target '{operation.TargetRegion}' does not exist in the current BodyState.", operation.TargetRegion));
+ if (input.SemanticInventory.ContainsKey(operation.Hole.StableId)) diagnostics.Add(new("sculpt-hole-duplicate", $"Hole '{operation.Hole.StableId}' already exists.", operation.Hole.StableId));
+ foreach (var contract in operation.Preserves) if (!input.SemanticInventory.ContainsKey(contract.EntityId)) diagnostics.Add(new("sculpt-preserve-unresolved", $"Preserved entity '{contract.EntityId}' does not exist in the current BodyState.", contract.EntityId));
+ var radius = operation.Hole.Diameter / 2d;
+ var actual = new SpatialInfluenceEnvelope(operation.Hole.CenterX - radius, operation.Hole.CenterY - radius, 0d, operation.Hole.CenterX + radius, operation.Hole.CenterY + radius, input.Construction.BaseHeight);
+ if (!operation.InfluenceEnvelope.Contains(actual, 1e-6)) diagnostics.Add(new("sculpt-outside-authorized-region", "HoleFeature influence envelope does not contain the full through-hole cylinder."));
+ if (diagnostics.Count > 0) return SculptResult.Failure(diagnostics);
+
+ var construction = input.Construction with { Holes = [.. input.Construction.Holes, operation.Hole] };
+ var built = SculptedHousingBrepBuilder.Build(construction);
+ if (built.Body is null) return SculptResult.Failure(built.Diagnostics);
+ var inventory = SculptedHousingFactory.Inventory(construction).ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal);
+ if (construction.ReplacementPatch is { } patch)
+ {
+ inventory.Remove(SculptedHousingFactory.CrownRegion);
+ inventory[patch.PatchId] = new(patch.PatchId, SculptEntityKind.Surface, $"{patch.ExportClass}:{patch.DegreeU}x{patch.DegreeV}:{patch.ControlCountU}x{patch.ControlCountV}", "Accepted bounded replacement patch.");
+ }
+ foreach (var contract in operation.Preserves)
+ {
+ var before = input.SemanticInventory[contract.EntityId]; var after = inventory[contract.EntityId]; var satisfied = before.GeometryFingerprint == after.GeometryFingerprint;
+ evidence.Add(new($"Preserve:{contract.EntityId}", satisfied, LocalityEvidenceLevel.ExactSemantic, satisfied ? 0d : null, 1e-6, satisfied ? "Current-state semantic identity and geometry fingerprint are unchanged." : "Preserved geometry changed."));
+ if (!satisfied) diagnostics.Add(new("sculpt-preservation-failed", $"Preservation contract failed for '{contract.EntityId}'.", contract.EntityId));
+ }
+ evidence.AddRange(SculptedHousingFactory.ValidateBody(built.Body, 1e-6));
+ if (diagnostics.Count > 0 || evidence.Any(x => !x.Satisfied)) return SculptResult.Failure(diagnostics, evidence);
+ var outputId = BodyStateId.Derive($"{input.StateId.Value}|HoleFeature|{operation.Canonical}");
+ var correspondence = operation.Preserves.Select(x => new GeometricDeltaEntry(x.EntityId, GeometricChangeKind.Preserved, [x.EntityId], "Resolved and verified against the current BodyState."))
+ .Append(new("<none>", GeometricChangeKind.Introduced, [operation.Hole.StableId], "Exact cylindrical through-hole on the current planar frame.")).ToArray();
+ var delta = new GeometricDelta(input.StateId, outputId, [operation.TargetRegion], operation.Preserves.Select(x => x.EntityId).ToArray(), [], [], [operation.Hole.StableId], [operation.TargetRegion], operation.InfluenceEnvelope, correspondence);
+ return new(true, new(outputId, input.StateId, input.BodyStableId, outputName, built.Body, construction, inventory, delta, evidence), delta, evidence, []);
+ }
+}
+
internal static class SculptLocalityVerifier
{
public static SculptValidationEvidence CompareOutsideTopEnvelope(BrepBody input, BrepBody output, double boundaryZ, double tolerance)
diff --git a/Aetheris.Surfacing/SculptingState.cs b/Aetheris.Surfacing/SculptingState.cs
index f51e269d..d880bb0d 100644
--- a/Aetheris.Surfacing/SculptingState.cs
+++ b/Aetheris.Surfacing/SculptingState.cs
@@ -56,7 +56,8 @@ public sealed record HousingConstruction(
double CrownWidth,
double CrownDepth,
double CrownOffset,
- IReadOnlyList<HousingHole> Holes)
+ IReadOnlyList<HousingHole> Holes,
+ BoundedSurfacePatch? ReplacementPatch = null)
{
public double FinalHeight => BaseHeight + CrownOffset;
public bool HasCrown => CrownOffset > 0d && (CrownWidth < Width || CrownDepth < Depth);
@@ -71,7 +72,11 @@ public sealed record BodyState(
HousingConstruction Construction,
IReadOnlyDictionary<string, SculptSemanticEntity> SemanticInventory,
GeometricDelta? Delta,
- IReadOnlyList<SculptValidationEvidence> ValidationEvidence);
+ IReadOnlyList<SculptValidationEvidence> ValidationEvidence)
+{
+ public IReadOnlyList<SurfacePatchMetadata> SurfacePatches => Construction.ReplacementPatch is { } patch
+ ? [SurfacePatchMetadata.From(patch)] : [];
+}
public sealed record OffsetRegionOperation(
string StableId,
@@ -92,6 +97,39 @@ public sealed record OffsetRegionOperation(
string.Join(',', Requirements.Order()), BoundaryContinuity);
}
+public sealed record ReplaceRegionOperation(
+ string StableId,
+ string TargetRegion,
+ BoundedSurfacePatch ReplacementPatch,
+ IReadOnlyList<string> MayModify,
+ SpatialInfluenceEnvelope InfluenceEnvelope,
+ IReadOnlyList<PreservationContract> Preserves,
+ IReadOnlyList<SculptRequirement> Requirements,
+ double GeometricTolerance = 1e-6,
+ double G1AngularToleranceDegrees = 0.1)
+{
+ public string Canonical => string.Join('|', StableId, TargetRegion, ReplacementPatch.PatchId,
+ ReplacementPatch.SurfaceClass, ReplacementPatch.DegreeU, ReplacementPatch.DegreeV,
+ ReplacementPatch.ControlCountU, ReplacementPatch.ControlCountV,
+ $"{ReplacementPatch.ParameterDomain.UMin:R},{ReplacementPatch.ParameterDomain.UMax:R},{ReplacementPatch.ParameterDomain.VMin:R},{ReplacementPatch.ParameterDomain.VMax:R}",
+ string.Join(';', ReplacementPatch.BoundaryLoop.Boundaries.OrderBy(x => x.PatchSide).Select(x => $"{x.PatchSide}:{x.ExistingBoundary}:{x.Continuity}")),
+ string.Join(',', MayModify.Order(StringComparer.Ordinal)),
+ $"{InfluenceEnvelope.MinX:R},{InfluenceEnvelope.MinY:R},{InfluenceEnvelope.MinZ:R},{InfluenceEnvelope.MaxX:R},{InfluenceEnvelope.MaxY:R},{InfluenceEnvelope.MaxZ:R}",
+ string.Join(',', Preserves.OrderBy(x => x.EntityId, StringComparer.Ordinal).Select(x => $"{x.EntityId}:{x.Mode}")),
+ string.Join(',', Requirements.Order()), GeometricTolerance.ToString("R"), G1AngularToleranceDegrees.ToString("R"));
+}
+
+public sealed record SafeHoleOperation(
+ string StableId,
+ string TargetRegion,
+ HousingHole Hole,
+ SpatialInfluenceEnvelope InfluenceEnvelope,
+ IReadOnlyList<PreservationContract> Preserves,
+ IReadOnlyList<SculptRequirement> Requirements)
+{
+ public string Canonical => $"{StableId}|{TargetRegion}|{Hole.StableId}|{Hole.CenterX:R}|{Hole.CenterY:R}|{Hole.Diameter:R}|{InfluenceEnvelope.MinX:R},{InfluenceEnvelope.MinY:R},{InfluenceEnvelope.MinZ:R},{InfluenceEnvelope.MaxX:R},{InfluenceEnvelope.MaxY:R},{InfluenceEnvelope.MaxZ:R}";
+}
+
public sealed record SculptDiagnostic(string Code, string Message, string? Entity = null);
public sealed record SculptResult(bool IsSuccess, BodyState? OutputState, GeometricDelta? Delta, IReadOnlyList<SculptValidationEvidence> Evidence, IReadOnlyList<SculptDiagnostic> Diagnostics)
{
diff --git a/Aetheris.Surfacing/SurfacePatchIr.cs b/Aetheris.Surfacing/SurfacePatchIr.cs
new file mode 100644
index 00000000..f7fefd54
--- /dev/null
+++ b/Aetheris.Surfacing/SurfacePatchIr.cs
@@ -0,0 +1,149 @@
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Surfacing;
+
+public readonly record struct SurfaceParameterDomain(double UMin, double UMax, double VMin, double VMax)
+{
+ public bool IsValid => double.IsFinite(UMin) && double.IsFinite(UMax) && double.IsFinite(VMin) && double.IsFinite(VMax)
+ && UMin < UMax && VMin < VMax;
+}
+
+public enum SurfacePatchClass { Analytic, NonRationalBSpline, InternalRationalNormalized }
+public enum PatchBoundarySide { South, East, North, West }
+public enum PatchBoundaryContinuity { G0, G1 }
+
+public sealed record PatchBoundaryCorrespondence(
+ string StableId,
+ PatchBoundarySide PatchSide,
+ string ExistingBoundary,
+ PatchBoundaryContinuity Continuity);
+
+public sealed record SurfaceBoundaryLoop(
+ string StableId,
+ IReadOnlyList<PatchBoundaryCorrespondence> Boundaries,
+ bool IsOuter = true)
+{
+ public IReadOnlyList<SculptDiagnostic> Validate()
+ {
+ var diagnostics = new List<SculptDiagnostic>();
+ if (!IsOuter) diagnostics.Add(new("surf-boundary-inner-loop-unsupported", "SURF-X1 currently supports one outer replacement loop and no holes in the replacement patch."));
+ if (Boundaries.Count != 4 || Boundaries.Select(x => x.PatchSide).Distinct().Count() != 4)
+ diagnostics.Add(new("surf-boundary-loop-invalid", "A rectangular replacement loop requires exactly one correspondence for South, East, North, and West."));
+ if (Boundaries.Any(x => string.IsNullOrWhiteSpace(x.ExistingBoundary)))
+ diagnostics.Add(new("surf-boundary-correspondence-invalid", "Every patch boundary must identify the existing body boundary it replaces."));
+ return diagnostics;
+ }
+}
+
+public abstract record BoundedSurfacePatch(
+ string PatchId,
+ SurfacePatchClass SurfaceClass,
+ SurfaceParameterDomain ParameterDomain,
+ SurfaceBoundaryLoop BoundaryLoop,
+ bool ReversedOrientation)
+{
+ public abstract SurfaceGeometry Support { get; }
+ public abstract Point3D Evaluate(double u, double v);
+ public abstract int? DegreeU { get; }
+ public abstract int? DegreeV { get; }
+ public abstract int? ControlCountU { get; }
+ public abstract int? ControlCountV { get; }
+ public abstract string ExportClass { get; }
+ public abstract IReadOnlyList<SculptDiagnostic> Validate();
+}
+
+public sealed record AnalyticSurfacePatch(
+ string Id,
+ SurfaceGeometry AnalyticSupport,
+ SurfaceParameterDomain Domain,
+ SurfaceBoundaryLoop Loop,
+ Func<double, double, Point3D> Evaluator,
+ bool Reversed = false)
+ : BoundedSurfacePatch(Id, SurfacePatchClass.Analytic, Domain, Loop, Reversed)
+{
+ public override SurfaceGeometry Support => AnalyticSupport;
+ public override Point3D Evaluate(double u, double v) => Evaluator(u, v);
+ public override int? DegreeU => null;
+ public override int? DegreeV => null;
+ public override int? ControlCountU => null;
+ public override int? ControlCountV => null;
+ public override string ExportClass => AnalyticSupport.Kind.ToString();
+ public override IReadOnlyList<SculptDiagnostic> Validate()
+ {
+ var diagnostics = Loop.Validate().ToList();
+ if (!Domain.IsValid) diagnostics.Add(new("surf-patch-domain-invalid", "The analytic patch parameter domain must be finite and non-empty.", PatchId));
+ if (AnalyticSupport.Kind == SurfaceGeometryKind.BSplineSurfaceWithKnots)
+ diagnostics.Add(new("surf-patch-class-invalid", "An analytic patch cannot wrap a B-spline support.", PatchId));
+ return diagnostics;
+ }
+}
+
+public sealed record BSplineSurfacePatch : BoundedSurfacePatch
+{
+ public BSplineSurfacePatch(string patchId, BSplineSurfaceWithKnots spline, SurfaceParameterDomain domain,
+ SurfaceBoundaryLoop boundaryLoop, bool reversedOrientation = false,
+ SurfacePatchClass surfaceClass = SurfacePatchClass.NonRationalBSpline)
+ : base(patchId, surfaceClass, domain, boundaryLoop, reversedOrientation)
+ {
+ Spline = spline ?? throw new ArgumentNullException(nameof(spline));
+ }
+
+ public BSplineSurfaceWithKnots Spline { get; }
+ public override SurfaceGeometry Support => SurfaceGeometry.FromBSplineSurfaceWithKnots(Spline);
+ public override Point3D Evaluate(double u, double v) => Spline.Evaluate(u, v);
+ public override int? DegreeU => Spline.DegreeU;
+ public override int? DegreeV => Spline.DegreeV;
+ public override int? ControlCountU => Spline.ControlPoints.Count;
+ public override int? ControlCountV => Spline.ControlPoints[0].Count;
+ public override string ExportClass => "NonRationalBSpline";
+
+ public override IReadOnlyList<SculptDiagnostic> Validate()
+ {
+ var diagnostics = BoundaryLoop.Validate().ToList();
+ if (!ParameterDomain.IsValid || ParameterDomain.UMin < Spline.DomainStartU || ParameterDomain.UMax > Spline.DomainEndU
+ || ParameterDomain.VMin < Spline.DomainStartV || ParameterDomain.VMax > Spline.DomainEndV)
+ diagnostics.Add(new("surf-patch-domain-invalid", "The bounded patch domain must be finite, non-empty, and contained in the spline knot domain.", PatchId));
+ if (SurfaceClass is not (SurfacePatchClass.NonRationalBSpline or SurfacePatchClass.InternalRationalNormalized))
+ diagnostics.Add(new("surf-patch-class-invalid", "A B-spline patch must be explicitly non-rational or exactly normalized from removable rationality.", PatchId));
+ return diagnostics;
+ }
+}
+
+public sealed record SurfacePatchMetadata(
+ string PatchId,
+ SurfacePatchClass SurfaceClass,
+ int? DegreeU,
+ int? DegreeV,
+ int? ControlCountU,
+ int? ControlCountV,
+ SurfaceParameterDomain ParameterDomain,
+ int BoundaryLoops,
+ IReadOnlyList<PatchBoundaryCorrespondence> ContinuityContracts,
+ string ExportClass)
+{
+ public static SurfacePatchMetadata From(BoundedSurfacePatch patch) => new(
+ patch.PatchId, patch.SurfaceClass, patch.DegreeU, patch.DegreeV, patch.ControlCountU, patch.ControlCountV,
+ patch.ParameterDomain, 1, patch.BoundaryLoop.Boundaries, patch.ExportClass);
+}
+
+public sealed record TrimRegionResult(bool IsSuccess, BoundedSurfacePatch? Patch, IReadOnlyList<SculptDiagnostic> Diagnostics);
+
+public static class SurfacePatchOperations
+{
+ public static TrimRegionResult TrimRegion(BSplineSurfacePatch patch, SurfaceParameterDomain domain)
+ {
+ var trimmed = patch with { ParameterDomain = domain };
+ var diagnostics = trimmed.Validate();
+ return diagnostics.Count == 0 ? new(true, trimmed, []) : new(false, null, diagnostics);
+ }
+
+ public static TrimRegionResult ExtendRegion(BSplineSurfacePatch patch, SurfaceParameterDomain domain)
+ {
+ if (domain.UMin < patch.Spline.DomainStartU || domain.UMax > patch.Spline.DomainEndU
+ || domain.VMin < patch.Spline.DomainStartV || domain.VMax > patch.Spline.DomainEndV)
+ return new(false, null, [new("surf-extend-law-unsupported", "A non-rational B-spline may only be extended into its existing knot support in SURF-X1; arbitrary extrapolation is not defined.", patch.PatchId)]);
+ return TrimRegion(patch, domain);
+ }
+}
diff --git a/Aetheris.Surfacing/SurfacingModule.cs b/Aetheris.Surfacing/SurfacingModule.cs
index 67b9bb51..fbec3286 100644
--- a/Aetheris.Surfacing/SurfacingModule.cs
+++ b/Aetheris.Surfacing/SurfacingModule.cs
@@ -22,9 +22,9 @@ public static class SurfacingModule
new(SectionSurfaceCapability,Id,Version,"Ordered-section surface with explicit non-rational materialization evidence."),
new(BoundaryPatchCapability,Id,Version,"Four-boundary G0 patch preserving boundary intent."),
new(PanelCapability,Id,Version,"Bounded oriented engineering surface with ordered semantic boundary edges and developability evidence."),
- new(BoundedSculptingCapability,Id,Version,"Immutable single-predecessor BodyState derivation with bounded OffsetRegion authority, preservation contracts, and inspectable GeometricDelta evidence.")],
+ new(BoundedSculptingCapability,Id,Version,"Immutable single-predecessor BodyState derivation with bounded OffsetRegion and rectangular ReplaceRegion authority, mixed G0/G1 patch contracts, preservation, and inspectable GeometricDelta evidence.")],
["Surfacing.PanelConcept", "Surfacing.SurfacePatchConcept"], ["Surfacing.RuledCanopyPanel","Surfacing.HyperbolicParaboloid","Surfacing.ParabolicCylinder","Surfacing.EllipticParaboloid","Surfacing.Helicoid"],
["Surface construction -> PanelIR -> semantic edges", "Panel edge Interface/Mate -> deterministic G0 evidence", "PanelIR -> bounded BRep-backed STEP export envelope"],
- ["panel-incomplete-boundary", "panel-boundary-orientation-inconsistent","panel-mate-endpoint-mismatch","panel-mate-g0-failure","panel-mate-g1-failure","panel-mate-g1-unknown","panel-mate-g2-failure","panel-mate-g2-unknown","surfacing-panel-thickness-invalid","sculpt-outside-authorized-region","sculpt-preservation-failed","sculpt-self-intersection","surf-surface-export-normalization-failed"],
+ ["panel-incomplete-boundary", "panel-boundary-orientation-inconsistent","panel-mate-endpoint-mismatch","panel-mate-g0-failure","panel-mate-g1-failure","panel-mate-g1-unknown","panel-mate-g2-failure","panel-mate-g2-unknown","surfacing-panel-thickness-invalid","sculpt-outside-authorized-region","sculpt-preservation-failed","sculpt-self-intersection","surf-boundary-g0-violation","surf-boundary-g1-violation","surf-selector-target-replaced","surf-surface-export-normalization-failed"],
[new(CoreModule.Id, new(1, 0, 0))], new("docs/development/milestones/modules/surfacing.md"));
}
diff --git a/docs/public/firmament/sculpting.md b/docs/public/firmament/sculpting.md
index b09209f0..68ef9096 100644
--- a/docs/public/firmament/sculpting.md
+++ b/docs/public/firmament/sculpting.md
@@ -1,6 +1,6 @@
-# Bounded mathematical sculpting
+# Bounded mathematical sculpting and patch replacement
-SURF-X0 supports bounded mathematical sculpting and locality-preserving region modification. It does not provide full general surfacing.
+SURF-X0 supports bounded mathematical sculpting and locality-preserving region modification. SURF-X1 adds one deliberately narrow freeform lane: replace the rectangular center of the admitted housing top with a bounded tensor-product patch. This is not full general surfacing.
Sculpting is a lower-authority escape hatch for geometry that an engineering feature such as `Boss`, `Pocket`, `Hole`, `Sweep`, `Fillet`, or `Chamfer` cannot express. Prefer those features whenever they carry the intended engineering meaning.
@@ -41,6 +41,53 @@ SculptState CrownRaised {
The accepted operation records reads, preserved/replaced/introduced/removed entities, the authorized domain, correspondence, and validation evidence in `GeometricDelta`. `aetheris inspect model.firmament --json` reports every state. `aetheris build model.firmament --json` also writes a sibling `.delta.json` artifact.
+`build` performs export preflight and the rational-surface product-boundary guard; it does not report an independent STEP reimport. Run `aetheris analyze result.step --json` after building to exercise the production importer and report the reconstructed topology, surface inventory, and bounds.
+
+## X1 patch authoring
+
+Use normal engineering features for normal CAD. `SurfacePatch` and `ReplaceRegion` are advanced sculpting tools for geometry that exact engineering features cannot express. The canonical witness is [`surf-x1-freeform-housing.firmament`](../../../fixtures/Canonical/Sculpting/surf-x1-freeform-housing.firmament).
+
+```firmament
+SurfacePatch CrownPatch {
+ Degree: [3, 3]
+ Domain: [0, 1, 0, 1]
+ KnotsU: [0, 0, 0, 0, 0.3333333333333333, 0.6666666666666666, 1, 1, 1, 1]
+ KnotsV: [0, 0, 0, 0, 0.3333333333333333, 0.6666666666666666, 1, 1, 1, 1]
+ ControlRow: [[-30mm, -20mm, 20mm], ...]
+ # Six rows of six finite control points in the complete fixture.
+ Boundary South { Existing: CrownBoundarySouth
+ Continuity: G0 }
+ Boundary East { Existing: CrownBoundaryEast
+ Continuity: G1 }
+ Boundary North { Existing: CrownBoundaryNorth
+ Continuity: G0 }
+ Boundary West { Existing: CrownBoundaryWest
+ Continuity: G1 }
+}
+
+SculptState FreeformCrown {
+ Input: Base
+ ReplaceRegion {
+ Target: HousingCrown
+ Patch: CrownPatch
+ InfluenceEnvelope: [-30mm, -20mm, 20mm, 30mm, 20mm, 28mm]
+ }
+ MayModify: [HousingCrown, CrownTransitionZone]
+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary, SideWallsLower]
+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]
+}
+```
+
+The public patch carries degree, rectangular control net, expanded nondecreasing knots, stable `[uMin,uMax] x [vMin,vMax]` domain, one outer loop, four explicit old-boundary correspondences, per-edge G0/G1 contracts, orientation, and export class. It has no weights field. `inspect --json` reports this metadata without dumping the control net.
+
+G0 compares 33 deterministic samples to the exact preserved boundary line. G1 additionally compares patch tangent planes to the planar frame and reports the maximum angular error. The flagship requires G1 on east/west and G0 on north/south. Accepted patch edges and vertices are shared BRep topology, not merely nearby geometry.
+
+`TrimRegion` currently restricts a non-rational patch to a subdomain already present in its knot support. `ExtendRegion` can restore or enlarge that bounded domain only inside the same support. Arbitrary extrapolation, surface-surface intersection trimming, holes in patch loops, and coincident/tangent-support classification are not yet public capabilities.
+
+An ordinary safe cylindrical `HoleFeature` can follow replacement on a surviving current-state region. Selectors are resolved against the immediate predecessor. A selector for removed `HousingCrown` fails with `surf-selector-target-replaced` and names `CrownPatch` and the replacing state.
+
+For low/high freeform alternatives, declare two complete `SurfacePatch` values and two sibling `SculptState` blocks whose `Input` is the same base state. Do not derive the high version from the accepted low version or edit an accepted control net in place. A model has one `Output`; select the sibling to build there, or keep separate small model files when both STEP variants are release artifacts.
+
## Guarantees and evidence
The housing lane verifies:
@@ -60,8 +107,14 @@ The housing lane verifies:
Internal algorithms may temporarily use rational spline mathematics, but exported product geometry must normalize to analytic or non-rational forms. The export order is exact analytic surface, exact or explicitly bounded non-rational B-spline, then a blocking diagnostic. Arbitrary rational NURBS fallback is prohibited. The diagnostic is `surf-surface-export-normalization-failed`.
-The X0 housing emits only `PLANE` and `CYLINDRICAL_SURFACE`. A final STEP scan must report `RationalNURBS = 0`; otherwise export fails.
+The X0 housing emits only `PLANE` and `CYLINDRICAL_SURFACE`. The X1 flagship adds one `B_SPLINE_SURFACE_WITH_KNOTS` with no rational complex entity. A final STEP scan must report `RationalNURBS = 0`; otherwise export fails.
+
+> Non-rational B-spline surfaces are an advanced product representation used only when exact analytic geometry is insufficient.
+
+> Rational NURBS remain an internal computational mechanism only. They are never a product-boundary fallback.
## Current limits
-SURF-X0 does not support general NURBS authoring, arbitrary freeform patches, Loft, Trim/Extend, G1/G2 patch networks, arbitrary deformation, global surface replacement, or arbitrary imported-face sculpting. The first materializer is intentionally limited to a rectangular housing with a bounded rectangular crown and through mounting holes. PMI and Assembly Interface persistence through this lane remain follow-up work; X0 preserves the named mounting-interface and hole-pattern semantic contracts but does not claim new AP242 PMI types.
+The admitted X1 materializer is limited to a single rectangular outer loop in the center of the canonical planar housing top. It does not provide general imported-face replacement, inner patch loops, arbitrary intersection/trim solving, general surface extension, G2, Blend, Loft, Shell, Draft, fitting, fairness optimization, or arbitrary patch networks. Analytic surface objects exist in the patch IR but direct Firmament patch authoring currently admits the non-rational B-spline form only.
+
+The named mounting interface and per-hole semantic identities survive the operation. Authored AP242 PMI and Assembly Interface association round-trip through this sculpting lane is not yet implemented and is not claimed.
diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.md
index bd798602..45628352 100644
--- a/docs/public/reference/supported-features.md
+++ b/docs/public/reference/supported-features.md
@@ -5,7 +5,7 @@
| Area | Status | Preview 3 boundary |
|---|---|---|
| Firmament V2 native primitives/profiles | Bounded | Named Box/Cylinder/Frustum/RoundedBox and admitted line/arc profile construction/composition |
-| Bounded mathematical sculpting | Bounded (SURF-X0) | Immutable single-predecessor `BodyState`, rectangular-housing `OffsetRegion`, explicit authority/preservation/postconditions, analytic locality proof, and rational-free STEP. This is not general surfacing. See the [sculpting guide](../firmament/sculpting.md). |
+| Bounded mathematical sculpting | Bounded (SURF-X1 subset) | Immutable single-predecessor `BodyState`; rectangular-housing `OffsetRegion`; and one-loop rectangular `ReplaceRegion` using a direct non-rational B-spline patch, mixed G0/G1 contracts, exact lower-body locality, current-state downstream holes, and rational-free STEP. General trim/intersection surfacing and AP242 PMI/interface persistence remain unsupported. See the [sculpting guide](../firmament/sculpting.md). |
| Firmament V2 analytic primitives | Bounded | Direct named Sphere, Cone (including zero-radius pointed end), and Torus routes round-trip through AP242; legacy `solid` declarations remain compatibility inputs, not canonical authoring |
| Circular Sweep | Bounded (X0) | Open planar XY Concept Path, tangent line/arc segments, constant circular diameter, analytic cylinder/torus faces, capped solid; no general 3D/variable/rail/twist sweep |
| Structural / weldment | Bounded (X2) | Explicit 3D nodes and straight paths; identifiable members; square/rectangular/round tube, angle, flat/round bar; orientation; catalog material; two-member butt and polygonal miter joints; semantic fillet welds; AP242 member assembly and deterministic JSON Cut List. No coping, curved routing, multi-member miter, connection design, weld analysis, or structural FEA. See [guide](../firmament/structural.md). |
@@ -29,7 +29,7 @@
| Platform qualification | Supported | Windows x64 bundle; NativeAOT Forge Host on `win-x64` |
| Linux/macOS release binaries | Not in Preview 3 | Framework logic tests do not constitute binary qualification |
| Post-Preview-3 feature families | X0 exception | Circular Sweep and Standard Products Paperclip are the bounded X0 additions; other new geometry/PMI/FEA/Forge families remain frozen |
-| General loft, helix, and freeform surface features | Not in Preview 3 | No public native V2 authoring and qualification route |
+| General loft, helix, and freeform surface features | Not in Preview 3 | The bounded SURF-X1 rectangular `ReplaceRegion` exception is not a general Loft, surface network, or imported-face editing route. |
| Through profile removal | Bounded semantic operations | Use qualified `Hole`, `Slot`, or another documented opening feature; Pocket never means through-all |
| Arbitrary solid Boolean subtraction / hemispherical cavity | Not in Preview 3 | No public `Union`, `Subtract`, `Intersect`, CSG tree, Sphere-from-Block subtraction, or hemisphere special case |
diff --git a/docs/release/SURF-X1-PATCH-SURFACING.md b/docs/release/SURF-X1-PATCH-SURFACING.md
new file mode 100644
index 00000000..36a125e0
--- /dev/null
+++ b/docs/release/SURF-X1-PATCH-SURFACING.md
@@ -0,0 +1,85 @@
+# SURF-X1 — patch surfacing and bounded replacement
+
+## Executive verdict
+
+**Meaningful progression.** Aetheris can now perform one real bounded freeform surface replacement through the authoritative `BodyState -> GeometricDelta -> verified BRep -> STEP` path. The canonical housing has a genuine trimmed non-rational B-spline crown, explicit four-edge correspondence, mixed G0/G1 checks, zero deviation below the authorized top region, shared topology, deterministic export, successful production reimport, and zero rational product surfaces.
+
+SURF-X1 is not fully accepted against the complete milestone: general surface/support intersection trimming, extension beyond an existing knot support, inner loops, imported-face replacement, AP242 PMI/Assembly Interface association persistence, and fresh-agent qualification remain unimplemented. Those gaps are stated rather than represented by a generic NURBS or whole-body fallback.
+
+## Patch architecture
+
+`BoundedSurfacePatch` distinguishes mathematical support from a body. `AnalyticSurfacePatch` retains its elementary `SurfaceGeometry`; `BSplineSurfacePatch` wraps the existing weight-free `BSplineSurfaceWithKnots`. Both carry a stable patch ID, parameter domain, orientation, and one explicit `SurfaceBoundaryLoop`. Public `SurfacePatch` Firmament authoring currently admits only the non-rational tensor-product form and requires degree, complete finite rectangular control net, expanded knots, domain, and four named boundary contracts.
+
+`ReplaceRegionOperation` consumes one predecessor, target region, patch, authorized entities/envelope, preservation contracts, and postconditions. Validation completes before a successor exists. The housing materializer creates a preserved planar top frame and a separately bound spline face. Its four edges and vertices are shared topology with the frame. It is not a Boolean and cannot replace arbitrary imported faces.
+
+`TrimRegion` restricts a B-spline patch to a subdomain already inside its knot support. `ExtendRegion` can enlarge that domain only within the same support; extrapolation fails with `surf-extend-law-unsupported`. General surface-surface intersection and trim classification remain the next geometric blocker.
+
+## Flagship housing
+
+- Source: [`surf-x1-freeform-housing.firmament`](../../fixtures/Canonical/Sculpting/surf-x1-freeform-housing.firmament)
+- Base state: `state-4826ec8df531eb593583`
+- Replacement state: `state-6a688b75addb5403f978`
+- Downstream-hole state: `state-a92a57779cb61433a0fb`
+- Patch: `CrownPatch`, degree 3 x 3, 6 x 6 control net, domain `[0,1] x [0,1]`
+- Bounds after production STEP reimport: `[-50,-40,0]` to `[50,40,26.26953125]` mm
+- Topology after reimport: 1 body, 1 shell, 11 faces, 28 edges, 20 vertices; `enclosed-manifold`
+- Authorized envelope: `[-30,-20,20]` to `[30,20,28]` mm
+- Maximum realized-BRep deviation below `z=20`: `0 mm` at `1e-6 mm` tolerance
+
+The replacement delta preserves `BottomMountingInterface`, `MountingHolePattern`, `OuterFootprintBoundary`, and `SideWallsLower`; replaces `HousingCrown -> CrownPatch`; and retains explicit South/East/North/West boundary correspondence. The current implementation introduces one crown patch, not separate transition patches.
+
+## Continuity evidence
+
+Each boundary is sampled at 33 deterministic parameters. G0 is point-to-exact-boundary-segment distance, not height alone. G1 compares the patch tangent-plane normal to the neighboring planar frame.
+
+| Boundary | Contract | Maximum G0 error | Maximum G1 angular error | Tolerance |
+|---|---|---:|---:|---:|
+| South | G0 | 0 mm | not required | 1e-6 mm |
+| East | G1 | 0 mm | 0.000574746 degrees | 0.1 degrees |
+| North | G0 | 0 mm | not required | 1e-6 mm |
+| West | G1 | 0 mm | 0.000574746 degrees | 0.1 degrees |
+
+Every realized edge has exactly two coedge uses. Replacement boundaries use shared edge IDs and shared vertex IDs. The core BRep currently has no separate public pcurve object, so this milestone does not claim independent pcurve round-trip qualification.
+
+## STEP surface inventory
+
+| Artifact | Planes | Cylinders | Cones | Spheres | Tori | Non-rational B-splines | Rational surfaces |
+|---|---:|---:|---:|---:|---:|---:|---:|
+| Freeform housing | 6 | 4 | 0 | 0 | 0 | 1 | **0** |
+
+The exporter emits one `B_SPLINE_SURFACE_WITH_KNOTS` and blocks `RATIONAL_B_SPLINE_SURFACE`. Production `Step242Importer` reimports the artifact and preserves the spline degree, control net, knots, closed shell, and surface-family inventory. The flagship uses no internal rational algorithm and no approximation. Existing normalization tests retain equal-weight rational plane -> `Plane`, equal-weight non-planar patch -> non-rational B-spline, and non-removable rationality -> blocking diagnostic. General conic rational recovery is not newly claimed by this lane.
+
+## Downstream feature propagation
+
+`CrownWithServiceHole` consumes `FreeformCrown`, resolves `OuterFootprintBoundary` in that current state, and adds exact cylindrical through-hole `H5`. It preserves `CrownPatch`, the four original individual hole identities, lower side walls, and four crown boundaries. Export contains the same single non-rational crown plus five cylinders and zero rational surfaces.
+
+A direct attempt to replace historical `HousingCrown` again from the replacement state fails atomically with `surf-selector-target-replaced` and explains that `CrownPatch` replaced it. No successor is returned.
+
+## Manual artifact
+
+- STEP: [`surf-x1-freeform-housing.step`](../../artifacts/local/surf-x1-freeform-housing.step)
+- Delta/evidence: [`surf-x1-freeform-housing.delta.json`](../../artifacts/local/surf-x1-freeform-housing.delta.json)
+- SHA-256: `a8cf1b5b7c273cf89d5c2b265d7a105be705ece526781b4c4cf7876e36e49fdb`
+- Size: 14,344 bytes
+
+Inspect the overall crown shape, east/west tangent transitions, front/back positional transitions, unexpected creases, dents or warts, unchanged four-hole mounting pattern, unchanged bottom interface, unchanged lower side walls, and the four trim edges. The structured continuity evidence is authoritative; visual inspection is an additional aesthetic check.
+
+## Qualification boundary and remaining blockers
+
+Implemented regression coverage includes patch invariants, bounded Trim/Extend policy, `ReplaceRegion`, mixed G0/G1, locality, preservation, shared topology, failure atomicity, stale references, deterministic state/STEP, downstream hole propagation, rational prohibition, STEP export/reimport, structured CLI metadata, and interior B-spline bounds.
+
+The next blocker is a topology-aware intersection/trim layer that can produce and classify non-rectangular trim curves and their parameter-space representation. Without it, broad `TrimRegion`, arbitrary support extension, inner loops, and imported-face replacement would be brittle special cases. Separately, sculpting state needs actual AP242 PMI and Assembly Interface association storage/rebinding before preservation parity can be claimed. G2, Blend, Loft, Shell, Draft, fitting, and fairness remain deferred by design.
+
+## Qualification results
+
+- zero-warning `Release` solution build: pass;
+- focused SURF-X1 tests: 8 pass;
+- solution test run: 3,126 pass, 1 unrelated load-sensitive display-fallback test fails during the parallel run and passes immediately in isolation;
+- CLI suite, including structured X1 build/analyze and public Markdown links: 400 pass;
+- canonical qualification: all 93 fixtures pass;
+- client: 82 tests, production build, and lint pass;
+- VS Code extension: 13 tests, typecheck, build, and VSIX package pass;
+- fresh packaged CLI: builds and analyzes the flagship; STEP hash matches the in-tree CLI artifact;
+- repository layout guard and `git diff --check`: pass.
+
+Five context-free agents were restricted to `docs/public/` and `fixtures/Canonical/`. A selected `SurfacePatch` + `ReplaceRegion` and the full preservation/export contract. B selected G1 east/west and G0 north/south with the correct numerical checks. C selected immutable sibling branching; its initial use of `OffsetRegion` exposed missing guidance for two freeform-patch variants, which the public guide now corrects. D selected current-state `HoleFeature`, preserved `CrownPatch` and H1-H4, and explained the stale selector diagnostic. E selected validate/inspect/build/analyze and the one-non-rational/zero-rational checks; its ambiguity over whether `build` itself reimports prompted an explicit command-boundary clarification in the guide.
diff --git a/fixtures/Canonical/README.md b/fixtures/Canonical/README.md
index 43b34fb2..6c6062ea 100644
--- a/fixtures/Canonical/README.md
+++ b/fixtures/Canonical/README.md
@@ -25,6 +25,7 @@ Everything in this directory is current authoring guidance. Examples progress fr
| use a CNC policy | `Templates/cnc-dfm-policy.firmament` | Record defaults, `with`, `Template<Policy>`, enforcement |
| make Sheet Metal | `SheetMetal/l-bracket-with-hole.firmament` | material, bend, planar hole, formed/flat output |
| apply a bounded mathematical sculpt | `Sculpting/sculpted-housing.firmament` | immutable `BodyState`, `OffsetRegion`, locality, preservation contracts |
+| replace a housing region with a freeform patch | `Sculpting/surf-x1-freeform-housing.firmament` | direct non-rational 6x6 B-spline patch, `ReplaceRegion`, explicit boundary correspondence, mixed G0/G1, downstream current-state hole |
| make a data-driven Sheet Metal tab | `SheetMetal/profile-delta-tab-family.firmament` | Table, `with`, reusable `ProfileDelta Tab` |
| run FEA | `FEA/cantilever.firmament` | material, `Fixed`, `Force`, four result families |
| analyze imported STEP | `FEA/inline-step-cantilever.firmament` | repository-stable `inlineSTEP`, face selection, FEA |
diff --git a/fixtures/Canonical/Sculpting/surf-x1-freeform-housing.firmament b/fixtures/Canonical/Sculpting/surf-x1-freeform-housing.firmament
new file mode 100644
index 00000000..33e3bbde
--- /dev/null
+++ b/fixtures/Canonical/Sculpting/surf-x1-freeform-housing.firmament
@@ -0,0 +1,63 @@
++Model FreeformControllerCover {
+ Units: mm
+
+ SurfacePatch CrownPatch {
+ Degree: [3, 3]
+ Domain: [0, 1, 0, 1]
+ KnotsU: [0, 0, 0, 0, 0.3333333333333333, 0.6666666666666666, 1, 1, 1, 1]
+ KnotsV: [0, 0, 0, 0, 0.3333333333333333, 0.6666666666666666, 1, 1, 1, 1]
+ ControlRow: [[-30mm, -20mm, 20mm], [-30mm, -12mm, 20mm], [-30mm, -4mm, 20mm], [-30mm, 4mm, 20mm], [-30mm, 12mm, 20mm], [-30mm, 20mm, 20mm]]
+ ControlRow: [[-20mm, -20mm, 20mm], [-20mm, -12mm, 20mm], [-20mm, -4mm, 20mm], [-20mm, 4mm, 20mm], [-20mm, 12mm, 20mm], [-20mm, 20mm, 20mm]]
+ ControlRow: [[-8mm, -20mm, 20mm], [-8mm, -12mm, 22mm], [-8mm, -4mm, 27mm], [-8mm, 4mm, 27mm], [-8mm, 12mm, 22mm], [-8mm, 20mm, 20mm]]
+ ControlRow: [[8mm, -20mm, 20mm], [8mm, -12mm, 22mm], [8mm, -4mm, 27mm], [8mm, 4mm, 27mm], [8mm, 12mm, 22mm], [8mm, 20mm, 20mm]]
+ ControlRow: [[20mm, -20mm, 20mm], [20mm, -12mm, 20mm], [20mm, -4mm, 20mm], [20mm, 4mm, 20mm], [20mm, 12mm, 20mm], [20mm, 20mm, 20mm]]
+ ControlRow: [[30mm, -20mm, 20mm], [30mm, -12mm, 20mm], [30mm, -4mm, 20mm], [30mm, 4mm, 20mm], [30mm, 12mm, 20mm], [30mm, 20mm, 20mm]]
+ Boundary South { Existing: CrownBoundarySouth
+ Continuity: G0 }
+ Boundary East { Existing: CrownBoundaryEast
+ Continuity: G1 }
+ Boundary North { Existing: CrownBoundaryNorth
+ Continuity: G0 }
+ Boundary West { Existing: CrownBoundaryWest
+ Continuity: G1 }
+ }
+
+ BodyState Base {
+ Size: [100mm, 80mm, 20mm]
+ Hole H1 { Center: [-38mm, -28mm]
+ Diameter: 4mm }
+ Hole H2 { Center: [38mm, -28mm]
+ Diameter: 4mm }
+ Hole H3 { Center: [38mm, 28mm]
+ Diameter: 4mm }
+ Hole H4 { Center: [-38mm, 28mm]
+ Diameter: 4mm }
+ }
+
+ SculptState FreeformCrown {
+ Input: Base
+ ReplaceRegion {
+ Target: HousingCrown
+ Patch: CrownPatch
+ InfluenceEnvelope: [-30mm, -20mm, 20mm, 30mm, 20mm, 28mm]
+ }
+ MayModify: [HousingCrown, CrownTransitionZone]
+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary, SideWallsLower]
+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]
+ }
+
+ SculptState CrownWithServiceHole {
+ Input: FreeformCrown
+ HoleFeature {
+ Target: OuterFootprintBoundary
+ Id: H5
+ Center: [40mm, 0mm]
+ Diameter: 4mm
+ InfluenceEnvelope: [38mm, -2mm, 0mm, 42mm, 2mm, 20mm]
+ }
+ Preserve: [CrownPatch, H1, H2, H3, H4, SideWallsLower, CrownBoundarySouth, CrownBoundaryEast, CrownBoundaryNorth, CrownBoundaryWest]
+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]
+ }
+
+ Output: FreeformCrown
+}
diff --git a/fixtures/Canonical/coverage.json b/fixtures/Canonical/coverage.json
index 5391c31b..987e808b 100644
--- a/fixtures/Canonical/coverage.json
+++ b/fixtures/Canonical/coverage.json
@@ -31,6 +31,10 @@
"FEA": "FEA/cantilever.firmament",
"inlineSTEP": "FEA/inline-step-cantilever.firmament",
"Assembly": "Assembly/bearing-module.firmament",
- "Piping": "Piping/pump-skid.firmament"
+ "Piping": "Piping/pump-skid.firmament",
+ "SurfacePatch": "Sculpting/surf-x1-freeform-housing.firmament",
+ "ReplaceRegion": "Sculpting/surf-x1-freeform-housing.firmament",
+ "PatchG1": "Sculpting/surf-x1-freeform-housing.firmament",
+ "PostSculptHole": "Sculpting/surf-x1-freeform-housing.firmament"
}
}