Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Fix planar analytic rendering to use real face boundaries
Yuechen Li49214ba582a8
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Queries/AnalyticDisplayPacketBuilderTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Queries/AnalyticDisplayPacketBuilderTests.csindex 65349afb..9c22ddc0 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Queries/AnalyticDisplayPacketBuilderTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Queries/AnalyticDisplayPacketBuilderTests.cs@@ -25,6 +25,27 @@ public sealed class AnalyticDisplayPacketBuilderTestsAssert.All(packet.AnalyticFaces, face => Assert.Equal(SurfaceGeometryKind.Plane, face.SurfaceKind));}+ [Fact]+ public void Build_BoxBody_PopulatesPlanarOuterBoundaryWithRealFaceExtent()+ {+ var body = BrepPrimitives.CreateBox(2d, 2d, 2d).Value;++ var packet = AnalyticDisplayPacketBuilder.Build(body);++ var planarFacesWithBoundary = packet.AnalyticFaces+ .Where(face => face.SurfaceKind == SurfaceGeometryKind.Plane && face.PlanarOuterBoundary is { Count: >= 3 })+ .ToArray();++ Assert.NotEmpty(planarFacesWithBoundary);++ var boundary = planarFacesWithBoundary[0].PlanarOuterBoundary!;+ Assert.Equal(4, boundary.Count);+ Assert.Equal(-1d, boundary.Min(vertex => vertex.X), 9);+ Assert.Equal(1d, boundary.Max(vertex => vertex.X), 9);+ Assert.Equal(-1d, boundary.Min(vertex => vertex.Y), 9);+ Assert.Equal(1d, boundary.Max(vertex => vertex.Y), 9);+ }+[Fact]public void Build_RotatedPlanarPolygonBody_KeepsNonAxisPlanarPolygonFaceAnalytic()diff --git a/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplayPacket.cs b/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplayPacket.csindex 97a7cbd3..81a55676 100644--- a/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplayPacket.cs+++ b/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplayPacket.cs@@ -30,7 +30,8 @@ public sealed record AnalyticDisplayFaceEntry(SurfaceGeometryKind SurfaceKind,SurfaceGeometry SurfaceGeometry,int LoopCount,- AnalyticDisplayFaceDomainHint? DomainHint);+ AnalyticDisplayFaceDomainHint? DomainHint,+ IReadOnlyList<Point3D>? PlanarOuterBoundary);public sealed record AnalyticDisplayFallbackFaceEntry(FaceId FaceId,@@ -82,13 +83,26 @@ public static class AnalyticDisplayPacketBuildersurface.Kind,surface,body.Topology.GetFace(faceId).LoopIds.Count,- TryResolveDomainHint(body, faceId, surface)));+ TryResolveDomainHint(body, faceId, surface),+ TryResolvePlanarOuterBoundary(body, faceId, surface)));}}return new AnalyticDisplayPacket(bodyId, analyticFaces, fallbackFaces);}+ private static IReadOnlyList<Point3D>? TryResolvePlanarOuterBoundary(BrepBody body, FaceId faceId, SurfaceGeometry surface)+ {+ if (surface.Kind != SurfaceGeometryKind.Plane || surface.Plane is not PlaneSurface plane)+ {+ return null;+ }++ return AnalyticPlanarFaceDomain.TryGetOuterBoundaryWorld(body, faceId, plane, out var outerBoundary)+ ? outerBoundary+ : null;+ }+private static AnalyticDisplayFaceDomainHint? TryResolveDomainHint(BrepBody body, FaceId faceId, SurfaceGeometry surface){switch (surface.Kind)diff --git a/Aetheris.Kernel.Core/Brep/Queries/AnalyticPlanarFaceDomain.cs b/Aetheris.Kernel.Core/Brep/Queries/AnalyticPlanarFaceDomain.csindex b8dbcb29..93f6f124 100644--- a/Aetheris.Kernel.Core/Brep/Queries/AnalyticPlanarFaceDomain.cs+++ b/Aetheris.Kernel.Core/Brep/Queries/AnalyticPlanarFaceDomain.cs@@ -82,6 +82,45 @@ internal sealed class AnalyticPlanarFaceDomainreturn false;}+ internal static bool TryGetOuterBoundaryWorld(BrepBody body, FaceId faceId, PlaneSurface plane, out IReadOnlyList<Point3D> outerBoundary)+ {+ outerBoundary = [];+ if (!body.Topology.TryGetFace(faceId, out var face) || face is null || face.LoopIds.Count == 0)+ {+ return false;+ }++ var loops = new List<(IReadOnlyList<Point3D> Vertices, IReadOnlyList<(double U, double V)> Projected, double Area)>(face.LoopIds.Count);+ foreach (var loopId in face.LoopIds)+ {+ var loop = body.Topology.GetLoop(loopId);+ if (!TryBuildPolygonLoopDetailed(body, loop, plane, out var vertices, out var projected))+ {+ return false;+ }++ loops.Add((vertices, projected, double.Abs(SignedArea(projected))));+ }++ var ordered = loops.OrderByDescending(entry => entry.Area).ToArray();+ if (ordered.Length == 0 || ordered[0].Area <= 1e-9d)+ {+ return false;+ }++ var candidateOuter = ordered[0].Projected;+ for (var i = 1; i < ordered.Length; i++)+ {+ if (!ordered[i].Projected.All(vertex => ContainsPoint(candidateOuter, vertex, ToleranceContext.Default)))+ {+ return false;+ }+ }++ outerBoundary = ordered[0].Vertices;+ return true;+ }+public bool Contains(Point3D point, ToleranceContext tolerance){if (_outerPolygon.Count > 0)@@ -184,12 +223,30 @@ internal sealed class AnalyticPlanarFaceDomainprivate static bool TryBuildPolygonLoop(BrepBody body, Loop loop, PlaneSurface plane, out IReadOnlyList<(double U, double V)> polygon){polygon = [];+ if (!TryBuildPolygonLoopDetailed(body, loop, plane, out _, out var projected))+ {+ return false;+ }++ polygon = projected;+ return true;+ }++ private static bool TryBuildPolygonLoopDetailed(+ BrepBody body,+ Loop loop,+ PlaneSurface plane,+ out IReadOnlyList<Point3D> vertices3d,+ out IReadOnlyList<(double U, double V)> projected)+ {+ vertices3d = [];+ projected = [];if (loop.CoedgeIds.Count < 3){return false;}- var segments = new List<(Point3D Start, Point3D End)>(loop.CoedgeIds.Count);+ var lines = new List<(Point3D Origin, Vector3D Direction)>(loop.CoedgeIds.Count);foreach (var coedgeId in loop.CoedgeIds){var coedge = body.Topology.GetCoedge(coedgeId);@@ -200,115 +257,76 @@ internal sealed class AnalyticPlanarFaceDomainreturn false;}- if (!TryGetCoedgeLineEndpoints(body, coedge, curve.Line3!.Value, out var start, out var end))+ var line = curve.Line3!.Value;+ var direction = coedge.IsReversed ? line.Direction.ToVector() * -1d : line.Direction.ToVector();+ if (direction.Length <= 1e-12d){return false;}- segments.Add((start, end));+ lines.Add((line.Origin, direction));}- var used = new bool[segments.Count];- var vertices = new List<Point3D>(segments.Count + 1) { segments[0].Start, segments[0].End };- used[0] = true;-- for (var i = 1; i < segments.Count; i++)+ var vertices = new List<Point3D>(lines.Count);+ for (var i = 0; i < lines.Count; i++){- var currentEnd = vertices[^1];- var nextIndex = -1;- var appendVertex = Point3D.Origin;-- for (var candidateIndex = 0; candidateIndex < segments.Count; candidateIndex++)- {- if (used[candidateIndex])- {- continue;- }-- var candidate = segments[candidateIndex];- if (PointsAlmostEqual(candidate.Start, currentEnd))- {- nextIndex = candidateIndex;- appendVertex = candidate.End;- break;- }-- if (PointsAlmostEqual(candidate.End, currentEnd))- {- nextIndex = candidateIndex;- appendVertex = candidate.Start;- break;- }- }-- if (nextIndex < 0)+ var current = lines[i];+ var next = lines[(i + 1) % lines.Count];+ var current2d = ProjectToPlane(current.Origin, plane);+ var next2d = ProjectToPlane(next.Origin, plane);+ var currentDir2d = (+ current.Direction.Dot(plane.UAxis.ToVector()),+ current.Direction.Dot(plane.VAxis.ToVector()));+ var nextDir2d = (+ next.Direction.Dot(plane.UAxis.ToVector()),+ next.Direction.Dot(plane.VAxis.ToVector()));+ if (!TryIntersectLines2D(current2d, currentDir2d, next2d, nextDir2d, out var intersection2d)){return false;}- used[nextIndex] = true;- vertices.Add(appendVertex);- }-- if (!PointsAlmostEqual(vertices[0], vertices[^1]))- {- return false;+ var point = plane.Origin + (plane.UAxis.ToVector() * intersection2d.U) + (plane.VAxis.ToVector() * intersection2d.V);+ vertices.Add(point);}- vertices.RemoveAt(vertices.Count - 1);if (vertices.Count < 3){return false;}- var projected = new List<(double U, double V)>(vertices.Count);+ var uvVertices = new List<(double U, double V)>(vertices.Count);foreach (var vertex in vertices){- projected.Add(ProjectToPlane(vertex, plane));+ uvVertices.Add(ProjectToPlane(vertex, plane));}- if (double.Abs(SignedArea(projected)) <= 1e-9d)+ if (double.Abs(SignedArea(uvVertices)) <= 1e-9d){return false;}- polygon = projected;+ vertices3d = vertices;+ projected = uvVertices;return true;}- private static bool TryGetCoedgeLineEndpoints(BrepBody body, Coedge coedge, Line3Curve line, out Point3D start, out Point3D end)+ private static bool TryIntersectLines2D(+ (double U, double V) originA,+ (double U, double V) directionA,+ (double U, double V) originB,+ (double U, double V) directionB,+ out (double U, double V) intersection){- var edge = body.Topology.GetEdge(coedge.EdgeId);- var haveStart = body.TryGetVertexPoint(edge.StartVertexId, out var startPoint);- var haveEnd = body.TryGetVertexPoint(edge.EndVertexId, out var endPoint);- if (!(haveStart && haveEnd))+ intersection = default;+ var determinant = (directionA.U * directionB.V) - (directionA.V * directionB.U);+ if (double.Abs(determinant) <= 1e-12d){- if (!body.Bindings.TryGetEdgeBinding(coedge.EdgeId, out var binding))- {- start = default;- end = default;- return false;- }-- var interval = binding.TrimInterval ?? new ParameterInterval(0d, 1d);- var sampled = CurveSampler.SampleLine(line, interval);- if (sampled.Count < 2)- {- start = default;- end = default;- return false;- }-- startPoint = sampled[0];- endPoint = sampled[1];- if (!binding.OrientedEdgeSense)- {- (startPoint, endPoint) = (endPoint, startPoint);- }+ return false;}- start = coedge.IsReversed ? endPoint : startPoint;- end = coedge.IsReversed ? startPoint : endPoint;+ var delta = (U: originB.U - originA.U, V: originB.V - originA.V);+ var t = ((delta.U * directionB.V) - (delta.V * directionB.U)) / determinant;+ intersection = (originA.U + (directionA.U * t), originA.V + (directionA.V * t));return true;}diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.csindex 39dee5c5..bea31ea4 100644--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs@@ -149,6 +149,32 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFactAssert.Null(prepared.Data.TessellationFallback);}+ [Fact]+ public async Task DisplayPrepare_BoxPrimitive_PlanarFaceIncludesOuterBoundaryContract()+ {+ var document = await CreateDocumentAsync("/api/v1/documents");+ var box = await CreateBoxAsync("/api/v1/documents", document.Data!.DocumentId, 2, 2, 2);++ var prepared = await PrepareDisplayAsync(document.Data.DocumentId, box.Data!.BodyId);++ Assert.Equal("analytic-only", prepared.Data!.Lane);+ var planarFace = prepared.Data.AnalyticPacket.AnalyticFaces.FirstOrDefault(face =>+ face.SurfaceKind == "Plane"+ && face.PlaneGeometry is not null+ && face.PlaneGeometry.OuterBoundary is not null+ && face.PlaneGeometry.OuterBoundary.Count >= 3);+ Assert.NotNull(planarFace);+ var vertices = planarFace.PlaneGeometry!.OuterBoundary!;+ var minX = vertices.Min(vertex => vertex.X);+ var maxX = vertices.Max(vertex => vertex.X);+ var minY = vertices.Min(vertex => vertex.Y);+ var maxY = vertices.Max(vertex => vertex.Y);+ var minZ = vertices.Min(vertex => vertex.Z);+ var maxZ = vertices.Max(vertex => vertex.Z);+ var extent = double.Max(maxX - minX, double.Max(maxY - minY, maxZ - minZ));+ Assert.True(extent >= 1.9d);+ }+[Fact]public async Task DisplayPrepare_ImportedUnsupportedBody_PreservesFallbackRouting(){diff --git a/Aetheris.Server/Api/ApiMappings.cs b/Aetheris.Server/Api/ApiMappings.csindex 5a4d9ede..3e558c06 100644--- a/Aetheris.Server/Api/ApiMappings.cs+++ b/Aetheris.Server/Api/ApiMappings.cs@@ -85,7 +85,8 @@ public static class ApiMappingsToPointDto(plane.Origin),ToVectorDto(plane.Normal.ToVector()),ToVectorDto(plane.UAxis.ToVector()),- ToVectorDto(plane.VAxis.ToVector())) : null,+ ToVectorDto(plane.VAxis.ToVector()),+ face.PlanarOuterBoundary?.Select(ToPointDto).ToArray()) : null,face.SurfaceGeometry.Cylinder is { } cylinder ? new AnalyticDisplayCylinderGeometryDto(ToPointDto(cylinder.Origin),ToVectorDto(cylinder.Axis.ToVector()),diff --git a/Aetheris.Server/Contracts/ApiContracts.cs b/Aetheris.Server/Contracts/ApiContracts.csindex b7a214af..b6a1409b 100644--- a/Aetheris.Server/Contracts/ApiContracts.cs+++ b/Aetheris.Server/Contracts/ApiContracts.cs@@ -86,7 +86,8 @@ public sealed record AnalyticDisplayPlaneGeometryDto(Point3Dto Origin,Vector3Dto Normal,Vector3Dto UAxis,- Vector3Dto VAxis);+ Vector3Dto VAxis,+ IReadOnlyList<Point3Dto>? OuterBoundary);public sealed record AnalyticDisplayCylinderGeometryDto(Point3Dto Origin,diff --git a/aetheris.client/src/__tests__/displaySceneBuilder.test.ts b/aetheris.client/src/__tests__/displaySceneBuilder.test.tsindex d1647fc8..fa0cbf40 100644--- a/aetheris.client/src/__tests__/displaySceneBuilder.test.ts+++ b/aetheris.client/src/__tests__/displaySceneBuilder.test.ts@@ -206,6 +206,12 @@ describe('buildDisplaySceneData', () => {normal: { x: 0, y: 0, z: 1 },uAxis: { x: 1, y: 0, z: 0 },vAxis: { x: 0, y: 1, z: 0 },+ outerBoundary: [+ { x: -1, y: -1, z: 0 },+ { x: 1, y: -1, z: 0 },+ { x: 1, y: 1, z: 0 },+ { x: -1, y: 1, z: 0 },+ ],},cylinderGeometry: null,coneGeometry: null,@@ -271,6 +277,12 @@ describe('buildDisplaySceneData', () => {normal: { x: 0, y: 0, z: 1 },uAxis: { x: 1, y: 0, z: 0 },vAxis: { x: 0, y: 1, z: 0 },+ outerBoundary: [+ { x: -1, y: -1, z: 0 },+ { x: 1, y: -1, z: 0 },+ { x: 1, y: 1, z: 0 },+ { x: -1, y: 1, z: 0 },+ ],},cylinderGeometry: null,coneGeometry: null,@@ -484,6 +496,53 @@ describe('mapAnalyticPacketToRenderData', () => {expect(Array.from(first.faces[0].indices)).toEqual(Array.from(second.faces[0].indices));});+ it('maps planar faces from outerBoundary polygon instead of placeholder quad', () => {+ const planarPacket = {+ bodyId: 4,+ analyticFaces: [+ {+ faceId: 401,+ shellId: 1,+ shellRole: 'Outer' as const,+ surfaceGeometryId: 4001,+ surfaceKind: 'Plane',+ loopCount: 1,+ domainHint: null,+ planeGeometry: {+ origin: { x: 0, y: 0, z: 0 },+ normal: { x: 0, y: 0, z: 1 },+ uAxis: { x: 1, y: 0, z: 0 },+ vAxis: { x: 0, y: 1, z: 0 },+ outerBoundary: [+ { x: -2, y: -1, z: 0 },+ { x: 3, y: -1, z: 0 },+ { x: 3, y: 2, z: 0 },+ { x: 1, y: 2, z: 0 },+ { x: -2, y: 1, z: 0 },+ ],+ },+ cylinderGeometry: null,+ coneGeometry: null,+ sphereGeometry: null,+ torusGeometry: null,+ },+ ],+ fallbackFaces: [],+ };++ const mapped = mapAnalyticPacketToRenderData(planarPacket);++ expect(mapped.faces).toHaveLength(1);+ expect(Array.from(mapped.faces[0].positions)).toEqual([+ -2, -1, 0,+ 3, -1, 0,+ 3, 2, 0,+ 1, 2, 0,+ -2, 1, 0,+ ]);+ expect(mapped.faces[0].indices.length).toBe(9);+ });+it('is deterministic for the same analytic packet input', () => {const first = mapAnalyticPacketToRenderData(analyticPreparation.analyticPacket);const second = mapAnalyticPacketToRenderData(analyticPreparation.analyticPacket);diff --git a/aetheris.client/src/api/aetherisApi.ts b/aetheris.client/src/api/aetherisApi.tsindex 19f2d30f..fe355cda 100644--- a/aetheris.client/src/api/aetherisApi.ts+++ b/aetheris.client/src/api/aetherisApi.ts@@ -113,6 +113,7 @@ export interface AnalyticDisplayPlaneGeometryDto {normal: Vector3Dto;uAxis: Vector3Dto;vAxis: Vector3Dto;+ outerBoundary: Point3Dto[] | null;}export interface AnalyticDisplayCylinderGeometryDto {diff --git a/aetheris.client/src/viewer/analyticMapper.ts b/aetheris.client/src/viewer/analyticMapper.tsindex 008f35f4..e5d0f62c 100644--- a/aetheris.client/src/viewer/analyticMapper.ts+++ b/aetheris.client/src/viewer/analyticMapper.ts@@ -29,29 +29,124 @@ function normalize(v: [number, number, number]): [number, number, number] {return [v[0] / len, v[1] / len, v[2] / len];}+function signedArea2d(points: [number, number][]): number {+ let area = 0;+ for (let i = 0; i < points.length; i += 1) {+ const [x1, y1] = points[i];+ const [x2, y2] = points[(i + 1) % points.length];+ area += (x1 * y2) - (x2 * y1);+ }++ return area * 0.5;+}++function pointInTriangle(point: [number, number], a: [number, number], b: [number, number], c: [number, number]): boolean {+ const cross1 = ((b[0] - a[0]) * (point[1] - a[1])) - ((b[1] - a[1]) * (point[0] - a[0]));+ const cross2 = ((c[0] - b[0]) * (point[1] - b[1])) - ((c[1] - b[1]) * (point[0] - b[0]));+ const cross3 = ((a[0] - c[0]) * (point[1] - c[1])) - ((a[1] - c[1]) * (point[0] - c[0]));+ const hasNeg = cross1 < -1e-9 || cross2 < -1e-9 || cross3 < -1e-9;+ const hasPos = cross1 > 1e-9 || cross2 > 1e-9 || cross3 > 1e-9;+ return !(hasNeg && hasPos);+}++function triangulateSimplePolygon(points: [number, number][]): number[] | null {+ if (points.length < 3) {+ return null;+ }++ const orientation = Math.sign(signedArea2d(points));+ if (orientation === 0) {+ return null;+ }++ const indices = [...points.keys()];+ const triangles: number[] = [];+ let guard = 0;+ while (indices.length > 3 && guard < points.length * points.length) {+ let earFound = false;+ for (let i = 0; i < indices.length; i += 1) {+ const prev = indices[(i - 1 + indices.length) % indices.length];+ const curr = indices[i];+ const next = indices[(i + 1) % indices.length];+ const a = points[prev];+ const b = points[curr];+ const c = points[next];+ const cross = ((b[0] - a[0]) * (c[1] - a[1])) - ((b[1] - a[1]) * (c[0] - a[0]));+ if (cross * orientation <= 1e-9) {+ continue;+ }++ let hasInteriorPoint = false;+ for (let j = 0; j < indices.length; j += 1) {+ const candidate = indices[j];+ if (candidate === prev || candidate === curr || candidate === next) {+ continue;+ }++ if (pointInTriangle(points[candidate], a, b, c)) {+ hasInteriorPoint = true;+ break;+ }+ }++ if (hasInteriorPoint) {+ continue;+ }++ triangles.push(prev, curr, next);+ indices.splice(i, 1);+ earFound = true;+ break;+ }++ if (!earFound) {+ return null;+ }++ guard += 1;+ }++ if (indices.length === 3) {+ triangles.push(indices[0], indices[1], indices[2]);+ return triangles;+ }++ return null;+}+function buildPlanePatch(face: AnalyticDisplayFaceDto): RenderFacePatch | null {if (!face.planeGeometry) {return null;}- const origin = toArray(face.planeGeometry.origin);- const normal = normalize(toArray(face.planeGeometry.normal));- const uAxis = normalize(toArray(face.planeGeometry.uAxis));- const vAxis = normalize(toArray(face.planeGeometry.vAxis));- const halfSize = 0.5;+ const outerBoundary = face.planeGeometry.outerBoundary;+ if (!outerBoundary || outerBoundary.length < 3) {+ return null;+ }- const corners: [number, number, number][] = [- add(add(origin, mul(uAxis, -halfSize)), mul(vAxis, -halfSize)),- add(add(origin, mul(uAxis, halfSize)), mul(vAxis, -halfSize)),- add(add(origin, mul(uAxis, halfSize)), mul(vAxis, halfSize)),- add(add(origin, mul(uAxis, -halfSize)), mul(vAxis, halfSize)),- ];+ const normal = normalize(toArray(face.planeGeometry.normal));+ const origin = toArray(face.planeGeometry.origin);+ const uAxis = toArray(face.planeGeometry.uAxis);+ const vAxis = toArray(face.planeGeometry.vAxis);+ const points3d = outerBoundary.map(toArray);+ const points2d: [number, number][] = points3d.map((point) => {+ const rel: [number, number, number] = [point[0] - origin[0], point[1] - origin[1], point[2] - origin[2]];+ return [+ (rel[0] * uAxis[0]) + (rel[1] * uAxis[1]) + (rel[2] * uAxis[2]),+ (rel[0] * vAxis[0]) + (rel[1] * vAxis[1]) + (rel[2] * vAxis[2]),+ ];+ });++ const triangles = triangulateSimplePolygon(points2d);+ if (!triangles || triangles.length === 0) {+ return null;+ }return {faceId: face.faceId,- positions: new Float32Array(corners.flat()),- normals: new Float32Array([normal, normal, normal, normal].flat()),- indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+ positions: new Float32Array(points3d.flat()),+ normals: new Float32Array(points3d.flatMap(() => normal)),+ indices: new Uint32Array(triangles),};}