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 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()
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
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, 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
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 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'
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
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")
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 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')
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 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
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
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
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)
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
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") for i in range(reader.NbRootsForTransfer()): reader.TransferRoot(i + 1) 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)
from OCC.STEPControl import STEPControl_Reader from OCC.StlAPI import StlAPI_Writer import sys input_file = sys.argv[1][0] output_file = sys.argv[1][1] step_reader = STEPControl_Reader() step_reader.ReadFile(input_file) step_reader.TransferRoot() myshape = step_reader.Shape() print("File read") # Export to STL stl_writer = StlAPI_Writer() stl_writer.SetASCIIMode(True) stl_writer.Write(myshape, output_file) print("Written")
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
from OCC.STEPControl import STEPControl_Reader from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity from OCC.Display.SimpleGui import init_display import sys step_reader = STEPControl_Reader() #status = step_reader.ReadFile('../stp/TABBY_EVO_step_asm.stp') #status = step_reader.ReadFile('../stp/single.stp') #status = step_reader.ReadFile('../stp/both.stp') #status = step_reader.ReadFile('../stp/part123.stp') status = step_reader.ReadFile('../stp/wheel.stp') #status = step_reader.ReadFile('../stp/tab2clean.stp') #status = step_reader.ReadFile('../stp/example.stp') #status = step_reader.ReadFile('../stp/TabbyEvo_4.stp') #status = step_reader.ReadFile('../stp/cylinder_block.stp') 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) #display, start_display, add_menu, add_function_to_menu = init_display() #display.DisplayShape(aResShape, update=True)
from OCC.STEPControl import STEPControl_Reader from OCC.TopAbs import TopAbs_FACE from OCC.TopExp import TopExp_Explorer from occlib.Topology import Topo from occlib.EdgeParse import EdgeOnSurface from occlib.BoundingBox import get_boundingbox from occlib.Scene import Line3D, Arc3D, BSpline3D import matplotlib.pyplot as plt import matplotlib.patches as mpatches if __name__ == "__main__": # Read the file and get the shape reader = STEPControl_Reader() tr = reader.WS().GetObject().TransferReader().GetObject() reader.ReadFile( os.path.abspath(os.path.join('.', 'models', 'TPI_PH_CNF95XX.STEP'))) reader.TransferRoots() shape = reader.OneShape() # Get bounding box xmin, ymin, zmin, xmax, ymax, zmax = get_boundingbox(shape) # Build section plane XYZ = (1, 0, 1) lim_coord1 = (xmin, xmax) lim_coord2 = (zmin, zmax) section_width = ymin + 1e-3
#! /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)
##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 OCC.STEPControl import STEPControl_Reader from OCC.Graphic3d import Graphic3d_NOM_STEEL from OCC.BRepAlgoAPI import BRepAlgoAPI_Cut from OCC.Display.SimpleGui import init_display from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox from OCC.gp import gp_Vec, gp_Trsf from OCC.BRepBuilderAPI import BRepBuilderAPI_Transform # loads file step_reader = STEPControl_Reader() step_reader.ReadFile('../_models/cylinder_block_mold_model.stp') step_reader.TransferRoot() block_cylinder_shape = step_reader.Shape() # create box box = BRepPrimAPI_MakeBox(30, 90, 90).Shape() trns = gp_Trsf() trns.SetTranslation(gp_Vec(0, -35, -35)) mold_basis = BRepBuilderAPI_Transform(box, trns).Shape() # compute mold print mold = BRepAlgoAPI_Cut(mold_basis, block_cylinder_shape).Shape() # display display, start_display, add_menu, add_function_to_menu = init_display()