def build_new_face(self, face, zpos, product): exp = TopExp.TopExp_Explorer(face, TopAbs.TopAbs_WIRE) while exp.More(): wireexp = BRepTools.BRepTools_WireExplorer( topods.Wire(exp.Current())) new_wire_builder = BRepBuilderAPI.BRepBuilderAPI_MakeWire() first_vertex = None previous_vertex = None while wireexp.More(): current_vertex = wireexp.CurrentVertex() current_point = BRep.BRep_Tool.Pnt(current_vertex) # Dodgy technique to squash in Z axis current_point.SetZ(zpos) current_vertex = BRepBuilderAPI.BRepBuilderAPI_MakeVertex( current_point).Vertex() if not first_vertex: first_vertex = current_vertex if not previous_vertex: previous_vertex = current_vertex else: try: new_wire_builder.Add( topods.Edge( BRepBuilderAPI.BRepBuilderAPI_MakeEdge( previous_vertex, current_vertex).Edge())) previous_vertex = current_vertex except: pass wireexp.Next() # make last edge if not wireexp.More(): try: new_wire_builder.Add( topods.Edge( BRepBuilderAPI.BRepBuilderAPI_MakeEdge( current_vertex, first_vertex).Edge())) except: pass try: new_wire = new_wire_builder.Wire() new_face = BRepBuilderAPI.BRepBuilderAPI_MakeFace( new_wire).Face() self.background_elements.append({ 'raw': product, 'geometry': new_wire, 'geometry_face': new_face, 'type': 'polygon', 'z': zpos }) except: #print('Could not build face') pass exp.Next()
def get_booleaned_edges(shape): edges = [] exp = TopExp.TopExp_Explorer(shape, TopAbs.TopAbs_EDGE) while exp.More(): edges.append(topods.Edge(exp.Current())) exp.Next() return edges
def __init__(self, shape): if not shape.IsNull(): if not shape.ShapeType() == Shape.EDGE: raise TypeError('Shape is not a TopoDS_Edge.') if not isinstance(shape, TopoDS_Edge): shape = topods.Edge(shape) super(Edge, self).__init__(shape)
def get_split_edges(self, edge_face_map, face, zmax, product): exp2 = TopExp.TopExp_Explorer(face, TopAbs.TopAbs_EDGE) while exp2.More(): edge = topods.Edge(exp2.Current()) adjface = TopoDS.TopoDS_Face() getadj = TopOpeBRepBuild.TopOpeBRepBuild_Tools.GetAdjacentFace( face, edge, edge_face_map, adjface) if getadj: try: edge_angle = math.degrees( self.get_angle_between_faces(face, adjface)) except: # TODO: Figure out when a math domain error might occur, # because it does, sometimes. edge_angle = 0 if edge_angle > 30 and edge_angle < 160: newedge = self.build_new_edge(edge, zmax + 0.01) if newedge: self.background_elements.append({ 'raw': product, 'geometry': newedge, 'type': 'line', 'z': zmax + 0.01 }) exp2.Next()
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 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 extract_trims_curves(self): # Read in the Trim Curves trim_curves = [] trims = ShapeAnalysis_FreeBoundsProperties(self.face) trims.Perform() num_loops = trims.NbClosedFreeBounds() num_open_loops = trims.NbOpenFreeBounds() if num_open_loops > 0: print('Warning: Face has open boundaries') for n_boundary in range(num_loops): boundary_data = trims.ClosedFreeBound(n_boundary + 1) boundary_wire = boundary_data.FreeBound() loop = [] c_id = 1 top_ex = TopExp_Explorer(boundary_wire, TopAbs_EDGE) while (top_ex.More()): edge = topods.Edge(top_ex.Current()) curve_adapter = BRepAdaptor_Curve2d(edge, self.face) curve_factory = CurveFactory() if curve_factory is not None: c = curve_factory.create_curve_object( curve_adapter, self.face, self.surf, c_id) curve = c.extract_curve_data(self.f_id) c_id = c_id + 1 if curve is None: continue loop.append(curve) top_ex.Next() # nurbs_surface.trim_curves.append(loop) trim_curves.append(loop) trim_dict = {} trim_dict['count'] = len(trim_curves) trim_dict['data'] = [] for loop in trim_curves: trim_dict['data'].append(loop) return trim_dict
def startBottle(startOnly=True): # minus the neck fillet, shelling & threads partName = "Bottle-start" # The points we'll use to create the profile of the bottle's body aPnt1 = gp_Pnt(-width / 2.0, 0, 0) aPnt2 = gp_Pnt(-width / 2.0, -thickness / 4.0, 0) aPnt3 = gp_Pnt(0, -thickness / 2.0, 0) aPnt4 = gp_Pnt(width / 2.0, -thickness / 4.0, 0) aPnt5 = gp_Pnt(width / 2.0, 0, 0) aArcOfCircle = GC_MakeArcOfCircle(aPnt2, aPnt3, aPnt4) aSegment1 = GC_MakeSegment(aPnt1, aPnt2) aSegment2 = GC_MakeSegment(aPnt4, aPnt5) # Could also construct the line edges directly using the points # instead of the resulting line. aEdge1 = BRepBuilderAPI_MakeEdge(aSegment1.Value()) aEdge2 = BRepBuilderAPI_MakeEdge(aArcOfCircle.Value()) aEdge3 = BRepBuilderAPI_MakeEdge(aSegment2.Value()) # Create a wire out of the edges aWire = BRepBuilderAPI_MakeWire(aEdge1.Edge(), aEdge2.Edge(), aEdge3.Edge()) # Quick way to specify the X axis xAxis = gp_OX() # Set up the mirror aTrsf = gp_Trsf() aTrsf.SetMirror(xAxis) # Apply the mirror transformation aBRespTrsf = BRepBuilderAPI_Transform(aWire.Wire(), aTrsf) # Get the mirrored shape back out of the transformation # and convert back to a wire aMirroredShape = aBRespTrsf.Shape() # A wire instead of a generic shape now aMirroredWire = topods.Wire(aMirroredShape) # Combine the two constituent wires mkWire = BRepBuilderAPI_MakeWire() mkWire.Add(aWire.Wire()) mkWire.Add(aMirroredWire) myWireProfile = mkWire.Wire() # The face that we'll sweep to make the prism myFaceProfile = BRepBuilderAPI_MakeFace(myWireProfile) # We want to sweep the face along the Z axis to the height aPrismVec = gp_Vec(0, 0, height) myBody = BRepPrimAPI_MakePrism(myFaceProfile.Face(), aPrismVec) # Add fillets to all edges through the explorer mkFillet = BRepFilletAPI_MakeFillet(myBody.Shape()) anEdgeExplorer = TopExp_Explorer(myBody.Shape(), TopAbs_EDGE) while anEdgeExplorer.More(): anEdge = topods.Edge(anEdgeExplorer.Current()) mkFillet.Add(thickness / 12.0, anEdge) anEdgeExplorer.Next() myBody = mkFillet.Shape() # Create the neck of the bottle neckLocation = gp_Pnt(0, 0, height) neckAxis = gp_DZ() neckAx2 = gp_Ax2(neckLocation, neckAxis) myNeckRadius = thickness / 4.0 myNeckHeight = height / 10.0 mkCylinder = BRepPrimAPI_MakeCylinder(neckAx2, myNeckRadius, myNeckHeight) myBody = BRepAlgoAPI_Fuse(myBody, mkCylinder.Shape()) if startOnly: # quit here uid = win.getNewPartUID(myBody.Shape(), name=partName) win.redraw() return partName = "Bottle-complete" # Our goal is to find the highest Z face and remove it faceToRemove = None zMax = -1 # We have to work our way through all the faces to find the highest Z face aFaceExplorer = TopExp_Explorer(myBody.Shape(), TopAbs_FACE) while aFaceExplorer.More(): aFace = topods.Face(aFaceExplorer.Current()) if face_is_plane(aFace): aPlane = geom_plane_from_face(aFace) # We want the highest Z face, so compare this to the previous faces aPnt = aPlane.Location() aZ = aPnt.Z() if aZ > zMax: zMax = aZ faceToRemove = aFace aFaceExplorer.Next() facesToRemove = TopTools_ListOfShape() facesToRemove.Append(faceToRemove) myBody = BRepOffsetAPI_MakeThickSolid(myBody.Shape(), facesToRemove, -thickness / 50.0, 0.001) # Set up our surfaces for the threading on the neck neckAx2_Ax3 = gp_Ax3(neckLocation, gp_DZ()) aCyl1 = Geom_CylindricalSurface(neckAx2_Ax3, myNeckRadius * 0.99) aCyl2 = Geom_CylindricalSurface(neckAx2_Ax3, myNeckRadius * 1.05) # Set up the curves for the threads on the bottle's neck aPnt = gp_Pnt2d(2.0 * math.pi, myNeckHeight / 2.0) aDir = gp_Dir2d(2.0 * math.pi, myNeckHeight / 4.0) anAx2d = gp_Ax2d(aPnt, aDir) aMajor = 2.0 * math.pi aMinor = myNeckHeight / 10.0 anEllipse1 = Geom2d_Ellipse(anAx2d, aMajor, aMinor) anEllipse2 = Geom2d_Ellipse(anAx2d, aMajor, aMinor / 4.0) anArc1 = Geom2d_TrimmedCurve(anEllipse1, 0, math.pi) anArc2 = Geom2d_TrimmedCurve(anEllipse2, 0, math.pi) anEllipsePnt1 = anEllipse1.Value(0) anEllipsePnt2 = anEllipse1.Value(math.pi) aSegment = GCE2d_MakeSegment(anEllipsePnt1, anEllipsePnt2) # Build edges and wires for threading anEdge1OnSurf1 = BRepBuilderAPI_MakeEdge(anArc1, aCyl1) anEdge2OnSurf1 = BRepBuilderAPI_MakeEdge(aSegment.Value(), aCyl1) anEdge1OnSurf2 = BRepBuilderAPI_MakeEdge(anArc2, aCyl2) anEdge2OnSurf2 = BRepBuilderAPI_MakeEdge(aSegment.Value(), aCyl2) threadingWire1 = BRepBuilderAPI_MakeWire(anEdge1OnSurf1.Edge(), anEdge2OnSurf1.Edge()) threadingWire2 = BRepBuilderAPI_MakeWire(anEdge1OnSurf2.Edge(), anEdge2OnSurf2.Edge()) # Compute the 3D representations of the edges/wires breplib.BuildCurves3d(threadingWire1.Shape()) breplib.BuildCurves3d(threadingWire2.Shape()) # Create the surfaces of the threading aTool = BRepOffsetAPI_ThruSections(True) aTool.AddWire(threadingWire1.Wire()) aTool.AddWire(threadingWire2.Wire()) aTool.CheckCompatibility(False) myThreading = aTool.Shape() # Build the resulting compound aRes = TopoDS_Compound() aBuilder = BRep_Builder() aBuilder.MakeCompound(aRes) aBuilder.Add(aRes, myBody.Shape()) aBuilder.Add(aRes, myThreading) uid = win.getNewPartUID(aRes, name=partName) win.redraw()
def Edge(self): return topods.Edge(self._shp) def Face(self): return topods.Face(self._shp)
def create_model(self): ###################################################### edges = [] if self.R2 == 0.0 or self.R1 == 0.0: self.a3 = self.a4 = self.a5 edge1 = make_edge(getGpPt(self.a1), getGpPt(self.a2)) edges.append(edge1) edge2 = make_edge(getGpPt(self.a2), getGpPt(self.a3)) edges.append(edge2) edge3 = make_edge(getGpPt(self.a3), getGpPt(self.a6)) edges.append(edge3) # arc2 = GC_MakeArcOfCircle(getGpPt(self.a6), getGpPt(self.a7), getGpPt(self.a8)) # edge4 = make_edge(arc2.Value()) # edges.append(edge4) # edge5 = make_edge(getGpPt(self.a8), getGpPt(self.a9)) # edges.append(edge5) # edge6 = make_edge(getGpPt(self.a9), getGpPt(self.a12)) # edges.append(edge6) # edge7 = make_edge(getGpPt(self.a12), getGpPt(self.a1)) # edges.append(edge7) edge4 = make_edge(getGpPt(self.a6), getGpPt(self.a9)) edges.append(edge4) edge5 = make_edge(getGpPt(self.a9), getGpPt(self.a12)) edges.append(edge5) edge6 = make_edge(getGpPt(self.a12), getGpPt(self.a1)) edges.append(edge6) else: edge1 = make_edge(getGpPt(self.a1), getGpPt(self.a2)) edges.append(edge1) edge2 = make_edge(getGpPt(self.a2), getGpPt(self.a3)) edges.append(edge2) arc1 = GC_MakeArcOfCircle(getGpPt(self.a3), getGpPt(self.a4), getGpPt(self.a5)) edge3 = make_edge(arc1.Value()) edges.append(edge3) edge4 = make_edge(getGpPt(self.a5), getGpPt(self.a6)) edges.append(edge4) arc2 = GC_MakeArcOfCircle(getGpPt(self.a6), getGpPt(self.a7), getGpPt(self.a8)) edge5 = make_edge(arc2.Value()) edges.append(edge5) edge6 = make_edge(getGpPt(self.a8), getGpPt(self.a9)) edges.append(edge6) arc3 = GC_MakeArcOfCircle(getGpPt(self.a9), getGpPt(self.a10), getGpPt(self.a11)) edge7 = make_edge(arc3.Value()) edges.append(edge7) edge8 = make_edge(getGpPt(self.a11), getGpPt(self.a12)) edges.append(edge8) edge9 = make_edge(getGpPt(self.a12), getGpPt(self.a1)) edges.append(edge9) wire = makeWireFromEdges(edges) aFace = makeFaceFromWire(wire) extrudeDir = self.L * self.wDir # extrudeDir is a numpy array prism = makePrismFromFace(aFace, extrudeDir) mkFillet = BRepFilletAPI_MakeFillet(prism) anEdgeExplorer = TopExp_Explorer(prism, TopAbs_EDGE) while anEdgeExplorer.More(): aEdge = topods.Edge(anEdgeExplorer.Current()) mkFillet.Add(self.T / 17., aEdge) anEdgeExplorer.Next() prism = mkFillet.Shape() return prism
mkWire.Add(aMirroredWire) myWireProfile = mkWire.Wire() # The face that we'll sweep to make the prism myFaceProfile = BRepBuilderAPI_MakeFace(myWireProfile) # We want to sweep the face along the Z axis to the height aPrismVec = gp_Vec(0, 0, height) myBody_step1 = BRepPrimAPI_MakePrism(myFaceProfile.Face(), aPrismVec) # Add fillets to all edges through the explorer mkFillet = BRepFilletAPI_MakeFillet(myBody_step1.Shape()) anEdgeExplorer = TopExp_Explorer(myBody_step1.Shape(), TopAbs_EDGE) while anEdgeExplorer.More(): anEdge = topods.Edge(anEdgeExplorer.Current()) mkFillet.Add(thickness / 12.0, anEdge) anEdgeExplorer.Next() # Create the neck of the bottle neckLocation = gp_Pnt(0, 0, height) neckAxis = gp_DZ() neckAx2 = gp_Ax2(neckLocation, neckAxis) myNeckRadius = thickness / 4.0 myNeckHeight = height / 10.0 mkCylinder = BRepPrimAPI_MakeCylinder(neckAx2, myNeckRadius, myNeckHeight) myBody_step2 = BRepAlgoAPI_Fuse(mkFillet.Shape(), mkCylinder.Shape())
def sort_edges_into_order(occedge_list, isclosed=False): """ This function creates a list of ordered OCCedges from a list of loose OCCedges. The edges does not need to form a close face. Parameters ---------- occedge_list : list of OCCedges The list of OCCedges to be sorted. isclosed : bool, optional True or False, is the resultant wires suppose to be closed or opened, Default = False. Returns ------- list of sorted edges : list of OCCedges A list of ordered OCCedges. """ from OCC.Core.TopoDS import topods from OCC.Core.TopExp import topexp from OCC.Core.BRep import BRep_Tool from OCC.Core.ShapeAnalysis import ShapeAnalysis_WireOrder from OCC.Core.Precision import precision sawo_statusdict = { 0: "all edges are direct and in sequence", 1: "all edges are direct but some are not in sequence", 2: "unresolved gaps remain", -1: "some edges are reversed, but no gaps remain", -2: "some edges are reversed and some gaps remain", -10: "failure on reorder" } mode3d = True SAWO = ShapeAnalysis_WireOrder(mode3d, precision.PConfusion()) for occedge in occedge_list: V1 = topexp.FirstVertex(topods.Edge(occedge)) V2 = topexp.LastVertex(topods.Edge(occedge)) pnt1 = BRep_Tool().Pnt(V1) pnt2 = BRep_Tool().Pnt(V2) SAWO.Add(pnt1.XYZ(), pnt2.XYZ()) SAWO.SetKeepLoopsMode(True) SAWO.Perform(isclosed) #print "SAWO.Status()", SAWO.Status() if not SAWO.IsDone(): raise RuntimeError("build wire: Unable to reorder edges: \n" + sawo_statusdict[SAWO.Status()]) else: if SAWO.Status() not in [0, -1]: pass # not critical, wirebuilder will handle this SAWO.SetChains(precision.PConfusion()) sorted_edge2dlist = [] #print "Number of chains: ", SAWO.NbChains() for i in range(SAWO.NbChains()): sorted_edges = [] estart, eend = SAWO.Chain(i + 1) #print "Number of edges in chain", i, ": ", eend - estart + 1 if (eend - estart + 1) == 0: continue for j in range(estart, eend + 1): idx = abs(SAWO.Ordered(j)) edge2w = occedge_list[idx - 1] if SAWO.Ordered(j) < 0: edge2w.Reverse() sorted_edges.append(edge2w) sorted_edge2dlist.append(sorted_edges) return sorted_edge2dlist
def get_boundingbox_shape(bb): """ Given the dict returned by `get_boundingbox`, this function creates a TopoDS_Compound to visualize the bounding box, including annotations :param bb: dict returned by `get_boundingbox` :return: a TopoDS_Compound to visualize the bounding box """ compound = TopoDS_Compound() builder = BRep_Builder() builder.MakeCompound(compound) bb_box = BRepPrimAPI_MakeBox(bb['dx'], bb['dy'], bb['dz']).Shape() translation = gp_Trsf() translation.SetTranslation(gp_Vec(bb['xmin'], bb['ymin'], bb['zmin'])) brep_trns = BRepBuilderAPI_Transform(bb_box, translation, False) brep_trns.Build() bb_box = brep_trns.Shape() anEdgeExplorer = TopExp_Explorer(bb_box, TopAbs_EDGE) while anEdgeExplorer.More(): anEdge = topods.Edge(anEdgeExplorer.Current()) builder.Add(compound, anEdge) anEdgeExplorer.Next() dx_string = text_to_brep(str(round(bb['dx'])) + " mm", "Arial", Font_FontAspect_Bold, 120., True) transformation = gp_Trsf() transformation.SetTranslation(gp_Vec(bb['xmin'] + 120, bb['ymin'] - 120, 0)) brep_trns = BRepBuilderAPI_Transform(dx_string, transformation, False) brep_trns.Build() dx_string = brep_trns.Shape() builder.Add(compound, dx_string) dy_string = text_to_brep(str(round(bb['dy'])) + " mm", "Arial", Font_FontAspect_Bold, 120., True) t1 = gp_Trsf() z = gp_Ax1(gp_Pnt(), gp_Dir(0, 0, 1)) t1.SetRotation(z, radians(90)) t2 = gp_Trsf() t2.SetTranslation(gp_Vec(bb['xmin'] - 25, bb['ymin'] + 120, 0)) brep_trns = BRepBuilderAPI_Transform(dy_string, t2 * t1, False) brep_trns.Build() dy_string = brep_trns.Shape() builder.Add(compound, dy_string) dz_string = text_to_brep(str(round(bb['dz'])) + " mm", "Arial", Font_FontAspect_Bold, 120., True) x = gp_Ax1(gp_Pnt(), gp_Dir(1, 0, 0)) y = gp_Ax1(gp_Pnt(), gp_Dir(0, 1, 0)) z = gp_Ax1(gp_Pnt(), gp_Dir(0, 0, 1)) t1 = gp_Trsf() t1.SetRotation(z, radians(90)) t2 = gp_Trsf() t2.SetRotation(y, radians(90)) t3 = gp_Trsf() t3.SetRotation(x, radians(90)) t4 = gp_Trsf() t4.SetTranslation(gp_Vec(bb['xmin'], bb['ymin'] - 25, 120)) brep_trns = BRepBuilderAPI_Transform(dz_string, t4 * t3 * t2 * t1, False) brep_trns.Build() dz_string = brep_trns.Shape() builder.Add(compound, dz_string) return compound
def read_step_file_withnames( filename, breadface=False, breadedge=False ): #Read a step file with names attached to solid, faces (can be extended to edges) """""[Read a step file with names attached to solid, faces (can be extended to edges)] Arguments: filename {[type]} -- [path to the .stp file] Keyword Arguments: breadface {bool} -- [read the faces' names] (default: {False}) breadedge {bool} -- [read the edges' names] (default: {False}) Returns: (dSolids, dFaces, dEdges) -- [two dicts with name (int) as key and aShape as value] """ "" reader = STEPControl_Reader() #tr = reader.WS().GetObject().TransferReader().GetObject() tr = reader.WS().GetObject().TransferReader() reader.ReadFile(filename) reader.TransferRoots() shape = reader.OneShape() dSolids = dict( ) #solids initial as a dict with name (int) as key and aShape as value dFaces = dict( ) #faces initial as a dict with name (int) as key and aShape as value dEdges = dict( ) #edges initial as a dict with name (int) as key and aShape as value #read the solid names exp = TopExp_Explorer(shape, TopAbs_SOLID) while exp.More(): s = exp.Current() exp.Next() #Converting TopoDS_Shape to TopoDS_Face solid = topods.Solid(s) #Working on the name item = tr.EntityFromShapeResult(s, 1) if item == None: continue #item = Handle_StepRepr_RepresentationItem.DownCast(item).GetObject() item = StepRepr_RepresentationItem.DownCast(item) name = item.Name().ToCString() if name: print('Found entity named: {}: {}.'.format(name, s)) nameid = int(name.split('_')[-1]) dSolids[nameid] = solid # read the face names if breadface: exp = TopExp_Explorer(shape, TopAbs_FACE) while exp.More(): s = exp.Current() exp.Next() #Converting TopoDS_Shape to TopoDS_Face face = topods.Face(s) #Working on the name item = tr.EntityFromShapeResult(s, 1) if item.IsNull(): continue #item = Handle_StepRepr_RepresentationItem.DownCast(item).GetObject() item = StepRepr_RepresentationItem.DownCast(item) name = item.Name().GetObject().ToCString() if name: # print('Found entity named: {}: {}.'.format(name, s)) nameid = int(name.split('_')[-1]) dFaces[nameid] = face # read the edge names if breadedge: exp = TopExp_Explorer(shape, TopAbs_EDGE) while exp.More(): s = exp.Current() exp.Next() #Converting TopoDS_Shape to TopoDS_Face edge = topods.Edge(s) #Working on the name item = tr.EntityFromShapeResult(s, 1) if item.IsNull(): continue #item = Handle_StepRepr_RepresentationItem.DownCast(item).GetObject() item = StepRepr_RepresentationItem.DownCast(item) name = item.Name().GetObject().ToCString() if name: # print('Found entity named: {}: {}.'.format(name, s)) nameid = int(name.split('_')[-1]) dEdges[nameid] = edge ret = (dSolids, dFaces, dEdges) return ret