Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add analytic-first map provenance
Yuechen Li00a32bc2eb86
diff --git a/Aetheris.CLI.Tests/CliBaselineTests.cs b/Aetheris.CLI.Tests/CliBaselineTests.csindex 2d5de116..4c04444c 100644--- a/Aetheris.CLI.Tests/CliBaselineTests.cs+++ b/Aetheris.CLI.Tests/CliBaselineTests.cs@@ -525,7 +525,29 @@ public sealed class CliBaselineTestsAssert.Equal(25, root.GetProperty("samples").GetArrayLength());Assert.Equal(1d, root.GetProperty("summary").GetProperty("hitCoverage").GetDouble(), 8);Assert.Equal("plane", root.GetProperty("summary").GetProperty("surfaceFamiliesHit").EnumerateObject().Single().Name);- Assert.True(root.GetProperty("samples")[12].GetProperty("firstHit").GetProperty("position").GetProperty("z").GetDouble() > 0d);+ Assert.Equal("analytic-cir-tessellated-fallback", root.GetProperty("backendPolicy").GetString());+ Assert.True(root.GetProperty("summary").GetProperty("analyticHitCount").GetInt32() > 0);+ Assert.Equal(0, root.GetProperty("summary").GetProperty("tessellatedFallbackHitCount").GetInt32());+ var centerHit = root.GetProperty("samples")[12].GetProperty("firstHit");+ Assert.True(centerHit.GetProperty("position").GetProperty("z").GetDouble() > 0d);+ Assert.Equal("plane", centerHit.GetProperty("surfaceFamily").GetString());+ Assert.Equal("analytic", centerHit.GetProperty("intersectionMode").GetString());+ Assert.Equal("exact", centerHit.GetProperty("confidence").GetString());+ Assert.Equal(2, root.GetProperty("samples")[12].GetProperty("intersectionModes").GetProperty("analytic").GetInt32());+ }++ [Fact]+ public void Analyze_Map_RayProbe_LinearExtrusion_Discloses_Tessellated_Fallback()+ {+ var stepPath = Path.Combine(RepoRoot, "testdata", "step242", "generated", "ruled-a2", "ellipse-linear-extrusion-production.step");+ using var doc = RunAnalyzeRayMap(stepPath, "--plane", "xy", "--direction", "-z", "--resolution", "4x4");+ var root = doc.RootElement;++ Assert.Equal("analytic-cir-tessellated-fallback", root.GetProperty("backendPolicy").GetString());+ Assert.True(root.GetProperty("summary").TryGetProperty("tessellatedFallbackHitCount", out _));+ Assert.Contains("linear-extrusion", root.GetRawText(), StringComparison.Ordinal);+ Assert.Contains("Exact ray intersection unavailable for linear-extrusion; used tessellated fallback.", root.GetProperty("diagnostics").EnumerateArray().Select(d => d.GetString()));+ Assert.Contains("tessellated-fallback", root.GetRawText(), StringComparison.Ordinal);}[Fact]diff --git a/Aetheris.CLI/StepAnalysisModels.cs b/Aetheris.CLI/StepAnalysisModels.csindex 2cdff2e7..6ae028bc 100644--- a/Aetheris.CLI/StepAnalysisModels.cs+++ b/Aetheris.CLI/StepAnalysisModels.cs@@ -120,10 +120,10 @@ public sealed record OrthographicMapResult(public sealed record RayMapBounds(double[] U, double[] V);-public sealed record RayMapHit(double T, Point3D Position, int? FaceIndex, string? SurfaceFamily, Vector3D? Normal, string IntersectionMode);-public sealed record RayMapSample(int I, int J, double U, double V, bool Hit, RayMapHit? FirstHit, RayMapHit? LastHit, int HitCount, IReadOnlyList<RayMapHit> Hits);-public sealed record RayMapSummary(double HitCoverage, double[]? HeightRange, IReadOnlyDictionary<string, int> SurfaceFamiliesHit);-public sealed record RayMapResult(string Mode, string Plane, string Direction, int[]? Resolution, double[]? Point, RayMapBounds Bounds, IReadOnlyList<RayMapSample> Samples, int HitCount, IReadOnlyList<RayMapHit>? Hits, RayMapSummary Summary, string IntersectionMode, IReadOnlyList<string> Diagnostics);+public sealed record RayMapHit(double T, Point3D Position, int? FaceIndex, string? SurfaceFamily, Vector3D? Normal, string IntersectionMode, string Confidence, IReadOnlyList<string> Diagnostics);+public sealed record RayMapSample(int I, int J, double U, double V, bool Hit, RayMapHit? FirstHit, RayMapHit? LastHit, int HitCount, IReadOnlyList<RayMapHit> Hits, IReadOnlyDictionary<string, int> IntersectionModes);+public sealed record RayMapSummary(double HitCoverage, double[]? HeightRange, IReadOnlyDictionary<string, int> SurfaceFamiliesHit, int AnalyticHitCount, int CirHitCount, int TessellatedFallbackHitCount, int UnsupportedSampleCount);+public sealed record RayMapResult(string Mode, string Plane, string Direction, int[]? Resolution, double[]? Point, RayMapBounds Bounds, IReadOnlyList<RayMapSample> Samples, int HitCount, IReadOnlyList<RayMapHit>? Hits, RayMapSummary Summary, string IntersectionMode, string BackendPolicy, IReadOnlyList<string> Diagnostics);public enum SectionPlaneFamily{diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.csindex d179a948..b7088f5c 100644--- a/Aetheris.CLI/StepAnalyzer.cs+++ b/Aetheris.CLI/StepAnalyzer.cs@@ -941,30 +941,27 @@ public sealed record VolumeAnalysisResult(var frame = ResolveRayMapFrame(plane, direction, bbox);var faceSurfaceKinds = BuildFaceSurfaceKinds(body, familyNames: true);var diagnostics = new List<string>();- var exactUnavailable = new HashSet<string>(StringComparer.Ordinal);- foreach (var family in faceSurfaceKinds.Values.Distinct(StringComparer.Ordinal))+ var diagnosticSet = new HashSet<string>(StringComparer.Ordinal);+ foreach (var family in faceSurfaceKinds.Values.Distinct(StringComparer.Ordinal).Where(f => f is not "plane").OrderBy(f => f, StringComparer.Ordinal)){- if (family is not "plane" and not "cylinder" and not "sphere")- {- exactUnavailable.Add(family);- }- }-- foreach (var family in exactUnavailable.OrderBy(v => v, StringComparer.Ordinal))- {- diagnostics.Add($"Exact ray intersection unavailable for {family}; used tessellated fallback.");+ AddDiagnostic(diagnostics, diagnosticSet, $"Exact ray intersection unavailable for {family}; used tessellated fallback.");}var tessellation = BrepDisplayTessellator.TessellateBoundedPartial(body, DisplayTessellationOptions.Default, TimeSpan.FromSeconds(10));foreach (var d in tessellation.FaceDiagnostics ?? []){- diagnostics.Add($"Tessellation diagnostic for face {d.FaceId?.Value.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "unknown"}: {d.Message}");+ AddDiagnostic(diagnostics, diagnosticSet, $"Tessellation diagnostic for face {d.FaceId?.Value.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "unknown"}: {d.Message}");}var samples = new List<RayMapSample>();var allHeights = new List<double>();var surfaceHits = new Dictionary<string, int>(StringComparer.Ordinal);var total = point.HasValue ? 1 : rows * cols;+ var analyticHitCount = 0;+ var cirHitCount = 0;+ var tessellatedFallbackHitCount = 0;+ var unsupportedSampleCount = 0;+for (var j = 0; j < (point.HasValue ? 1 : rows); j++){var v = point?.V ?? frame.MinV + (rows == 1 ? 0.5d : j / (double)(rows - 1)) * frame.RangeV;@@ -972,7 +969,18 @@ public sealed record VolumeAnalysisResult({var u = point?.U ?? frame.MinU + (cols == 1 ? 0.5d : i / (double)(cols - 1)) * frame.RangeU;var origin = frame.PlaneOrigin + (frame.UAxis * u) + (frame.VAxis * v) - (frame.RayDirection * Math.Max(1e-5d, ToleranceContext.Default.Linear * 64d));- var hits = IntersectTessellatedRay(tessellation, origin, frame.RayDirection, faceSurfaceKinds)+ var analyticHits = IntersectAnalyticPlaneRay(body, origin, frame.RayDirection, faceSurfaceKinds).ToArray();+ var tessellatedHits = IntersectTessellatedRay(tessellation, origin, frame.RayDirection, faceSurfaceKinds)+ .Where(h => h.SurfaceFamily is not "plane")+ .ToArray();++ foreach (var hit in tessellatedHits)+ {+ var family = hit.SurfaceFamily ?? "unknown";+ AddDiagnostic(diagnostics, diagnosticSet, $"Exact ray intersection unavailable for {family}; used tessellated fallback.");+ }++ var hits = analyticHits.Concat(tessellatedHits).OrderBy(h => h.T).ToArray();var first = hits.FirstOrDefault();@@ -985,19 +993,38 @@ public sealed record VolumeAnalysisResult(surfaceHits[sf] = surfaceHits.TryGetValue(sf, out var c) ? c + 1 : 1;}}+ else+ {+ unsupportedSampleCount++;+ }- samples.Add(new RayMapSample(i, j, u, v, first is not null, first, last, hits.Length, hits));+ var modeCounts = hits.GroupBy(h => h.IntersectionMode, StringComparer.Ordinal)+ .ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal);+ modeCounts.TryAdd("analytic", 0);+ modeCounts.TryAdd("cir-evaluated", 0);+ modeCounts.TryAdd("tessellated-fallback", 0);+ modeCounts.TryAdd("unsupported", 0);+ analyticHitCount += modeCounts["analytic"];+ cirHitCount += modeCounts["cir-evaluated"];+ tessellatedFallbackHitCount += modeCounts["tessellated-fallback"];++ samples.Add(new RayMapSample(i, j, u, v, first is not null, first, last, hits.Length, hits, new SortedDictionary<string, int>(modeCounts, StringComparer.Ordinal)));}}var summary = new RayMapSummary(samples.Count(s => s.Hit) / (double)total,allHeights.Count == 0 ? null : [allHeights.Min(), allHeights.Max()],- new SortedDictionary<string, int>(surfaceHits, StringComparer.Ordinal));+ new SortedDictionary<string, int>(surfaceHits, StringComparer.Ordinal),+ analyticHitCount,+ cirHitCount,+ tessellatedFallbackHitCount,+ unsupportedSampleCount);var bounds = new RayMapBounds([frame.MinU, frame.MaxU], [frame.MinV, frame.MaxV]);var mode = point.HasValue ? "point" : "grid";var pointArray = point.HasValue ? new[] { point.Value.U, point.Value.V } : null;- return new RayMapResult(mode, plane.ToLowerInvariant(), direction.ToLowerInvariant(), point.HasValue ? null : [cols, rows], pointArray, bounds, samples, samples.Sum(s => s.HitCount), point.HasValue ? samples.Single().Hits : null, summary, "tessellated-fallback", diagnostics);+ var resultMode = tessellatedFallbackHitCount > 0 ? "analytic-first-with-tessellated-fallback" : "analytic";+ return new RayMapResult(mode, plane.ToLowerInvariant(), direction.ToLowerInvariant(), point.HasValue ? null : [cols, rows], pointArray, bounds, samples, samples.Sum(s => s.HitCount), point.HasValue ? samples.Single().Hits : null, summary, resultMode, "analytic-cir-tessellated-fallback", diagnostics);}private static AnalyzeSummary BuildSummary(BrepBody body, ICollection<string> notes)@@ -1858,6 +1885,105 @@ public sealed record VolumeAnalysisResult(};}+ private static void AddDiagnostic(ICollection<string> diagnostics, ISet<string> diagnosticSet, string diagnostic)+ {+ if (diagnosticSet.Add(diagnostic))+ {+ diagnostics.Add(diagnostic);+ }+ }++ private static IReadOnlyList<RayMapHit> IntersectAnalyticPlaneRay(BrepBody body, Point3D origin, Vector3D direction, IReadOnlyDictionary<int, string> faceSurfaceKinds)+ {+ var hits = new List<RayMapHit>();+ foreach (var face in body.Topology.Faces)+ {+ if (!body.TryGetFaceSurface(face.Id, out var surface) || surface?.Plane is not PlaneSurface plane)+ {+ continue;+ }++ var normal = plane.Normal.ToVector();+ var denom = normal.Dot(direction);+ if (Math.Abs(denom) < 1e-10d)+ {+ continue;+ }++ var t = (plane.Origin - origin).Dot(normal) / denom;+ if (t < -1e-9d)+ {+ continue;+ }++ var position = origin + direction * t;+ if (!IsPointInPlanarFaceBounds(body, face.Id, plane, position))+ {+ continue;+ }++ var family = faceSurfaceKinds.TryGetValue(face.Id.Value, out var sf) ? sf : "plane";+ hits.Add(new RayMapHit(t, position, face.Id.Value, family, normal, "analytic", "exact", []));+ }++ return hits.OrderBy(h => h.T).ToArray();+ }++ private static bool IsPointInPlanarFaceBounds(BrepBody body, FaceId faceId, PlaneSurface plane, Point3D point)+ {+ var vertices = body.GetEdges(faceId)+ .SelectMany(edge => body.GetVertices(edge))+ .Distinct()+ .Select(vertex => body.TryGetVertexPoint(vertex, out var p) ? (Point3D?)p : null)+ .Where(p => p.HasValue)+ .Select(p => p!.Value)+ .ToArray();+ if (vertices.Length < 3)+ {+ return false;+ }++ var uAxis = plane.UAxis.ToVector();+ var vAxis = plane.VAxis.ToVector();+ var projected = vertices+ .Select(v => ((v - plane.Origin).Dot(uAxis), (v - plane.Origin).Dot(vAxis)))+ .Distinct()+ .ToArray();+ if (projected.Length < 3)+ {+ return false;+ }++ var centerU = projected.Average(p => p.Item1);+ var centerV = projected.Average(p => p.Item2);+ var polygon = projected+ .OrderBy(p => Math.Atan2(p.Item2 - centerV, p.Item1 - centerU))+ .ToArray();+ var pu = (point - plane.Origin).Dot(uAxis);+ var pv = (point - plane.Origin).Dot(vAxis);+ var inside = false;+ const double epsilon = 1e-8d;+ for (var i = 0; i < polygon.Length; i++)+ {+ var a = polygon[i];+ var b = polygon[(i + 1) % polygon.Length];+ var cross = (b.Item1 - a.Item1) * (pv - a.Item2) - (b.Item2 - a.Item2) * (pu - a.Item1);+ var dot = (pu - a.Item1) * (pu - b.Item1) + (pv - a.Item2) * (pv - b.Item2);+ if (Math.Abs(cross) <= epsilon && dot <= epsilon)+ {+ return true;+ }++ if (((a.Item2 > pv) != (b.Item2 > pv)) &&+ pu < (b.Item1 - a.Item1) * (pv - a.Item2) / (b.Item2 - a.Item2) + a.Item1)+ {+ inside = !inside;+ }+ }++ return inside;+ }+private static IReadOnlyList<RayMapHit> IntersectTessellatedRay(DisplayTessellationResult tessellation, Point3D origin, Vector3D direction, IReadOnlyDictionary<int, string> faceSurfaceKinds){var hits = new List<RayMapHit>();@@ -1872,7 +1998,7 @@ public sealed record VolumeAnalysisResult(var p = origin + direction * t;var family = faceSurfaceKinds.TryGetValue(patch.FaceId.Value, out var sf) ? sf : "unknown";if (hits.Any(h => Math.Abs(h.T - t) < 1e-7d && h.FaceIndex == patch.FaceId.Value)) continue;- hits.Add(new RayMapHit(t, p, patch.FaceId.Value, family, normal, "tessellated-fallback"));+ hits.Add(new RayMapHit(t, p, patch.FaceId.Value, family, normal, "tessellated-fallback", "approximate", [$"Exact ray intersection unavailable for {family}; used tessellated fallback."]));}}diff --git a/docs/implementation/analyze-map-a0-ray-height-map.md b/docs/implementation/analyze-map-a0-ray-height-map.mdindex 042983f8..54bc1bc0 100644--- a/docs/implementation/analyze-map-a0-ray-height-map.md+++ b/docs/implementation/analyze-map-a0-ray-height-map.md@@ -33,3 +33,8 @@ Fallback diagnostics are emitted when exact intersection is unavailable for surf## LimitationsThe A0 map is tessellation-backed, so curved and swept surfaces are approximate. It does not classify solid intervals yet, and six-view output is deferred to A1; run the command once per direction for equivalent coverage.+++## Forward link++ANALYZE-MAP-A1 refactors the ray path to analytic-first backend dispatch with per-hit provenance and explicit tessellated fallback diagnostics. See `docs/implementation/analyze-map-a1-analytic-backend-provenance.md`.diff --git a/docs/implementation/analyze-map-a1-analytic-backend-provenance.md b/docs/implementation/analyze-map-a1-analytic-backend-provenance.mdnew file mode 100644index 00000000..d327db56--- /dev/null+++ b/docs/implementation/analyze-map-a1-analytic-backend-provenance.md@@ -0,0 +1,111 @@+# ANALYZE-MAP-A1 analytic backend provenance++`aetheris analyze map` is an LLM-oriented spatial measurement tool: it samples a selected view plane, shoots rays through model space, and reports hit positions, depths/heights, face ids, and surface families. It is not a topology metadata report and should not treat display meshes as geometric truth.++## Why tessellation is not the source of truth++Display tessellation answers, "How should this model be drawn?" The map analyzer answers, "Where is the model in 3D space?" Those are different contracts. Tessellation is useful for approximate fallback coverage, but it can be slow, display-policy dependent, and fragile for trimmed or highly curved surfaces. A1 therefore makes tessellated hits explicit and approximate rather than silently reusing display triangles as authoritative measurements.++## Backend ladder++The map ray path now reports the intended backend policy:++```text+analytic-cir-tessellated-fallback+```++The ladder is:++1. **Analytic exact intersection** for supported bounded faces.+2. **CIR/evaluable intersection** as a future hook when a usable map ray evaluator is admitted.+3. **Tessellated fallback** for unsupported analytic families.+4. **Unsupported/no-hit diagnostic** when no backend can produce a hit.++A1 implements the dispatch/provenance shape and exact bounded planar face hits. CIR remains a documented future backend; A1 does not infer CIR mirrors from arbitrary STEP input.++## A1 plane analytic handler++Planar faces are intersected by exact ray-plane math. The candidate point is then checked against the current face bounds using imported face vertices projected into the plane basis. When the bounded check succeeds, the hit is reported as:++```json+{+ "surfaceFamily": "plane",+ "intersectionMode": "analytic",+ "confidence": "exact",+ "diagnostics": []+}+```++If a future planar case cannot establish bounded containment reliably, it must not be promoted to an exact analytic face hit. It should fall back or report a diagnostic rather than claiming that an infinite-plane candidate is a bounded face hit.++## JSON provenance++Each hit carries backend provenance:++```json+{+ "position": { "x": 0, "y": 0, "z": 6 },+ "faceIndex": 4,+ "surfaceFamily": "plane",+ "intersectionMode": "analytic",+ "confidence": "exact",+ "diagnostics": []+}+```++Each sample summarizes modes observed along that ray:++```json+{+ "i": 0,+ "j": 0,+ "hit": true,+ "hitCount": 2,+ "intersectionModes": {+ "analytic": 2,+ "cir-evaluated": 0,+ "tessellated-fallback": 0,+ "unsupported": 0+ }+}+```++The result summary includes backend counts and the top-level backend policy:++```json+{+ "backendPolicy": "analytic-cir-tessellated-fallback",+ "summary": {+ "analyticHitCount": 100,+ "cirHitCount": 0,+ "tessellatedFallbackHitCount": 24,+ "unsupportedSampleCount": 0+ }+}+```++## Fallback semantics++Unsupported A1 families such as `cylinder`, `cone`, `sphere`, `torus`, `linear-extrusion`, `surface-of-revolution`, and `bspline` may still map through tessellation. When that happens, hits use:++```json+{+ "intersectionMode": "tessellated-fallback",+ "confidence": "approximate",+ "diagnostics": [+ "Exact ray intersection unavailable for linear-extrusion; used tessellated fallback."+ ]+}+```++The same diagnostic is also surfaced at the top level once per surface family so callers can decide whether approximate samples are acceptable.++## Current limitations and future hooks++A1 intentionally does not implement analytic cylinder, sphere, cone, torus, ruled/swept, or B-spline ray intersections. It also does not reconstruct features, integrate volume, change DisplayIR, or add modeling capabilities.++CIR/evaluable intersection remains the next architectural hook once an admitted ray API exists for map workloads. Torus should be prioritized in a later truth pass because tessellated torus and trimmed-loop display paths have historically been fragile. Suggested future milestone:++```text+ANALYZE-MAP-A3: analytic cone + torus truth pass+```