Ejemplo n.º 1
0
def vertex_fillet(cube, vert):
    # apply a fillet on incident edges on a vertex
    afillet = BRepFilletAPI_MakeFillet(cube)
    cnt = 0
    # find edges from vertex
    _map = TopTools_IndexedDataMapOfShapeListOfShape()
    topexp_MapShapesAndAncestors(cube, TopAbs_VERTEX, TopAbs_EDGE, _map)
    results = _map.FindFromKey(vert)
    topology_iterator = TopTools_ListIteratorOfListOfShape(results)
    while topology_iterator.More():
        edge = topods_Edge(topology_iterator.Value())
        topology_iterator.Next()
        first, last = topexp_FirstVertex(edge), topexp_LastVertex(edge)
        vertex, first_vert, last_vert = BRep_Tool().Pnt(vert), BRep_Tool().Pnt(
            first), BRep_Tool().Pnt(last)
        if edge.Orientation():
            if not vertex.IsEqual(first_vert, 0.001):
                afillet.Add(0, 20., edge)
            else:
                afillet.Add(20, 0, edge)
        cnt += 1
    afillet.Build()
    if afillet.IsDone():
        return afillet.Shape()
    else:
        raise AssertionError('you failed on me you fool!')
Ejemplo n.º 2
0
 def project_curve(self, other):
     # this way Geom_Circle and alike are valid too
     if (isinstance(other, TopoDS_Edge) or isinstance(other, Geom_Curve)
             or issubclass(other, Geom_Curve)):
         # convert edge to curve
         first, last = topexp.FirstVertex(other), topexp.LastVertex(other)
         lbound, ubound = BRep_Tool().Parameter(
             first, other), BRep_Tool().Parameter(last, other)
         other = BRep_Tool.Curve(other, lbound, ubound).GetObject()
         return geomprojlib.Project(other, self.surface_handle)
Ejemplo n.º 3
0
def sort_edges_into_order(occedgelist, isclosed=False):
    from OCC.TopoDS import topods
    from OCC.TopExp import topexp
    from OCC.BRep import BRep_Tool
    from OCC.ShapeAnalysis import ShapeAnalysis_WireOrder
    from OCC.Precision import precision

    sawo_statusdict = {
        0: "all edges are direct and in sequence",
        1: "all edges are direct but some are not in sequence",
        2: "unresolved gaps remain",
        -1: "some edges are reversed, but no gaps remain",
        -2: "some edges are reversed and some gaps remain",
        -10: "failure on reorder"
    }

    mode3d = True
    SAWO = ShapeAnalysis_WireOrder(mode3d, precision.PConfusion())

    for occedge in occedgelist:
        V1 = topexp.FirstVertex(topods.Edge(occedge))
        V2 = topexp.LastVertex(topods.Edge(occedge))
        pnt1 = BRep_Tool().Pnt(V1)
        pnt2 = BRep_Tool().Pnt(V2)
        SAWO.Add(pnt1.XYZ(), pnt2.XYZ())
        SAWO.SetKeepLoopsMode(True)

    SAWO.Perform(isclosed)
    #print "SAWO.Status()", SAWO.Status()
    if not SAWO.IsDone():
        raise RuntimeError, "build wire: Unable to reorder edges: \n" + sawo_statusdict[
            SAWO.Status()]
    else:
        if SAWO.Status() not in [0, -1]:
            pass  # not critical, wirebuilder will handle this
        SAWO.SetChains(precision.PConfusion())
        sorted_edge2dlist = []
        #print "Number of chains: ", SAWO.NbChains()
        for i in range(SAWO.NbChains()):
            sorted_edges = []
            estart, eend = SAWO.Chain(i + 1)
            #print "Number of edges in chain", i, ": ", eend - estart + 1
            if (eend - estart + 1) == 0:
                continue
            for j in range(estart, eend + 1):
                idx = abs(SAWO.Ordered(j))
                edge2w = occedgelist[idx - 1]
                if SAWO.Ordered(j) < 0:
                    edge2w.Reverse()
                sorted_edges.append(edge2w)

            sorted_edge2dlist.append(sorted_edges)

    return sorted_edge2dlist
