def get_transform(self): d = self.declaration t = gp_Trsf() #: TODO: Order matters... how to configure it??? if d.mirror: try: p,v = d.mirror except ValueError: raise ValueError("You must specify a tuple containing a (point,direction)") t.SetMirror(gp_Ax1(gp_Pnt(*p), gp_Dir(*v))) if d.scale: try: p,s = d.scale except ValueError: raise ValueError("You must specify a tuple containing a (point,scale)") t.SetScale(gp_Pnt(*p),s) if d.translate: t.SetTranslation(gp_Vec(*d.translate)) if d.rotate: try: p,v,a = d.rotate except ValueError: raise ValueError("You must specify a tuple containing a (point,direction,angle)") t.SetRotation(gp_Ax1(gp_Pnt(*p), gp_Dir(*v)),a) return t
def execute(self): ax = gp.gp_Ax2(gp.gp_Pnt(*self.position), gp.gp_Dir(*self.z_axis), gp.gp_Dir(*self.x_axis)) m_box = BRepPrimAPI.BRepPrimAPI_MakeBox(ax, *self.dims) self.update_naming(m_box) return m_box.Shape()
def line(): # create a line p1 = gp_Pnt(2., 3., 4.) d1 = gp_Dir(4., 5., 6.) line1 = Geom_Line(p1, d1) ais_line1 = AIS_Line(line1.GetHandle()) # if we need to edit color, we can simply use SetColor # ais_line1.SetColor(Quantity_NOC_RED) # but actually we need to edit more, not just color. Line width and style as well # To do that, we need to do use AIS_Drawer and apply it to ais_line1 width = 1.0 drawer = Prs3d_Drawer() ais_line1.SetAttributes(drawer.GetHandle()) display.Context.Display(ais_line1.GetHandle(), False) # we can apply the same rule for other lines by just doing a for loop for i in range(1, 5): p2 = gp_Pnt(i, 2., 5.) d2 = gp_Dir(4*i, 6., 9.) line2 = Geom_Line(p2, d2) ais_line2 = AIS_Line(line2.GetHandle()) width = float(i) drawer = ais_line2.Attributes().GetObject() # asp : first parameter color, second type, last width asp = Prs3d_LineAspect(9*i, i, width) drawer.SetLineAspect(asp.GetHandle()) ais_line2.SetAttributes(drawer.GetHandle()) display.Context.Display(ais_line2.GetHandle(), False) start_display()
def _calcTransforms(self): """Computes transformation matrices to convert between coordinates Computes transformation matrices to convert between local and global coordinates. """ # r is the forward transformation matrix from world to local coordinates # ok i will be really honest, i cannot understand exactly why this works # something bout the order of the translation and the rotation. # the double-inverting is strange, and I don't understand it. forward = Matrix() inverse = Matrix() global_coord_system = gp_Ax3() local_coord_system = gp_Ax3(gp_Pnt(*self.origin.toTuple()), gp_Dir(*self.zDir.toTuple()), gp_Dir(*self.xDir.toTuple())) forward.wrapped.SetTransformation(global_coord_system, local_coord_system) inverse.wrapped.SetTransformation(local_coord_system, global_coord_system) # TODO verify if this is OK self.lcs = local_coord_system self.rG = inverse self.fG = forward
def tangent(self, u, v): dU, dV = gp_Dir(), gp_Dir() curv = self.curvature(u, v) if curv.IsTangentUDefined() and curv.IsTangentVDefined(): curv.TangentU(dU), curv.TangentV(dV) return dU, dV else: return None, None
def make_box(position, direction, x_axis, dx, dy, dz): box = BRepPrimAPI.BRepPrimAPI_MakeBox(gp.gp_Pnt(-dx/2., -dy/2., 0.0), dx, dy, -dz) ax = gp.gp_Ax2(gp.gp_Pnt(*position), gp.gp_Dir(*direction), gp.gp_Dir(*x_axis)) ax3 = gp.gp_Ax3() trans = gp.gp_Trsf() trans.SetTransformation(gp.gp_Ax3(ax), ax3) t_box = BRepBuilderAPI.BRepBuilderAPI_Transform(box.Shape(), trans) return toshape(t_box)
def def_ax(x, y, z, lx=150, ly=200, dx=0, dy=0, dz=0): axs = gp_Ax3(gp_Pnt(x, y, z), gp_Dir(0, 0, 1), gp_Dir(1, 0, 0)) a_x = gp_Ax1(gp_Pnt(x, y, z), axs.XDirection()) a_y = gp_Ax1(gp_Pnt(x, y, z), axs.YDirection()) a_z = gp_Ax1(gp_Pnt(x, y, z), axs.Direction()) rot_axs(axs, a_x, dx) rot_axs(axs, a_y, dy) rot_axs(axs, a_z, dz) pln = BRepBuilderAPI_MakeFace(gp_Pln(axs), -lx / 2, lx / 2, -ly / 2, ly / 2).Face() return axs, pln
def second_derivative(h_surf, u=0, v=0): p1 = gp_Pnt() pu, pv = gp_Vec(), gp_Vec() puu, pvv = gp_Vec(), gp_Vec() puv = gp_Vec() prop = GeomLProp_SLProps(h_surf, u, v, 1, 1) GeomLProp_SurfaceTool.D2(h_surf, u, v, p1, pu, pv, puu, pvv, puv) e0 = pu.Crossed(pv) pu.Normalize() pv.Normalize() e0.Normalize() puu.Normalize() pvv.Normalize() puv.Normalize() print(p1) print("pu", pu) print("pv", pv) print("e0", e0) print("puu", puu) print("pvv", pvv) print("puv", puv) first_form = np.array([[pu.Dot(pu), pu.Dot(pv)], [pv.Dot(pu), pv.Dot(pv)]]) secnd_form = np.array([[e0.Dot(puu), e0.Dot(puv)], [e0.Dot(puv), e0.Dot(pvv)]]) print(first_form) print(secnd_form) print(prop.GaussianCurvature()) print(prop.MeanCurvature()) d1, d2 = gp_Dir(), gp_Dir() prop.CurvatureDirections(d1, d2) a1 = gp_Ax3() v1 = dir_to_vec(d1) v2 = dir_to_vec(d2) if pu.IsParallel(v1, 1 / 1000): c1 = prop.MaxCurvature() c2 = prop.MinCurvature() print(v1.Dot(pu), v1.Dot(pv)) print(v2.Dot(pu), v2.Dot(pv)) else: c1 = prop.MinCurvature() c2 = prop.MaxCurvature() print(v1.Dot(pu), v1.Dot(pv)) print(v2.Dot(pu), v2.Dot(pv)) print(c1, 1 / c1) print(c2, 1 / c2) px = np.linspace(-1, 1, 100) * 100 p1_y = px**2 / c1 p2_y = px**2 / c1 curv1 = curv_spl(px, p1_y) curv2 = curv_spl(px, p2_y)
def make_cylinder(position, direction, radius, length, offset, x_axis): cyl_ax = gp.gp_Ax2(gp.gp_Pnt(offset,0,0), gp.gp_Dir(0,0,1), gp.gp_Dir(1,0,0)) cyl = BRepPrimAPI.BRepPrimAPI_MakeCylinder(cyl_ax, radius, length) ax = gp.gp_Ax2(gp.gp_Pnt(*position), gp.gp_Dir(*direction), gp.gp_Dir(*x_axis)) ax3 = gp.gp_Ax3() trans = gp.gp_Trsf() trans.SetTransformation(gp.gp_Ax3(ax), ax3) t_cyl = BRepBuilderAPI.BRepBuilderAPI_Transform(cyl.Shape(), trans) print(position, direction, radius, length) return toshape(t_cyl)
def through_sections(): #ruled circle_1 = gp_Circ(gp_Ax2(gp_Pnt(-100., 0., -100.), gp_Dir(0., 0., 1.)), 40.) wire_1 = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle_1).Edge()).Wire() circle_2 = gp_Circ(gp_Ax2(gp_Pnt(-10., 0., -0.), gp_Dir(0., 0., 1.)), 40.) wire_2 = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle_2).Edge()).Wire() circle_3 = gp_Circ(gp_Ax2(gp_Pnt(-75., 0., 100.), gp_Dir(0., 0., 1.)), 40.) wire_3 = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle_3).Edge()).Wire() circle_4 = gp_Circ(gp_Ax2(gp_Pnt(0., 0., 200.), gp_Dir(0., 0., 1.)), 40.) wire_4 = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle_4).Edge()).Wire() generatorA = BRepOffsetAPI_ThruSections(False, True) map(generatorA.AddWire, [wire_1, wire_2, wire_3, wire_4]) generatorA.Build() display.DisplayShape(generatorA.Shape()) #smooth circle_1b = gp_Circ(gp_Ax2(gp_Pnt(100., 0., -100.), gp_Dir(0., 0., 1.)), 40.) wire_1b = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle_1b).Edge()).Wire() circle_2b = gp_Circ(gp_Ax2(gp_Pnt(210., 0., -0.), gp_Dir(0., 0., 1.)), 40.) wire_2b = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle_2b).Edge()).Wire() circle_3b = gp_Circ(gp_Ax2(gp_Pnt(275., 0., 100.), gp_Dir(0., 0., 1.)), 40.) wire_3b = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle_3b).Edge()).Wire() circle_4b = gp_Circ(gp_Ax2(gp_Pnt(200., 0., 200.), gp_Dir(0., 0., 1.)), 40.) wire_4b = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle_4b).Edge()).Wire() generatorB = BRepOffsetAPI_ThruSections(True, False) map(generatorB.AddWire, [wire_1b, wire_2b, wire_3b, wire_4b]) generatorB.Build() display.DisplayShape(generatorB.Shape(), update=True)
def edge(event=None): # The blud edge BlueEdge = BRepBuilderAPI_MakeEdge(gp_Pnt(-80, -50, -20), gp_Pnt(-30, -60, -60)) V1 = BRepBuilderAPI_MakeVertex(gp_Pnt(-20, 10, -30)) V2 = BRepBuilderAPI_MakeVertex(gp_Pnt(10, 7, -25)) YellowEdge = BRepBuilderAPI_MakeEdge(V1.Vertex(), V2.Vertex()) #The white edge line = gp_Lin(gp_Ax1(gp_Pnt(10, 10, 10), gp_Dir(1, 0, 0))) WhiteEdge = BRepBuilderAPI_MakeEdge(line, -20, 10) #The red edge Elips = gp_Elips(gp_Ax2(gp_Pnt(10, 0, 0), gp_Dir(1, 1, 1)), 60, 30) RedEdge = BRepBuilderAPI_MakeEdge(Elips, 0, math.pi/2) # The green edge and the both extreme vertex P1 = gp_Pnt(-15, 200, 10) P2 = gp_Pnt(5, 204, 0) P3 = gp_Pnt(15, 200, 0) P4 = gp_Pnt(-15, 20, 15) P5 = gp_Pnt(-5, 20, 0) P6 = gp_Pnt(15, 20, 0) P7 = gp_Pnt(24, 120, 0) P8 = gp_Pnt(-24, 120, 12.5) array = TColgp_Array1OfPnt(1, 8) array.SetValue(1, P1) array.SetValue(2, P2) array.SetValue(3, P3) array.SetValue(4, P4) array.SetValue(5, P5) array.SetValue(6, P6) array.SetValue(7, P7) array.SetValue(8, P8) curve = Geom_BezierCurve(array) ME = BRepBuilderAPI_MakeEdge(curve.GetHandle()) GreenEdge = ME V3 = ME.Vertex1() V4 = ME.Vertex2() display.DisplayColoredShape(BlueEdge.Edge(), 'BLUE') display.DisplayShape(V1.Vertex()) display.DisplayShape(V2.Vertex()) display.DisplayColoredShape(WhiteEdge.Edge(), 'WHITE') display.DisplayColoredShape(YellowEdge.Edge(), 'YELLOW') display.DisplayColoredShape(RedEdge.Edge(), 'RED') display.DisplayColoredShape(GreenEdge.Edge(), 'GREEN') display.DisplayShape(V3) display.DisplayShape(V4, update=True)
def edge(event=None): # The blud edge BlueEdge = BRepBuilderAPI_MakeEdge(gp_Pnt(-80, -50, -20), gp_Pnt(-30, -60, -60)) V1 = BRepBuilderAPI_MakeVertex(gp_Pnt(-20, 10, -30)) V2 = BRepBuilderAPI_MakeVertex(gp_Pnt(10, 7, -25)) YellowEdge = BRepBuilderAPI_MakeEdge(V1.Vertex(), V2.Vertex()) #The white edge line = gp_Lin(gp_Ax1(gp_Pnt(10, 10, 10), gp_Dir(1, 0, 0))) WhiteEdge = BRepBuilderAPI_MakeEdge(line, -20, 10) #The red edge Elips = gp_Elips(gp_Ax2(gp_Pnt(10, 0, 0), gp_Dir(1, 1, 1)), 60, 30) RedEdge = BRepBuilderAPI_MakeEdge(Elips, 0, math.pi / 2) # The green edge and the both extreme vertex P1 = gp_Pnt(-15, 200, 10) P2 = gp_Pnt(5, 204, 0) P3 = gp_Pnt(15, 200, 0) P4 = gp_Pnt(-15, 20, 15) P5 = gp_Pnt(-5, 20, 0) P6 = gp_Pnt(15, 20, 0) P7 = gp_Pnt(24, 120, 0) P8 = gp_Pnt(-24, 120, 12.5) array = TColgp_Array1OfPnt(1, 8) array.SetValue(1, P1) array.SetValue(2, P2) array.SetValue(3, P3) array.SetValue(4, P4) array.SetValue(5, P5) array.SetValue(6, P6) array.SetValue(7, P7) array.SetValue(8, P8) curve = Geom_BezierCurve(array) ME = BRepBuilderAPI_MakeEdge(curve.GetHandle()) GreenEdge = ME V3 = ME.Vertex1() V4 = ME.Vertex2() display.DisplayColoredShape(BlueEdge.Edge(), 'BLUE') display.DisplayShape(V1.Vertex()) display.DisplayShape(V2.Vertex()) display.DisplayColoredShape(WhiteEdge.Edge(), 'WHITE') display.DisplayColoredShape(YellowEdge.Edge(), 'YELLOW') display.DisplayColoredShape(RedEdge.Edge(), 'RED') display.DisplayColoredShape(GreenEdge.Edge(), 'GREEN') display.DisplayShape(V3) display.DisplayShape(V4, update=True)
def edge(event=None): # The blud edge blue_edge = BRepBuilderAPI_MakeEdge(gp_Pnt(-80, -50, -20), gp_Pnt(-30, -60, -60)) v1 = BRepBuilderAPI_MakeVertex(gp_Pnt(-20, 10, -30)) v2 = BRepBuilderAPI_MakeVertex(gp_Pnt(10, 7, -25)) yellow_edge = BRepBuilderAPI_MakeEdge(v1.Vertex(), v2.Vertex()) # The white edge line = gp_Lin(gp_Ax1(gp_Pnt(10, 10, 10), gp_Dir(1, 0, 0))) white_edge = BRepBuilderAPI_MakeEdge(line, -20, 10) # The red edge elips = gp_Elips(gp_Ax2(gp_Pnt(10, 0, 0), gp_Dir(1, 1, 1)), 60, 30) red_edge = BRepBuilderAPI_MakeEdge(elips, 0, math.pi / 2) # The green edge and the both extreme vertex p1 = gp_Pnt(-15, 200, 10) p2 = gp_Pnt(5, 204, 0) p3 = gp_Pnt(15, 200, 0) p4 = gp_Pnt(-15, 20, 15) p5 = gp_Pnt(-5, 20, 0) p6 = gp_Pnt(15, 20, 0) p7 = gp_Pnt(24, 120, 0) p8 = gp_Pnt(-24, 120, 12.5) array = TColgp_Array1OfPnt(1, 8) array.SetValue(1, p1) array.SetValue(2, p2) array.SetValue(3, p3) array.SetValue(4, p4) array.SetValue(5, p5) array.SetValue(6, p6) array.SetValue(7, p7) array.SetValue(8, p8) curve = Geom_BezierCurve(array) make_edge = BRepBuilderAPI_MakeEdge(curve.GetHandle()) green_edge = make_edge v3 = make_edge.Vertex1() v4 = make_edge.Vertex2() display.DisplayColoredShape(blue_edge.Edge(), 'BLUE') display.DisplayShape(v1.Vertex()) display.DisplayShape(v2.Vertex()) display.DisplayColoredShape(white_edge.Edge(), 'WHITE') display.DisplayColoredShape(yellow_edge.Edge(), 'YELLOW') display.DisplayColoredShape(red_edge.Edge(), 'RED') display.DisplayColoredShape(green_edge.Edge(), 'GREEN') display.DisplayShape(v3) display.DisplayShape(v4, update=True)
def position_shape(shape, centre, direction, x_axis): ax = gp.gp_Ax3() ax.SetLocation(gp.gp_Pnt(*centre)) ax.SetDirection(gp.gp_Dir(*direction)) ax.SetXDirection(gp.gp_Dir(*x_axis)) tr = gp.gp_Trsf() tr.SetTransformation(ax, gp.gp_Ax3()) loc = TopLoc.TopLoc_Location(tr) shape.Location(loc) #trans = BRepBuilderAPI.BRepBuilderAPI_Transform(shape, tr) #return toshape(trans) return shape
def create(self,center_Pnt,merged_arg=0): self.new_Pnt=center_Pnt self.new_gp_Pnt=gp_Pnt(center_Pnt[0],center_Pnt[1],center_Pnt[2]) self.shape=BRepPrimAPI_MakeSphere(self.new_gp_Pnt,2.1).Shape() display.DisplayShape(self.shape, update=True, color='YELLOW') self.attach_gp_dir=[] self.attach_gp_Ax2=[] self.magnet=[] self.attach_dir = [] for i in range(len(self.attach_pos)): if self.attach_pos[i]!=0: # self.attach_gp_dir.append(i) # self.attach_gp_Ax2.append(i) # self.magnet.append(i) self.dir=merged_arg merge_rotate=[math.cos(i * self.divide_arg)*math.cos(merged_arg)- math.sin(i*self.divide_arg)*math.sin(merged_arg), math.sin(i * self.divide_arg)*math.cos(merged_arg)+ math.cos(i * self.divide_arg)*math.sin(merged_arg),0] self.attach_dir.append([merge_rotate[0],merge_rotate[1],merge_rotate[2]]) self.attach_gp_dir.append(gp_Dir(self.attach_dir[i][0],self.attach_dir[i][1],self.attach_dir[i][2])) self.attach_gp_Ax2.append(gp_Ax2(self.new_gp_Pnt,self.attach_gp_dir[i])) self.magnet.append(BRepPrimAPI_MakeCylinder(self.attach_gp_Ax2[i],0.25,2.4).Shape()) if self.attach_pos[i]==1: display.DisplayShape(self.magnet[i], update=True, color='RED') elif self.attach_pos[i]==-1: display.DisplayShape(self.magnet[i], update=True, color=22)#22 is blue else: self.attach_gp_dir.append(i) self.attach_gp_Ax2.append(i) self.attach_dir.append(i) self.magnet.append(i)
def AddCone(BasePoint, Radius, height, direction=gp_Dir(1, 0, 0)): """Generates a cone shape originating at BasePoint with base Radius and height (points in the direction of input 'direction) Parameters ---------- BasePoint : OCC.gp.gp_Pnt or array length 3 The centre base point Radius : scalar Cone base radius height : scalar Cone height direction : OCC.gp.gp_Dir (default: positive x direction) the direction of the cones axis i.e. normal to the base: defaults to x axis Returns ------- shape : TopoDS_Shape The generated Cone """ try: BasePoint = gp_Pnt(*BasePoint) except: pass ax2 = gp_Ax2(BasePoint, direction) cone = BRepPrimAPI_MakeCone(ax2, Radius, 0, height) return cone.Shape()
def split_edge_with_face(event=None): display.EraseAll() p0 = gp_Pnt() vnorm = gp_Dir(1, 0, 0) pln = gp_Pln(p0, vnorm) face = BRepBuilderAPI_MakeFace(pln, -10, 10, -10, 10).Face() p1 = gp_Pnt(0, 0, 15) p2 = gp_Pnt(0, 0, -15) edge = BRepBuilderAPI_MakeEdge(p1, p2).Edge() # Initialize splitter splitter = GEOMAlgo_Splitter() # Add the edge as an argument and the face as a tool. This will split # the edge with the face. splitter.AddArgument(edge) splitter.AddTool(face) splitter.Perform() edges = [] exp = TopExp_Explorer(splitter.Shape(), TopAbs_EDGE) while exp.More(): edges.append(exp.Current()) exp.Next() print('Number of edges in split shape: ', len(edges)) display.DisplayShape(edges[0], color='red') display.DisplayShape(edges[1], color='green') display.DisplayShape(edges[2], color='yellow') display.FitAll()
def pipe_fillet(radius): # the points p1 = gp_Pnt(0, 0, 0) p2 = gp_Pnt(0, 1, 0) p3 = gp_Pnt(1, 2, 0) p4 = gp_Pnt(2, 2, 0) # the edges ed1 = BRepBuilderAPI_MakeEdge(p1, p2).Edge() ed2 = BRepBuilderAPI_MakeEdge(p2, p3).Edge() ed3 = BRepBuilderAPI_MakeEdge(p3, p4).Edge() # inbetween fillet12 = filletEdges(ed1, ed2) fillet23 = filletEdges(ed2, ed3) # the wire makeWire = BRepBuilderAPI_MakeWire() makeWire.Add(ed1) makeWire.Add(fillet12) makeWire.Add(ed2) makeWire.Add(fillet23) makeWire.Add(ed3) makeWire.Build() wire = makeWire.Wire() # the pipe dir = gp_Dir(0, 1, 0) circle = gp_Circ(gp_Ax2(p1, dir), radius) profile_edge = BRepBuilderAPI_MakeEdge(circle).Edge() profile_wire = BRepBuilderAPI_MakeWire(profile_edge).Wire() profile_face = BRepBuilderAPI_MakeFace(profile_wire).Face() pipe = BRepOffsetAPI_MakePipe(wire, profile_face).Shape() #display.DisplayShape(pipe, update=True) return (pipe)
def normalEdgesAlongEdge(edge, length , interval): "compute an edge having length at the specified parameter on the supplied curve:" edgeList = []; ew = Wrappers.Edge(edge); zDir = gp.gp().DZ(); zVec = gp.gp_Vec(zDir); curve = ew.curve; pStart = ew.firstParameter; pEnd = ew.lastParameter; for p in Wrappers.frange6(pStart,pEnd,interval): tangent = gp.gp_Vec(); tanpoint = gp.gp_Pnt(); curve.D1(p,tanpoint,tangent ); axis = gp.gp_Ax1(tanpoint, gp.gp_Dir(tangent.Crossed(zVec) ) ); line = Geom.Geom_Line(axis ); e = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(line.GetHandle(),0, length).Edge(); if e: edgeList.append(e); return edgeList;
def pipe(event=None): CurvePoles = TColgp_Array1OfPnt(1,6) pt1 = gp_Pnt(0.,0.,0.); pt2 = gp_Pnt(20.,50.,0.); pt3 = gp_Pnt(60.,100.,0.); pt4 = gp_Pnt(150.,0.,0.); CurvePoles.SetValue(1, pt1) CurvePoles.SetValue(2, pt2) CurvePoles.SetValue(3, pt3) CurvePoles.SetValue(4, pt4) curve = Geom_BezierCurve(CurvePoles) print type(curve) E = BRepBuilderAPI_MakeEdge(curve.GetHandle()).Edge() W = BRepBuilderAPI_MakeWire(E).Wire() #ais1 = AIS_Shape(W) #self.interactive_context.Display(ais1,1) c = gp_Circ(gp_Ax2(gp_Pnt(0.,0.,0.),gp_Dir(0.,1.,0.)),10.) Ec = BRepBuilderAPI_MakeEdge(c).Edge() Wc = BRepBuilderAPI_MakeWire(Ec).Wire() #ais3 = AIS_Shape(Wc) #self.interactive_context.Display(ais3,1) F = BRepBuilderAPI_MakeFace(gp_Pln(gp_Ax3(gp.gp().ZOX())),Wc,1).Face() MKPipe = BRepOffsetAPI_MakePipe(W,F) MKPipe.Build() display.DisplayShape(MKPipe.Shape())
def rotate(occtopology, rot_pypt, pyaxis, degree): """ This function rotates an OCCtopology based on the rotation point, an axis and the rotation degree. Parameters ---------- occtopology : OCCtopology The OCCtopology to be rotated. OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex rot_pypt : tuple of floats The OCCtopology will rotate in reference to this point. A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z) pyaxis : tuple of floats The OCCtopology will rotate along this axis. A pyaxis is a tuple that documents the xyz of a direction e.g. (x,y,z) degree : float The degree of rotation. Returns ------- rotated topology : OCCtopology (OCCshape) The rotated OCCtopology. """ from math import radians gp_ax3 = gp_Ax1(gp_Pnt(rot_pypt[0], rot_pypt[1], rot_pypt[2]), gp_Dir(pyaxis[0], pyaxis[1], pyaxis[2])) aTrsf = gp_Trsf() aTrsf.SetRotation(gp_ax3, radians(degree)) rot_brep = BRepBuilderAPI_Transform(aTrsf) rot_brep.Perform(occtopology, True) rot_shape = rot_brep.Shape() return rot_shape
def align_planes_byNormal(shp_add, normalDir_base, normalDir_add): """[summary] Arguments: shp_add {topoDS_Shape} -- [description] normalDir_base {gp_Dir} -- [description] normalDir_add {gp_Dir} -- [description] rotateAng [deg]{float} -- [description] """ if not normalDir_base.IsParallel(normalDir_add, radians(0.01)): rotateAxDir = normalDir_base.Crossed(normalDir_add) # determin rotate angle rotRelAng = degrees( normalDir_base.AngleWithRef(normalDir_add, rotateAxDir)) if rotRelAng > 89.99: rotRelAng -= 180 elif rotRelAng < -89.99: rotRelAng += 180 rotateAx1 = gp_Ax1(centerOfMass(shp_add), rotateAxDir) ax3 = gp_Ax3(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)) ax3 = ax3.Rotated(rotateAx1, radians(rotRelAng)) shp2Trsf = gp_Trsf() shp2Trsf.SetTransformation(ax3) shp2Toploc = TopLoc_Location(shp2Trsf) shp_add.Move(shp2Toploc) else: logging.debug("Planes are already parallel to each other")
def test_project_curve_to_plane(): # Projects a line of length 1 from above the XOY plane, and tests points # on the resulting line from OCC.Geom import Geom_Plane, Geom_TrimmedCurve from OCC.GC import GC_MakeSegment from OCC.gp import gp_Ax3, gp_XOY, gp_Pnt, gp_Dir XOY = Geom_Plane(gp_Ax3(gp_XOY())) curve = GC_MakeSegment(gp_Pnt(0, 0, 5), gp_Pnt(1, 0, 5)).Value() direction = gp_Dir(0, 0, 1) Hproj_curve = act.project_curve_to_plane(curve, XOY.GetHandle(), direction) proj_curve = Hproj_curve.GetObject() # The start and end points of the curve p1 = proj_curve.Value(0) p2 = proj_curve.Value(1) p1_array = np.array([p1.X(), p1.Y(), p1.Z()]) p2_array = np.array([p2.X(), p2.Y(), p2.Z()]) # The expected start and end points start = np.array([0, 0, 0]) end = np.array([1, 0, 0]) # Assert that neither points have a Y or Z component, and that assert((np.all(p1_array == start) and np.all(p2_array == end)) or (np.all(p1_array == end) and np.all(p2_array == start)))
def display_vector(self, origin, direction): r"""Display a vector starting at origin and going in direction Parameters ---------- origin : tuple(float) The origin coordinates (x, y, z) of the vector to display direction : tuple(float) The direction coordinates (x, y, z) of the vector to display """ xo, yo, zo = origin xd, yd, zd = direction end = (xo + xd, yo + xd, zo + zd) xe, ye, ze = end # self.glarea.d3d.DisplayVector(gp_Vec(xd, yd, zd), gp_Pnt(xo, yo, zo)) presentation = Prs3d_Presentation(self.glarea.occ_context.MainPrsMgr(). GetObject().StructureManager()) arrow = Prs3d_Arrow() arrow.Draw(presentation.GetHandle(), gp_Pnt(xe, ye, ze), gp_Dir(gp_Vec(xd, yd, zd)), _math.radians(20), gp_Vec(xd, yd, zd).Magnitude() / 4.) presentation.Display() e1 = BRepBuilderAPI_MakeEdge(gp_Pnt(xo, yo, zo), gp_Pnt(xe, ye, ze)).\ Edge() self.display(e1, line_width=4)
def make_interp_parabola(FL, rmin, rmax, segments=50): A = 1./(4*FL) x = numpy.linspace(rmin, rmax, segments) y = (A * x**2) - FL points = [(X,0,Z) for X,Z in zip(x,y)] points.append((x[0],0,y[-1])) def pairs(itr): a,b = itertools.tee(itr) next(b) return zip(a,b) edges = (BRepBuilderAPI.BRepBuilderAPI_MakeEdge( gp.gp_Pnt(*p1), gp.gp_Pnt(*p2)) for p1, p2 in pairs(points)) last_edge = BRepBuilderAPI.BRepBuilderAPI_MakeEdge( gp.gp_Pnt(*points[-1]), gp.gp_Pnt(*points[0])) wire = BRepBuilderAPI.BRepBuilderAPI_MakeWire() for e in edges: wire.Add(e.Edge()) wire.Add(last_edge.Edge()) face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(wire.Wire()) ax = gp.gp_Ax1(gp.gp_Pnt(0,0,0), gp.gp_Dir(0,0,1)) revol = BRepPrimAPI.BRepPrimAPI_MakeRevol(face.Shape(), ax) return revol.Shape()
def slicer(event=None): # Param Zmin, Zmax, deltaZ = -100, 100, 5 # Note: the shape can also come from a shape selected from InteractiveViewer if 'display' in dir(): shape = display.GetSelectedShape() else: # Create the shape to slice shape = BRepPrimAPI_MakeSphere(60.).Shape() # Define the direction D = gp_Dir(0., 0., 1.) # the z direction # Perform slice sections = [] init_time = time.time() # for total time computation for z in range(Zmin, Zmax, deltaZ): # Create Plane defined by a point and the perpendicular direction P = gp_Pnt(0, 0, z) Pln = gp_Pln(P, D) face = BRepBuilderAPI_MakeFace(Pln).Shape() # Computes Shape/Plane intersection section_shp = BRepAlgoAPI_Section(shape, face) if section_shp.IsDone(): sections.append(section_shp) total_time = time.time() - init_time print("%.3fs necessary to perform slice." % total_time) display.EraseAll() display.DisplayShape(shape) for section_ in sections: display.DisplayShape(section_.Shape()) display.FitAll()
def boolean_cut(base): # Create a cylinder cylinder_radius = 0.25 cylinder_height = 2.0 cylinder_origin = gp_Ax2(gp_Pnt(0.0, 0.0, -cylinder_height / 2.0), gp_Dir(0.0, 0.0, 1.0)) cylinder = BRepPrimAPI_MakeCylinder(cylinder_origin, cylinder_radius, cylinder_height) # Repeatedly move and subtract it from the input shape move = gp_Trsf() boolean_result = base clone_radius = 1.0 for clone in range(8): angle = clone * pi / 4.0 # Move the cylinder move.SetTranslation( gp_Vec(cos(angle) * clone_radius, sin(angle) * clone_radius, 0.0)) moved_cylinder = BRepBuilderAPI_Transform(cylinder.Shape(), move, True).Shape() # Subtract the moved cylinder from the drilled sphere boolean_result = BRepAlgoAPI_Cut(boolean_result, moved_cylinder).Shape() return boolean_result
def intersect_shape_by_half_line(topods_shape, x, y, z, vx, vy, vz): r"""Intersect shape by half line starting at (x, y, z) in the direction (vx, vy, vz) This function tries to have a more intuitive interface than intersect_shape_by_line() Parameters ---------- topods_shape x : float Starting point x y : float Starting point y z : float Starting point z vx : float Direction vector x component vy : float Direction vector y component vz : float Direction vector z component Returns ------- a list of gp_Pnt, ordered in natural order going from the point where the half line starts and following the direction """ return _intersect_shape_by_line(topods_shape, gp_Lin(gp_Pnt(x, y, z), gp_Dir(vx, vy, vz)), 0, float("+inf"))
def tangentAt(self, locationVector=None): """ Compute tangent vector at the specified location. :param locationVector: location to use. Use the center point if None :return: tangent vector """ curve = self._geomAdaptor() if locationVector: raise NotImplementedError else: umin, umax = curve.FirstParameter(), curve.LastParameter() umid = 0.5 * (umin + umax) # TODO what are good parameters for those? curve_props = BRepLProp_CLProps(curve, 2, curve.Tolerance()) curve_props.SetParameter(umid) if curve_props.IsTangentDefined(): dir_handle = gp_Dir( ) # this is awkward due to C++ pass by ref in the API curve_props.Tangent(dir_handle) return Vector(dir_handle)
def slicer(event=None): # Param Zmin, Zmax, deltaZ = -100, 100, 5 # Note: the shape can also come from a shape selected from InteractiveViewer if 'display' in dir(): shape = display.GetSelectedShape() else: # Create the shape to slice shape = BRepPrimAPI_MakeSphere(60.).Shape() # Define the direction D = gp_Dir(0., 0., 1.) # the z direction # Perform slice sections = [] init_time = time.time() # for total time computation for z in range(Zmin, Zmax, deltaZ): # Create Plane defined by a point and the perpendicular direction P = gp_Pnt(0, 0, z) Pln = gp_Pln(P, D) face = BRepBuilderAPI_MakeFace(Pln).Shape() # Computes Shape/Plane intersection section = BRepAlgoAPI_Section(shape, face) if section.IsDone(): sections.append(section) total_time = time.time() - init_time print("%.3fs necessary to perform slice." % total_time) display.EraseAll() display.DisplayShape(shape) for section in sections: display.DisplayShape(section.Shape()) display.FitAll()
def occ(display): ''' display, start_display, add_menu, add_function_to_menu = init_display() my_box = BRepPrimAPI_MakeBox(10., 20., 30.).Shape() display.DisplayShape(my_box, update=True) #start_display() ''' display.EraseAll() ais_boxshp = build_shape(display) ax1 = gp_Ax1(gp_Pnt(25., 25., 25.), gp_Dir(0., 0., 1.)) aCubeTrsf = gp_Trsf() angle = 0.0 tA = time.time() n_rotations = 200 for i in range(n_rotations): aCubeTrsf.SetRotation(ax1, angle) aCubeToploc = TopLoc_Location(aCubeTrsf) display.Context.SetLocation(ais_boxshp, aCubeToploc) display.Context.UpdateCurrentViewer() angle += 2*pi / n_rotations print("%i rotations took %f" % (n_rotations, time.time() - tA))
def make_ellipsoid(focus1, focus2, major_axis): """ @param focus1: length 3 sequence giving first focus location @param focus2: length 3 sequence giving second focus location @param path_length: major axis length """ f1 = numpy.asarray(focus1) f2 = numpy.asarray(focus2) direction = -(f1 - f2) centre = (f1 + f2)/2. sep = numpy.sqrt((direction**2).sum()) minor_axis = numpy.sqrt( major_axis**2 - (sep/2.)**2 ) sphere = BRepPrimAPI.BRepPrimAPI_MakeSphere(minor_axis) scale = gp.gp_GTrsf() scale.SetValue(3,3, major_axis/minor_axis) ellipse = BRepBuilderAPI.BRepBuilderAPI_GTransform(sphere.Shape(), scale) loc = gp.gp_Ax3() loc.SetLocation(gp.gp_Pnt(*centre)) loc.SetDirection(gp.gp_Dir(*direction)) tr = gp.gp_Trsf() tr.SetTransformation(loc, gp.gp_Ax3()) trans = BRepBuilderAPI.BRepBuilderAPI_Transform(ellipse.Shape(), tr) shape = toshape(trans) return shape
def mirror(brep, plane='xz', axe2=None, copy=False): """Originally from pythonocc-utils : might add dependency on this? Mirrors object Parameters ---------- brep : OCC.TopoDS.TopoDS_Shape The shape to mirror plane : string (default = 'xz') The name of the plane in which to mirror objects. Acceptable inputs are any of 'xy', 'yx' , 'zy', 'yz', 'yz', 'zy'. Overwritten if axe2 is defined. axe2 : OCC.gp.gp_Ax2 The axes through which to mirror (overwrites input 'plane') copy : bool Returns ------- BRepBuilderAPI_Transform.Shape : TopoDS_Shape The reflected shape Notes ----- Pchambers: Added a functionality here to specify a plane using a string so that users could avoid interacting with core occ objects""" if axe2: plane = None else: Orig = gp_Pnt(0., 0., 0.) if plane in ['xz', 'zx']: ydir = gp_Dir(0, 1, 0) axe2 = gp_Ax2(Orig, ydir) elif plane in ['yz', 'zy']: xdir = gp_Dir(1, 0, 0) axe2 = gp_Ax2(Orig, xdir) elif plane in ['xy', 'yx']: zdir = gp_Dir(0, 0, 1) axe2 = gp_Ax2(Orig, zdir) else: raise (ValueError, "Unknown mirror plane string,", plane) trns = gp_Trsf() trns.SetMirror(axe2) brep_trns = BRepBuilderAPI_Transform(brep, trns, copy) return brep_trns.Shape()
def group_cylinders_byAxisDir(cylinders, anglTolDeg=5, roundDigit=6, groupParallelAx=True): logging.debug('Entering group_cylinders_byAxisDir') cyl_ax = {} for cylinder in cylinders: cyl = BRepAdaptor_Surface(cylinder, True).Cylinder() axis = cyl.Axis() key = (round(axis.Direction().X(), roundDigit), round(axis.Direction().Y(), roundDigit), round(axis.Direction().Z(), roundDigit)) if key in cyl_ax.keys(): cyl_ax[key].append(cylinder) else: cyl_ax[key] = [cylinder] for key in cyl_ax.keys(): listOflist = list(find_full_cylinder(cyl_ax[key]).values()) cyl_ax[key] = [k for i in listOflist for k in i] if groupParallelAx: axisKeyList = list(cyl_ax.keys()) combineList = [] j = 0 while len(axisKeyList) >= 1: ax1 = axisKeyList.pop(0) grp = [ax1] dir1 = gp_Dir(ax1[0], ax1[1], ax1[2]) while j < len(axisKeyList): ax2 = axisKeyList[j] dir2 = gp_Dir(ax2[0], ax2[1], ax2[2]) j += 1 if dir1.IsParallel(dir2, radians(anglTolDeg)): grp.append(ax2) j -= 1 axisKeyList.pop(j) combineList.append(grp) j = 0 cyl_grpByAx = {} for i in combineList: cyl_grpByAx[i[0]] = [] for j in i: cyl_grpByAx[i[0]] += cyl_ax[j] else: cyl_grpByAx = cyl_ax return cyl_grpByAx
def mirror(brep, plane='xz', axe2=None, copy=False): """Originally from pythonocc-utils : might add dependency on this? Mirrors object Parameters ---------- brep : OCC.TopoDS.TopoDS_Shape The shape to mirror plane : string (default = 'xz') The name of the plane in which to mirror objects. Acceptable inputs are any of 'xy', 'yx' , 'zy', 'yz', 'yz', 'zy'. Overwritten if axe2 is defined. axe2 : OCC.gp.gp_Ax2 The axes through which to mirror (overwrites input 'plane') copy : bool Returns ------- BRepBuilderAPI_Transform.Shape : TopoDS_Shape The reflected shape Notes ----- Pchambers: Added a functionality here to specify a plane using a string so that users could avoid interacting with core occ objects""" if axe2: plane = None else: Orig = gp_Pnt(0., 0., 0.) if plane in ['xz', 'zx']: ydir = gp_Dir(0, 1, 0) axe2 = gp_Ax2(Orig, ydir) elif plane in ['yz', 'zy']: xdir = gp_Dir(1, 0, 0) axe2 = gp_Ax2(Orig, xdir) elif plane in ['xy', 'yx']: zdir = gp_Dir(0, 0, 1) axe2 = gp_Ax2(Orig, zdir) else: raise(ValueError, "Unknown mirror plane string,", plane) trns = gp_Trsf() trns.SetMirror(axe2) brep_trns = BRepBuilderAPI_Transform(brep, trns, copy) return brep_trns.Shape()
def rotate(self, angle, axis): ax = gp_Ax1(gp_Pnt(*axis[:3]), gp_Dir(*axis[3:])) tr = gp_Trsf() tr.SetRotation(ax, angle) loc = TopLoc_Location(tr) self.shape = BRepBuilderAPI_Transform(self.shape, tr).Shape() self.__extract_curves() return self
def generate_shape(): """Create a sphere with faces top and bottom""" sphere_radius = 1.0 sphere_angle = atan(0.5) sphere_origin = gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)) sphere = BRepPrimAPI_MakeSphere(sphere_origin, sphere_radius, -sphere_angle, sphere_angle).Shape() return sphere
def rotate(shape, axis, angle): tr = gp_Trsf() point = axis[0] vec = axis[1] axis = gp.gp_Ax1(gp.gp_Pnt(*point), gp.gp_Dir(*vec)) tr.SetRotation(axis, angle) loc = TopLoc_Location(tr) return shape.Moved(loc)
def CutSect(Shape, SpanStation): """ Parameters ---------- Shape : TopoDS_Shape The Shape to find planar cut section (parallel to xz plane) SpanStation : scalar in range (0, 1) y-direction location at which to cut Shape Returns ------- Section : result of OCC.BRepAlgoAPI.BRepAlgoAPI_Section (TopoDS_Shape) The cut section of shape given a cut plane parallel to xz at input Spanstation. Chord : result of OCC.GC.GC_MakeSegment.Value (Geom_TrimmedCurve) The Chord line between x direction extremeties """ (Xmin, Ymin, Zmin, Xmax, Ymax, Zmax) = ObjectsExtents([Shape]) YStation = Ymin + (Ymax - Ymin) * SpanStation OriginX = Xmin - 1 OriginZ = Zmin - 1 P = gp_Pln(gp_Pnt(OriginX, YStation, OriginZ), gp_Dir(gp_Vec(0, 1, 0))) # Note: using 2*extents here as previous +1 trimmed plane too short CutPlaneSrf = make_face(P, 0, Zmax + 2, 0, Xmax +2) I = BRepAlgoAPI_Section(Shape, CutPlaneSrf) I.ComputePCurveOn1(True) I.Approximation(True) I.Build() Section = I.Shape() (Xmin, Ymin, Zmin, Xmax, Ymax, Zmax) = ObjectsExtents([Section]) # Currently assume only one edge exists in the intersection: exp = TopExp_Explorer(Section, TopAbs_EDGE) edge = topods_Edge(exp.Current()) # Find the apparent chord of the section (that is, the line connecting the # fore most and aftmost points on the curve DivPoints = Uniform_Points_on_Curve(edge, 200) Xs = np.array([pt.X() for pt in DivPoints]) min_idx = np.argmin(Xs) LeadingPoint = gp_Pnt(Xs[min_idx], DivPoints[min_idx].Y(), DivPoints[min_idx].Z()) max_idx = np.argmax(Xs) TrailingPoint = gp_Pnt(Xs[max_idx], DivPoints[max_idx].Y(), DivPoints[max_idx].Z()) HChord = GC_MakeSegment(TrailingPoint, LeadingPoint).Value() # Chord = HChord.GetObject() return Section, HChord
def rotating_cube_2_axis(event=None): display.EraseAll() ais_boxshp = build_shape() ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 0., 1.)) ax2 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 1., 0.)) a_cube_trsf = gp_Trsf() a_cube_trsf2 = gp_Trsf() angle = 0.0 tA = time.time() n_rotations = 200 for i in range(n_rotations): a_cube_trsf.SetRotation(ax1, angle) a_cube_trsf2.SetRotation(ax2, angle) aCubeToploc = TopLoc_Location(a_cube_trsf * a_cube_trsf2) display.Context.SetLocation(ais_boxshp, aCubeToploc) display.Context.UpdateCurrentViewer() angle += 2*pi / n_rotations print("%i rotations took %f" % (n_rotations, time.time() - tA))
def test_project_curve_to_surface(): """Returning object rather than handle from this function gave bugs between 0.16.3 and 0.16.5 - adding test to preempt future oddness""" # Edge to project: h = 5 pnts = np.array([[0, h, 0], [1, h, 2], [2, h, 3], [4, h, 3], [5, h, 5]]) spline = act.points_to_bspline(pnts) # Surface to project onto: from OCC.GC import GC_MakeCircle circle = GC_MakeCircle(gp_Pnt(0,0,0), gp_Dir(0, 1, 0), 10).Value() edge = act.make_edge(circle) face = act.make_face(act.make_wire(edge)) Hprojected_curve = act.project_curve_to_surface(spline, face, gp_Dir(0, -1, 0)) # Check that the curve created is not null check_valid_object(Hprojected_curve)
def add_feature(base): """Add a "feature" to a shape. In this case we drill a hole through it.""" feature_diameter = 0.8 feature_origin = gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)) feature_maker = BRepFeat_MakeCylindricalHole() feature_maker.Init(base, feature_origin) feature_maker.Build() feature_maker.Perform(feature_diameter / 2.0) shape = feature_maker.Shape() return shape
def MakeWindow(self, Xwc, Zwc): """Makes at Window centered at Wxc Zwc using the bspline wire returned by WindowContour THIS FUNCTION IS IN DEVELOPMENT AND NOT YET TESTED FULLY Parameters ---------- Xwc : scalar The window center x coordinate Zwc : scalar The window center z coordinate Returns ------- WinStbd : TopoDS_Shape The window surface cut out (starboard side) WinPort : TopoDS_Shape The window surface cut out (Port side) Notes ----- Changes the contents of self['OML']. Makes both the port and starboard windows at the input location. """ raise NotImplementedError( "This function is in development, and its output is untested") WinCenter = [Xwc, Zwc] W_wire = self.WindowContour(WinCenter) ExtPathStbd = gp_Dir(gp_Vec(gp_Pnt(0, 0, 0), gp_Pnt(0, 10, 0))) ExtPathPort = gp_Dir(gp_Vec(0, -10, 0)) self['OML'], WinStbd = act.SplitShapeFromProjection(self['OML'], W_wire, direction=ExtPathStbd) self['OML'], WinPort = act.SplitShapeFromProjection(self['OML'], W_wire, direction=ExtPathPort) return WinStbd, WinPort
def _isAtZLevel(self, zLevel, face): bf = BRepGProp.BRepGProp_Face(face) bounds = bf.Bounds() vec = gp.gp_Vec() zDir = gp.gp().DZ() pt = gp.gp_Pnt() # get a normal vector to the face bf.Normal(bounds[0], bounds[1], pt, vec) z = pt.Z() sDir = gp.gp_Dir(vec) return (abs(z - zLevel) < 0.0001) and (zDir.IsParallel(sDir, 0.0001))
def mode_drawing(self, widget=None): """ This is a stand-alone call to make a drafting-like drawing of the shape. It's better than HLR, because HLR shows creases at edges where shapes are tangent. If this must be a menu call, pop up a separate window for it. """ self.saved_projection = self.glarea.occ_view.ViewOrientation() # Graphic3d_Vertex vcenter = self.saved_projection.ViewReferencePoint() vout = self.saved_projection.ViewReferencePlane() # Graphic3d_Vector vup = self.saved_projection.ViewReferenceUp() # Graphic3d_Vector vout_gp = _gp.gp_Vec(vout.X(), vout.Y(), vout.Z()) vright = _gp.gp_Vec(vup.X(), vup.Y(), vup.Z()) vright.Cross(vout_gp) projection = _HLRAlgo_Projector( _gp.gp_Ax2(_gp.gp_Pnt(vcenter.X(), vcenter.Y(), vcenter.Z()), _gp.gp_Dir(vout.X(), vout.Y(), vout.Z()), _gp.gp_Dir(vright.X(), vright.Y(), vright.Z()))) hlr_algo = _HLRBRep_Algo() handle_hlr_algo = hlr_algo.GetHandle() for display_shape in self.display_shapes: hlr_algo.Add(display_shape['shape']) hlr_algo.Projector(projection) hlr_algo.Update() hlr_algo.Hide() hlr_toshape = _HLRBRep_HLRToShape(handle_hlr_algo) vcompound = hlr_toshape.VCompound() outlinevcompound = hlr_toshape.OutLineVCompound() self.clear(0) self.display(vcompound, color=display_shape['color'], line_type=display_shape['line_type'], line_width=display_shape['line_width'], logging=False) self.display(outlinevcompound, color=display_shape['color'], line_type=display_shape['line_type'], line_width=display_shape['line_width'], logging=False) self.viewstandard(viewtype='top')
def tangent(self, u): '''sets or gets ( iff vector ) the tangency at the u parameter tangency can be constrained so when setting the tangency, you're constrainting it in fact ''' self._curvature.SetParameter(u) if self._curvature.IsTangentDefined(): ddd = gp_Dir() self._curvature.Tangent(ddd) return ddd else: raise ValueError('no tangent defined')
def isFaceAtZLevel(zLevel,face): bf = BRepGProp.BRepGProp_Face(face); bounds = bf.Bounds(); vec = gp.gp_Vec(); zDir = gp.gp().DZ(); pt = gp.gp_Pnt(); #get a normal vector to the face bf.Normal(bounds[0],bounds[1],pt,vec); z=pt.Z(); sDir = gp.gp_Dir(vec); return (abs(z - zLevel) < 0.0001 ) and ( zDir.IsParallel(sDir,0.0001))
def test_handling_exceptions(self): """ asserts that handling of OCC exceptions is handled correctly in pythonocc See Also -------- issue #259 -- Standard errors like Standard_OutOfRange not caught """ d = gp_Dir(0, 0, 1) with self.assertRaises(RuntimeError): d.Coord(-1) # Standard_OutOfRange
def DisplayVector(self, vec, pnt, update=False): if self._inited: aPresentation = Prs3d_Presentation(self._struc_mgr) arrow = Prs3d_Arrow() arrow.Draw( aPresentation.GetHandle(), (pnt.as_vec() + vec).as_pnt(), gp_Dir(vec), math.radians(20), vec.Magnitude() ) aPresentation.Display() # it would be more coherent if a AIS_InteractiveObject # would be returned if update: self.Repaint() return aPresentation
def makeKeyHoleWire(): circle2 = gp.gp_Circ(gp.gp_Ax2(gp.gp_Pnt(40,40,2),gp.gp_Dir(0,0,1)),10) Edge4 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(circle2,gp.gp_Pnt(40,50,2),gp.gp_Pnt(50,40,2)).Edge() ExistingWire2 = BRepBuilderAPI.BRepBuilderAPI_MakeWire(Edge4).Wire() P1 = gp.gp_Pnt(50,40,2) P2 = gp.gp_Pnt(80,40,2) #5,204,0 Edge5 = BRepBuilderAPI.BRepBuilderAPI_MakeEdge(P1,P2).Edge() MW = BRepBuilderAPI.BRepBuilderAPI_MakeWire() MW.Add(Edge5) MW.Add(ExistingWire2) if MW.IsDone(): WhiteWire = MW.Wire() return [WhiteWire,Edge5,ExistingWire2];
def _cut_finger_notch(front, dx, dz): finger_width = 2.0 finger_height = 1.0 front = _cut(front, _box(_pnt(dx / 2. - finger_width / 2., 0, dz - finger_height), finger_width, THICKNESS_0, finger_height)) cyl = BRepPrimAPI_MakeCylinder(finger_width / 2.0, THICKNESS_0).Shape() tr = gp.gp_Trsf() tr.SetRotation(gp.gp_Ax1(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(1, 0, 0)), math.pi / 2.0) tr2 = gp.gp_Trsf() tr2.SetTranslation(gp.gp_Vec(dx / 2., THICKNESS_0, dz - finger_height)) tr2.Multiply(tr) cyl = BRepBuilderAPI_Transform(cyl, tr2, True).Shape() front = _cut(front, cyl) return front
def normal(self, u): '''returns the normal at u computes the main normal if no normal is found see: www.opencascade.org/org/forum/thread_645+&cd=10&hl=nl&ct=clnk&gl=nl ''' try: self._curvature.SetParameter(u) a_dir = gp_Dir() self._curvature.Normal(a_dir) return a_dir except: raise ValueError('no normal was found')
def mirror(self, **kwargs): """ params (one of): point def. mirror about point axis plane """ inValue=None if 'point' in kwargs: inValue = gp_Pnt(kwargs['point']) elif 'axis' in kwargs: inValue = gp_Ax1(gp_Pnt(*kwargs['axis'][:3]), gp_Dir(*kwargs['axis'][3:])) elif 'plane' in kwargs: inValue = gp_Ax2(gp_Pnt(*kwargs['axis'][:3]), gp_Dir(*kwargs['axis'][3:])) else: print "Warning: mirror could not be done becase there was no parameters specified" return self tr = gp_Trsf() tr.SetMirror(inValue) self.shape = BRepBuilderAPI_Transform(self.shape, tr).Shape() self.__extract_curves() return self
def draft_angle(event=None): S = BRepPrimAPI_MakeBox(200., 300., 150.).Shape() adraft = BRepOffsetAPI_DraftAngle(S) topExp = TopExp_Explorer() topExp.Init(S, TopAbs_FACE) while topExp.More(): face = topods_Face(topExp.Current()) surf = Handle_Geom_Plane_DownCast(BRep_Tool_Surface(face)).GetObject() dirf = surf.Pln().Axis().Direction() ddd = gp_Dir(0, 0, 1) if dirf.IsNormal(ddd, precision_Angular()): adraft.Add(face, ddd, math.radians(15), gp_Pln(gp_Ax3(gp_XOY()))) topExp.Next() adraft.Build() display.DisplayShape(adraft.Shape(), update=True)