Exemple #1
0
    def GenerateStruct(self, ChordFactor, ScaleFactor):
        from OCC.TopoDS import TopoDS_Builder, TopoDS_Compound, TopoDS_Shape, TopoDS_HShape

        x0 = [ChordFactor, ScaleFactor]

        SectionRibs, RibFace = self._BuildRibs(*x0)
        LSparLEFullWing, LSparTEFullWing, LSparMIDFullWing, StringerUpFullWing, StringerDownFullWing, PointsFullwingUp, PointsFullWingDown = self._BuildSpars(
            *x0)
        PanelUp, PanelDown = self._BuildPanels(*x0)

        builder = TopoDS_Builder()

        # Add Ribs
        Ribs = TopoDS_Compound()
        builder.MakeCompound(Ribs)
        for g in RibFace:
            builder.Add(Ribs, g)
        self.AddComponent(Ribs, 'Ribs')

        ##Add Spars
        Spars = TopoDS_Compound()
        builder.MakeCompound(Spars)
        SparsLEMIDTE = LSparLEFullWing + LSparMIDFullWing + LSparTEFullWing
        for h in SparsLEMIDTE:
            builder.Add(Spars, h)
        self.AddComponent(Spars, 'Spars')
        #Add Stringers
        Stringers = TopoDS_Compound()
        builder.MakeCompound(Stringers)
        for p in xrange(self.NoStiffners * self.SegmentNoLoft):
            p1 = StringerUpFullWing[p]
            p2 = StringerDownFullWing[p]
            builder.Add(Stringers, p1)
            builder.Add(Stringers, p2)
        self.AddComponent(Stringers, 'Stringers')

        #Add Panels
        Panels = TopoDS_Compound()
        builder.MakeCompound(Panels)
        for h in xrange(len(PanelUp)):
            h1 = PanelUp[h]
            h2 = PanelDown[h]
            builder.Add(Panels, h1)
            builder.Add(Panels, h2)
        self.AddComponent(Panels, 'Panels')
        vec = gp_Vec(gp_Pnt(-0.5, 0., 0.), self.ApexPoint)
        self.TranslateComponents(vec)
        return None
Exemple #2
0
def writeBRep(filename, shapeList):
    aRes = TopoDS_Compound()
    aBuilder = BRep_Builder()
    aBuilder.MakeCompound(aRes)
    for shape in shapeList:
        aBuilder.Add(aRes, shape)
    breptools_Write(aRes, filename)
Exemple #3
0
def _combine(*components):
    builder = TopoDS_Builder()
    compound = TopoDS_Compound()
    builder.MakeCompound(compound)
    for c in components:
        builder.Add(compound, c)
    return compound
Exemple #4
0
    def export(self, event):
        """ Export the current model to stl """
        from OCC.StlAPI import StlAPI_Writer
        from OCC.BRepMesh import BRepMesh_IncrementalMesh
        #: TODO: All parts
        options = event.parameters.get('options')
        if not isinstance(options, ExportOptions):
            return False

        exporter = StlAPI_Writer()
        exporter.SetASCIIMode(not options.binary)

        #: Make a compound of compounds (if needed)
        compound = TopoDS_Compound()
        builder = BRep_Builder()
        builder.MakeCompound(compound)
        for part in self.parts:
            #: Must mesh the shape first
            if isinstance(part, Part):
                builder.Add(compound, part.proxy.shape)
            else:
                builder.Add(compound, part.proxy.shape.Shape())

        #: Build the mesh
        mesh = BRepMesh_IncrementalMesh(compound, options.linear_deflection,
                                        options.relative,
                                        options.angular_deflection)
        mesh.Perform()
        if not mesh.IsDone():
            raise ExportError("Failed to create the mesh")

        exporter.Write(compound, options.path)
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)
Exemple #6
0
def regions2step(splinegons, filename, application_protocol='AP203'):
    """Writes splinegon regions to a STEP file.

    Parameters
    ----------
    splinegons : list
        Each member of the list is a `TopoDS_Face` object, the surface of a region.
    filename : str
        Name of the file the regions are saved into.
    application_protocol : {'AP203', 'AP214IS', 'AP242DIS'}, optional
        Version of schema used for the output STEP file. The default is 'AP203'.

    Returns
    -------
    None

    See Also
    --------
    splinegonize
    write_step_file

    """
    # Initialize a container that we will populate with the splinegons
    builder = BRep_Builder()
    compound = TopoDS_Compound()
    builder.MakeCompound(compound)
    # Combine multiple faces
    for splinegon in splinegons:
        builder.Add(compound, splinegon)
    # Write to STEP file
    write_step_file(compound, filename, application_protocol)