Ejemplo n.º 4
0
    def project_curve(self, other):
        # this way Geom_Circle and alike are valid too
        if isinstance(other, TopoDS_Edge) or\
             isinstance(other, Geom_Curve)  or\
             issubclass(other, Geom_Curve):
                if isinstance(other, TopoDS_Edge):
                    # convert edge to curve
                    first, last = TopExp.FirstVertex(other), TopExp.LastVertex(other)
                    lbound, ubound  = BRep_Tool().Parameter(first, other), BRep_Tool().Parameter(first, other)
                    other = BRep_Tool.Curve(other, lbound, ubound).GetObject()

                from OCC.GeomProjLib import GeomProjLib
                return GeomProjLib().Project(other, self.surface_handle)
Ejemplo n.º 5
0
 def curve(self):
     if self._curve is not None and not self.is_dirty:
         pass
     else:
         self._curve_handle = BRep_Tool().Curve(self)[0]
         self._curve = self._curve_handle.GetObject()
     return self._curve
Ejemplo n.º 6
0
 def pcurve(self, face):
     """
     computes the 2d parametric spline that lies on the surface of the face
     :return: Geom2d_Curve, u, v
     """
     crv, u, v = BRep_Tool().CurveOnSurface(self, face)
     return crv.GetObject(), u, v
Ejemplo n.º 7
0
def simple_mesh(occshape, mesh_incremental_float=0.8):
    #TODO: figure out why is it that some surfaces do not work
    occshape = TopoDS_Shape(occshape)
    bt = BRep_Tool()
    BRepMesh_IncrementalMesh(occshape, mesh_incremental_float)
    occshape_face_list = fetch.geom_explorer(occshape, "face")
    occface_list = []
    for occshape_face in occshape_face_list:
        location = TopLoc_Location()
        #occshape_face = modify.fix_face(occshape_face)
        facing = bt.Triangulation(occshape_face, location).GetObject()
        if facing:
            tab = facing.Nodes()
            tri = facing.Triangles()
            for i in range(1, facing.NbTriangles() + 1):
                trian = tri.Value(i)
                index1, index2, index3 = trian.Get()
                #print index1, index2, index3
                pypt1 = fetch.occpt2pypt(tab.Value(index1))
                pypt2 = fetch.occpt2pypt(tab.Value(index2))
                pypt3 = fetch.occpt2pypt(tab.Value(index3))
                #print pypt1, pypt2, pypt3
                occface = make_polygon([pypt1, pypt2, pypt3])
                occface_list.append(occface)
    return occface_list
def occ_triangle_mesh(event=None):
    #
    # Mesh the shape
    #
    BRepMesh_IncrementalMesh(aShape, 0.1)
    builder = BRep_Builder()
    Comp = TopoDS_Compound()
    builder.MakeCompound(Comp)

    ex = TopExp_Explorer(aShape, TopAbs_FACE)
    while ex.More():
        F = topods_Face(ex.Current())
        L = TopLoc_Location()
        facing = (BRep_Tool().Triangulation(F, L)).GetObject()
        tab = facing.Nodes()
        tri = facing.Triangles()
        for i in range(1, facing.NbTriangles() + 1):
            trian = tri.Value(i)
            #print trian
            index1, index2, index3 = trian.Get()
            for j in range(1, 4):
                if j == 1:
                    M = index1
                    N = index2
                elif j == 2:
                    N = index3
                elif j == 3:
                    M = index2
                ME = BRepBuilderAPI_MakeEdge(tab.Value(M), tab.Value(N))
                if ME.IsDone():
                    builder.Add(Comp, ME.Edge())
        ex.Next()
    display.DisplayShape(Comp, update=True)
