def rotate(event=None):
    display.EraseAll()
    origin = gp_Vec(0, 0, 0)
    origin_pt = as_pnt(origin)

    vX = gp_Vec(12, 0, 0)
    vY = gp_Vec(0, 12, 0)
    v45 = (gp_Vec(1, 1, 1).Normalized() * 12)
    q1 = gp_Quaternion(vX, vY)

    p1 = as_pnt(origin + vX)
    p2 = as_pnt(origin + vY)
    p3 = as_pnt(origin + (q1 * vY))
    p4 = as_pnt(origin + (q1 * v45))

    # RED
    e1 = make_edge(origin_pt, p1)
    e2 = make_edge(origin_pt, p2)
    e3 = make_edge(origin_pt, as_pnt(v45))
    # GREEN -> transformed
    e4 = make_edge(origin_pt, p3)
    e5 = make_edge(origin_pt, p4)

    display.DisplayShape([e1, e2, e3])
    display.DisplayColoredShape([e4, e5], 'GREEN')
    display.DisplayMessage(p1, 'e1')
    display.DisplayMessage(p2, 'e2')
    display.DisplayMessage(as_pnt(v45), 'e3')
    display.DisplayMessage(p3, 'q1*vY')
    display.DisplayMessage(p4, 'q1*v45')
    display.DisplayVector((q1 * vY).Normalized(), as_pnt(origin + q1 * vY / 2.))
    display.DisplayVector((q1 * v45).Normalized(), as_pnt(origin + q1 * v45 / 2.))
    display.FitAll()
Exemple #2
0
    def get_transform(self):
        d = self.declaration
        result = gp_Trsf()
        #: TODO: Order matters... how to configure it???
        if d.operations:
            for op in d.operations:
                t = gp_Trsf()
                if isinstance(op, Translate):
                    t.SetTranslation(gp_Vec(op.x, op.y, op.z))
                elif isinstance(op, Rotate):
                    t.SetRotation(
                        gp_Ax1(gp_Pnt(*op.point), gp_Dir(*op.direction)),
                        op.angle)
                elif isinstance(op, Mirror):
                    Ax = gp_Ax2 if op.plane else gp_Ax1
                    t.SetMirror(Ax(gp_Pnt(*op.point), gp_Dir(op.x, op.y,
                                                             op.z)))
                elif isinstance(op, Scale):
                    t.SetScale(gp_Pnt(*op.point), op.s)
                result.Multiply(t)
        else:
            axis = gp_Ax3()
            axis.SetDirection(d.direction.proxy)
            result.SetTransformation(axis)
            result.SetTranslationPart(gp_Vec(*d.position))
            if d.rotation:
                t = gp_Trsf()
                t.SetRotation(gp_Ax1(d.position.proxy, d.direction.proxy),
                              d.rotation)
                result.Multiply(t)

        return result
def midpoint(pntA, pntB):
    '''
    computes the point that lies in the middle between pntA and pntB
    @param pntA:    gp_Pnt
    @param pntB:    gp_Pnt
    '''
    vec1 = gp_Vec(pntA.XYZ())
    vec2 = gp_Vec(pntB.XYZ())
    veccie = (vec1+vec2)/2.
    return gp_Pnt(veccie.XYZ())
def make_plane(center=gp_Pnt(0, 0, 0),
               vec_normal=gp_Vec(0, 0, 1),
               extent_x_min=-100.,
               extent_x_max=100.,
               extent_y_min=-100.,
               extent_y_max=100.,
               depth=0.):
    if depth != 0:
        center = center.add_vec(gp_Vec(0, 0, depth))
    PL = gp_Pln(center, vec_normal.as_dir())
    face = make_face(PL, extent_x_min, extent_x_max, extent_y_min,
                     extent_y_max)
    return face
