Ejemplo n.º 1
0
 def test_list(self):
     '''
     Test python lists features
     '''
     P1 = gp_Pnt(1, 2, 3)
     P2 = gp_Pnt(2, 3, 4)
     P3 = gp_Pnt(5, 7, 8)
     l = [P1, P2]
     self.assertEqual(P1 in l, True)
     self.assertNotEqual(P3 in l, True)
     self.assertEqual(l.index(P1), 0)
     self.assertEqual(l.index(P2), 1)
     # Do the same for Vertices (TopoDS_Shape has
     # a HashCode() method overloaded
     V1 = BRepBuilderAPI_MakeVertex(P1).Vertex()
     V2 = BRepBuilderAPI_MakeVertex(P2).Vertex()
     V3 = BRepBuilderAPI_MakeVertex(P3).Vertex()
     vl = [V1, V2]
     self.assertEqual(V1 in vl, True)
     self.assertNotEqual(V3 in vl, True)
     # index test()
     self.assertEqual(vl.index(V1), 0)
     self.assertEqual(vl.index(V2), 1)
     # reverse() test
     vl.reverse()
     self.assertEqual(vl.index(V1), 1)
     self.assertEqual(vl.index(V2), 0)
Ejemplo n.º 2
0
def make_vertex(args):
    if isinstance(args, (list, tuple)):
        args = gp_Pnt(*args)

    vert = BRepBuilderAPI_MakeVertex(args)
    with assert_isdone(vert, 'failed to produce vertex'):
        result = vert.Vertex()
        vert.Delete()
        return result
Ejemplo n.º 3
0
def sampleSolid(n, solid, vertexList=None):
    # Create a bounding box for the shape
    boundingBox = Bnd_Box()
    brepbndlib_Add(solid, boundingBox)
    xMin, yMin, zMin, xMax, yMax, zMax = boundingBox.Get()
    xSideLength = xMax - xMin
    ySideLength = yMax - yMin
    zSideLength = zMax - zMin

    # Create extrema sampler to measure if the point is in the shape. For now,
    # just initialize it with the same shape. We'll load the vertex later.
    brepDistShapeShape = BRepExtrema_DistShapeShape(solid, solid)

    # Create a random number of vertices and check to see which ones are
    # in the shape.
    vertices = createPointsDataFrame(n)
    vertices.inShape = vertices.inShape.astype('int')
    # Loop over the vertices
    for i in range(0, n):
        # Pick a random point
        x = xMin + random() * xSideLength
        y = yMin + random() * ySideLength
        z = zMin + random() * zSideLength
        # Create a vertex from a geometric point
        gpPoint = gp_Pnt(x, y, z)
        vertexBuilder = BRepBuilderAPI_MakeVertex(gpPoint)
        vertex = vertexBuilder.Vertex()
        # Load the vertex into the extrema calculator
        brepDistShapeShape.LoadS2(vertex)
        brepDistShapeShape.Perform()
        # Compute the containment with the box and store the value
        inShape = 1 if brepDistShapeShape.InnerSolution() else 0
        # Store the shape value
        vertices.set_value(i, 'x', x)
        vertices.set_value(i, 'y', y)
        vertices.set_value(i, 'z', z)
        vertices.set_value(i, 'inShape', inShape)
        if inShape != 0:
            vertexList.append(vertex)

    # Slice the data frame so that only the x,y,z variables for points in the box are saved.
    innerVertices = vertices[vertices.inShape == 1]
    innerCoords = innerVertices[['x', 'y', 'z']]

    return innerCoords
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
def discretize(shape, tol):
    """This method discretizes the OpenCascade shape.

    :param shape: Shape to discretize
    :type shape:
    :return: discretized face; profile coordinates; id of the surface the\
    coordinates belong to
    :rtype: OCC.TopoDS.TopoDS_Compound; numpy.ndarray; numpy.ndarray
    """
    BRepMesh_IncrementalMesh(shape, tol, False, 5)
    builder = BRep_Builder()
    comp = TopoDS_Compound()
    builder.MakeCompound(comp)

    bt = BRep_Tool()
    ex = TopExp_Explorer(shape, TopAbs_EDGE)
    edge_coords = np.zeros([0, 3])
    edge_ids = np.zeros([0], dtype=int)
    edge_id = 0
    while ex.More():
        edge = topods_Edge(ex.Current())
        location = TopLoc_Location()
        edging = (bt.Polygon3D(edge, location)).GetObject()
        tab = edging.Nodes()
        for i in range(1, edging.NbNodes() + 1):
            p = tab.Value(i)
            edge_coords = np.append(edge_coords,
                                    [[p.X(), p.Y(), p.Z()]],
                                    axis=0)
            edge_ids = np.append(edge_ids, edge_id)
            mv = BRepBuilderAPI_MakeVertex(p)
            if mv.IsDone():
                builder.Add(comp, mv.Vertex())
        edge_id += 1
        ex.Next()

    edge_coords = np.round(edge_coords, 8)
    return edge_coords, edge_ids