Ejemplo n.º 9
0
def face_normal(face):
    umin, umax, vmin, vmax = BRepTools.BRepTools().UVBounds(face)
    surf = BRep_Tool().Surface(face)
    props = GeomLProp_SLProps(surf, (umin + umax) / 2., (vmin + vmax) / 2., 1,
                              TOLERANCE)
    norm = props.Normal()
    if face.Orientation() == TopAbs_REVERSED:
        norm.Reverse()
    return norm
def uv_from_projected_point_on_face(face, pt):
    '''
    returns the uv coordinate from a projected point on a face
    '''
    srf = BRep_Tool().Surface(face)
    sas = ShapeAnalysis_Surface(srf)
    uv = sas.ValueOfUV(pt, 1e-2)
    print('distance ', sas.Value(uv).Distance(pt))
    return uv.Coord()
Ejemplo n.º 11
0
def process_wire(wire):
    '''takes a wire and extracts points
    returns a list of points'''
    vertices = []
    explorer = BRepTools_WireExplorer(wire)
    while explorer.More():
        vertex = TopoDS().Vertex(explorer.CurrentVertex())
        xyz = Point(BRep_Tool().Pnt(vertex))
        vertices.append(xyz)
        explorer.Next()
    return vertices
Ejemplo n.º 12
0
def face_normal(face: TopoDS_Face) -> gp_Dir:
    """

    :param face:
    :return:
    """
    umin, umax, vmin, vmax = breptools_UVBounds(face)
    surf = BRep_Tool().Surface(face)
    props = GeomLProp_SLProps(surf, (umin + umax) / 2., (vmin + vmax) / 2., 1,
                              TOLERANCE)
    norm = props.Normal()
    if face.Orientation() == TopAbs_REVERSED:
        norm.Reverse()
    return norm
Ejemplo n.º 13
0
def make_coons(edges):
    bt = BRep_Tool()
    if len(edges) == 4:
        spl1, spl2, spl3, spl4 = edges  #[curve_to_bspline(bt.Curve(i)[0]) for i in edges]
        srf = GeomFill_BSplineCurves(spl1, spl2, spl3, spl4,
                                     GeomFill_StretchStyle)
    elif len(edges) == 3:
        spl1, spl2, spl3 = edges  #[curve_to_bspline(bt.Curve(i)[0]) for i in edges]
        srf = GeomFill_BSplineCurves(spl1, spl2, spl3, GeomFill_StretchStyle)
    elif len(edges) == 2:
        spl1, spl2 = edges  #[curve_to_bspline(bt.Curve(i)[0]) for i in edges]
        srf = GeomFill_BSplineCurves(spl1, spl2, GeomFill_StretchStyle)
    else:
        raise ValueError('give 2,3 or 4 curves')
    return srf.Surface()
Ejemplo n.º 14
0
    def continuity_edge_face(self, edge, face):
        """
        compute the continuity between two faces at :edge:

        :param edge: an Edge or TopoDS_Edge from :face:
        :param face: a Face or TopoDS_Face
        :return: bool, GeomAbs_Shape if it has continuity, otherwise
         False, None
        """
        bt = BRep_Tool()
        if bt.HasContinuity(edge, self, face):
            continuity = bt.Continuity(edge, self, face)
            return True, continuity
        else:
            return False, None
Ejemplo n.º 15
0
 def __init__(self, pnt):
     if isinstance(pnt, (list, tuple)):
         gp_Pnt.__init__(self, *pnt)
     elif isinstance(pnt, vec):
         gp_Pnt.__init__(self, *pnt)
     elif isinstance(pnt, gp_Pnt):
         gp_Pnt.__init__(self, pnt)
     elif isinstance(pnt, TopoDS_Vertex):
         # convert to type "gp_Pnt"
         gp_Pnt.__init__(self, BRep_Tool.Pnt(pnt))
     elif isinstance(pnt, TopoDS_Shape):
         self.brt = BRep_Tool()
         self.pnt1 = self.brt.Pnt(topods_Vertex(pnt))
         gp_Pnt.__init__(self, self.pnt1.XYZ())
     else:
         raise TypeError