def surface_from_curves():
    '''
    @param display:
    '''
    # First spline
    array = []
    array.append(gp_Pnt(-4, 0, 2))
    array.append(gp_Pnt(-7, 2, 2))
    array.append(gp_Pnt(-6, 3, 1))
    array.append(gp_Pnt(-4, 3, -1))
    array.append(gp_Pnt(-3, 5, -2))

    pt_list1 = point_list_to_TColgp_Array1OfPnt(array)
    SPL1 = GeomAPI_PointsToBSpline(pt_list1).Curve()

    # Second spline
    a2 = []
    a2.append(gp_Pnt(-4, 0, 2))
    a2.append(gp_Pnt(-2, 2, 0))
    a2.append(gp_Pnt(2, 3, -1))
    a2.append(gp_Pnt(3, 7, -2))
    a2.append(gp_Pnt(4, 9, -1))
    pt_list2 = point_list_to_TColgp_Array1OfPnt(a2)
    SPL2 = GeomAPI_PointsToBSpline(pt_list2).Curve()

    # Fill with StretchStyle
    aGeomFill1 = GeomFill_BSplineCurves(SPL1,
                                        SPL2,
                                        GeomFill_StretchStyle)

    SPL3 = Geom_BSplineCurve.DownCast(SPL1.Translated(gp_Vec(10, 0, 0)))
    SPL4 = Geom_BSplineCurve.DownCast(SPL2.Translated(gp_Vec(10, 0, 0)))
    # Fill with CoonsStyle
    aGeomFill2 = GeomFill_BSplineCurves(SPL3,
                                        SPL4,
                                        GeomFill_CoonsStyle)
    SPL5 = Geom_BSplineCurve.DownCast(SPL1.Translated(gp_Vec(20, 0, 0)))
    SPL6 = Geom_BSplineCurve.DownCast(SPL2.Translated(gp_Vec(20, 0, 0)))
    # Fill with CurvedStyle
    aGeomFill3 = GeomFill_BSplineCurves(SPL5,
                                        SPL6,
                                        GeomFill_CurvedStyle)

    aBSplineSurface1 = aGeomFill1.Surface()
    aBSplineSurface2 = aGeomFill2.Surface()
    aBSplineSurface3 = aGeomFill3.Surface()
   
    display.DisplayShape(make_face(aBSplineSurface1, 1e-6))
    display.DisplayShape(make_face(aBSplineSurface2, 1e-6))
    display.DisplayShape(make_face(aBSplineSurface3, 1e-6), update=True)
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
Exemple #7
0
    def create_shape(self):
        d = self.declaration
        if not d.source:
            return
        if os.path.exists(os.path.expanduser(d.source)):
            svg = etree.parse(os.path.expanduser(d.source)).getroot()
        else:
            svg = etree.fromstring(d.source)
        node = OccSvgDoc(element=svg)

        builder = BRep_Builder()
        shape = TopoDS_Compound()
        builder.MakeCompound(shape)

        shapes = node.create_shape()
        for s in shapes:
            builder.Add(shape, s)

        bbox = self.get_bounding_box(shape)
        cx, cy = bbox.dx / 2, bbox.dy / 2

        # Move to position and align along direction axis
        t = gp_Trsf()
        axis = gp_Ax3()
        axis.SetDirection(d.direction.proxy)
        t.SetTransformation(axis)
        pos = d.position-(cx, cy, 0)
        t.SetTranslationPart(gp_Vec(*pos))

        self.shape = BRepBuilderAPI_Transform(shape, t, False).Shape()
def normal_vector_from_plane(plane, vec_length=1.):
    '''
    returns a vector normal to the plane of length vec_length
    @param plane:
    '''
    trns = gp_Vec(plane.Axis().Direction())
    return trns.Normalized() * vec_length
def prism():
    # the bspline profile
    array = TColgp_Array1OfPnt(1, 5)
    array.SetValue(1, gp_Pnt(0, 0, 0))
    array.SetValue(2, gp_Pnt(1, 2, 0))
    array.SetValue(3, gp_Pnt(2, 3, 0))
    array.SetValue(4, gp_Pnt(4, 3, 0))
    array.SetValue(5, gp_Pnt(5, 5, 0))
    bspline = GeomAPI_PointsToBSpline(array).Curve()
    profile = BRepBuilderAPI_MakeEdge(bspline).Edge()

    # the linear path
    starting_point = gp_Pnt(0., 0., 0.)
    end_point = gp_Pnt(0., 0., 6.)
    vec = gp_Vec(starting_point, end_point)
    path = BRepBuilderAPI_MakeEdge(starting_point, end_point).Edge()

    # extrusion
    prism = BRepPrimAPI_MakePrism(profile, vec).Shape()

    display.DisplayShape(profile, update=False)
    display.DisplayShape(starting_point, update=False)
    display.DisplayShape(end_point, update=False)
    display.DisplayShape(path, update=False)
    display.DisplayShape(prism, update=True)
Exemple #10
0
    def get_transform(self):
        """ Create a transform which rotates the default axis to align
        with the normal given by the position

        Returns
        -------
        transform: gp_Trsf

        """
        d = self.declaration

        # Move to position and align along direction axis
        t = gp_Trsf()
        if d.direction.is_parallel(DZ):
            t.SetRotation(AZ, d.direction.angle(DZ) + d.rotation)
        else:
            d1 = d.direction.cross(DZ)
            axis = gp_Ax1(gp_Pnt(0, 0, 0), d1.proxy)
            t.SetRotation(axis, d.direction.angle(DZ))

            # Apply the rotation an reverse any rotation added in
            sign = 1 if d1.y >= 0 else -1
            angle = d.rotation + sign * d1.angle(DX)

            if angle:
                rot = gp_Trsf()
                rot.SetRotation(AZ, angle)
                t.Multiply(rot)

        t.SetTranslationPart(gp_Vec(*d.position))
        return t
Exemple #11
0
def animate_translate_clip_plane(event=None):
    plane_definition = clip_plane_1.ToPlane()  # it's a gp_Pln
    h = 0.2
    for i in range(100):
        plane_definition.Translate(gp_Vec(0., 0., h))
        clip_plane_1.SetEquation(plane_definition)
        display.Context.UpdateCurrentViewer()
 def as_vec(self):
     if self.is_line():
         first, last = map(
             vertex2pnt,
             [self.first_vertex(), self.last_vertex()])
         return gp_Vec(first, last)
     else:
         raise ValueError(
             "edge is not a line, hence no meaningful vector can be returned"
         )