Exemple #7
0
def make_drawers(dx, dy, dz, arrangement):
    air_space = 0.05
    available_z_space = dz - THICKNESS_0 * (len(arrangement) + 1)
    drawer_space_height = available_z_space / len(arrangement)
    drawer_depth = dy - BACK_INSET - THICKNESS_1
    offsets = []
    for i in range(len(arrangement) - 1):
        offsets.append(THICKNESS_0 + (i + 1) *
                       (drawer_space_height + THICKNESS_0))
    drawer_box = make_drawer_box(dx, dy, dz, offsets)
    drawers = []
    for level, num_drawers in enumerate(arrangement):
        drawer_width = (dx - THICKNESS_0 * 2 -
                        (num_drawers + 1) * air_space) / float(num_drawers)
        z_pos = dz - (level + 1) * (THICKNESS_0 +
                                    drawer_space_height) + air_space
        for drawer_index in range(num_drawers):
            drawer = make_drawer(drawer_width, drawer_depth,
                                 drawer_space_height - 2 * air_space)
            _move(
                drawer, THICKNESS_0 + air_space +
                (air_space + drawer_width) * drawer_index, 0, z_pos)
            drawers.append(drawer)

    builder = TopoDS_Builder()
    compound = TopoDS_Compound()
    builder.MakeCompound(compound)
    builder.Add(compound, drawer_box)
    for drawer in drawers:
        builder.Add(compound, drawer)
    return compound
Exemple #8
0
def make_drawer_box(dx, dy, dz, separator_offsets):
    """Makes a box to contain simple drawers.

    Args:
        dx (float): The total outer width of the drawer box
        dy (float): The total outer depth of the drawer box
        dz (float): The total outer height of the drawer box
        separator_offsets (List[float]): The distance from 
            the outer bottom of the drawer box to the top of
            each drawer separator.

    Returns:
        A TopoDS_Compound representing the drawer box.
    """
    pieces = [
        _make_side(dx, dy, dz, separator_offsets, True),
        _make_side(dx, dy, dz, separator_offsets, False),
        _make_topbottom(dx, dy, dz, True),
        _make_topbottom(dx, dy, dz, False),
        _make_back(dx, dy, dz)
    ]
    for separator_offset in separator_offsets:
        pieces.append(_make_separator(dx, dy, separator_offset))

    builder = TopoDS_Builder()
    compound = TopoDS_Compound()
    builder.MakeCompound(compound)
    for piece in pieces:
        builder.Add(compound, piece)
    return compound
Exemple #9
0
    def extrudeLinearWithRotation(cls, outerWire, innerWires, vecCenter,
                                  vecNormal, angleDegrees):
        """
            Creates a 'twisted prism' by extruding, while simultaneously rotating around the extrusion vector.

            Though the signature may appear to be similar enough to extrudeLinear to merit combining them, the
            construction methods used here are different enough that they should be separate.

            At a high level, the steps followed are:
            (1) accept a set of wires
            (2) create another set of wires like this one, but which are transformed and rotated
            (3) create a ruledSurface between the sets of wires
            (4) create a shell and compute the resulting object

            :param outerWire: the outermost wire, a cad.Wire
            :param innerWires: a list of inner wires, a list of cad.Wire
            :param vecCenter: the center point about which to rotate.  the axis of rotation is defined by
                   vecNormal, located at vecCenter. ( a cad.Vector )
            :param vecNormal: a vector along which to extrude the wires ( a cad.Vector )
            :param angleDegrees: the angle to rotate through while extruding
            :return: a cad.Solid object
        """
        # make straight spine
        straight_spine_e = Edge.makeLine(vecCenter, vecCenter.add(vecNormal))
        straight_spine_w = Wire.combine([
            straight_spine_e,
        ]).wrapped

        # make an auxliliary spine
        pitch = 360. / angleDegrees * vecNormal.Length
        radius = 1
        aux_spine_w = Wire.makeHelix(pitch,
                                     vecNormal.Length,
                                     radius,
                                     center=vecCenter,
                                     dir=vecNormal).wrapped

        # extrude the outer wire
        outer_solid = cls._extrudeAuxSpine(outerWire.wrapped, straight_spine_w,
                                           aux_spine_w)

        # extrude inner wires
        inner_solids = [
            cls._extrudeAuxSpine(w.wrapped, straight_spine_w.aux_spine_w)
            for w in innerWires
        ]

        # combine dthe inner solids into compund
        inner_comp = TopoDS_Compound()
        comp_builder = TopoDS_Builder()
        comp_builder.MakeCompound(inner_comp)  # TODO this could be not needed

        for i in inner_solids:
            comp_builder.Add(inner_comp, i)

        # subtract from the outer solid
        return cls(BRepAlgoAPI_Cut(outer_solid, inner_comp).Shape())
