Example #1
0
 def __init__(self, shape):
     if not shape.IsNull():
         if not shape.ShapeType() == Shape.WIRE:
             raise TypeError('Shape is not a TopoDS_Wire.')
         if not isinstance(shape, TopoDS_Wire):
             shape = topods.Wire(shape)
     super(Wire, self).__init__(shape)
Example #2
0
    def build_new_face(self, face, zpos, product):
        exp = TopExp.TopExp_Explorer(face, TopAbs.TopAbs_WIRE)
        while exp.More():
            wireexp = BRepTools.BRepTools_WireExplorer(
                topods.Wire(exp.Current()))
            new_wire_builder = BRepBuilderAPI.BRepBuilderAPI_MakeWire()
            first_vertex = None
            previous_vertex = None
            while wireexp.More():
                current_vertex = wireexp.CurrentVertex()
                current_point = BRep.BRep_Tool.Pnt(current_vertex)
                # Dodgy technique to squash in Z axis
                current_point.SetZ(zpos)
                current_vertex = BRepBuilderAPI.BRepBuilderAPI_MakeVertex(
                    current_point).Vertex()
                if not first_vertex:
                    first_vertex = current_vertex
                if not previous_vertex:
                    previous_vertex = current_vertex
                else:
                    try:
                        new_wire_builder.Add(
                            topods.Edge(
                                BRepBuilderAPI.BRepBuilderAPI_MakeEdge(
                                    previous_vertex, current_vertex).Edge()))
                        previous_vertex = current_vertex
                    except:
                        pass
                wireexp.Next()

                # make last edge
                if not wireexp.More():
                    try:
                        new_wire_builder.Add(
                            topods.Edge(
                                BRepBuilderAPI.BRepBuilderAPI_MakeEdge(
                                    current_vertex, first_vertex).Edge()))
                    except:
                        pass
            try:
                new_wire = new_wire_builder.Wire()
                new_face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(
                    new_wire).Face()
                self.background_elements.append({
                    'raw': product,
                    'geometry': new_wire,
                    'geometry_face': new_face,
                    'type': 'polygon',
                    'z': zpos
                })
            except:
                #print('Could not build face')
                pass
            exp.Next()
Example #3
0
def do_cut(process_data):
    global_id, shape, section, trsf_data = process_data

    axis = gp.gp_Ax2(
        gp.gp_Pnt(trsf_data['top_left_corner'][0],
                  trsf_data['top_left_corner'][1],
                  trsf_data['top_left_corner'][2]),
        gp.gp_Dir(trsf_data['projection'][0], trsf_data['projection'][1],
                  trsf_data['projection'][2]),
        gp.gp_Dir(trsf_data['x_axis'][0], trsf_data['x_axis'][1],
                  trsf_data['x_axis'][2]))
    source = gp.gp_Ax3(axis)
    destination = gp.gp_Ax3(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(0, 0, -1),
                            gp.gp_Dir(1, 0, 0))
    transformation = gp.gp_Trsf()
    transformation.SetDisplacement(source, destination)

    cut_polygons = []
    section = BRepAlgoAPI.BRepAlgoAPI_Section(section, shape).Shape()
    section_edges = get_booleaned_edges(section)
    if len(section_edges) <= 0:
        return cut_polygons
    wires = connect_edges_into_wires(section_edges)
    for i in range(wires.Length()):
        wire_shape = wires.Value(i + 1)

        transformed_wire = BRepBuilderAPI.BRepBuilderAPI_Transform(
            wire_shape, transformation)
        wire_shape = transformed_wire.Shape()

        wire = topods.Wire(wire_shape)
        face = BRepBuilderAPI.BRepBuilderAPI_MakeFace(wire).Face()

        points = []
        exp = BRepTools.BRepTools_WireExplorer(wire)
        while exp.More():
            point = BRep.BRep_Tool.Pnt(exp.CurrentVertex())
            points.append((point.X(), -point.Y()))
            exp.Next()
        cut_polygons.append({
            'global_id': global_id,
            'metadata': {},
            'points': points
        })
    return cut_polygons
Example #4
0
 def get_wire(self):
     if (self.wire == None):
         occ_edges = []
         for i, e in enumerate(self.edges):
             o = "Element %i/%i: " % (i, len(self.edges))
             if (isinstance(e, Line3)):
                 occ_edges.append(e.to_edge())
             elif (isinstance(e, Fillet2)):
                 if ((len(self.edges)) <= (i + 1)):
                     error("Not enough elements for fillet")
                     exit(0)
                 else:
                     occ_edges.append(
                         e.to_edge(self.edges[i - 1], self.edges[i + 1]))
             o += repr(e)
             debug(o)
         if occ_edges == []:
             return None
         self.wire = make_wire(occ_edges)
         trsf_wire = BRepBuilderAPI_Transform(self.wire, self.trsf)
         trsf_shape = trsf_wire.Shape()
         self.wire = topods.Wire(trsf_shape)
         self.face = None
     return self.wire
