Пример #1
0
class Model (plotocc):

    def __init__(self):
        super().__init__()

        self.builder = BRep_Builder()
        self.compound = TopoDS_Compound()
        self.builder.MakeCompound(self.compound)

        schema = 'AP203'
        assembly_mode = 1

        self.writer = STEPControl_Writer()
        self.fp = self.writer.WS().TransferWriter().FinderProcess()
        Interface_Static_SetCVal('write.step.schema', schema)
        Interface_Static_SetCVal('write.step.unit', 'M')
        Interface_Static_SetCVal('write.step.assembly', str(assembly_mode))

    def AddShape(self, shp, name="shape"):
        Interface_Static_SetCVal('write.step.product.name', name)
        status = self.writer.Transfer(shp, STEPControl_AsIs)
        if int(status) > int(IFSelect_RetError):
            raise Exception('Some Error occurred')

        # This portion is not working as I hoped
        item = stepconstruct_FindEntity(self.fp, shp)
        if not item:
            raise Exception('Item not found')

    def export_stp_with_name(self):
        status = self.writer.Write(self.tempname + ".stp")
        if int(status) > int(IFSelect_RetError):
            raise Exception('Something bad happened')
Пример #2
0
class ExportCAFMethod(object):
    def __init__(self, name="name", tol=1.0E-10):
        self.name = name
        self.schema = 'AP214'
        self.assembly_mode = 1

        self.stp = STEPControl_Writer()
        self.stp.SetTolerance(tol)
        self.app = self.stp.WS().TransferWriter().FinderProcess()
        Interface_Static_SetCVal('write.step.schema', self.schema)
        Interface_Static_SetCVal('write.step.unit', 'MM')
        Interface_Static_SetCVal('write.step.assembly',
                                 str(self.assembly_mode))

        # Interface_Static_SetCVal ("write.step.schema","AP203")
        # Interface_Static_SetIVal ("write.step.schema", 3)
        # Interface_Static_SetRVal

    def Add(self, shape, name="name"):
        """
        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.
        """
        Interface_Static_SetCVal('write.step.product.name', name)
        self.stp.Transfer(shape, STEPControl_AsIs)
        item = stepconstruct_FindEntity(self.app, shape)
        item.SetName(TCollection_HAsciiString(name))

    def Write(self, filename=None):
        if not filename:
            filename = self.name
        path, ext = os.path.splitext(filename)
        if not ext:
            ext = ".stp"
        status = self.stp.Write(path + ext)
        assert (status == IFSelect_RetDone)
class ExportCAFMethod(object):
    def __init__(self, name="name", tol=1.0E-10):
        self.name = name
        self.writer = STEPControl_Writer()
        self.fp = self.writer.WS().TransferWriter().FinderProcess()
        Interface_Static_SetCVal("write.step.schema", "AP214")
        Interface_Static_SetCVal('write.step.unit', 'mm')
        Interface_Static_SetCVal('write.step.assembly', str(1))

    def Add(self, shape, name="name"):
        """
        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.
        """
        Interface_Static_SetCVal('write.step.product.name', name)
        status = self.writer.Transfer(shape, STEPControl_AsIs)
        if int(status) > int(IFSelect_RetError):
            raise Exception('Some Error occurred')

        # This portion is not working as I hoped
        item = stepconstruct_FindEntity(self.fp, shape)
        if not item:
            raise Exception('Item not found')

        item.SetName(TCollection_HAsciiString(name))

    def Write(self, filename=None):
        if not filename:
            filename = self.name
        path, ext = os.path.splitext(filename)
        if not ext:
            ext = ".stp"
        status = self.writer.Write(path + ext)
        assert (status == IFSelect_RetDone)