Ejemplo n.º 16
0
def format_wire_for_roboDK(wire, is_reverse=False):
    vertices = sweeper.get_ordered_vertices_from_wire(wire)
    brt = BRep_Tool()
    wire = []
    last_path_direction = None
    for i in range(len(vertices)):
        index = i
        next_index = index + 1
        if is_reverse:
            index = len(vertices) - 1 - i
            next_index = index - 1
        v = vertices[index]
        pnt = brt.Pnt(topods_Vertex(v))
        normal = get_vertex_normal(v, front_face)
        if not ((index == 0 and is_reverse) or
                (index == len(vertices) - 1 and not is_reverse)):
            pnt_next = brt.Pnt(topods_Vertex(vertices[next_index]))
            mat_pnt = numpy.mat([pnt.X(), pnt.Y(), pnt.Z()])
            mat_pnt_next = numpy.mat(
                [pnt_next.X(), pnt_next.Y(),
                 pnt_next.Z()])
            path_direction = mat_pnt_next - mat_pnt
            path_direction = path_direction / scipy.linalg.norm(path_direction)
            last_path_direction = path_direction
        else:
            path_direction = last_path_direction
        #direction should be away from base_position
        p1 = [pnt.X() + normal.X(), pnt.Y() + normal.Y(), pnt.Z() + normal.Z()]
        p2 = [pnt.X() - normal.X(), pnt.Y() - normal.Y(), pnt.Z() - normal.Z()]
        #normal vector should point towards base_position
        if sweeper.get_distance_points(
                p1, sweeper.base_position) < sweeper.get_distance_points(
                    p2, sweeper.base_position):
            direction = [normal.X(), normal.Y(), normal.Z()]
        else:
            direction = [-normal.X(), -normal.Y(), -normal.Z()]
        wire.append({
            "location": [pnt.X(), pnt.Y(), pnt.Z()],
            "direction":
            direction,
            "path_direction": [
                path_direction.item(0),
                path_direction.item(1),
                path_direction.item(2)
            ]
        })
    return wire
Ejemplo n.º 17
0
def GetFacesSurfaces(BRepShape):
    FaceExplorer = TopExp_Explorer(BRepShape, TopAbs_FACE)

    Faces = []
    while FaceExplorer.More():
        ShapeFace = FaceExplorer.Current()  # a TopoDS_Shape
        # Convert TopoDS_Shape to a TopoDS_Face
        Face = topods.Face(ShapeFace)

        Faces.append(Face)
        FaceExplorer.Next()
        pass

    Surfaces = [BRep_Tool().Surface(Face) for Face in Faces]
    SurfObjs = [Surface.GetObject() for Surface in Surfaces]

    return (Faces, Surfaces, SurfObjs)
Ejemplo n.º 18
0
def dumpTopology(shape, level=0):
    """
     Print the details of an object from the top down
    """
    brt = BRep_Tool()
    s = shape.ShapeType()
    if s == TopAbs_VERTEX:
        pnt = brt.Pnt(topods_Vertex(shape))
        print(".." * level  + "<Vertex %i: %s %s %s>" % (hash(shape), pnt.X(), pnt.Y(), pnt.Z()))
    else:
        print(".." * level, end="")
        print(shapeTypeString(shape))
    it = TopoDS_Iterator(shape)
    while it.More():
        shp = it.Value()
        it.Next()
        dumpTopology(shp, level + 1)
Ejemplo n.º 19
0
    def continuity_edge_face(self, edge, face):
        """
        compute the continuity between two faces at :edge:

        :param edge: an Edge or TopoDS_Edge from :face:
        :param face: a Face or TopoDS_Face
        :return: bool, GeomAbs_Shape if it has continuity, otherwise
         False, None
        """
        edge = edge if not isinstance(edge,KbeObject) else edge.topo
        face = face if not isinstance(face, KbeObject) else face.topo
        bt = BRep_Tool()
        if bt.HasContinuity(edge, self.topo, face):
            continuity = bt.Continuity(edge, self.topo, face)
            return True, continuity
        else:
            return False, None