Example #5
0
def startBottle(startOnly=True):  # minus the neck fillet, shelling & threads
    partName = "Bottle-start"
    # The points we'll use to create the profile of the bottle's body
    aPnt1 = gp_Pnt(-width / 2.0, 0, 0)
    aPnt2 = gp_Pnt(-width / 2.0, -thickness / 4.0, 0)
    aPnt3 = gp_Pnt(0, -thickness / 2.0, 0)
    aPnt4 = gp_Pnt(width / 2.0, -thickness / 4.0, 0)
    aPnt5 = gp_Pnt(width / 2.0, 0, 0)

    aArcOfCircle = GC_MakeArcOfCircle(aPnt2, aPnt3, aPnt4)
    aSegment1 = GC_MakeSegment(aPnt1, aPnt2)
    aSegment2 = GC_MakeSegment(aPnt4, aPnt5)

    # Could also construct the line edges directly using the points
    # instead of the resulting line.
    aEdge1 = BRepBuilderAPI_MakeEdge(aSegment1.Value())
    aEdge2 = BRepBuilderAPI_MakeEdge(aArcOfCircle.Value())
    aEdge3 = BRepBuilderAPI_MakeEdge(aSegment2.Value())

    # Create a wire out of the edges
    aWire = BRepBuilderAPI_MakeWire(aEdge1.Edge(), aEdge2.Edge(),
                                    aEdge3.Edge())

    # Quick way to specify the X axis
    xAxis = gp_OX()

    # Set up the mirror
    aTrsf = gp_Trsf()
    aTrsf.SetMirror(xAxis)

    # Apply the mirror transformation
    aBRespTrsf = BRepBuilderAPI_Transform(aWire.Wire(), aTrsf)

    # Get the mirrored shape back out of the transformation
    # and convert back to a wire
    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.Shape()

    # Create the neck of the bottle
    neckLocation = gp_Pnt(0, 0, height)
    neckAxis = gp_DZ()
    neckAx2 = gp_Ax2(neckLocation, neckAxis)

    myNeckRadius = thickness / 4.0
    myNeckHeight = height / 10.0

    mkCylinder = BRepPrimAPI_MakeCylinder(neckAx2, myNeckRadius, myNeckHeight)
    myBody = BRepAlgoAPI_Fuse(myBody, mkCylinder.Shape())
    if startOnly:  # quit here
        uid = win.getNewPartUID(myBody.Shape(), name=partName)
        win.redraw()
        return

    partName = "Bottle-complete"
    # Our goal is to find the highest Z face and remove it
    faceToRemove = None
    zMax = -1

    # We have to work our way through all the faces to find the highest Z face
    aFaceExplorer = TopExp_Explorer(myBody.Shape(), TopAbs_FACE)
    while aFaceExplorer.More():
        aFace = topods.Face(aFaceExplorer.Current())

        if face_is_plane(aFace):
            aPlane = geom_plane_from_face(aFace)

            # We want the highest Z face, so compare this to the previous faces
            aPnt = aPlane.Location()
            aZ = aPnt.Z()
            if aZ > zMax:
                zMax = aZ
                faceToRemove = aFace

        aFaceExplorer.Next()

    facesToRemove = TopTools_ListOfShape()
    facesToRemove.Append(faceToRemove)

    myBody = BRepOffsetAPI_MakeThickSolid(myBody.Shape(), facesToRemove,
                                          -thickness / 50.0, 0.001)

    # Set up our surfaces for the threading on the neck
    neckAx2_Ax3 = gp_Ax3(neckLocation, gp_DZ())
    aCyl1 = Geom_CylindricalSurface(neckAx2_Ax3, myNeckRadius * 0.99)
    aCyl2 = Geom_CylindricalSurface(neckAx2_Ax3, myNeckRadius * 1.05)

    # Set up the curves for the threads on the bottle's neck
    aPnt = gp_Pnt2d(2.0 * math.pi, myNeckHeight / 2.0)
    aDir = gp_Dir2d(2.0 * math.pi, myNeckHeight / 4.0)
    anAx2d = gp_Ax2d(aPnt, aDir)

    aMajor = 2.0 * math.pi
    aMinor = myNeckHeight / 10.0

    anEllipse1 = Geom2d_Ellipse(anAx2d, aMajor, aMinor)
    anEllipse2 = Geom2d_Ellipse(anAx2d, aMajor, aMinor / 4.0)

    anArc1 = Geom2d_TrimmedCurve(anEllipse1, 0, math.pi)
    anArc2 = Geom2d_TrimmedCurve(anEllipse2, 0, math.pi)

    anEllipsePnt1 = anEllipse1.Value(0)
    anEllipsePnt2 = anEllipse1.Value(math.pi)

    aSegment = GCE2d_MakeSegment(anEllipsePnt1, anEllipsePnt2)

    # Build edges and wires for threading
    anEdge1OnSurf1 = BRepBuilderAPI_MakeEdge(anArc1, aCyl1)
    anEdge2OnSurf1 = BRepBuilderAPI_MakeEdge(aSegment.Value(), aCyl1)
    anEdge1OnSurf2 = BRepBuilderAPI_MakeEdge(anArc2, aCyl2)
    anEdge2OnSurf2 = BRepBuilderAPI_MakeEdge(aSegment.Value(), aCyl2)

    threadingWire1 = BRepBuilderAPI_MakeWire(anEdge1OnSurf1.Edge(),
                                             anEdge2OnSurf1.Edge())
    threadingWire2 = BRepBuilderAPI_MakeWire(anEdge1OnSurf2.Edge(),
                                             anEdge2OnSurf2.Edge())

    # Compute the 3D representations of the edges/wires
    breplib.BuildCurves3d(threadingWire1.Shape())
    breplib.BuildCurves3d(threadingWire2.Shape())

    # Create the surfaces of the threading
    aTool = BRepOffsetAPI_ThruSections(True)
    aTool.AddWire(threadingWire1.Wire())
    aTool.AddWire(threadingWire2.Wire())
    aTool.CheckCompatibility(False)
    myThreading = aTool.Shape()

    # Build the resulting compound
    aRes = TopoDS_Compound()
    aBuilder = BRep_Builder()
    aBuilder.MakeCompound(aRes)
    aBuilder.Add(aRes, myBody.Shape())
    aBuilder.Add(aRes, myThreading)
    uid = win.getNewPartUID(aRes, name=partName)
    win.redraw()
