Example #1
0
      def getShape(self, pos, rotation) :
          import cadquery as cq
          from OCC.Core.gp import gp_Ax2, gp_Pnt, gp_Dir
          from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeCylinder
          from OCC.Core.BRepAlgoAPI import BRepAlgoAPI_Cut

          print("Get Shape gTube")
          x = pos[0]
          y = pos[1]
          z = pos[2]
          tube1 = BRepPrimAPI_MakeCylinder(gp_Ax2(gp_Pnt(x,y,z), \
                  gp_Dir(0, 0, 1)),\
                  self.Radius[1], self.Z).Shape()
          if self.Radius[0] != 0 :
             tube2 = BRepPrimAPI_MakeCylinder(gp_Ax2(gp_Pnt(x,y,z), \
                     gp_Dir(0, 0, 1)),\
                     self.Radius[0], self.Z).Shape()
             tube1 = BRepAlgoAPI_Cut(tube1, tube2).Shape()
          if self.Sector.completeRev() == False :
             print("Need to section")
             if self.Sector.less90() == True :
                print("Common")
                shape = self.Sector.makeCommon(self.Radius[1], self.Z, tube1) 
             else :
                print("Cut") 
                shape = self.Sector.makeCut(self.Radius[1], self.Z, tube1)
             if self.Sector.getStart() == 0 :
                return shape
             else :
                return self.Sector.rotate(shape)
          else : 
             return tube1 
Example #2
0
def axs_curvature(h_surf, u=0, v=0):
    prop = GeomLProp_SLProps(2, 0.01)
    prop.SetSurface(h_surf)
    prop.SetParameters(u, v)

    d1, d2 = gp_Dir(), gp_Dir()
    prop.CurvatureDirections(d1, d2)
    vz = dir_to_vec(prop.Normal())
    v1 = dir_to_vec(d1)
    v2 = dir_to_vec(d2)
    c1 = prop.MaxCurvature()
    c2 = prop.MinCurvature()

    if c1 == 0:
        r1 = 0
    else:
        r1 = 1 / c1

    if c2 == 0:
        r2 = 0
    else:
        r2 = 1 / c2

    print("Max", c1, r1, v1)
    print("Min", c2, r1, v2)
    print(v1.Dot(v2))
    print(prop.Value())
    return vz, v1, v2, r1, r2
Example #3
0
      def getShape(self, pos, rotation) :
          import cadquery as cq
          from OCC.Core.gp import gp_Ax2, gp_Pnt, gp_Dir
          from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeCone
          from OCC.Core.BRepAlgoAPI import BRepAlgoAPI_Cut

          print("Get Shape gCone")
          x = pos[0]
          y = pos[1]
          z = pos[2]
          cone1 = BRepPrimAPI_MakeCone(gp_Ax2(gp_Pnt(x,y,z), \
                  gp_Dir(0, 0, 1)),\
                  self.R1[1], self.R2[1], self.Z).Shape()
          if (self.R1[0] != 0 or self.R2[0] != 0 ) :
             cone2 = BRepPrimAPI_MakeCone(gp_Ax2(gp_Pnt(x,y,z), \
                  gp_Dir(0, 0, 1)),\
                  self.R1[0], self.R2[0], self.Z).Shape()
             cone1 = BRepAlgoAPI_Cut(cone1, cone2).Shape()
          if self.Sector != None :
             if self.Sector.completeRev() == False :
                print("Need to section")
                if self.Sector.less90() == True :
                   print("Common")
                   shape = self.Sector.makeCommon(self.R1[1], self.Z, cone1) 
                else :
                   print("Cut") 
                   shape = self.Sector.makeCut(self.R1[1], self.Z, cone1)
                if self.Sector.getStart() == 0 :
                   return shape
                else :
                   return self.Sector.rotate(shape)
          print("Cone Shape")
          print(cone1)
          return(cone1)
