def _create_from_svg(cls, filepath, height_mm): assert isinstance(filepath, pathlib.Path) if not filepath.is_file(): raise IOError( "Unable to create Face from image file: {}. File does not exist" .format(filepath)) # Load as a document rather than as paths directly (using svg2paths) because # the document respects any transforms doc = Document(str(filepath)) paths = doc.paths() continuous_paths = cls._get_continuous_subpaths(paths) continuous_paths = cls._remove_zero_length_lines(continuous_paths) ymin = min([path.bbox()[2] for path in continuous_paths]) ymax = max([path.bbox()[3] for path in continuous_paths]) current_height = ymax - ymin assert current_height >= 0 scaling_factor = height_mm / current_height scaled_paths = [ path.scaled(scaling_factor, -scaling_factor) for path in continuous_paths ] # Line up to the x and y axes xmin = min([path.bbox()[0] for path in scaled_paths]) ymin = min([path.bbox()[2] for path in scaled_paths]) translated_paths = [ path.translated(complex(-xmin, -ymin)) for path in scaled_paths ] normalized_paths = cls._normalize_paths_clockwise(translated_paths) path_hierarchies = cls._create_path_hierarchy(normalized_paths) # Currently only really support a single main contiguous shape with holes. # Although multiple disconnected shapes can be generated, they won't be # perfectly represented by the final geometry because some material has to # connect them assert len(path_hierarchies) == 1 faceMaker = BRepBuilderAPI_MakeFace(PL_XZ) for path_hierarchy in path_hierarchies: root_edges = cls._create_edges_from_path( path_hierarchy.root_path()) root_wire = cls._create_wire_from_edges(root_edges) faceMaker.Add(root_wire) for sub_path in path_hierarchy.child_paths(): sub_path_edges = cls._create_edges_from_path(sub_path) sub_path_wire = cls._create_wire_from_edges(sub_path_edges) # reverse the wire so it creates a hole sub_path_wire.Reverse() faceMaker.Add(sub_path_wire) return faceMaker.Shape()
def brep_feat_local_revolution(event=None): S = BRepPrimAPI_MakeBox(400., 250., 300.).Shape() faces = list(TopologyExplorer(S).faces()) F1 = faces[2] surf = BRep_Tool_Surface(F1) D = gp_OX() MW1 = BRepBuilderAPI_MakeWire() p1 = gp_Pnt2d(100., 100.) p2 = gp_Pnt2d(200., 100.) aline = GCE2d_MakeLine(p1, p2).Value() MW1.Add(BRepBuilderAPI_MakeEdge(aline, surf, 0., p1.Distance(p2)).Edge()) p1 = gp_Pnt2d(200., 100.) p2 = gp_Pnt2d(150., 200.) aline = GCE2d_MakeLine(p1, p2).Value() MW1.Add(BRepBuilderAPI_MakeEdge(aline, surf, 0., p1.Distance(p2)).Edge()) p1 = gp_Pnt2d(150., 200.) p2 = gp_Pnt2d(100., 100.) aline = GCE2d_MakeLine(p1, p2).Value() MW1.Add(BRepBuilderAPI_MakeEdge(aline, surf, 0., p1.Distance(p2)).Edge()) MKF1 = BRepBuilderAPI_MakeFace() MKF1.Init(surf, False, 1e-6) MKF1.Add(MW1.Wire()) FP = MKF1.Face() breplib_BuildCurves3d(FP) MKrev = BRepFeat_MakeRevol(S, FP, F1, D, 1, True) F2 = faces[4] MKrev.Perform(F2) display.EraseAll() display.DisplayShape(MKrev.Shape()) display.FitAll()
def extrusion(event=None): # Make a box Box = BRepPrimAPI_MakeBox(400., 250., 300.) S = Box.Shape() # Choose the first Face of the box F = next(TopologyExplorer(S).faces()) surf = BRep_Tool_Surface(F) # Make a plane from this face Pl = Handle_Geom_Plane_DownCast(surf) Pln = Pl.GetObject() # Get the normal of this plane. This will be the direction of extrusion. D = Pln.Axis().Direction() # Inverse normal D.Reverse() # Create the 2D planar sketch MW = BRepBuilderAPI_MakeWire() p1 = gp_Pnt2d(200., -100.) p2 = gp_Pnt2d(100., -100.) aline = GCE2d_MakeLine(p1, p2).Value() Edge1 = BRepBuilderAPI_MakeEdge(aline, surf, 0., p1.Distance(p2)) MW.Add(Edge1.Edge()) p1 = p2 p2 = gp_Pnt2d(100., -200.) aline = GCE2d_MakeLine(p1, p2).Value() Edge2 = BRepBuilderAPI_MakeEdge(aline, surf, 0., p1.Distance(p2)) MW.Add(Edge2.Edge()) p1 = p2 p2 = gp_Pnt2d(200., -200.) aline = GCE2d_MakeLine(p1, p2).Value() Edge3 = BRepBuilderAPI_MakeEdge(aline, surf, 0., p1.Distance(p2)) MW.Add(Edge3.Edge()) p1 = p2 p2 = gp_Pnt2d(200., -100.) aline = GCE2d_MakeLine(p1, p2).Value() Edge4 = BRepBuilderAPI_MakeEdge(aline, surf, 0., p1.Distance(p2)) MW.Add(Edge4.Edge()) # Build Face from Wire. NB: a face is required to generate a solid. MKF = BRepBuilderAPI_MakeFace() MKF.Init(surf, False, 1e-6) MKF.Add(MW.Wire()) FP = MKF.Face() breplib_BuildCurves3d(FP) MKP = BRepFeat_MakePrism(S, FP, F, D, False, True) MKP.Perform(200.) # TODO MKP completes, seeing a split operation but no extrusion assert MKP.IsDone() res1 = MKP.Shape() display.EraseAll() display.DisplayColoredShape(res1, 'BLUE') display.FitAll()
def holes_in_face(): aPlane = gp_Pln() print(type(gp_Pln())) print(type(gp_XOY())) aCircle1 = gp_Circ(gp_XOY(), 1.0) aCircle2 = gp_Circ(gp_XOY(), 1.0) aCircle3 = gp_Circ(gp_XOY(), 1.0) aCircle1.SetLocation(gp_Pnt(3.0, 3.0, 0.0)) aCircle2.SetLocation(gp_Pnt(7.0, 3.0, 0.0)) aCircle3.SetLocation(gp_Pnt(3.0, 7.0, 0.0)) anEdgeMaker1 = BRepBuilderAPI_MakeEdge(aCircle1) anEdgeMaker2 = BRepBuilderAPI_MakeEdge(aCircle2) anEdgeMaker3 = BRepBuilderAPI_MakeEdge(aCircle3) aWireMaker1 = BRepBuilderAPI_MakeWire(anEdgeMaker1.Edge()) aWireMaker2 = BRepBuilderAPI_MakeWire(anEdgeMaker2.Edge()) aWireMaker3 = BRepBuilderAPI_MakeWire(anEdgeMaker3.Edge()) aFaceMaker = BRepBuilderAPI_MakeFace(aPlane, 0.0, 10.0, 0.0, 10.0) if aWireMaker1.IsDone(): aWire1 = aWireMaker1.Wire() aWire1.Reverse() # Makes this a hole in outer profile aFaceMaker.Add(aWire1) if aWireMaker2.IsDone(): aWire2 = aWireMaker2.Wire() aWire2.Reverse() # Makes this a hole in outer profile aFaceMaker.Add(aWire2) if aWireMaker3.IsDone(): aWire3 = aWireMaker3.Wire() aWire3.Reverse() # Makes this a hole in outer profile aFaceMaker.Add(aWire3) if not aFaceMaker.IsDone(): raise AssertionError("shape not Done.") return aFaceMaker.Shape()
def add_wire_to_face(face, wire, reverse=False): ''' apply a wire to a face use reverse to set the orientation of the wire to opposite @param face: @param wire: @param reverse: ''' face = BRepBuilderAPI_MakeFace(face) if reverse: wire.Reverse() face.Add(wire) result = face.Face() face.Delete() return result
def make_PolyPlane(self, num=6, radi=1.0, shft=0.0, axs=gp_Ax3()): lxy = radi - 0.1 pnts = [] angl = 360 / num for i in range(num): thet = np.deg2rad(i * angl) + np.deg2rad(shft) x, y = radi * np.sin(thet), radi * np.cos(thet) pnts.append(gp_Pnt(x, y, 0)) pnts.append(pnts[0]) poly = make_polygon(pnts) brep = BRepBuilderAPI_MakeFace(gp_Pln(), poly) brep.Add(poly) face = brep.Face() face.Location(set_loc(gp_Ax3(), axs)) return face
def _fill(wires): if not isinstance(wires, (list, tuple)): return Shape(BRepBuilderAPI_MakeFace(wires.Wire_orEdgeToWire()).Face()) algo = BRepBuilderAPI_MakeFace(wires[0].Wire_orEdgeToWire()) for i in range(1, len(wires)): algo.Add(wires[i].Wire_orEdgeToWire()) algo.Build() fixer = ShapeFix_Face(algo.Face()) fixer.Perform() fixer.FixOrientation() return Shape(fixer.Face())
def brepfeat_prism(event=None): box = BRepPrimAPI_MakeBox(400, 250, 300).Shape() faces = TopologyExplorer(box).faces() for i in range(5): face = next(faces) srf = BRep_Tool_Surface(face) c = gp_Circ2d(gp_Ax2d(gp_Pnt2d(200, 130), gp_Dir2d(1, 0)), 75) circle = Geom2d_Circle(c) wire = BRepBuilderAPI_MakeWire() wire.Add(BRepBuilderAPI_MakeEdge(circle, srf, 0., pi).Edge()) wire.Add(BRepBuilderAPI_MakeEdge(circle, srf, pi, 2. * pi).Edge()) wire.Build() display.DisplayShape(wire.Wire()) mkf = BRepBuilderAPI_MakeFace() mkf.Init(srf, False, 1e-6) mkf.Add(wire.Wire()) mkf.Build() new_face = mkf.Face() breplib_BuildCurves3d(new_face) display.DisplayShape(new_face) prism = BRepFeat_MakeDPrism(box, mkf.Face(), face, 100, True, True) prism.Perform(400) assert prism.IsDone() display.EraseAll() display.DisplayShape(prism.Shape()) display.DisplayColoredShape(wire.Wire(), 'RED') display.FitAll()
def brep_feat_extrusion_protrusion(event=None): # Extrusion S = BRepPrimAPI_MakeBox(400., 250., 300.).Shape() faces = TopologyExplorer(S).faces() F = next(faces) surf1 = BRep_Tool_Surface(F) Pl1 = Geom_Plane.DownCast(surf1) D1 = Pl1.Pln().Axis().Direction().Reversed() MW = BRepBuilderAPI_MakeWire() p1, p2 = gp_Pnt2d(200., -100.), gp_Pnt2d(100., -100.) aline = GCE2d_MakeLine(p1, p2).Value() MW.Add(BRepBuilderAPI_MakeEdge(aline, surf1, 0., p1.Distance(p2)).Edge()) p1, p2 = gp_Pnt2d(100., -100.), gp_Pnt2d(100., -200.) aline = GCE2d_MakeLine(p1, p2).Value() MW.Add(BRepBuilderAPI_MakeEdge(aline, surf1, 0., p1.Distance(p2)).Edge()) p1, p2 = gp_Pnt2d(100., -200.), gp_Pnt2d(200., -200.) aline = GCE2d_MakeLine(p1, p2).Value() MW.Add(BRepBuilderAPI_MakeEdge(aline, surf1, 0., p1.Distance(p2)).Edge()) p1, p2 = gp_Pnt2d(200., -200.), gp_Pnt2d(200., -100.) aline = GCE2d_MakeLine(p1, p2).Value() MW.Add(BRepBuilderAPI_MakeEdge(aline, surf1, 0., p1.Distance(p2)).Edge()) MKF = BRepBuilderAPI_MakeFace() MKF.Init(surf1, False, 1e-6) MKF.Add(MW.Wire()) FP = MKF.Face() breplib_BuildCurves3d(FP) display.EraseAll() MKP = BRepFeat_MakePrism(S, FP, F, D1, 0, True) MKP.PerformThruAll() res1 = MKP.Shape() display.DisplayShape(res1) # Protrusion next(faces) F2 = next(faces) surf2 = BRep_Tool_Surface(F2) Pl2 = Geom_Plane.DownCast(surf2) D2 = Pl2.Pln().Axis().Direction().Reversed() MW2 = BRepBuilderAPI_MakeWire() p1, p2 = gp_Pnt2d(100., 100.), gp_Pnt2d(200., 100.) aline = GCE2d_MakeLine(p1, p2).Value() MW2.Add(BRepBuilderAPI_MakeEdge(aline, surf2, 0., p1.Distance(p2)).Edge()) p1, p2 = gp_Pnt2d(200., 100.), gp_Pnt2d(150., 200.) aline = GCE2d_MakeLine(p1, p2).Value() MW2.Add(BRepBuilderAPI_MakeEdge(aline, surf2, 0., p1.Distance(p2)).Edge()) p1, p2 = gp_Pnt2d(150., 200.), gp_Pnt2d(100., 100.) aline = GCE2d_MakeLine(p1, p2).Value() MW2.Add(BRepBuilderAPI_MakeEdge(aline, surf2, 0., p1.Distance(p2)).Edge()) MKF2 = BRepBuilderAPI_MakeFace() MKF2.Init(surf2, False, 1e-6) MKF2.Add(MW2.Wire()) MKF2.Build() FP = MKF2.Face() breplib_BuildCurves3d(FP) MKP2 = BRepFeat_MakePrism(res1, FP, F2, D2, 0, True) MKP2.PerformThruAll() display.EraseAll() trf = gp_Trsf() trf.SetTranslation(gp_Vec(0, 0, 300)) gtrf = gp_GTrsf() gtrf.SetTrsf(trf) tr = BRepBuilderAPI_GTransform(MKP2.Shape(), gtrf, True) fused = BRepAlgoAPI_Fuse(tr.Shape(), MKP2.Shape()) fused.Build() display.DisplayShape(fused.Shape()) display.FitAll()
poly_1 = obj.make_PolyWire(num=6, axs=axis_1) proj = BRepProj_Projection(poly_1, face, axis.Direction()) bound_poly_1 = proj.Current() axis_2 = axis.Transformed(trsf) axis_2.Translate(gp_Pnt(0, 0, 0), gp_Pnt(0, 2, 0)) poly_2 = obj.make_PolyWire(num=10, axs=axis_2) proj = BRepProj_Projection(poly_2, face, axis.Direction()) bound_poly_2 = proj.Current() proj = BRepProj_Projection(poly_0, face, axis.Direction()) bound_poly = proj.Current() print(bound_poly) print(surf) api = BRepBuilderAPI_MakeFace(surf, 1.0) api.Add(bound_poly) bound_face = api.Face() print(api.IsDone()) #api = BRepBuilderAPI_MakeFace(bound_face, bound_poly_1) #bound_face = api.Face() print(face.Location().Transformation()) obj.display.DisplayShape(face, color="BLUE", transparency=0.9) obj.display.DisplayShape(bound_face, color="RED", transparency=0.9) obj.display.DisplayShape(poly_0) obj.display.DisplayShape(poly_1) obj.display.DisplayShape(poly_2) obj.display.DisplayShape(bound_poly_0) obj.display.DisplayShape(bound_poly_1) obj.display.DisplayShape(bound_poly_2) obj.display.DisplayShape(bound_poly)
obj = plotocc(view=False) face1 = read_step_file("./stp_surf/gen_surf_001.stp") axis1 = gp_Ax3(gp_Pnt(0, 0, 1), gp_Dir(0, 0, 1)) face1.Location(set_loc(gp_Ax3(), axis1)) face2 = read_step_file("./stp_surf/gen_surf_030.stp") axis2 = gp_Ax3(gp_Pnt(0, 0, 2), gp_Dir(0, 0, 1)) face2.Location(set_loc(gp_Ax3(), axis2)) axs = gp_Ax3() ax1 = gp_Ax3(gp_Pnt(0, 0, -10), axs.Direction()) vec = gp_Vec(gp_Pnt(0, 0, -10), gp_Pnt(0, 0, 10)) face = obj.make_EllipWire(rxy=[50.0, 50.0], axs=ax1, skin=0) body = BRepPrimAPI_MakePrism(face, vec).Shape() lens = make_lens(body, face1, face2) obj.create_tempdir(flag=-1) wire1 = obj.make_PolyWire(radi=50, num=6, axs=axis1) proj = BRepProj_Projection(wire1, face1, axis1.Direction()) proj_wire = proj.Current() top = Topo(face1) for faces in top.faces(): face1_1 = faces print(faces) api = BRepBuilderAPI_MakeFace(face1_1) api.Add(proj_wire) obj.export_stp(api.Face())
def __call__(self, obj, dst=None): """ This method performs the deformation on the CAD geometry. If `obj` is a TopoDS_Shape, the method returns a TopoDS_Shape containing the deformed geometry. If `obj` is a filename, the method deforms the geometry contained in the file and writes the deformed shape to `dst` (which has to be set). :param obj: the input geometry. :type obj: str or TopoDS_Shape :param str dst: if `obj` is a string containing the input filename, `dst` refers to the file where the deformed geometry is saved. """ # Manage input if isinstance(obj, str): # if a input filename is passed if dst is None: raise ValueError( 'Source file is provided, but no destination specified') shape = self.read_shape(obj) elif isinstance(obj, TopoDS_Shape): shape = obj # Maybe do we need to handle also Compound? else: raise TypeError #create compound to store modified faces compound_builder = BRep_Builder() compound = TopoDS_Compound() compound_builder.MakeCompound(compound) # cycle on the faces to get the control points # iterator to faces (TopoDS_Shape) contained in the shape faces_explorer = TopExp_Explorer(shape, TopAbs_FACE) while faces_explorer.More(): # performing some conversions to get the right # format (BSplineSurface) # TopoDS_Face obtained from iterator face = topods_Face(faces_explorer.Current()) # performing some conversions to get the right # format (BSplineSurface) bspline_surface = self._bspline_surface_from_face(face) # add the required amount of poles in u and v directions self._enrich_surface_knots(bspline_surface) # deform the Bspline surface through FFD self._deform_bspline_surface(bspline_surface) # through moving the control points, we now changed the SURFACE # underlying FACE we are processing. we now need to obtain the # curves (actually, the WIRES) that define the bounds of the # surface and TRIM the surface with them, to obtain the new FACE #we now start really looping on the wires #we will create a single curve joining all the edges in the wire # the curve must be a bspline curve so we need to make conversions # through all the way # list that will contain the (single) outer wire of the face outer_wires = [] # list that will contain all the inner wires (holes) of the face inner_wires = [] # iterator to loop over TopoDS_Wire in the original (undeformed) # face wire_explorer = TopExp_Explorer(face, TopAbs_WIRE) while wire_explorer.More(): # wire obtained from the iterator wire = topods_Wire(wire_explorer.Current()) # getting a bpline curve joining all the edges of the wire composite_curve = self._bspline_curve_from_wire(wire) # adding all the required knots to the Bspline curve self._enrich_curve_knots(composite_curve) # deforming the Bspline curve through FFD self._deform_bspline_curve(composite_curve) # the GeomCurve corresponding to the whole edge has now # been deformed. Now we must make it become an proper # wire # list of shapes (needed by the wire generator) shapes_list = TopTools_ListOfShape() # edge (to be converted to wire) obtained from the modified # Bspline curve modified_composite_edge = \ BRepBuilderAPI_MakeEdge(composite_curve).Edge() # modified edge is added to shapes_list shapes_list.Append(modified_composite_edge) # wire builder wire_maker = BRepBuilderAPI_MakeWire() wire_maker.Add(shapes_list) # deformed wire is finally obtained modified_wire = wire_maker.Wire() # now, the wire can be outer or inner. we store the outer # and (possible) inner ones in different lists # this is because we first need to trim the surface # using the outer wire, and then we can trim it # with the wires corresponding to all the holes. # the wire order is important, in the trimming process if wire == breptools_OuterWire(face): outer_wires.append(modified_wire) else: inner_wires.append(modified_wire) wire_explorer.Next() # so once we finished looping on all the wires to modify them, # we first use the only outer one to trim the surface # face builder object face_maker = BRepBuilderAPI_MakeFace(bspline_surface, outer_wires[0]) # and then add all other inner wires for the holes for inner_wire in inner_wires: face_maker.Add(inner_wire) # finally, we get our trimmed face with all its holes trimmed_modified_face = face_maker.Face() # trimmed_modified_face is added to the modified faces compound compound_builder.Add(compound, trimmed_modified_face) # and move to the next face faces_explorer.Next() ## END SURFACES ################################################# if isinstance(dst, str): # if a input filename is passed # save the shape exactly to the filename, aka `dst` self.write_shape(dst, compound) else: return compound
def write_face(self, points_face, list_points_edge, topo_face, toledge): """ Method to recreate a Face associated to a geometric surface after the modification of Face points. It returns a TopoDS_Face. :param points_face: the new face points array. :param list_points_edge: new edge points :param topo_face: the face to be modified :param toledge: tolerance on the surface creation after modification :return: TopoDS_Face (Shape) :rtype: TopoDS_Shape """ # convert Face to Geom B-spline Surface nurbs_converter = BRepBuilderAPI_NurbsConvert(topo_face) nurbs_converter.Perform(topo_face) nurbs_face = nurbs_converter.Shape() topo_nurbsface = topods.Face(nurbs_face) h_geomsurface = BRep_Tool.Surface(topo_nurbsface) h_bsurface = geomconvert_SurfaceToBSplineSurface(h_geomsurface) bsurface = h_bsurface nb_u = bsurface.NbUPoles() nb_v = bsurface.NbVPoles() # check consistency if points_face.shape[0] != nb_u * nb_v: raise ValueError("Input control points do not have not have the " "same number as the geometric face!") # cycle on the face points indice_cpt = 0 for iu in range(1, nb_u + 1): for iv in range(1, nb_v + 1): cpt = points_face[indice_cpt] bsurface.SetPole(iu, iv, gp_Pnt(cpt[0], cpt[1], cpt[2])) indice_cpt += 1 # create modified new face new_bspline_tface = BRepBuilderAPI_MakeFace() toler = precision_Confusion() new_bspline_tface.Init(bsurface, False, toler) # cycle on the wires face_wires_explorer = TopExp_Explorer( topo_nurbsface.Oriented(TopAbs_FORWARD), TopAbs_WIRE) ind_edge_total = 0 while face_wires_explorer.More(): # get old wire twire = topods_Wire(face_wires_explorer.Current()) # cycle on the edges ind_edge = 0 wire_explorer_edge = TopExp_Explorer( twire.Oriented(TopAbs_FORWARD), TopAbs_EDGE) # check edges order on the wire mode3d = True tolerance_edges = toledge wire_order = ShapeAnalysis_WireOrder(mode3d, tolerance_edges) # an edge list deformed_edges = [] # cycle on the edges while wire_explorer_edge.More(): tedge = topods_Edge(wire_explorer_edge.Current()) new_bspline_tedge = self.write_edge( list_points_edge[ind_edge_total], tedge) deformed_edges.append(new_bspline_tedge) analyzer = topexp() vfirst = analyzer.FirstVertex(new_bspline_tedge) vlast = analyzer.LastVertex(new_bspline_tedge) pt1 = BRep_Tool.Pnt(vfirst) pt2 = BRep_Tool.Pnt(vlast) wire_order.Add(pt1.XYZ(), pt2.XYZ()) ind_edge += 1 ind_edge_total += 1 wire_explorer_edge.Next() # grouping the edges in a wire, then in the face # check edges order and connectivity within the wire wire_order.Perform() # new wire to be created stol = ShapeFix_ShapeTolerance() new_bspline_twire = BRepBuilderAPI_MakeWire() for order_i in range(1, wire_order.NbEdges() + 1): deformed_edge_i = wire_order.Ordered(order_i) if deformed_edge_i > 0: # insert the deformed edge to the new wire new_edge_toadd = deformed_edges[deformed_edge_i - 1] stol.SetTolerance(new_edge_toadd, toledge) new_bspline_twire.Add(new_edge_toadd) if new_bspline_twire.Error() != 0: stol.SetTolerance(new_edge_toadd, toledge * 10.0) new_bspline_twire.Add(new_edge_toadd) else: deformed_edge_revers = deformed_edges[ np.abs(deformed_edge_i) - 1] stol.SetTolerance(deformed_edge_revers, toledge) new_bspline_twire.Add(deformed_edge_revers) if new_bspline_twire.Error() != 0: stol.SetTolerance(deformed_edge_revers, toledge * 10.0) new_bspline_twire.Add(deformed_edge_revers) # add new wire to the Face new_bspline_tface.Add(new_bspline_twire.Wire()) face_wires_explorer.Next() return topods.Face(new_bspline_tface.Face())