Exemple #13
0
def fit_plane_through_face_vertices(_face):
    """
    :param _face:   OCC.KBE.face.Face instance
    :return:        Geom_Plane
    """
    from OCCT.GeomPlate import GeomPlate_BuildAveragePlane

    uvs_from_vertices = [_face.project_vertex(vertex2pnt(i)) for i in Topo(_face).vertices()]
    normals = [gp_Vec(_face.DiffGeom.normal(*uv[0])) for uv in uvs_from_vertices]
    points = [i[1] for i in uvs_from_vertices]

    NORMALS = TColgp_SequenceOfVec()
    [NORMALS.Append(i) for i in normals]
    POINTS = to_tcol_(points, TColgp_HArray1OfPnt)

    pl = GeomPlate_BuildAveragePlane(NORMALS, POINTS).Plane().GetObject()
    vec = gp_Vec(pl.Location(), _face.GlobalProperties.centre())
    pt = (pl.Location().as_vec() + vec).as_pnt()
    pl.SetLocation(pt)
    return pl
def brep_feat_rib(event=None):
    mkw = BRepBuilderAPI_MakeWire()

    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(0., 0., 0.), gp_Pnt(200., 0.,
                                                           0.)).Edge())
    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(200., 0., 0.), gp_Pnt(200., 0.,
                                                             50.)).Edge())
    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(200., 0., 50.), gp_Pnt(50., 0.,
                                                              50.)).Edge())
    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(50., 0., 50.), gp_Pnt(50., 0.,
                                                             200.)).Edge())
    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(50., 0., 200.), gp_Pnt(0., 0.,
                                                              200.)).Edge())
    mkw.Add(
        BRepBuilderAPI_MakeEdge(gp_Pnt(0., 0., 200.), gp_Pnt(0., 0.,
                                                             0.)).Edge())

    S = BRepPrimAPI_MakePrism(
        BRepBuilderAPI_MakeFace(mkw.Wire()).Face(),
        gp_Vec(gp_Pnt(0., 0., 0.), gp_Pnt(0., 100., 0.)))
    display.EraseAll()
    #    display.DisplayShape(S.Shape())

    W = BRepBuilderAPI_MakeWire(
        BRepBuilderAPI_MakeEdge(gp_Pnt(50., 45., 100.), gp_Pnt(100., 45.,
                                                               50.)).Edge())

    aplane = Geom_Plane(0., 1., 0., -45.)

    aform = BRepFeat_MakeLinearForm(S.Shape(), W.Wire(), aplane,
                                    gp_Vec(0., 10., 0.), gp_Vec(0., 0., 0.), 1,
                                    True)
    aform.Perform()
    display.DisplayShape(aform.Shape())
    display.FitAll()
def interpolate(event=None):
    display.EraseAll()

    origin = gp_Vec()
    vX = gp_Vec(12, 0, 0)
    vY = gp_Vec(0, 12, 0)
    v45 = (gp_Vec(1, 1, 1).Normalized() * 12)

    q = gp_Quaternion()
    interp = gp_QuaternionSLerp(gp_Quaternion(vX, vX), gp_Quaternion(vX, vY))

    for i in frange(0, 1.0, 0.01):
        interp.Interpolate(i, q)
        # displace the white edges a little from the origin so not to obstruct the other edges
        v = gp_Vec(0, -24*i, 0)
        q_v_ = q * v45
        p = gp_Pnt((q_v_ + v).XYZ())
        v__as_pnt = gp_Pnt((origin + v).XYZ())
        e = make_edge(v__as_pnt, p)
        display.DisplayColoredShape(e, 'WHITE')
        msg = 'v45->q1*v45 @{0}'.format(i / 10.)
        display.DisplayMessage(p, msg)
    display.FitAll()
Exemple #16
0
    def get_value_at(cls, curve, t, derivative=0):
        """ Get the value of the curve at parameter t with it's derivatives.

        Parameters
        ----------
        curve: BRepAdaptor_Curve
            The curve to get the value from
        t: Float
            The parameter value from 0 to 1
        derivative: Int
            The derivative from 0 to 4

        Returns
        -------
        results: Point or Tuple
            If the derivative is 0 only the position at t is returned,
            otherwise a tuple of the position and all deriviatives.
        """
        p = gp_Pnt()
        if derivative == 0:
            curve.D0(t, p)
            return coerce_point(p)
        v1 = gp_Vec()
        if derivative == 1:
            curve.D1(t, p, v1)
            return (coerce_point(p), coerce_direction(v1))
        v2 = gp_Vec()
        if derivative == 2:
            curve.D1(t, p, v1, v2)
            return (coerce_point(p), coerce_direction(v1),
                    coerce_direction(v2))
        v3 = gp_Vec()
        if derivative == 3:
            curve.D3(t, p, v1, v2, v3)
            return (coerce_point(p), coerce_direction(v1),
                    coerce_direction(v2), coerce_direction(v3))
        raise ValueError("Invalid derivative")