Ejemplo n.º 20
0
    def __init__(self, wireA, wireB):
        self.wireA = wireA
        self.wireB = wireB
        self.we_A = WireExplorer(self.wireA)
        self.we_B = WireExplorer(self.wireB)
        self.tp_A = Topo(self.wireA)
        self.tp_B = Topo(self.wireB)
        self.bt = BRep_Tool()
        self.vertsA = [v for v in self.we_A.ordered_vertices()]
        self.vertsB = [v for v in self.we_B.ordered_vertices()]

        self.edgesA = [v for v in WireExplorer(wireA).ordered_edges()]
        self.edgesB = [v for v in WireExplorer(wireB).ordered_edges()]

        self.pntsB = [self.bt.Pnt(v) for v in self.vertsB]
        self.number_of_vertices = len(self.vertsA)
        self.index = 0
Ejemplo n.º 21
0
def dump_topology_to_string(shape, level=0, buffer=""):
    """
    Reutnrs the details of an object from the top down
    """
    brt = BRep_Tool()
    s = shape.ShapeType()
    if s == TopAbs_VERTEX:
        pnt = brt.Pnt(topods_Vertex(shape))
        print(".." * level + "<Vertex %i: %s %s %s>\n" %
              (hash(shape), pnt.X(), pnt.Y(), pnt.Z()))
    else:
        print(".." * level, end="")
        print(shape_type_string(shape))
    it = TopoDS_Iterator(shape)
    while it.More() and level < 5:  # LEVEL MAX
        shp = it.Value()
        it.Next()
        print(dump_topology_to_string(shp, level + 1, buffer))
def radius_at_uv(face, u, v):
    '''
    returns the mean radius at a u,v coordinate
    @param face:    surface input
    @param u,v:     u,v coordinate
    '''
    h_srf = BRep_Tool().Surface(face)
    uv_domain = GeomLProp_SurfaceTool().Bounds(h_srf)
    curvature = GeomLProp_SLProps(h_srf, u, v, 1, 1e-6)
    try:
        _crv_min = 1. / curvature.MinCurvature()
    except ZeroDivisionError:
        _crv_min = 0.

    try:
        _crv_max = 1. / curvature.MaxCurvature()
    except ZeroDivisionError:
        _crv_max = 0.
    return abs((_crv_min + _crv_max) / 2.)
Ejemplo n.º 23
0
def make_point(vertex):
    #print "make_point: vertex=", vertex
    if isinstance(vertex, TopoDS_Vertex):
        #first check to see if it points anywhere
        location = vertex.Location()
        if location.IsDifferent(location.__class__()) == 1:
            print "making a gp_Pnt"
            pnt = BRep_Tool().Pnt(vertex)
            print "making a point"
            return Point(pnt)
        else:
            print "vertex wasn't anything special"
            return Point(0, 0, 0)  #but it might not actually be 0,0,0
    elif isinstance(vertex, Point):
        return vertex
    elif isinstance(vertex, gp_Pnt):
        return Point(vertex)
    else:
        return vertex