Пример #4
0
class StepExporter:
    def __init__(self, schema="AP242", assembly_mode=1):
        self.writer = STEPControl_Writer()
        fp = self.writer.WS().TransferWriter().FinderProcess()
        self.fp = fp

        Interface_Static_SetCVal("write.step.schema", schema)
        # Interface_Static_SetCVal('write.precision.val', '1e-5')
        Interface_Static_SetCVal("write.precision.mode", "1")
        Interface_Static_SetCVal("write.step.assembly", str(assembly_mode))

    def add_to_step_writer(self,
                           obj: valid_types,
                           geom_repr=ElemType.SOLID,
                           fuse_piping=False):
        """Write current assembly to STEP file"""
        from ada.concepts.connections import JointBase

        if geom_repr not in ElemType.all:
            raise ValueError(
                f'Invalid geom_repr: "{geom_repr}". Must be in "{ElemType.all}"'
            )

        if issubclass(type(obj), Shape):
            self.add_geom(obj.geom, obj, geom_repr=geom_repr)
        elif type(obj) in (Beam, Plate, Wall):
            self.export_structural(obj, geom_repr)
        elif type(obj) is Pipe:
            self.export_piping(obj, geom_repr, fuse_piping)
        elif type(obj) in (Part, Assembly) or issubclass(type(obj), JointBase):
            for sub_obj in obj.get_all_physical_objects(
                    sub_elements_only=False):
                if type(sub_obj) in (Plate, Beam, Wall):
                    self.export_structural(sub_obj, geom_repr)
                elif type(sub_obj) in (Pipe, ):
                    self.export_piping(sub_obj, geom_repr, fuse_piping)
                elif issubclass(type(sub_obj), Shape):
                    self.add_geom(sub_obj.geom, sub_obj, geom_repr=geom_repr)
                else:
                    raise ValueError("Unknown Geometry type")
        else:
            raise ValueError("Unknown Geometry type")

    def add_geom(self, geom, obj, geom_repr=None):
        from ada.concepts.transforms import Placement
        from ada.core.vector_utils import vector_length

        from .utils import transform_shape

        name = obj.name if obj.name is not None else next(shp_names)
        Interface_Static_SetCVal("write.step.product.name", name)

        # Transform geometry
        res = obj.placement.absolute_placement()
        if vector_length(res - Placement().origin) > 0:
            geom = transform_shape(geom, transform=tuple(res))
        try:
            if geom_repr == ElemType.SHELL:
                stat = self.writer.Transfer(
                    geom, STEPControl_ShellBasedSurfaceModel)
            else:
                stat = self.writer.Transfer(geom, STEPControl_AsIs)
        except BaseException as e:
            logging.info(f"Passing {obj} due to {e}")
            return None

        if int(stat) > int(IFSelect_RetError):
            raise Exception("Some Error occurred")

        item = stepconstruct_FindEntity(self.fp, geom)
        if not item:
            logging.debug("STEP item not found for FindEntity")
        else:
            item.SetName(TCollection_HAsciiString(name))

    def export_structural(self, stru_obj: Union[Plate, Beam, Wall], geom_repr):
        if geom_repr == ElemType.SHELL:
            self.add_geom(stru_obj.shell, stru_obj)
        elif geom_repr == ElemType.LINE:
            self.add_geom(stru_obj.line, stru_obj)
        else:
            self.add_geom(stru_obj.solid, stru_obj)

    def export_piping(self, pipe: Pipe, geom_repr, fuse_shapes=False):
        result = None
        for pipe_seg in pipe.segments:
            if geom_repr == ElemType.LINE:
                geom = pipe_seg.line
            elif geom_repr == ElemType.SHELL:
                geom = pipe_seg.shell
            else:
                geom = pipe_seg.solid

            if fuse_shapes is True:
                if result is None:
                    result = geom
                else:
                    result = BRepAlgoAPI_Fuse(result, geom).Shape()
            else:
                self.add_geom(geom, pipe)

        if fuse_shapes is True:
            self.add_geom(result, pipe)

    def write_to_file(self,
                      destination_file,
                      silent,
                      return_file_obj=False) -> Union[None, StringIO]:
        if return_file_obj:
            logging.warning(
                "returning file objects for STEP is not yet supported. But will be from OCCT v7.7.0."
            )

        destination_file = pathlib.Path(destination_file).with_suffix(".stp")
        os.makedirs(destination_file.parent, exist_ok=True)

        status = self.writer.Write(str(destination_file))
        if int(status) > int(IFSelect_RetError):
            raise Exception("Error during write operation")
        if silent is False:
            print(f'step file created at "{destination_file}"')
