示例#1
0
def write_step_file(a_shape, filename, application_protocol="AP203"):
    """ exports a shape to a STEP file
    a_shape: the topods_shape to export (a compound, a solid etc.)
    filename: the filename
    application protocol: "AP203" or "AP214IS" or "AP242DIS"
    """
    # a few checks
    if a_shape.IsNull():
        raise AssertionError("Shape %s is null." % a_shape)
    if application_protocol not in ["AP203", "AP214IS", "AP242DIS"]:
        raise AssertionError("application_protocol must be either AP203 or AP214IS. You passed %s." % application_protocol)
    if os.path.isfile(filename):
        print("Warning: %s file already exists and will be replaced" % filename)
    # creates and initialise the step exporter
    step_writer = STEPControl_Writer()
    Interface_Static_SetCVal("write.step.schema", application_protocol)

    # transfer shapes and write file
    step_writer.Transfer(a_shape, STEPControl_AsIs)
    status = step_writer.Write(filename)

    if not status == IFSelect_RetDone:
        raise IOError("Error while writing shape to STEP file.")
    if not os.path.isfile(filename):
        raise IOError("File %s was not saved to filesystem." % filename)
示例#2
0
    def add_occ_shape(self, name, occ_shape):
        """
        Add an OpenCascade TopoDS_Shape.
        """

        if name not in self._ref:

            from OCC.STEPControl import STEPControl_Writer, STEPControl_AsIs

            # step format is used for the storage.
            step_writer = STEPControl_Writer()

            step_writer.Transfer(occ_shape, STEPControl_AsIs)

            shape_data = None

            with tmpfile() as tmpf:

                step_writer.Write(tmpf[1])

                tmpf[0].flush()
                shape_data = str_of_file(tmpf[1])

                shape = self._ref.create_dataset(name, (1, ),
                                                 dtype=h5py.new_vlen(str))
                shape[:] = shape_data
                shape.attrs['id'] = self._number_of_shapes
                shape.attrs['type'] = 'step'
                self._number_of_shapes += 1
示例#3
0
    def write_step(stshape):
        # initialize the STEP exporter
        step_writer = STEPControl_Writer()

        # missing person => load failure
        #Interface_Static_SetCVal("write.step.schema", "AP203")

        step_str, shape = stshape

        step_writer.Transfer(shape, STEPControl_AsIs)
        status = step_writer.Write(
            'siconos-mechanisms-{0}.stp'.format(step_str))
示例#4
0
 def write_shape_to_file(self, shape, filename):
     """
     This method saves the `shape` to the file `filename`.
     :param: TopoDS_Shape shape: loaded shape
     :param string filename: name of the input file.
         It should have proper extension (.step or .stp)
     """
     self._check_filename_type(filename)
     self._check_extension(filename)
     step_writer = STEPControl_Writer()
     # Changes write schema to STEP standard AP203
     # It is considered the most secure standard for STEP.
     # *According to PythonOCC documentation (http://www.pythonocc.org/)
     Interface_Static_SetCVal("write.step.schema", "AP203")
     step_writer.Transfer(shape, STEPControl_AsIs)
     step_writer.Write(filename)
def writeSTEP(filepath, shape):
    """ Write STEP file of the shape"""

    # STEPControl_AsIs says to make the STEP model the same geometry type as the
    # shape (ie. a solid Shape should be a STEP Solid)
    writer = STEPControl_Writer()
    writer.Transfer(diffuser.Shape(), STEPControl_AsIs)

    # Write the STEP file to the given filepath
    try:
        writer.Write(filepath.as_posix())
    except:
        print('Write failed')
    else:
        if args.v >= 1:
            print(f'\nSTEP file was successfully saved to:\n {filepath}')