Exemple #10
0
def display_edges():
    comp = TopoDS_Compound()
    builder = BRep.BRep_Builder()
    builder.MakeCompound(comp)

    for e in edges:
        #contour = BRepAlgo_Fuse(contour, e).Shape()
        builder.Add(comp, e)

    displays[curr_tab].DisplayColoredShape(comp, 'BLACK', False)
 def get_compound(self):
     """ Create and returns a compound from the _shapes list
     """
     # Create a compound
     compound = TopoDS_Compound()
     B = BRep_Builder()
     B.MakeCompound(compound)
     # Populate the compound
     for shape in self._shapes:
         B.Add(compound, shape)
     return compound
Exemple #12
0
def compound(topo):
    """
    accumulate a bunch of TopoDS_* in list `topo` to a TopoDS_Compound
    @param topo: list of TopoDS_* instances
    """
    bd = TopoDS_Builder()
    comp = TopoDS_Compound()
    bd.MakeCompound(comp)
    for i in topo:
        bd.Add(comp, i)
    return comp
Exemple #13
0
 def testTopoDS_byref_arguments(self):
     '''
     Test byref pass arguments to TopoDS
     '''
     cyl1 = BRepPrimAPI_MakeCylinder(10., 10.).Shape()
     cyl2 = BRepPrimAPI_MakeCylinder(100., 50.).Shape()
     c = TopoDS_Compound()
     bb = TopoDS_Builder()
     bb.MakeCompound(c)
     for child in [cyl1, cyl2]:
         bb.Add(c, child)
Exemple #14
0
    def makeCompound(cls, listOfShapes):
        """
        Create a compound out of a list of shapes
        """
        comp = TopoDS_Compound()
        comp_builder = TopoDS_Builder()
        comp_builder.MakeCompound(comp)  # TODO this could be not needed

        for s in listOfShapes:
            comp_builder.Add(comp, s.wrapped)

        return cls(comp)
Exemple #15
0
def read_step_file(filename, as_compound=True, verbosity=True):
    """ read the STEP file and returns a compound
    filename: the file path
    verbosity: optional, False by default.
    as_compound: True by default. If there are more than one shape at root,
    gather all shapes into one compound. Otherwise returns a list of shapes.
    """
    if not os.path.isfile(filename):
        raise FileNotFoundError("%s not found." % filename)

    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(filename)

    if status == IFSelect_RetDone:  # check status
        if verbosity:
            failsonly = False
            step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
            step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
        transfer_result = step_reader.TransferRoots()
        if not transfer_result:
            raise AssertionError("Transfer failed.")
        _nbs = step_reader.NbShapes()
        if _nbs == 0:
            raise AssertionError("No shape to transfer.")
        elif _nbs == 1:  # most cases
            return step_reader.Shape(1)
        elif _nbs > 1:
            print("Number of shapes:", _nbs)
            shps = []
            # loop over root shapes
            for k in range(1, _nbs + 1):
                new_shp = step_reader.Shape(k)
                if not new_shp.IsNull():
                    shps.append(new_shp)
            if as_compound:
                builder = BRep_Builder()
                compound = TopoDS_Compound()
                builder.MakeCompound(compound)
                for s in shps:
                    builder.Add(compound, s)
                # shps = compound
                # compound, result = list_of_shapes_to_compound(shps)
                # if not result:
                #    print("Warning: all shapes were not added to the compound")
                return compound
            else:
                print("Warning, returns a list of shapes.")
                return shps
    else:
        raise AssertionError("Error: can't read file.")
    return None