Example #4
0
    def rotate(self, x=0.0, y=0.0, z=0.0):
        trsf = gp_Trsf()
        if (x != 0.0):
            axx = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(1., 0., 0.))
            a_trsf1 = gp_Trsf()
            a_trsf1.SetRotation(axx, math.radians(x))
            #trsf = trsf*a_trsf1
            trsf = a_trsf1 * trsf

        if (y != 0.0):
            axy = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 1., 0.))
            a_trsf2 = gp_Trsf()
            a_trsf2.SetRotation(axy, math.radians(y))
            #trsf = trsf*a_trsf2
            trsf = a_trsf2 * trsf

        if (z != 0.0):
            axz = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 0., 1.))
            a_trsf3 = gp_Trsf()
            a_trsf3.SetRotation(axz, math.radians(z))
            #trsf = trsf*a_trsf3
            trsf = a_trsf3 * trsf

        for c in self.children:
            c.propagate_trsf(trsf)
Example #5
0
    def __init__(self):
        plotocc.__init__(self)
        axs = gp_Ax3(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1))
        shp = self.make_PolyWire(num=15, skin=None, axs=axs)
        self.export_stp(shp)
        print(shp, shp.Location().Transformation())
        loc = shp.Location()
        loc_inv = loc.Inverted()
        shp.Located(loc_inv)
        print(shp, shp.Location().Transformation())
        self.export_stp(shp)

        axs = gp_Ax3(gp_Pnt(0, 0, 1), gp_Dir(0, 0, 1))
        shp = self.make_PolyWire(num=15, skin=0, axs=axs)
        print(shp, shp.Location().Transformation())

        axs = gp_Ax3(gp_Pnt(0, 0, 3), gp_Dir(0, 0, 1))
        shp = self.make_StarWire(num=15, skin=1, axs=axs, radi=[1.1, 1.0])
        print(shp, shp.Location().Transformation())

        axs = gp_Ax3(gp_Pnt(0, 0, 5), gp_Dir(0, 1, 1))
        shp = self.make_StarWire(num=15, skin=0, axs=axs, radi=[0.9, 1.0])
        print(shp, shp.Location())

        self.export_stp(shp)
        print(shp)
        loc = shp.Location()
        loc_inv = loc.Inverted()
        shp = shp.Located(loc_inv)
        print(loc.Transformation())
        print(loc_inv.Transformation())
        self.export_stp(shp.Reversed())
Example #6
0
def wpBy3Pts(*args):
    """Direction from pt1 to pt2 sets wDir, pt2 is wpOrigin.
    Direction from pt2 to pt3 sets uDir."""
    prev_uid = win.activeWpUID  # uid of currently active workplane
    if win.ptStack:
        # Finish
        p3 = win.ptStack.pop()
        p2 = win.ptStack.pop()
        p1 = win.ptStack.pop()
        wVec = gp_Vec(p1, p2)
        wDir = gp_Dir(wVec)
        origin = p2
        uVec = gp_Vec(p2, p3)
        uDir = gp_Dir(uVec)
        axis3 = gp_Ax3(origin, wDir, uDir)
        wp = workplane.WorkPlane(100, ax3=axis3)
        new_uid = win.get_wp_uid(wp)
        display_new_active_wp(prev_uid, new_uid)
        win.clearCallback()
    else:
        # Initial setup
        win.registerCallback(wpBy3PtsC)
        display.selected_shape = None
        display.SetSelectionModeVertex()
        statusText = "Pick 3 points. Dir from pt1-pt2 sets wDir, pt2 is origin."
        win.statusBar().showMessage(statusText)
        return
    def create_section_box(self):
        top_left_corner = gp.gp_Pnt(
            self.section_box["top_left_corner"][0],
            self.section_box["top_left_corner"][1],
            self.section_box["top_left_corner"][2],
        )
        axis = gp.gp_Ax2(
            top_left_corner,
            gp.gp_Dir(
                self.section_box["projection"][0], self.section_box["projection"][1], self.section_box["projection"][2]
            ),
            gp.gp_Dir(self.section_box["x_axis"][0], self.section_box["x_axis"][1], self.section_box["x_axis"][2]),
        )
        section_box = BRepPrimAPI.BRepPrimAPI_MakeBox(
            axis, self.section_box["x"], self.section_box["y"], self.section_box["z"]
        )
        self.section_box["shape"] = section_box.Shape()
        self.section_box["face"] = section_box.BottomFace()

        source = gp.gp_Ax3(axis)
        self.transformation_data = {
            "top_left_corner": self.section_box["top_left_corner"],
            "projection": self.section_box["projection"],
            "x_axis": self.section_box["x_axis"],
        }
        destination = gp.gp_Ax3(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(0, 0, -1), gp.gp_Dir(1, 0, 0))
        self.transformation_dest = destination
        self.transformation = gp.gp_Trsf()
        self.transformation.SetDisplacement(source, destination)