示例#6
0
def build(input, output):
    #sample xml for testing
    xml = "<eagle version=\"7\"><drawing><board><plain><wire x1=\"0\" y1=\"0\" x2=\"0\" y2=\"2\" width=\"0.254\" layer=\"20\"/><wire x1=\"0\" y1=\"2\" x2=\"1.5\" y2=\"2\" width=\"0.254\" layer=\"20\"/><wire x1=\"1.5\" y1=\"2\" x2=\"1\" y2=\"0\" width=\"0.254\" layer=\"20\"/><wire x1=\"1\" y1=\"0\" x2=\"0\" y2=\"0\" width=\"0.254\" layer=\"20\"/></plain></board></drawing></eagle>"

    #xmldoc = minidom.parseString( xml )

    xmldoc = minidom.parse(input)

    wires = xmldoc.getElementsByTagName('wire')

    makeWire = BRepBuilderAPI_MakeWire()

    for wire in wires:

        if wire.attributes['layer'].value == '20':
            x1 = float(wire.attributes['x1'].value)
            y1 = float(wire.attributes['y1'].value)

            x2 = float(wire.attributes['x2'].value)
            y2 = float(wire.attributes['y2'].value)

            #print('Building edge from  {}, {} to {}, {}'.format( x1,y1,x2,y2))

            edge = BRepBuilderAPI_MakeEdge( gp_Pnt( x1, y1, 0.0 ), \
                                            gp_Pnt( x2, y2, 0.0 ) \
                                                      )

            makeWire.Add(edge.Edge())

    face = BRepBuilderAPI_MakeFace(makeWire.Wire())

    #vector & height
    vector = gp_Vec(0, 0, .1)

    body = BRepPrimAPI_MakePrism(face.Face(), vector)

    # initialize the STEP exporter
    step_writer = STEPControl_Writer()
    Interface_Static_SetCVal("write.step.schema", "AP203")

    # transfer shapes and write file
    step_writer.Transfer(body.Shape(), STEPControl_AsIs)
    status = step_writer.Write(output)

    if status != IFSelect_RetDone:
        raise AssertionError("load failed")
示例#7
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.STEPControl import STEPControl_Writer, STEPControl_AsIs
        from OCC.Interface import Interface_Static_SetCVal as SetCVal
        from OCC.Interface import Interface_Static_SetIVal as SetIVal
        from OCC.Interface import Interface_Static_SetRVal as SetRVal
        from OCC.IFSelect import IFSelect_RetDone
        
        # Set all params
        exporter = STEPControl_Writer()
        SetIVal("write.precision.mode", PRECISION_MODES[self.precision_mode])
        if self.precision_mode == 'greatest':
            SetRVal("write.precision.val", self.precision_val)
        SetIVal("write.step.assembly", ASSEMBLY_MODES[self.assembly_mode])
        SetCVal("write.step.schema", self.schema)
        if self.product_name:
            SetCVal("write.step.product.name", self.product_name)
        SetIVal("write.surfacecurve.mode", 
                SURFACECURVE_MODES[self.surfacecurve_mode])
        SetCVal("write.step.unit", self.units.upper())
        SetIVal("write.step.vertex.mode", VERTEX_MODES[self.vertex_mode])

        # Load the enaml model file
        parts = load_model(self.filename)
        
        for part in parts:
            # Render the part from the declaration
            shape = part.render()
            
            # Transfer all shapes
            if hasattr(shape, 'Shape'):
                exporter.Transfer(shape.Shape(), STEPControl_AsIs)
            else:
                exporter.Transfer(shape, STEPControl_AsIs)

        # Send it
        status = exporter.Write(self.path)
        if status != IFSelect_RetDone or not os.path.exists(self.path):
            raise RuntimeError("Failed to write shape")
示例#8
0
class ExportMethod(object):
    def __init__(self, tol=1.0E-6):
        self.obj = STEPControl_Writer()
        self.obj.SetTolerance(tol)
        Interface_Static_SetCVal("write.step.schema", "AP214")
        """
        self.obj.PrintStatsTransfer:
        what
        0 gives general statistics (number of translated roots, number of warnings, number of fail messages),
        1 gives root results,
        2 gives statistics for all checked entities,
        3 gives the list of translated entities,
        4 gives warning and fail messages,
        5 gives fail messages only. The use of mode depends on the value of what. If what is 0, mode is ignored. 
        
        If what is 1, 2 or 3, mode defines the following:
        0 lists the numbers of IGES or STEP entities in the respective model
        1 gives the number, identifier, type and result type for each IGES or STEP entity and/or its status (fail, warning, etc.)
        2 gives maximum information for each IGES or STEP entity (i.e. checks)
        3 gives the number of entities per type of IGES or STEP entity
        4 gives the number of IGES or STEP entities per result type and/or status
        5 gives the number of pairs (IGES or STEP or result type and status)
        6 gives the number of pairs (IGES or STEP or result type and status) AND the list of entity numbers in the IGES or STEP model. 
        
        If what is 4 or 5, mode defines the warning and fail messages as follows:
        if mode is 0 all warnings and checks per entity are returned
        if mode is 2 the list of entities per warning is returned. If mode is not set, only the list of all entities per warning is given.
        """

    def add_shpe(self, shape):
        """
        STEPControl_AsIs                   translates an Open CASCADE shape to its highest possible STEP representation.
        STEPControl_ManifoldSolidBrep      translates an Open CASCADE shape to a STEP manifold_solid_brep or brep_with_voids entity.
        STEPControl_FacetedBrep            translates an Open CASCADE shape into a STEP faceted_brep entity.
        STEPControl_ShellBasedSurfaceModel translates an Open CASCADE shape into a STEP shell_based_surface_model entity.
        STEPControl_GeometricCurveSet      translates an Open CASCADE shape into a STEP geometric_curve_set entity.
        """
        self.obj.Transfer(shape, STEPControl_AsIs)

    def fileout(self, filename):
        status = self.obj.Write(filename)
        assert (status == IFSelect_RetDone)