def read_iges_file(filename, return_as_shapes=False, verbosity=False):
    """ read the IGES file and returns a compound
    filename: the file path
    return_as_shapes: optional, False by default. If True returns a list of shapes,
                      else returns a single compound
    verbosity: optionl, False by default.
    """
    assert os.path.isfile(filename)

    iges_reader = IGESControl_Reader()
    status = iges_reader.ReadFile(filename)

    _shapes = []

    if status == IFSelect_RetDone:  # check status
        if verbosity:
            failsonly = False
            iges_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
            iges_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
        iges_reader.TransferRoots()
        nbr = iges_reader.NbRootsForTransfer()
        for n in range(1, nbr + 1):
            nbs = iges_reader.NbShapes()
            if nbs == 0:
                print("At least one shape in IGES cannot be transfered")
            elif nbr == 1 and nbs == 1:
                aResShape = iges_reader.Shape(1)
                if aResShape.IsNull():
                    print("At least one shape in IGES cannot be transferred")
                else:
                    _shapes.append(aResShape)
            else:
                for i in range(1, nbs + 1):
                    aShape = iges_reader.Shape(i)
                    if aShape.IsNull():
                        print(
                            "At least one shape in STEP cannot be transferred")
                    else:
                        _shapes.append(aShape)
    # if not return as shapes
    # create a compound and store all shapes
    # TODO
    if not return_as_shapes:
        builder = BRep_Builder()
        Comp = TopoDS_Compound()
        builder.MakeCompound(Comp)
        for s in _shapes:
            builder.Add(Comp, s)
        _shapes = Comp
    return _shapes
Exemple #17
0
def make_compound(shape_array):
    """
    Creates a TopoDS_Compund from a list of TopoDS_Shapes

    :param shape_array: list of shapes
    :return: TopoDS_Compound
    """

    b = BRep_Builder()
    c = TopoDS_Compound()
    b.MakeCompound(c)
    for shape in shape_array:
        b.Add(c, shape)
    return c
Exemple #18
0
    def export(self):
        """ Export a DeclaraCAD model from an enaml file to an STL based on the
        given options.
        
        Parameters
        ----------
        options: declaracad.occ.plugin.ExportOptions
        
        """
        from OCC.BRep import BRep_Builder
        from OCC.BRepMesh import BRepMesh_IncrementalMesh
        from OCC.StlAPI import StlAPI_Writer
        from OCC.TopoDS import TopoDS_Compound
        
        # Make a compound of compounds (if needed)
        compound = TopoDS_Compound()
        builder = BRep_Builder()
        builder.MakeCompound(compound)
        
        # Load the enaml model file
        parts = load_model(self.filename)
        
        for part in parts:
            # Render the part from the declaration
            shape = part.render()
            
            # Must mesh the shape firsts
            if hasattr(shape, 'Shape'):
                builder.Add(compound, shape.Shape())
            else:
                builder.Add(compound, shape)

        #: Build the mesh
        exporter = StlAPI_Writer()
        exporter.SetASCIIMode(not self.binary)
        mesh = BRepMesh_IncrementalMesh(
            compound,
            self.linear_deflection,
            self.relative,
            self.angular_deflection
        )
        mesh.Perform()
        if not mesh.IsDone():
            raise RuntimeError("Failed to create the mesh")
        
        exporter.Write(compound, self.path)
            
        if not os.path.exists(self.path):
            raise RuntimeError("Failed to write shape")
Exemple #19
0
def make_drawer(dx, dy, dz):
    pieces = [
        _make_side(dx, dy, dz, True),
        _make_side(dx, dy, dz, False),
        _make_end(dx, dy, dz, True),
        _make_end(dx, dy, dz, False),
        _make_bottom(dx, dy)
    ]

    builder = TopoDS_Builder()
    compound = TopoDS_Compound()
    builder.MakeCompound(compound)
    for piece in pieces:
        builder.Add(compound, piece)
    return compound