Example #8
0
    def create_section_box(self):
        top_left_corner = gp.gp_Pnt(self.section_box['top_left_corner'][0],
                                    self.section_box['top_left_corner'][1],
                                    self.section_box['top_left_corner'][2])
        axis = gp.gp_Ax2(
            top_left_corner,
            gp.gp_Dir(self.section_box['projection'][0],
                      self.section_box['projection'][1],
                      self.section_box['projection'][2]),
            gp.gp_Dir(self.section_box['x_axis'][0],
                      self.section_box['x_axis'][1],
                      self.section_box['x_axis'][2]))
        section_box = BRepPrimAPI.BRepPrimAPI_MakeBox(axis,
                                                      self.section_box['x'],
                                                      self.section_box['y'],
                                                      self.section_box['z'])
        self.section_box['shape'] = section_box.Shape()
        self.section_box['face'] = section_box.BottomFace()

        source = gp.gp_Ax3(axis)
        self.transformation_data = {
            'top_left_corner': self.section_box['top_left_corner'],
            'projection': self.section_box['projection'],
            'x_axis': self.section_box['x_axis']
        }
        destination = gp.gp_Ax3(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(0, 0, -1),
                                gp.gp_Dir(1, 0, 0))
        self.transformation_dest = destination
        self.transformation = gp.gp_Trsf()
        self.transformation.SetDisplacement(source, destination)
 def slice_selected_surfaces(nozz_dia, direc):
     slices = []
     counter1 = 0
     edge_clearance = nozz_dia / 2
     xmin, ymin, zzz, xmax, ymax, zzz =\
      Slicing.get_surfaces_boundingbox(surfaces)
     new_surfaces = Slicing.sort_surfaces(surfaces, direc)
     if direc == 'X':
         imin = xmin
         imax = xmax
     elif direc == 'Y':
         imin = ymin
         imax = ymax
     for i in numpy.arange(imin+edge_clearance, imax-edge_clearance+nozz_dia/2, \
      nozz_dia):
         if direc == 'X':
             plane = gp_Pln(gp_Pnt(i, 0., 0), gp_Dir(1., 0., 0.))
         elif direc == 'Y':
             plane = gp_Pln(gp_Pnt(0., i, 0), gp_Dir(0., 1., 0.))
         face = BRepBuilderAPI_MakeFace(plane).Face()
         slices.append([])
         for surface in new_surfaces:
             slices[counter1].extend(Slicing.plane_shape_intersection(face,\
              surface))
         counter1 = counter1 + 1
     return slices
Example #10
0
    def _axis(self, size):

        style = self._axisStyle()

        step = size / 10
        ss = [1, 5, 10, 50, 100, 500, 1000, 5000, 10000]
        for s in ss:
            if step < s:
                step = s / 5
                break

        pnt = gp_Pnt(0, 0, 0)
        dir1 = gp_Dir(gp_Vec(0, 0, 1))
        dir2 = gp_Dir(gp_Vec(1, 0, 0))
        geomAxis = Geom_Axis2Placement(pnt, dir1, dir2)

        trih = AIS_Trihedron(geomAxis)
        trih.SetSize(size)

        self._drawAis(trih, style)

        self._drawPoint(gp_Pnt(0, 0, 0), style)

        cnt = int(size // step)
        for i in range(1, cnt):
            d = i * step
            self._drawPoint(gp_Pnt(d, 0, 0), style)
            self._drawPoint(gp_Pnt(0, d, 0), style)
            self._drawPoint(gp_Pnt(0, 0, d), style)
Example #11
0
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)

    # 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
    drawer = Prs3d_Drawer()
    ais_line1.SetAttributes(drawer)

    display.Context.Display(ais_line1, 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)

        width = float(i)
        drawer = ais_line2.Attributes()
        # asp : first parameter color, second type, last width
        asp = Prs3d_LineAspect(9 * i, i, width)
        drawer.SetLineAspect(asp)
        ais_line2.SetAttributes(drawer)

        display.Context.Display(ais_line2, False)
    start_display()
Example #12
0
    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