示例#9
0
def write_step_file(shape, filename, application_protocol='AP203'):
    """ Exports a shape to a STEP file.

    Parameters
    ----------
    shape : TopoDS_Shape
        Shape to be exported, an object of the `TopoDS_Shape` class or one of its subclasses. See
        https://www.opencascade.com/doc/occt-7.4.0/refman/html/class_topo_d_s___shape.html
    filename : str
        Name of the file the shape is saved into.
    application_protocol : {'AP203', 'AP214IS', 'AP242DIS'}, optional
        Version of schema used for the output STEP file. The default is 'AP203'.

    Notes
    -----
    For details on how to read and write STEP files, see the documentation on
    https://dev.opencascade.org/doc/overview/html/occt_user_guides__step.html.

    """
    if shape.IsNull():
        raise AssertionError('Shape is null.')
    if application_protocol not in ['AP203', 'AP214IS', 'AP242DIS']:
        raise ValueError(
            'Application protocol must be one of {"AP203", "AP214IS", "AP242DIS"}.'
        )
    if os.path.isfile(filename):
        warnings.warn('File already exists and will be replaced.',
                      RuntimeWarning)

    # Create and initialize the STEP exporter
    step_writer = STEPControl_Writer()
    Interface_Static_SetCVal("write.step.schema", application_protocol)

    # Transfer shape and write file
    step_writer.Transfer(shape, STEPControl_AsIs)
    status = step_writer.Write(filename)

    if status != IFSelect_RetDone:
        raise IOError('Error while writing shape to STEP file.')
    if not os.path.isfile(filename):
        raise IOError('File was not saved.')
def export_STEPFile(shapes, filename):
    """Exports a .stp file containing the input shapes
    Parameters
    ----------
    shapes : list of TopoDS_Shape
        Shapes to write to file
    filename : string
        The output filename
    """
    # initialize the STEP exporter
    step_writer = STEPControl_Writer()
    #    Interface_Static_SetCVal("write.step.schema", "AP214") # Use default?

    # transfer shapes
    for shape in shapes:
        step_writer.Transfer(shape, STEPControl_AsIs)

    status = step_writer.Write(filename)

    assert (status == IFSelect_RetDone)
    return status
示例#11
0
def write_step_file(a_shape, filename, application_protocol="AP203"):
    """ exports a shape to a STEP file
    a_shape: the topods_shape to export (a compound, a solid etc.)
    filename: the filename
    application protocol: "AP203" or "AP214"
    """
    # a few checks
    assert not a_shape.IsNull()
    assert application_protocol in ["AP203", "AP214IS"]
    if os.path.isfile(filename):
        print("Warning: %s file already exists and will be replaced" %
              filename)
    # creates and initialise the step exporter
    step_writer = STEPControl_Writer()
    Interface_Static_SetCVal("write.step.schema", "AP203")

    # transfer shapes and write file
    step_writer.Transfer(a_shape, STEPControl_AsIs)
    status = step_writer.Write(filename)

    assert status == IFSelect_RetDone
    assert os.path.isfile(filename)