Ejemplo n.º 7
0
def test_update_ApexPoint():
    """Tests that Build is triggered on updating Apex Point"""
    # Create example airliner wing
    P = (0, 0, 0)
    wing = LiftingSurface(P, mySweepAngleFunctionAirliner,
                          myDihedralFunctionAirliner, myTwistFunctionAirliner,
                          myChordFunctionAirliner, myAirfoilFunctionAirliner)

    # By adding a point to the wing, we will see if the move transformation
    # has been performed when the ApexPoint attribute is changed:
    from OCC.BRepBuilderAPI import BRepBuilderAPI_MakeVertex
    v = BRepBuilderAPI_MakeVertex(gp_Pnt(0, 0, 0)).Vertex()
    wing['test_pnt'] = v

    # Updating the apex should move the surface (and test vertex) through
    # the vector newApex - oldApex
    wing.ApexPoint = gp_Pnt(10, 10, 10)

    # Retrieve the vertex and point from the translated shape
    from OCC.TopoDS import topods_Vertex
    from OCC.BRep import BRep_Tool_Pnt
    vout = topods_Vertex(wing['test_pnt'])
    p = BRep_Tool_Pnt(vout)

    # Check that the vertex was correctly transformed
    xyz = [p.X(), p.Y(), p.Z()]
    assert (xyz == [10, 10, 10])


# def test_Fit_BlendedTipDevice(simple_wing):
#     # Fit a blended winglet to this wing and test the output
#     wing = simple_wing

#     wing.Fit_BlendedTipDevice(rootchord_norm=0.8, spanfraction=0.1, cant=40,
#                              transition=0.1, sweep=40, taper=0.7)

#     # Test the (theoretical) tip chord equals the winglet root chord:
#     assert((Wing.ChordFunct(1) * Wing.ScaleFactor * Wing.ChordFactor) ==
#         Winglet.ChordFunct(0) * Winglet.ScaleFactor * Winglet.ChordFactor)

#     # Test the length of the LE curve is the correct spanfraction
Ejemplo n.º 8
0
def intersection(a, b):

    if set([a.ShapeType(), b.ShapeType()]) <= set([TopAbs.TopAbs_WIRE, TopAbs.TopAbs_EDGE]):
        # TODO: check if the computed point is within the bounded part of
        # the curves
        l = []
        for c0 in subshapes(a, TopAbs.TopAbs_EDGE):
            c0_ = BRep_Tool.Curve(c0)[0]
            for c1 in subshapes(b, TopAbs.TopAbs_EDGE):
                c1_ = BRep_Tool.Curve(c1)[0]
                # TODO: use IntTools_EdgeEdge
                #  or IntTools_BeanBeanIntersector
                u = GeomAPI_ExtremaCurveCurve(c0_, c1_)
                par = u.LowerDistanceParameters()[0]
                pnt = c0_.GetObject().Value(par)
                l.append(BRepBuilderAPI_MakeVertex(pnt).Vertex())
        return l

    c = BRepAlgoAPI.BRepAlgoAPI_Common(a, b).Shape()
    comp = TopoDS.topods_Compound(c)
    # get the subshape of the compound:
    types = set([a.ShapeType(), b.ShapeType()])
    # compound = 0
    # compsolid = 1
    # solid = 2
    # shell = 3
    # face = 4
    # wire = 5
    # edge = 6
    # vertex = 7
    # shape = 8
    if types == set([TopAbs.TopAbs_FACE]):
        return [subshapes(comp, TopAbs.TopAbs_FACE)[0]]
    elif types == set([TopAbs.TopAbs_FACE, TopAbs.TopAbs_SOLID]):
        return [subshapes(comp, TopAbs.TopAbs_SHELL)[0]]
    elif types == set([TopAbs.TopAbs_SOLID]):
        return [subshapes(comp, TopAbs.TopAbs_SOLID)[0]]
    elif types == set([TopAbs.TopAbs_SHELL]):
        return [subshapes(comp, TopAbs.TopAbs_EDGE)[0]]
    else:
        raise ConstructionError()
Ejemplo n.º 9
0
def make_vertex(*args):
    vert = BRepBuilderAPI_MakeVertex(*args)
    result = vert.Vertex()
    return result