Exemple #17
0
    def make_shape(self):
        # 1 - retrieve the data from the UIUC airfoil data page
        foil_dat_url = 'http://m-selig.ae.illinois.edu/ads/coord_seligFmt/%s.dat' % self.profile
        print("Connecting to m-selig, retrieving foil data")
        f = urllib2.urlopen(foil_dat_url)
        print("Building foil geometry")
        plan = gp_Pln(gp_Pnt(0., 0., 0.), gp_Dir(0., 0.,
                                                 1.))  # Z=0 plan / XY plan
        section_pts_2d = []

        for line in f.readlines()[1:]:  # The first line contains info only
            # 2 - do some cleanup on the data (mostly dealing with spaces)
            data = line.split()
            # 3 - create an array of points
            if len(data) == 2:  # two coordinates for each point
                section_pts_2d.append(
                    gp_Pnt2d(
                        float(data[0]) * self.chord,
                        float(data[1]) * self.chord))

        # 4 - use the array to create a spline describing the airfoil section
        spline_2d = Geom2dAPI_PointsToBSpline(
            point2d_list_to_TColgp_Array1OfPnt2d(section_pts_2d),
            len(section_pts_2d) - 1,  # order min
            len(section_pts_2d))  # order max
        spline = geomapi.To3d(spline_2d.Curve(), plan)

        # 5 - figure out if the trailing edge has a thickness or not,
        # and create a Face
        try:
            # first and last point of spline -> trailing edge
            trailing_edge = make_edge(
                gp_Pnt(section_pts_2d[0].X(), section_pts_2d[0].Y(), 0.0),
                gp_Pnt(section_pts_2d[-1].X(), section_pts_2d[-1].Y(), 0.0))
            face = BRepBuilderAPI_MakeFace(
                make_wire([make_edge(spline), trailing_edge]))
        except AssertionError:
            # the trailing edge segment could not be created, probably because
            # the points are too close
            # No need to build a trailing edge
            face = BRepBuilderAPI_MakeFace(make_wire(make_edge(spline)))

        # 6 - extrude the Face to create a Solid
        return BRepPrimAPI_MakePrism(
            face.Face(), gp_Vec(gp_Pnt(0., 0., 0.),
                                gp_Pnt(0., 0., self.span))).Shape()
def glue_solids_edges(event=None):
    display.EraseAll()
    display.Context.RemoveAll(True)

    # With common edges
    S3 = BRepPrimAPI_MakeBox(500., 400., 300.).Shape()
    S4 = BRepPrimAPI_MakeBox(gp_Pnt(0., 0., 300.), gp_Pnt(200., 200.,
                                                          500.)).Shape()

    faces_S3 = get_faces(S3)
    faces_S4 = get_faces(S4)

    # tagging allows to visually find the right faces to glue
    tag_faces(faces_S3, "BLUE", "s3")
    tag_faces(faces_S4, "GREEN", "s4")

    F3, F4 = faces_S3[5], faces_S4[4]

    glue2 = BRepFeat_Gluer(S4, S3)
    glue2.Bind(F4, F3)
    glue2.Build()
    shape = glue2.Shape()

    # move the glued shape, such to be able to inspect input and output
    # of glueing operation
    trsf = gp_Trsf()
    trsf.SetTranslation(gp_Vec(750, 0, 0))
    shape.Move(TopLoc_Location(trsf))

    common_edges = LocOpe_FindEdges(F4, F3)
    common_edges.InitIterator()

    n = 0
    while common_edges.More():
        edge_from = common_edges.EdgeFrom()
        edge_to = common_edges.EdgeTo()

        tag_edge(edge_from, "edge_{0}_from".format(n))
        tag_edge(edge_to, "edge_{0}_to".format(n))

        glue2.Bind(edge_from, edge_to)
        common_edges.Next()
        n += 1

    tag_faces(get_faces(shape), "BLACK", "")
    display.FitAll()
Exemple #19
0
    def update_shape(self, change=None):
        d = self.declaration

        if d.shape:
            shape = coerce_shape(d.shape)
            copy = True
        else:

            shape = self.get_shape().shape
            copy = False

        if d.infinite:
            args = (shape, d.direction.proxy, True, copy, d.canonize)
        else:
            args = (shape, gp_Vec(*d.vector), copy, d.canonize)
        prism = BRepPrimAPI_MakePrism(*args)
        self.shape = prism.Shape()