示例#12
0
def build_test(path):
    #points
    pt1 = gp_Pnt(0, 0, 0)
    pt2 = gp_Pnt(0, 2, 0)
    pt3 = gp_Pnt(1.5, 2, 0)
    pt4 = gp_Pnt(1, 0, 0)

    edge1 = BRepBuilderAPI_MakeEdge(pt1, pt2)
    edge2 = BRepBuilderAPI_MakeEdge(pt2, pt3)
    edge3 = BRepBuilderAPI_MakeEdge(pt3, pt4)
    edge4 = BRepBuilderAPI_MakeEdge(pt4, pt1)

    #make wire with 4 edges
    wire = BRepBuilderAPI_MakeWire(edge1.Edge(), edge2.Edge(), edge3.Edge(),
                                   edge4.Edge())

    #alternate wire. create and then add in
    #makeWire = BRepBuilderAPI_MakeWire()
    #makeWire.add( wire )
    #wireProfile = makeWire.Wire()

    face = BRepBuilderAPI_MakeFace(wire.Wire())

    #vector & height
    vector = gp_Vec(0, 0, .1)

    body = BRepPrimAPI_MakePrism(face.Face(), vector)

    # initialize the STEP exporter
    step_writer = STEPControl_Writer()
    Interface_Static_SetCVal("write.step.schema", "AP203")

    # transfer shapes and write file
    step_writer.Transfer(body.Shape(), STEPControl_AsIs)
    status = step_writer.Write(path)

    if status != IFSelect_RetDone:
        raise AssertionError("load failed")
示例#13
0
    def test_static_method(self):
        '''
        Test wrapper for static methods.

        ... snippet from the SWIG documentation ...

        Static class members present a special problem for Python.
        Prior to Python-2.2, Python classes had no support for static methods
        and no version of Python supports static member variables in a manner
        that
        SWIG can utilize. Therefore, SWIG generates wrappers that try to work
        around
        some of these issues. To illustrate, suppose you have a class like
        this:

        class Spam {
        public:
           static void foo();
           static int bar;
        };
        In Python, the static member can be access in three different ways:

        >>> example.Spam_foo()    # Spam::foo()
        >>> s = example.Spam()
        >>> s.foo()               # Spam::foo() via an instance
        >>> example.Spam.foo()    # Spam::foo(). Python-2.2 only

        ... end snippet ...

        In order that SWIG properly wraps static methods, the keyword 'static'
        must be included in the interface file. For instance, in the
        Interface.i file, the following line:

        static Standard_Boolean SetCVal(const char * name, const char * val);

        makes possible to use the method as:
        >>> from OCC.Interface import *
        >>> Interface_Static_SetCVal("write.step.schema","AP203")
        '''
        # needs to be inited otherwise the following does not work
        STEPControl_Writer()
        # Note : static methods are wrapped with lowercase convention
        # so SetCVal can be accessed with setcval
        r = Interface_Static_SetCVal("write.step.schema", "AP203")
        self.assertEqual(r, 1)
        l = Interface_Static_CVal("write.step.schema")
        self.assertEqual(l, "AP203")
示例#14
0
def export_STEPFile_name(shapes, filename):
    print(filename)
    step_writer = STEPControl_Writer()
    ws = step_writer.WS().GetObject()
    print(ws.ModeWriteShape())
##(at your option) any later version.
##
##pythonOCC is distributed in the hope that it will be useful,
##but WITHOUT ANY WARRANTY; without even the implied warranty of
##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##GNU Lesser General Public License for more details.
##
##You should have received a copy of the GNU Lesser General Public License
##along with pythonOCC.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function

from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox

from OCC.STEPControl import STEPControl_Writer, STEPControl_AsIs
from OCC.Interface import Interface_Static_SetCVal
from OCC.IFSelect import IFSelect_RetDone

# creates a basic shape
box_s = BRepPrimAPI_MakeBox(10, 20, 30).Shape()

# initialize the STEP exporter
step_writer = STEPControl_Writer()
Interface_Static_SetCVal("write.step.schema", "AP203")

# transfer shapes and write file
step_writer.Transfer(box_s, STEPControl_AsIs)
status = step_writer.Write("box.stp")

assert (status == IFSelect_RetDone)
示例#16
0
文件: twcad.py 项目: WIEQLI/turboWAVE
    ) == 'domain':
        display.DisplayShape(shape.occ_shape,
                             update=True,
                             transparency=shape.transparency)
start_display()