Exemple #20
0
def occ_load_file(filename):
    """
    load in pythonocc a igs or step file

    :param filename: a filename with extension
    :return: a topods_shape
    """

    from OCC.STEPControl import STEPControl_Reader
    from OCC.IGESControl import IGESControl_Reader
    from OCC.BRep import BRep_Builder
    from OCC.TopoDS import TopoDS_Compound
    from OCC.IFSelect import IFSelect_RetDone,\
    IFSelect_ItemsByEntity

    reader_switch = {
        'stp': STEPControl_Reader,
        'step': STEPControl_Reader,
        'igs': IGESControl_Reader,
        'iges': IGESControl_Reader
    }

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

    reader = reader_switch[os.path.splitext(filename)[1][1:].lower()]()

    status = reader.ReadFile(filename)

    if status == IFSelect_RetDone:  # check status
        failsonly = False
        reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
        reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)

        ok = reader.TransferRoots()
        nbs = reader.NbShapes()

        for i in range(1, nbs + 1):
            shape = reader.Shape(i)
            builder.Add(comp, shape)

    return comp
Exemple #21
0
def step_reader(step_string):

    from OCC.StlAPI import StlAPI_Writer
    from OCC.STEPControl import STEPControl_Reader
    from OCC.BRep import BRep_Builder
    from OCC.TopoDS import TopoDS_Compound
    from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity

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

    stl_writer = StlAPI_Writer()
    stl_writer.SetASCIIMode(True)

    with io.tmpfile(contents=io.shapes()[shape_name][:][0]) as tmpfile:
        step_reader = STEPControl_Reader()

        status = step_reader.ReadFile(tmpfile[1])

        if status == IFSelect_RetDone:  # check status
            failsonly = False
            step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
            step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)

            ok = step_reader.TransferRoot(1)
            nbs = step_reader.NbShapes()

            l = []
            for i in range(1, nbs + 1):
                shape = step_reader.Shape(i)

                builder.Add(comp, shape)

            with io.tmpfile(suffix='.stl') as tmpf:
                    stl_writer.Write(comp, tmpf[1])
                    tmpf[0].flush()

                    reader = vtk.vtkSTLReader()
                    reader.SetFileName(tmpf[1])
                    reader.Update()

                    return reader
Exemple #22
0
 def create_shape(self):
     d = self.declaration
     if not d.source:
         return
     if os.path.exists(d.source):
         svg = etree.parse(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)
     self.wires = shapes
     self.shape = shape
Exemple #23
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)
Exemple #24
0
def _make_table():
    builder = TopoDS_Builder()
    compound = TopoDS_Compound()
    builder.MakeCompound(compound)
    table_top = _box(SPECS.length, SPECS.width, TABLE_THICKNESS)
    _move(table_top, 0, 0, PEDESTAL_HEIGHT)
    builder.Add(compound, table_top)
    for i in range(4):
        pedestal = _box(SPECS.pedestal_thickness, SPECS.pedestal_width, PEDESTAL_HEIGHT)
        if i < 2:
            x = SPECS.pedestal_inset
        else:
            x = SPECS.length - SPECS.pedestal_inset - SPECS.pedestal_thickness
        if i % 2 == 0:
            y = (SPECS.width + SPECS.pedestal_gap) / 2
        else:
            y = (SPECS.width - SPECS.pedestal_gap) / 2 - SPECS.pedestal_width
        _move(pedestal, x, y, 0.)
        builder.Add(compound, pedestal)
    return compound
Exemple #25
0
    def vstep(step_str):

        step = int(step_str)

        positions = dpos_data[nbobjs * step:nbobjs * step + nbobjs, 2:]

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

        for _id in range(positions.shape[0]):

            q0, q1, q2, q3, q4, q5, q6 = [float(x) for x in positions[_id, :]]

            obj = obj_by_id[_id + 1]

            q = Quaternion((q3, q4, q5, q6))

            for shape_name, avatar in zip(io.instances()[obj], avatars(obj)):
                offset = get_offset(obj, shape_name)
                p = q.rotate(offset[0])
                r = q * Quaternion(offset[1])

                tr = gp_Trsf()
                qocc = gp_Quaternion(r[1], r[2], r[3], r[0])
                tr.SetRotation(qocc)
                xyz = gp_XYZ(q0 + p[0], q1 + p[1], q2 + p[2])
                vec = gp_Vec(xyz)
                tr.SetTranslationPart(vec)
                loc = TopLoc_Location(tr)

                display.Context.SetLocation(avatar, loc)

                moved_shape = BRepBuilderAPI_Transform(
                    avatar.GetObject().Shape(), tr, True).Shape()

                builder.Add(comp, moved_shape)

            display.Context.UpdateCurrentViewer()

        write_step((step_str, comp))
