Example #1
0
    def import_step(self, fn):
        """
        Import a STEP file generated by the OpenVSP.

        :param str fn: The full path to the file.

        :return: None.

        :raise RuntimeError: If the file cannot be read.
        """
        print('Importing OpenVSP STEP file...')

        # Build a compound for geometric sets
        compound = TopoDS_Compound()
        BRep_Builder().MakeCompound(compound)

        # Read file
        step_reader = STEPControl_Reader()
        status = step_reader.ReadFile(fn)
        if status not in [IFSelect_RetVoid, IFSelect_RetDone]:
            raise RuntimeError("Unable to read OpenVSP STEP file.")

        # TODO Convert to desired units
        # Interface_Static.SetCVal_("xstep.cascade.unit", "SOME UNIT HERE")

        # Transfer
        # OpenVSP STEP files result in one root and one shape (a compound)
        step_reader.TransferRoot(1)
        master_shape = step_reader.Shape(1)

        # Iterate over master shape to find compounds for geometric sets. These
        # sets contain the surfaces that make up the component.
        iterator = TopoDS_Iterator(master_shape, True, True)
        more = True
        while iterator.More() and more:
            print('--Processing a component...')
            # The compound
            compound = iterator.Value()
            # Hack to handle single component for now...
            if compound.ShapeType() != TopAbs_COMPOUND:
                compound = master_shape
                more = False

            solid, is_valid, invalid_shapes = _build_solid(
                compound, self._divide)
            if is_valid:
                print('  Successfully built a solid.')
                self._solids.append(solid)
            else:
                print('  Failed to build a valid solid.')
                self._invalid.append(solid)
                self._invalid_shapes += invalid_shapes

            # Next shape
            iterator.Next()

        print('Finished.\n')
Example #2
0
def load_dxf(filename):
    doc = ezdxf.readfile(filename)
    edges = TopTools_HSequenceOfShape()

    for element in doc.modelspace():
        dxf_type = element.dxftype()
        d = element.dxf
        if dxf_type == 'LINE':
            node = Segment(points=[d.start, d.end]).render()
        elif dxf_type == 'ARC':
            node = Arc(position=d.center,
                       radius=d.radius,
                       alpha1=radians(d.start_angle),
                       alpha2=radians(d.end_angle)).render()
        elif dxf_type == 'CIRCLE':
            node = Circle(radius=d.radius, position=d.center).render()
        else:
            log.warning(f"Unhandled element: {element}")
            continue
        edges.Append(node)

    wires = ShapeAnalysis_FreeBounds.ConnectEdgesToWires_(edges, 1e-6, False)

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

    for i in range(1, wires.Size() + 1):
        builder.Add(shape, wires.Value(i))

    return [TopoShape(shape=shape)]
Example #3
0
    def create_shape(self):
        d = self.declaration
        if not d.source:
            return
        if os.path.exists(os.path.expanduser(d.source)):
            svg = etree.parse(os.path.expanduser(d.source)).getroot()
        else:
            svg = etree.fromstring(d.source)
        node = OccSvgDoc(element=svg)

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

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

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

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

        self.shape = BRepBuilderAPI_Transform(shape, t, False).Shape()
Example #4
0
    def update_shape(self, change=None):
        """ Create the toolkit shape for the proxy object.

        """
        d = self.declaration
        builder = self.builder = BRep_Builder()
        shape = TopoDS_Compound()
        builder.MakeCompound(shape)
        for c in self.children():
            if not isinstance(c, OccShape):
                continue
            if c.shape is None or not c.declaration.display:
                continue
            # Note infinite planes cannot be added to a compound!
            builder.Add(shape, c.shape)
        location = self.location = self._default_location()
        shape.Location(location)
        self.shape = shape
Example #5
0
 def __init__(self, shapes):
     topods_compound = TopoDS_Compound()
     builder = BRep_Builder()
     builder.MakeCompound(topods_compound)
     for shape in shapes:
         shape = Shape.to_shape(shape)
         if isinstance(shape, Shape):
             builder.Add(topods_compound, shape.object)
     self._cp = Compound(topods_compound)
 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
Example #7
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
Example #8
0
    def compound(shapes):
        """
        Create a compound from a list of shapes.

        :param shapes: List of shapes.
        :type: collections.Sequence(OCCT.TopoDS.TopoDS_Shape)
        """

        cp = TopoDS_Compound()
        builder = BRep_Builder()
        builder.MakeCompound(cp)
        for shape in shapes:
            builder.Add(cp, shape)
        return cp
Example #9
0
    def by_shapes(shapes):
        """
        Create a new compound from a collection of shapes.

        :param collections.Sequence(afem.topology.entities.Shape) shapes: The
            shapes.

        :return: The new compound.
        :rtype: afem.topology.entities.Compound
        """
        topods_compound = TopoDS_Compound()
        builder = BRep_Builder()
        builder.MakeCompound(topods_compound)
        for shape in shapes:
            if isinstance(shape, Shape):
                builder.Add(topods_compound, shape.object)
        return Compound(topods_compound)
Example #10
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

        """

        # 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()
        # TODO: pyOCCT needs to support updating the reference
        # 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")
Example #11
0
    def create_shape(self):
        d = self.declaration
        if not d.source:
            return
        if os.path.exists(os.path.expanduser(d.source)):
            svg = etree.parse(os.path.expanduser(d.source)).getroot()
        else:
            svg = etree.fromstring(d.source)
        node = self.doc = OccSvgDoc(element=svg)
        viewbox = svg.attrib.get('viewBox')
        x, y = (0, 0)
        sx, sy = (1, 1)
        if viewbox:
            ow = parse_unit(svg.attrib.get('width'))
            oh = parse_unit(svg.attrib.get('height'))
            x, y, iw, ih = map(parse_unit, viewbox.split())
            sx = ow / iw
            sy = oh / ih

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

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

        bbox = self.get_bounding_box(shape)

        # Move to position and align along direction axis
        t = self.get_transform()
        if d.mirror:
            m = gp_Trsf()
            m.SetMirror(gp_Ax2(gp_Pnt(*bbox.center), gp_Dir(0, 1, 0)))
            t.Multiply(m)

        # Apply viewport scale
        s = gp_Trsf()
        s.SetValues(sx, 0, 0, x, 0, sy, 0, y, 0, 0, 1, 0)
        t.Multiply(s)

        self.shape = BRepBuilderAPI_Transform(shape, t, False).Shape()
def simple_mesh():
    #
    # Create the 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))
        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)
Example #13
0
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
bottle = TopoDS_Compound()
aBuilder = BRep_Builder()
aBuilder.MakeCompound(bottle)
aBuilder.Add(bottle, myBody.Shape())
aBuilder.Add(bottle, myThreading)
print("bottle finished")

if __name__ == "__main__":
    from OCC.Display.SimpleGui import init_display
    display, start_display, add_menu, add_function_to_menu = init_display()
    display.DisplayColoredShape(bottle, update=True)
    start_display()