def AddVerticesToScene(self, pnt_list, vertex_color, vertex_width=5): """ shp is a list of gp_Pnt """ vertices_list = [] # will be passed to pythreejs BB = BRep_Builder() compound = TopoDS_Compound() BB.MakeCompound(compound) for vertex in pnt_list: vertex_to_add = BRepBuilderAPI_MakeVertex(vertex).Shape() BB.Add(compound, vertex_to_add) vertices_list.append([vertex.X(), vertex.Y(), vertex.Z()]) # map the Points and the AIS_PointCloud # and to the dict of shapes, to have a mapping between meshes and shapes point_cloud_id = "%s" % uuid.uuid4().hex self._shapes[point_cloud_id] = compound vertices_list = np.array(vertices_list, dtype=np.float32) attributes = { "position": BufferAttribute(vertices_list, normalized=False) } mat = PointsMaterial(color=vertex_color, sizeAttenuation=True, size=vertex_width) geom = BufferGeometry(attributes=attributes) points = Points(geometry=geom, material=mat, name=point_cloud_id) return points
def create_compound(nodes): aRes = TopoDS_Compound() aBuilder = BRep_Builder() aBuilder.MakeCompound(aRes) for n in nodes: aBuilder.Add(aRes, n.solid()) return aRes
def compas_quadmesh_to_occ_shell(mesh: Mesh) -> TopoDS_Shell: """Convert a COMPAS quad mesh to an OCC shell. Parameters ---------- mesh : :class:`~compas.datastructures.Mesh` A COMPAS mesh data structure with quad faces. Returns ------- TopoDS_Shell Raises ------ AssertionError If the input mesh is not a quad mesh. """ assert mesh.is_quadmesh(), "The input mesh is not a quad mesh." shell = TopoDS_Shell() builder = BRep_Builder() builder.MakeShell(shell) for face in mesh.faces(): points = mesh.face_coordinates(face) builder.Add(shell, quad_to_face(points)) return shell
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 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 write_target_edges(self,filename): comp = TopoDS_Compound() builder = BRep_Builder() builder.MakeCompound(comp) for shape in self.target_edges: builder.Add(comp, shape) breptools_Write(comp,filename)
def test_rule_motion_00(self): gcode = "G21 G94\n" gcode += "G54\n" gcode += "M6 T1 G43 H1\n" motions = [] for i in range(3): builder = BRep_Builder() shape = TopoDS_Shape() assert breptools_Read(shape, './input/tip_{}.brep'.format(i + 1), builder) tip_edge = OCCUtils.Topo(shape).edges().__next__() print(OCCUtils.Topo(shape).number_of_edges()) builder = BRep_Builder() shape = TopoDS_Shape() assert breptools_Read(shape, './input/shank_{}.brep'.format(i + 1), builder) shank_edge = OCCUtils.Topo(shape).edges().__next__() print(OCCUtils.Topo(shape).number_of_edges(), '\n') rm = HackerCAD.RuledMotion(tip_edge, shank_edge) motions.append(rm) pp = HackerCAD.PostProcessor() gcode += pp.process(motions) gcode += "M2\n" f = open("./output/bla.ngc", "w") f.write(gcode) f.close()
def __init__(self, faces): topods_shell = TopoDS_Shell() builder = BRep_Builder() builder.MakeShell(topods_shell) for face in faces: builder.Add(topods_shell, face.object) self._shell = Shell(topods_shell)
def main(): vertices = [gp_Pnt(p[0], p[1], p[2]) for p in mesh['vertices']] oFaces = [] builder = BRep_Builder() shell = TopoDS_Shell() builder.MakeShell(shell) for face in mesh['faces']: edges = [] face.reverse() for i in range(len(face)): cur = face[i] nxt = face[(i + 1) % len(face)] segment = GC_MakeSegment(vertices[cur], vertices[nxt]) edges.append(BRepBuilderAPI_MakeEdge(segment.Value())) wire = BRepBuilderAPI_MakeWire() for edge in edges: wire.Add(edge.Edge()) oFace = BRepBuilderAPI_MakeFace(wire.Wire()) builder.Add(shell, oFace.Shape()) write_stl_file(shell, "./cube_binding.stl")
def export_file(self): builder = BRep_Builder() compound = TopoDS_Compound() builder.MakeCompound(compound) builder.Add(compound, self.b1) builder.Add(compound, self.b2) builder.Add(compound, make_polygon(self.pts)) self.export_stp(compound)
def make_comp_selcted(self): bild = BRep_Builder() comp = TopoDS_Compound() bild.MakeCompound(comp) for shp in self.selected_shape: print(shp) bild.Add(comp, shp) return comp
def export_file(self): builder = BRep_Builder() compound = TopoDS_Compound() builder.MakeCompound(compound) builder.Add(compound, self.b1) builder.Add(compound, self.b2) builder.Add(compound, make_polygon(self.pts)) write_step_file(compound, "./tmp/test.stp")
def __init__(self, shapes): topods_compound = TopoDS_Compound() builder = BRep_Builder() builder.MakeCompound(topods_compound) for shape in shapes: shape = Shape.to_shape(shape) if isinstance(shape, Shape): builder.Add(topods_compound, shape.object) self._cp = Compound(topods_compound)
class GenCompound(object): def __init__(self): self.builder = BRep_Builder() self.compound = TopoDS_Compound() self.builder.MakeCompound(self.compound) def add_shapes(self, shps=[]): for shp in shps: self.builder.Add(self.compound, shp)
def export_stp_selected(self): if self.touch == True: builder = BRep_Builder() compound = TopoDS_Compound() builder.MakeCompound(compound) for shp in self.selected_shape: print(shp) builder.Add(compound, shp) self.export_stp(compound)
def compound(self): """ Create and returns a compound from the _shapes list""" # Create a compound compound = TopoDS_Compound() brep_builder = BRep_Builder() brep_builder.MakeCompound(compound) # Populate the compound for shape in self._shapes: brep_builder.Add(compound, shape) return compound
def __init__(self,name,wire=False) : from OCC.Core.BRep import BRep_Builder from OCC.Core.TopoDS import TopoDS_Compound self.Name = name self.Wire = wire self.Objects = [] self.SubVols = [] #Combined shape of objects self.Compound = TopoDS_Compound() self.Builder = BRep_Builder() self.Builder.MakeCompound(self.Compound)
def read_iges_file(filename, return_as_shapes=False, verbosity=False, visible_only=False): """ read the IGES file and returns a compound filename: the file path return_as_shapes: optional, False by default. If True returns a list of shapes, else returns a single compound verbosity: optionl, False by default. """ if not os.path.isfile(filename): raise FileNotFoundError("%s not found." % filename) iges_reader = IGESControl_Reader() iges_reader.SetReadVisible(visible_only) status = iges_reader.ReadFile(filename) _shapes = [] if status == IFSelect_RetDone: # check status if verbosity: failsonly = False iges_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) iges_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) iges_reader.TransferRoots() nbr = iges_reader.NbRootsForTransfer() for n in range(1, nbr + 1): nbs = iges_reader.NbShapes() if nbs == 0: print("At least one shape in IGES cannot be transfered") elif nbr == 1 and nbs == 1: a_res_shape = iges_reader.Shape(1) if a_res_shape.IsNull(): print("At least one shape in IGES cannot be transferred") else: _shapes.append(a_res_shape) else: for i in range(1, nbs + 1): a_shape = iges_reader.Shape(i) if a_shape.IsNull(): print( "At least one shape in STEP cannot be transferred") else: _shapes.append(a_shape) # if not return as shapes # create a compound and store all shapes if not return_as_shapes: builder = BRep_Builder() compound = TopoDS_Compound() builder.MakeCompound(compound) for s in _shapes: builder.Add(compound, s) _shapes = compound return _shapes
def to_shell(self): """ Create a shell from the face. :return: The shell. :rtype: afem.topology.entities.Shell """ topods_shell = TopoDS_Shell() builder = BRep_Builder() builder.MakeShell(topods_shell) builder.Add(topods_shell, self.object) return Shell(topods_shell)
def __init__(self): plotocc.__init__(self) self.compound = TopoDS_Compound() self.builder = BRep_Builder() self.builder.MakeCompound(self.compound) mmat = math_Matrix(1, 4, 1, 3, 0.0) mmat.SetDiag(1.0) print(mmat.Determinant()) print(mmat.DumpToString()) mvec = math_Vector(1, 3) print(mvec.Norm()) print(mvec.DumpToString())
def move_to_box(iname, cname, wname, visualize=False): """Move foam to periodic box. Works on BREP files. Information about physical volumes is lost. Args: iname (str): input filename cname (str): output filename with cells wname (str): output filename with walls visualize (bool): show picture of foam morphology in box if True """ cells = TopoDS_Shape() builder = BRep_Builder() breptools_Read(cells, iname, builder) texp = TopologyExplorer(cells) solids = list(texp.solids()) cells = TopoDS_Compound() builder.MakeCompound(cells) box = BRepPrimAPI_MakeBox(gp_Pnt(1, -1, -1), 3, 3, 3).Shape() vec = gp_Vec(-1, 0, 0) solids = slice_and_move(solids, box, vec) box = BRepPrimAPI_MakeBox(gp_Pnt(-3, -1, -1), 3, 3, 3).Shape() vec = gp_Vec(1, 0, 0) solids = slice_and_move(solids, box, vec) box = BRepPrimAPI_MakeBox(gp_Pnt(-1, 1, -1), 3, 3, 3).Shape() vec = gp_Vec(0, -1, 0) solids = slice_and_move(solids, box, vec) box = BRepPrimAPI_MakeBox(gp_Pnt(-1, -3, -1), 3, 3, 3).Shape() vec = gp_Vec(0, 1, 0) solids = slice_and_move(solids, box, vec) box = BRepPrimAPI_MakeBox(gp_Pnt(-1, -1, 1), 3, 3, 3).Shape() vec = gp_Vec(0, 0, -1) solids = slice_and_move(solids, box, vec) box = BRepPrimAPI_MakeBox(gp_Pnt(-1, -1, -3), 3, 3, 3).Shape() vec = gp_Vec(0, 0, 1) solids = slice_and_move(solids, box, vec) create_compound(solids, cells, builder) breptools_Write(cells, cname) if visualize: display, start_display, _, _ = init_display() display.DisplayShape(cells, update=True) start_display() box = BRepPrimAPI_MakeBox(gp_Pnt(0, 0, 0), 1, 1, 1).Shape() walls = BRepAlgoAPI_Cut(box, cells).Shape() breptools_Write(walls, wname) if visualize: display, start_display, _, _ = init_display() display.DisplayShape(walls, update=True) start_display()
def by_face(face): """ Create a shell from a face. :param afem.topology.entities.Face face: The face. :return: The shell. :rtype: afem.topology.entities.Shell """ topods_shell = TopoDS_Shell() builder = BRep_Builder() builder.MakeShell(topods_shell) builder.Add(topods_shell, face.object) return Shell(topods_shell)
def make_compound(parts): """ Takes a list of parts and returns a TopoDS_Compound from the parts' shapes. :param parts: A list of Part instances :return: a TopoDS_Compound from all of the parts' shapes """ compound = TopoDS_Compound() builder = BRep_Builder() builder.MakeCompound(compound) for part in parts: builder.Add(compound, part._shape) return compound
def __init__(self): super().__init__() self.builder = BRep_Builder() self.compound = TopoDS_Compound() self.builder.MakeCompound(self.compound) schema = 'AP203' assembly_mode = 1 self.writer = STEPControl_Writer() self.fp = self.writer.WS().TransferWriter().FinderProcess() Interface_Static_SetCVal('write.step.schema', schema) Interface_Static_SetCVal('write.step.unit', 'M') Interface_Static_SetCVal('write.step.assembly', str(assembly_mode))
def read_step_file(filename, return_as_shapes=False, verbosity=True): """ read the STEP file and returns a compound filename: the file path return_as_shapes: optional, False by default. If True returns a list of shapes, else returns a single compound verbosity: optional, False by default. """ if not os.path.isfile(filename): raise FileNotFoundError("%s not found." % filename) step_reader = STEPControl_Reader() status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: # check status if verbosity: failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) shapes_to_return = [] for root_num in range(1, step_reader.NbRootsForTransfer() + 1): transfer_result = step_reader.TransferRoot(root_num) if not transfer_result: raise AssertionError("Transfer failed.") shape = step_reader.Shape(root_num) if shape.IsNull(): raise AssertionError("Shape is null.") shapes_to_return.append(shape) if return_as_shapes: return shapes_to_return builder = BRep_Builder() compound_shape = TopoDS_Compound() builder.MakeCompound(compound_shape) for shape in shapes_to_return: builder.Add(compound_shape, shape) return compound_shape else: raise AssertionError("Error: can't read file.")
def test_adaptive(self): gcode = "G21 G94\n" gcode += "G54\n" gcode += "M6 T1 G43 H1\n" hex_flats = TopoDS_Shape() builder = BRep_Builder() assert breptools_Read(hex_flats, './inputs/hex_flats.brep', builder) t = OCCUtils.Topo(hex_flats) num_faces = 0 for face_i in t.faces(): print("face") a2d = HackerCAD.Adaptive2d(face_i) a2d.tool_diameter = 25.4 / 32.0 a2d.helix_diameter = a2d.tool_diameter * 0.35 a2d.depth = 5.0 a2d.helix_angle = 0.5 a2d.flip_ax_dir() wire = a2d.compute() breptools_Write(wire, "output/hex_flat_{}.brep".format(num_faces)) num_faces += 1 pp = HackerCAD.PostProcessor() gcode += pp.process(a2d.motions) gcode += "M2\n" f = open("./output/bla.ngc", "w") f.write(gcode) f.close()
def read_cadfile(self, fileName, disp=True): print(fileName) base_dir = os.path.dirname(fileName) basename = os.path.basename(fileName) rootname, extname = os.path.splitext(fileName) if extname in [".stp", ".step"]: shpe = read_step_file(fileName) elif extname in [".igs", ".iges"]: shpe = read_iges_file(fileName) elif extname in [".stl"]: shpe = read_stl_file(fileName) elif extname in [".brep"]: shpe = TopoDS_Shape() builder = BRep_Builder() breptools_Read(shpe, fileName, builder) elif extname in [".geo"]: stlfile = self.import_geofile(fileName, 0.1) shpe = read_stl_file(stlfile) else: print("Incorrect file index") # sys.exit(0) if disp == True: self.display.DisplayShape(shpe, update=True) return shpe
def test_default_constructor_DEFINE_STANDARD_ALLOC(self): ''' OCE classes the defines standard alllocator can be instanciated if they're not abstract nor define any protected or private constructor ''' BRep_Builder() TopoDS_Builder() ShapeAnalysis_Curve()
class Model (plotocc): def __init__(self): super().__init__() self.builder = BRep_Builder() self.compound = TopoDS_Compound() self.builder.MakeCompound(self.compound) schema = 'AP203' assembly_mode = 1 self.writer = STEPControl_Writer() self.fp = self.writer.WS().TransferWriter().FinderProcess() Interface_Static_SetCVal('write.step.schema', schema) Interface_Static_SetCVal('write.step.unit', 'M') Interface_Static_SetCVal('write.step.assembly', str(assembly_mode)) def AddShape(self, shp, name="shape"): Interface_Static_SetCVal('write.step.product.name', name) status = self.writer.Transfer(shp, STEPControl_AsIs) if int(status) > int(IFSelect_RetError): raise Exception('Some Error occurred') # This portion is not working as I hoped item = stepconstruct_FindEntity(self.fp, shp) if not item: raise Exception('Item not found') def export_stp_with_name(self): status = self.writer.Write(self.tempname + ".stp") if int(status) > int(IFSelect_RetError): raise Exception('Something bad happened')
def list_of_shapes_to_compound(list_of_shapes): """ takes a list of shape in input, gather all shapes into one compound returns the compund and a boolean, True if all shapes were added to the compund, False otherwise """ all_shapes_converted = True the_compound = TopoDS_Compound() the_builder = BRep_Builder() the_builder.MakeCompound(the_compound) for shp in list_of_shapes: # first ensure the shape is not Null if shp.IsNull(): all_shapes_converted = False continue else: the_builder.Add(the_compound, shp) return the_compound, all_shapes_converted