def glue_solids(event=None):
    display.EraseAll()
    display.Context.RemoveAll(True)
    # Without common edges
    S1 = BRepPrimAPI_MakeBox(gp_Pnt(500., 500., 0.), gp_Pnt(100., 250.,
                                                            300.)).Shape()
    facesA = get_faces(S1)
    tag_faces(facesA, "BLUE", "facesA")

    # the face to glue
    F1 = facesA[5]

    S2 = BRepPrimAPI_MakeBox(gp_Pnt(400., 400., 300.),
                             gp_Pnt(200., 300., 500.)).Shape()
    facesB = get_faces(S2)

    tag_faces(facesB, "GREEN", "facesB")

    # the face to glue of the opposite shape
    F2 = facesB[4]

    # perform glueing operation
    glue1 = BRepFeat_Gluer(S2, S1)
    glue1.Bind(F2, F1)
    shape = glue1.Shape()

    display.SetModeHLR()

    # move the glued shape, such to be able to inspect input and output
    # of glueing operation
    trsf = gp_Trsf()
    trsf.SetTranslation(gp_Vec(500, 0, 0))
    shape.Move(TopLoc_Location(trsf))

    tag_faces(get_faces(shape), "BLACK", "")

    # render glued shape
    display.DisplayShape(shape)
    display.FitAll()
def 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()
Exemple #22
0
 def as_vec(self):
     '''returns a gp_Vec version of self'''
     return gp_Vec(*self._pnt.Coord())
def build_tooth():
    base_center = gp_Pnt2d(pitch_circle_radius + (tooth_radius - roller_radius), 0)
    base_circle = gp_Circ2d(gp_Ax2d(base_center, gp_Dir2d()), tooth_radius)
    trimmed_base = GCE2d_MakeArcOfCircle(base_circle,
                                         M_PI - (roller_contact_angle / 2.),
                                         M_PI).Value()
    trimmed_base.Reverse()  # just a trick
    p0 = trimmed_base.StartPoint()
    p1 = trimmed_base.EndPoint()

    # Determine the center of the profile circle
    x_distance = cos(roller_contact_angle / 2.) * (profile_radius + tooth_radius)
    y_distance = sin(roller_contact_angle / 2.) * (profile_radius + tooth_radius)
    profile_center = gp_Pnt2d(pitch_circle_radius - x_distance, y_distance)

    # Construct the profile circle gp_Circ2d
    profile_circle = gp_Circ2d(gp_Ax2d(profile_center, gp_Dir2d()),
                               profile_center.Distance(p1))
    geom_profile_circle = GCE2d_MakeCircle(profile_circle).Value()

    # Construct the outer circle gp_Circ2d
    outer_circle = gp_Circ2d(gp_Ax2d(gp_Pnt2d(0, 0), gp_Dir2d()), top_radius)
    geom_outer_circle = GCE2d_MakeCircle(outer_circle).Value()

    inter = Geom2dAPI_InterCurveCurve(geom_profile_circle, geom_outer_circle)
    num_points = inter.NbPoints()
    assert isinstance(p1, gp_Pnt2d)
    if num_points == 2:
        if p1.Distance(inter.Point(1)) < p1.Distance(inter.Point(2)):
            p2 = inter.Point(1)
        else:
            p2 = inter.Point(2)
    elif num_points == 1:
        p2 = inter.Point(1)
    else:
        sys.exit(-1)

    # Trim the profile circle and mirror
    trimmed_profile = GCE2d_MakeArcOfCircle(profile_circle, p1, p2).Value()

    # Calculate the outermost point
    p3 = gp_Pnt2d(cos(tooth_angle / 2.) * top_radius,
                  sin(tooth_angle / 2.) * top_radius)

    # and use it to create the third arc
    trimmed_outer = GCE2d_MakeArcOfCircle(outer_circle, p2, p3).Value()

    # Mirror and reverse the three arcs
    mirror_axis = gp_Ax2d(gp_Origin2d(), gp_DX2d().Rotated(tooth_angle / 2.))

    mirror_base = Geom2d_TrimmedCurve.DownCast(trimmed_base.Copy())
    mirror_profile = Geom2d_TrimmedCurve.DownCast(trimmed_profile.Copy())
    mirror_outer = Geom2d_TrimmedCurve.DownCast(trimmed_outer.Copy())

    mirror_base.Mirror(mirror_axis)
    mirror_profile.Mirror(mirror_axis)
    mirror_outer.Mirror(mirror_axis)

    mirror_base.Reverse()
    mirror_profile.Reverse()
    mirror_outer.Reverse()

    # Replace the two outer arcs with a single one
    outer_start = trimmed_outer.StartPoint()
    outer_mid = trimmed_outer.EndPoint()
    outer_end = mirror_outer.EndPoint()

    outer_arc = GCE2d_MakeArcOfCircle(outer_start, outer_mid, outer_end).Value()

    # Create an arc for the inside of the wedge
    inner_circle = gp_Circ2d(gp_Ax2d(gp_Pnt2d(0, 0), gp_Dir2d()),
                             top_radius - roller_diameter)
    inner_start = gp_Pnt2d(top_radius - roller_diameter, 0)
    inner_arc = GCE2d_MakeArcOfCircle(inner_circle, inner_start, tooth_angle).Value()
    inner_arc.Reverse()

    # Convert the 2D arcs and two extra lines to 3D edges
    plane = gp_Pln(gp_Origin(), gp_DZ())
    arc1 = BRepBuilderAPI_MakeEdge(geomapi_To3d(trimmed_base, plane)).Edge()
    arc2 = BRepBuilderAPI_MakeEdge(geomapi_To3d(trimmed_profile, plane)).Edge()
    arc3 = BRepBuilderAPI_MakeEdge(geomapi_To3d(outer_arc, plane)).Edge()
    arc4 = BRepBuilderAPI_MakeEdge(geomapi_To3d(mirror_profile, plane)).Edge()
    arc5 = BRepBuilderAPI_MakeEdge(geomapi_To3d(mirror_base, plane)).Edge()

    p4 = mirror_base.EndPoint()
    p5 = inner_arc.StartPoint()

    lin1 = BRepBuilderAPI_MakeEdge(gp_Pnt(p4.X(), p4.Y(), 0),
                                   gp_Pnt(p5.X(), p5.Y(), 0)).Edge()
    arc6 = BRepBuilderAPI_MakeEdge(geomapi_To3d(inner_arc, plane)).Edge()

    p6 = inner_arc.EndPoint()
    lin2 = BRepBuilderAPI_MakeEdge(gp_Pnt(p6.X(), p6.Y(), 0),
                                   gp_Pnt(p0.X(), p0.Y(), 0)).Edge()

    wire = BRepBuilderAPI_MakeWire(arc1)
    wire.Add(arc2)
    wire.Add(arc3)
    wire.Add(arc4)
    wire.Add(arc5)
    wire.Add(lin1)
    wire.Add(arc6)
    wire.Add(lin2)

    face = BRepBuilderAPI_MakeFace(wire.Wire())

    wedge = BRepPrimAPI_MakePrism(face.Shape(), gp_Vec(0.0, 0.0, thickness))

    return wedge.Shape()
