Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Expose judged blend decisions and provenance in sculpting builds
Yuechen Li539fbac8259e
diff --git a/Aetheris.CLI.Tests/SculptingCliTests.cs b/Aetheris.CLI.Tests/SculptingCliTests.csindex 1ff230e1..604ff557 100644--- a/Aetheris.CLI.Tests/SculptingCliTests.cs+++ b/Aetheris.CLI.Tests/SculptingCliTests.cs@@ -46,5 +46,26 @@ public sealed class SculptingCliTestsfinally { if (File.Exists(output)) File.Delete(output); var delta = Path.ChangeExtension(output, ".delta.json"); if (File.Exists(delta)) File.Delete(delta); }}+ [Fact]+ public void JudgedBlendBuildExposesCompactCandidateTraceAndProvenance()+ {+ var fixture = Path.Combine(Root(), "fixtures", "Canonical", "Sculpting", "surf-x2-judged-housing.firmament");+ var output = Path.Combine(Path.GetTempPath(), "aetheris-surf-x2-" + Guid.NewGuid().ToString("N") + ".step");+ try+ {+ var buildOut = new StringWriter(); var buildErr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["build", fixture, "--output", output, "--json"], buildOut, buildErr));+ using var build = JsonDocument.Parse(buildOut.ToString()); var root = build.RootElement;+ var judgment = root.GetProperty("blendJudgment");+ Assert.Equal("PowerM3Degree6", judgment.GetProperty("selectedCandidateId").GetString());+ Assert.Equal(4, judgment.GetProperty("candidates").GetArrayLength());+ Assert.Contains(judgment.GetProperty("candidates").EnumerateArray(), item => item.GetProperty("disposition").GetString() == "Rejected");+ Assert.Equal(0, root.GetProperty("rationalNurbs").GetInt32());+ using var delta = JsonDocument.Parse(File.ReadAllText(Path.ChangeExtension(output, ".delta.json")));+ Assert.Equal("PowerM3Degree6", delta.RootElement.GetProperty("delta").GetProperty("blendJudgment").GetProperty("selectedCandidateId").GetString());+ }+ 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.csindex 539ad28f..0f8ad25a 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -538,6 +538,7 @@ public static class CliRunnercompile.OutputState.Delta,validationEvidence = compile.OutputState.ValidationEvidence,surfacePatches = compile.OutputState.SurfacePatches,+ blendJudgment = compile.OutputState.BlendJudgment,surfaceInventory = export.Inventory,productBoundary = new { rationalNurbs = export.Inventory.RationalNurbs, admitted = export.Inventory.RationalNurbs == 0 },timingsMilliseconds = compile.Timings with { StepExportMilliseconds = exportClock.Elapsed.TotalMilliseconds }@@ -546,10 +547,20 @@ 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, surfacePatches = compile.OutputState.SurfacePatches, surfaceInventory = export.Inventory, rationalNurbs = export.Inventory.RationalNurbs,+ validationEvidence = compile.OutputState.ValidationEvidence, surfacePatches = compile.OutputState.SurfacePatches, blendJudgment = compile.OutputState.BlendJudgment, 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}"); }+ 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}");+ if (compile.OutputState.BlendJudgment is { } judgment)+ {+ stdout.WriteLine($"Blend judgment: {judgment.Request}");+ foreach (var candidate in judgment.Candidates)+ stdout.WriteLine($" {candidate.CandidateId}: {candidate.Disposition}" + (candidate.Metrics is null ? $" — {candidate.RejectionReason}" : $"; utility={candidate.Metrics.Utility:F6}, fairness={candidate.Metrics.Fairness:F6}, curvature={candidate.Metrics.CurvatureSmoothness:F6}, compactness={candidate.Metrics.Compactness:F6}, complexity={candidate.Metrics.Complexity:F6}"));+ stdout.WriteLine($" Selected: {judgment.SelectedCandidateId} ({(judgment.ManualOverride ? "manual override" : judgment.JudgmentPolicyId)})");+ }+ }return 0;}@@ -557,7 +568,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, surfacePatches = state.SurfacePatches, hasDelta = state.Delta is not null+ semanticInventory = state.SemanticInventory.Values, surfacePatches = state.SurfacePatches, blendJudgment = state.BlendJudgment, hasDelta = state.Delta is not null};private static int RunSheetMetalAuthoredBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)diff --git a/Aetheris.Kernel.Core/Judgment/JudgmentEngine.cs b/Aetheris.Kernel.Core/Judgment/JudgmentEngine.csindex 16460273..cbb84009 100644--- a/Aetheris.Kernel.Core/Judgment/JudgmentEngine.cs+++ b/Aetheris.Kernel.Core/Judgment/JudgmentEngine.cs@@ -15,6 +15,29 @@ public static class When=> context => !predicate(context);}+/// <summary>Small normalized utility primitives shared by bounded static judgments.</summary>+public static class Utility+{+ public static double Clamp01(double value) => double.Clamp(value, 0d, 1d);++ public static double Remap(double value, double minimum, double maximum)+ {+ if (!double.IsFinite(value) || !double.IsFinite(minimum) || !double.IsFinite(maximum) || maximum <= minimum)+ return 0d;+ return Clamp01((value - minimum) / (maximum - minimum));+ }++ public static double Pow(double value, double exponent)+ => Clamp01(double.Pow(Clamp01(value), exponent));++ public static double Weighted(params (double Value, double Weight)[] considerations)+ {+ var admitted = considerations.Where(item => double.IsFinite(item.Value) && double.IsFinite(item.Weight) && item.Weight > 0d).ToArray();+ var total = admitted.Sum(item => item.Weight);+ return total <= 0d ? 0d : Clamp01(admitted.Sum(item => Clamp01(item.Value) * item.Weight) / total);+ }+}+/// <summary>/// Generic bounded candidate contract for deterministic judgment./// </summary>diff --git a/Aetheris.Kernel.Firmament.Tests/SurfX2BlendBoundaryTests.cs b/Aetheris.Kernel.Firmament.Tests/SurfX2BlendBoundaryTests.csnew file mode 100644index 00000000..a4a46653--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/SurfX2BlendBoundaryTests.cs@@ -0,0 +1,71 @@+using Aetheris.Surfacing;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class SurfX2BlendBoundaryTests+{+ [Fact]+ public void JudgedHousingGeneratesRejectsScoresAndRealizesG2Winner()+ {+ var result = SculptingAuthoring.CompileFile(Fixture("Canonical", "Sculpting", "surf-x2-judged-housing.firmament"));++ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(item => $"{item.Code}: {item.Message}")));+ var state = Assert.IsType<BodyState>(result.OutputState);+ var trace = Assert.IsType<BlendJudgmentTrace>(state.BlendJudgment);+ Assert.Equal("StandardBlendJudgment/v1", trace.JudgmentPolicyId);+ Assert.Equal("PowerM3Degree6", trace.SelectedCandidateId);+ Assert.Equal(4, trace.Candidates.Count);+ var rejected = Assert.Single(trace.Candidates, candidate => candidate.CandidateId == "PowerM2Degree4");+ Assert.Equal(BlendCandidateDisposition.Rejected, rejected.Disposition);+ Assert.Contains("g2-unsatisfied", rejected.RejectionReason, StringComparison.Ordinal);+ Assert.Equal(0.1024d, rejected.BoundaryEvidence.MaximumNormalCurvatureError, 8);+ var selected = Assert.Single(trace.Candidates, candidate => candidate.Disposition == BlendCandidateDisposition.Selected);+ Assert.Equal(BlendContinuity.G2, selected.ContinuityCapability);+ Assert.Equal(0d, selected.BoundaryEvidence.MaximumNormalCurvatureError);+ Assert.Equal(3, trace.Candidates.Count(candidate => candidate.Metrics is not null));+ Assert.All(state.SurfacePatches.Single().ContinuityContracts, contract => Assert.Equal(PatchBoundaryContinuity.G2, contract.Continuity));+ Assert.Contains(state.ValidationEvidence, item => item.Check.EndsWith(":G2", StringComparison.Ordinal) && item.Satisfied && item.Level == LocalityEvidenceLevel.ExactAnalytic);+ Assert.Equal("PowerM3Degree6", state.Delta!.BlendJudgment!.SelectedCandidateId);+ var export = SculptStepExporter.Export(state, "JudgedBlendHousing");+ Assert.True(export.IsSuccess); Assert.Equal(1, export.Inventory.NonRationalBSpline); Assert.Equal(0, export.Inventory.RationalNurbs);+ }++ [Fact]+ public void CandidateSetWinnerDeltaAndStepAreDeterministic()+ {+ var source = File.ReadAllText(Fixture("Canonical", "Sculpting", "surf-x2-judged-housing.firmament"));+ var first = SculptingAuthoring.Compile(source); var second = SculptingAuthoring.Compile(source);++ Assert.True(first.IsSuccess); Assert.True(second.IsSuccess);+ Assert.Equal(first.OutputState!.StateId, second.OutputState!.StateId);+ Assert.Equal(first.OutputState.BlendJudgment!.CandidateSetId, second.OutputState.BlendJudgment!.CandidateSetId);+ Assert.Equal(first.OutputState.BlendJudgment.SelectedCandidateId, second.OutputState.BlendJudgment.SelectedCandidateId);+ Assert.Equal(SculptStepExporter.Export(first.OutputState, first.ModelName).Step, SculptStepExporter.Export(second.OutputState, second.ModelName).Step);+ }++ [Fact]+ public void ExplicitFallbackAndEligibleManualOverrideAreVisible()+ {+ var source = File.ReadAllText(Fixture("Canonical", "Sculpting", "surf-x2-judged-housing.firmament"));+ var fallback = SculptingAuthoring.Compile(source.Replace("Minimum: G2", "Minimum: G1", StringComparison.Ordinal).Replace("MaximumDegree: 10", "MaximumDegree: 4", StringComparison.Ordinal));+ Assert.True(fallback.IsSuccess, string.Join(" | ", fallback.Diagnostics.Select(item => item.Message)));+ Assert.Equal("PowerM2Degree4", fallback.OutputState!.BlendJudgment!.SelectedCandidateId);+ Assert.Contains("active G1", fallback.OutputState.BlendJudgment.Request, StringComparison.Ordinal);++ var overridden = SculptingAuthoring.Compile(source.Replace("Policy: StandardBlendJudgment", "Policy: StandardBlendJudgment\n UseCandidate: PowerM4Degree8", StringComparison.Ordinal));+ Assert.True(overridden.IsSuccess, string.Join(" | ", overridden.Diagnostics.Select(item => item.Message)));+ Assert.True(overridden.OutputState!.BlendJudgment!.ManualOverride);+ Assert.Equal("PowerM4Degree8", overridden.OutputState.BlendJudgment.SelectedCandidateId);+ }++ [Fact]+ public void RequiredG2FailsWhenDegreeGateLeavesOnlyG1()+ {+ var result = SculptingAuthoring.CompileFile(Fixture("Invalid", "Sculpting", "surf-x2-g2-unsatisfied.firmament"));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, item => item.Code == "surf-blend-no-eligible-candidates");+ }++ private static string Fixture(params string[] parts) => Path.Combine([Root(), "fixtures", .. parts]);+ private static string Root() { var directory = new DirectoryInfo(AppContext.BaseDirectory); while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent; return directory!.FullName; }+}diff --git a/Aetheris.Surfacing/BlendBoundary.cs b/Aetheris.Surfacing/BlendBoundary.csnew file mode 100644index 00000000..d3044ee8--- /dev/null+++ b/Aetheris.Surfacing/BlendBoundary.cs@@ -0,0 +1,395 @@+using Aetheris.Geometry;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Judgment;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Surfacing;++public enum BlendContinuity { G0, G1, G2 }+public enum BlendCandidateDisposition { Rejected, Eligible, Selected }++public sealed record BlendJudgmentPolicy(+ string PolicyId,+ double FairnessWeight,+ double CurvatureVariationWeight,+ double CompactnessWeight,+ double ComplexityWeight)+{+ public static BlendJudgmentPolicy StandardBlendJudgment { get; } = new(+ "StandardBlendJudgment/v1", .40d, .30d, .20d, .10d);+}++public sealed record BlendBoundaryOperation(+ string StableId,+ string SupportA,+ string SupportB,+ string Region,+ BlendContinuity PreferredContinuity,+ BlendContinuity MinimumContinuity,+ double RegionWidth,+ double RegionDepth,+ double CrownHeight,+ IReadOnlyList<string> MayModify,+ SpatialInfluenceEnvelope InfluenceEnvelope,+ IReadOnlyList<PreservationContract> Preserves,+ IReadOnlyList<SculptRequirement> Requirements,+ BlendJudgmentPolicy? Policy = null,+ string? UseCandidate = null,+ int MaximumDegree = 10,+ double GeometricTolerance = 1e-6,+ double G1AngularToleranceDegrees = .1d,+ double G2CurvatureTolerance = 1e-6)+{+ public BlendJudgmentPolicy EffectivePolicy => Policy ?? BlendJudgmentPolicy.StandardBlendJudgment;+ public string Canonical => string.Join('|', StableId, SupportA, SupportB, Region, PreferredContinuity, MinimumContinuity,+ RegionWidth.ToString("R"), RegionDepth.ToString("R"), CrownHeight.ToString("R"), MaximumDegree,+ 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(item => item.EntityId, StringComparer.Ordinal).Select(item => $"{item.EntityId}:{item.Mode}")),+ string.Join(',', Requirements.Order()), EffectivePolicy.PolicyId, UseCandidate ?? "<policy>");+}++public sealed record BlendBoundaryEvidence(+ double MaximumPositionError,+ double MaximumTangentPlaneErrorDegrees,+ double MaximumNormalCurvatureError,+ int SampleCount,+ string Formulation);++public sealed record BlendQualityMetrics(+ double BendingEnergy,+ double CurvatureVariation,+ double ChangedAreaFraction,+ int ControlPointCount,+ double Fairness,+ double CurvatureSmoothness,+ double Compactness,+ double Complexity,+ double Utility);++public sealed record BlendCandidateTrace(+ string CandidateId,+ string ConstructionFamily,+ IReadOnlyDictionary<string, string> Parameters,+ BlendContinuity ContinuityCapability,+ string SurfaceClass,+ int DegreeU,+ int DegreeV,+ int ControlPointCount,+ BlendCandidateDisposition Disposition,+ string? RejectionReason,+ BlendBoundaryEvidence BoundaryEvidence,+ BlendQualityMetrics? Metrics);++public sealed record BlendJudgmentTrace(+ string Request,+ string JudgmentPolicyId,+ string CandidateSetId,+ string? SelectedCandidateId,+ bool ManualOverride,+ string TieBreak,+ IReadOnlyList<BlendCandidateTrace> Candidates);++public sealed record BlendJudgmentProvenance(+ string JudgmentPolicyId,+ string CandidateSetId,+ string SelectedCandidateId,+ IReadOnlyDictionary<string, double> QualityMetrics);++public sealed record BlendBoundaryResult(+ bool IsSuccess,+ BodyState? OutputState,+ GeometricDelta? Delta,+ BlendJudgmentTrace Trace,+ IReadOnlyList<SculptDiagnostic> Diagnostics);++internal sealed record MaterializedBlendCandidate(+ string CandidateId,+ int EdgeOrder,+ BSplineSurfacePatch Patch,+ BlendContinuity Capability,+ BlendBoundaryEvidence BoundaryEvidence,+ BlendQualityMetrics RawMetrics,+ bool IsAdmissible,+ string? RejectionReason);++/// <summary>+/// Deterministic two-support transition for the qualified housing crown/planar-shoulder case.+/// The product patch is the exact tensor product z=h*g_m(u)g_m(v), where+/// g_m(t)=4^m[t(1-t)]^m. m>=3 has zero first and second transverse derivatives at+/// every planar shoulder boundary, which is Aetheris' bounded G2 contract here:+/// coincident position, coincident tangent plane, and equal transverse normal curvature.+/// </summary>+public static class BlendBoundarySculptor+{+ private const int MetricSamples = 25;++ public static BlendBoundaryResult Apply(BodyState input, string outputName, BlendBoundaryOperation operation)+ {+ ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);+ var diagnostics = ValidateRequest(input, operation).ToList();+ if (diagnostics.Count > 0) return Failure(operation, diagnostics);++ var candidates = Enumerable.Range(2, 4)+ .Select(order => ConstructAndQualify(input, operation, order))+ .OrderBy(candidate => candidate.CandidateId, StringComparer.Ordinal)+ .ToArray();+ var eligibleForPreferred = candidates.Where(candidate => candidate.IsAdmissible && candidate.Capability >= operation.PreferredContinuity).ToArray();+ var activeRequirement = eligibleForPreferred.Length > 0 ? operation.PreferredContinuity : operation.MinimumContinuity;+ var eligible = candidates.Where(candidate => candidate.IsAdmissible && candidate.Capability >= activeRequirement).ToArray();+ if (eligible.Length > 0)+ {+ var normalized = Normalize(eligible, operation.EffectivePolicy);+ candidates = candidates.Select(candidate => normalized.FirstOrDefault(item => item.CandidateId == candidate.CandidateId) ?? candidate).ToArray();+ eligible = candidates.Where(candidate => candidate.IsAdmissible && candidate.Capability >= activeRequirement).ToArray();+ }++ MaterializedBlendCandidate? selected = null;+ var manual = false;+ if (operation.UseCandidate is not null)+ {+ selected = eligible.SingleOrDefault(candidate => StringComparer.Ordinal.Equals(candidate.CandidateId, operation.UseCandidate));+ if (selected is null)+ diagnostics.Add(new("surf-blend-override-ineligible", $"Candidate override '{operation.UseCandidate}' is absent or ineligible for {activeRequirement}."));+ else manual = true;+ }+ else if (eligible.Length > 0)+ {+ var context = new BlendSelectionContext(eligible);+ var options = eligible.Select(candidate => new JudgmentCandidate<BlendSelectionContext>(candidate.CandidateId, _ => true,+ _ => candidate.RawMetrics.Utility, TieBreakerPriority: candidate.RawMetrics.ControlPointCount)).ToArray();+ var judgment = new JudgmentEngine<BlendSelectionContext>().Evaluate(context, options);+ if (judgment.IsSuccess)+ selected = eligible.Single(candidate => candidate.CandidateId == judgment.Selection!.Value.Candidate.Name);+ }++ if (selected is null)+ {+ if (diagnostics.Count == 0)+ {+ foreach (var candidate in candidates)+ {+ var reason = candidate.RejectionReason ?? (candidate.Capability < activeRequirement+ ? $"continuity capability {candidate.Capability} is below active {activeRequirement}."+ : "candidate was not selected");+ diagnostics.Add(new("surf-blend-candidate-rejected", $"{candidate.CandidateId}: {reason}", candidate.CandidateId));+ }+ diagnostics.Add(new("surf-blend-no-eligible-candidates", $"No candidate satisfies minimum continuity {operation.MinimumContinuity}; continuity requirements are never lowered by scoring."));+ }+ return Failure(operation, diagnostics, Trace(operation, candidates, null, manual, activeRequirement));+ }++ var patchContinuity = selected.Capability switch { BlendContinuity.G2 => PatchBoundaryContinuity.G2, BlendContinuity.G1 => PatchBoundaryContinuity.G1, _ => PatchBoundaryContinuity.G0 };+ var selectedPatch = selected.Patch with { BoundaryLoop = BoundaryLoop(operation.StableId, patchContinuity) };+ var replace = new ReplaceRegionOperation(operation.StableId + ".ReplaceRegion", operation.SupportA, selectedPatch,+ operation.MayModify, operation.InfluenceEnvelope, operation.Preserves, operation.Requirements,+ operation.GeometricTolerance, operation.G1AngularToleranceDegrees, operation.G2CurvatureTolerance);+ var certifiedBounds = new SpatialInfluenceEnvelope(-operation.RegionWidth / 2d, -operation.RegionDepth / 2d, operation.InfluenceEnvelope.MinZ,+ operation.RegionWidth / 2d, operation.RegionDepth / 2d, operation.InfluenceEnvelope.MinZ + operation.CrownHeight);+ var realized = ReplaceRegionSculptor.ApplyWithCertifiedPolynomialBounds(input, outputName, replace, certifiedBounds);+ if (!realized.IsSuccess || realized.OutputState is null || realized.Delta is null)+ return Failure(operation, realized.Diagnostics, Trace(operation, candidates, selected, manual, activeRequirement));++ var trace = Trace(operation, candidates, selected, manual, activeRequirement);+ var provenance = new BlendJudgmentProvenance(operation.EffectivePolicy.PolicyId, trace.CandidateSetId, selected.CandidateId,+ new Dictionary<string, double>(StringComparer.Ordinal)+ {+ ["Fairness"] = selected.RawMetrics.Fairness,+ ["CurvatureSmoothness"] = selected.RawMetrics.CurvatureSmoothness,+ ["Compactness"] = selected.RawMetrics.Compactness,+ ["Complexity"] = selected.RawMetrics.Complexity,+ ["Utility"] = selected.RawMetrics.Utility+ });+ var outputId = BodyStateId.Derive($"{input.StateId.Value}|BlendBoundary|{operation.Canonical}|{selected.CandidateId}");+ var delta = realized.Delta with { OutputState = outputId, BlendJudgment = provenance };+ var state = realized.OutputState with { StateId = outputId, Delta = delta, BlendJudgment = trace };+ return new(true, state, delta, trace, []);+ }++ private static IEnumerable<SculptDiagnostic> ValidateRequest(BodyState input, BlendBoundaryOperation operation)+ {+ if (!input.SemanticInventory.ContainsKey(operation.SupportA)) yield return new("surf-blend-support-unresolved", $"SupportA '{operation.SupportA}' is not present in the input BodyState.");+ if (string.IsNullOrWhiteSpace(operation.SupportB)) yield return new("surf-blend-support-unresolved", "SupportB must identify the preserved analytic shoulder.");+ if (!operation.MayModify.Contains(operation.Region, StringComparer.Ordinal) && !operation.MayModify.Contains(operation.SupportA, StringComparer.Ordinal))+ yield return new("sculpt-target-not-authorized", "BlendBoundary region/support is absent from MayModify.");+ if (operation.MinimumContinuity > operation.PreferredContinuity) yield return new("surf-blend-continuity-invalid", "Minimum continuity cannot exceed preferred continuity.");+ if (!double.IsFinite(operation.RegionWidth) || !double.IsFinite(operation.RegionDepth) || !double.IsFinite(operation.CrownHeight)+ || operation.RegionWidth <= 0d || operation.RegionDepth <= 0d || operation.CrownHeight <= 0d+ || operation.RegionWidth >= input.Construction.Width || operation.RegionDepth >= input.Construction.Depth)+ yield return new("surf-blend-region-invalid", "The bounded transition region must be positive and strictly inside the housing footprint.");+ if (operation.MaximumDegree < 1) yield return new("surf-blend-degree-invalid", "MaximumDegree must be positive.");+ }++ private static MaterializedBlendCandidate ConstructAndQualify(BodyState input, BlendBoundaryOperation operation, int order)+ {+ var degree = order * 2;+ var id = $"PowerM{order}Degree{degree}";+ var capability = order >= 3 ? BlendContinuity.G2 : order >= 2 ? BlendContinuity.G1 : BlendContinuity.G0;+ var patch = CreatePatch(operation, order, id);+ var boundary = BoundaryEvidence(operation, order);+ var raw = MeasureQuality(operation, order, degree + 1);+ string? rejection = null;+ if (degree > operation.MaximumDegree) rejection = $"surf-blend-complexity-limit — degree {degree} exceeds MaximumDegree {operation.MaximumDegree}.";+ else if (capability < operation.MinimumContinuity) rejection = $"surf-blend-g2-unsatisfied — capability {capability} is below required {operation.MinimumContinuity}; maximum normal-curvature error is {boundary.MaximumNormalCurvatureError:R}.";+ else if (patch.Validate().Count > 0) rejection = "surf-blend-trim-invalid — materialized patch contract is invalid.";+ else+ {+ var construction = input.Construction with { CrownWidth = operation.RegionWidth, CrownDepth = operation.RegionDepth, CrownOffset = operation.CrownHeight, ReplacementPatch = patch };+ var built = SculptedHousingBrepBuilder.Build(construction);+ if (built.Body is null) rejection = "surf-blend-topology-invalid — " + string.Join(" | ", built.Diagnostics.Select(item => item.Message));+ else+ {+ var bodyEvidence = SculptedHousingFactory.ValidateBody(built.Body, operation.GeometricTolerance);+ var failed = bodyEvidence.FirstOrDefault(item => !item.Satisfied);+ if (failed is not null) rejection = $"surf-blend-realized-brep-invalid — {failed.Check}: {failed.Detail}";+ else+ {+ var points = SamplePatch(patch, 17);+ var actual = new SpatialInfluenceEnvelope(points.Min(p => p.X), points.Min(p => p.Y), input.Construction.BaseHeight,+ points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z));+ if (!operation.InfluenceEnvelope.Contains(actual, operation.GeometricTolerance)) rejection = "surf-blend-locality-violation — candidate exceeds the authorized influence envelope.";+ }+ }+ }+ return new(id, order, patch, capability, boundary, raw, rejection is null, rejection);+ }++ private static BSplineSurfacePatch CreatePatch(BlendBoundaryOperation operation, int order, string id)+ {+ var degree = order * 2; var count = degree + 1;+ var central = double.Pow(4d, order) / Binomial(degree, order);+ var rows = new Point3D[count][];+ for (var i = 0; i < count; i++)+ {+ rows[i] = new Point3D[count];+ for (var j = 0; j < count; j++)+ {+ var x = -operation.RegionWidth / 2d + operation.RegionWidth * i / degree;+ var y = -operation.RegionDepth / 2d + operation.RegionDepth * j / degree;+ var z = operation.InfluenceEnvelope.MinZ + (i == order && j == order ? operation.CrownHeight * central * central : 0d);+ rows[i][j] = new(x, y, z);+ }+ }+ var spline = new BSplineSurfaceWithKnots(degree, degree, rows, "UNSPECIFIED", false, false, false,+ [degree + 1, degree + 1], [degree + 1, degree + 1], [0d, 1d], [0d, 1d], "UNSPECIFIED");+ return new(operation.StableId + "." + id, spline, new(0d, 1d, 0d, 1d), BoundaryLoop(operation.StableId, PatchBoundaryContinuity.G0));+ }++ private static SurfaceBoundaryLoop BoundaryLoop(string stableId, PatchBoundaryContinuity continuity) => new(stableId + ".OuterLoop",+ [+ new(stableId + ".South", PatchBoundarySide.South, "CrownBoundarySouth", continuity),+ new(stableId + ".East", PatchBoundarySide.East, "CrownBoundaryEast", continuity),+ new(stableId + ".North", PatchBoundarySide.North, "CrownBoundaryNorth", continuity),+ new(stableId + ".West", PatchBoundarySide.West, "CrownBoundaryWest", continuity)+ ]);++ private static BlendBoundaryEvidence BoundaryEvidence(BlendBoundaryOperation operation, int order)+ {+ var maxCurvature = 0d;+ for (var i = 0; i < 33; i++)+ {+ var t = i / 32d;+ foreach (var (u, v, alongV) in new[] { (t, 0d, true), (1d, t, false), (t, 1d, true), (0d, t, false) })+ {+ var jet = Jet(operation, order, u, v);+ var normal = jet.Du.Cross(jet.Dv); if (!normal.TryNormalize(out var n)) { maxCurvature = double.PositiveInfinity; continue; }+ var tangent = alongV ? jet.Dv : jet.Du;+ var second = alongV ? jet.Dvv : jet.Duu;+ maxCurvature = double.Max(maxCurvature, double.Abs(second.Dot(n) / tangent.Dot(tangent)));+ }+ }+ return new(0d, 0d, maxCurvature, 132,+ "G2 = G0 position + coincident tangent plane + transverse normal-curvature continuity to the planar shoulder; exact polynomial first/second jets sampled at 33 parameters per side.");+ }++ private static BlendQualityMetrics MeasureQuality(BlendBoundaryOperation operation, int order, int controlCount)+ {+ var bending = 0d; var variation = 0d; var footprint = 0; var previous = new double?[MetricSamples, MetricSamples];+ var du = 1d / (MetricSamples - 1d); var dv = du;+ for (var i = 0; i < MetricSamples; i++) for (var j = 0; j < MetricSamples; j++)+ {+ var jet = Jet(operation, order, i * du, j * dv);+ var cross = jet.Du.Cross(jet.Dv); var area = cross.Length;+ if (!cross.TryNormalize(out var normal) || area <= 1e-14d) continue;+ var E = jet.Du.Dot(jet.Du); var F = jet.Du.Dot(jet.Dv); var G = jet.Dv.Dot(jet.Dv); var det = E * G - F * F;+ var e = jet.Duu.Dot(normal); var f = jet.Duv.Dot(normal); var g = jet.Dvv.Dot(normal);+ var mean = (e * G - 2d * f * F + g * E) / (2d * det);+ var gaussian = (e * g - f * f) / det;+ var discriminant = double.Sqrt(double.Max(0d, mean * mean - gaussian));+ var k1 = mean + discriminant; var k2 = mean - discriminant;+ bending += (k1 * k1 + k2 * k2) * area * du * dv;+ previous[i, j] = mean;+ if (operation.CrownHeight * Shape(order, i * du) * Shape(order, j * dv) > operation.CrownHeight * .01d) footprint++;+ if (i > 0 && previous[i - 1, j].HasValue) variation += double.Abs(mean - previous[i - 1, j]!.Value);+ if (j > 0 && previous[i, j - 1].HasValue) variation += double.Abs(mean - previous[i, j - 1]!.Value);+ }+ var characteristic = double.Sqrt(operation.RegionWidth * operation.RegionDepth);+ var changed = footprint / (double)(MetricSamples * MetricSamples);+ return new(bending, variation * characteristic / (MetricSamples * MetricSamples), changed, controlCount * controlCount,+ 0d, 0d, 0d, 0d, 0d);+ }++ private static MaterializedBlendCandidate[] Normalize(IReadOnlyList<MaterializedBlendCandidate> eligible, BlendJudgmentPolicy policy)+ {+ static double PreferLow(double value, double min, double max) => max - min <= 1e-15d ? 1d : 1d - Utility.Remap(value, min, max);+ var bendMin = eligible.Min(c => c.RawMetrics.BendingEnergy); var bendMax = eligible.Max(c => c.RawMetrics.BendingEnergy);+ var variationMin = eligible.Min(c => c.RawMetrics.CurvatureVariation); var variationMax = eligible.Max(c => c.RawMetrics.CurvatureVariation);+ var footprintMin = eligible.Min(c => c.RawMetrics.ChangedAreaFraction); var footprintMax = eligible.Max(c => c.RawMetrics.ChangedAreaFraction);+ var complexityMin = eligible.Min(c => c.RawMetrics.ControlPointCount); var complexityMax = eligible.Max(c => c.RawMetrics.ControlPointCount);+ return eligible.Select(candidate =>+ {+ var raw = candidate.RawMetrics;+ var fairness = PreferLow(raw.BendingEnergy, bendMin, bendMax);+ var smoothness = PreferLow(raw.CurvatureVariation, variationMin, variationMax);+ var compactness = PreferLow(raw.ChangedAreaFraction, footprintMin, footprintMax);+ var complexity = PreferLow(raw.ControlPointCount, complexityMin, complexityMax);+ var utility = Utility.Weighted((fairness, policy.FairnessWeight), (smoothness, policy.CurvatureVariationWeight),+ (compactness, policy.CompactnessWeight), (complexity, policy.ComplexityWeight));+ return candidate with { RawMetrics = raw with { Fairness = fairness, CurvatureSmoothness = smoothness, Compactness = compactness, Complexity = complexity, Utility = utility } };+ }).ToArray();+ }++ private static BlendJudgmentTrace Trace(BlendBoundaryOperation operation, IReadOnlyList<MaterializedBlendCandidate> candidates,+ MaterializedBlendCandidate? selected, bool manual, BlendContinuity activeRequirement)+ {+ var ids = string.Join('|', candidates.Select(candidate => candidate.CandidateId));+ var candidateSet = BodyStateId.Derive(operation.Canonical + "|" + ids).Value.Replace("state-", "blend-set-", StringComparison.Ordinal);+ return new($"Preferred {operation.PreferredContinuity}; minimum {operation.MinimumContinuity}; active {activeRequirement} between {operation.SupportA} and {operation.SupportB}",+ operation.EffectivePolicy.PolicyId, candidateSet, selected?.CandidateId, manual,+ "Highest composite utility; ties use lower materialized control-point count, then ordinal CandidateId.",+ candidates.Select(candidate => new BlendCandidateTrace(candidate.CandidateId, "symmetric polynomial Bezier power transition",+ new Dictionary<string, string>(StringComparer.Ordinal) { ["EdgeVanishingOrder"] = candidate.EdgeOrder.ToString(), ["RegionWidthMm"] = operation.RegionWidth.ToString("R"), ["RegionDepthMm"] = operation.RegionDepth.ToString("R"), ["CrownHeightMm"] = operation.CrownHeight.ToString("R") },+ candidate.Capability, candidate.Patch.ExportClass, candidate.Patch.Spline.DegreeU, candidate.Patch.Spline.DegreeV,+ candidate.RawMetrics.ControlPointCount,+ selected?.CandidateId == candidate.CandidateId ? BlendCandidateDisposition.Selected : candidate.IsAdmissible && candidate.Capability >= activeRequirement ? BlendCandidateDisposition.Eligible : BlendCandidateDisposition.Rejected,+ candidate.IsAdmissible && candidate.Capability < activeRequirement ? $"Continuity capability {candidate.Capability} is below active {activeRequirement}." : candidate.RejectionReason,+ candidate.BoundaryEvidence, candidate.IsAdmissible && candidate.Capability >= activeRequirement ? candidate.RawMetrics : null)).ToArray());+ }++ private static BlendBoundaryResult Failure(BlendBoundaryOperation operation, IReadOnlyList<SculptDiagnostic> diagnostics,+ BlendJudgmentTrace? trace = null) => new(false, null, null, trace ?? new($"{operation.PreferredContinuity} between {operation.SupportA} and {operation.SupportB}",+ operation.EffectivePolicy.PolicyId, "<not-generated>", null, false, "No selection.", []), diagnostics);++ private static PatchJet2 Jet(BlendBoundaryOperation operation, int order, double u, double v)+ {+ var gu = Shape(order, u); var gv = Shape(order, v); var gpu = ShapeFirst(order, u); var gpv = ShapeFirst(order, v);+ var gppu = ShapeSecond(order, u); var gppv = ShapeSecond(order, v); var h = operation.CrownHeight;+ return new(new(-operation.RegionWidth / 2d + operation.RegionWidth * u, -operation.RegionDepth / 2d + operation.RegionDepth * v, operation.InfluenceEnvelope.MinZ + h * gu * gv),+ new(operation.RegionWidth, 0d, h * gpu * gv), new(0d, operation.RegionDepth, h * gu * gpv),+ new(0d, 0d, h * gppu * gv), new(0d, 0d, h * gpu * gpv), new(0d, 0d, h * gu * gppv), DifferentialSingularityKind.Regular);+ }++ private static double Shape(int order, double t) => double.Pow(4d * t * (1d - t), order);+ private static double ShapeFirst(int order, double t)+ {+ var q = t * (1d - t); return double.Pow(4d, order) * order * double.Pow(q, order - 1) * (1d - 2d * t);+ }+ private static double ShapeSecond(int order, double t)+ {+ var q = t * (1d - t); var a = order == 1 ? 1d : double.Pow(q, order - 2);+ return double.Pow(4d, order) * order * (a * ((order - 1d) * (1d - 2d * t) * (1d - 2d * t) - 2d * q));+ }+ private static double Binomial(int n, int k) { var result = 1d; for (var i = 1; i <= k; i++) result = result * (n - (k - i)) / i; return result; }+ private static IReadOnlyList<Point3D> SamplePatch(BoundedSurfacePatch patch, int count) => Enumerable.Range(0, count).SelectMany(i => Enumerable.Range(0, count).Select(j => patch.Evaluate(i / (count - 1d), j / (count - 1d)))).ToArray();+ private sealed record BlendSelectionContext(IReadOnlyList<MaterializedBlendCandidate> Candidates);+}diff --git a/Aetheris.Surfacing/SculptingAuthoring.cs b/Aetheris.Surfacing/SculptingAuthoring.csindex ec6ca839..4b4aada9 100644--- a/Aetheris.Surfacing/SculptingAuthoring.cs+++ b/Aetheris.Surfacing/SculptingAuthoring.cs@@ -60,8 +60,9 @@ public static class SculptingAuthoringif (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();var replaceBlock = Blocks(block.Body, "ReplaceRegion").SingleOrDefault();+ var blendBlock = Blocks(block.Body, "BlendBoundary").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 (new[] { operationBlock, replaceBlock, blendBlock, holeBlock }.Count(x => x is not null) != 1) { diagnostics.Add(new("sculpt-operation-unsupported", $"SculptState '{block.Name}' requires exactly one OffsetRegion, ReplaceRegion, BlendBoundary, 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;@@ -95,6 +96,32 @@ public static class SculptingAuthoringelse if (!states.TryAdd(block.Name, replaceResult.OutputState)) diagnostics.Add(new("sculpt-state-duplicate", $"State '{block.Name}' is declared more than once."));continue;}+ if (blendBlock is not null)+ {+ var between = List(blendBlock.Body, "Between"); var regionName = ScalarText(blendBlock.Body, "Region") ?? string.Empty;+ var preferredText = ScalarText(blendBlock.Body, "Preferred") ?? ScalarText(blendBlock.Body, "Continuity") ?? "G2";+ var minimumText = ScalarText(blendBlock.Body, "Minimum") ?? preferredText;+ var size = Vector(blendBlock.Body, "RegionSize", 2, diagnostics); var height = Length(blendBlock.Body, "Height", diagnostics);+ var blendEnvelope = Vector(blendBlock.Body, "InfluenceEnvelope", 6, diagnostics);+ var blendMayModify = List(block.Body, "MayModify"); var blendPreserve = List(block.Body, "Preserve");+ var blendRequirements = ParseRequirements(List(block.Body, "Require"), diagnostics);+ var policyText = ScalarText(blendBlock.Body, "Policy") ?? "StandardBlendJudgment";+ var useCandidate = ScalarText(blendBlock.Body, "UseCandidate"); var maximumDegree = Integer(blendBlock.Body, "MaximumDegree") ?? 10;+ operationClock.Stop(); opConstruction += operationClock.Elapsed;+ if (between.Count != 2) diagnostics.Add(new("surf-blend-supports-invalid", $"BlendBoundary in '{block.Name}' requires exactly two Between supports."));+ if (!Enum.TryParse<BlendContinuity>(preferredText, true, out var preferred)) diagnostics.Add(new("surf-blend-continuity-invalid", $"Preferred continuity '{preferredText}' must be G0, G1, or G2."));+ if (!Enum.TryParse<BlendContinuity>(minimumText, true, out var minimum)) diagnostics.Add(new("surf-blend-continuity-invalid", $"Minimum continuity '{minimumText}' must be G0, G1, or G2."));+ if (!StringComparer.Ordinal.Equals(policyText, "StandardBlendJudgment")) diagnostics.Add(new("surf-blend-policy-unresolved", $"Blend policy '{policyText}' is not defined; use StandardBlendJudgment."));+ if (between.Count != 2 || size is null || height is null || blendEnvelope is null || !Enum.TryParse<BlendContinuity>(preferredText, true, out preferred)+ || !Enum.TryParse<BlendContinuity>(minimumText, true, out minimum) || !StringComparer.Ordinal.Equals(policyText, "StandardBlendJudgment")) continue;+ var blendOperation = new BlendBoundaryOperation(block.Name + ".BlendBoundary", between[0], between[1], regionName, preferred, minimum,+ size[0], size[1], height.Value, blendMayModify, new(blendEnvelope[0], blendEnvelope[1], blendEnvelope[2], blendEnvelope[3], blendEnvelope[4], blendEnvelope[5]),+ blendPreserve.Select(Preservation).ToArray(), blendRequirements, BlendJudgmentPolicy.StandardBlendJudgment, useCandidate, maximumDegree);+ var blendClock = Stopwatch.StartNew(); var blendResult = BlendBoundarySculptor.Apply(input, block.Name, blendOperation); blendClock.Stop(); verification += blendClock.Elapsed;+ if (!blendResult.IsSuccess || blendResult.OutputState is null) diagnostics.AddRange(blendResult.Diagnostics);+ else if (!states.TryAdd(block.Name, blendResult.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);@@ -145,6 +172,11 @@ public static class SculptingAuthoring}private static int MatchingBrace(string source, int open) { var depth = 0; var quoted = false; for (var i = open; i < source.Length; i++) { if (source[i] == '"' && (i == 0 || source[i - 1] != '\\')) quoted = !quoted; if (quoted) continue; if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) return i; } return -1; }private static string? ScalarText(string body, string field) { var m = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(field)}\s*:\s*(?<v>[A-Za-z_]\w*)\s*$", RegexOptions.CultureInvariant); return m.Success ? m.Groups["v"].Value : null; }+ private static int? Integer(string body, string field)+ {+ var match = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(field)}\s*:\s*(?<v>\d+)\s*$", RegexOptions.CultureInvariant);+ return match.Success && int.TryParse(match.Groups["v"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out var value) ? value : null;+ }private static double? Length(string body, string field, List<SculptDiagnostic> diagnostics){var m = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(field)}\s*:\s*(?<v>[-+]?\d+(?:\.\d+)?)mm\s*$", RegexOptions.CultureInvariant);@@ -209,7 +241,11 @@ public static class SculptingAuthoring{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; }+ if (!Enum.TryParse<PatchBoundaryContinuity>(continuityText, true, out var continuity) || continuity == PatchBoundaryContinuity.G2)+ {+ diagnostics.Add(new("surf-boundary-continuity-invalid", $"Direct SurfacePatch boundary '{block.Name}' continuity must be G0 or G1; use BlendBoundary for qualified G2 construction and evidence."));+ continue;+ }result.Add(new($"Boundary{block.Name}", side, existing, continuity));}return result;diff --git a/Aetheris.Surfacing/SculptingExecution.cs b/Aetheris.Surfacing/SculptingExecution.csindex 57b76008..31958b7b 100644--- a/Aetheris.Surfacing/SculptingExecution.cs+++ b/Aetheris.Surfacing/SculptingExecution.cs@@ -43,7 +43,7 @@ public static class SculptedHousingFactoryvar 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."),+ [TransitionZone] = new(TransitionZone, SculptEntityKind.Region, $"transition:z={c.BaseHeight:R}..{c.FinalHeight:R}", "Bounded 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."),@@ -210,6 +210,12 @@ public static class OffsetRegionSculptorpublic static class ReplaceRegionSculptor{public static SculptResult Apply(BodyState input, string outputName, ReplaceRegionOperation operation)+ => ApplyCore(input, outputName, operation, null);++ internal static SculptResult ApplyWithCertifiedPolynomialBounds(BodyState input, string outputName, ReplaceRegionOperation operation, SpatialInfluenceEnvelope certifiedBounds)+ => ApplyCore(input, outputName, operation, certifiedBounds);++ private static SculptResult ApplyCore(BodyState input, string outputName, ReplaceRegionOperation operation, SpatialInfluenceEnvelope? certifiedBounds){ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);var diagnostics = operation.ReplacementPatch.Validate().ToList();@@ -271,10 +277,16 @@ public static class ReplaceRegionSculptorvar sampled = Sample(operation.ReplacementPatch, 17);var maximumZ = sampled.Max(x => x.Z);- var envelopePoints = operation.ReplacementPatch is BSplineSurfacePatch splinePatch+ var envelopePoints = operation.ReplacementPatch is BSplineSurfacePatch splinePatch && certifiedBounds is null? 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)),+ var actual = certifiedBounds ?? 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 (certifiedBounds is { } certified)+ {+ var observed = new SpatialInfluenceEnvelope(sampled.Min(point => point.X), sampled.Min(point => point.Y), sampled.Min(point => point.Z),+ sampled.Max(point => point.X), sampled.Max(point => point.Y), sampled.Max(point => point.Z));+ if (!certified.Contains(observed, operation.GeometricTolerance)) diagnostics.Add(new("surf-certified-bounds-invalid", "The supplied exact patch-bounds certificate does not contain deterministic surface samples."));+ }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."));@@ -284,12 +296,20 @@ public static class ReplaceRegionSculptorvar 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)+ if (boundary.Continuity is PatchBoundaryContinuity.G1 or PatchBoundaryContinuity.G2){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 (boundary.Continuity == PatchBoundaryContinuity.G2)+ {+ var curvature = MeasurePlanarBoundarySecondDifference(operation.ReplacementPatch, boundary.PatchSide);+ var g2Ok = curvature <= operation.G2CurvatureTolerance;+ evidence.Add(new($"Boundary:{boundary.StableId}:G2", g2Ok, LocalityEvidenceLevel.ExactAnalytic, curvature, operation.G2CurvatureTolerance,+ $"Exact clamped B-spline boundary control-net second-difference evidence is {curvature:R}; zero proves transverse normal-curvature equality to the planar shoulder."));+ if (!g2Ok) diagnostics.Add(new("surf-boundary-g2-violation", $"Boundary '{boundary.StableId}' has planar normal-curvature control residual {curvature:R}, exceeding {operation.G2CurvatureTolerance:R}.", boundary.StableId));+ }}if (diagnostics.Count > 0) return SculptResult.Failure(diagnostics, evidence);@@ -322,7 +342,7 @@ public static class ReplaceRegionSculptorvar 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."))+ .Append(new(SculptedHousingFactory.CrownRegion, GeometricChangeKind.Replaced, [operation.ReplacementPatch.PatchId], "Explicit outer-loop boundary correspondence; declared G0/G1/G2 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);@@ -379,6 +399,20 @@ public static class ReplaceRegionSculptorreturn (g0, g1);}+ private static double MeasurePlanarBoundarySecondDifference(BoundedSurfacePatch patch, PatchBoundarySide side)+ {+ if (patch is not BSplineSurfacePatch spline) return double.PositiveInfinity;+ var points = spline.Spline.ControlPoints; var uCount = points.Count; var vCount = points[0].Count;+ IEnumerable<Vector3D> differences = side switch+ {+ PatchBoundarySide.South => Enumerable.Range(0, uCount).Select(i => (points[i][2] - points[i][1]) - (points[i][1] - points[i][0])),+ PatchBoundarySide.North => Enumerable.Range(0, uCount).Select(i => (points[i][vCount - 3] - points[i][vCount - 2]) - (points[i][vCount - 2] - points[i][vCount - 1])),+ PatchBoundarySide.West => Enumerable.Range(0, vCount).Select(j => (points[2][j] - points[1][j]) - (points[1][j] - points[0][j])),+ _ => Enumerable.Range(0, vCount).Select(j => (points[uCount - 3][j] - points[uCount - 2][j]) - (points[uCount - 2][j] - points[uCount - 1][j]))+ };+ return differences.Max(vector => vector.Length);+ }+private static SculptValidationEvidence VerifySharedBoundaryTopology(BrepBody body){var counts = body.Topology.Coedges.GroupBy(x => x.EdgeId).ToDictionary(x => x.Key, x => x.Count());diff --git a/Aetheris.Surfacing/SculptingState.cs b/Aetheris.Surfacing/SculptingState.csindex 395a1369..1c7fdddb 100644--- a/Aetheris.Surfacing/SculptingState.cs+++ b/Aetheris.Surfacing/SculptingState.cs@@ -39,7 +39,8 @@ public sealed record GeometricDelta(IReadOnlyList<string> Introduces,IReadOnlyList<string> AuthorizedRegion,SpatialInfluenceEnvelope InfluenceEnvelope,- IReadOnlyList<GeometricDeltaEntry> Correspondence);+ IReadOnlyList<GeometricDeltaEntry> Correspondence,+ BlendJudgmentProvenance? BlendJudgment = null);public sealed record SculptValidationEvidence(string Check,@@ -81,7 +82,8 @@ public sealed record BodyState(IReadOnlyList<SculptValidationEvidence> ValidationEvidence,IReadOnlyList<PersistentGeometryAssociation>? GeometryAssociations = null,IReadOnlyList<Step242SemanticPmi>? SemanticPmi = null,- IReadOnlyList<SculptAssemblyInterface>? AssemblyInterfaces = null)+ IReadOnlyList<SculptAssemblyInterface>? AssemblyInterfaces = null,+ BlendJudgmentTrace? BlendJudgment = null){public IReadOnlyList<SurfacePatchMetadata> SurfacePatches => Construction.ReplacementPatch is { } patch? [SurfacePatchMetadata.From(patch, Body.Topology.Faces.FirstOrDefault(face =>@@ -116,7 +118,8 @@ public sealed record ReplaceRegionOperation(IReadOnlyList<PreservationContract> Preserves,IReadOnlyList<SculptRequirement> Requirements,double GeometricTolerance = 1e-6,- double G1AngularToleranceDegrees = 0.1)+ double G1AngularToleranceDegrees = 0.1,+ double G2CurvatureTolerance = 1e-6){public string Canonical => string.Join('|', StableId, TargetRegion, ReplacementPatch.PatchId,ReplacementPatch.SurfaceClass, ReplacementPatch.DegreeU, ReplacementPatch.DegreeV,@@ -126,7 +129,7 @@ public sealed record ReplaceRegionOperation(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"));+ string.Join(',', Requirements.Order()), GeometricTolerance.ToString("R"), G1AngularToleranceDegrees.ToString("R"), G2CurvatureTolerance.ToString("R"));}public sealed record SafeHoleOperation(diff --git a/Aetheris.Surfacing/SurfacePatchIr.cs b/Aetheris.Surfacing/SurfacePatchIr.csindex a2af12e0..ddcb7a88 100644--- a/Aetheris.Surfacing/SurfacePatchIr.cs+++ b/Aetheris.Surfacing/SurfacePatchIr.cs@@ -12,7 +12,7 @@ public readonly record struct SurfaceParameterDomain(double UMin, double UMax, dpublic enum SurfacePatchClass { Analytic, NonRationalBSpline, InternalRationalNormalized }public enum PatchBoundarySide { South, East, North, West }-public enum PatchBoundaryContinuity { G0, G1 }+public enum PatchBoundaryContinuity { G0, G1, G2 }public sealed record PatchBoundaryCorrespondence(string StableId,diff --git a/Aetheris.Surfacing/SurfacingModule.cs b/Aetheris.Surfacing/SurfacingModule.csindex 28618134..2bea0104 100644--- a/Aetheris.Surfacing/SurfacingModule.cs+++ b/Aetheris.Surfacing/SurfacingModule.cs@@ -13,6 +13,7 @@ public static class SurfacingModulepublic const string BoundaryPatchCapability = "Surfacing.BoundaryPatch";public const string PanelCapability = "Surfacing.Panel";public const string BoundedSculptingCapability = "Surfacing.BoundedSculpting";+ public const string JudgedBlendCapability = "Surfacing.JudgedBlend";public static AetherisModule Definition { get; } = new(Id, "Surfacing", Version,@@ -22,9 +23,10 @@ public static class SurfacingModulenew(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 and trimmed ReplaceRegion authority, qualified intersection-derived boundaries, face-local pcurves, inner openings, imported-face grafting, mixed G0/G1 contracts, persistent associations, and inspectable GeometricDelta evidence.")],+ new(BoundedSculptingCapability,Id,Version,"Immutable single-predecessor BodyState derivation with bounded OffsetRegion and trimmed ReplaceRegion authority, qualified intersection-derived boundaries, face-local pcurves, inner openings, imported-face grafting, mixed G0/G1/G2 contracts, persistent associations, and inspectable GeometricDelta evidence."),+ new(JudgedBlendCapability,Id,Version,"Qualified crown-to-planar-shoulder BlendBoundary with exact polynomial G1/G2 candidates, validity-before-utility fairness judgment, deterministic trace, and rational-free STEP realization.")],["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-boundary-g0-violation","surf-boundary-g1-violation","surf-selector-target-replaced","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-boundary-g2-violation","surf-blend-g2-unsatisfied","surf-blend-no-eligible-candidates","surf-blend-locality-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.mdindex 21788537..78dbfb89 100644--- a/docs/public/firmament/sculpting.md+++ b/docs/public/firmament/sculpting.md@@ -1,6 +1,6 @@# Bounded mathematical sculpting and patch replacement-SURF-X0 supports bounded mathematical sculpting and locality-preserving region modification. SURF-X1 adds direct rectangular patch replacement. SURF-X1a closes the trim path for the admitted housing: qualified surface intersections derive the outer boundary, face-local pcurves qualify every trim, circular inner loops preserve openings, and an imported `ADVANCED_FACE` can receive a bounded support-surface graft. This is not full general surfacing.+SURF-X0 supports bounded mathematical sculpting and locality-preserving region modification. SURF-X1 adds direct rectangular patch replacement. SURF-X1a closes the trim path for the admitted housing: qualified surface intersections derive the outer boundary, face-local pcurves qualify every trim, circular inner loops preserve openings, and an imported `ADVANCED_FACE` can receive a bounded support-surface graft. SURF-X2 adds a qualified two-support crown-to-planar-shoulder `BlendBoundary` that generates and deterministically judges exact non-rational polynomial candidates. 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.@@ -124,6 +124,54 @@ An ordinary safe cylindrical `HoleFeature` can follow replacement on a survivingFor 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.+## X2 judged blend authoring++Use `BlendBoundary` when the admitted housing crown must transition into its preserved planar top shoulder under an explicit continuity and quality policy. The canonical witness is [`surf-x2-judged-housing.firmament`](../../../fixtures/Canonical/Sculpting/surf-x2-judged-housing.firmament).++```firmament+SculptState JudgedCrown {+ Input: Base+ BlendBoundary {+ Between: [HousingCrown, PlanarTopShoulder]+ Region: CrownTransitionZone+ Preferred: G2+ Minimum: G2+ RegionSize: [80mm, 50mm]+ Height: 8mm+ MaximumDegree: 10+ Policy: StandardBlendJudgment+ InfluenceEnvelope: [-40mm, -25mm, 20mm, 40mm, 25mm, 28mm]+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary, SideWallsLower]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+}+```++The qualified candidates are tensor-product polynomial Bézier patches++```text+z(u,v) = baseZ + height * g_m(u) * g_m(v)+g_m(t) = 4^m [t(1-t)]^m+```++with edge-vanishing orders `m=2,3,4,5`. They are genuinely different curvature distributions and materialize as degrees 4, 6, 8, and 10 with 25, 49, 81, and 121 control points. `m=2` is G1 but not G2; `m>=3` has zero first and second transverse derivatives at all four shoulder boundaries.++Aetheris' bounded X2 G2 contract is precise: boundary positions coincide, tangent planes coincide, and the transition's transverse normal curvature equals the planar shoulder's zero normal curvature. Exact polynomial first and second jets are evaluated at 33 deterministic parameters per side. This formulation does not claim principal-direction matching, arbitrary cross-boundary reparameterization, or general G2 between unrelated supports.++Candidate processing is strictly ordered:++```text+construct -> normalize to non-rational B-spline -> validate trim/BRep/pcurves+ -> validate continuity/locality/preservation -> score -> select -> ReplaceRegion+```++An invalid candidate never receives utility. The standard policy scores only eligible candidates with documented weights: bending fairness `0.40`, mean-curvature variation `0.30`, changed-area compactness `0.20`, and materialized control-point complexity `0.10`. Bending fairness is the deterministic 25×25 quadrature of `integral(k1^2+k2^2)dA`; curvature variation sums adjacent mean-curvature changes on the same grid. Considerations are min/max normalized within the canonical candidate set and clamped to `[0,1]`. Highest composite utility wins; ties use lower actual control-point count, then ordinal `CandidateId`.++`Preferred: G2, Minimum: G1` explicitly permits fallback. `Minimum: G2` never does. `MaximumDegree` is a hard representation gate, not a scoring preference. `UseCandidate: PowerM4Degree8` may override policy only when that candidate is eligible for the active continuity request. JSON build/inspect output and the sibling `.delta.json` retain the policy ID, candidate-set ID, rejected and eligible candidates, boundary evidence, considerations, score, selected ID, and whether selection was overridden.++This utility judgment is a repeatable engineering selector, not proof of aesthetic superiority. Review highlight flow, unexpected flat spots, curvature bumps, creases, symmetry, locality, and mounting-interface preservation in a capable STEP viewer before aesthetic approval.+## Guarantees and evidenceThe housing lane verifies:@@ -151,4 +199,4 @@ The X0 housing emits only `PLANE` and `CYLINDRICAL_SURFACE`. The X1 flagship add## Current limits-The admitted X1a materializer is limited to rectangular housing-top replacement, four qualified boundary intersections, and circular inner openings whose existing 3D edges lie on the replacement support. It does not provide arbitrary intersection networks, general Cylinder/B-spline or B-spline/B-spline discovery, arbitrary nested islands, G2, Blend, Loft, Shell, Draft, fitting, fairness optimization, or arbitrary patch networks. Direct Firmament patch authoring admits the non-rational B-spline form only; imported replacement is an advanced API path over an already imported BRep.+The admitted X2 materializer is limited to one rectangular housing crown transitioning to its coplanar analytic shoulder through the exact polynomial family above. It does not provide arbitrary intersection networks, general Plane/Cylinder or Cylinder/Cylinder blends, general Cylinder/B-spline or B-spline/B-spline discovery, arbitrary nested islands, variable blend laws, a free control-net optimizer, N-way junctions, Loft, Shell, Draft, or arbitrary patch networks. Existing exact Fillet and Chamfer authoring and materializers are unchanged: a fillet is conceptually a constrained blend specialization, while a planar chamfer should remain planar rather than being forced through freeform machinery.diff --git a/docs/public/reference/diagnostics.md b/docs/public/reference/diagnostics.mdindex 4f1db927..c4e523cb 100644--- a/docs/public/reference/diagnostics.md+++ b/docs/public/reference/diagnostics.md@@ -21,6 +21,13 @@- `surf-imported-selector-unresolved`: a STEP `ADVANCED_FACE` identity does not resolve to exactly one current face.- `surf-association-target-removed`: PMI or an Assembly Interface has no explicit `Preserved` correspondence; Aetheris refuses name- or proximity-based rebinding.- `surf-association-current-geometry-missing`: an explicitly preserved association references a face absent from the output `BodyState`.+- `surf-blend-g2-unsatisfied`: a constructible blend candidate fails the hard transverse normal-curvature contract and is rejected before scoring.+- `surf-blend-candidate-rejected`: compact per-candidate evidence emitted when the complete request has no selectable candidate.+- `surf-blend-no-eligible-candidates`: representation, continuity, topology, locality, or preservation gates leave no candidate at the declared minimum continuity.+- `surf-blend-override-ineligible`: `UseCandidate` names an absent candidate or one that fails the active hard requirements.+- `surf-blend-locality-violation`: a candidate exceeds the authorized transition envelope and cannot enter utility judgment.+- `surf-boundary-g2-violation`: realized exact boundary second-difference evidence exceeds the planar-shoulder normal-curvature tolerance.+- `surf-certified-bounds-invalid`: a claimed exact polynomial bounds certificate does not contain deterministic surface samples.- `surf-selector-target-replaced`: a historical native or imported selector has an explicit successor and cannot be reused.Start with `aetheris validate source.firmament --json`; use `build` when geometry, AP242, assertions, or artifacts are involved. A diagnostic code is the stable automation key, while its message identifies the value/target and expected category where useful.diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.mdindex 4d4e8d21..dae70bb6 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-X1a subset) | Immutable single-predecessor `BodyState`; rectangular-housing `OffsetRegion`; direct or imported-face `ReplaceRegion`; qualified Plane/Plane, normal Plane/Cylinder, and Plane/non-rational-B-spline boundary intersections; face-local pcurves; circular inner loops; bounded support extension; exact lower-body locality; AP242 PMI/interface geometry associations; and rational-free STEP. General surface networks remain unsupported. See the [sculpting guide](../firmament/sculpting.md). |+| Bounded mathematical sculpting | Bounded (SURF-X2 subset) | Immutable single-predecessor `BodyState`; rectangular-housing `OffsetRegion`; direct or imported-face `ReplaceRegion`; qualified crown-to-planar-shoulder `BlendBoundary` with hard G1/G2 evidence, four deterministic polynomial candidates, fairness/curvature/compactness/complexity judgment, override/fallback trace, qualified intersections and pcurves, exact lower-body locality, AP242 association persistence, and rational-free STEP. General blend networks 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). |diff --git a/docs/release/SURF-X2-GENERALIZED-BLEND-FAIRNESS.md b/docs/release/SURF-X2-GENERALIZED-BLEND-FAIRNESS.mdnew file mode 100644index 00000000..a6d17712--- /dev/null+++ b/docs/release/SURF-X2-GENERALIZED-BLEND-FAIRNESS.md@@ -0,0 +1,98 @@+# SURF-X2 generalized blend and fairness judgment++## Executive verdict++**Meaningful progression.** Aetheris can generate and deterministically choose among high-quality G1/G2 transition surfaces for the qualified two-support housing-crown/planar-shoulder lane, and the selected patch flows through the real SURF-X1a trim, pcurve, `BodyState`, preservation, and rational-free STEP path. The broader SURF-X2 surface-pair matrix and variable-law scope are not complete, so this report does not claim general production blend support.++## Blend mathematics++Candidate `m` is the exact tensor-product graph++```text+x = -width/2 + width*u+y = -depth/2 + depth*v+z = baseZ + height * g_m(u) * g_m(v)+g_m(t) = 4^m [t(1-t)]^m+```++for `m=2..5`. It is emitted exactly as a clamped, single-span, non-rational polynomial B-spline of degree `2m`. `m=2` has zero first but nonzero second transverse derivative at a shoulder and is G1-only. `m>=3` has zero first and second transverse derivatives.++The bounded G2 contract is position equality, tangent-plane equality, and transverse normal-curvature equality to the planar shoulder at 33 fixed parameters per side. It is a normal-curvature formulation; it does not claim global principal-direction compatibility. Candidate evidence uses analytic polynomial jets. The realized selected B-spline is independently checked from its clamped boundary control-net second differences.++Fairness is a fixed 25×25 quadrature of `integral(k1^2+k2^2)dA`. Curvature variation is the normalized sum of adjacent mean-curvature differences. Compactness is the sampled fraction above one percent of requested height. Complexity is the actual post-normalization control-point count. No numerical optimizer is used, so convergence and stochastic-seed concerns do not apply.++## Judgment policy++Every candidate is normalized to a non-rational B-spline, materialized through the housing BRep builder, and gated for requested continuity, degree limit, trim contract, pcurves, manifold validity, self-intersection evidence, locality, and preserved semantics before scoring. `StandardBlendJudgment/v1` weights fairness `0.40`, curvature variation `0.30`, compactness `0.20`, and complexity `0.10`. Considerations use deterministic candidate-set min/max normalization and `[0,1]` clamping. Highest utility wins; equal utility uses lower materialized control-point count and then ordinal `CandidateId`. Source/generation order is not a tie-break.++An explicit `Preferred: G2, Minimum: G1` permits fallback. Exact `Minimum: G2` fails if no G2 candidate survives. `UseCandidate` can select a different eligible candidate and is recorded as a manual override.++## Flagship candidate evidence++Input: `100 × 80 × 20 mm` housing, `80 × 50 mm` authorized transition, `8 mm` crown height, four protected mounting holes. Values below are from the canonical CLI build.++| Candidate | Eligible for G2 | G1 error (deg) | G2 error (1/mm) | Bending energy | Curvature variation | Footprint | Controls | Utility |+|---|---:|---:|---:|---:|---:|---:|---:|---:|+| `PowerM2Degree4` | no | 0 | 0.1024 | — | — | — | 25 | — |+| `PowerM3Degree6` | yes, selected | 0 | 0 | 4.1367937876 | 0.3846414874 | 0.6544 | 49 | 0.800000 |+| `PowerM4Degree8` | yes | 0 | 0 | 4.7605539756 | 0.3946031772 | 0.5392 | 81 | 0.604060 |+| `PowerM5Degree10` | yes | 0 | 0 | 5.4642390046 | 0.4139407492 | 0.4880 | 121 | 0.200000 |++`PowerM3Degree6` won because it has the lowest bending energy and curvature variation and the lowest G2-eligible representation complexity. The more compact higher-order candidates do not recover enough compactness utility to offset their curvature and complexity costs. The G1 candidate is rejected, not assigned a low score.++## Realized geometry and preservation++The selected candidate is committed through `ReplaceRegionSculptor`. The realized BRep has shared trim edges, two pcurves per edge, valid orientation, edge incidence two, and no preflight errors. Independent locality comparison below `z=20 mm` reports zero deviation and identical lower planes/cylinders/circular trims. `BottomMountingInterface`, `MountingHolePattern`, `OuterFootprintBoundary`, and `SideWallsLower` retain exact semantic fingerprints; AP242 association remapping uses explicit correspondence.++Representation inventory:++```text+Planes: 6+Cylinders: 4+Cones: 0+Spheres: 0+Tori: 0+NonRationalBSplines: 1+RationalProductSurfaces: 0+```++The generated manual artifact is `artifacts/local/surf-x2/surf-x2-judged-blend-housing.step` (SHA-256 `4b5f4a0d36fef35af5f31c889496321d97cfd96a4276e6af56065c6401dd85c8`), with its sibling decision/provenance JSON. `candidate-a-g1.step` and `candidate-c-power-m4.step` provide additional local comparisons. Generated output remains ignored by policy.++## Human inspection++Automated utility is mathematical engineering evidence, not aesthetic approval. A human result has not yet been recorded. Inspect highlight flow, flat spots, curvature bumps, boundary creases, intended symmetry, transition locality, and mounting/interface preservation in a capable STEP viewer.++## Relationship to Fillet and Chamfer++Existing bounded Fillet and Chamfer implementations already use `JudgmentEngine` for their own admissible strategy choices. X2 does not gratuitously reroute them. A constant-radius Fillet is conceptually a more constrained generalized blend; a planar Chamfer is an exact planar transition and should not be lowered through a freeform B-spline when the analytic representation is better.++## Fresh-agent requests++| Request | Result in qualified lane |+|---|---|+| A — required G2 crown-to-side-support transition | `BlendBoundary`, hard G2 gate, candidate generation, judgment |+| B — prefer smoother with slightly larger patch | express with larger bounded `RegionSize`; standard fairness remains explicit; custom weight authoring is deferred |+| C — more compact without curvature spikes | higher-order eligible candidates expose compactness and curvature separately; custom weights are deferred |+| D — G2 mandatory or fail | `Minimum: G2`; regression proves no G1 fallback |+| E — explain selection | CLI JSON/text and `.delta.json` expose rejection, metrics, score, tie-break, and winner |+| F — export selected surface | STEP contains analytic supports plus one non-rational B-spline and zero rational product surfaces |++## Validation recorded during implementation++- Release build of the CLI dependency graph: passed with zero warnings/errors.+- Full serial .NET suite: 3,140 passed, zero failed. The legacy-gated FrictionLab assembly reports no discoverable tests under the ordinary solution invocation, consistent with its gate.+- Focused Firmament/SURF-X2 tests: 4 passed; focused CLI judgment-report test: 1 passed.+- Canonical qualification: 97 fixtures passed, including three X2 valid witnesses.+- Canonical real CLI build and STEP reimport: one enclosed body, 11 faces, 28 edges, 20 vertices, bounds `[-50,-40,0]` to `[50,40,28] mm`.+- Canonical surface inventory: 6 planes, 4 cylinders, 1 non-rational B-spline, 0 rational surfaces.+- Client: 82 tests, TypeScript/production build, and lint passed.+- VS Code extension: 13 tests, typecheck, build, and VSIX package passed.+- Fresh self-contained win-x64 CLI publish and canonical X2 validation passed.+- Repository layout guard (3,726 tracked files) and `git diff --check` passed.+- NativeAOT Forge validation was not rerun because Forge and its host/interop boundary were not changed.++Manual visual approval remains outstanding and is deliberately separate from mathematical utility evidence.++## Deferred scope++Plane/Cylinder and Cylinder/Cylinder generalized blends, general freeform-to-freeform boundaries, variable blend laws, bounded control-point optimization, candidate STEP fan-out, arbitrary imported-face blend authoring, and N-way junctions are not implemented. Fillet/Chamfer public semantics are unchanged.diff --git a/fixtures/Canonical/Sculpting/surf-x2-g1-blend.firmament b/fixtures/Canonical/Sculpting/surf-x2-g1-blend.firmamentnew file mode 100644index 00000000..21f5b4d5--- /dev/null+++ b/fixtures/Canonical/Sculpting/surf-x2-g1-blend.firmament@@ -0,0 +1,26 @@++Model QualifiedG1Blend {+ Units: mm+ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-47mm, -32mm]+ Diameter: 4mm }+ }+ SculptState G1Crown {+ Input: Base+ BlendBoundary {+ Between: [HousingCrown, PlanarTopShoulder]+ Region: CrownTransitionZone+ Preferred: G1+ Minimum: G1+ RegionSize: [80mm, 50mm]+ Height: 8mm+ MaximumDegree: 4+ Policy: StandardBlendJudgment+ InfluenceEnvelope: [-40mm, -25mm, 20mm, 40mm, 25mm, 28mm]+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary, SideWallsLower]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: G1Crown+}diff --git a/fixtures/Canonical/Sculpting/surf-x2-judged-housing.firmament b/fixtures/Canonical/Sculpting/surf-x2-judged-housing.firmamentnew file mode 100644index 00000000..2682c6ee--- /dev/null+++ b/fixtures/Canonical/Sculpting/surf-x2-judged-housing.firmament@@ -0,0 +1,35 @@++Model JudgedBlendHousing {+ Units: mm++ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-47mm, -32mm]+ Diameter: 4mm }+ Hole H2 { Center: [47mm, -32mm]+ Diameter: 4mm }+ Hole H3 { Center: [47mm, 32mm]+ Diameter: 4mm }+ Hole H4 { Center: [-47mm, 32mm]+ Diameter: 4mm }+ }++ SculptState JudgedCrown {+ Input: Base+ BlendBoundary {+ Between: [HousingCrown, PlanarTopShoulder]+ Region: CrownTransitionZone+ Preferred: G2+ Minimum: G2+ RegionSize: [80mm, 50mm]+ Height: 8mm+ MaximumDegree: 10+ Policy: StandardBlendJudgment+ InfluenceEnvelope: [-40mm, -25mm, 20mm, 40mm, 25mm, 28mm]+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary, SideWallsLower]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }++ Output: JudgedCrown+}diff --git a/fixtures/Canonical/Sculpting/surf-x2-manual-candidate.firmament b/fixtures/Canonical/Sculpting/surf-x2-manual-candidate.firmamentnew file mode 100644index 00000000..a6b463e6--- /dev/null+++ b/fixtures/Canonical/Sculpting/surf-x2-manual-candidate.firmament@@ -0,0 +1,27 @@++Model ManualEligibleBlendCandidate {+ Units: mm+ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-47mm, -32mm]+ Diameter: 4mm }+ }+ SculptState ManualCrown {+ Input: Base+ BlendBoundary {+ Between: [HousingCrown, PlanarTopShoulder]+ Region: CrownTransitionZone+ Preferred: G2+ Minimum: G2+ RegionSize: [80mm, 50mm]+ Height: 8mm+ MaximumDegree: 10+ Policy: StandardBlendJudgment+ UseCandidate: PowerM4Degree8+ InfluenceEnvelope: [-40mm, -25mm, 20mm, 40mm, 25mm, 28mm]+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary, SideWallsLower]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: ManualCrown+}diff --git a/fixtures/Invalid/Sculpting/surf-x2-g2-unsatisfied.firmament b/fixtures/Invalid/Sculpting/surf-x2-g2-unsatisfied.firmamentnew file mode 100644index 00000000..ed6328cf--- /dev/null+++ b/fixtures/Invalid/Sculpting/surf-x2-g2-unsatisfied.firmament@@ -0,0 +1,25 @@++Model G2UnsatisfiedBlend {+ Units: mm+ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-47mm, -32mm]+ Diameter: 4mm }+ }+ SculptState InvalidBlend {+ Input: Base+ BlendBoundary {+ Between: [HousingCrown, PlanarTopShoulder]+ Region: CrownTransitionZone+ Preferred: G2+ Minimum: G2+ RegionSize: [80mm, 50mm]+ Height: 8mm+ MaximumDegree: 4+ InfluenceEnvelope: [-40mm, -25mm, 20mm, 40mm, 25mm, 28mm]+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary, SideWallsLower]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: InvalidBlend+}diff --git a/fixtures/Invalid/Sculpting/surf-x2-locality-violation.firmament b/fixtures/Invalid/Sculpting/surf-x2-locality-violation.firmamentnew file mode 100644index 00000000..08e6a542--- /dev/null+++ b/fixtures/Invalid/Sculpting/surf-x2-locality-violation.firmament@@ -0,0 +1,24 @@++Model BlendLocalityViolation {+ Units: mm+ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-47mm, -32mm]+ Diameter: 4mm }+ }+ SculptState InvalidBlend {+ Input: Base+ BlendBoundary {+ Between: [HousingCrown, PlanarTopShoulder]+ Region: CrownTransitionZone+ Preferred: G2+ Minimum: G2+ RegionSize: [80mm, 50mm]+ Height: 8mm+ InfluenceEnvelope: [-40mm, -25mm, 20mm, 40mm, 25mm, 27mm]+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary, SideWallsLower]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: InvalidBlend+}