Exemple #1
0
    def load_shape_from_file(self, filename):
        """
        This method loads a shape from the file `filename`.

        :param string filename: name of the input file.
            It should have proper extension (.step or .stp)

        :return: shape: loaded shape
        :rtype: TopoDS_Shape
        """
        self._check_filename_type(filename)
        self._check_extension(filename)
        reader = STEPControl_Reader()
        return_reader = reader.ReadFile(filename)
        # check status
        if return_reader == IFSelect_RetDone:
            return_transfer = reader.TransferRoots()
            if return_transfer:
                # load all shapes in one
                shape = reader.OneShape()
                return shape
            else:
                raise RuntimeError("Shapes not loaded.")
        else:
            raise RuntimeError("Cannot read the file.")
def read_step_file(filename, return_as_shapes=False, verbosity=False):
    """ read the STEP 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)

    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)
        ok = step_reader.TransferRoot(1)
        _nbs = step_reader.NbShapes()
        shape_to_return = step_reader.Shape(1)  # a compound
        assert not shape_to_return.IsNull()
    else:
        raise AssertionError("Error: can't read file.")
    if return_as_shapes:
        shape_to_return = TopologyExplorer(shape_to_return).solids()

    return shape_to_return
Exemple #3
0
def convert(source, dest):
    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(source)

    if status == IFSelect_RetDone:
        i = 1
        ok = False
        number_of_roots = step_reader.NbRootsForTransfer()

        while i <= number_of_roots and not ok:
            ok = step_reader.TransferRoot(i)
            i += 1

        if (not ok):
            return {
                'error': 'Failed to find a suitable root for the STEP file'
            }

        shape = step_reader.Shape(1)
        output = os.path.abspath(dest)
        stl_ascii = False
        stl_writer = StlAPI_Writer()
        stl_writer.SetASCIIMode(stl_ascii)
        stl_writer.Write(shape, output)
        print "STL FILE: %s" % output

    else:
        print "Error, can't read file: %s" % './demo.stp'
Exemple #4
0
def main(argv):
  step_reader = STEPControl_Reader()
  status = step_reader.ReadFile(argv[0])

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

      number_of_roots = step_reader.NbRootsForTransfer()

      ok = False
      i = 1

      while not ok and i <= number_of_roots:
        ok = step_reader.TransferRoot(i)
        i += 1

      _nbs = step_reader.NbShapes()
      aResShape = step_reader.Shape(1)
  else:
      print("Error: can't read file.")
      sys.exit(0)

  display, start_display, add_menu, add_function_to_menu = init_display()
  display.DisplayShape(aResShape, update=True)
  start_display()
Exemple #5
0
 def load_stp(self, path):
     """ Load a stp model """
     reader = STEPControl_Reader()
     status = reader.ReadFile(path)
     if status != IFSelect_RetDone:
         raise ValueError("Failed to load: {}".format(path))
     reader.PrintCheckLoad(False, IFSelect_ItemsByEntity)
     reader.PrintCheckTransfer(False, IFSelect_ItemsByEntity)
     ok = reader.TransferRoot()
     return reader.Shape(1)
def load_step_singleshape(filename):
    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(filename)
    if status != IFSelect_RetDone:
        raise IOError("STEP reader status = %s" % (str(status)))

    step_reader.TransferRoot(1)  # Not sure what this does

    if step_reader.NbShapes() > 1:
        raise ValueError("STEP file contains multiple shapes")

    return step_reader.Shape(1)
def analyze_file(filename):
    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(str(filename))
    result = None

    if status == IFSelect_RetDone:  # check status
        number_of_roots = step_reader.NbRootsForTransfer()
        ok = False
        i = 1

        while i <= number_of_roots and not ok:
            ok = step_reader.TransferRoot(i)
            i += 1

        if (not ok):
            return {
                'error': 'Failed to find a suitable root for the STEP file'
            }

        number_of_shapes = step_reader.NbShapes()

        if (number_of_shapes > 1):
            return {'error': 'Cannot handle more than one shape in a file'}

        aResShape = step_reader.Shape(1)

        # bounding box
        bbox = Bnd_Box()
        deflection = 0.01
        BRepMesh_IncrementalMesh(aResShape, deflection)

        brepbndlib_Add(aResShape, bbox)
        xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()

        bounding_box = calculate_bnd_box(bbox)

        result = {
            'x0': bounding_box['x_min'],
            'x1': bounding_box['x_max'],
            'y0': bounding_box['y_min'],
            'y1': bounding_box['y_max'],
            'z0': bounding_box['z_min'],
            'z1': bounding_box['z_max'],
            'length': bounding_box['x_length'],
            'width': bounding_box['z_length'],
            'height': bounding_box['y_length'],
            'volume': calculate_volume(aResShape)
        }

    else:
        result = {'error': 'Cannot read file'}

    return result
Exemple #8
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
Exemple #9
0
    def _load_model_file(filePath):
        step_reader = STEPControl_Reader()
        status = step_reader.ReadFile(filePath)

        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()

            _shape = step_reader.Shape(1)
            return _shape
        else:
            raise Exception("Error: can't read file - Method: _load_STEP_file")
Exemple #10
0
def read_step(filename):
    from OCC.STEPControl import STEPControl_Reader
    from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity

    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(filename)
    if status == IFSelect_RetDone:
        failsonly = False
        step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
        step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) 

        ok = step_reader.TransferRoot(1)
        _nbs = step_reader.NbShapes()
        return step_reader.Shape(1)
    else:
        raise ValueError('Cannot read the file')
Exemple #11
0
def read_step_file(filename):
    """ read the STEP file and returns a compound
    """
    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(filename)

    if status == IFSelect_RetDone:  # check status
        failsonly = False
        step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
        step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
        step_reader.TransferRoot(1)
        a_shape = step_reader.Shape(1)
    else:
        print("Error: can't read file.")
        sys.exit(0)
    return a_shape
Exemple #12
0
def read_step_file(filename):
    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(filename)

    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)
    return aResShape
def get_shape_from_file(filename):
    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(str(filename))

    if status == IFSelect_RetDone:
        number_of_roots = step_reader.NbRootsForTransfer()
    else:
        raise ConversionError("Could not read {}".format(filename))

    i = 1
    ok = False
    while not ok and i <= number_of_roots:
        ok = step_reader.TransferRoot(i)
        i += 1

    return ok and step_reader.Shape(1)
Exemple #14
0
    def load_shape_from_file(self, filename):
        """
		This method loads a shape from the file `filename`.

		:param string filename: name of the input file.
			It should have proper extension (.step or .stp)

		:return: shape: loaded shape
		:rtype: TopoDS_Shape
		"""
        self._check_filename_type(filename)
        self._check_extension(filename)
        reader = STEPControl_Reader()
        reader.ReadFile(filename)
        reader.TransferRoots()
        shape = reader.Shape()
        return shape
def read_step_file(filename):
    """ read the STEP file and returns a compound
    """
    print("loading STEP file... ")
    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(filename)

    if status == IFSelect_RetDone:  # check status
        failsonly = False

        ok = step_reader.TransferRoot(1)
        _nbs = step_reader.NbShapes()
        aResShape = step_reader.Shape(1)
    else:
        print("Error: can't read file.")
        sys.exit(0)
    print("done.")
    return aResShape
Exemple #16
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 #17
0
def importStep(fileName):
    """
        Accepts a file name and loads the STEP file into a cadquery shape
        :param fileName: The path and name of the STEP file to be imported
    """
    # Now read and return the shape
    reader = STEPControl_Reader()
    readStatus = reader.ReadFile(fileName)
    if readStatus != OCC.IFSelect.IFSelect_RetDone:
        raise ValueError("STEP File could not be loaded")
    reader.TransferRoot()

    occ_shapes = []
    for i in range(reader.NbShapes()):
        occ_shapes.append(reader.Shape(i + 1))

    # Make sure that we extract all the solids
    solids = []
    for shape in occ_shapes:
        solids.append(Shape.cast(shape))

    return cadquery.Workplane("XY").newObject(solids)
Exemple #18
0
    def make_shape(shape_name):
        global current_color

        # cf CADMBTB_API, but cannot get the same color order
        colors = list(
            reversed([
                Quantity_NOC_DARKVIOLET, Quantity_NOC_BLUE1,
                Quantity_NOC_GREEN, Quantity_NOC_RED, Quantity_NOC_ORANGE,
                Quantity_NOC_SALMON, Quantity_NOC_YELLOW
            ]))

        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):
                    ais_shape = display.DisplayShape(step_reader.Shape(i),
                                                     update=True,
                                                     transparency=.55)
                    ais_shape.GetObject().SetColor(colors[current_color % 6])
                    current_color += 1
                    ais_shape.GetObject().SetMaterial(
                        Graphic3d.Graphic3d_NOM_PLASTIC)
                    l.append(ais_shape)

                return l
Exemple #19
0
#! /home/uguen/anaconda/bin/python
from OCC.STEPControl import STEPControl_Reader
from OCC.Display.WebGl import x3dom_renderer_osv
import pdb
import sys
#
# usage stp2html.py filename level
#
filename = sys.argv[1]
level = sys.argv[2]
fileout = filename.replace('.stp', '')
step_reader = STEPControl_Reader()
step_reader.ReadFile(filename)
step_reader.TransferRoot()
shape = step_reader.Shape()
my_renderer = x3dom_renderer_osv.X3DomRenderer(path='.',
                                               filename=fileout,
                                               level=level)
#my_renderer = x3dom_renderer.X3DomRenderer()
my_renderer.DisplayShape(shape)
Exemple #20
0
def analyze_file(filename):
    step_reader = STEPControl_Reader()
    status = step_reader.ReadFile(filename)
    result = None

    if status == IFSelect_RetDone:  # check status
        number_of_roots = step_reader.NbRootsForTransfer()
        ok = False
        i = 1

        while i <= number_of_roots and not ok:
            ok = step_reader.TransferRoot(i)
            i += 1

        if (not ok):
            return {
                'error': 'Failed to find a suitable root for the STEP file'
            }

        number_of_shapes = step_reader.NbShapes()

        if (number_of_shapes > 1):
            return {'error': 'Cannot handle more than one shape in a file'}

        aResShape = step_reader.Shape(1)

        # Units
        length = TColStd_SequenceOfAsciiString()
        angles = TColStd_SequenceOfAsciiString()
        solid_angles = TColStd_SequenceOfAsciiString()
        step_reader.FileUnits(length, angles, solid_angles)

        # bounding box
        bbox = Bnd_Box()
        deflection = 0.01
        BRepMesh_IncrementalMesh(aResShape, deflection)

        brepbndlib_Add(aResShape, bbox)
        xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()

        bounding_box = calculate_bnd_box(bbox)

        bounding_cylinder = calculate_bounding_cylinder(
            aResShape, bounding_box)

        result = {
            'bounding_box_volume': bounding_box['volume'],
            'bounding_box_x_length': bounding_box['x_length'],
            'bounding_box_y_length': bounding_box['y_length'],
            'bounding_box_z_length': bounding_box['z_length'],
            'mesh_volume': calculate_volume(aResShape),
            'mesh_surface_area': None,
            'cylinder_volume': bounding_cylinder['cylinder_volume'],
            'cylinder_diameter': bounding_cylinder['radius'] * 2,
            'cylinder_length': bounding_cylinder['height'],
            'convex_hull_volume': None,
            'euler_number': None,
            'units': length.First().ToCString().lower()
        }

    else:
        result = {'error': 'Cannot read file'}

    return result