def cut_out(base):
    outer = gp_Circ2d(gp_OX2d(), top_radius - 1.75 * roller_diameter)
    inner = gp_Circ2d(gp_OX2d(), center_radius + 0.75 * roller_diameter)

    geom_outer = GCE2d_MakeCircle(outer).Value()
    geom_inner = GCE2d_MakeCircle(inner).Value()
    geom_inner.Reverse()

    base_angle = (2. * M_PI) / mounting_hole_count
    hole_angle = atan(hole_radius / mounting_radius)
    correction_angle = 3 * hole_angle

    left = gp_Lin2d(gp_Origin2d(), gp_DX2d())
    right = gp_Lin2d(gp_Origin2d(), gp_DX2d())
    left.Rotate(gp_Origin2d(), correction_angle)
    right.Rotate(gp_Origin2d(), base_angle - correction_angle)

    geom_left = GCE2d_MakeLine(left).Value()
    geom_right = GCE2d_MakeLine(right).Value()

    inter_1 = Geom2dAPI_InterCurveCurve(geom_outer, geom_left)
    inter_2 = Geom2dAPI_InterCurveCurve(geom_outer, geom_right)
    inter_3 = Geom2dAPI_InterCurveCurve(geom_inner, geom_right)
    inter_4 = Geom2dAPI_InterCurveCurve(geom_inner, geom_left)

    if inter_1.Point(1).X() > 0:
        p1 = inter_1.Point(1)
    else:
        p1 = inter_1.Point(2)

    if inter_2.Point(1).X() > 0:
        p2 = inter_2.Point(1)
    else:
        p2 = inter_2.Point(2)

    if inter_3.Point(1).X() > 0:
        p3 = inter_3.Point(1)
    else:
        p3 = inter_3.Point(2)

    if inter_4.Point(1).X() > 0:
        p4 = inter_4.Point(1)
    else:
        p4 = inter_4.Point(2)

    trimmed_outer = GCE2d_MakeArcOfCircle(outer, p1, p2).Value()
    trimmed_inner = GCE2d_MakeArcOfCircle(inner, p4, p3).Value()

    plane = gp_Pln(gp_Origin(), gp_DZ())

    arc1 = BRepBuilderAPI_MakeEdge(geomapi_To3d(trimmed_outer, plane)).Edge()

    lin1 = BRepBuilderAPI_MakeEdge(gp_Pnt(p2.X(), p2.Y(), 0),
                                   gp_Pnt(p3.X(), p3.Y(), 0)).Edge()

    arc2 = BRepBuilderAPI_MakeEdge(geomapi_To3d(trimmed_inner, plane)).Edge()

    lin2 = BRepBuilderAPI_MakeEdge(gp_Pnt(p4.X(), p4.Y(), 0),
                                   gp_Pnt(p1.X(), p1.Y(), 0)).Edge()

    cutout_wire = BRepBuilderAPI_MakeWire(arc1)
    cutout_wire.Add(lin1)
    cutout_wire.Add(arc2)
    cutout_wire.Add(lin2)

    # Turn the wire into a face
    cutout_face = BRepBuilderAPI_MakeFace(cutout_wire.Wire())
    filleted_face = BRepFilletAPI_MakeFillet2d(cutout_face.Face())

    explorer = BRepTools_WireExplorer(cutout_wire.Wire())
    while explorer.More():
        vertex = explorer.CurrentVertex()
        filleted_face.AddFillet(vertex, roller_radius)
        explorer.Next()

    cutout = BRepPrimAPI_MakePrism(filleted_face.Shape(),
                                   gp_Vec(0.0, 0.0, thickness)).Shape()

    result = base
    rotate = gp_Trsf()
    for i in range(0, mounting_hole_count):
        rotate.SetRotation(gp_OZ(), i * 2. * M_PI / mounting_hole_count)
        rotated_cutout = BRepBuilderAPI_Transform(cutout, rotate, True)

        result = BRepAlgoAPI_Cut(result,
                                 rotated_cutout.Shape()).Shape()

    return result