Example #6
0
 def Wire(self): return topods.Wire(self._shp)
 def Edge(self): return topods.Edge(self._shp)
# Quick way to specify the X axis
xAxis = gp_OX()

# Set up the mirror
aTrsf = gp_Trsf()
aTrsf.SetMirror(xAxis)

# Apply the mirror transformation
aBRespTrsf = BRepBuilderAPI_Transform(aWire.Wire(), aTrsf)

# Get the mirrored shape back out of the transformation and convert back to a wire
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_step1 = BRepPrimAPI_MakePrism(myFaceProfile.Face(), aPrismVec)

# Add fillets to all edges through the explorer
Example #8
0
 def transform(self, trsf):
     self.wire = topods.Wire(
         BRepBuilderAPI_Transform(self.get_wire(), trsf, True).Shape())
Example #9
0
from OCC.Core.BRep import BRep_Builder
from OCC.Core.BRepTools import breptools
from OCC.Core.BRepAdaptor import BRepAdaptor_CompCurve, BRepAdaptor_HCompCurve
from OCC.Core.ShapeAnalysis import ShapeAnalysis_Curve
from OCC.Core.TopoDS import TopoDS_Shape, topods
from OCC.Core.gp import gp_Pnt
from OCC.Core.Approx import Approx_Curve3d
from OCC.Core.GeomAbs import GeomAbs_C2
from OCC.Core.GeomAPI import GeomAPI_ProjectPointOnCurve

# Read wire
wire_filename = os.path.join('..', 'assets', 'models', 'wire.brep')
shp = TopoDS_Shape()
aBuilder = BRep_Builder()
breptools.Read(shp, wire_filename, aBuilder)
wire = topods.Wire(shp)
if wire.IsNull():
    raise AssertionError("Wire is Null")

# discretize the wire and interpolate using a C2
wireAdaptor = BRepAdaptor_CompCurve(wire)
curve = BRepAdaptor_HCompCurve(wireAdaptor)
tol = 1e-7
max_segments = 200
max_degrees = 12
approx = Approx_Curve3d(curve, tol, GeomAbs_C2, max_segments, max_degrees)
if (approx.IsDone() and approx.HasResult()):
    an_approximated_curve = approx.Curve()

# there are two ways to project a point on this curve,
# they both give the same restult