Ejemplo n.º 24
0
def simple_mesh():
    #
    # Create the shape
    #
    shape = BRepPrimAPI_MakeBox(200, 200, 200).Shape()
    theBox = BRepPrimAPI_MakeBox(200, 60, 60).Shape()
    theSphere = BRepPrimAPI_MakeSphere(gp_Pnt(100, 20, 20), 80).Shape()
    shape = BRepAlgoAPI_Fuse(theSphere, theBox).Shape()
    #
    # Mesh the shape
    #
    BRepMesh_IncrementalMesh(shape, 0.8)
    builder = BRep_Builder()
    comp = TopoDS_Compound()
    builder.MakeCompound(comp)

    bt = BRep_Tool()
    ex = TopExp_Explorer(shape, TopAbs_FACE)
    while ex.More():
        face = topods_Face(ex.Current())
        location = TopLoc_Location()
        facing = (bt.Triangulation(face, location)).GetObject()
        tab = facing.Nodes()
        tri = facing.Triangles()
        for i in range(1, facing.NbTriangles()+1):
            trian = tri.Value(i)
            index1, index2, index3 = trian.Get()
            for j in range(1, 4):
                if j == 1:
                    m = index1
                    n = index2
                elif j == 2:
                    n = index3
                elif j == 3:
                    m = index2
                me = BRepBuilderAPI_MakeEdge(tab.Value(m), tab.Value(n))
                if me.IsDone():
                    builder.Add(comp, me.Edge())
        ex.Next()
    display.EraseAll()
    display.DisplayShape(shape)
    display.DisplayShape(comp, update=True)
Ejemplo n.º 25
0
 def DumpTop(self, shape, level=0):
     """
     Print the details of an object from the top down
     """
     brt = BRep_Tool()
     s = shape.ShapeType()
     if s == TopAbs_VERTEX:
         pnt = brt.Pnt(topods_Vertex(shape))
         dmp = " " * level
         dmp += "%s - " % shapeTypeString(shape)
         dmp += "%.5e %.5e %.5e" % (pnt.X(), pnt.Y(), pnt.Z())
         print(dmp)
     else:
         dmp = " " * level
         dmp += shapeTypeString(shape)
         print(dmp)
     it = TopoDS_Iterator(shape)
     while it.More():
         shp = it.Value()
         it.Next()
         self.DumpTop(shp, level + 1)
Ejemplo n.º 26
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.º 27
0
def arrange_edges_2_wires(occedgelist, isclosed=False):
    from OCC.TopoDS import topods
    from OCC.TopExp import topexp
    from OCC.BRep import BRep_Tool
    from OCC.ShapeAnalysis import ShapeAnalysis_WireOrder
    from OCC.Precision import precision
    from OCC.BRepBuilderAPI import BRepBuilderAPI_WireDone, BRepBuilderAPI_EmptyWire, BRepBuilderAPI_DisconnectedWire, BRepBuilderAPI_NonManifoldWire

    wb_errdict = {
        BRepBuilderAPI_WireDone: "No error",
        BRepBuilderAPI_EmptyWire: "Empty wire",
        BRepBuilderAPI_DisconnectedWire: "disconnected wire",
        BRepBuilderAPI_NonManifoldWire: "non-manifold wire"
    }

    sawo_statusdict = {
        0: "all edges are direct and in sequence",
        1: "all edges are direct but some are not in sequence",
        2: "unresolved gaps remain",
        -1: "some edges are reversed, but no gaps remain",
        -2: "some edges are reversed and some gaps remain",
        -10: "failure on reorder"
    }

    mode3d = True
    SAWO = ShapeAnalysis_WireOrder(mode3d, precision.PConfusion())

    for edge in occedgelist:
        V1 = topexp.FirstVertex(topods.Edge(edge))
        V2 = topexp.LastVertex(topods.Edge(edge))
        pnt1 = BRep_Tool().Pnt(V1)
        pnt2 = BRep_Tool().Pnt(V2)
        SAWO.Add(pnt1.XYZ(), pnt2.XYZ())
        SAWO.SetKeepLoopsMode(True)

    SAWO.Perform(isclosed)
    #print "SAWO.Status()", SAWO.Status()
    if not SAWO.IsDone():
        raise RuntimeError, "build wire: Unable to reorder edges: \n" + sawo_statusdict[
            SAWO.Status()]
    else:
        if SAWO.Status() not in [0, -1]:
            pass  # not critical, wirebuilder will handle this
        SAWO.SetChains(precision.PConfusion())
        wirelist = []
        #print "Number of chains: ", SAWO.NbChains()

        for i in range(SAWO.NbChains()):
            wirebuilder = BRepBuilderAPI_MakeWire()
            estart, eend = SAWO.Chain(i + 1)
            #print "Number of edges in chain", i, ": ", eend - estart + 1
            if (eend - estart + 1) == 0:
                continue
            for j in range(estart, eend + 1):
                idx = abs(
                    SAWO.Ordered(j)
                )  # wirebuilder = s_addToWireBuilder(wirebuilder, edgelist[idx-1])
                edge2w = occedgelist[idx - 1]
                wirebuilder.Add(edge2w)
                if wirebuilder is None:
                    raise RuntimeError, " build wire: Error adding edge number " + str(
                        j + 1) + " to Wire number " + str(i)
                    err = wirebuilder.Error()
                    if err != BRepBuilderAPI_WireDone:
                        raise RuntimeError, "Overlay2D: build wire: Error adding edge number " + str(
                            j + 1) + " to Wire number " + str(
                                i) + ": \n" + wb_errdict[err]
                        try:
                            wirebuilder.Build()
                            aWire = wirebuilder.Wire()
                            wirelist.append(aWire)
                        except Exception, err:
                            raise RuntimeError, "Overlay2D: build wire: Creation of Wire number " + str(
                                i) + " from edge(s) failed. \n" + str(err)

            wirebuilder.Build()
            aWire = wirebuilder.Wire()
            wirelist.append(aWire)
