diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/threed/STEPFile.java b/src/main/java/com/neuronrobotics/bowlerstudio/threed/STEPFile.java index d8cac7ab..a061c069 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/threed/STEPFile.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/threed/STEPFile.java @@ -89,6 +89,10 @@ public STEPFile(List csgs, double angleDegrees, double topologyRepairTolera for (CSG csg : csgs) { if (csg == null) throw new IllegalArgumentException("csgs must not contain null"); + // BSP polygons may geometrically cover a boundary using different + // segment partitions. Both the BRep and retained tessellation need + // matching atomic edges, before decomposition or feature extraction. + csg = StepBRepWrite.conformPartitions(csg); // the mesh is decomposed into its connected bodies first: each body // becomes a part of its own, with its own MANIFOLD_SOLID_BREP in the // file, rather than several bodies sharing one shell — which is what a @@ -341,7 +345,7 @@ private static void part(StepEmitter emitter, Part part) { long representation = emitter.add("ADVANCED_BREP_SHAPE_REPRESENTATION(" + quote(part.name()) + "," + references(items) + ",#" + contexts.representation + ")"); emitter.add("SHAPE_DEFINITION_REPRESENTATION(#" + product.definitionShape + ",#" + representation + ")"); - tessellation(emitter, part, contexts, representation); + tessellation(emitter, part, contexts, representation, items.get(items.size() - 1)); colour(emitter, part.csg, contexts.representation, items); } @@ -350,13 +354,14 @@ private static void part(StepEmitter emitter, Part part) { * package reads the BRep; a reader that can use the tessellation reproduces * the source triangles exactly instead of re-triangulating the faces. */ - private static void tessellation(StepEmitter emitter, Part part, Contexts contexts, long brep) { - long tessellated = StepTessellatedWrite.representation(emitter, part.csg, part.name(), contexts.representation); + private static void tessellation(StepEmitter emitter, Part part, Contexts contexts, long brep, long solid) { + long tessellated = StepTessellatedWrite.representation(emitter, part.csg, part.name(), contexts.representation, solid); if (tessellated == 0) return; - // plain relationship: the tessellation describes the same shape, at the same - // coordinates, so there is nothing to transform - emitter.add("SHAPE_REPRESENTATION_RELATIONSHIP(" + quote(part.name()) + "," + quote("tessellation of the BRep") + // The solid carries the explicit geometric link. Keep this as a general + // alternate-representation relation; a shape relation transfers a second + // instance of the same BRep in readers such as OCCT. + emitter.add("REPRESENTATION_RELATIONSHIP(" + quote(part.name()) + "," + quote("tessellation of the BRep") + ",#" + brep + ",#" + tessellated + ")"); } @@ -391,7 +396,7 @@ private static void assembly(StepEmitter emitter, List parts) { + references(representationItems) + ",#" + contexts.representation + ")"); emitter.add( "SHAPE_DEFINITION_REPRESENTATION(#" + product.definitionShape + ",#" + representations[i] + ")"); - tessellation(emitter, part, contexts, representations[i]); + tessellation(emitter, part, contexts, representations[i], items.get(items.size() - 1)); colour(emitter, part.csg, contexts.representation, geometry); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepBRepWrite.java b/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepBRepWrite.java index 1705ee5f..401b1e8b 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepBRepWrite.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepBRepWrite.java @@ -80,6 +80,24 @@ static List items(StepEmitter emitter, CSG csg, String name) { return List.of(placement, body); } + /** + * Condition BSP boundary partitions once for both AP242 representations and + * body decomposition. Already conforming meshes retain their exact arrays. + * The caller's CSG is never changed. + */ + static CSG conformPartitions(CSG source) { + if (source.getVertices() == null || source.getTriangles() == null) + return source; + Mesh mesh = new Mesh(source.getVertices(), source.getTriangles(), false); + if (mesh.conformedTriangles == 0) + return source; + long[] indices = new long[mesh.triangles.size() * 3]; + for (int i = 0; i < mesh.triangles.size(); i++) + for (int j = 0; j < 3; j++) + indices[i * 3 + j] = mesh.triangles.get(i)[j]; + return new CSG(mesh.points, indices, source.getColor()).historySync(source); + } + /** A solid or surface model over the mesh, or 0 when the mesh has no faces. */ static long solid(StepEmitter emitter, CSG csg, String name) { double[] vertices = csg.getVertices(); @@ -149,7 +167,7 @@ private static boolean isWatertight(List>> faces) { return unpairedEdges(faces) == 0 && !faces.isEmpty(); } - /** How many directed edges of the written loops lack their opposite. */ + /** Directed boundary uses that fail the ordinary one-forward/one-reverse contract. */ private static int unpairedEdges(List>> faces) { Map directions = new HashMap<>(); for (List> loops : faces) @@ -166,12 +184,12 @@ private static int unpairedEdges(List>> faces) { // a degenerate edge, running from a point to itself, is its own opposite if (from == to) continue; - // An edge can also carry more than one pairing when two sheets of the part - // meet along it: as many walks one way as the other, each pair closing. That - // closes the surface too, so only an imbalance marks the shell open. + // A MANIFOLD_SOLID_BREP needs exactly two incident faces. Balanced + // multiplicity (for example 2:2) is still a nonmanifold edge and + // must not be labeled as one closed solid. int forward = entry.getValue(); int backward = directions.getOrDefault(directed(to, from), 0); - if (forward != backward) + if (forward != 1 || backward != 1) unpaired++; } return unpaired; @@ -207,7 +225,7 @@ private static long placement(StepEmitter emitter, String name) { /** The mesh, grouped into coplanar faces and sharing vertices and edges. */ private static final class Mesh { - private final double[] points; + private double[] points; private final List triangles = new ArrayList<>(); private final List> faces = new ArrayList<>(); /** Undirected edge to the triangles that use it, for growing a face. */ @@ -223,24 +241,20 @@ private static final class Mesh { /** How many references named a point another index already named. */ private int duplicateReferences; - /** - * The scale at which a STEP reader merges two points into one, as a fraction - * of the model's extent. It is the yardstick the file is written to: two - * entities closer than this are one point to the reader that sews them. - */ - private static final double READER_TOLERANCE = 1e-6; - - private final double readerTolerance; private final double planeTolerance; /** A mesh vertex to the vertex that represents it. */ /** Triangles the source had and this mesh could not keep, for diagnostics. */ private int droppedCollapsed; + private int conformedTriangles; private Mesh(double[] points, long[] sourceTriangles) { + this(points, sourceTriangles, true); + } + + private Mesh(double[] points, long[] sourceTriangles, boolean groupFaces) { this.points = points; this.planeTolerance = PLANE_TOLERANCE * diagonal(points); - this.readerTolerance = READER_TOLERANCE * diagonal(points); Log.debug("StepBRepWrite: mesh of " + (points.length / 3) + " vertices, " + (sourceTriangles == null ? 0 : sourceTriangles.length / 3) + " triangles, plane tolerance " + planeTolerance); @@ -250,8 +264,10 @@ private Mesh(double[] points, long[] sourceTriangles) { TickToc.tic("index"); index(); indexVertices(); + conformBoundaryPartitions(); TickToc.tic("group"); - group(); + if (groupFaces) + group(); Log.debug("StepBRepWrite: grouped into " + faces.size() + " faces"); } @@ -410,6 +426,10 @@ private List splitMiddles(int a, int b) { * hash cells the segment's box covers, so only nearby points are measured. */ private List onSegment(int a, int b) { + return onSegment(a, b, planeTolerance, false); + } + + private List onSegment(int a, int b, double lineTolerance, boolean neighbours) { double[] pa = point(a); double[] pb = point(b); double dx = pb[0] - pa[0], dy = pb[1] - pa[1], dz = pb[2] - pa[2]; @@ -431,7 +451,7 @@ private List onSegment(int a, int b) { // a junction lies on the line, so its own cell catches it; the ring // only matters at the two ends, where rounding can push the point // one cell over - int ring = step == 0 || step == steps ? 1 : 0; + int ring = neighbours || step == 0 || step == steps ? 1 : 0; for (long ox = -ring; ox <= ring; ox++) for (long oy = -ring; oy <= ring; oy++) for (long oz = -ring; oz <= ring; oz++) { @@ -449,7 +469,7 @@ private List onSegment(int a, int b) { double qx = pa[0] + u * dx, qy = pa[1] + u * dy, qz = pa[2] + u * dz; double off = Math.sqrt((q[0] - qx) * (q[0] - qx) + (q[1] - qy) * (q[1] - qy) + (q[2] - qz) * (q[2] - qz)); - if (off <= planeTolerance) + if (off <= lineTolerance && canonical[vertex] == vertex) on.add(vertex); } } @@ -463,10 +483,118 @@ private List onSegment(int a, int b) { return on; } + /** Roundoff of the local arithmetic, independent of unrelated model extent. */ + private double coordinateRoundoff(int... vertices) { + double scale = 1; + for (int vertex : vertices) + for (double coordinate : point(vertex)) + scale = Math.max(scale, Math.abs(coordinate)); + return 32 * Math.ulp(scale); + } + + /** + * BSP clipping partitions each polygon independently. Consequently a closed + * surface can contain A--B opposite B--M--A: geometrically covered, but not + * an indexed manifold. STEP requires the same atomic EDGE_CURVEs on both + * sides. Conform only existing one-use edges before grouping faces. + * + * No points are welded or moved and no boundary is capped. Existing points + * must lie on an edge to floating-point roundoff (not the model's plane or + * snap tolerance). A centre fan retains every boundary segment, including + * collinear chains which a corner fan would discard as zero-area triangles. + */ + private void conformBoundaryPartitions() { + if (byEdge.values().stream().noneMatch(uses -> uses.size() == 1)) + return; + Set boundaryVertices = new HashSet<>(); + for (Map.Entry> edge : byEdge.entrySet()) + if (edge.getValue().size() == 1) { + boundaryVertices.add((int) (edge.getKey() >> 32)); + boundaryVertices.add((int) (long) edge.getKey()); + } + Map> partitions = new HashMap<>(); + for (Map.Entry> edge : byEdge.entrySet()) { + if (edge.getValue().size() != 1) + continue; + int a = (int) (edge.getKey() >> 32), b = (int) (long) edge.getKey(); + List middle = new ArrayList<>(onSegment(a, b, coordinateRoundoff(a, b), true)); + middle.removeIf(vertex -> !boundaryVertices.contains(vertex)); + if (!middle.isEmpty()) + partitions.put(edge.getKey(), middle); + } + if (partitions.isEmpty()) + return; + List conformed = new ArrayList<>(); + List centres = new ArrayList<>(); + int originalCount = points.length / 3; + for (int[] triangle : triangles) { + List boundary = new ArrayList<>(); + boolean split = false; + for (int i = 0; i < 3; i++) { + int a = triangle[i], b = triangle[(i + 1) % 3]; + boundary.add(a); + List middle = partitions.get(key(a, b)); + if (middle == null) + continue; + split = true; + if (a < b) + boundary.addAll(middle); + else + for (int j = middle.size() - 1; j >= 0; j--) + boundary.add(middle.get(j)); + } + if (!split) { + conformed.add(triangle); + continue; + } + double[] a = point(triangle[0]), b = point(triangle[1]), c = point(triangle[2]); + double[] centre = new double[3]; + for (int i = 0; i < 3; i++) + centre[i] = a[i] + (b[i] - a[i]) / 3 + (c[i] - a[i]) / 3; + // Refuse an unrepresentable/degenerate fan rather than dropping or + // reversing any surface. Keep the original open mesh in that case. + double[] normal = triangleCross(a, b, c); + double sourceArea = triangleArea(a, b, c), fanArea = 0; + boolean safe = sourceArea > 0 && Double.isFinite(sourceArea); + for (int i = 0; i < boundary.size(); i++) { + double[] from = point(boundary.get(i)), to = point(boundary.get((i + 1) % boundary.size())); + double[] fanNormal = triangleCross(from, to, centre); + safe &= normal[0] * fanNormal[0] + normal[1] * fanNormal[1] + normal[2] * fanNormal[2] > 0; + fanArea += triangleArea(from, to, centre); + } + double perimeter = distance(a, b) + distance(b, c) + distance(c, a); + double roundoff = coordinateRoundoff(triangle); + safe &= Math.abs(fanArea - sourceArea) <= roundoff * perimeter + 32 * Math.ulp(sourceArea); + if (!safe) { + conformed.add(triangle); + continue; + } + int vertex = originalCount + centres.size(); + centres.add(centre); + for (int i = 0; i < boundary.size(); i++) + conformed.add(new int[]{boundary.get(i), boundary.get((i + 1) % boundary.size()), vertex}); + } + conformedTriangles = centres.size(); + points = java.util.Arrays.copyOf(points, points.length + centres.size() * 3); + for (int i = 0; i < centres.size(); i++) + System.arraycopy(centres.get(i), 0, points, (originalCount + i) * 3, 3); + canonical = java.util.Arrays.copyOf(canonical, points.length / 3); + for (int i = originalCount; i < canonical.length; i++) + canonical[i] = i; + triangles.clear(); + triangles.addAll(conformed); + byEdge.clear(); + byCell.clear(); + index(); + indexVertices(); + Log.debug("StepBRepWrite: conformed " + centres.size() + " triangle boundaries across " + + partitions.size() + " partitioned edges"); + } + /** - * Takes the source triangles exactly as the CSG object holds them. The mesh's - * own cleanup is Manifold simplify's work, done on the CSG before this writer - * sees it; the writer neither welds vertices nor moves nor drops triangles. + * Takes the source triangles exactly as the CSG object holds them. Geometrically covered BSP boundary + * partitions are conformed separately before grouping; this never moves + * source vertices or caps an uncovered boundary. * *

* A triangle naming one vertex twice has no edge to pair and no area to face, @@ -545,6 +673,12 @@ private double surfaceArea(List some) { } + private static double[] triangleCross(double[] a, double[] b, double[] c) { + double ux=b[0]-a[0], uy=b[1]-a[1], uz=b[2]-a[2]; + double vx=c[0]-a[0], vy=c[1]-a[1], vz=c[2]-a[2]; + return new double[]{uy*vz-uz*vy, uz*vx-ux*vz, ux*vy-uy*vx}; + } + /** The area of one triangle given by three points. */ private static double triangleArea(double[] a, double[] b, double[] c) { double ux = b[0] - a[0], uy = b[1] - a[1], uz = b[2] - a[2]; @@ -749,7 +883,9 @@ private boolean fitsPlane(int[] triangle, double[] origin, Vector3d plane) { Vector3d candidate = normal(triangle); if (candidate == null || candidate.dot(plane) <= 0) return false; - return coplanar(triangle, origin, plane); + // A fused face is emitted on one analytic plane. Use the reader's + // plane resolution here, rather than the model-scale junction tolerance. + return coplanar(triangle, origin, plane, PLANE_RESOLUTION); } /** @@ -1103,8 +1239,13 @@ private List pairedPlan(List plan) { settled.add(planned); continue; } - for (int index : planned.region) - settled.add(new Planned(List.of(index), null)); + for (List loop : planned.loops) + for (int i = 0; i < loop.size(); i++) + rest.merge(directed(loop.get(i), loop.get((i + 1) % loop.size())), -1, Integer::sum); + for (int index : planned.region) { + settled.add(new Planned(List.of(index), null)); + countEdges(triangleLoop(index), rest); + } split++; } if (split > 0) @@ -1135,17 +1276,19 @@ private boolean pairsBetterAsTriangles(Planned planned, Map rest) Set touched = new LinkedHashSet<>(loops.keySet()); touched.addAll(triangles.keySet()); + for (long edge : new ArrayList<>(touched)) + touched.add(directed((int) edge, (int) (edge >> 32))); int before = 0; int after = 0; for (long edge : touched) { long reverse = directed((int) (edge & 0xffffffffL), (int) (edge >> 32)); - int loopsForward = rest.getOrDefault(edge, 0) + loops.getOrDefault(edge, 0); - int loopsBackward = rest.getOrDefault(reverse, 0) + loops.getOrDefault(reverse, 0); - int trianglesForward = rest.getOrDefault(edge, 0) + triangles.getOrDefault(edge, 0); - int trianglesBackward = rest.getOrDefault(reverse, 0) + triangles.getOrDefault(reverse, 0); - if (loopsForward != loopsBackward) + int loopsForward = rest.getOrDefault(edge, 0); + int loopsBackward = rest.getOrDefault(reverse, 0); + int trianglesForward = loopsForward - loops.getOrDefault(edge, 0) + triangles.getOrDefault(edge, 0); + int trianglesBackward = loopsBackward - loops.getOrDefault(reverse, 0) + triangles.getOrDefault(reverse, 0); + if (loopsForward > 0 && (loopsForward != 1 || loopsBackward != 1)) before++; - if (trianglesForward != trianglesBackward) + if (trianglesForward > 0 && (trianglesForward != 1 || trianglesBackward != 1)) after++; } return after < before; @@ -1173,6 +1316,20 @@ private boolean pairsBetterAsTriangles(Planned planned, Map rest) * mesh goes out as the exact plan left it. */ private Mesh settledMesh() { + // Apply the existing model-scale identification to triangle indices + // before grouping, not just to VERTEX_POINT names during emission. + // Accept a correction only when it preserves closed indexed topology, + // the export bounds budget and the same source-area budget as verifiedPlan. + if (!Boolean.getBoolean("step.snap.disabled") && isEdgeManifold()) { + Mesh coherent = snappedMesh(); + if (coherent != null && coherent.isEdgeManifold() + && sameBounds(coherent, STEPFile.BREP_BOUNDS_BUDGET_MM) + && Math.abs(surfaceArea(triangles) - coherent.surfaceArea(coherent.triangles)) + <= Math.max(1e-9, surfaceArea(triangles) * 1e-6)) { + Log.debug("StepBRepWrite: using coherent model-scale mesh before face construction"); + return coherent; + } + } List plan = plan(); int fellBack = 0; for (Planned planned : plan) @@ -1218,6 +1375,28 @@ private Mesh settledMesh() { * triangle naming one index twice after the snap has no edge to pair and is * dropped, exactly as {@link #prepare} drops one from the source. */ + private double[] usedBounds() { + double[] result = {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY}; + for (int[] triangle : triangles) + for (int vertex : triangle) { + double[] p = point(vertex); + for (int axis = 0; axis < 3; axis++) { + result[axis] = Math.min(result[axis], p[axis]); + result[axis + 3] = Math.max(result[axis + 3], p[axis]); + } + } + return result; + } + + private boolean sameBounds(Mesh other, double budget) { + double[] a = usedBounds(), b = other.usedBounds(); + for (int i = 0; i < 6; i++) + if (!Double.isFinite(a[i]) || !Double.isFinite(b[i]) || Math.abs(a[i] - b[i]) > budget) + return false; + return true; + } + private Mesh snappedMesh() { int vertexCount = points.length / 3; if (vertexCount == 0) @@ -1914,60 +2093,15 @@ private long vertex(StepEmitter emitter, int vertex) { if (existing != null) return existing; - // A point is written under the name the reader will give it. Two vertices - // closer than a reader's own merge scale are one point to that reader, so - // writing them as two entities leaves every edge that names one of them - // with nothing to pair on the face that names the other — the shell then - // reads as open even though the file's indices pair. The reader's scale is - // the yardstick because the file is for a reader. - int shared = sharedVertexName(vertex); - Long same = vertices.get(shared); - if (same != null) { - vertices.put(vertex, same); - return same; - } - long cartesian = emitter.add("CARTESIAN_POINT(''," + coords(point(shared)) + ")"); + // Exact coincident points were canonicalized before grouping. Keep every + // remaining vertex distinct: renaming nearby endpoints here would change + // the topology while their LINE geometry still uses the original points. + long cartesian = emitter.add("CARTESIAN_POINT(''," + coords(point(vertex)) + ")"); long id = emitter.add("VERTEX_POINT('',#" + cartesian + ")"); - vertices.put(shared, id); vertices.put(vertex, id); return id; } - /** The lowest index of the vertices a reader's tolerance makes one point. */ - private int sharedVertexName(int vertex) { - if (readerNames == null) { - int count = points.length / 3; - int[] name = new int[count]; - for (int v = 0; v < count; v++) - name[v] = v; - Map> byCell = new HashMap<>(); - for (int v = 0; v < count; v++) { - double[] p = point(v); - long cx = Math.round(p[0] / readerTolerance); - long cy = Math.round(p[1] / readerTolerance); - long cz = Math.round(p[2] / readerTolerance); - int lowest = v; - for (int dx = -1; dx <= 1; dx++) - for (int dy = -1; dy <= 1; dy++) - for (int dz = -1; dz <= 1; dz++) { - List cell = byCell.get(cell(cx + dx, cy + dy, cz + dz)); - if (cell == null) - continue; - for (int other : cell) - if (distance(p, point(other)) <= readerTolerance) - lowest = Math.min(lowest, name[other]); - } - name[v] = lowest; - byCell.computeIfAbsent(cell(cx, cy, cz), unused -> new ArrayList<>()).add(v); - } - readerNames = name; - } - return readerNames[vertex]; - } - - /** Each vertex to the name the reader will give its point. */ - private int[] readerNames; - private long line(StepEmitter emitter, double[] a, double[] b) { double dx = b[0] - a[0]; double dy = b[1] - a[1]; @@ -1982,7 +2116,10 @@ private long line(StepEmitter emitter, double[] a, double[] b) { long origin = emitter.add("CARTESIAN_POINT(''," + coords(a) + ")"); long direction = emitter.add( "DIRECTION('',(" + real(dx / length) + "," + real(dy / length) + "," + real(dz / length) + "))"); - long vector = emitter.add("VECTOR('',#" + direction + "," + real(length) + ")"); + // LINE is unbounded; EDGE_CURVE endpoints trim it. A unit vector + // preserves its geometry without a tiny parameter scale that a STEP + // reader may reject as a zero vector. + long vector = emitter.add("VECTOR('',#" + direction + ",1.)"); return emitter.add("LINE('',#" + origin + ",#" + vector + ")"); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepEmitter.java b/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepEmitter.java index 55e605d9..a9c754af 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepEmitter.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepEmitter.java @@ -5,13 +5,19 @@ final class StepEmitter { private final StringBuilder out = new StringBuilder(); private long nextId; + private final java.util.Map kinds = new java.util.HashMap<>(); long add(String entity) { long id = ++nextId; + kinds.put(id, entity.substring(0, entity.indexOf('(')).trim()); out.append('#').append(id).append('=').append(entity).append(';').append('\n'); return id; } + boolean is(long id, String kind) { + return kind.equals(kinds.get(id)); + } + String text() { return out.toString(); } diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepImport.java b/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepImport.java index 5e9882aa..e7fcca1c 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepImport.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepImport.java @@ -233,6 +233,8 @@ private static CSG readTessellation(StepReader reader, Instance representation) * so it reproduces the source mesh exactly. */ private static boolean isTessellated(StepReader reader, Instance representation) { + if (StepReader.kindOf(representation, "TESSELLATED_SHAPE_REPRESENTATION")) + return true; for (Value item : reader.list(reader.attribute(representation, "REPRESENTATION", "items"))) { Instance instance = reader.instance(item); if (StepReader.kindOf(instance, "TESSELLATED_SURFACE_SET") diff --git a/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepTessellatedWrite.java b/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepTessellatedWrite.java index 38a659e4..8e7bb893 100644 --- a/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepTessellatedWrite.java +++ b/src/main/java/com/neuronrobotics/bowlerstudio/threed/StepTessellatedWrite.java @@ -28,7 +28,7 @@ private StepTessellatedWrite() { * A {@code TESSELLATED_SHAPE_REPRESENTATION} over the mesh, or 0 when the mesh * has no triangles to describe. */ - static long representation(StepEmitter emitter, CSG csg, String name, long context) { + static long representation(StepEmitter emitter, CSG csg, String name, long context, long solid) { double[] vertices = csg.getVertices(); long[] triangles = csg.getTriangles(); if (vertices == null || triangles == null || triangles.length < 3 || vertices.length < 9) @@ -38,11 +38,14 @@ static long representation(StepEmitter emitter, CSG csg, String name, long conte + " triangles for " + name); TickToc.tic("write tessellation " + name); long coordinates = coordinates(emitter, vertices); - // a triangulated surface set is a tessellated surface set with an index list - // per triangle, so its parameters are: name, coordinates, pnmax, normals, - // pnindex, triangles - long surface = emitter.add("TRIANGULATED_SURFACE_SET(" + quote(name) + ",#" + coordinates + ",$,$,$," - + triangles(triangles) + ")"); + // Retain every mesh vertex and triangle. A solid link lets the reader + // attach this alternate representation to the existing BRep rather + // than importing an additional face with no analytic surface. + long surface = emitter.add("TRIANGULATED_FACE(" + quote(name) + ",#" + coordinates + "," + + (vertices.length / 3) + ",(),$,()," + triangles(triangles) + ")"); + long tessellated = emitter.is(solid, "MANIFOLD_SOLID_BREP") + ? emitter.add("TESSELLATED_SOLID(" + quote(name) + ",(#" + surface + "),#" + solid + ")") + : surface; // the placement keeps the representation's own frame at the origin, matching // what the BRep representation does @@ -51,7 +54,7 @@ static long representation(StepEmitter emitter, CSG csg, String name, long conte long reference = emitter.add("DIRECTION('',(1.,0.,0.))"); long placement = emitter.add("AXIS2_PLACEMENT_3D('',#" + origin + ",#" + axis + ",#" + reference + ")"); - return emitter.add("TESSELLATED_SHAPE_REPRESENTATION(" + quote(name) + ",(#" + placement + ",#" + surface + return emitter.add("TESSELLATED_SHAPE_REPRESENTATION(" + quote(name) + ",(#" + placement + ",#" + tessellated + "),#" + context + ")"); } diff --git a/test/java/src/com/neuronrobotics/bowlerstudio/threed/StepBoundaryPartitionTest.java b/test/java/src/com/neuronrobotics/bowlerstudio/threed/StepBoundaryPartitionTest.java new file mode 100644 index 00000000..2114d7e6 --- /dev/null +++ b/test/java/src/com/neuronrobotics/bowlerstudio/threed/StepBoundaryPartitionTest.java @@ -0,0 +1,161 @@ +package com.neuronrobotics.bowlerstudio.threed; + +import static org.junit.Assert.*; +import java.lang.reflect.*; +import java.util.*; +import org.junit.Test; +import eu.mihosoft.vrl.v3d.CSG; +import javafx.scene.paint.Color; + +/** BSP boundary partitions are not necessarily an indexed, conforming triangle mesh. */ +public class StepBoundaryPartitionTest { + private static CSG tetra(double[] left, double[] right, double gap) { + List p = new ArrayList<>(Arrays.asList(0.,0.,0., 9.,0.,0., 0.,5.,0., 0.,0.,4.)); + List t = new ArrayList<>(); + List a = chain(p,left,0), b = chain(p,right,gap); + for(int i=0;i chain(List p,double[] x,double gap) { + List c=new ArrayList<>();c.add(0); + for(double v:x) {c.add(p.size()/3);p.add(v);p.add(gap);p.add(0.);} + c.add(1);return c; + } + private static void add(List t,int a,int b,int c){t.add((long)a);t.add((long)b);t.add((long)c);} + private static String point(double[] p){return Arrays.toString(p);} + private static int unmatched(CSG c) { + Map e=new HashMap<>(); + for(StepFace f:StepBRepWrite.faces(c)) for(List l:f.loops) + for(int i=0;i"+point(l.get((i+1)%l.size())),1,Integer::sum); + int bad=0;for(String k:e.keySet()){int i=k.indexOf('>');String r=k.substring(i+1)+">"+k.substring(0,i);if(e.get(k)!=1||e.getOrDefault(r,0)!=1)bad++;}return bad; + } + @Test public void oneEdgeAgainstNineSegmentsClosesWithoutMovingSource() { + CSG c=tetra(new double[]{},new double[]{1,2,3,4,5,6,7,8},0); + double[] p=c.getVertices().clone();long[] t=c.getTriangles().clone(); + assertEquals(0,unmatched(c));assertArrayEquals(p,c.getVertices(),0);assertArrayEquals(t,c.getTriangles()); + StepEmitter e=new StepEmitter();StepBRepWrite.items(e,c,"nine pieces"); + assertTrue(e.text().contains("CLOSED_SHELL"));assertFalse(e.text().contains("OPEN_SHELL")); + } + @Test public void independentlyPartitionedSidesGetTheSameAtomicEdges() { + assertEquals(0,unmatched(tetra(new double[]{1,4,7},new double[]{2,3,5,6,8},0))); + } + @Test public void aRealOffsetGapIsNotConformedOrCapped() { + CSG c=tetra(new double[]{},new double[]{1,2,3,4,5,6,7,8},1e-8); + assertTrue(unmatched(c)>0); + // An unrelated coordinate must not inflate the local collinearity budget. + double[] withDistantUnused=Arrays.copyOf(c.getVertices(),c.getVertices().length+3); + withDistantUnused[withDistantUnused.length-3]=1e12; + assertTrue(unmatched(new CSG(withDistantUnused,c.getTriangles(),Color.GRAY))>0); + StepEmitter e=new StepEmitter();StepBRepWrite.items(e,c,"real gap"); + assertFalse(e.text().contains("CLOSED_SHELL"));assertTrue(e.text().contains("OPEN_SHELL")); + } + @Test public void anUncoveredIntervalRemainsAnOpenBoundary() { + CSG complete=tetra(new double[]{},new double[]{1,2,3,4,5,6,7,8},0); + long[] source=complete.getTriangles(), missing=new long[source.length-3]; + System.arraycopy(source,0,missing,0,12); + System.arraycopy(source,15,missing,12,source.length-15); + CSG c=new CSG(complete.getVertices(),missing,Color.GRAY); + assertTrue(unmatched(c)>0); + StepEmitter e=new StepEmitter();StepBRepWrite.items(e,c,"uncovered interval"); + assertTrue(e.text().contains("OPEN_SHELL")); + } + @Test public void retainedTessellationUsesTheSameConformingBoundaryContract() throws Exception { + CSG.OptType previous=CSG.getDefaultOptionType(); + try { + CSG.setDefaultOptType(CSG.OptType.CSG_BOUND); + CSG c=tetra(new double[]{1,4,7},new double[]{2,3,5,6,8},0); + STEPFile writer=new STEPFile(c); + STEPFile reader=new STEPFile(new java.io.ByteArrayInputStream(writer.toStep().getBytes(java.nio.charset.StandardCharsets.UTF_8))); + assertEquals(1,reader.getShapes().size()); + CSG mesh=reader.getShapes().get(0).getMesh(); + assertNotNull(mesh); + assertArrayEquals(writer.getCsg().getVertices(),mesh.getVertices(),0); + assertArrayEquals(writer.getCsg().getTriangles(),mesh.getTriangles()); + Map uses=new HashMap<>();long[] t=mesh.getTriangles(); + for(int i=0;i>>32); + assertEquals(Integer.valueOf(1),uses.get(reverse)); + } + } finally {CSG.setDefaultOptType(previous);} + } + @Test public void balancedTwoToTwoUsesAreStillRejected() throws Exception { + Method watertight=StepBRepWrite.class.getDeclaredMethod("isWatertight",List.class); + watertight.setAccessible(true); + List> face=List.of(List.of(0,1,2)),reverse=List.of(List.of(2,1,0)); + assertTrue((Boolean)watertight.invoke(null,List.of(face,reverse))); + assertFalse("balanced multiplicity is not a manifold shell", + (Boolean)watertight.invoke(null,List.of(face,reverse,face,reverse))); + } + private static Map edgeCounts(List> loops) { + Map edges=new HashMap<>(); + for(List loop:loops) for(int i=0;i> loops) { + Map edges=edgeCounts(loops);int bad=0; + for(long edge:edges.keySet()) { + long reverse=((edge&0xffffffffL)<<32)|(edge>>>32); + if(edges.get(edge)!=1 || edges.getOrDefault(reverse,0)!=1)bad++; + } + return bad; + } + @Test public void individuallyFavorableFallbacksAreRecheckedAgainstAcceptedChanges() throws Exception { + // An accounting counterexample, not a claim about the box/sphere geometry: + // two replacements improve 13 -> 12 alone, but together worsen it to 14. + int[][] triangles={{4,3,2},{3,4,1},{5,0,6},{2,0,1},{6,4,0}}; + List> loops=List.of(List.of(4,6,3,2),List.of(3,6,4,0,5,1), + List.of(1,5,2,3,0,6),List.of(2,0,3,5,1),List.of(6,1,4,0)); + Class mesh=Class.forName(StepBRepWrite.class.getName()+"$Mesh"); + Constructor ctor=mesh.getDeclaredConstructor(double[].class,long[].class);ctor.setAccessible(true); + Object m=ctor.newInstance(new double[]{0,0,0, 1,0,0, 0,1,0, 1,1,0, 2,0,0, 0,2,0, 2,2,0},new long[]{0,1,2}); + Field ts=mesh.getDeclaredField("triangles");ts.setAccessible(true); + List raw=(List)ts.get(m);raw.clear();raw.addAll(Arrays.asList(triangles)); + Class planned=Class.forName(StepBRepWrite.class.getName()+"$Mesh$Planned"); + Constructor pc=planned.getDeclaredConstructor(List.class,List.class);pc.setAccessible(true); + List plan=new ArrayList<>();for(int i=0;i> one=new ArrayList<>(loops); + one.set(i,Arrays.asList(triangles[i][0],triangles[i][1],triangles[i][2])); + assertEquals(12,badUses(one)); + assertTrue((Boolean)better.invoke(m,plan.get(i),edgeCounts(loops))); + } + List> both=new ArrayList<>(loops); + for(int i:new int[]{1,3})both.set(i,Arrays.asList(triangles[i][0],triangles[i][1],triangles[i][2])); + assertEquals(14,badUses(both)); + Method settle=mesh.getDeclaredMethod("pairedPlan",List.class);settle.setAccessible(true); + List result=(List)settle.invoke(m,plan); + Field regions=planned.getDeclaredField("region"),outlines=planned.getDeclaredField("loops"); + regions.setAccessible(true);outlines.setAccessible(true); + List accepted=new ArrayList<>();List> actual=new ArrayList<>(); + for(Object face:result) { + int i=((List)regions.get(face)).get(0); + if(outlines.get(face)==null) {accepted.add(i);actual.add(Arrays.asList(triangles[i][0],triangles[i][1],triangles[i][2]));} + else actual.addAll((List>)outlines.get(face)); + } + assertEquals(List.of(1),accepted); + assertEquals(12,badUses(actual)); + } + @Test public void fallbackDoesNotCountTheFaceUnderComparisonTwice() throws Exception { + Class mesh=Class.forName(StepBRepWrite.class.getName()+"$Mesh"); + Constructor ctor=mesh.getDeclaredConstructor(double[].class,long[].class);ctor.setAccessible(true); + Object m=ctor.newInstance(new double[]{0,0,0, 0,2,0, 4,0,0, 2,0,0},new long[]{0,1,2}); + Field ts=mesh.getDeclaredField("triangles");ts.setAccessible(true); + List triangles=(List)ts.get(m);triangles.clear();triangles.add(new int[]{0,1,2}); + Class planned=Class.forName(StepBRepWrite.class.getName()+"$Mesh$Planned"); + Constructor pc=planned.getDeclaredConstructor(List.class,List.class);pc.setAccessible(true); + List loop=List.of(0,1,2,3); + Object face=pc.newInstance(List.of(0),List.of(loop)); + Map all=new HashMap<>(); + for(int i=0;i=3); + } + @Test + public void subConfusionLineUsesAUnitVectorWithoutMovingItsEndpoints() { + // The first edge is the actual 9.999999406e-8 mm edge found in the nametag. + CSG csg=new CSG(new double[]{-64.00000005,-117,8,-63.99999995,-117,8,-64,-116,8}, + new long[]{0,1,2},javafx.scene.paint.Color.GRAY); + StepEmitter e=new StepEmitter();StepBRepWrite.items(e,csg,"tiny-line"); + Matcher entities=Pattern.compile("#(\\d+)=(.*?);").matcher(e.text()); + Map rhs=new HashMap<>(); + while(entities.find())rhs.put(entities.group(1),entities.group(2)); + int count=0; + for(String entity:rhs.values())if(entity.startsWith("LINE(")) { + Matcher refs=Pattern.compile("#(\\d+)").matcher(entity);refs.find();refs.find(); + String vector=rhs.get(refs.group(1)); + double magnitude=Double.parseDouble(vector.substring(vector.lastIndexOf(',')+1,vector.length()-1)); + assertEquals("STEP LINE direction scale is independent of edge length",1.0,magnitude,0.0);count++; + } + assertEquals(3,count); + } + +} diff --git a/test/java/src/junit/bowler/AdversarialNametagStepExportTest.java b/test/java/src/junit/bowler/AdversarialNametagStepExportTest.java index 31ea7335..ac0105ea 100644 --- a/test/java/src/junit/bowler/AdversarialNametagStepExportTest.java +++ b/test/java/src/junit/bowler/AdversarialNametagStepExportTest.java @@ -122,6 +122,7 @@ public void theWholeLoopFromCSGToStepToFreeCADTo3mfToCSG() throws Throwable { File threeMF = new File(work, "Marvelous_Champion_Nametag_exported.3mf"); FreecadLoader.to3MFFile(fcStd, threeMF); assertTrue("the FreeCAD 3MF export wrote no file", threeMF.isFile() && threeMF.length() > 0); + verifyActualMesh(threeMF, work); // the FreeCAD gate over the exported STEP, its report read here: the verdict // comes from what FreeCAD measured, not from this JVM's own opinion @@ -143,17 +144,45 @@ public void theWholeLoopFromCSGToStepToFreeCADTo3mfToCSG() throws Throwable { // bounds, to a hundredth of a micron eu.mihosoft.vrl.v3d.Bounds actual = roundTripped.getBounds(); double[][] checks = {{expected.getMin().x, actual.getMin().x}, {expected.getMin().y, actual.getMin().y}, - {expected.getMin().z, expected.getMin().z}, {expected.getMax().x, actual.getMax().x}, + {expected.getMin().z, actual.getMin().z}, {expected.getMax().x, actual.getMax().x}, {expected.getMax().y, actual.getMax().y}, {expected.getMax().z, actual.getMax().z}}; String[] names = {"minimum x", "minimum y", "minimum z", "maximum x", "maximum y", "maximum z"}; for (int at = 0; at < checks.length; at++) { double wanted = checks[at][0]; - double got = checks[at][at == 2 ? 0 : 1]; + double got = checks[at][1]; assertTrue("the round trip's " + names[at] + " " + got + " must match the reference's " + wanted + " within " + BOUNDS_TOLERANCE, Math.abs(got - wanted) <= BOUNDS_TOLERANCE); } } + /** Verify the actual helper output, including duplicate build instances, before Manifold loads it. */ + private static void verifyActualMesh(File mesh, File work) throws Exception { + File script = new File(work, "step_export_mesh_gate.py"); + try (java.io.InputStream in = AdversarialNametagStepExportTest.class + .getResourceAsStream("/step_export_mesh_gate.py")) { + assertNotNull("the actual-mesh checker resource must exist", in); + Files.copy(in, script.toPath()); + } + File report = new File(work, "actual_mesh_report.json"); + File log = new File(work, "actual_mesh_check.log"); + ProcessBuilder builder = new ProcessBuilder( + DownloadManager.getConfigExecutable("freecad", null).getAbsolutePath(), + "-c", script.getAbsolutePath()); + builder.environment().put("QT_QPA_PLATFORM", "offscreen"); + builder.environment().put("CHECK_3MF", mesh.getAbsolutePath()); + builder.environment().put("CHECK_JSON", report.getAbsolutePath()); + builder.redirectErrorStream(true).redirectOutput(log); + Process process = builder.start(); + boolean finished = process.waitFor(60, java.util.concurrent.TimeUnit.SECONDS); + if (!finished) { + process.destroyForcibly(); + throw new AssertionError("actual 3MF checker timed out; log: " + log.getAbsolutePath()); + } + assertTrue("actual 3MF checker wrote no report; log: " + log.getAbsolutePath(), report.isFile()); + assertEquals("actual helper 3MF is invalid or duplicated: " + Files.readString(report.toPath()), + 0, process.exitValue()); + } + /** The occurrences of a token in the file text, for the entity counts. */ private static int count(String text, String token) { return text.split(java.util.regex.Pattern.quote(token), -1).length - 1; @@ -207,5 +236,10 @@ private static void runGate(File step, File report) throws Exception { } Log.debug("the FreeCAD gate printed:\n" + new String(Files.readAllBytes(log.toPath()), StandardCharsets.UTF_8)); assertTrue("the FreeCAD gate wrote no report at " + report.getAbsolutePath(), report.isFile()); + String gateLog = Files.readString(log.toPath()); + assertEquals("FreeCAD structural gate failed; round-trip JSON is a separate verdict:\n" + gateLog, + 0, process.exitValue()); + assertTrue("FreeCAD must explicitly report structural PASS: " + log.getAbsolutePath(), + gateLog.contains("GATE: PASS")); } } diff --git a/test/java/src/junit/bowler/CharmingTrollBRepCoverageTest.java b/test/java/src/junit/bowler/CharmingTrollBRepCoverageTest.java index b2d21ddb..197317fd 100644 --- a/test/java/src/junit/bowler/CharmingTrollBRepCoverageTest.java +++ b/test/java/src/junit/bowler/CharmingTrollBRepCoverageTest.java @@ -32,7 +32,6 @@ * CAD package does. What comes back must enclose the same volume and cover the * same surface as the mesh it was written from. */ -@Ignore public class CharmingTrollBRepCoverageTest { private static final File CORPUS = new File("testStepFiles"); diff --git a/test/java/src/junit/bowler/CharmingTrollStepRoundTripTest.java b/test/java/src/junit/bowler/CharmingTrollStepRoundTripTest.java index 74e592d5..3b6a367d 100644 --- a/test/java/src/junit/bowler/CharmingTrollStepRoundTripTest.java +++ b/test/java/src/junit/bowler/CharmingTrollStepRoundTripTest.java @@ -250,7 +250,7 @@ public void theTessellationIsRelatedToTheBRep() throws Throwable { String text = new STEPFile(parts).toStep(); Log.debug("text: " + text.length() + " characters"); assertTrue("the mesh must be carried as a tessellation", text.contains("TESSELLATED_SHAPE_REPRESENTATION")); - assertTrue("the tessellation must be tied to the BRep", text.contains("SHAPE_REPRESENTATION_RELATIONSHIP")); + assertTrue("the tessellation must be tied to the BRep", text.contains("REPRESENTATION_RELATIONSHIP(")); assertEquals("every part gets a tessellation of its own", parts.size(), count(text, "TESSELLATED_SHAPE_REPRESENTATION")); // one shape definition per part, plus the assembly when there is more than one diff --git a/test/java/src/junit/bowler/StepLinkedTessellationRegressionTest.java b/test/java/src/junit/bowler/StepLinkedTessellationRegressionTest.java new file mode 100644 index 00000000..f45a09d8 --- /dev/null +++ b/test/java/src/junit/bowler/StepLinkedTessellationRegressionTest.java @@ -0,0 +1,24 @@ +package junit.bowler; + +import static org.junit.Assert.*; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import org.junit.Test; +import com.neuronrobotics.bowlerstudio.threed.STEPFile; +import eu.mihosoft.vrl.v3d.CSG; +import eu.mihosoft.vrl.v3d.Cube; + +public class StepLinkedTessellationRegressionTest { + @Test + public void alternateMeshRetainsItsIndicesWithoutCreatingAnotherPart() throws Exception { + CSG c=new Cube(10).toCSG(); + STEPFile writer=new STEPFile(c); + String text=writer.toStep(); + STEPFile reader=new STEPFile(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8))); + assertEquals("one physical part despite two representations",1,reader.getShapes().size()); + CSG mesh=reader.getShapes().get(0).getMesh(); + assertNotNull("retain the alternate mesh",mesh); + assertArrayEquals(writer.getCsg().getVertices(),mesh.getVertices(),0.0); + assertArrayEquals(writer.getCsg().getTriangles(),mesh.getTriangles()); + } +} diff --git a/test/java/src/junit/bowler/StepNametagSeamRegressionTest.java b/test/java/src/junit/bowler/StepNametagSeamRegressionTest.java new file mode 100644 index 00000000..3c81bdb6 --- /dev/null +++ b/test/java/src/junit/bowler/StepNametagSeamRegressionTest.java @@ -0,0 +1,41 @@ +package junit.bowler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.List; +import org.junit.Test; +import com.neuronrobotics.bowlerstudio.threed.StepBRepWrite; +import com.neuronrobotics.bowlerstudio.threed.StepFace; +import eu.mihosoft.vrl.v3d.CSG; + +/** Exact triangles 777, 805 and 925 after STEPFile's unchanged nametag preprocessing. */ +public class StepNametagSeamRegressionTest { + @Test + public void theMeasuredNametagDiagonalStaysInsideOneFace() { + double[] points = { + -59.882693858936115, -68.86891176844921, 2.999998999999998, // 381 + -59.92195629552549, -69.60209397678534, 2.999998999999998, // 372 + -59.92190534855179, -69.6020939797163, 5.999997999999998, // 420 + -59.88264291222147, -68.8689117655158, 5.999997999999998, // 457 + -59.88265600289158, -68.8691561371088, 5.999997999999998 // 456 + }; + CSG mesh = new CSG(points, new long[]{0,1,2, 0,2,3, 3,2,4}, javafx.scene.paint.Color.GRAY); + List faces = StepBRepWrite.faces(mesh); + assertEquals("the side and its 4.39e-9 mm sliver must form one face", 1, faces.size()); + assertEquals(1, faces.get(0).loops.size()); + List loop = faces.get(0).loops.get(0); + assertEquals("keep the sliver tip on the outline", 5, loop.size()); + for (int i=0; i faces=StepBRepWrite.faces(c); + assertEquals("these source triangles are nonplanar; their weighted fit moves the boundary 5.55e-5 mm",2,faces.size()); + } +} diff --git a/test/resources/step_export_mesh_gate.py b/test/resources/step_export_mesh_gate.py new file mode 100644 index 00000000..c8593157 --- /dev/null +++ b/test/resources/step_export_mesh_gate.py @@ -0,0 +1,30 @@ +"""Check the actual single-body 3MF output before a CSG loader can clean it.""" +import json, os, sys, traceback, zipfile +import xml.etree.ElementTree as ET +import Mesh + +try: + path = os.environ['CHECK_3MF'] + mesh = Mesh.Mesh(path) + with zipfile.ZipFile(path) as archive: + entry = next(n for n in archive.namelist() if n.lower().endswith('.model')) + model = ET.fromstring(archive.read(entry)) + namespace = {'m': model.tag.split('}')[0][1:]} + build_items = len(model.findall('m:build/m:item', namespace)) + report = {'file': path, 'facets': mesh.CountFacets, 'vertices': mesh.CountPoints, + 'solid': mesh.isSolid(), 'self_intersections': mesh.hasSelfIntersections(), + 'non_manifold_edges': mesh.hasNonManifolds(), 'components': mesh.countComponents(), + 'build_items': build_items} + report['pass'] = (report['facets'] > 0 and report['solid'] + and not report['self_intersections'] and not report['non_manifold_edges'] + and report['components'] == 1 and build_items == 1) + with open(os.environ['CHECK_JSON'], 'w') as handle: + json.dump(report, handle, indent=2) + print(json.dumps(report)) + code = 0 if report['pass'] else 1 +except BaseException: + traceback.print_exc() + code = 2 +sys.stdout.flush() +sys.stderr.flush() +os._exit(code)