Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions src/main/java/com/neuronrobotics/bowlerstudio/threed/STEPFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@ public STEPFile(List<CSG> 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
Expand Down Expand Up @@ -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);
}

Expand All @@ -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 + ")");
}

Expand Down Expand Up @@ -391,7 +396,7 @@ private static void assembly(StepEmitter emitter, List<Part> 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);
}

Expand Down
297 changes: 217 additions & 80 deletions src/main/java/com/neuronrobotics/bowlerstudio/threed/StepBRepWrite.java

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,19 @@ final class StepEmitter {

private final StringBuilder out = new StringBuilder();
private long nextId;
private final java.util.Map<Long, String> 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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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 + ")");
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<Double> p = new ArrayList<>(Arrays.asList(0.,0.,0., 9.,0.,0., 0.,5.,0., 0.,0.,4.));
List<Long> t = new ArrayList<>();
List<Integer> a = chain(p,left,0), b = chain(p,right,gap);
for(int i=0;i<a.size()-1;i++) add(t,2,a.get(i+1),a.get(i));
for(int i=0;i<b.size()-1;i++) add(t,3,b.get(i),b.get(i+1));
add(t,1,2,3);add(t,2,0,3);
return new CSG(p.stream().mapToDouble(Double::doubleValue).toArray(),t.stream().mapToLong(Long::longValue).toArray(),Color.GRAY);
}
private static List<Integer> chain(List<Double> p,double[] x,double gap) {
List<Integer> 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<Long> 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<String,Integer> e=new HashMap<>();
for(StepFace f:StepBRepWrite.faces(c)) for(List<double[]> l:f.loops)
for(int i=0;i<l.size();i++) e.merge(point(l.get(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<Long,Integer> uses=new HashMap<>();long[] t=mesh.getTriangles();
for(int i=0;i<t.length;i+=3)for(int j=0;j<3;j++)
uses.merge((t[i+j]<<32)|(t[i+(j+1)%3]&0xffffffffL),1,Integer::sum);
for(long edge:uses.keySet()) {
assertEquals(Integer.valueOf(1),uses.get(edge));
long reverse=((edge&0xffffffffL)<<32)|(edge>>>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<List<Integer>> 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<Long,Integer> edgeCounts(List<List<Integer>> loops) {
Map<Long,Integer> edges=new HashMap<>();
for(List<Integer> loop:loops) for(int i=0;i<loop.size();i++)
edges.merge(((long)loop.get(i)<<32)|(loop.get((i+1)%loop.size())&0xffffffffL),1,Integer::sum);
return edges;
}
private static int badUses(List<List<Integer>> loops) {
Map<Long,Integer> 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<List<Integer>> 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<int[]> raw=(List<int[]>)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<Object> plan=new ArrayList<>();for(int i=0;i<loops.size();i++)plan.add(pc.newInstance(List.of(i),List.of(loops.get(i))));
Method better=mesh.getDeclaredMethod("pairsBetterAsTriangles",planned,Map.class);better.setAccessible(true);
assertEquals(13,badUses(loops));
for(int i:new int[]{1,3}) {
List<List<Integer>> 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<List<Integer>> 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<Integer> accepted=new ArrayList<>();List<List<Integer>> actual=new ArrayList<>();
for(Object face:result) {
int i=((List<Integer>)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<List<Integer>>)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<int[]> triangles=(List<int[]>)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<Integer> loop=List.of(0,1,2,3);
Object face=pc.newInstance(List.of(0),List.of(loop));
Map<Long,Integer> all=new HashMap<>();
for(int i=0;i<loop.size();i++) {int a=loop.get(i),b=loop.get((i+1)%loop.size());all.put(((long)a<<32)|(b&0xffffffffL),1);all.put(((long)b<<32)|(a&0xffffffffL),1);}
Method better=mesh.getDeclaredMethod("pairsBetterAsTriangles",planned,Map.class);better.setAccessible(true);
assertFalse("a closed four-edge face must not become an unmatched triangle",(Boolean)better.invoke(m,face,all));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.neuronrobotics.bowlerstudio.threed;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertTrue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import eu.mihosoft.vrl.v3d.CSG;

/** Actual nametag corner: triangle 248 and its three edge neighbors after preprocessing. */
public class StepVertexIdentityTest {
@Test
public void nearbyDistinctCornerVerticesDoNotBecomeClosedLineEdges() {
double[] points={
-64.00000005,-116.99999995,7.9999985928571435, //109
-64.00000005,-117.00000017857143,7.99999905, //111
-64.00000005,-116.99999995,7.99999905, //110
-63.99999995,-117.00000005,1.7499992062499994, //57
-64.29451211029968,-116.99999995,7.99999905 //108
};
CSG csg=new CSG(points,new long[]{0,1,2,0,3,1,1,4,2,4,0,2},javafx.scene.paint.Color.GRAY);
StepEmitter emitter=new StepEmitter();
StepBRepWrite.items(emitter,csg,"actual-corner");
Matcher m=Pattern.compile("EDGE_CURVE\\('',[#](\\d+),[#](\\d+),[#](\\d+),\\.T\\.\\)").matcher(emitter.text());
int edges=0;
while(m.find()) {
edges++;
assertFalse("distinct source points must not become a LINE edge with the same start/end VERTEX_POINT: "+m.group(),m.group(1).equals(m.group(2)));
}
assertTrue("the exact corner must emit edges",edges>=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<String,String> 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);
}

}
Loading
Loading