def round_tooth(wedge):
    round_x = 2.6
    round_z = 0.06 * pitch
    round_radius = pitch

    # Determine where the circle used for rounding has to start and stop
    p2d_1 = gp_Pnt2d(top_radius - round_x, 0)
    p2d_2 = gp_Pnt2d(top_radius, round_z)

    # Construct the rounding circle
    round_circle = GccAna_Circ2d2TanRad(p2d_1, p2d_2, round_radius, 0.01)
    if (round_circle.NbSolutions() != 2):
        sys.exit(-2)

    round_circle_2d_1 = round_circle.ThisSolution(1)
    round_circle_2d_2 = round_circle.ThisSolution(2)

    if (round_circle_2d_1.Position().Location().Coord()[1] >= 0):
        round_circle_2d = round_circle_2d_1
    else:
        round_circle_2d = round_circle_2d_2

    # Remove the arc used for rounding
    trimmed_circle = GCE2d_MakeArcOfCircle(round_circle_2d, p2d_1, p2d_2).Value()

    # Calculate extra points used to construct lines
    p1 = gp_Pnt(p2d_1.X(), 0, p2d_1.Y())
    p2 = gp_Pnt(p2d_2.X(), 0, p2d_2.Y())
    p3 = gp_Pnt(p2d_2.X() + 1, 0, p2d_2.Y())
    p4 = gp_Pnt(p2d_2.X() + 1, 0, p2d_1.Y() - 1)
    p5 = gp_Pnt(p2d_1.X(), 0, p2d_1.Y() - 1)

    # Convert the arc and four extra lines into 3D edges
    plane = gp_Pln(gp_Ax3(gp_Origin(), gp_DY().Reversed(), gp_DX()))
    arc1 = BRepBuilderAPI_MakeEdge(geomapi_To3d(trimmed_circle, plane)).Edge()
    lin1 = BRepBuilderAPI_MakeEdge(p2, p3).Edge()
    lin2 = BRepBuilderAPI_MakeEdge(p3, p4).Edge()
    lin3 = BRepBuilderAPI_MakeEdge(p4, p5).Edge()
    lin4 = BRepBuilderAPI_MakeEdge(p5, p1).Edge()

    # Make a wire composed of the edges
    round_wire = BRepBuilderAPI_MakeWire(arc1)
    round_wire.Add(lin1)
    round_wire.Add(lin2)
    round_wire.Add(lin3)
    round_wire.Add(lin4)

    # Turn the wire into a face
    round_face = BRepBuilderAPI_MakeFace(round_wire.Wire()).Shape()

    # Revolve the face around the Z axis over the tooth angle
    rounding_cut_1 = BRepPrimAPI_MakeRevol(round_face, gp_OZ(), tooth_angle).Shape()

    # Construct a mirrored copy of the first cutting shape
    mirror = gp_Trsf()
    mirror.SetMirror(gp_XOY())
    mirrored_cut_1 = BRepBuilderAPI_Transform(rounding_cut_1, mirror, True).Shape()

    # and translate it so that it ends up on the other side of the wedge
    translate = gp_Trsf()
    translate.SetTranslation(gp_Vec(0, 0, thickness))
    rounding_cut_2 = BRepBuilderAPI_Transform(mirrored_cut_1, translate, False).Shape()

    # Cut the wedge using the first and second cutting shape
    cut_1 = BRepAlgoAPI_Cut(wedge, rounding_cut_1).Shape()
    cut_2 = BRepAlgoAPI_Cut(cut_1, rounding_cut_2).Shape()

    return cut_2
Exemple #26
0
from OCCT.BRepPrimAPI import BRepPrimAPI_MakeTorus
from OCCT.gp import gp_Vec

from OCC.Extend.ShapeFactory import translate_shp, rotate_shp_3_axis

my_ren = threejs_renderer.ThreejsRenderer()
n_toruses = 100