Exemple #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
Exemple #27
0
    def write(self, mesh_points, filename, tolerance=None):
        """
        Writes a output file, called filename, copying all the structures
        from self.filename but the coordinates. `mesh_points` is a matrix
        that contains the new coordinates to write in the output file.

        :param numpy.ndarray mesh_points: it is a `n_points`-by-3 matrix
            containing the coordinates of the points of the mesh
        :param string filename: name of the output file.
        :param float tolerance: tolerance for the construction of the faces
            and wires in the write function. If not given it uses
            `self.tolerance`.
        """
        self._check_filename_type(filename)
        self._check_extension(filename)
        self._check_infile_instantiation()

        self.outfile = filename

        if tolerance is not None:
            self.tolerance = tolerance

        # cycle on the faces to update the control points position
        # init some quantities
        faces_explorer = TopExp_Explorer(self.shape, TopAbs_FACE)
        n_faces = 0
        control_point_position = self._control_point_position

        compound_builder = BRep_Builder()
        compound = TopoDS_Compound()
        compound_builder.MakeCompound(compound)

        while faces_explorer.More():
            # similar to the parser method
            face = topods_Face(faces_explorer.Current())
            nurbs_converter = BRepBuilderAPI_NurbsConvert(face)
            nurbs_converter.Perform(face)
            nurbs_face = nurbs_converter.Shape()
            face_aux = topods_Face(nurbs_face)
            brep_face = BRep_Tool.Surface(topods_Face(nurbs_face))
            bspline_face = geomconvert_SurfaceToBSplineSurface(brep_face)
            occ_face = bspline_face.GetObject()

            n_poles_u = occ_face.NbUPoles()
            n_poles_v = occ_face.NbVPoles()

            i = 0
            for pole_u_direction in range(n_poles_u):
                for pole_v_direction in range(n_poles_v):
                    control_point_coordinates = mesh_points[
                        i + control_point_position[n_faces], :]
                    point_xyz = gp_XYZ(*control_point_coordinates)

                    gp_point = gp_Pnt(point_xyz)
                    occ_face.SetPole(pole_u_direction + 1,
                                     pole_v_direction + 1, gp_point)
                    i += 1

            # construct the deformed wire for the trimmed surfaces
            wire_maker = BRepBuilderAPI_MakeWire()
            tol = ShapeFix_ShapeTolerance()
            brep = BRepBuilderAPI_MakeFace(occ_face.GetHandle(),
                                           self.tolerance).Face()
            brep_face = BRep_Tool.Surface(brep)

            # cycle on the edges
            edge_explorer = TopExp_Explorer(nurbs_face, TopAbs_EDGE)
            while edge_explorer.More():
                edge = topods_Edge(edge_explorer.Current())
                # edge in the (u,v) coordinates
                edge_uv_coordinates = BRep_Tool.CurveOnSurface(edge, face_aux)
                # evaluating the new edge: same (u,v) coordinates, but different (x,y,x) ones
                edge_phis_coordinates_aux = BRepBuilderAPI_MakeEdge(
                    edge_uv_coordinates[0], brep_face)
                edge_phis_coordinates = edge_phis_coordinates_aux.Edge()
                tol.SetTolerance(edge_phis_coordinates, self.tolerance)
                wire_maker.Add(edge_phis_coordinates)
                edge_explorer.Next()

            # grouping the edges in a wire
            wire = wire_maker.Wire()

            # trimming the surfaces
            brep_surf = BRepBuilderAPI_MakeFace(occ_face.GetHandle(),
                                                wire).Shape()
            compound_builder.Add(compound, brep_surf)
            n_faces += 1
            faces_explorer.Next()
        self.write_shape_to_file(compound, self.outfile)