Ejemplo n.º 10
0
    def DisplayShape(self,
                     shapes,
                     material=None,
                     texture=None,
                     color=None,
                     transparency=None,
                     update=False):
        '''
        '''
        # if a gp_Pnt is passed, first convert to vertex
        if issubclass(shapes.__class__, gp_Pnt):
            vertex = BRepBuilderAPI_MakeVertex(shapes)
            shapes = [vertex.Shape()]
            SOLO = True
        elif isinstance(shapes, gp_Pnt2d):
            vertex = BRepBuilderAPI_MakeVertex(
                gp_Pnt(shapes.X(), shapes.Y(), 0))
            shapes = [vertex.Shape()]
            SOLO = True
        # if a Geom_Curve is passed
        elif callable(getattr(shapes, "GetHandle", None)):
            handle = shapes.GetHandle()
            if issubclass(handle.__class__, Handle_Geom_Curve):
                edge = BRepBuilderAPI_MakeEdge(handle)
                shapes = [edge.Shape()]
                SOLO = True
            elif issubclass(handle.__class__, Handle_Geom2d_Curve):
                edge2d = BRepBuilderAPI_MakeEdge2d(handle)
                shapes = [edge2d.Shape()]
                SOLO = True
            elif issubclass(handle.__class__, Handle_Geom_Surface):
                bounds = True
                toldegen = 1e-6
                face = BRepBuilderAPI_MakeFace()
                face.Init(handle, bounds, toldegen)
                face.Build()
                shapes = [face.Shape()]
                SOLO = True
        elif isinstance(shapes, Handle_Geom_Surface):
            bounds = True
            toldegen = 1e-6
            face = BRepBuilderAPI_MakeFace()
            face.Init(shapes, bounds, toldegen)
            face.Build()
            shapes = [face.Shape()]
            SOLO = True
        elif isinstance(shapes, Handle_Geom_Curve):
            edge = BRepBuilderAPI_MakeEdge(shapes)
            shapes = [edge.Shape()]
            SOLO = True
        elif isinstance(shapes, Handle_Geom2d_Curve):
            edge2d = BRepBuilderAPI_MakeEdge2d(shapes)
            shapes = [edge2d.Shape()]
            SOLO = True
        elif issubclass(shapes.__class__, TopoDS_Shape):
            shapes = [shapes]
            SOLO = True
        else:
            SOLO = False

        ais_shapes = []

        for shape in shapes:
            if material or texture:
                if texture:
                    self.View.SetSurfaceDetail(OCC.V3d.V3d_TEX_ALL)
                    shape_to_display = OCC.AIS.AIS_TexturedShape(shape)
                    filename, toScaleU, toScaleV, toRepeatU, toRepeatV, originU, originV = texture.GetProperties(
                    )
                    shape_to_display.SetTextureFileName(
                        TCollection_AsciiString(filename))
                    shape_to_display.SetTextureMapOn()
                    shape_to_display.SetTextureScale(True, toScaleU, toScaleV)
                    shape_to_display.SetTextureRepeat(True, toRepeatU,
                                                      toRepeatV)
                    shape_to_display.SetTextureOrigin(True, originU, originV)
                    shape_to_display.SetDisplayMode(3)
                elif material:
                    shape_to_display = AIS_Shape(shape)
                    shape_to_display.SetMaterial(material)
            else:
                # TODO: can we use .Set to attach all TopoDS_Shapes
                # to this AIS_Shape instance?
                shape_to_display = AIS_Shape(shape)

            ais_shapes.append(shape_to_display.GetHandle())

        if not SOLO:
            # computing graphic properties is expensive
            # if an iterable is found, so cluster all TopoDS_Shape under
            # an AIS_MultipleConnectedInteractive
            shape_to_display = AIS_MultipleConnectedInteractive()
            for i in ais_shapes:
                shape_to_display.Connect(i)

        # set the graphic properties
        if material is None:
            #The default material is too shiny to show the object
            #color well, so I set it to something less reflective
            shape_to_display.SetMaterial(Graphic3d_NOM_NEON_GNC)
        if color:
            if isinstance(color, str):
                color = get_color_from_name(color)
            for shp in ais_shapes:
                self.Context.SetColor(shp, color, False)
        if transparency:
            shape_to_display.SetTransparency(transparency)
        if update:
            # only update when explicitely told to do so
            self.Context.Display(shape_to_display.GetHandle(), False)
            # especially this call takes up a lot of time...
            self.FitAll()
            self.Repaint()
        else:
            self.Context.Display(shape_to_display.GetHandle(), False)

        if SOLO:
            return ais_shapes[0]
        else:
            return shape_to_display