Пример #5
0
def export_STEPFile_name(shapes, filename):
    print(filename)
    step_writer = STEPControl_Writer()
    ws = step_writer.WS().GetObject()
    print(ws.ModeWriteShape())
Пример #6
0
    def to_stp(self, destination_file, geom_repr="solid", schema="AP242"):
        """
        Write current assembly to STEP file

        OpenCascade reference:

            https://www.opencascade.com/doc/occt-7.4.0/overview/html/occt_user_guides__step.html#occt_step_3


        :param destination_file:
        :param geom_repr:
        :param schema: STEP Schemas.
        """

        from OCC.Core.IFSelect import IFSelect_RetError
        from OCC.Core.Interface import Interface_Static_SetCVal
        from OCC.Core.STEPConstruct import stepconstruct_FindEntity
        from OCC.Core.STEPControl import STEPControl_AsIs, STEPControl_Writer
        from OCC.Core.TCollection import TCollection_HAsciiString

        from ada.core.utils import Counter

        if geom_repr not in ["shell", "solid"]:
            raise ValueError(
                'Geometry representation can only accept either "solid" or "shell" as input'
            )

        destination_file = pathlib.Path(destination_file).with_suffix(".stp")

        assembly_mode = 1
        shp_names = Counter(1, "shp")
        writer = STEPControl_Writer()
        fp = writer.WS().TransferWriter().FinderProcess()
        Interface_Static_SetCVal("write.step.schema", schema)
        # Interface_Static_SetCVal('write.precision.val', '1e-5')
        Interface_Static_SetCVal("write.precision.mode", "1")
        Interface_Static_SetCVal("write.step.assembly", str(assembly_mode))

        from ada import Assembly, Beam, Part, Pipe, Plate, Shape, Wall

        def add_geom(geo, o):
            name = o.name if o.name is not None else next(shp_names)
            Interface_Static_SetCVal("write.step.product.name", name)
            stat = writer.Transfer(geo, STEPControl_AsIs)
            if int(stat) > int(IFSelect_RetError):
                raise Exception("Some Error occurred")

            item = stepconstruct_FindEntity(fp, geo)
            if not item:
                logging.debug("STEP item not found for FindEntity")
            else:
                item.SetName(TCollection_HAsciiString(name))

        if type(self) is Shape:
            assert isinstance(self, Shape)
            add_geom(self.geom, self)
        elif type(self) in (Beam, Plate, Wall):
            assert isinstance(self, (Beam, Plate, Wall))
            if geom_repr == "shell":
                add_geom(self.shell, self)
            else:
                add_geom(self.solid, self)
        elif type(self) is Pipe:
            assert isinstance(self, Pipe)
            for geom in self.geometries:
                add_geom(geom, self)
        elif type(self) in (Part, Assembly):
            assert isinstance(self, Part)

            for p in self.get_all_subparts() + [self]:
                for obj in list(p.plates) + list(p.beams) + list(
                        p.shapes) + list(p.pipes) + list(p.walls):
                    if type(obj) in (Plate, Beam, Wall):
                        try:
                            if geom_repr == "shell":
                                add_geom(obj.shell, self)
                            else:
                                add_geom(obj.solid, self)
                        except BaseException as e:
                            logging.info(f'passing pl "{obj.name}" due to {e}')
                            continue
                    elif type(obj) in (Pipe, ):
                        assert isinstance(obj, Pipe)
                        for geom in obj.geometries:
                            add_geom(geom, self)
                    elif type(obj) is Shape:
                        add_geom(obj.geom, self)
                    else:
                        raise ValueError("Unkown Geometry type")

        os.makedirs(destination_file.parent, exist_ok=True)

        status = writer.Write(str(destination_file))
        if int(status) > int(IFSelect_RetError):
            raise Exception("Error during write operation")

        print(f'step file created at "{destination_file}"')
Пример #7
0
from OCC.Core.IFSelect import IFSelect_RetError
from OCC.Core.Interface import Interface_Static_SetCVal
from OCC.Core.STEPConstruct import stepconstruct_FindEntity
from OCC.Core.STEPControl import (STEPControl_AsIs, STEPControl_Writer)
from OCC.Core.TCollection import TCollection_HAsciiString
from OCC.Core.BRepPrimAPI import BRepPrimAPI_MakeBox
from OCC.Extend.DataExchange import read_step_file_with_names_colors