Exemple #28
0
    def write_shape(self, l_shells, filename, tol):
        """
        Method to recreate a TopoDS_Shape associated to a geometric shape
        after the modification of points of each Face. It
        returns a TopoDS_Shape (Shape).

        :param l_shells: the list of shells after initial parsing
        :param filename: the output filename
        :param tol: tolerance on the surface creation after modification
        :return: None

        """
        self.outfile = filename
        # global compound containing multiple shells
        global_compound_builder = BRep_Builder()
        global_comp = TopoDS_Compound()
        global_compound_builder.MakeCompound(global_comp)

        if self.check_topo == 0:
            # cycle on shells (multiple objects)
            shape_shells_explorer = TopExp_Explorer(
                self.shape.Oriented(TopAbs_FORWARD), TopAbs_SHELL)
            ishell = 0

            while shape_shells_explorer.More():
                per_shell = topods_Shell(shape_shells_explorer.Current())
                # a local compound containing a shell
                compound_builder = BRep_Builder()
                comp = TopoDS_Compound()
                compound_builder.MakeCompound(comp)

                # cycle on faces
                faces_explorer = TopExp_Explorer(
                    per_shell.Oriented(TopAbs_FORWARD), TopAbs_FACE)
                iface = 0
                while faces_explorer.More():
                    topoface = topods.Face(faces_explorer.Current())
                    newface = self.write_face(l_shells[ishell][iface][0],
                                              l_shells[ishell][iface][1],
                                              topoface, tol)

                    # add face to compound
                    compound_builder.Add(comp, newface)
                    iface += 1
                    faces_explorer.Next()

                new_shell = self.combine_faces(comp, 0.01)
                itype = TopoDS_Shape.ShapeType(new_shell)
                # add the new shell to the global compound
                global_compound_builder.Add(global_comp, new_shell)

                print("Shell {0} of type {1} Processed ".format(ishell, itype))
                print "=============================================="

                ishell += 1
                shape_shells_explorer.Next()

        else:
            # cycle on faces
            # a local compound containing a shell
            compound_builder = BRep_Builder()
            comp = TopoDS_Compound()
            compound_builder.MakeCompound(comp)

            # cycle on faces
            faces_explorer = TopExp_Explorer(
                self.shape.Oriented(TopAbs_FORWARD), TopAbs_FACE)
            iface = 0
            while faces_explorer.More():
                topoface = topods.Face(faces_explorer.Current())
                newface = self.write_face(l_shells[0][iface][0],
                                          l_shells[0][iface][1], topoface, tol)

                # add face to compound
                compound_builder.Add(comp, newface)
                iface += 1
                faces_explorer.Next()

            new_shell = self.combine_faces(comp, 0.01)
            itype = TopoDS_Shape.ShapeType(new_shell)
            # add the new shell to the global compound
            global_compound_builder.Add(global_comp, new_shell)

            print("Shell {0} of type {1} Processed ".format(0, itype))
            print "=============================================="

        self.write_shape_to_file(global_comp, self.outfile)
anEdge2OnSurf2 = BRepBuilderAPI_MakeEdge(aSegment.Value(),
                                         Handle_Geom_Surface(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)

display, start_display, add_menu, add_function_to_menu = init_display('wx')
display.DisplayColoredShape(aRes)

start_display()
Exemple #30
0
sphere_r1 = BRepPrimAPI_MakeSphere(point, radius)
sphere_r1_shape = sphere_r1.Shape()

radius = 0.01
sphere_r01 = BRepPrimAPI_MakeSphere(point, radius)
sphere_r01_shape = sphere_r01.Shape()

radius = 0.001
sphere_r001 = BRepPrimAPI_MakeSphere(point, radius)
sphere_r001_shape = sphere_r001.Shape()

from OCC.BRep import BRep_Builder
from OCC.TopoDS import TopoDS_Compound

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

from OCC.BRep import BRep_Builder
from OCC.TopoDS import TopoDS_Compound

builder.Add(comp, sphere_r1_shape)

radius = 1.0
point = gp_Pnt(4., 0., 0.)
sphere_r1_t = BRepPrimAPI_MakeSphere(point, radius)
sphere_r1_t_shape = sphere_r1_t.Shape()

builder.Add(comp, sphere_r1_t_shape)

# this cylinder is defined for the visualisation of the axis edge