def __init__(self, myShape, ignore_orientation=False): """ implements topology traversal from any TopoDS_Shape this class lets you find how various topological entities are connected from one to another find the faces connected to an edge, find the vertices this edge is made from, get all faces connected to a vertex, and find out how many topological elements are connected from a source *note* when traversing TopoDS_Wire entities, its advised to use the specialized ``WireExplorer`` class, which will return the vertices / edges in the expected order :param myShape: the shape which topology will be traversed :param ignore_orientation: filter out TopoDS_* entities of similar TShape but different Orientation for instance, a cube has 24 edges, 4 edges for each of 6 faces that results in 48 vertices, while there are only 8 vertices that have a unique geometric coordinate in certain cases ( computing a graph from the topology ) its preferable to return topological entities that share similar geometry, though differ in orientation by setting the ``ignore_orientation`` variable to True, in case of a cube, just 12 edges and only 8 vertices will be returned for further reference see TopoDS_Shape IsEqual / IsSame methods """ self.myShape = myShape self.ignore_orientation = ignore_orientation self.topExp = TopExp_Explorer()
def occ_triangle_mesh(event=None): # # Mesh the shape # BRepMesh_IncrementalMesh(aShape, 0.1) builder = BRep_Builder() Comp = TopoDS_Compound() builder.MakeCompound(Comp) ex = TopExp_Explorer(aShape, TopAbs_FACE) while ex.More(): F = topods_Face(ex.Current()) L = TopLoc_Location() facing = (BRep_Tool().Triangulation(F, L)) tab = facing.Nodes() tri = facing.Triangles() for i in range(1, facing.NbTriangles() + 1): trian = tri.Value(i) #print trian index1, index2, index3 = trian.Get() for j in range(1, 4): if j == 1: M = index1 N = index2 elif j == 2: N = index3 elif j == 3: M = index2 ME = BRepBuilderAPI_MakeEdge(tab.Value(M), tab.Value(N)) if ME.IsDone(): builder.Add(Comp, ME.Edge()) ex.Next() display.DisplayShape(Comp, update=True)
def prop_solids(self): sol_exp = TopExp_Explorer(self.splitter.Shape(), TopAbs_SOLID) self.sol_num = 0 while sol_exp.More(): self.sol_num += 1 self.prop_soild(sol_exp.Current()) sol_exp.Next()
def triangulate_solid(self): mesh = BRepMesh_IncrementalMesh(self.shape, 0.3, False, 0.5, True) mesh.Perform() b = BRep_Tool() ex = TopExp_Explorer(self.shape, TopAbs_FACE) faces = [] verts = [] while ex.More(): face = topods_Face(ex.Current()) location = TopLoc_Location() triang_face = (b.Triangulation(face, location)) if triang_face != None: tab = triang_face.Nodes() tri = triang_face.Triangles() for i in range(1, triang_face.NbTriangles() + 1): try: verts.append(list(tab.Value(i).Coord())) except: continue for i in range(1, triang_face.NbTriangles() + 1): try: index1, index2, index3 = tri.Value(i).Get() faces.append([index1 - 1, index2 - 1, index3 - 1]) except: continue ex.Next() return verts, faces
def getShapeItems(shape, topologyType): items = [] ex = TopExp_Explorer(shape, topologyType) while ex.More(): items.append(ex.Current()) ex.Next() return items
def objToStr(obj) : ret = dict() ret['CLASS'] = str(obj.__class__.__name__) if isinstance(obj,gp_Pnt): ret['x,y,z'] = '(' + str(obj.X()) + ',' + str(obj.Y()) + ',' + str(obj.Z()) + ')' elif isinstance(obj, AIS_Point): ret['Component().Pnt()'] = obj.Component().Pnt() elif isinstance(obj, AIS_Line): pass elif isinstance(obj, Geom_Point): ret['Pnt()'] = obj.Pnt() elif isinstance(obj, AIS_Shape): ret['Shape()'] = obj.Shape() elif isinstance(obj, TopoDS_Shape): ret['Type'] = SHAPE_TYPES[obj.ShapeType()] exp = TopExp_Explorer(obj, TopAbs_ShapeEnum(TopAbs_ShapeEnum.TopAbs_EDGE)) i = 0 while (exp.More()): ret['Edge-'+str(i)] = exp.Current().__class__.__name__ i += 1 exp.Next() exp = TopExp_Explorer(obj, TopAbs_ShapeEnum(TopAbs_ShapeEnum.TopAbs_VERTEX)) i = 0 while (exp.More()): ret['Vertex-'+str(i)] = exp.Current().__class__.__name__ i += 1 exp.Next() #todo QuantityColor elif hasattr(obj,'__dict__'): return vars(obj) else: ret['class'] = ' Unknown structure ' return ret
def __init__(self): plotocc.__init__(self) self.shell = read_step_file(self.tmpdir + "SurfUV.stp") print(self.shell) top = TopExp_Explorer(self.shell, TopAbs_FACE) self.face = top.Current() print(top.Depth()) print(self.face) self.surf = BRep_Tool.Surface(self.face) u0, u1, v0, v1 = shapeanalysis_GetFaceUVBounds(self.face) print(u0, u1, v0, v1) sas = ShapeAnalysis_Surface(self.surf) print(sas.Value(u0, v0)) print(sas.Value(u0, v1)) print(sas.Value(u1, v0)) print(sas.Value(u1, v1)) u = u0 while u <= u1: v = v0 while v <= v1: p = sas.Value(u, v) self.display.DisplayShape(p, update=False) v += 1 / 3 u += 1 / 4
def face_mesh_triangle(comp=TopoDS_Shape(), isR=0.1, thA=0.1): # Mesh the shape BRepMesh_IncrementalMesh(comp, isR, True, thA, True) bild1 = BRep_Builder() comp1 = TopoDS_Compound() bild1.MakeCompound(comp1) bt = BRep_Tool() ex = TopExp_Explorer(comp, TopAbs_FACE) while ex.More(): face = topods_Face(ex.Current()) location = TopLoc_Location() facing = bt.Triangulation(face, location) tab = facing.Nodes() tri = facing.Triangles() print(facing.NbTriangles(), facing.NbNodes()) for i in range(1, facing.NbTriangles() + 1): trian = tri.Value(i) index1, index2, index3 = trian.Get() for j in range(1, 4): if j == 1: m = index1 n = index2 elif j == 2: n = index3 elif j == 3: m = index2 me = BRepBuilderAPI_MakeEdge(tab.Value(m), tab.Value(n)) if me.IsDone(): bild1.Add(comp1, me.Edge()) ex.Next() return comp1
def generate_face_framework(face, shape_maps): def generate_wire_framework(wire): wire_framework = [] ex = TopExp_Explorer(wire, TopAbs_EDGE) while ex.More(): edge = ex.Current() edge_info = (wire, edge) wire_framework.append(edge_info) ex.Next() return wire_framework _, wire_map, _ = shape_maps wire_frameworks = [] outer_loop, inner_loops = [], [] ex = TopExp_Explorer(face, TopAbs_WIRE) outer_wire_id = wire_map.FindIndex(shapeanalysis.OuterWire(face)) while ex.More(): wire = ex.Current() wire_id = wire_map.FindIndex(wire) if wire_id == outer_wire_id and INCLUDE_OUTER_WIRES: outer_loop += generate_wire_framework(wire) elif wire_id != outer_wire_id and INCLUDE_INNER_WIRES: inner_loops.append(generate_wire_framework(wire)) else: pass ex.Next() wire_frameworks.append(outer_loop) wire_frameworks += inner_loops return wire_frameworks, face
def split_edge_with_face(event=None): display.EraseAll() p0 = gp_Pnt() vnorm = gp_Dir(1, 0, 0) pln = gp_Pln(p0, vnorm) face = BRepBuilderAPI_MakeFace(pln, -10, 10, -10, 10).Face() p1 = gp_Pnt(0, 0, 15) p2 = gp_Pnt(0, 0, -15) edge = BRepBuilderAPI_MakeEdge(p1, p2).Edge() # Initialize splitter splitter = BOPAlgo_Splitter() # Add the edge as an argument and the face as a tool. This will split # the edge with the face. splitter.AddArgument(edge) splitter.AddTool(face) splitter.Perform() edges = [] exp = TopExp_Explorer(splitter.Shape(), TopAbs_EDGE) while exp.More(): edges.append(exp.Current()) exp.Next() print('Number of edges in split shape: ', len(edges)) display.DisplayShape(edges[0], color='red') display.DisplayShape(edges[1], color='green') display.DisplayShape(edges[2], color='yellow') display.FitAll()
def faces(self) -> List[BRepFace]: faces = [] explorer = TopExp_Explorer(self.shape, TopAbs_FACE) while explorer.More(): face = explorer.Current() faces.append(BRepFace(face)) explorer.Next() return faces
def loops(self) -> List[BRepLoop]: loops = [] explorer = TopExp_Explorer(self.shape, TopAbs_WIRE) while explorer.More(): wire = explorer.Current() loops.append(BRepLoop(wire)) explorer.Next() return loops
def reflection_elements(self, getter, topabs): ret = [] ex = TopExp_Explorer(self.Shape(), topabs) while ex.More(): obj = getter(ex.Current()) ret.append(Shape(obj)) ex.Next() return ret
def vertices(self) -> List[BRepVertex]: vertices = [] explorer = TopExp_Explorer(self.edge, TopAbs_VERTEX) while explorer.More(): vertex = explorer.Current() vertices.append(BRepVertex(vertex)) explorer.Next() return vertices
def get_faces(shp): ex = TopExp_Explorer(shp, TopAbs_FACE) seq = [] while ex.More(): s1 = ex.Current() seq.append(s1) ex.Next() return seq
def edges(self) -> List[BRepEdge]: edges = [] explorer = TopExp_Explorer(self.shape, TopAbs_EDGE) while explorer.More(): edge = explorer.Current() edges.append(BRepEdge(edge)) explorer.Next() return edges
def GetShapeEdges(shape): #input opencad TopoDs_shape return lst of TopoDS_edges edges = [] exp = TopExp_Explorer(shape, OCC.Core.TopAbs.TopAbs_EDGE) while exp.More(): count = 0 edges.append(exp.Current()) exp.Next() return edges
def generate_wire_framework(wire): wire_framework = [] ex = TopExp_Explorer(wire, TopAbs_EDGE) while ex.More(): edge = ex.Current() edge_info = (wire, edge) wire_framework.append(edge_info) ex.Next() return wire_framework
def points_from_edge(edge): vset = [] exp = TopExp_Explorer(edge, TopAbs_VERTEX) while exp.More(): s = exp.Current() exp.Next() vert = topods.Vertex(s) vset.append(as_list(vert)) return list(vset)
def color_the_edges(shp, display, color, width): shapeList = [] Ex = TopExp_Explorer(shp, TopAbs_EDGE) ctx = display.Context while Ex.More(): aEdge = topods.Edge(Ex.Current()) # ais_shape = AIS_Shape(aEdge) # ctx.SetColor(ais_shape, color, True) # ctx.SetWidth(ais_shape, width, False) # ctx.Display(ais_shape, False) Ex.Next()
def show_split_solid(self): colors = ["BLUE", "RED", "GREEN", "YELLOW", "BLACK", "WHITE"] num = 0 sol_exp = TopExp_Explorer(self.splitter.Shape(), TopAbs_SOLID) while sol_exp.More(): num += 1 self.display.DisplayShape(sol_exp.Current(), color=colors[num % len(colors)], transparency=0.5) sol_exp.Next() self.ShowOCC()
def fileout(self, dirname="./shp/"): num = 0 stp_file = dirname + "shp_{:04d}.stp".format(num) write_step_file(self.base, stp_file) sol_exp = TopExp_Explorer(self.splitter.Shape(), TopAbs_SOLID) while sol_exp.More(): num += 1 stp_file = dirname + "shp_{:04d}.stp".format(num) write_step_file(sol_exp.Current(), stp_file) sol_exp.Next()
def contourAsPoints(self) -> numpy.array: # Create the wire wire = self.countourAsWire() pts = [] if self.done: # Loop over the wire to get the edges edge_explorer = TopExp_Explorer(wire, TopAbs_EDGE) while edge_explorer.More(): edge = OCC.Core.TopoDS.topods_Edge(edge_explorer.Current()) curve = edge.Value() # TODO: Get the coordinates from the edge curve edge_explorer.Next() return pts
def _loop_topo(self, topologyType: TopAbs_ShapeEnum, topologicalEntity=None, topologyTypeToAvoid=None) -> Iterator[Any]: ''' this could be a faces generator for a python TopoShape class that way you can just do: for face in srf.faces: processFace(face) ''' topoTypes = { TopAbs_VERTEX: TopoDS_Vertex, TopAbs_EDGE: TopoDS_Edge, TopAbs_FACE: TopoDS_Face, TopAbs_WIRE: TopoDS_Wire, TopAbs_SHELL: TopoDS_Shell, TopAbs_SOLID: TopoDS_Solid, TopAbs_COMPOUND: TopoDS_Compound, TopAbs_COMPSOLID: TopoDS_CompSolid } topExp = TopExp_Explorer() if topologyType not in topoTypes.keys(): raise AssertionError("%s not one of %s" % (topologyType, topoTypes.keys())) # use self.myShape if nothing is specified if topologicalEntity is None and topologyTypeToAvoid is None: topExp.Init(self.myShape, topologyType) elif topologicalEntity is None and topologyTypeToAvoid is not None: topExp.Init(self.myShape, topologyType, topologyTypeToAvoid) elif topologyTypeToAvoid is None: topExp.Init(topologicalEntity, topologyType) elif topologyTypeToAvoid: topExp.Init(topologicalEntity, topologyType, topologyTypeToAvoid) seq = [] while topExp.More(): current_item = topExp.Current() topo_to_add = self.topoFactory[topologyType](current_item) seq.append(topo_to_add) topExp.Next() if self.ignore_orientation: # filter out those entities that share the same TShape # but do *not* share the same orientation #filter_orientation_seq = [] filter_orientation_seq: List = [] for i in seq: _present = False for j in filter_orientation_seq: if i.IsSame(j): _present = True break if _present is False: filter_orientation_seq.append(i) return iter(filter_orientation_seq) else: return iter(seq)
def makeFillets(event=None): newPrtName = 'bodyWithFillets' workPart = win.activePart wrkPrtUID = win.activePartUID mkFillet = BRepFilletAPI_MakeFillet(workPart) aEdgeExplorer = TopExp_Explorer(workPart, TopAbs_EDGE) while aEdgeExplorer.More(): aEdge = topods_Edge(aEdgeExplorer.Current()) mkFillet.Add(thickness / 12., aEdge) aEdgeExplorer.Next() myBody = mkFillet.Shape() win.getNewPartUID(myBody, name=newPrtName, ancestor=wrkPrtUID) win.statusBar().showMessage('Bottle with fillets complete') win.redraw()
def list_face(shape): ''' input shape: TopoDS_Shape output fset: {TopoDS_Face} ''' fset = set() exp = TopExp_Explorer(shape,TopAbs_FACE) while exp.More(): s = exp.Current() exp.Next() face = topods.Face(s) fset.add(face) return list(fset)
def _near_part(shp, pnt, topabs): min = float("inf") ret = shape_types[topabs].construct() vtx = point3(pnt).Vtx() ex = TopExp_Explorer(shp.Shape(), topabs) while ex.More(): obj = shape_types[topabs].convert(ex.Current()) extrema = BRepExtrema_DistShapeShape(obj, vtx) if min > extrema.Value(): ret = obj min = extrema.Value() ex.Next() return Shape(ret)
def list_edge(shape): ''' input shape: TopoDS_Shape output eset: {TopoDS_Edge} ''' eset = set() exp = TopExp_Explorer(shape,TopAbs_EDGE) while exp.More(): s = exp.Current() exp.Next() e = topods.Edge(s) eset.add(e) # print(face) return list(eset)
def prop_soild(self, sol=TopoDS_Solid()): self.sol_builder = TopoDS_Builder() sol_exp = TopExp_Explorer(sol, TopAbs_FACE) sol_top = TopologyExplorer(sol) #print(self.cal_vol(sol), self.base_vol) print(sol_top.number_of_faces()) self.face_lst = TopTools_ListOfShape() self.face_cnt = [] self.face_num = 0 self.face_init(sol_exp.Current()) #self.sol_builder.Add(sol, sol_exp.Current()) sol_exp.Next() while sol_exp.More(): face = sol_exp.Current() self.face_expand(face) sol_exp.Next() if self.file == True: stp_file = "./shp/shp_{:04d}.stp".format(self.sol_num) write_step_file(sol, stp_file) stp_file = "./shp/shp_{:04d}_exp.stp".format(self.sol_num) new_shpe = TopoDS_Compound() self.sol_builder.Add(gp_Pnt()) # self.sol_builder.MakeCompSolid(new_shpe) #write_step_file(new_shpe, stp_file) # if self.show == True: # self.display.DisplayShape(self.face_cnt) """self.face_init(face)
def combine_faces(compshape, sew_tolerance): """ Method to combine faces in a shell by adding connectivity and continuity :param compshape: TopoDS_Shape :param sew_tolerance: tolerance for sewing :return: Topo_Shell """ offsew = BRepOffsetAPI_FindContigousEdges(sew_tolerance) sew = BRepBuilderAPI_Sewing(sew_tolerance) face_explorers = TopExp_Explorer(compshape, TopAbs_FACE) n_faces = 0 # cycle on Faces while face_explorers.More(): tface = topods.Face(face_explorers.Current()) sew.Add(tface) offsew.Add(tface) n_faces += 1 face_explorers.Next() offsew.Perform() offsew.Dump() sew.Perform() shell = sew.SewedShape() sew.Dump() shell = topods.Shell(shell) shell_fixer = ShapeFix_Shell() shell_fixer.FixFaceOrientation(shell) """ if shell_fixer.Perform(): print("{} shells fixed! ".format(shell_fixer.NbShells())) else: print "Shells not fixed! " new_shell = shell_fixer.Shell() if brepalgo_IsValid(new_shell): print "Shell valid! " else: print "Shell failed! " """ return new_shell