def simple_mesh(): # # Create the shape # theBox = BRepPrimAPI_MakeBox(200, 60, 60).Shape() theSphere = BRepPrimAPI_MakeSphere(gp_Pnt(100, 20, 20), 80).Shape() shape = BRepAlgoAPI_Fuse(theSphere, theBox).Shape() # # Mesh the shape # BRepMesh_IncrementalMesh(shape, 0.8) builder = BRep_Builder() comp = TopoDS_Compound() builder.MakeCompound(comp) bt = BRep_Tool() ex = TopExp_Explorer(shape, TopAbs_FACE) while ex.More(): face = topods_Face(ex.Current()) location = TopLoc_Location() facing = (bt.Triangulation(face, location)) tab = facing.Nodes() tri = facing.Triangles() 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(): builder.Add(comp, me.Edge()) ex.Next() display.EraseAll() display.DisplayShape(shape) display.DisplayShape(comp, update=True)
def glue_solids(event=None): display.EraseAll() display.Context.RemoveAll(True) # Without common edges S1 = read_step_file(os.path.join('part_of_sattelate', 'pribore', 'DAV_WS16.STEP')) display.DisplayShape(S1, color='BLUE', transparency=0.9) measure(S1) # the face to glue S2 = read_step_file(os.path.join('part_of_sattelate', 'pribore', 'Camara_WS16.STEP')) trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(750, 0, 0)) S2.Move(TopLoc_Location(trsf)) fuse_shp = BRepAlgoAPI_Fuse(S1, S2).Shape() props = GProp_GProps() brepgprop_VolumeProperties(fuse_shp, props) # Get inertia properties mass = props.Mass() cog = props.CentreOfMass() matrix_of_inertia = props.MatrixOfInertia() # Display inertia properties print("Cube mass = %s" % mass) cog_x, cog_y, cog_z = cog.Coord() print("Center of mass: x = %f;y = %f;z = %f;" % (cog_x, cog_y, cog_z)) display.DisplayShape(fuse_shp) #pstring = 'x: % \n y: % \n z: %' % (cog_x, cog_y, cog_z) pnt = gp_Pnt(cog_x, cog_y, cog_z) # display points display.DisplayShape(pnt, update=True) pnt = gp_Pnt(0, 0, 0) # display points display.DisplayShape(pnt, update=True) #display.DisplayMessage(pnt, pstring) display.FitAll()
def glue_solids(event=None): display.EraseAll() display.Context.RemoveAll(True) # Without common edges S1 = BRepPrimAPI_MakeBox(gp_Pnt(500., 500., 0.), gp_Pnt(100., 250., 300.)).Shape() facesA = get_faces(S1) tag_faces(facesA, "BLUE", "facesA") # the face to glue F1 = facesA[5] S2 = BRepPrimAPI_MakeBox(gp_Pnt(400., 400., 300.), gp_Pnt(200., 300., 500.)).Shape() facesB = get_faces(S2) tag_faces(facesB, "GREEN", "facesB") # the face to glue of the opposite shape F2 = facesB[4] # perform glueing operation glue1 = BRepFeat_Gluer(S2, S1) glue1.Bind(F2, F1) shape = glue1.Shape() display.SetModeHLR() # move the glued shape, such to be able to inspect input and output # of glueing operation trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(500, 0, 0)) shape.Move(TopLoc_Location(trsf)) tag_faces(get_faces(shape), "BLACK", "") # render glued shape display.DisplayShape(shape) display.FitAll()
def surf_trf(axs, face): trf = gp_Trsf() trf.SetTransformation(axs, gp_Ax3()) srf = face.Moved(TopLoc_Location(trf)) return srf
def _get_sub_shapes(lab, loc): #global cnt, lvl #cnt += 1 #print("\n[%d] level %d, handling LABEL %s\n" % (cnt, lvl, _get_label_name(lab))) #print() #print(lab.DumpToString()) #print() #print("Is Assembly :", shape_tool.IsAssembly(lab)) #print("Is Free :", shape_tool.IsFree(lab)) #print("Is Shape :", shape_tool.IsShape(lab)) #print("Is Compound :", shape_tool.IsCompound(lab)) #print("Is Component :", shape_tool.IsComponent(lab)) #print("Is SimpleShape :", shape_tool.IsSimpleShape(lab)) #print("Is Reference :", shape_tool.IsReference(lab)) #users = TDF_LabelSequence() #users_cnt = shape_tool.GetUsers(lab, users) #print("Nr Users :", users_cnt) l_subss = TDF_LabelSequence() shape_tool.GetSubShapes(lab, l_subss) #print("Nb subshapes :", l_subss.Length()) l_comps = TDF_LabelSequence() shape_tool.GetComponents(lab, l_comps) #print("Nb components :", l_comps.Length()) #print() name = lab.GetLabelName() print("Name :", name) if shape_tool.IsAssembly(lab): l_c = TDF_LabelSequence() shape_tool.GetComponents(lab, l_c) for i in range(l_c.Length()): label = l_c.Value(i + 1) if shape_tool.IsReference(label): #print("\n######## reference label :", label) label_reference = TDF_Label() shape_tool.GetReferredShape(label, label_reference) loc = shape_tool.GetLocation(label) #print(" loc :", loc) #trans = loc.Transformation() #print(" tran form :", trans.Form()) #rot = trans.GetRotation() #print(" rotation :", rot) #print(" X :", rot.X()) #print(" Y :", rot.Y()) #print(" Z :", rot.Z()) #print(" W :", rot.W()) #tran = trans.TranslationPart() #print(" translation :", tran) #print(" X :", tran.X()) #print(" Y :", tran.Y()) #print(" Z :", tran.Z()) locs.append(loc) #print(">>>>") #lvl += 1 _get_sub_shapes(label_reference, loc) #lvl -= 1 #print("<<<<") locs.pop() elif shape_tool.IsSimpleShape(lab): #print("\n######## simpleshape label :", lab) shape = shape_tool.GetShape(lab) #print(" all ass locs :", locs) loc = TopLoc_Location() for l in locs: #print(" take loc :", l) loc = loc.Multiplied(l) #trans = loc.Transformation() #print(" FINAL loc :") #print(" tran form :", trans.Form()) #rot = trans.GetRotation() #print(" rotation :", rot) #print(" X :", rot.X()) #print(" Y :", rot.Y()) #print(" Z :", rot.Z()) #print(" W :", rot.W()) #tran = trans.TranslationPart() #print(" translation :", tran) #print(" X :", tran.X()) #print(" Y :", tran.Y()) #print(" Z :", tran.Z()) c = Quantity_Color(0.5, 0.5, 0.5, Quantity_TOC_RGB) # default color colorSet = False if (color_tool.GetInstanceColor(shape, 0, c) or color_tool.GetInstanceColor(shape, 1, c) or color_tool.GetInstanceColor(shape, 2, c)): color_tool.SetInstanceColor(shape, 0, c) color_tool.SetInstanceColor(shape, 1, c) color_tool.SetInstanceColor(shape, 2, c) colorSet = True n = c.Name(c.Red(), c.Green(), c.Blue()) print(' instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) if not colorSet: if (color_tool.GetColor(lab, 0, c) or color_tool.GetColor(lab, 1, c) or color_tool.GetColor(lab, 2, c)): color_tool.SetInstanceColor(shape, 0, c) color_tool.SetInstanceColor(shape, 1, c) color_tool.SetInstanceColor(shape, 2, c) n = c.Name(c.Red(), c.Green(), c.Blue()) print(' shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) shape_disp = BRepBuilderAPI_Transform( shape, loc.Transformation()).Shape() if not shape_disp in output_shapes: output_shapes[shape_disp] = [lab.GetLabelName(), c] for i in range(l_subss.Length()): lab_subs = l_subss.Value(i + 1) #print("\n######## simpleshape subshape label :", lab) shape_sub = shape_tool.GetShape(lab_subs) c = Quantity_Color(0.5, 0.5, 0.5, Quantity_TOC_RGB) # default color colorSet = False if (color_tool.GetInstanceColor(shape_sub, 0, c) or color_tool.GetInstanceColor(shape_sub, 1, c) or color_tool.GetInstanceColor(shape_sub, 2, c)): color_tool.SetInstanceColor(shape_sub, 0, c) color_tool.SetInstanceColor(shape_sub, 1, c) color_tool.SetInstanceColor(shape_sub, 2, c) colorSet = True n = c.Name(c.Red(), c.Green(), c.Blue()) print(' instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) if not colorSet: if (color_tool.GetColor(lab_subs, 0, c) or color_tool.GetColor(lab_subs, 1, c) or color_tool.GetColor(lab_subs, 2, c)): color_tool.SetInstanceColor(shape, 0, c) color_tool.SetInstanceColor(shape, 1, c) color_tool.SetInstanceColor(shape, 2, c) n = c.Name(c.Red(), c.Green(), c.Blue()) print(' shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) shape_to_disp = BRepBuilderAPI_Transform( shape_sub, loc.Transformation()).Shape() # position the subshape to display if not shape_to_disp in output_shapes: output_shapes[shape_to_disp] = [lab_subs.GetLabelName(), c]
def Locate_centre_face(self, number, name_body, angle, x_drive, y_drive): cp = BRepBuilderAPI_Copy(self.reserv_models[name_body]) cp.Perform(self.reserv_models[name_body]) shape = cp.Shape() # move to zero bbox = Bnd_Box() brepbndlib_Add(shape, bbox) xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get() trsf = gp_Trsf() trsf.SetTranslation( gp_Vec(-xmin - (xmax - xmin) / 2, -ymin - (ymax - ymin) / 2, -zmin)) shape.Move(TopLoc_Location(trsf)) # Process vector of rotation to face x = -self.walls[number][1][1] y = self.walls[number][1][0] z = 0 P0 = gp_Pnt(0, 0, 0) P1 = gp_Pnt(0, 0, 1) P2 = gp_Pnt(self.walls[number][1][0], self.walls[number][1][1], self.walls[number][1][2]) # rotation to Ax z v_x = gp_Vec(P0, gp_Pnt(0, 1, 0)) v_r = gp_Vec(P0, gp_Pnt(x, y, z)) if v_x.X != v_r.X and v_x.Y != v_r.Y and v_x.Z != v_r.Z: trsf = gp_Trsf() #print(v_r.Angle(v_x)) trsf.SetRotation(gp_Ax1(P0, gp_Dir(0, 0, 1)), v_r.Angle(v_x)) shape.Move(TopLoc_Location(trsf)) # rotation in parallel to face v0 = gp_Vec(P0, P1) v1 = gp_Vec(P0, P2) # print(v1.Angle(v0)) if v1.X != v0.X and v1.Y != v0.Y and v1.Z != v0.Z: trsf = gp_Trsf() trsf.SetRotation(gp_Ax1(P0, gp_Dir(x, y, z)), v1.Angle(v0)) # move to face shape.Move(TopLoc_Location(trsf)) trsf = gp_Trsf() trsf.SetTranslation( gp_Vec(self.walls[number][0][0], self.walls[number][0][1], self.walls[number][0][2])) shape.Move(TopLoc_Location(trsf)) # Rotation by given angle trsf = gp_Trsf() trsf.SetRotation( gp_Ax1( P0, gp_Dir(self.walls[number][1][0], self.walls[number][1][1], self.walls[number][1][2])), angle) shape.Move(TopLoc_Location(trsf)) # initional x, y offset_y, offset_x = self.rot_point(xmax - xmin, ymax - ymin, angle) limit_x = self.walls[number][3][0] / 2 - offset_x limit_y = self.walls[number][3][1] / 2 - offset_y move_x = limit_x * x_drive move_y = limit_y * y_drive # Move to x and y x_axy = self.walls[number][1][1] * self.walls[number][2][ 2] - self.walls[number][1][2] * self.walls[number][2][1] y_axy = -(self.walls[number][1][0] * self.walls[number][2][2] - self.walls[number][1][2] * self.walls[number][2][0]) z_axy = self.walls[number][1][0] * self.walls[number][2][ 1] - self.walls[number][1][1] * self.walls[number][2][0] x_axy *= move_y y_axy *= move_y z_axy *= move_y trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(x_axy, y_axy, z_axy)) shape.Move(TopLoc_Location(trsf)) trsf = gp_Trsf() trsf.SetTranslation( gp_Vec(self.walls[number][2][0] * move_x, self.walls[number][2][1] * move_x, self.walls[number][2][2] * move_x)) shape.Move(TopLoc_Location(trsf)) #print(name_body, shape) self.modules[name_body] = shape
def __init__(self, shape): from OCC.Core.BRep import BRep_Tool from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh from OCC.Core.TopAbs import TopAbs_FACE, TopAbs_VERTEX from OCC.Core.TopExp import TopExp_Explorer from OCC.Core.TopLoc import TopLoc_Location from OCC.Core.TopoDS import topods_Face, topods_Vertex, TopoDS_Iterator vertices = [] # a (nested) list of vec3 triangles = [] # a (flat) list of integers normals = [] uv = [] # Mesh the shape linDeflection = 0.8 BRepMesh_IncrementalMesh(shape, linDeflection) bt = BRep_Tool() # Explore the faces of the shape # each face is triangulated, we need to collect all the parts expFac = TopExp_Explorer(shape, TopAbs_FACE) while expFac.More(): face = topods_Face(expFac.Current()) location = TopLoc_Location() facing = (bt.Triangulation(face, location)) try: tri = facing.Triangles() nTri = facing.NbTriangles() ver = facing.Nodes() except: tri = None nTri = None ver = None # store origin of the face's local coordinates transf = face.Location().Transformation() # iterate over triangles and store indices of vertices defining each triangle # OCC uses one-based indexing for i in range(1, nTri + 1): # each triangle is defined by three points # each point is defined by its index in the list of vertices index1, index2, index3 = tri.Value(i).Get() indices = [index1, index2, index3] # python uses zero-based indexing # for each vertex of a triangle, check whether it is already known # then store it (or not) and update the index for idx in [0, 1, 2]: # read global coordinates of each point vec3 = [ ver.Value(indices[idx]).Transformed(transf).X(), ver.Value(indices[idx]).Transformed(transf).Y(), ver.Value(indices[idx]).Transformed(transf).Z() ] if vec3 not in vertices: vertices.append(vec3) indices[idx] = vertices.index(vec3) triangles.extend(indices) expFac.Next() self.shape = shape self.vertices = vertices self.triangles = triangles self.normals = normals self.uv = uv
def read_file(self): """Build tree = treelib.Tree() to facilitate displaying the CAD model and constructing the tree view showing the assembly/component relationships. Each node of self.tree contains the following: (Name, UID, ParentUID, {Data}) where the Data keys are: 'a' (isAssy?), 'l' (TopLoc_Location), 'c' (Quantity_Color), 's' (TopoDS_Shape) """ logger.info("Reading STEP file") tmodel = TreeModel("STEP") self.shape_tool = tmodel.shape_tool self.color_tool = tmodel.color_tool step_reader = STEPCAFControl_Reader() step_reader.SetColorMode(True) step_reader.SetLayerMode(True) step_reader.SetNameMode(True) step_reader.SetMatMode(True) status = step_reader.ReadFile(self.filename) if status == IFSelect_RetDone: logger.info("Transfer doc to STEPCAFControl_Reader") step_reader.Transfer(tmodel.doc) labels = TDF_LabelSequence() self.shape_tool.GetShapes(labels) logger.info('Number of labels at root : %i', labels.Length()) try: rootlabel = labels.Value(1) # First label at root except RuntimeError: return name = self.getName(rootlabel) logger.info('Name of root label: %s', name) isAssy = self.shape_tool.IsAssembly(rootlabel) logger.info("First label at root holds an assembly? %s", isAssy) if isAssy: # If first label at root holds an assembly, it is the Top Assembly. # Through this label, the entire assembly is accessible. # there is no need to examine other labels at root explicitly. topLoc = TopLoc_Location() topLoc = self.shape_tool.GetLocation(rootlabel) self.assyLocStack.append(topLoc) entry = rootlabel.EntryDumpToString() logger.debug("Entry: %s", entry) logger.debug("Top assy name: %s", name) # Create root node for top assy newAssyUID = self.getNewUID() self.tree.create_node(name, newAssyUID, None, {'a': True, 'l': None, 'c': None, 's': None}) self.assyUidStack.append(newAssyUID) topComps = TDF_LabelSequence() # Components of Top Assy subchilds = False isAssy = self.shape_tool.GetComponents(rootlabel, topComps, subchilds) logger.debug("Is Assembly? %s", isAssy) logger.debug("Number of components: %s", topComps.Length()) logger.debug("Is Reference? %s", self.shape_tool.IsReference(rootlabel)) if topComps.Length(): self.findComponents(rootlabel, topComps) else: # Labels at root can hold solids or compounds (which are 'crude' assemblies) # Either way, we will need to create a root node in self.tree newAssyUID = self.getNewUID() self.tree.create_node(os.path.basename(self.filename), newAssyUID, None, {'a': True, 'l': None, 'c': None, 's': None}) self.assyUidStack = [newAssyUID] for j in range(labels.Length()): label = labels.Value(j+1) name = self.getName(label) isAssy = self.shape_tool.IsAssembly(label) logger.debug("Label %i is assembly?: %s", j+1, isAssy) shape = self.shape_tool.GetShape(label) color = self.getColor(shape) isSimpleShape = self.shape_tool.IsSimpleShape(label) logger.debug("Is Simple Shape? %s", isSimpleShape) shapeType = shape.ShapeType() logger.debug("The shape type is: %i", shapeType) if shapeType == 0: logger.debug("The shape type is OCC.Core.TopAbs.TopAbs_COMPOUND") topo = TopologyExplorer(shape) #topo = aocutils.topology.Topo(shape) logger.debug("Nb of compounds : %i", topo.number_of_compounds()) logger.debug("Nb of solids : %i", topo.number_of_solids()) logger.debug("Nb of shells : %i", topo.number_of_shells()) newAssyUID = self.getNewUID() for i, solid in enumerate(topo.solids()): name = "P%s" % str(i+1) self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], {'a': False, 'l': None, 'c': color, 's': solid}) elif shapeType == 2: logger.debug("The shape type is OCC.Core.TopAbs.TopAbs_SOLID") self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], {'a': False, 'l': None, 'c': color, 's': shape}) elif shapeType == 3: logger.debug("The shape type is OCC.Core.TopAbs.TopAbs_SHELL") self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], {'a': False, 'l': None, 'c': color, 's': shape}) return tmodel.doc # <class 'OCC.Core.TDocStd.TDocStd_Document'>
# c.Blue(), # Quantity_TOC_RGB)) shp = read_step_file(os.path.join('part_of_sattelate', 'pribore', 'DAV_WS16.STEP')) #BRepOffsetAPI_MakeOffsetShape(shp, 10, 0.1) #kode to rotation trsf = gp_Trsf() # vX = gp_Vec(12, 0, 0) # vY = gp_Vec(0, 12, 0) Mat = gp_Mat(0.5, (0.75**0.5), 0, -(0.75**2), 0.5, 0, 0, 0, 1) trsf.SetRotation(gp_Quaternion(Mat)) shp.Move(TopLoc_Location(trsf)) def measure(shape): bbox = Bnd_Box() #bbox.SetGap(tol) #bbox.SetShape(shape) brepbndlib_Add(shape, bbox) xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get() my_box = BRepPrimAPI_MakeBox(gp_Pnt(xmin, ymin, zmin), gp_Pnt(xmax, ymax, zmax)).Shape() #display.SetBackgroundImage('nevers-pont-de-loire.jpg', stretch=True) display.DisplayShape(my_box, color='GREEN', transparency=0.9) print(zmin, zmax, 'zzzzzzzzzzzzz') def glue_solids(event=None):
def _get_sub_shapes(lab, loc): l_subss = TDF_LabelSequence() shape_tool.GetSubShapes(lab, l_subss) #print("Nb subshapes :", l_subss.Length()) l_comps = TDF_LabelSequence() shape_tool.GetComponents(lab, l_comps) #print("Nb components :", l_comps.Length()) #print() name = lab.GetLabelName() print("Name :", name) if shape_tool.IsAssembly(lab): l_c = TDF_LabelSequence() shape_tool.GetComponents(lab, l_c) for i in range(l_c.Length()): label = l_c.Value(i + 1) if shape_tool.IsReference(label): label_reference = TDF_Label() shape_tool.GetReferredShape(label, label_reference) loc = shape_tool.GetLocation(label) locs.append(loc) _get_sub_shapes(label_reference, loc) locs.pop() elif shape_tool.IsSimpleShape(lab): shape = shape_tool.GetShape(lab) loc = TopLoc_Location() for l in locs: loc = loc.Multiplied(l) c = Quantity_Color(0.5, 0.5, 0.5, Quantity_TOC_RGB) # default color colorSet = False if (color_tool.GetInstanceColor(shape, 0, c) or color_tool.GetInstanceColor(shape, 1, c) or color_tool.GetInstanceColor(shape, 2, c)): color_tool.SetInstanceColor(shape, 0, c) color_tool.SetInstanceColor(shape, 1, c) color_tool.SetInstanceColor(shape, 2, c) colorSet = True n = c.Name(c.Red(), c.Green(), c.Blue()) print(' Instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) if not colorSet: if (color_tool.GetColor(lab, 0, c) or color_tool.GetColor(lab, 1, c) or color_tool.GetColor(lab, 2, c)): color_tool.SetInstanceColor(shape, 0, c) color_tool.SetInstanceColor(shape, 1, c) color_tool.SetInstanceColor(shape, 2, c) n = c.Name(c.Red(), c.Green(), c.Blue()) print(' Shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) shape_disp = BRepBuilderAPI_Transform( shape, loc.Transformation()).Shape() if not shape_disp in output_shapes: output_shapes[shape_disp] = [lab.GetLabelName(), c] for i in range(l_subss.Length()): lab_subs = l_subss.Value(i + 1) shape_sub = shape_tool.GetShape(lab_subs) c = Quantity_Color(0.5, 0.5, 0.5, Quantity_TOC_RGB) # default color colorSet = False if (color_tool.GetInstanceColor(shape_sub, 0, c) or color_tool.GetInstanceColor(shape_sub, 1, c) or color_tool.GetInstanceColor(shape_sub, 2, c)): color_tool.SetInstanceColor(shape_sub, 0, c) color_tool.SetInstanceColor(shape_sub, 1, c) color_tool.SetInstanceColor(shape_sub, 2, c) colorSet = True n = c.Name(c.Red(), c.Green(), c.Blue()) print(' Instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) if not colorSet: if (color_tool.GetColor(lab_subs, 0, c) or color_tool.GetColor(lab_subs, 1, c) or color_tool.GetColor(lab_subs, 2, c)): color_tool.SetInstanceColor(shape, 0, c) color_tool.SetInstanceColor(shape, 1, c) color_tool.SetInstanceColor(shape, 2, c) n = c.Name(c.Red(), c.Green(), c.Blue()) print(' Shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) shape_to_disp = BRepBuilderAPI_Transform( shape_sub, loc.Transformation()).Shape() # position the subshape to display if not shape_to_disp in output_shapes: output_shapes[shape_to_disp] = [ lab_subs.GetLabelName(), c ]
# ============================================================================== # BRep # ============================================================================== brep = BRep() brep.shape = face # mesh = brep.to_tesselation() BRepMesh_IncrementalMesh(brep.shape, 0.1, False, 0.1, False) bt = BRep_Tool() ex = TopExp_Explorer(brep.shape, TopAbs_FACE) while ex.More(): face = topods_Face(ex.Current()) location = TopLoc_Location() facing = (bt.Triangulation(face, location)) tab = facing.Nodes() tri = facing.Triangles() 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))
def Move_Beam(self, ax0=gp_Ax3(), ax1=gp_Ax3()): trf = gp_Trsf() trf.SetTransformation(ax1, ax0) loc = TopLoc_Location(trf) self.beam.Transform(trf)
def Move_Axs(self, axs=gp_Ax3(), ax0=gp_Ax3(), ax1=gp_Ax3()): trf = gp_Trsf() trf.SetTransformation(ax1, ax0) loc = TopLoc_Location(trf) return axs.Transformed(trf)
from OCC.Core.TopLoc import TopLoc_Location from OCC.Core.Addons import text_to_brep, register_font, Font_FA_Regular, Font_FA_Undefined display, start_display, add_menu, add_function_to_menu = init_display() # resgister font register_font("./fonts/Respective.ttf") register_font("./fonts/METROLOX.ttf") text = """ Japan """ # create a basic string arialbold_brep_string1 = text_to_brep(text, "Respective", Font_FA_Regular, 10., True) arialbold_brep_string2 = text_to_brep(text, "METOLOX", Font_FA_Regular, 10., True) trf = gp_Trsf() trf.SetDisplacement(gp_Ax3(), gp_Ax3(gp_Pnt(0, 20, 0), gp_Dir(0, 0, 1))) arialbold_brep_string2.Move(TopLoc_Location(trf)) # Then display the string display.DisplayShape(arialbold_brep_string1) display.DisplayShape(arialbold_brep_string2) display.FitAll() start_display()
def mesh_model(model, res_path, convert=True, all_edges=True): fil = model.split("/")[-1][:-5] folder = "/".join(model.split("/")[:-1]) with fileinput.FileInput(model, inplace=True) as fi: for line in fi: print(line.replace( "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-06 )", "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-17 )" ), end='') occ_steps = read_step_file(model) bt = BRep_Tool() for occ_cnt in range(len(occ_steps)): if convert: try: nurbs_converter = BRepBuilderAPI_NurbsConvert( occ_steps[occ_cnt]) nurbs_converter.Perform(occ_steps[occ_cnt]) nurbs = nurbs_converter.Shape() except: print("Conversion failed") continue else: nurbs = occ_steps[occ_cnt] mesh = BRepMesh_IncrementalMesh(occ_steps[occ_cnt], 0.9, False, 0.5, True) mesh.Perform() if not mesh.IsDone(): print("Mesh is not done.") continue occ_topo = TopologyExplorer(nurbs) occ_top = Topo(nurbs) occ_topo1 = TopologyExplorer(occ_steps[occ_cnt]) occ_top1 = Topo(occ_steps[occ_cnt]) d1_feats = [] d2_feats = [] t_curves = [] tr_curves = [] stats = {} stats["model"] = model total_edges = 0 total_surfs = 0 stats["curves"] = [] stats["surfs"] = [] c_cnt = 0 t_cnt = 0 # Iterate over edges for edge in occ_topo.edges(): curve = BRepAdaptor_Curve(edge) stats["curves"].append(edge_map[curve.GetType()]) d1_feat = convert_curve(curve) if edge_map[curve.GetType()] == "Other": continue for f in occ_top.faces_from_edge(edge): if f == None: print("Broken face") continue su = BRepAdaptor_Surface(f) c = BRepAdaptor_Curve2d(edge, f) t_curve = { "surface": f, "3dcurve": edge, "3dcurve_id": c_cnt, "2dcurve_id": t_cnt } t_curves.append(t_curve) tr_curves.append(convert_2dcurve(c)) t_cnt += 1 d1_feats.append(d1_feat) c_cnt += 1 total_edges += 1 patches = [] faces1 = list(occ_topo1.faces()) # Iterate over faces for fci, face in enumerate(occ_topo.faces()): surf = BRepAdaptor_Surface(face) stats["surfs"].append(surf_map[surf.GetType()]) d2_feat = convert_surface(surf) if surf_map[surf.GetType()] == "Other": continue for tc in t_curves: if tc["surface"] == face: patch = { "3dcurves": [], "2dcurves": [], "orientations": [], "surf_orientation": face.Orientation(), "wire_ids": [], "wire_orientations": [] } for wc, fw in enumerate(occ_top.wires_from_face(face)): patch["wire_orientations"].append(fw.Orientation()) if all_edges: edges = [ i for i in WireExplorer(fw).ordered_edges() ] else: edges = list(occ_top.edges_from_wire(fw)) for fe in edges: for ttc in t_curves: if ttc["3dcurve"].IsSame(fe) and tc[ "surface"] == ttc["surface"]: patch["3dcurves"].append(ttc["3dcurve_id"]) patch["2dcurves"].append(ttc["2dcurve_id"]) patch["wire_ids"].append(wc) orientation = fe.Orientation() patch["orientations"].append(orientation) patches.append(patch) break location = TopLoc_Location() facing = (bt.Triangulation(faces1[fci], location)) if facing != None: tab = facing.Nodes() tri = facing.Triangles() verts = [] for i in range(1, facing.NbNodes() + 1): verts.append(list(tab.Value(i).Coord())) faces = [] for i in range(1, facing.NbTriangles() + 1): index1, index2, index3 = tri.Value(i).Get() faces.append([index1 - 1, index2 - 1, index3 - 1]) os.makedirs(res_path, exist_ok=True) igl.write_triangle_mesh( "%s/%s_%03i_mesh_%04i.obj" % (res_path, fil, occ_cnt, fci), np.array(verts), np.array(faces)) d2_feat["faces"] = faces d2_feat["verts"] = verts else: print("Missing triangulation") continue d2_feats.append(d2_feat) total_surfs += 1 bbox = get_boundingbox(occ_steps[occ_cnt], use_mesh=False) xmin, ymin, zmin, xmax, ymax, zmax = bbox[:6] bbox1 = [ "%.2f" % xmin, "%.2f" % ymin, "%.2f" % zmin, "%.2f" % xmax, "%.2f" % ymax, "%.2f" % zmax, "%.2f" % (xmax - xmin), "%.2f" % (ymax - ymin), "%.2f" % (zmax - zmin) ] stats["#edges"] = total_edges stats["#surfs"] = total_surfs # Fix possible orientation problems if convert: for p in patches: # Check orientation of first curve if len(p["2dcurves"]) >= 2: cur = tr_curves[p["2dcurves"][0]] nxt = tr_curves[p["2dcurves"][1]] c_ori = p["orientations"][0] n_ori = p["orientations"][1] if c_ori == 0: pole0 = np.array(cur["poles"][0]) pole1 = np.array(cur["poles"][-1]) else: pole0 = np.array(cur["poles"][-1]) pole1 = np.array(cur["poles"][0]) if n_ori == 0: pole2 = np.array(nxt["poles"][0]) pole3 = np.array(nxt["poles"][-1]) else: pole2 = np.array(nxt["poles"][-1]) pole3 = np.array(nxt["poles"][0]) d02 = np.abs(pole0 - pole2) d12 = np.abs(pole1 - pole2) d03 = np.abs(pole0 - pole3) d13 = np.abs(pole1 - pole3) amin = np.argmin([d02, d12, d03, d13]) if amin == 0 or amin == 2: # Orientation of first curve incorrect, fix p["orientations"][0] = abs(c_ori - 1) # Fix all orientations for i in range(len(p["2dcurves"]) - 1): cur = tr_curves[p["2dcurves"][i]] nxt = tr_curves[p["2dcurves"][i + 1]] c_ori = p["orientations"][i] n_ori = p["orientations"][i + 1] if c_ori == 0: pole1 = np.array(cur["poles"][-1]) else: pole1 = np.array(cur["poles"][0]) if n_ori == 0: pole2 = np.array(nxt["poles"][0]) pole3 = np.array(nxt["poles"][-1]) else: pole2 = np.array(nxt["poles"][-1]) pole3 = np.array(nxt["poles"][0]) d12 = np.abs(pole1 - pole2) d13 = np.abs(pole1 - pole3) amin = np.min([d12, d13]) if amin == 1: # Incorrect orientation, flip p["orientations"][i + 1] = abs(n_ori - 1) features = { "curves": d1_feats, "surfaces": d2_feats, "trim": tr_curves, "topo": patches, "bbox": bbox1 } os.makedirs(res_path, exist_ok=True) fip = fil + "_features2" with open("%s/%s_%03i.yml" % (res_path, fip, occ_cnt), "w") as fili: yaml.dump(features, fili, indent=2) fip = fil + "_features" with open("%s/%s_%03i.yml" % (res_path, fip, occ_cnt), "w") as fili: features2 = copy.deepcopy(features) for sf in features2["surfaces"]: del sf["faces"] del sf["verts"] yaml.dump(features2, fili, indent=2) # res_path = folder.replace("/step/", "/stat/") # fip = fil + "_stats" # with open("%s/%s_%03i.yml"%(res_path, fip, occ_cnt), "w") as fili: # yaml.dump(stats, fili, indent=2) print("Writing results for %s with %i parts." % (model, len(occ_steps)))
def Locate_centre_face2(self, number, name_body, angle, x_drive, y_drive): from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeFace, BRepBuilderAPI_MakeWire, BRepBuilderAPI_MakeEdge, \ BRepBuilderAPI_Copy from OCC.Core.Bnd import Bnd_Box from OCC.Core.BRepBndLib import brepbndlib_Add from OCC.Core.gp import gp_Pnt, gp_Trsf, gp_Vec, gp_Pln, gp_Dir, gp_Ax3, gp_Ax1 from OCC.Core.TopLoc import TopLoc_Location cp = BRepBuilderAPI_Copy(self.reserv_models[name_body]) cp.Perform(self.reserv_models[name_body]) shape = cp.Shape() # move to zero bbox = Bnd_Box() brepbndlib_Add(shape, bbox) xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get() trsf = gp_Trsf() trsf.SetTranslation( gp_Vec(-xmin - (xmax - xmin) / 2, -ymin - (ymax - ymin) / 2, -zmin)) shape.Move(TopLoc_Location(trsf)) # Process vector of rotation to face x, y = 1, 1 x = -self.walls[number][1][1] y = self.walls[number][1][0] z = 0 P0 = gp_Pnt(0, 0, 0) P1 = gp_Pnt(0, 0, 1) P2 = gp_Pnt(self.walls[number][1][0], self.walls[number][1][1], self.walls[number][1][2]) # rotation to Ax z v_x = gp_Vec(P0, gp_Pnt(0, 1, 0)) v_r = gp_Vec(P0, gp_Pnt(x, y, z)) trsf = gp_Trsf() #print(v_r.Angle(v_x)) trsf.SetRotation(gp_Ax1(P0, gp_Dir(0, 0, 1)), v_r.Angle(v_x)) shape.Move(TopLoc_Location(trsf)) # rotation in parallel to face v0 = gp_Vec(P0, P1) v1 = gp_Vec(P0, P2) # print(v1.Angle(v0)) trsf = gp_Trsf() trsf.SetRotation(gp_Ax1(P0, gp_Dir(x, y, z)), v1.Angle(v0)) # move to face shape.Move(TopLoc_Location(trsf)) trsf = gp_Trsf() trsf.SetTranslation( gp_Vec(self.walls[number][0][0], self.walls[number][0][1], self.walls[number][0][2])) shape.Move(TopLoc_Location(trsf)) # Rotation by given angle trsf = gp_Trsf() trsf.SetRotation( gp_Ax1( P0, gp_Dir(self.walls[number][1][0], self.walls[number][1][1], self.walls[number][1][2])), angle) shape.Move(TopLoc_Location(trsf)) # initional x, y offset_y, offset_x = self.rot_point(xmax - xmin, ymax - ymin, angle) limit_x = self.walls[number][3][0] / 2 - offset_x limit_y = self.walls[number][3][1] / 2 - offset_y move_x = int(limit_x * x_drive) move_y = int(limit_y * y_drive) # Move to x and y x_axy = self.walls[number][1][1] * self.walls[number][2][ 2] - self.walls[number][1][2] * self.walls[number][2][1] y_axy = -(self.walls[number][1][0] * self.walls[number][2][2] - self.walls[number][1][2] * self.walls[number][2][0]) z_axy = self.walls[number][1][0] * self.walls[number][2][ 1] - self.walls[number][1][1] * self.walls[number][2][0] x_axy *= move_y y_axy *= move_y z_axy *= move_y trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(x_axy, y_axy, z_axy)) shape.Move(TopLoc_Location(trsf)) trsf = gp_Trsf() trsf.SetTranslation( gp_Vec(self.walls[number][2][0] * move_x, self.walls[number][2][1] * move_x, self.walls[number][2][2] * move_x)) shape.Move(TopLoc_Location(trsf)) # print(name_body, shape) self.modules[name_body] = shape
def MoveSurface(self, ax1=gp_Ax3(), ax2=gp_Ax3()): trsf = set_trf(ax1, ax2) self.face.Move(TopLoc_Location(trsf))
def parse_components(self, comps, shape_tool, color_tool): """Parse components from comps (LabelSequence). Components of an assembly are, by definition, references which refer to either a simple shape or a compound shape (an assembly). Components are essentially 'instances' of the referred shape or assembly and carry a location vector specifing the location of the referred shape or assembly.""" for j in range(comps.Length()): logger.debug("Assy_entry_stack: %s", self.assy_entry_stack) logger.debug("loop %i of %i", j + 1, comps.Length()) c_label = comps.Value(j + 1) # component label <class 'TDF_Label'> c_name = c_label.GetLabelName() c_entry = c_label.EntryDumpToString() c_uid = self.get_uid_from_entry(c_entry) c_shape = shape_tool.GetShape(c_label) logger.debug("Component number %i", j + 1) logger.debug("Component name: %s", c_name) logger.debug("Component entry: %s", c_entry) ref_label = TDF_Label() # label of referred shape (or assembly) is_ref = shape_tool.GetReferredShape(c_label, ref_label) if is_ref: # I think all components are references ref_name = ref_label.GetLabelName() ref_shape = shape_tool.GetShape(ref_label) ref_entry = ref_label.EntryDumpToString() self.label_dict[c_uid] = { 'entry': c_entry, 'name': c_name, 'parent_uid': self.parent_uid_stack[-1], 'ref_entry': ref_entry } if shape_tool.IsSimpleShape(ref_label): self.label_dict[c_uid].update({'is_assy': False}) temp_assy_loc_stack = list(self.assy_loc_stack) # Multiply locations in stack sequentially to a result if len(temp_assy_loc_stack) > 1: res_loc = temp_assy_loc_stack.pop(0) for loc in temp_assy_loc_stack: res_loc = res_loc.Multiplied(loc) c_shape.Move(res_loc) elif len(temp_assy_loc_stack) == 1: res_loc = temp_assy_loc_stack.pop() c_shape.Move(res_loc) else: res_loc = None # It is possible for this component to both specify a # location 'c_loc' and refer directly to a top level shape. # If this component *does* specify a location 'c_loc', # it will be applied to the referred shape without being # included in temp_assy_loc_stack. But in order to keep # track of the total location from the root shape to the # instance, it needs to be accounted for (by mutiplying # res_loc by it) before saving it to part_dict. c_loc = None c_loc = shape_tool.GetLocation(c_label) if c_loc: loc = res_loc.Multiplied(c_loc) color = Quantity_Color() color_tool.GetColor(ref_shape, XCAFDoc_ColorSurf, color) self.part_dict[c_uid] = { 'shape': c_shape, 'color': color, 'name': c_name, 'loc': loc } elif shape_tool.IsAssembly(ref_label): self.label_dict[c_uid].update({'is_assy': True}) logger.debug("Referred item is an Assembly") # Location vector is carried by component aLoc = TopLoc_Location() aLoc = shape_tool.GetLocation(c_label) self.assy_loc_stack.append(aLoc) self.assy_entry_stack.append(ref_entry) self.parent_uid_stack.append(c_uid) r_comps = TDF_LabelSequence() # Components of Assy subchilds = False isAssy = shape_tool.GetComponents(ref_label, r_comps, subchilds) logger.debug("Assy name: %s", ref_name) logger.debug("Is Assembly? %s", isAssy) logger.debug("Number of components: %s", r_comps.Length()) if r_comps.Length(): logger.debug("") logger.debug("Parsing components of label entry %s)", ref_entry) self.parse_components(r_comps, shape_tool, color_tool) else: print( f"I was wrong: All components are *not* references {c_uid}" ) self.assy_entry_stack.pop() self.assy_loc_stack.pop() self.parent_uid_stack.pop()
def location_from_vector(x, y, z): trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(x, y, z)) loc = TopLoc_Location(trsf) return loc
def set_loc(ax1=gp_Ax3(), ax2=gp_Ax3()): trf = set_trf(ax1, ax2) loc = TopLoc_Location(trf) return loc
def findComponents(self, label, comps): """Discover components from comps (LabelSequence) of an assembly (label). Components of an assembly are, by definition, references which refer to either a shape or another assembly. Components are essentially 'instances' of the referred shape or assembly, and carry a location vector specifing the location of the referred shape or assembly. """ logger.debug("") logger.debug("Finding components of label entry %s)", label.EntryDumpToString()) for j in range(comps.Length()): logger.debug("loop %i of %i", j+1, comps.Length()) cLabel = comps.Value(j+1) # component label <class 'OCC.Core.TDF.TDF_Label'> cShape = self.shape_tool.GetShape(cLabel) logger.debug("Component number %i", j+1) logger.debug("Component entry: %s", cLabel.EntryDumpToString()) name = self.getName(cLabel) logger.debug("Component name: %s", name) refLabel = TDF_Label() # label of referred shape (or assembly) isRef = self.shape_tool.GetReferredShape(cLabel, refLabel) if isRef: # I think all components are references, but just in case... refShape = self.shape_tool.GetShape(refLabel) refLabelEntry = refLabel.EntryDumpToString() logger.debug("Entry referred to: %s", refLabelEntry) refName = self.getName(refLabel) logger.debug("Name of referred item: %s", refName) if self.shape_tool.IsSimpleShape(refLabel): logger.debug("Referred item is a Shape") logger.debug("Name of Shape: %s", refName) tempAssyLocStack = list(self.assyLocStack) tempAssyLocStack.reverse() for loc in tempAssyLocStack: cShape.Move(loc) color = self.getColor(refShape) self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], {'a': False, 'l': None, 'c': color, 's': cShape}) elif self.shape_tool.IsAssembly(refLabel): logger.debug("Referred item is an Assembly") logger.debug("Name of Assembly: %s", refName) name = self.getName(cLabel) # Instance name aLoc = TopLoc_Location() # Location vector is carried by component aLoc = self.shape_tool.GetLocation(cLabel) self.assyLocStack.append(aLoc) newAssyUID = self.getNewUID() self.tree.create_node(name, newAssyUID, self.assyUidStack[-1], {'a': True, 'l': aLoc, 'c': None, 's': None}) self.assyUidStack.append(newAssyUID) rComps = TDF_LabelSequence() # Components of Assy subchilds = False isAssy = self.shape_tool.GetComponents(refLabel, rComps, subchilds) logger.debug("Assy name: %s", name) logger.debug("Is Assembly? %s", isAssy) logger.debug("Number of components: %s", rComps.Length()) if rComps.Length(): self.findComponents(refLabel, rComps) self.assyUidStack.pop() self.assyLocStack.pop()
def read_file(self): """Build self.tree (treelib.Tree()) containing CAD data read from a step file. Each node of self.tree contains the following: (Name, UID, ParentUID, {Data}) where the Data keys are: 'a' (isAssy?), 'l' (TopLoc_Location), 'c' (Quantity_Color), 's' (TopoDS_Shape) """ logger.info("Reading STEP file") doc = TDocStd_Document(TCollection_ExtendedString("STEP")) # Create the application app = XCAFApp_Application_GetApplication() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), doc) # Get root shapes shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) shape_tool.SetAutoNaming(True) self.color_tool = XCAFDoc_DocumentTool_ColorTool(doc.Main()) layer_tool = XCAFDoc_DocumentTool_LayerTool(doc.Main()) l_materials = XCAFDoc_DocumentTool_MaterialTool(doc.Main()) step_reader = STEPCAFControl_Reader() step_reader.SetColorMode(True) step_reader.SetLayerMode(True) step_reader.SetNameMode(True) step_reader.SetMatMode(True) status = step_reader.ReadFile(self.filename) if status == IFSelect_RetDone: logger.info("Transfer doc to STEPCAFControl_Reader") step_reader.Transfer(doc) # Test round trip by writing doc back to another file. logger.info("Doing a 'short-circuit' Round Trip test") doctype = type(doc) # <class 'OCC.Core.TDocStd.TDocStd_Document'> logger.info(f"Writing {doctype} back to another STEP file") self.testRTStep(doc) # Save doc to file (for educational purposes) (not working yet) logger.debug("Saving doc to file") savefilename = TCollection_ExtendedString('../doc.txt') app.SaveAs(doc, savefilename) labels = TDF_LabelSequence() color_labels = TDF_LabelSequence() shape_tool.GetShapes(labels) self.shape_tool = shape_tool logger.info('Number of labels at root : %i' % labels.Length()) try: label = labels.Value(1) # First label at root except RuntimeError: return name = self.getName(label) logger.info('Name of root label: %s' % name) isAssy = shape_tool.IsAssembly(label) logger.info("First label at root holds an assembly? %s" % isAssy) if isAssy: # If first label at root holds an assembly, it is the Top Assembly. # Through this label, the entire assembly is accessible. # No need to examine other labels at root explicitly. topLoc = TopLoc_Location() topLoc = shape_tool.GetLocation(label) self.assyLocStack.append(topLoc) entry = label.EntryDumpToString() logger.debug("Entry: %s" % entry) logger.debug("Top assy name: %s" % name) # Create root node for top assy newAssyUID = self.getNewUID() self.tree.create_node(name, newAssyUID, None, { 'a': True, 'l': None, 'c': None, 's': None }) self.assyUidStack.append(newAssyUID) topComps = TDF_LabelSequence() # Components of Top Assy subchilds = False isAssy = shape_tool.GetComponents(label, topComps, subchilds) logger.debug("Is Assembly? %s" % isAssy) logger.debug("Number of components: %s" % topComps.Length()) logger.debug("Is Reference? %s" % shape_tool.IsReference(label)) if topComps.Length(): self.findComponents(label, topComps) else: # Labels at root can hold solids or compounds (which are 'crude' assemblies) # Either way, we will need to create a root node in self.tree newAssyUID = self.getNewUID() self.tree.create_node(os.path.basename(self.filename), newAssyUID, None, { 'a': True, 'l': None, 'c': None, 's': None }) self.assyUidStack = [newAssyUID] for j in range(labels.Length()): label = labels.Value(j + 1) name = self.getName(label) isAssy = shape_tool.IsAssembly(label) logger.debug("Label %i is assembly?: %s" % (j + 1, isAssy)) shape = shape_tool.GetShape(label) color = self.getColor(shape) isSimpleShape = self.shape_tool.IsSimpleShape(label) logger.debug("Is Simple Shape? %s" % isSimpleShape) shapeType = shape.ShapeType() logger.debug("The shape type is: %i" % shapeType) if shapeType == 0: logger.debug( "The shape type is OCC.Core.TopAbs.TopAbs_COMPOUND") topo = TopologyExplorer(shape) #topo = aocutils.topology.Topo(shape) logger.debug("Nb of compounds : %i" % topo.number_of_compounds()) logger.debug("Nb of solids : %i" % topo.number_of_solids()) logger.debug("Nb of shells : %i" % topo.number_of_shells()) newAssyUID = self.getNewUID() for i, solid in enumerate(topo.solids()): name = "P%s" % str(i + 1) self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], { 'a': False, 'l': None, 'c': color, 's': solid }) elif shapeType == 2: logger.debug( "The shape type is OCC.Core.TopAbs.TopAbs_SOLID") self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], { 'a': False, 'l': None, 'c': color, 's': shape }) elif shapeType == 3: logger.debug( "The shape type is OCC.Core.TopAbs.TopAbs_SHELL") self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], { 'a': False, 'l': None, 'c': color, 's': shape }) return True
def surf_trf(pnt, vec, face): axs = gp_Ax3(pnt, vec_to_dir(vec)) trf = gp_Trsf() trf.SetTransformation(axs, gp_Ax3()) srf = face.Moved(TopLoc_Location(trf)) return srf
def findComponents(self, label, comps): # Discover Components of an Assembly logger.debug("") logger.debug("Finding components of label (entry = %s)" % label.EntryDumpToString()) for j in range(comps.Length()): logger.debug("loop %i of %i" % (j + 1, comps.Length())) cLabel = comps.Value(j + 1) cShape = self.shape_tool.GetShape(cLabel) logger.debug("Label %i - type : %s" % (j + 1, type(cLabel))) logger.debug("Entry: %s" % cLabel.EntryDumpToString()) name = self.getName(cLabel) logger.debug("Part name: %s" % name) logger.debug("Is Assembly? %s" % self.shape_tool.IsAssembly(cLabel)) logger.debug("Is Component? %s" % self.shape_tool.IsComponent(cLabel)) logger.debug("Is Simple Shape? %s" % self.shape_tool.IsSimpleShape(cLabel)) logger.debug("Is Reference? %s" % self.shape_tool.IsReference(cLabel)) refLabel = TDF_Label() isRef = self.shape_tool.GetReferredShape(cLabel, refLabel) if isRef: refShape = self.shape_tool.GetShape(refLabel) refLabelEntry = refLabel.EntryDumpToString() logger.debug("Entry of referred shape: %s" % refLabelEntry) refName = self.getName(refLabel) logger.debug("Name of referred shape: %s" % refName) logger.debug("Is Assembly? %s" % self.shape_tool.IsAssembly(refLabel)) logger.debug("Is Component? %s" % self.shape_tool.IsComponent(refLabel)) logger.debug("Is Simple Shape? %s" % self.shape_tool.IsSimpleShape(refLabel)) logger.debug("Is Reference? %s" % self.shape_tool.IsReference(refLabel)) if self.shape_tool.IsSimpleShape(refLabel): tempAssyLocStack = list(self.assyLocStack) tempAssyLocStack.reverse() for loc in tempAssyLocStack: cShape.Move(loc) color = self.getColor(refShape) self.tree.create_node(name, self.getNewUID(), self.assyUidStack[-1], { 'a': False, 'l': None, 'c': color, 's': cShape }) elif self.shape_tool.IsAssembly(refLabel): name = self.getName(cLabel) # Instance name aLoc = TopLoc_Location() aLoc = self.shape_tool.GetLocation(cLabel) self.assyLocStack.append(aLoc) newAssyUID = self.getNewUID() self.tree.create_node(name, newAssyUID, self.assyUidStack[-1], { 'a': True, 'l': aLoc, 'c': None, 's': None }) self.assyUidStack.append(newAssyUID) rComps = TDF_LabelSequence() # Components of Assy subchilds = False isAssy = self.shape_tool.GetComponents( refLabel, rComps, subchilds) logger.debug("Assy name: %s" % name) logger.debug("Is Assembly? %s" % isAssy) logger.debug("Number of components: %s" % rComps.Length()) if rComps.Length(): self.findComponents(refLabel, rComps) self.assyUidStack.pop() self.assyLocStack.pop() return
def getSubShapes(lab, loc): global cnt, lvl cnt += 1 print("\n[%d] level %d, handling LABEL %s\n" % (cnt, lvl, get_label_name(lab))) print() print(lab.DumpToString()) print() print("Is Assembly :", shape_tool.IsAssembly(lab)) print("Is Free :", shape_tool.IsFree(lab)) print("Is Shape :", shape_tool.IsShape(lab)) print("Is Compound :", shape_tool.IsCompound(lab)) print("Is Component :", shape_tool.IsComponent(lab)) print("Is SimpleShape :", shape_tool.IsSimpleShape(lab)) print("Is Reference :", shape_tool.IsReference(lab)) users = TDF_LabelSequence() users_cnt = shape_tool.GetUsers(lab, users) print("Nr Users :", users_cnt) l_subss = TDF_LabelSequence() shape_tool.GetSubShapes(lab, l_subss) print("Nb subshapes :", l_subss.Length()) l_comps = TDF_LabelSequence() shape_tool.GetComponents(lab, l_comps) print("Nb components :", l_comps.Length()) print() if shape_tool.IsAssembly(lab): l_c = TDF_LabelSequence() shape_tool.GetComponents(lab, l_c) for i in range(l_c.Length()): label = l_c.Value(i + 1) if shape_tool.IsReference(label): print("\n######## reference label :", label) label_reference = TDF_Label() shape_tool.GetReferredShape(label, label_reference) loc = shape_tool.GetLocation(label) print(" loc :", loc) trans = loc.Transformation() print(" tran form :", trans.Form()) rot = trans.GetRotation() print(" rotation :", rot) print(" X :", rot.X()) print(" Y :", rot.Y()) print(" Z :", rot.Z()) print(" W :", rot.W()) tran = trans.TranslationPart() print(" translation :", tran) print(" X :", tran.X()) print(" Y :", tran.Y()) print(" Z :", tran.Z()) locs.append(loc) print(">>>>") lvl += 1 getSubShapes(label_reference, loc) lvl -= 1 print("<<<<") locs.pop() elif shape_tool.IsSimpleShape(lab): print("\n######## simpleshape label :", lab) shape = shape_tool.GetShape(lab) print(" all ass locs :", locs) loc = TopLoc_Location() for i in range(len(locs)): print(" take loc :", locs[i]) loc = loc.Multiplied(locs[i]) trans = loc.Transformation() print(" FINAL loc :") print(" tran form :", trans.Form()) rot = trans.GetRotation() print(" rotation :", rot) print(" X :", rot.X()) print(" Y :", rot.Y()) print(" Z :", rot.Z()) print(" W :", rot.W()) tran = trans.TranslationPart() print(" translation :", tran) print(" X :", tran.X()) print(" Y :", tran.Y()) print(" Z :", tran.Z()) shape = BRepBuilderAPI_Transform(shape, loc.Transformation()).Shape() c = Quantity_Color() colorSet = False if (color_tool.GetInstanceColor(shape, 0, c) or color_tool.GetInstanceColor(shape, 1, c) or color_tool.GetInstanceColor(shape, 2, c)): for i in (0, 1, 2): color_tool.SetInstanceColor(shape, i, c) colorSet = True n = c.Name(c.Red(), c.Green(), c.Blue()) print(' instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) if not colorSet: if (color_tool.GetColor(lab, 0, c) or color_tool.GetColor(lab, 1, c) or color_tool.GetColor(lab, 2, c)): for i in (0, 1, 2): color_tool.SetInstanceColor(shape, i, c) n = c.Name(c.Red(), c.Green(), c.Blue()) print(' shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # n = c.Name(c.Red(), c.Green(), c.Blue()) # print(' color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # Display shape display.DisplayColoredShape(shape, c) for i in range(l_subss.Length()): lab = l_subss.Value(i + 1) print("\n######## simpleshape subshape label :", lab) shape = shape_tool.GetShape(lab) c = Quantity_Color() colorSet = False if (color_tool.GetInstanceColor(shape, 0, c) or color_tool.GetInstanceColor(shape, 1, c) or color_tool.GetInstanceColor(shape, 2, c)): for i in (0, 1, 2): color_tool.SetInstanceColor(shape, i, c) colorSet = True n = c.Name(c.Red(), c.Green(), c.Blue()) print(' instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) if not colorSet: if (color_tool.GetColor(lab, 0, c) or color_tool.GetColor(lab, 1, c) or color_tool.GetColor(lab, 2, c)): for i in (0, 1, 2): color_tool.SetInstanceColor(shape, i, c) n = c.Name(c.Red(), c.Green(), c.Blue()) print(' shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # n = c.Name(c.Red(), c.Green(), c.Blue()) # print(' color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # Display shape display.DisplayColoredShape(shape, c)
def Create_Bk(self, filename="SFU01204-4", ss="BKBF10", L=1000): pass "获取选择零件名称 获取路径" # 获取零件名称 try: pass new_shape = TopoDS_Shape() #filename = "SFU2005-4" # 获取相应零件的路径*************************************** self.partpath = os.getcwd() self.partpath = self.partpath + "\\3Ddata" + "\\STP" + "\\" + filename + ".stp" self.shape = read_step_file(self.partpath) self.shape.Free(True) # 先释放shape # self.new_build.Add(self.aCompound,shape123)#将shaoe添加入复合体 self.new_build.Add(self.aCompound, self.shape) #绘制丝杆************************************************** if int(filename[3:6]) == 12 or int(filename[3:6]) == 14 or int( filename[3:6]) == 15: ss = "BKBF10" elif int(filename[3:6]) == 14 or int(filename[3:6]) == 15 or int( filename[3:6]) == 16 or int(filename[3:6]) == 18: pass ss = "BKBF12" elif int(filename[3:6]) == 18 or int(filename[3:6]) == 20: ss = "BKBF15" elif int(filename[3:6]) == 20 or int(filename[3:6]) == 25: ss = "BKBF17" elif int(filename[3:6]) == 25 or int(filename[3:6]) == 28: ss = "BKBF20" elif int(filename[3:6]) == 32 or int(filename[3:6]) == 36: ss = "BKBF25" elif int(filename[3:6]) == 36 or int(filename[3:6]) == 40: ss = "BKBF30" elif int(filename[3:6]) == 40 or int(filename[3:6]) == 45 or int( filename[3:6]) == 50: ss = "BKBF35" elif int(filename[3:6]) == 50 or int(filename[3:6]) == 55: ss = "BKBF40" self.BK_serise_dict[ss]["D3"] = int(filename[3:6]) #重新设置丝杆直径 #print(filename[3:6]) #PL = (L - 15 - 39 - 10) / 2 ''' PL = (L - self.BK_serise_dict[ss]["L1"] - self.BK_serise_dict[ss]["L3"] - self.BK_serise_dict[ss]["L4"]) / 2 ''' #Center_point=filename[0:] PL = L / 2 #P1 = [0, 0, PL + 39 + 15] P1 = [ 0, 0, PL + self.BK_serise_dict[ss]["L3"] + self.BK_serise_dict[ss]["L1"] ] #P2 = [0, 4, PL + 39 + 15] P2 = [ 0, self.BK_serise_dict[ss]["D1"] / 2, PL + self.BK_serise_dict[ss]["L3"] + self.BK_serise_dict[ss]["L1"] ] #P3 = [0, 4, PL + 39] P3 = [ 0, self.BK_serise_dict[ss]["D1"] / 2, PL + self.BK_serise_dict[ss]["L3"] ] #P4 = [0, 5, PL + 39] P4 = [ 0, self.BK_serise_dict[ss]["D2"] / 2, PL + self.BK_serise_dict[ss]["L3"] ] #P5 = [0, 5, PL] P5 = [0, self.BK_serise_dict[ss]["D2"] / 2, PL] #P6 = [0, 6, PL] P6 = [0, self.BK_serise_dict[ss]["D3"] / 2, PL] #P7 = [0, 6, -PL] P7 = [0, self.BK_serise_dict[ss]["D3"] / 2, -PL] #P8 = [0, 4, -PL] P8 = [0, self.BK_serise_dict[ss]["D4"] / 2, -PL] #P9 = [0, 4, -PL - 7.9] P9 = [ 0, self.BK_serise_dict[ss]["D4"] / 2, -PL - self.BK_serise_dict[ss]["L5"] ] #P10 = [0, 4 - 0.2, -PL - 7.9] P10 = [ 0, self.BK_serise_dict[ss]["D5"] / 2, -PL - self.BK_serise_dict[ss]["L5"] ] #P11 = [0, 4 - 0.2, -PL - 7.9 - 0.8] P11 = [ 0, self.BK_serise_dict[ss]["D5"] / 2, -PL - self.BK_serise_dict[ss]["L5"] - self.BK_serise_dict[ss]["L6"] ] #P12 = [0, 4, -PL - 7.9 - 0.8] P12 = [ 0, self.BK_serise_dict[ss]["D4"] / 2, -PL - self.BK_serise_dict[ss]["L5"] - self.BK_serise_dict[ss]["L6"] ] #P13 = [0, 4, -PL - 10] P13 = [ 0, self.BK_serise_dict[ss]["D4"] / 2, -PL - self.BK_serise_dict[ss]["L4"] ] #P14 = [0, 0, -PL - 10] P14 = [0, 0, -PL - self.BK_serise_dict[ss]["L4"]] E11 = BRepBuilderAPI_MakeEdge(gp_Pnt(P1[0], P1[1], P1[2]), gp_Pnt(P2[0], P2[1], P2[2])).Edge() E12 = BRepBuilderAPI_MakeEdge(gp_Pnt(P2[0], P2[1], P2[2]), gp_Pnt(P3[0], P3[1], P3[2])).Edge() E13 = BRepBuilderAPI_MakeEdge(gp_Pnt(P3[0], P3[1], P3[2]), gp_Pnt(P4[0], P4[1], P4[2])).Edge() E14 = BRepBuilderAPI_MakeEdge(gp_Pnt(P4[0], P4[1], P4[2]), gp_Pnt(P5[0], P5[1], P5[2])).Edge() E15 = BRepBuilderAPI_MakeEdge(gp_Pnt(P5[0], P5[1], P5[2]), gp_Pnt(P6[0], P6[1], P6[2])).Edge() E16 = BRepBuilderAPI_MakeEdge(gp_Pnt(P6[0], P6[1], P6[2]), gp_Pnt(P7[0], P7[1], P7[2])).Edge() E17 = BRepBuilderAPI_MakeEdge(gp_Pnt(P7[0], P7[1], P7[2]), gp_Pnt(P8[0], P8[1], P8[2])).Edge() E18 = BRepBuilderAPI_MakeEdge(gp_Pnt(P8[0], P8[1], P8[2]), gp_Pnt(P9[0], P9[1], P9[2])).Edge() E19 = BRepBuilderAPI_MakeEdge(gp_Pnt(P9[0], P9[1], P9[2]), gp_Pnt(P10[0], P10[1], P10[2])).Edge() E20 = BRepBuilderAPI_MakeEdge(gp_Pnt(P10[0], P10[1], P10[2]), gp_Pnt(P11[0], P11[1], P11[2])).Edge() E21 = BRepBuilderAPI_MakeEdge(gp_Pnt(P11[0], P11[1], P11[2]), gp_Pnt(P12[0], P12[1], P12[2])).Edge() E22 = BRepBuilderAPI_MakeEdge(gp_Pnt(P12[0], P12[1], P12[2]), gp_Pnt(P13[0], P13[1], P13[2])).Edge() E23 = BRepBuilderAPI_MakeEdge(gp_Pnt(P13[0], P13[1], P13[2]), gp_Pnt(P14[0], P14[1], P14[2])).Edge() E24 = BRepBuilderAPI_MakeEdge(gp_Pnt(P14[0], P14[1], P14[2]), gp_Pnt(P1[0], P1[1], P1[2])).Edge() new_charme = ChFi2d_ChamferAPI() new_charme.Init(E11, E12) new_charme.Perform() E25 = new_charme.Result(E11, E12, self.BK_serise_dict[ss]["C1"], self.BK_serise_dict[ss]["C1"]) #倒角1 new_charme.Init(E13, E14) new_charme.Perform() E26 = new_charme.Result(E13, E14, self.BK_serise_dict[ss]["C2"], self.BK_serise_dict[ss]["C2"]) #倒角2 new_charme.Init(E15, E16) new_charme.Perform() E27 = new_charme.Result(E15, E16, self.BK_serise_dict[ss]["C3"], self.BK_serise_dict[ss]["C3"]) #倒角3 new_charme.Init(E16, E17) new_charme.Perform() E28 = new_charme.Result(E16, E17, self.BK_serise_dict[ss]["C3"], self.BK_serise_dict[ss]["C3"]) # 倒角4 new_charme.Init(E22, E23) new_charme.Perform() E29 = new_charme.Result(E22, E23, self.BK_serise_dict[ss]["C1"], self.BK_serise_dict[ss]["C1"]) # 倒角5 #print(type(E11)) #print(E29.IsNull()) W1 = BRepBuilderAPI_MakeWire(E11, E25, E12).Wire() W2 = BRepBuilderAPI_MakeWire(E13, E26, E14).Wire() W3 = BRepBuilderAPI_MakeWire(E15, E27, E16).Wire() W4 = BRepBuilderAPI_MakeWire(E16, E28, E17).Wire() W5 = BRepBuilderAPI_MakeWire(E18, E19, E20, E21).Wire() W6 = BRepBuilderAPI_MakeWire(E22, E29, E23, E24).Wire() #print("succeed") mkWire = BRepBuilderAPI_MakeWire() mkWire.Add(W1) mkWire.Add(W2) mkWire.Add(W3) mkWire.Add(W4) mkWire.Add(W5) mkWire.Add(W6) Rob = BRepPrimAPI_MakeRevol( BRepBuilderAPI_MakeFace(mkWire.Wire()).Face(), gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1))).Shape() #倒角----------------------------- #MF=BRepFilletAPI_MakeChamfer(Rob) #MF.Add() #移动 ls_filename = filename[0:8] + "_4" move_distance = 0.5 * L - ( L - float(self.SFU_serise_dict[ls_filename]["L"])) / 2 cone = TopoDS_Shape(Rob) T = gp_Trsf() T.SetTranslation(gp_Vec(0, 0, -move_distance)) loc = TopLoc_Location(T) cone.Location(loc) self.new_build.Add(self.aCompound, cone) print(type(self.aCompound)) return self.aCompound except: return False