Example #13
0
def New_shp(Xmax, Xmin, Ymax, Ymin, Zmax, Zmin, X, Y, Z):
    Index = random.randint(1, 4)
    position = cal_position(Xmax, Xmin, Ymax, Ymin, Zmax, Zmin)
    A = (X + Y + Z) / 5
    if Index == 1:
        X1 = random.uniform(0.5 * A, A)
        Y1 = random.uniform(0.5 * A, A)
        Z1 = random.uniform(0.5 * A, A)
        nshp = BRepPrimAPI_MakeBox(
            gp_Pnt(-0.5 * X1 + position[0], -0.5 * Y1 + position[1],
                   -0.5 * Z1 + position[2]), X1, Y1, Z1).Shape()
    if Index == 2:

        R = random.uniform(0.25 * A, 0.5 * A)
        nshp = BRepPrimAPI_MakeSphere(
            gp_Pnt(position[0], position[1], position[2]), R).Shape()
    if Index == 3:
        R2 = random.uniform(0.25 * A, 0.5 * A)
        H = random.uniform(0.5 * A, A)
        origin = gp_Ax2(
            gp_Pnt(position[0], position[1], -0.5 * H + position[2]),
            gp_Dir(0.0, 0.0, 1.0))
        nshp = BRepPrimAPI_MakeCone(origin, R2, 0, H).Shape()
    if Index == 4:

        R = random.uniform(0.25 * A, 0.5 * A)
        H = random.uniform(0.5 * A, A)
        cylinder_origin = gp_Ax2(
            gp_Pnt(position[0], position[1], -0.5 * H + position[2]),
            gp_Dir(0.0, 0.0, 1.0))
        nshp = BRepPrimAPI_MakeCylinder(cylinder_origin, R, H).Shape()
    return nshp
Example #14
0
def euler_to_gp_trsf(euler_zxz=None, unit="deg"):
    """
    returns a rotation-only gp_Trsf given Euler angles

    :param euler_zxz: a list of three intrinsic Euler angles
                      in zxz-convention
    :param unit: If "deg", the euler angles are in degrees,
                 otherwise radians

    :return: A rotation-only gp_Trsf
    """

    if euler_zxz is None:
        euler_zxz = [0, 0, 0]
    if unit == "deg":  # convert angle to radians
        euler_zxz = [radians(a) for a in euler_zxz]

    x = gp_Ax1(gp_Pnt(), gp_Dir(1, 0, 0))
    z = gp_Ax1(gp_Pnt(), gp_Dir(0, 0, 1))

    trns = gp_Trsf()
    trns.SetRotation(z, euler_zxz[2])

    trns_next = gp_Trsf()
    trns_next.SetRotation(x, euler_zxz[1])

    trns = trns *trns_next

    trns_next = gp_Trsf()
    trns_next.SetRotation(z, euler_zxz[0])

    return trns *trns_next
Example #15
0
def wpBy3Pts(*args):
    """Direction from pt1 to pt2 sets wDir, pt2 is wpOrigin.
    Direction from pt2 to pt3 sets uDir."""
    if win.ptStack:
        # Finish
        p3 = win.ptStack.pop()
        p2 = win.ptStack.pop()
        p1 = win.ptStack.pop()
        wVec = gp_Vec(p1, p2)
        wDir = gp_Dir(wVec)
        origin = p2
        uVec = gp_Vec(p2, p3)
        uDir = gp_Dir(uVec)
        axis3 = gp_Ax3(origin, wDir, uDir)
        wp = workplane.WorkPlane(100, ax3=axis3)
        win.getNewPartUID(wp, typ='w')
        win.clearCallback()
        statusText = "Workplane created."
        win.statusBar().showMessage(statusText)
    else:
        # Initial setup
        win.registerCallback(wpBy3PtsC)
        display.selected_shape = None
        display.SetSelectionModeVertex()
        statusText = "Pick 3 points. Dir from pt1-pt2 sets wDir, pt2 is origin."
        win.statusBar().showMessage(statusText)
        return