idx = 0
for i in range(n_toruses):
    torus_shp = BRepPrimAPI_MakeTorus(10 + random.random() * 10,
                                      random.random() * 10).Shape()
    # random position and orientation and color
    angle_x = random.random() * 360
    angle_y = random.random() * 360
    angle_z = random.random() * 360
    rotated_torus = rotate_shp_3_axis(torus_shp, angle_x, angle_y, angle_z,
                                      'deg')
    tr_x = random.uniform(-70, 50)
    tr_y = random.uniform(-70, 50)
    tr_z = random.uniform(-50, 50)
    trans_torus = translate_shp(rotated_torus, gp_Vec(tr_x, tr_y, tr_z))
    rnd_color = (random.random(), random.random(), random.random())
    my_ren.DisplayShape(trans_torus,
                        export_edges=True,
                        color=rnd_color,
                        transparency=random.random())
    print("%i%%" % (idx * 100 / n_toruses), end="")
    idx += 1
my_ren.render()
Exemple #27
0
import sys

from OCC.Display.SimpleGui import init_display
from OCCT.BRepPrimAPI import BRepPrimAPI_MakeBox, BRepPrimAPI_MakeCone
from OCCT.Graphic3d import Graphic3d_NOM_PLASTIC, Graphic3d_NOM_ALUMINIUM
from OCCT.V3d import V3d_SpotLight, V3d_XnegYnegZpos
from OCCT.Quantity import Quantity_Color, Quantity_NOC_WHITE, Quantity_NOC_CORAL2, Quantity_NOC_BROWN
from OCCT.BRepAlgoAPI import BRepAlgoAPI_Cut
from OCCT.gp import gp_Vec

from OCC.Extend.ShapeFactory import translate_shp

# first create geometry
from core_classic_occ_bottle import bottle
table = translate_shp(
    BRepPrimAPI_MakeBox(100, 100, 10).Shape(), gp_Vec(-50, -50, -10))
glass_out = BRepPrimAPI_MakeCone(7, 9, 25).Shape()
glass_in = translate_shp(
    BRepPrimAPI_MakeCone(7, 9, 25).Shape(), gp_Vec(0., 0., 0.2))
glass = BRepAlgoAPI_Cut(glass_out, glass_in).Shape()
translated_glass = translate_shp(glass, gp_Vec(-30, -30, 0))

# then inits display
display, start_display, add_menu, add_function_to_menu = init_display()

# create one spotlight
spot_light = V3d_SpotLight(display.Viewer, -100, -100, 100, V3d_XnegYnegZpos,
                           Quantity_Color(Quantity_NOC_WHITE))
## display the spotlight in rasterized mode
display.Viewer.AddLight(spot_light)
display.View.SetLightOn()
Exemple #28
0
aMirroredShape = aBRespTrsf.Shape()

# A wire instead of a generic shape now
aMirroredWire = topods.Wire(aMirroredShape)

# Combine the two constituent wires
mkWire = BRepBuilderAPI_MakeWire()
mkWire.Add(aWire.Wire())
mkWire.Add(aMirroredWire)
myWireProfile = mkWire.Wire()

# The face that we'll sweep to make the prism
myFaceProfile = BRepBuilderAPI_MakeFace(myWireProfile)

# We want to sweep the face along the Z axis to the height
aPrismVec = gp_Vec(0, 0, height)
myBody = BRepPrimAPI_MakePrism(myFaceProfile.Face(), aPrismVec)

# Add fillets to all edges through the explorer
mkFillet = BRepFilletAPI_MakeFillet(myBody.Shape())
anEdgeExplorer = TopExp_Explorer(myBody.Shape(), TopAbs_EDGE)

while anEdgeExplorer.More():
    anEdge = topods.Edge(anEdgeExplorer.Current())
    mkFillet.Add(thickness / 12.0, anEdge)

    anEdgeExplorer.Next()

myBody = mkFillet

# Create the neck of the bottle
def random_vec():
    x, y, z = [random.uniform(-1, 1) for i in range(3)]
    return gp_Vec(x, y, z)
Exemple #30
0
from __future__ import print_function

from OCC.Display.WebGl import threejs_renderer
from OCCT.BRepPrimAPI import BRepPrimAPI_MakeTorus
from OCCT.gp import gp_Vec

from OCC.Extend.ShapeFactory import translate_shp

my_ren = threejs_renderer.ThreejsRenderer()

idx = 0
torus_shp1 = BRepPrimAPI_MakeTorus(20, 5).Shape()

torus_shp2b = BRepPrimAPI_MakeTorus(20, 5).Shape()
torus_shp2 = translate_shp(torus_shp2b, gp_Vec(60, 0, 0))

torus_shp3b = BRepPrimAPI_MakeTorus(20, 5).Shape()
torus_shp3 = translate_shp(torus_shp3b, gp_Vec(-60, 0, 0))

# default quality
print("Computing RED torus: default quality")
my_ren.DisplayShape(torus_shp1, export_edges=True, color=(1,0,0))  # red

# better mesh quality, i.e. more triangles
print("Computing GREEN torus: better quality, more time to compute")
my_ren.DisplayShape(torus_shp2, export_edges=True, color=(0,1,0),  # green
                    mesh_quality = 0.5)

# worse quality, i.e. less triangles
print("Computing BLUE torus: worse quality, faster to compute")