Ejemplo n.º 11
0
    def makeVertex(cls, x, y, z):

        return cls(BRepBuilderAPI_MakeVertex(gp_Pnt(x, y, z)).Vertex())
Ejemplo n.º 12
0
 def create_shape(self):
     d = self.declaration
     v = BRepBuilderAPI_MakeVertex(gp_Pnt(d.x, d.y, d.z))
     self.shape = v.Vertex()
Ejemplo n.º 13
0
def make_vertex(*args):
    vert = BRepBuilderAPI_MakeVertex(*args)
    with assert_isdone(vert, 'failed to produce vertex'):
        result = vert.Vertex()
        vert.Delete()
        return result
Ejemplo n.º 14
0
    def _write_blade_errors(self, upper_face, lower_face, errors):
        """
        Private method to write the errors between the generated foil points in
        3D space from the parametric transformations, and their projections on
        the generated blade faces from the OCC algorithm.

        :param string upper_face: if string is passed then the method generates
            the blade upper surface using the BRepOffsetAPI_ThruSections
            algorithm, then exports the generated CAD into .iges file holding
            the name <upper_face_string>.iges
        :param string lower_face: if string is passed then the method generates
            the blade lower surface using the BRepOffsetAPI_ThruSections
            algorithm, then exports the generated CAD into .iges file holding
            the name <lower_face_string>.iges
        :param string errors: if string is passed then the method writes out
            the distances between each discrete point used to construct the
            blade and the nearest point on the CAD that is perpendicular to
            that point
        """
        from OCC.gp import gp_Pnt
        from OCC.BRepBuilderAPI import BRepBuilderAPI_MakeVertex
        from OCC.BRepExtrema import BRepExtrema_DistShapeShape

        output_string = '\n'
        with open(errors + '.txt', 'w') as f:
            if upper_face:
                output_string += '########## UPPER FACE ##########\n\n'
                output_string += 'N_section\t\tN_point\t\t\tX_crds\t\t\t\t'
                output_string += 'Y_crds\t\t\t\t\tZ_crds\t\t\t\t\tDISTANCE'
                output_string += '\n\n'
                for i in range(self.n_sections):
                    alength = len(self.blade_coordinates_up[i][0])
                    for j in range(alength):
                        vertex = BRepBuilderAPI_MakeVertex(
                            gp_Pnt(
                                1000 * self.blade_coordinates_up[i][0][j],
                                1000 * self.blade_coordinates_up[i][1][j],
                                1000 *
                                self.blade_coordinates_up[i][2][j])).Vertex()
                        projection = BRepExtrema_DistShapeShape(
                            self.generated_upper_face, vertex)
                        projection.Perform()
                        output_string += str(i) + '\t\t\t' + str(
                            j) + '\t\t\t' + str(
                                1000 *
                                self.blade_coordinates_up[i][0][j]) + '\t\t\t'
                        output_string += str(
                            1000 * self.blade_coordinates_up[i][1][j]
                        ) + '\t\t\t' + str(
                            1000 * self.blade_coordinates_up[i][2][j]
                        ) + '\t\t\t' + str(projection.Value())
                        output_string += '\n'

            if lower_face:
                output_string += '########## LOWER FACE ##########\n\n'
                output_string += 'N_section\t\tN_point\t\t\tX_crds\t\t\t\t'
                output_string += 'Y_crds\t\t\t\t\tZ_crds\t\t\t\t\tDISTANCE'
                output_string += '\n\n'
                for i in range(self.n_sections):
                    alength = len(self.blade_coordinates_down[i][0])
                    for j in range(alength):
                        vertex = BRepBuilderAPI_MakeVertex(
                            gp_Pnt(1000 * self.blade_coordinates_down[i][0][j],
                                   1000 * self.blade_coordinates_down[i][1][j],
                                   1000 * self.blade_coordinates_down[i][2][j])
                        ).Vertex()
                        projection = BRepExtrema_DistShapeShape(
                            self.generated_lower_face, vertex)
                        projection.Perform()
                        output_string += str(i) + '\t\t\t' + str(
                            j) + '\t\t\t' + str(
                                1000 * self.blade_coordinates_down[i][0][j]
                            ) + '\t\t\t'
                        output_string += str(
                            1000 * self.blade_coordinates_down[i][1][j]
                        ) + '\t\t\t' + str(
                            1000 * self.blade_coordinates_down[i][2][j]
                        ) + '\t\t\t' + str(projection.Value())
                        output_string += '\n'
            f.write(output_string)