Example #16
0
  def generate_tool_targets(self):
    ba = BRepAdaptor_Curve(self.helix_edge)
    u_min = ba.FirstParameter()
    u_max = ba.LastParameter()
    u_step = 0.1
    u_now = u_min
    while u_now <= u_max:
      v_contact = gp_Vec(ba.Value(u_now).XYZ())
      if self.inside: # cut inside
        v_contact_to_ball_center = -gp_Vec(v_contact.X(),v_contact.Y(),0).Normalized()*self.ball_radius
      else: # cut outside
        v_contact_to_ball_center =  gp_Vec(v_contact.X(),v_contact.Y(),0).Normalized()*self.ball_radius
      trsf = gp_Trsf()
      trsf.SetRotation(gp_Ax1(gp_Pnt(0,0,0),gp_Dir(0,0,1)),pi/2)
      v_rotation_axis = v_contact_to_ball_center.Transformed(trsf)
      trsf.SetRotation(gp_Ax1(gp_Pnt(0,0,0),gp_Dir(v_rotation_axis.XYZ())),radians(self.cutting_angle))
      v_ball_center_to_tool_tip = gp_Vec(0,0,-self.ball_radius)
      v_ball_center_to_tool_tip.Transform(trsf)
      v_tool_tip = v_contact+v_contact_to_ball_center+v_ball_center_to_tool_tip
      v_tool_orientation = - v_ball_center_to_tool_tip.Normalized() * (0.500+1e-8)

      if self.create_target_vis_edges:
        me = BRepBuilderAPI_MakeEdge(gp_Pnt(v_tool_tip.XYZ()),gp_Pnt((v_tool_tip+v_tool_orientation).XYZ()))
        self.target_edges.append(me.Edge())

      I = v_tool_tip.X() / 1000
      J = v_tool_tip.Y() / 1000
      K = v_tool_tip.Z() / 1000

      U = v_tool_orientation.X()
      V = v_tool_orientation.Y()
      W = v_tool_orientation.Z()


      x,y,z,a,b = self.ikSolver.solve((I,J,K,U,V,W),1e-6,False)

      x += self.output_offset[0]
      y += self.output_offset[1]
      z += self.output_offset[2]
      a += self.output_offset[3]
      b += self.output_offset[4]

      if self.v_previous_contact_point:
        cut_distance = (v_contact - self.v_previous_contact_point).Magnitude()
        f = self.feedrate / cut_distance
        self.gcode += "G01 X{:.6f} Y{:.6f} Z{:.6f} A{:.6f} B{:.6f} F{:.6f}\n".format(x,y,z,a,b,f)
      else:
        f = 0
        self.gcode += "G0 X{:.6f} Y{:.6f} Z{:.6f} A{:.6f} B{:.6f}\n".format(x,y,z,a,b)
      self.v_previous_contact_point = v_contact

      print(x,y,z,a,b)

      if u_now == u_max:
        break
      u_next = u_now + u_step
      if u_next > u_max:
        u_next = u_max
      u_now = u_next
Example #17
0
 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
Example #18
0
    def test_constructor(self):
        self.assertEqual(point3(0, 0, 1), point3(gp_Dir(0, 0, 1)))
        self.assertEqual(point3(0, 1, 1), point3(gp_Vec(0, 1, 1)))
        self.assertEqual(point3(1, 0, 1), point3(gp_Pnt(1, 0, 1)))

        self.assertEqual(vector3(0, 0, 1), vector3(gp_Dir(0, 0, 1)))
        self.assertEqual(vector3(0, 1, 1), vector3(gp_Vec(0, 1, 1)))
        self.assertEqual(vector3(1, 0, 1), vector3(gp_Pnt(1, 0, 1)))
Example #19
0
    def set_orient1(self):

        self._display.View.Camera().SetDirection(gp_Dir(
            math.cos(self.pitch) * math.cos(self.yaw),
            math.cos(self.pitch) * math.sin(self.yaw),
            math.sin(self.pitch)
        ))
        self._display.View.Camera().SetUp(gp_Dir(0, 0, 1))
Example #20
0
 def _to_occ(self) -> BRepPrimAPI_MakeBox:
     xaxis = self.frame.xaxis.scaled(-0.5 * self.xsize)
     yaxis = self.frame.yaxis.scaled(-0.5 * self.ysize)
     zaxis = self.frame.zaxis.scaled(-0.5 * self.zsize)
     frame = self.frame.transformed(
         Translation.from_vector(xaxis + yaxis + zaxis))
     ax2 = gp_Ax2(gp_Pnt(*frame.point), gp_Dir(*frame.zaxis),
                  gp_Dir(*frame.xaxis))
     return BRepPrimAPI_MakeBox(ax2, self.xsize, self.ysize, self.zsize)