schema = 'AP203'
assembly_mode = 1

writer = STEPControl_Writer()
fp = writer.WS().TransferWriter().FinderProcess()
Interface_Static_SetCVal('write.step.schema', schema)
Interface_Static_SetCVal('write.step.unit', 'M')
Interface_Static_SetCVal('write.step.assembly', str(assembly_mode))

my_box1 = BRepPrimAPI_MakeBox(10., 20., 30.).Shape()
my_box2 = BRepPrimAPI_MakeBox(20., 1., 30.).Shape()

components = [my_box1, my_box2]
comp_names = ['PartA', 'PartB']
for i, comp in enumerate(components):
    Interface_Static_SetCVal('write.step.product.name', comp_names[i])
    status = writer.Transfer(comp, STEPControl_AsIs)
    if int(status) > int(IFSelect_RetError):
        raise Exception('Some Error occurred')

    # This portion is not working as I hoped
    item = stepconstruct_FindEntity(fp, comp)
    if not item:
Пример #8
0
class StepWrite(object):
    """
    Write shape to a STEP file.
    
    :param str schema: Schema for STEP file ('AP203', or 'AP214').
    :param units: Units to convert STEP file to.
    :type units: str or None
    :param product_name: The name of the STEP product entry. If more than
        one product is generated during translation, then OpenCASCADE will
        automatically append a unique integer.
    :type product_name: str or None
    :param assembly_mode: Mode for writing assemblies (0, 1, or 2).
    :type assembly_mode: int or None

    .. note::
        The assembly modes are as follows:

        * 0 (off, default): Writes STEP files without assemblies.
        * 1(on): Writes all shapes in the form of STEP assemblies.
        * 2(auto): Writes shapes having a structure of (possibly nested)
          compounds in the form of STEP assemblies, single shapes are written
          without assembly structures.
    """
    def __init__(self,
                 schema='AP203',
                 units=None,
                 product_name=None,
                 assembly_mode=None):
        self._writer = STEPControl_Writer()
        self._fp = self._writer.WS().TransferWriter().FinderProcess()
        Interface_Static.SetCVal('write.step.schema', schema)

        try:
            units = units_dict[units]
        except KeyError:
            units = Settings.units
        Interface_Static.SetCVal('write.step.unit', units)

        if product_name is not None:
            Interface_Static.SetCVal('write.step.product.name', product_name)

        if assembly_mode is not None:
            Interface_Static.SetIVal_('write.step.assembly', assembly_mode)

    @property
    def object(self):
        """
        :return: The STEP writer object.
        :rtype: OCC.Core.STEPControl.STEPControl_Writer
        """
        return self._writer

    def transfer(self, *shapes):
        """
        Transfer and add the shapes to the exported entities.

        :param afem.topology.entities.Shape shapes: The shape(s).

        :return: *True* if shape was transferred, *False* if not.
        :rtype: bool
        """
        added_shape = False
        for shape in shapes:
            shape = Shape.to_shape(shape)
            if not shape:
                continue
            status = self._writer.Transfer(shape.object, STEPControl_AsIs)
            if int(status) < int(IFSelect_RetError):
                added_shape = True
        return added_shape

    def set_name(self, shape, name):
        """
        Set the name of the STEP entity for the given shape. The shape(s)
        should be transferred before naming them.

        :param afem.topology.entities.Shape shape: The shape (or sub-shape).
        :param str name: The name.

        :return: *True* if name is set, *False* otherwise.
        :rtype: bool
        """
        item = stepconstruct.FindEntity(self._fp, shape.object)
        if not item:
            return False

        item.SetName(TCollection_HAsciiString(name))
        return True

    def write(self, fn='afem.stp'):
        """
        Write the STEP file.

        :param str fn: The filename.

        :return: *True* if written, *False* if not.
        :rtype: bool
        """
        status = self._writer.Write(fn)
        return int(status) < int(IFSelect_RetError)