예제 #1
0
파일: io.py 프로젝트: psavine42/OCCUtilsExt
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 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")
예제 #4
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))
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 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)
예제 #7
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")
예제 #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")
##(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)
예제 #14
0
파일: twcad.py 프로젝트: WIEQLI/turboWAVE
                             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.')
    print('Did you list a valid region on the command line?')
예제 #15
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")
예제 #16
0
    def exportStep(self, fileName):

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

        return writer.Write(fileName)
예제 #17
0
    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)

# -  case STEPControl_AsIs : ModeTrans() = 0; break;
# -  case STEPControl_ManifoldSolidBrep : ModeTrans() = 3; break;
# -  case STEPControl_BrepWithVoids :     ModeTrans() = 5; break;
# -  case STEPControl_FacetedBrep :       ModeTrans() = 1; break;
# -  case STEPControl_FacetedBrepAndBrepWithVoids : ModeTrans() = 6; break;
# -  case STEPControl_ShellBasedSurfaceModel :      ModeTrans() = 2;
# -  case STEPControl_GeometricCurveSet :           ModeTrans() = 4;
# -  case STEPControl_Hybrid : ModeTrans() = 0; break;  // PAS IMPLEMENTE !!
##step_writer.Transfer(aResShape)
예제 #18
0
def _write_step(table):
    step_writer = STEPControl_Writer()
    step_writer.Transfer(table, STEPControl_AsIs)
    status = step_writer.Write("table.stp")
예제 #19
0
def write_step(shape, file_name):
    step_writer = STEPControl_Writer()
    step_writer.Transfer(shape, STEPControl_AsIs)
    step_writer.Write(file_name)