Example #21
0
    def drawTrihedron(self, objName, size):
        gpPnt = gp_Pnt(0, 0, 0)
        gpDir1 = gp_Dir(gp_Vec(0, 0, 1))
        gpDir2 = gp_Dir(gp_Vec(1, 0, 0))
        geomAxis = Geom_Axis2Placement(gpPnt, gpDir1, gpDir2)

        trih = AIS_Trihedron(geomAxis)
        trih.SetSize(11)

        self._drawNative(objName, trih)
Example #22
0
 def make_axis_triedron(self):
     self.x_axis = AIS_Axis(
         Geom_Line(gp_Lin(gp_Pnt(0, 0, 0), gp_Dir(gp_XYZ(1, 0, 0)))))
     self.y_axis = AIS_Axis(
         Geom_Line(gp_Lin(gp_Pnt(0, 0, 0), gp_Dir(gp_XYZ(0, 1, 0)))))
     self.z_axis = AIS_Axis(
         Geom_Line(gp_Lin(gp_Pnt(0, 0, 0), gp_Dir(gp_XYZ(0, 0, 1)))))
     self.x_axis.SetColor(Quantity_Color(1, 0, 0, Quantity_TOC_RGB))
     self.y_axis.SetColor(Quantity_Color(0, 1, 0, Quantity_TOC_RGB))
     self.z_axis.SetColor(Quantity_Color(0, 0, 1, Quantity_TOC_RGB))
Example #23
0
    def __init__(self, size, face=None, faceU=None, ax3=None):
        # gp_Ax3 of XYZ coord system
        origin = gp_Pnt(0, 0, 0)
        wDir = gp_Dir(0, 0, 1)
        uDir = gp_Dir(1, 0, 0)
        vDir = gp_Dir(0, 1, 0)
        xyzAx3 = gp_Ax3(origin, wDir, uDir)
        if (not face and not ax3):  # create default wp (in XY plane at 0,0,0)
            axis3 = xyzAx3
            gpPlane = gp_Pln(xyzAx3)
            self.gpPlane = gpPlane  # type: gp_Pln
            self.plane = Geom_Plane(gpPlane)  # type: Geom_Plane
        elif face:  # create workplane on face, uDir defined by faceU
            wDir = face_normal(face)  # from OCCUtils.Construct module
            props = GProp_GProps()
            brepgprop_SurfaceProperties(face, props)
            origin = props.CentreOfMass()
            '''
            surface = BRep_Tool_Surface(face) # type: Handle_Geom_Surface
            plane = Handle_Geom_Plane.DownCast(surface).GetObject() # type: Geom_Plane
            gpPlane = plane.Pln() # type: gp_Pln
            origin = gpPlane.Location() # type: gp_Pnt
            '''
            uDir = face_normal(faceU)  # from OCCUtils.Construct module
            axis3 = gp_Ax3(origin, wDir, uDir)
            vDir = axis3.YDirection()
            self.gpPlane = gp_Pln(axis3)
            self.plane = Geom_Plane(self.gpPlane)  # type: Geom_Plane
        elif ax3:
            axis3 = ax3
            uDir = axis3.XDirection()
            vDir = axis3.YDirection()
            wDir = axis3.Axis().Direction()
            origin = axis3.Location()
            self.gpPlane = gp_Pln(axis3)
            self.plane = Geom_Plane(self.gpPlane)  # type: Geom_Plane

        self.Trsf = gp_Trsf()
        self.Trsf.SetTransformation(axis3)
        self.Trsf.Invert()
        self.origin = origin
        self.uDir = uDir
        self.vDir = vDir
        self.wDir = wDir
        self.face = face
        self.size = size
        self.border = self.makeWpBorder(self.size)
        self.clList = []  # List of 'native' construction lines
        self.clineList = []  # List of pyOCC construction lines
        self.ccircList = []  # List of pyOCC construction circles
        self.wireList = []  # List of pyOCC wires
        self.wire = None
        self.hvcl((0, 0))  # Make H-V clines through origin
        self.accuracy = 0.001  # min distance between two points