# Export geometry to STEP or STL if requested
lastArg = sys.argv[-1].split('=')
cmd = lastArg[0]
if cmd == 'stepfile' or cmd == 'stlfile':
    if len(lastArg) == 1:
        print('ERROR: no name was given for the requested output file.')
        exit(1)
    filename = lastArg[1]
    if cmd == 'stepfile':
        step_writer = STEPControl_Writer()
        Interface_Static_SetCVal("write.step.schema", "AP203")
        for shape in tw_shape:
            if shape.Name() in sys.argv:
                step_writer.Transfer(shape.occ_shape, STEPControl_AsIs)
                status = step_writer.Write(filename + '.step')
                assert (status == IFSelect_RetDone)
                exit(0)
    if cmd == 'stlfile':
        stl_writer = StlAPI_Writer()
        stl_writer.SetASCIIMode(True)
        for shape in tw_shape:
            if shape.Name() in sys.argv:
                status = stl_writer.Write(shape.occ_shape, filename + '.stl')
                exit(0)
    print('ERROR: failed to write requested ouptut file.')
示例#17
0
def write_step(shape, file_name):
    step_writer = STEPControl_Writer()
    step_writer.Transfer(shape, STEPControl_AsIs)
    step_writer.Write(file_name)
示例#18
0
RZ = TH - RH + RS
p = gp_Pnt(RX, RY, RZ)
radiator = BRepPrimAPI_MakeBox(p, RL, RW, RH).Shape()

# FANS on radiator
FR = 3  # radius
FD = 2  # depth
FS = 2  # fan's distance from radiator's bottom
FX = float(RL) / 2 + RX
FYleft = RY
FYright = RY + RW
FZ = RZ + FS + FR
p = gp_Ax2(gp_Pnt(FX, FYleft, FZ), -gp_DY())
leftFan = BRepPrimAPI_MakeCylinder(p, FR, FD).Shape()
p = gp_Ax2(gp_Pnt(FX, FYright, FZ), gp_DY())
rightFan = BRepPrimAPI_MakeCylinder(p, FR, FD).Shape()

# initialize the STEP exporter
step_writer = STEPControl_Writer()

# transfer shapes and write file
step_writer.Transfer(tank, STEPControl_AsIs)
step_writer.Transfer(leftBush, STEPControl_AsIs)
step_writer.Transfer(midBush, STEPControl_AsIs)
step_writer.Transfer(rightBush, STEPControl_AsIs)
step_writer.Transfer(expVessel, STEPControl_AsIs)
step_writer.Transfer(radiator, STEPControl_AsIs)
step_writer.Transfer(leftFan, STEPControl_AsIs)
step_writer.Transfer(rightFan, STEPControl_AsIs)
step_writer.Write("temp.stp")
示例#19
0
 def __init__(self, tol=1.0E-6):
     self.obj = STEPControl_Writer()
     self.obj.SetTolerance(tol)
     Interface_Static_SetCVal("write.step.schema", "AP214")
     """
示例#20
0
    def exportStep(self, fileName):

        writer = STEPControl_Writer()
        writer.Transfer(self.wrapped, STEPControl_AsIs)

        return writer.Write(fileName)
示例#21
0
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()
    aResShape = step_reader.Shape(1)
else:
    print("Error: can't read file.")
    sys.exit(0)

##breptools_Clean(aResShape)

# initialize the STEP exporter
step_writer = STEPControl_Writer()
##step_writer = STEPControl_ActorWrite()
## step_writer = STEPCAFControl_Writer()

Interface_Static_SetCVal("write.step.schema", "AP214")

# transfer shapes and write file
#step_writer.Transfer(box_s, STEPControl_AsIs)
#status = step_writer.Write("box.stp")

step_writer.Transfer(aResShape, STEPControl_AsIs)
## step_writer.Transfer(aResShape, STEPControl_GeometricCurveSet)
## step_writer.Transfer(aResShape, STEPControl_ManifoldSolidBrep)
## step_writer.Transfer(aResShape, STEPControl_ShellBasedSurfaceModel)
### step_writer.Transfer(aResShape, STEPControl_FacetedBrep)
### step_writer.Transfer(aResShape, STEPControl_BrepWithVoids)
示例#22
0
def _write_step(table):
    step_writer = STEPControl_Writer()
    step_writer.Transfer(table, STEPControl_AsIs)
    status = step_writer.Write("table.stp")