Ejemplo n.º 28
0
#!/usr/bin/env python
Ejemplo n.º 29
0
def shape_to_pts(sh):
    return [BRep_Tool().Pnt(topods_Vertex(v)) for v in Topo(sh).vertices()]
Ejemplo n.º 30
0
    def __init__(self, shape):
        from OCC.BRep import BRep_Tool
        from OCC.BRepMesh import BRepMesh_IncrementalMesh
        from OCC.TopAbs import TopAbs_FACE, TopAbs_VERTEX
        from OCC.TopExp import TopExp_Explorer
        from OCC.TopLoc import TopLoc_Location
        from OCC.TopoDS import topods_Face, topods_Vertex, TopoDS_Iterator

        vertices = []  # a (nested) list of vec3
        triangles = []  # a (flat) list of integers
        normals = []
        uv = []

        # Mesh the shape
        linDeflection = 0.8
        BRepMesh_IncrementalMesh(shape, linDeflection)
        bt = BRep_Tool()

        # Explore the faces of the shape
        # each face is triangulated, we need to collect all the parts
        expFac = TopExp_Explorer(shape, TopAbs_FACE)
        while expFac.More():
            face = topods_Face(expFac.Current())
            location = TopLoc_Location()
            facing = (bt.Triangulation(face, location)).GetObject()
            try:
                tri = facing.Triangles()
                nTri = facing.NbTriangles()
                ver = facing.Nodes()
            except:
                tri = None
                nTri = None
                ver = None
            # store origin of the face's local coordinates
            transf = face.Location().Transformation()

            # iterate over triangles and store indices of vertices defining each triangle
            # OCC uses one-based indexing
            for i in range(1, nTri + 1):
                # each triangle is defined by three points
                # each point is defined by its index in the list of vertices
                index1, index2, index3 = tri.Value(i).Get()
                indices = [index1, index2, index3]

                # python uses zero-based indexing
                # for each vertex of a triangle, check whether it is already known
                # then store it (or not) and update the index
                for idx in [0, 1, 2]:
                    # read global coordinates of each point
                    vec3 = [
                        ver.Value(indices[idx]).Transformed(transf).X(),
                        ver.Value(indices[idx]).Transformed(transf).Y(),
                        ver.Value(indices[idx]).Transformed(transf).Z()
                    ]
                    if vec3 not in vertices:
                        vertices.append(vec3)
                    indices[idx] = vertices.index(vec3)
                triangles.extend(indices)
            expFac.Next()

        self.shape = shape
        self.vertices = vertices
        self.triangles = triangles
        self.normals = normals
        self.uv = uv