Example #24
0
def get_axs(filename, ax=gp_Ax3()):
    dat = np.loadtxt(filename, skiprows=2)
    pnt = gp_Pnt(*dat[0])
    d_x = gp_Dir(*dat[1])
    d_y = gp_Dir(*dat[2])
    d_z = d_x.Crossed(d_y)
    axs = gp_Ax3(pnt, d_z, d_x)
    trf = gp_Trsf()
    trf.SetTransformation(ax, gp_Ax3())
    axs.Transform(trf)
    return axs
Example #25
0
 def read_file(self, axs=gp_Ax3(), name=None, filename="pln.cor"):
     if name == None:
         name = self.name
     dat = np.loadtxt(filename, skiprows=2)
     pnt = gp_Pnt(*dat[0])
     d_x = gp_Dir(*dat[1])
     d_y = gp_Dir(*dat[2])
     d_z = d_x.Crossed(d_y)
     trf = gp_Trsf()
     trf.SetTransformation(axs, gp_Ax3())
     self.axis = gp_Ax3(pnt, d_z, d_x)
     self.axis.Transform(trf)
Example #26
0
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)
Example #27
0
    def gen_through(self):
        obj = BRepOffsetAPI_ThruSections()

        ax2_1 = gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1))
        crl_1 = gp_Circ(ax2_1, 100)
        obj.AddWire(crl_1)

        ax2_2 = gp_Ax2(gp_Pnt(0, 0, 100), gp_Dir(0, 0, 1))
        crl_2 = gp_Circ(ax2_2, 200)
        obj.AddWire(crl_2)

        obj.Build()
        self.display.DisplayShape(obj.Shape())
Example #28
0
 def MultiRay(self,
              rght=[-10, 0],
              left=[10, 0],
              uppr=[0, 10],
              bott=[0, -10]):
     ax_rght = gp_Ax3(gp_Pnt(*rght, 0), gp_Dir(0, 0, 1))
     ax_left = gp_Ax3(gp_Pnt(*left, 0), gp_Dir(0, 0, 1))
     ax_uppr = gp_Ax3(gp_Pnt(*uppr, 0), gp_Dir(0, 0, 1))
     ax_bott = gp_Ax3(gp_Pnt(*bott, 0), gp_Dir(0, 0, 1))
     self.beam_rght = self.Move_Axs(self.beam, gp_Ax3(), ax_rght)
     self.beam_left = self.Move_Axs(self.beam, gp_Ax3(), ax_left)
     self.beam_uppr = self.Move_Axs(self.beam, gp_Ax3(), ax_uppr)
     self.beam_bott = self.Move_Axs(self.beam, gp_Ax3(), ax_bott)
Example #29
0
    def __init__(self):
        plotocc.__init__(self)
        self.b1 = gen_ellipsoid(axs=gp_Ax3(
            gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)), rxyz=[100, 100, 105])
        self.b2 = gen_ellipsoid(axs=gp_Ax3(
            gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)), rxyz=[210, 210, 210])

        self.base = BRepAlgoAPI_Cut(self.b2, self.b1).Shape()
        self.beam = gp_Ax3(gp_Pnt(0, 150, 0), gp_Dir(1, 1.5, 0))
        print(self.b1)

        top = Topo(self.base)
        print(top.number_of_faces())
Example #30
0
def get_oriented_boundingbox_ratio(shape, optimal_OBB=True, ratio=1.0):
    """ return the oriented bounding box of the TopoDS_Shape `shape`

    Parameters
    ----------

    shape : TopoDS_Shape or a subclass such as TopoDS_Face
        the shape to compute the bounding box from

    optimal_OBB : bool, True by default. If set to True, compute the
        optimal (i.e. the smallest oriented bounding box). 
        Optimal OBB is a bit longer.

    ratio : float, 1.0 by default.

    Returns
    -------
        a list with center, x, y and z sizes

        a shape
    """
    obb = Bnd_OBB()
    if optimal_OBB:
        is_triangulationUsed = True
        is_optimal = True
        is_shapeToleranceUsed = False
        brepbndlib_AddOBB(shape, obb, is_triangulationUsed, is_optimal,
                          is_shapeToleranceUsed)
    else:
        brepbndlib_AddOBB(shape, obb)

    # converts the bounding box to a shape
    aBaryCenter = obb.Center()
    aXDir = obb.XDirection()
    aYDir = obb.YDirection()
    aZDir = obb.ZDirection()
    aHalfX = obb.XHSize()
    aHalfY = obb.YHSize()
    aHalfZ = obb.ZHSize()
    dx = aHalfX * ratio
    dy = aHalfY * ratio
    dz = aHalfZ * ratio

    ax = gp_XYZ(aXDir.X(), aXDir.Y(), aXDir.Z())
    ay = gp_XYZ(aYDir.X(), aYDir.Y(), aYDir.Z())
    az = gp_XYZ(aZDir.X(), aZDir.Y(), aZDir.Z())
    p = gp_Pnt(aBaryCenter.X(), aBaryCenter.Y(), aBaryCenter.Z())
    anAxes = gp_Ax2(p, gp_Dir(aZDir), gp_Dir(aXDir))
    anAxes.SetLocation(gp_Pnt(p.XYZ() - ax * dx - ay * dy - az * dz))
    aBox = BRepPrimAPI_MakeBox(anAxes, 2.0 * dx, 2.0 * dy, 2.0 * dz).Shape()
    return aBaryCenter, [dx, dy, dz], aBox
    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 test_hash_eq_operator(self):
     ''' test that the == wrapper is ok
     '''
     # test Standard
     s = Standard_Transient()
     s2 = Standard_Transient()
     self.assertFalse(s == s2)
     self.assertTrue(s == s)
     # test list.index, that uses __eq__ method
     p1 = gp_Pnt(0., 0., 0.)
     line = gp_Lin(p1, gp_Dir(1., 0., 0.))
     items = [p1, line]
     res = items.index(line)
     self.assertEqual(res, 1.)
 def test_shape_conversion_as_py_none(self):
     # see issue #600 and PR #614
     # a null topods_shape should be returned as Py_None by the TopoDS transformer
     # the following test case returns a null topods_shape
     box = BRepPrimAPI_MakeBox(1., 1., 1.).Shape()
     hlr = HLRBRep_Algo()
     hlr.Add(box)
     projector = HLRAlgo_Projector(gp_Ax2(gp_Pnt(), gp_Dir(-1.75, 1.1, 5)))
     hlr.Projector(projector)
     hlr.Update()
     hlr.Hide()
     hlr_shapes = HLRBRep_HLRToShape(hlr)
     visible_smooth_edges = hlr_shapes.Rg1LineVCompound()
     self.assertTrue(visible_smooth_edges is None)
    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)
        # testing exception segfaults on osx travis
        # TODO : check why
        if not os.getenv('TRAVIS_OS_NAME') == "osx":
            with self.assertRaises(RuntimeError):
                d.Coord(-1)  # Standard_OutOfRange
 def test_axis(self):
     '''Test: axis'''
     P1 = gp_Pnt(2, 3, 4)
     D = gp_Dir(4, 5, 6)
     A = gp_Ax3(P1, D)
     IsDirectA = A.Direct()
     self.assertTrue(IsDirectA)
     AXDirection = A.XDirection()
     self.assertIsInstance(AXDirection, gp_Dir)
     AYDirection = A.YDirection()
     self.assertIsInstance(AXDirection, gp_Dir)
     P2 = gp_Pnt(5, 3, 4)
     A2 = gp_Ax3(P2, D)
     A2.YReverse()
     # axis3 is now left handed
     IsDirectA2 = A2.Direct()
     self.assertFalse(IsDirectA2)
     A2XDirection = A2.XDirection()
     self.assertTrue(isinstance(A2XDirection, gp_Dir))
     A2YDirection = A2.YDirection()
     self.assertTrue(isinstance(A2YDirection, gp_Dir))
Example #36
0
    def DisplayVector(self, vec, pnt, update=False):
        """ displays a vector as an arrow
        """
        if self._inited:
            aPresentation = Prs3d_Presentation(self._struc_mgr)

            pnt_as_vec = gp_Vec(pnt.X(), pnt.Y(), pnt.Z())
            start = pnt_as_vec + vec
            pnt_start = gp_Pnt(start.X(), start.Y(), start.Z())

            Prs3d_Arrow.Draw(
                aPresentation.GetHandle(),
                pnt_start,
                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