def read_in_step_files_and_save_as_seperate_step_files(read_folder, write_folder): try: os.mkdir(write_folder) except: print('error making folder') if os.path.isfile(read_folder): file = read_folder if file.endswith(".step") or file.endswith(".stp"): print('reading in ', os.path.join(read_folder, file)) multipart_step = Part.read(file) file_counter = 1 for solid in multipart_step.Solids: print(write_folder + '/' + file + str(file_counter)) solid.exportStep(write_folder + '/' + os.path.splitext(file)[0] + str(file_counter) + '.stp') file_counter = file_counter + 1 return True for file in os.listdir(read_folder): if file.endswith(".step") or file.endswith(".stp"): print('reading in ', os.path.join(read_folder, file)) multipart_step = Part.read(os.path.join(read_folder, file)) file_counter = 1 for solid in multipart_step.Solids: print(write_folder + '/' + file + str(file_counter)) solid.exportStep(write_folder + '/' + os.path.splitext(file)[0] + str(file_counter) + '.stp') file_counter = file_counter + 1 return True
def execute(self, obj): # Load workplane model WorkplaneModelPath = "C:\\repos\\MHTech\\trunk\\SimpleCAM\\VakuumplanXY.step" # Should load from setup sheet workplaneShape = None try: workplaneShape = Part.read(WorkplaneModelPath) except: pass if workplaneShape: workplaneShape.Placement.Base = FreeCAD.Vector(0.0, 0.0, 0.0) workplaneShape.Placement.Rotation = FreeCAD.Rotation(0.0, 0.0, 0.0) # Load VacuumTable Model vacuumTableShape = None try: vacuumTableShape = Part.read(obj.VacuumTableModelPath) except: pass if vacuumTableShape: vacuumTableShape.Placement.Base = FreeCAD.Vector( obj.XPos, obj.YPos, 0.0) vacuumTableShape.Placement.Rotation = FreeCAD.Rotation( obj.Orientation, 0.0, 0.0) # Combine workplane and VacuumTable models if vacuumTableShape and workplaneShape: obj.Shape = workplaneShape.fuse(vacuumTableShape) obj.Placement = workplaneShape.Placement elif workplaneShape: obj.Shape = workplaneShape obj.Placement = workplaneShape.Placement
def read_in_envelope_file(envelope_directory_filename): if os.path.isfile(envelope_directory_filename): envelope = Part.read(envelope_directory_filename) elif os.path.isfile( pkg_resources.resource_filename('breeder_blanket_model_maker', envelope_directory_filename)): envelope = Part.read( pkg_resources.resource_filename('breeder_blanket_model_maker', envelope_directory_filename)) else: raise ValueError('Input envelope file was not found') return envelope
def downloadReadyObject(self, downloadReadyObj): if downloadReadyObj["isExternal"]: # Alert user that this is a crawled document. msgBox = QtWidgets.QMessageBox() msgBox.setIcon(QtWidgets.QMessageBox.Question) msgBox.setWindowTitle("3DfindIT") msgBox.setText( "Should 3DfindIT redirect you to the website of the supplier?") msgBox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) msgBox.setWindowModality(QtCore.Qt.ApplicationModal) if (msgBox.exec_() == QtWidgets.QMessageBox.Yes): # Open in system browser. webbrowser.open(downloadReadyObj["url"], new=2) else: # Download file. tmpDownloadPath = tempfile.mkstemp(prefix="3df", suffix=".zip")[1] urlretrieve(downloadReadyObj["url"], tmpDownloadPath) # Extract zip file. tmpExtractPath = tempfile.mkdtemp(prefix="3df") with ZipFile(tmpDownloadPath, 'r') as zip: zip.extractall(tmpExtractPath) # Open the STEP file. stepFile = tmpExtractPath + "\\" + downloadReadyObj["startFile"] Part.show(Part.read(stepFile), downloadReadyObj["NB"]) # Fit to view. FreeCADGui.SendMsgToActiveView("ViewFit")
def importStepFromURL(url): #Now read and return the shape try: # Account for differences in urllib between Python 2 and 3 if hasattr(urlreader, "urlopen"): webFile = urlreader.urlopen(url) else: import urllib.request webFile = urllib.request.urlopen(url) tempFile = tempfile.NamedTemporaryFile(suffix='.step', delete=False) tempFile.write(webFile.read()) webFile.close() tempFile.close() rshape = Part.read(tempFile.name) #Make sure that we extract all the solids solids = [] for solid in rshape.Solids: solids.append(Shape.cast(solid)) return cadquery.Workplane("XY").newObject(solids) except: raise ValueError("STEP File from the URL: " + url + " Could not be loaded")
def insert(filename,docname,returnpath=False): """Called by FreeCAD on importing a file in an existing document""" converter = getConverter() if not converter: FreeCAD.Console.PrintError(translate("CADExchanger","CAD Exchanger converter path is not set. Please check Preferences -> Import/Export/CAD Exchanger\n")) return try: doc = FreeCAD.getDocument(docname) except NameError: doc = FreeCAD.newDocument(docname) FreeCAD.ActiveDocument = doc tempname = tempfile.mkstemp(suffix=".brep")[1] #exstr = [converter, " -i ", filename, " -e ", tempname] exstr = [converter, " -i \"", filename, "\" -e \"", tempname, "\""] print ("executing "+"".join(exstr)) #result = subprocess.call(exstr) result = subprocess.Popen("".join(exstr), shell=True, stdout=subprocess.PIPE) stdout = result.communicate()[0] if result.returncode != 0: FreeCAD.Console.PrintError(translate("CADExchanger","Error during CADExchanger conversion\n")) if not isinstance(stdout,str): stdout = stdout.decode("utf8") print('CADExchanger output:\n' + stdout) return if returnpath: return tempname else: import Part Part.show(Part.read(tempname)) return doc
def insertPart(directory, filename, document, group, attributes=None): if not os.path.isfile(os.path.join(directory, filename)): directory = os.path.expanduser('~/.FreeCAD/Mod/yaml-workspace') if not os.path.isfile(os.path.join(directory, filename)): print('ERROR: `{}` not found!'.format(filename)) return part = Part.Shape() part = Part.read(u'{}/{}'.format(directory, filename)) object_name = filename[:-4] if 'objectName' in attributes: object_name = attributes['objectName'] new_part = document.addObject("Part::Feature", object_name) new_part.Shape = part if attributes: color = getColor(attributes) if color: new_part.ViewObject.ShapeColor = color transparency = getTransparency(attributes) if transparency: new_part.ViewObject.Transparency = transparency placement = getPlacement(attributes) rotation = getRotation(attributes) new_part.Placement = App.Placement(placement, rotation) group.addObject(new_part)
def insert(filename, docname): "called on importing a file in an existing document" if not converter: FreeCAD.Console.PrintError( translate( "CADExchanger", "CAD Exchanger converter path is not set. Please check Preferences -> Import/Export/CAD Exchanger\n" )) return if subprocess.call(converter) != 1: FreeCAD.Console.PrintError( translate("CADExchanger", "Error while running CAD Exchanger\n")) return try: doc = FreeCAD.getDocument(docname) except NameError: doc = FreeCAD.newDocument(docname) FreeCAD.ActiveDocument = doc tempname = tempfile.mkstemp(suffix=".brep")[1] exstr = [converter, " -i ", filename, " -e ", tempname] print "executing " + "".join(exstr) result = subprocess.call(exstr) if result != 0: FreeCAD.Console.PrintError( translate("CADExchanger", "Error during CAD Exchanger conversion\n")) return import Part Part.show(Part.read(tempname)) return doc
def read_in_step_files_and_save_as_single_stl_files(read_folder, write_folder, ignore_files=['']): list_of_solid_parts = [] try: os.mkdir(write_folder) print('making folder', write_folder) except: print('error making folder', write_folder) #print('read_folder',read_folder) #print(os.listdir(read_folder)) for file in os.listdir(read_folder): if file not in ignore_files: if file.endswith(".step") or file.endswith(".stp"): #print('reading in ' ,os.path.join(read_folder, file)) multipart_step = Part.read(os.path.join(read_folder, file)) stl_filename = write_folder + '/' + os.path.splitext( file)[0] + '.stl' if len(multipart_step.Solids) == 0: singlepart_step = multipart_step solid_mesh = MeshPart.meshFromShape(singlepart_step, LinearDeflection=0.1) list_of_solid_parts.append(solid_mesh) else: solid_mesh = MeshPart.meshFromShape(multipart_step, LinearDeflection=0.1) solid_mesh.write(stl_filename)
def place(self, path): import FreeCADGui import Part self.shape = Part.read(path) if hasattr(FreeCADGui, "Snapper"): try: import DraftTrackers except Exception: import draftguitools.gui_trackers as DraftTrackers self.box = DraftTrackers.ghostTracker(self.shape, dotted=True, scolor=(0.0, 0.0, 1.0), swidth=1.0) self.delta = self.shape.BoundBox.Center self.box.move(self.delta) self.box.on() if hasattr(FreeCAD, "DraftWorkingPlane"): FreeCAD.DraftWorkingPlane.setup() self.origin = self.makeOriginWidget() FreeCADGui.Snapper.getPoint(movecallback=self.mouseMove, callback=self.mouseClick, extradlg=self.origin) else: Part.show(self.shape)
def insert(self, index=None): import Part if not index: index = self.form.tree.selectedIndexes() if not index: return index = index[0] path = self.dirmodel.filePath(index) self.name = os.path.splitext(os.path.basename(path))[0] if path.lower().endswith(".stp") or path.lower().endswith( ".step") or path.lower().endswith( ".brp") or path.lower().endswith(".brep"): self.shape = Part.read(path) if hasattr(FreeCADGui, "Snapper"): import DraftTrackers self.box = DraftTrackers.ghostTracker(self.shape, dotted=True, scolor=(0.0, 0.0, 1.0), swidth=1.0) self.delta = self.shape.BoundBox.Center self.box.move(self.delta) self.box.on() if hasattr(FreeCAD, "DraftWorkingPlane"): FreeCAD.DraftWorkingPlane.setup() self.origin = self.makeOriginWidget() FreeCADGui.Snapper.getPoint(movecallback=self.move, callback=self.place, extradlg=self.origin) else: Part.show(self.shape) elif path.lower().endswith(".fcstd"): FreeCADGui.ActiveDocument.mergeProject(path)
def getShape(obj,objid): "gets a shape from an IfcOpenShell object" #print "retrieving shape from obj ",objid import Part sh=Part.Shape() brep_data = None if IFCOPENSHELL5: try: brep_data = IfcImport.create_shape(obj) except: print "Unable to retrieve shape data" else: brep_data = obj.mesh.brep_data if brep_data: try: if MAKETEMPFILES: import tempfile tf = tempfile.mkstemp(suffix=".brp")[1] of = pyopen(tf,"wb") of.write(brep_data) of.close() sh = Part.read(tf) os.remove(tf) else: sh.importBrepFromString(brep_data) except: print "Error: malformed shape" return None else: if IFCOPENSHELL5 and ADDPLACEMENT: sh.Placement = getPlacement(getAttr(obj,"ObjectPlacement")) if not sh.Solids: # try to extract a solid shape if sh.Faces: try: if DEBUG: print "Malformed solid. Attempting to fix..." shell = Part.makeShell(sh.Faces) if shell: solid = Part.makeSolid(shell) if solid: sh = solid except: if DEBUG: print "failed to retrieve solid from object ",objid else: if DEBUG: print "object ", objid, " doesn't contain any geometry" if not IFCOPENSHELL5: m = obj.matrix mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9], m[1], m[4], m[7], m[10], m[2], m[5], m[8], m[11], 0, 0, 0, 1) sh.Placement = FreeCAD.Placement(mat) # if DEBUG: print "getting Shape from ",obj #print "getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull() #for v in sh.Vertexes: print v.Point return sh
def importAssembly(FileName,DestItem): for i in Part.read(FileName).Solids: po = FreeCAD.activeDocument().addObject('Assembly::ItemPart','STP-Part') DestItem.Items = DestItem.Items + [po] bo = FreeCAD.activeDocument().addObject('PartDesign::Body','STP-Body') po.Model = bo so = FreeCAD.activeDocument().addObject('PartDesign::Solid','STP-Solid') bo.Model = so bo.Tip = so so.Shape = i
def MirrorPart(path, name): input = path + "/step/" + name + ".step" step = path + "/step/" + name + "-mirrored.step" stl = path + "/stl/" + name + "-mirrored.stl" print ("Reading: " + input) s1 = Part.read(input) s2 = s1.mirror(FreeCAD.Base.Vector(0,0,0),FreeCAD.Base.Vector(0,0,1)) s2.rotate(FreeCAD.Base.Vector(0,0,0),FreeCAD.Base.Vector(0,1,0),180) s2.exportStep(step) s2.exportStl(stl)
def importAssembly(FileName, DestItem): for i in Part.read(FileName).Solids: po = FreeCAD.activeDocument().addObject('Assembly::ItemPart', 'STP-Part') DestItem.Items = DestItem.Items + [po] bo = FreeCAD.activeDocument().addObject('PartDesign::Body', 'STP-Body') po.Model = bo so = FreeCAD.activeDocument().addObject('PartDesign::Solid', 'STP-Solid') bo.Model = so bo.Tip = so so.Shape = i
def clicked(self, index, previewDocName = "Viewer"): import Part, FreeCADGui, zipfile, tempfile, os self.previewOn = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/BIM").GetBool("3DPreview",False) try: self.path = self.dirmodel.filePath(index) except: self.path = self.previousIndex print(self.path) self.isFile = os.path.isfile(self.path) # if the 3D preview checkbox is on ticked, show the preview if self.previewOn == True or self.linked == True: if self.isFile == True: # close a non linked preview document if self.linked == False: try: FreeCAD.closeDocument(self.previewDocName) except: pass # create different kinds of previews based on file type if self.path.lower().endswith(".stp") or self.path.lower().endswith(".step") or self.path.lower().endswith(".brp") or self.path.lower().endswith(".brep"): self.previewDocName = "Viewer" FreeCAD.newDocument(self.previewDocName) FreeCAD.setActiveDocument(self.previewDocName) Part.show(Part.read(self.path)) FreeCADGui.SendMsgToActiveView("ViewFit") elif self.path.lower().endswith(".fcstd"): openedDoc = FreeCAD.openDocument(self.path) FreeCADGui.SendMsgToActiveView("ViewFit") self.previewDocName = FreeCAD.ActiveDocument.Name thumbnailSave = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/BIM").GetBool("SaveThumbnails",False) if thumbnailSave == True: FreeCAD.ActiveDocument.save() if self.linked == False: self.previousIndex = self.path # create a 2D image preview if self.path.lower().endswith(".fcstd"): zfile=zipfile.ZipFile(self.path) files=zfile.namelist() # check for meta-file if it's really a FreeCAD document if files[0] == "Document.xml": image="thumbnails/Thumbnail.png" if image in files: image=zfile.read(image) thumbfile = tempfile.mkstemp(suffix='.png')[1] thumb = open(thumbfile,"wb") thumb.write(image) thumb.close() im = QtGui.QPixmap(thumbfile) self.form.framePreview.setPixmap(im) return self.previewDocName, self.previousIndex, self.linked self.form.framePreview.clear() return self.previewDocName, self.previousIndex, self.linked
def getShape(obj,objid): "gets a shape from an IfcOpenShell object" #print "retrieving shape from obj ",objid import Part sh=Part.Shape() brep_data = None if IOC_ADVANCED: try: brep_data = IfcImport.create_shape(obj) except: print "Unable to retrieve shape data" else: brep_data = obj.mesh.brep_data if brep_data: try: if MAKETEMPFILES: import tempfile tf = tempfile.mkstemp(suffix=".brp")[1] of = pyopen(tf,"wb") of.write(brep_data) of.close() sh = Part.read(tf) os.remove(tf) else: sh.importBrepFromString(brep_data) except: print "Error: malformed shape" return None if not sh.Solids: # try to extract a solid shape if sh.Faces: try: if DEBUG: print "Malformed solid. Attempting to fix..." shell = Part.makeShell(sh.Faces) if shell: solid = Part.makeSolid(shell) if solid: sh = solid except: if DEBUG: print "failed to retrieve solid from object ",objid else: if DEBUG: print "object ", objid, " doesn't contain any geometry" if not IOC_ADVANCED: m = obj.matrix mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9], m[1], m[4], m[7], m[10], m[2], m[5], m[8], m[11], 0, 0, 0, 1) sh.Placement = FreeCAD.Placement(mat) # if DEBUG: print "getting Shape from ",obj #print "getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull() #for v in sh.Vertexes: print v.Point return sh
def read_in_step_file_and_save_as_seperate_step_files(file, write_folder=''): if file.endswith(".step") or file.endswith(".stp"): print('reading in ', os.path.join(file)) multipart_step = Part.read(os.path.join(file)) file_counter = 1 for solid in multipart_step.Solids: print(write_folder + '/' + file + str(file_counter)) solid.exportStep( os.path.join( write_folder, os.path.splitext(file)[0] + str(file_counter) + '.stp')) file_counter = file_counter + 1
def STEP2Solid(stepFilenames): if type(stepFilenames) is not list: listIn = False stepFilenames=[stepFilenames] else: listIn=True robjs=[] for stepFilename in stepFilenames: robjs.append(Part.read(stepFilename)) if (len(robjs) is 1) and (listIn is False): return robjs[0] else: return robjs
def import_step_part(doc, path, name): """ Imports part from step file and returns it. :param doc: FreeCAD document. :param path: Path to step file. :param name: A string. :return: FreeCAD document object 'Part::Feature'. """ part = doc.addObject('Part::Feature', name + '_obj') part.Shape = Part.read(path) doc.recompute() return part
def convert(in_file, out_file, lib_dir=None): """Converts to STL via the FreeCAD library.""" import sys import os if not os.path.isfile(in_file): raise IOError("could not find input file: {}".format(in_file)) if os.path.isabs(out_file): out_dir = os.path.dirname(out_file) if not os.path.isdir(out_dir): raise IOError( "output directory does not exist: {}".format(out_dir)) if lib_dir: if os.path.isdir(lib_dir): sys.path.append(lib_dir) else: raise IOError( "FreeCAD lib directory does not exist: {}".format(lib_dir)) try: import FreeCAD except ImportError: if os.name == 'posix': possible_lib_dirs = [ '/usr/lib/freecad/lib', # Linux '/usr/lib64/freecad/lib', # Linux '/Applications/FreeCAD.app/Contents/Frameworks/lib', # OS X ] for lib_dir in possible_lib_dirs: if os.path.isdir(lib_dir): sys.path.append(lib_dir) break else: sys.stderr.write("Cannot find path to FreeCad.so\n") raise elif os.name == 'nt': sys.stderr.write("Cannot find path to FreeCad.pwd\n") raise else: raise NotImplementedError("Unknown OS: {}".format(os.name)) import FreeCAD # no harm in re-importing import Part in_part = Part.read(in_file) in_part.exportStl(out_file)
def doubleclicked(self, index): path = self.dirmodel.filePath(index) FreeCAD.Console.PrintMessage(path+"\n") if path.lower().endswith(".stp") or path.lower().endswith(".step") or path.lower().endswith(".brp") or path.lower().endswith(".brep"): try: Part.show(Part.read(path)) except: sayexc1() elif path.lower().endswith(".fcstd"): FreeCAD.Console.PrintMessage('!'+path+"! merge ...\n") try: FreeCADGui.ActiveDocument.mergeProject(path) except: sayexc1() FreeCAD.Console.PrintMessage(path+" done.\n")
def accept(self): self.recupererDonnees() distancesListe = [] if self.objetDebut: distancesListe.append(self.decalageDebut) if self.plEspaceRestant == 0: distancesListe.append(self.espaceRestant) if self.plEspaceRestant == 1: distancesListe.append(self.ecartementRegulier-self.decalageDebut) if self.plEspaceRestant == 2: distancesListe.append(self.espaceRestant/2-self.decalageDebut) for i in range(self.qteEcartement-2): distancesListe.append(self.ecartementRegulier) if self.objetFin: if self.plEspaceRestant == 0: distancesListe.append(self.ecartementRegulier-self.decalageFin-self.decalageDebut) if self.plEspaceRestant == 1: distancesListe.append(self.espaceRestant-self.decalageFin) if self.plEspaceRestant == 2: distancesListe.append(self.ecartementRegulier) distancesListe.append((self.espaceRestant/2)-self.decalageFin) repartition = Arch.makeAxis(num=len(distancesListe), name="Repartition") repartition.Length = 1000.00 repartition.Distances= distancesListe self.sel = FreeCADGui.Selection.getSelection() if self.sel: edges = DraftGeomUtils.sortEdges(self.sel[0].Shape.Wires[0].Edges) vec1 = edges[0].Vertexes[-1].Point.sub(edges[0].Vertexes[0].Point) point1 = edges[0].Vertexes[0].Point rot = math.degrees(DraftVecUtils.angle(vec1))*-1 repartition.Placement = FreeCAD.Placement(FreeCAD.Vector(point1),FreeCAD.Rotation(FreeCAD.Vector(0.0,0.0,1.0),rot)) FreeCAD.ActiveDocument.recompute() else: repartition.Placement = FreeCAD.Placement(FreeCAD.Vector(0.0,0.0,0.0),FreeCAD.Rotation(FreeCAD.Vector(0.0,0.0,1.0),0)) m = FreeCADGui.getMainWindow() w = m.findChild(QtGui.QDockWidget,"PartsLibrary") if w: if w.isVisible(): index = w.folder_view.selectedIndexes()[0] path = w.dirmodel.filePath(index) if path.lower().endswith(".stp") or path.lower().endswith(".step") or path.lower().endswith(".brep"): objetRepartit = Part.show(Part.read(path)) else: objetRepartit = FreeCADGui.ActiveDocument.mergeProject(path) repartitionStructurel = Arch.makeStructuralSystem([FreeCAD.ActiveDocument.Objects[-1],],[repartition,], name="RepartitionStructurelle") return True
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 try: rshape = Part.read(fileName) r = Shape.cast(rshape) #print "loadStep: " + str(r) #print "Faces=%d" % cadquery.CQ(r).solids().size() return cadquery.CQ(r) except: raise ValueError("STEP File Could not be loaded")
def execute(self, obj): # Load workplane model WorkplaneModelPath = "C:\\repos\\MHTech\\trunk\\SimpleCAM\\VakuumplanXY.step" # Should load from setup sheet workplaneShape = None try: workplaneShape = Part.read(WorkplaneModelPath) except: pass if workplaneShape: workplaneShape.Placement.Base = FreeCAD.Vector(0.0, 0.0, 0.0) workplaneShape.Placement.Rotation = FreeCAD.Rotation(0.0, 0.0, 0.0) # Set fixture object shape if workplaneShape: obj.Shape = workplaneShape obj.Placement = workplaneShape.Placement
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 try: rshape = Part.read(fileName) #Make sure that we extract all the solids solids = [] for solid in rshape.Solids: solids.append(Shape.cast(solid)) return cadquery.Workplane("XY").newObject(solids) except: raise ValueError("STEP File Could not be loaded")
def getShape(obj): "gets a shape from an IfcOpenShell object" #print "retrieving shape from obj ",obj.id import Part sh=Part.Shape() try: if MAKETEMPFILES: import tempfile tf = tempfile.mkstemp(suffix=".brp")[1] of = pyopen(tf,"wb") of.write(obj.mesh.brep_data) of.close() sh = Part.read(tf) os.remove(tf) else: sh.importBrepFromString(obj.mesh.brep_data) #sh = Part.makeBox(2,2,2) except: print "Error: malformed shape" return None if not sh.Solids: # try to extract a solid shape if sh.Faces: try: if DEBUG: print "Malformed solid. Attempting to fix..." shell = Part.makeShell(sh.Faces) if shell: solid = Part.makeSolid(shell) if solid: sh = solid except: if DEBUG: print "failed to retrieve solid from object ",obj.id else: if DEBUG: print "object ", obj.id, " doesn't contain any face" m = obj.matrix mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9], m[1], m[4], m[7], m[10], m[2], m[5], m[8], m[11], 0, 0, 0, 1) sh.Placement = FreeCAD.Placement(mat) # if DEBUG: print "getting Shape from ",obj #print "getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull() #for v in sh.Vertexes: print v.Point return sh
def find_facets(file): multipart_step = Part.read(os.path.join(file)) solid_mesh = MeshPart.meshFromShape(multipart_step, LinearDeflection=1) print(type(solid_mesh)) for f in solid_mesh.Facets: print(f) print('') print(f.Points) print('') print(f.PointIndices) print('') print('') print(len(solid_mesh.Facets)) print('hi')
def read_in_step_files_and_save_as_single_step(read_folder, write_folder, prefix_required): try: os.mkdir(write_folder) except: print('error making folder') list_of_all_solids = [] for file in os.listdir(read_folder): if file.endswith(".step") or file.endswith(".stp"): if file.startswith(prefix_required): #print('reading in ' ,os.path.join(read_folder, file)) multipart_step = Part.read(os.path.join(read_folder, file)) if type(multipart_step.Solids) == list: list_of_all_solids = list_of_all_solids + multipart_step.Solids else: list_of_all_solids.append(multipart_step.Solids) Part.makeCompound(list_of_all_solids).exportStep( os.path.join(write_folder, 'grouped_' + prefix_required + '.step'))
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 try: rshape = Part.read(fileName) # Extract all solids and surfaces geometry = [] for solid in rshape.Solids: geometry.append(Shape.cast(solid)) for shell in rshape.Shells: geometry.append(Shape.cast(shell)) return cadquery.Workplane("XY").newObject(geometry) except: raise ValueError("STEP File Could not be loaded")
def save_components_as_stl(dictionary_of_parts, output_folder): try: os.makedirs(output_folder) except: pass for component in dictionary_of_parts: filename_list = [] file = dictionary_of_parts[component]['step_filename'] multipart_step = Part.read(file) #path =os.path.join(output_folder, os.path.splitext(file)[0] + '_' + str(file_counter) + '.stl') file_counter = 1 for solid in multipart_step.Solids: solid_mesh = MeshPart.meshFromShape(solid, LinearDeflection=0.01) stl_filename = os.path.join( output_folder, os.path.splitext(os.path.split(file)[1])[0] + '_' + str(file_counter) + '.stl') filename_list.append(stl_filename) solid_mesh.write(stl_filename) file_counter = file_counter + 1 if len(multipart_step.Solids) == 0: singlepart_step = multipart_step solid_mesh = MeshPart.meshFromShape(singlepart_step, LinearDeflection=0.01) stl_filename = os.path.join( output_folder, os.path.splitext(os.path.split(file)[1])[0] + '_' + str(file_counter) + '.stl') filename_list.append(stl_filename) solid_mesh.write(stl_filename) file_counter = file_counter + 1 dictionary_of_parts[component]['stl_filename'] = filename_list return dictionary_of_parts
def HCPB_detailed_module(blanket_parameters_dict): #loads in parameters envelope_directory_filename = blanket_parameters_dict['envelope_filename'] output_folder = blanket_parameters_dict['output_folder'] if 'output_files' in blanket_parameters_dict.keys(): output_files = blanket_parameters_dict['output_files'] else: output_files=['step','stl','h5m','merged_stl'] output_folder_step = output_folder + '/step' output_folder_stl = output_folder + '/stl' output_folder_h5m = output_folder + '/h5m' output_folder_merged_stl = output_folder + '/merged_stl' armour_thickness = blanket_parameters_dict['armour_thickness'] first_wall_thickness = blanket_parameters_dict['first_wall_thickness'] end_cap_thickness = blanket_parameters_dict['end_cap_thickness'] back_walls_thicknesses = blanket_parameters_dict['back_walls_thicknesses'] if 'plasma_filename' in blanket_parameters_dict: plasma_filename = blanket_parameters_dict['plasma_filename'] plasma = Part.read(plasma_filename) else: plasma = Part.makeTorus(9100, 2900) envelope = read_in_envelope_file(envelope_directory_filename) envelope_back_face = find_envelope_back_face(envelope, plasma) envelope_front_face = find_envelope_front_face(envelope, envelope_back_face) front_face_midpoint = find_front_face_midpoint(envelope_front_face) original_envelope_front_face_id = envelope_front_face_id(envelope,envelope_back_face) envelope_back_face_id = find_envelope_back_face_id(envelope, plasma) front_face_polodial_edges_to_fillet = find_front_face_polodial_edges_to_fillet(envelope_front_face.Edges) front_face_torodial_edges_to_fillet = find_front_face_torodial_edges_to_fillet(envelope_front_face.Edges) first_wall_poloidal_fillet_radius = blanket_parameters_dict['first_wall_poloidal_fillet_radius'] filleted_envelope_solid = filleted_envelope(fillet_radius=first_wall_poloidal_fillet_radius, edges=front_face_polodial_edges_to_fillet, envelope=envelope) filleted_envelope_back_face = find_envelope_back_face(filleted_envelope_solid, plasma) filleted_envelope_front_face = find_envelope_front_face(filleted_envelope_solid,filleted_envelope_back_face) filleted_envelope_front_face_id = envelope_front_face_id(wedge=filleted_envelope_solid, envelope_back_face=filleted_envelope_back_face) end_cap_faces = find_end_cap_faces(faces_under_consideration=filleted_envelope_solid.Faces) first_wall_armour, envelope_removed_armour = chop_off_first_wall_armour(armour_thickness=armour_thickness, faces_not_in_first_wall=[filleted_envelope_back_face] +end_cap_faces, filleted_envelope=filleted_envelope_solid, front_face=envelope_front_face) dictionary_of_parts = collections.defaultdict(dict) dictionary_of_parts['armour']['part'] = [first_wall_armour] envelope_removed_armour_end_cap_faces = find_end_cap_faces(faces_under_consideration=envelope_removed_armour.Faces) armour_removed_envelope_back_face = find_envelope_back_face(envelope_removed_armour, plasma) armour_removed_envelope_front_face = find_envelope_front_face(envelope_removed_armour, armour_removed_envelope_back_face) first_wall, first_wall_removed_envelope = chop_off_first_wall(faces_not_in_first_wall=[armour_removed_envelope_back_face] + envelope_removed_armour_end_cap_faces, thickness=first_wall_thickness, filleted_envelope= envelope_removed_armour) dictionary_of_parts['first_wall_homogenised']['part'] = [first_wall] first_wall_removed_envelope_back_face = find_envelope_back_face(first_wall_removed_envelope, plasma) first_wall_removed_envelope_front_face = find_envelope_front_face(first_wall_removed_envelope,first_wall_removed_envelope_back_face) first_wall_removed_envelope_midpoint = find_front_face_midpoint(first_wall_removed_envelope_front_face) if 'cooling_channel_offset_from_first_wall' in blanket_parameters_dict and 'first_wall_channel_radial_mm' in blanket_parameters_dict and 'first_wall_channel_poloidal_segmentations' in blanket_parameters_dict: cooling_channel_offset_from_first_wall = blanket_parameters_dict['cooling_channel_offset_from_first_wall'] first_wall_channel_radial_mm = blanket_parameters_dict['first_wall_channel_radial_mm'] first_wall_front_layer, first_wall_removed_envelope_temp1 = chop_off_first_wall(faces_not_in_first_wall=[armour_removed_envelope_back_face] + envelope_removed_armour_end_cap_faces, thickness=cooling_channel_offset_from_first_wall, filleted_envelope=envelope_removed_armour) first_wall_back_layer, first_wall_removed_envelope_temp2 = chop_off_first_wall(faces_not_in_first_wall=[armour_removed_envelope_back_face] + envelope_removed_armour_end_cap_faces, thickness=first_wall_channel_radial_mm + cooling_channel_offset_from_first_wall, filleted_envelope=envelope_removed_armour) first_wall_middle_layer = first_wall.common(first_wall_back_layer).cut(first_wall_front_layer) first_wall_back_layer = first_wall.cut(first_wall_back_layer) dictionary_of_parts['first_wall_material']['part'] = [first_wall_front_layer, first_wall_back_layer] first_wall_poloidally_segmented = chop_up_poloidally(midpoint=first_wall_removed_envelope_midpoint, poloidal_segmentations=blanket_parameters_dict['first_wall_channel_poloidal_segmentations'], envelope=first_wall_middle_layer, method='first_wall', top_bottom_edges=front_face_torodial_edges_to_fillet, front_face=envelope_front_face) for i, key in enumerate(blanket_parameters_dict['first_wall_channel_poloidal_segmentations']): dictionary_of_parts[key]['part'] = first_wall_poloidally_segmented[i] dictionary_of_parts['first_wall_material']['part'] = dictionary_of_parts['first_wall_material']['part'] \ + [first_wall_front_layer, first_wall_back_layer] end_caps, envelope_removed_endcaps = chop_of_end_caps(end_cap_faces,end_cap_thickness,first_wall_removed_envelope) dictionary_of_parts['end_caps_homogenised']['part'] = end_caps back_face_envelope_removed_caps = find_envelope_back_face(envelope_removed_endcaps, plasma) back_walls, envelope_removed_back_wall = chop_off_back_walls(back_face=back_face_envelope_removed_caps, remaining_shapes=envelope_removed_endcaps, back_walls_thicknesses=back_walls_thicknesses) for i, key in enumerate(blanket_parameters_dict['back_walls_thicknesses']): dictionary_of_parts[key]['part'] = [back_walls[i]] poloidal_segmentations = blanket_parameters_dict['poloidal_segmentations'] envelope_poloidally_segmented = chop_up_poloidally(midpoint=first_wall_removed_envelope_midpoint, poloidal_segmentations=poloidal_segmentations, envelope=envelope_removed_back_wall, method='HCPB',top_bottom_edges=front_face_torodial_edges_to_fillet, front_face=envelope_front_face) neutron_multiplier = envelope_poloidally_segmented[0] cooling_plate = envelope_poloidally_segmented[1] + envelope_poloidally_segmented[3] breeder_material = envelope_poloidally_segmented[2] for i, key in enumerate(blanket_parameters_dict['poloidal_segmentations']): dictionary_of_parts[key]['part'] = envelope_poloidally_segmented[i] cylinder_slice = make_cylinder_slice(10) prefix='_' + os.path.splitext(os.path.split(envelope_directory_filename)[-1])[0] dictionary_of_parts= save_components_as_step(dictionary_of_parts = dictionary_of_parts, output_folder = output_folder_step, filename_prefix =prefix) if 'step' in output_files: save_components_as_step(dictionary_of_parts = dictionary_of_parts, output_folder = output_folder_step, filename_prefix =prefix) if 'merged_stl' in output_files: save_components_as_merged_stl_file(dictionary_of_parts=dictionary_of_parts, output_folder=output_folder_merged_stl, blanket_type=blanket_parameters_dict['blanket_type']) if 'stl' in output_files: save_components_as_stl(dictionary_of_parts = dictionary_of_parts, output_folder = output_folder_stl) if 'h5m' in output_files: save_components_as_h5m_file(dictionary_of_parts = dictionary_of_parts, output_folder = output_folder_h5m, blanket_type=blanket_parameters_dict['blanket_type']) return dictionary_of_parts
#! /usr/bin/env freecadcmd import Part import sys required_args = 3 if len(sys.argv) == required_args + 1: in_path = sys.argv[2] out_path = sys.argv[3] else: print sys.argv print "{} {} /path/to/input /path/to/output".format(sys.argv[0], sys.argv[1]) sys.exit(1) in_part = Part.read(in_path) in_part.exportStl(out_path)
def getShape(obj,objid): "gets a shape from an IfcOpenShell object" #print "retrieving shape from obj ",objid import Part sh=Part.Shape() brep_data = None if IFCOPENSHELL5: try: if SEPARATE_OPENINGS and hasattr(IfcImport,"DISABLE_OPENING_SUBTRACTIONS"): if SEPARATE_PLACEMENTS and hasattr(IfcImport,"DISABLE_OBJECT_PLACEMENT"): brep_data = IfcImport.create_shape(obj,IfcImport.DISABLE_OPENING_SUBTRACTIONS | IfcImport.DISABLE_OBJECT_PLACEMENT) else: brep_data = IfcImport.create_shape(obj,IfcImport.DISABLE_OPENING_SUBTRACTIONS) else: if SEPARATE_PLACEMENTS and hasattr(IfcImport,"DISABLE_OBJECT_PLACEMENT"): brep_data = IfcImport.create_shape(obj,IfcImport.DISABLE_OBJECT_PLACEMENT) else: brep_data = IfcImport.create_shape(obj) except: print "Unable to retrieve shape data" else: brep_data = obj.mesh.brep_data if brep_data: try: if MAKETEMPFILES: import tempfile tf = tempfile.mkstemp(suffix=".brp")[1] of = pyopen(tf,"wb") of.write(brep_data) of.close() sh = Part.read(tf) os.remove(tf) else: sh.importBrepFromString(brep_data) except: print " error: malformed shape" return None else: if IFCOPENSHELL5 and SEPARATE_PLACEMENTS: p = getPlacement(getAttr(obj,"ObjectPlacement")) if p: sh.Placement = p if not sh.Solids: # try to extract a solid shape if sh.Faces: try: if DEBUG: print " malformed solid. Attempting to fix..." shell = Part.makeShell(sh.Faces) if shell: solid = Part.makeSolid(shell) if solid: sh = solid except: if DEBUG: print " failed to retrieve solid from object ",objid else: if DEBUG: print " object ", objid, " doesn't contain any geometry" if not IFCOPENSHELL5: m = obj.matrix mat = FreeCAD.Matrix(m[0], m[3], m[6], m[9], m[1], m[4], m[7], m[10], m[2], m[5], m[8], m[11], 0, 0, 0, 1) sh.Placement = FreeCAD.Placement(mat) # if DEBUG: print "getting Shape from ",obj #print "getting shape: ",sh,sh.Solids,sh.Volume,sh.isValid(),sh.isNull() #for v in sh.Vertexes: print v.Point return sh
def addPart(self, newPart, koloroweElemnty=True, adjustParts=False, groupParts=True, partMinX=0, partMinY=0, partMinZ=0): doc = FreeCAD.activeDocument() gruboscPlytki = getPCBheight()[1] result = ['OK'] #grp = doc.addObject("App::DocumentObjectGroup", "Parts") # basic data partNameTXT = partNameTXT_label = self.generateNewLabel(newPart[0][0]) if isinstance(partNameTXT, unicode): partNameTXT = unicodedata.normalize('NFKD', partNameTXT).encode('ascii', 'ignore') # partValueTXT = newPart[0][2] #if isinstance(partValueTXT, unicode): #partValueTXT = unicodedata.normalize('NFKD', partValueTXT).encode('ascii', 'ignore') partRotation = self.adjustRotation(newPart[0][5]) # rotation around Z # check if 3D model exist ################################################################# ################################################################# fileData = self.partExist(newPart[0][1], "{0} {1} ({2})".format(partNameTXT_label, partValueTXT, newPart[0][1])) if fileData[0]: packageData = self.__SQL__.getValues(fileData[2]) filePath = fileData[1] correctingValue_X = fileData[3][2] # pos_X correctingValue_Y = fileData[3][3] # pos_Y correctingValue_Z = fileData[3][4] # pos_Z correctingValue_RX = fileData[3][5] # pos_RX correctingValue_RY = fileData[3][6] # pos_RY correctingValue_RZ = fileData[3][7] # pos_RZ ################################################################ # DODANIE OBIEKTU NA PLANSZE ################################################################ step_model = doc.addObject("Part::FeaturePython", "{0} ({1})".format(partNameTXT, fileData[3][0])) step_model.Label = partNameTXT_label if not koloroweElemnty: step_model.Shape = Part.read(filePath) else: active = FreeCAD.ActiveDocument.Name step_model = self.getPartShape(filePath, step_model, koloroweElemnty) FreeCAD.setActiveDocument(active) FreeCAD.ActiveDocument=FreeCAD.getDocument(active) FreeCADGui.ActiveDocument=FreeCADGui.getDocument(active) obj = partObject(step_model) step_model.Package = u"{0}".format(fileData[3][0]) step_model.Side = "{0}".format(newPart[0][6]) ################################################################ # PUTTING OBJECT IN CORRECT POSITION/ORIENTATION ################################################################ # rotate object according to (RX, RY, RZ) set by user sX = step_model.Shape.BoundBox.Center.x * (-1) + step_model.Placement.Base.x sY = step_model.Shape.BoundBox.Center.y * (-1) + step_model.Placement.Base.y sZ = step_model.Shape.BoundBox.Center.z * (-1) + step_model.Placement.Base.z + gruboscPlytki / 2. rotateX = correctingValue_RX rotateY = correctingValue_RY rotateZ = correctingValue_RZ pla = FreeCAD.Placement(step_model.Placement.Base, FreeCAD.Rotation(rotateX, rotateY, rotateZ), FreeCAD.Base.Vector(sX, sY, sZ)) step_model.Placement = pla ## placement object to 0, 0, PCB_size / 2. (X, Y, Z) sX = step_model.Shape.BoundBox.Center.x * (-1) + step_model.Placement.Base.x sY = step_model.Shape.BoundBox.Center.y * (-1) + step_model.Placement.Base.y sZ = step_model.Shape.BoundBox.Center.z * (-1) + step_model.Placement.Base.z + gruboscPlytki / 2. step_model.Placement.Base.x = sX + correctingValue_X step_model.Placement.Base.y = sY + correctingValue_Y step_model.Placement.Base.z = sZ # move object to correct Z step_model.Placement.Base.z = step_model.Placement.Base.z + (gruboscPlytki - step_model.Shape.BoundBox.Center.z) + correctingValue_Z ################################################################# # FILTERING OBJECTS BY SIZE L/W/H ################################################################# if partMinX != 0: minValue = partMinX if step_model.Side == 'TOP': minValue += gruboscPlytki if step_model.Shape.BoundBox.XLength < minValue: doc.removeObject(step_model.Name) return elif partMinY != 0: minValue = partMinY if step_model.Side == 'TOP': minValue += gruboscPlytki if step_model.Shape.BoundBox.YLength < minValue: doc.removeObject(step_model.Name) return elif partMinZ != 0: minValue = partMinZ if step_model.Side == 'TOP': minValue += gruboscPlytki if step_model.Shape.BoundBox.ZLength < minValue: doc.removeObject(step_model.Name) return ################################################################# # SETTTING OBJECT SIDE ON THE PCB ################################################################# if newPart[0][6] == 'BOTTOM': # ROT Y - MIRROR shape = step_model.Shape.copy() shape.Placement = step_model.Placement shape.rotate((0, 0, gruboscPlytki / 2.), (0.0, 1.0, 0.0), 180) step_model.Placement = shape.Placement # ROT Z - VALUE FROM EAGLE shape = step_model.Shape.copy() shape.Placement = step_model.Placement shape.rotate((0, 0, 0), (0.0, 0.0, 1.0), -partRotation) step_model.Placement = shape.Placement else: # ROT Z - VALUE FROM EAGLE shape = step_model.Shape.copy() shape.Placement = step_model.Placement shape.rotate((0, 0, 0), (0.0, 0.0, 1.0), partRotation) step_model.Placement = shape.Placement ################################################################# # placement object to X, Y set in eagle ################################################################# step_model.Placement.Base.x = step_model.Placement.Base.x + newPart[0][3] step_model.Placement.Base.y = step_model.Placement.Base.y + newPart[0][4] ################################################################# # ################################################################# step_model.X = step_model.Shape.BoundBox.Center.x step_model.Y = step_model.Shape.BoundBox.Center.y step_model.Proxy.oldX = step_model.Shape.BoundBox.Center.x step_model.Proxy.oldY = step_model.Shape.BoundBox.Center.y step_model.Proxy.offsetX = correctingValue_X step_model.Proxy.offsetY = correctingValue_Y step_model.Proxy.oldROT = partRotation step_model.Rot = partRotation step_model.Proxy.update_Z = step_model.Placement.Base.z ################################################################# # DODANIE PODSTAWKI # dodajPodstawke - definicja zachowania dla danego obiektu # 0 - brak podstawki # 1 - dodanie podstawki ################################################################# dodajPodstawke = False if eval(packageData["add_socket"])[0] and self.allSocked == 0 and eval(packageData["add_socket"])[1] != fileData[2]: socketData = self.__SQL__.getValues(eval(packageData["add_socket"])[1]) if eval(socketData["socket"])[0]: dial = QtGui.QMessageBox() dial.setText(u"Add socket to part {0} (Package: {1}, Library: {2})?".format(partNameTXT, newPart[0][1], newPart[0][7])) dial.setWindowTitle("Socket") dial.setIcon(QtGui.QMessageBox.Question) dial.addButton('No', QtGui.QMessageBox.RejectRole) podstawkaTAK = dial.addButton('Yes', QtGui.QMessageBox.YesRole) zawszePodstawki = dial.addButton('Yes for all', QtGui.QMessageBox.YesRole) nigdyPodstawki = dial.addButton('No for all', QtGui.QMessageBox.RejectRole) dial.exec_() if dial.clickedButton() == nigdyPodstawki: self.allSocked = -1 elif dial.clickedButton() == zawszePodstawki: self.allSocked = 1 elif dial.clickedButton() == podstawkaTAK: dodajPodstawke = True else: dodajPodstawke = False # if (dodajPodstawke or self.allSocked == 1) and eval(packageData["add_socket"])[0]: socketData = self.__SQL__.getValues(eval(packageData["add_socket"])[1]) if self.__SQL__.has_section(eval(packageData["add_socket"])[1]): # sprawdzamy czy podana podstawka istnieje step_model.Socket = float(eval(socketData["socket"])[1]) # ustawienie wysokosci podstawki package = eval(socketData["soft"])[0][0] EL_Name = [socketData["name"], newPart[0][3], newPart[0][4], 1.27, newPart[0][5], newPart[0][6], "bottom-left", False, 'None', '', True] EL_Value = ["", newPart[0][3], newPart[0][4], 1.27, newPart[0][5], newPart[0][6], "bottom-left", False, 'None', '', True] PCB_EL = [[socketData["name"], package, "", newPart[0][3], newPart[0][4], newPart[0][5], newPart[0][6], ""], EL_Name, EL_Value] else: PCB_EL = [socketData["name"], socketData["name"], "", ""] self.addPart(PCB_EL, koloroweElemnty, adjustParts, groupParts, partMinX, partMinY, partMinZ) ################################################################## ## part name object ## [txt, x, y, size, rot, side, align, spin, mirror, font] ################################################################## annotationName = createAnnotation() annotationName.defaultName = '{0}_Name'.format(partNameTXT_label) annotationName.mode = 'anno_name' annotationName.Side = newPart[1][5] annotationName.Rot = self.adjustRotation(newPart[1][4]) annotationName.Text = partNameTXT_label annotationName.Spin = newPart[1][7] if adjustParts and "adjust" in packageData.keys() and "Name" in eval(packageData["adjust"]).keys() and eval(str(eval(packageData["adjust"])["Name"][0])): values = eval(packageData["adjust"])["Name"] if step_model.Side == "BOTTOM": x1 = self.odbijWspolrzedne(newPart[0][3] + values[2], step_model.X.Value) annotationName.Mirror = True [xR, yR] = self.obrocPunkt2([x1, newPart[0][4] + values[3]], [step_model.X.Value, step_model.Y.Value], -step_model.Rot.Value) else: annotationName.Mirror = False [xR, yR] = self.obrocPunkt2([newPart[0][3] + values[2], newPart[0][4] + values[3]], [step_model.X.Value, step_model.Y.Value], step_model.Rot.Value) annotationName.X = xR annotationName.Y = yR annotationName.Z = values[4] annotationName.Align = str(values[7]) annotationName.Size = values[5] annotationName.Color = values[6] annotationName.Visibility = eval(values[1]) else: annotationName.X = newPart[1][1] annotationName.Y = newPart[1][2] annotationName.Z = 0 annotationName.Align = newPart[1][6] annotationName.Size = newPart[1][3] annotationName.Mirror = newPart[1][8] annotationName.Color = (1., 1., 1.) annotationName.Visibility = newPart[1][10] annotationName.generate() ################################################################# # part value # [txt, x, y, size, rot, side, align, spin, mirror, font] ################################################################# annotationValue = createAnnotation() annotationValue.defaultName = '{0}_Value'.format(partNameTXT_label) annotationValue.mode = 'anno_value' annotationValue.Side = newPart[2][5] annotationValue.Rot = self.adjustRotation(newPart[2][4]) annotationValue.Text = partValueTXT annotationValue.Spin = newPart[2][7] if adjustParts and "adjust" in packageData.keys() and "Value" in eval(packageData["adjust"]).keys() and eval(str(eval(packageData["adjust"])["Value"][0])): values = eval(packageData["adjust"])["Value"] if step_model.Side == "BOTTOM": x1 = self.odbijWspolrzedne(newPart[0][3] + values[2], step_model.X.Value) annotationValue.Mirror = True [xR, yR] = self.obrocPunkt2([x1, newPart[0][4] + values[3]], [step_model.X.Value, step_model.Y.Value], -step_model.Rot.Value) else: annotationValue.Mirror = False [xR, yR] = self.obrocPunkt2([newPart[0][3] + values[2], newPart[0][4] + values[3]], [step_model.X.Value, step_model.Y.Value], step_model.Rot.Value) annotationValue.X = xR annotationValue.Y = yR annotationValue.Z = values[4] annotationValue.Align = str(values[7]) annotationValue.Size = values[5] annotationValue.Color = values[6] annotationValue.Visibility = eval(values[1]) else: annotationValue.X = newPart[2][1] annotationValue.Y = newPart[2][2] annotationValue.Z = 0 annotationValue.Align = newPart[2][6] annotationValue.Size = newPart[2][3] annotationValue.Mirror = newPart[2][8] annotationValue.Color = (1., 1., 1.) annotationValue.Visibility = newPart[2][10] annotationValue.generate() # step_model.PartName = annotationName.Annotation step_model.PartValue = annotationValue.Annotation ################ viewProviderPartObject(step_model.ViewObject) ################################################################# # KOLORY DLA ELEMENTOW ################################################################# #if koloroweElemnty: #if filePath.upper().endswith('.IGS') or filePath.upper().endswith('IGES'): #step_model = self.getColorFromIGS(filePath, step_model) #elif filePath.upper().endswith('.STP') or filePath.upper().endswith('STEP'): #step_model = self.getColorFromSTP(filePath, step_model) else: ################################################################# # FILTERING OBJECTS BY SIZE L/W/H ################################################################# if partMinX != 0 or partMinY or partMinZ: return ################################################################# ################################################################# ## DODANIE OBIEKTU NA PLANSZE step_model = doc.addObject("Part::FeaturePython", "{0} ({1})".format(partNameTXT, newPart[0][1])) step_model.Label = partNameTXT_label obj = partObject_E(step_model) #step_model.Label = partNameTXT step_model.Package = "{0}".format(newPart[0][1]) #step_model.Value = "{0}".format(i[0][2]) ##### # placement object to X, Y set in eagle step_model.Placement.Base.x = step_model.Placement.Base.x + newPart[0][3] step_model.Placement.Base.y = step_model.Placement.Base.y + newPart[0][4] # move object to correct Z step_model.Placement.Base.z = step_model.Placement.Base.z + gruboscPlytki ##### step_model.Side = "{0}".format(newPart[0][6]) step_model.X = newPart[0][3] step_model.Y = newPart[0][4] step_model.Rot = partRotation step_model.Proxy.update_Z = 0 ###### ###### # part name object # [txt, x, y, size, rot, side, align, spin, mirror, font] annotationName = createAnnotation() annotationName.defaultName = u'{0}_Name'.format(partNameTXT_label) annotationName.mode = 'anno_name' annotationName.X = newPart[1][1] annotationName.Y = newPart[1][2] annotationName.Z = 0 annotationName.Side = newPart[1][5] annotationName.Rot = self.adjustRotation(newPart[1][4]) annotationName.Text = partNameTXT_label annotationName.Align = newPart[1][6] annotationName.Size = newPart[1][3] annotationName.Spin = newPart[1][7] annotationName.Mirror = newPart[1][8] annotationName.Visibility = newPart[1][10] annotationName.Color = (1., 1., 1.) annotationName.generate() # part value # [txt, x, y, size, rot, side, align, spin, mirror, font] annotationValue = createAnnotation() annotationValue.defaultName = u'{0}_Value'.format(partNameTXT_label) annotationValue.mode = 'anno_value' annotationValue.X = newPart[2][1] annotationValue.Y = newPart[2][2] annotationValue.Z = 0 annotationValue.Side = newPart[2][5] annotationValue.Rot = self.adjustRotation(newPart[2][4]) annotationValue.Text = partValueTXT annotationValue.Align = newPart[2][6] annotationValue.Size = newPart[2][3] annotationValue.Spin = newPart[2][7] annotationValue.Mirror = newPart[2][8] annotationValue.Visibility = newPart[2][10] annotationValue.Color = (1., 1., 1.) annotationValue.generate() # step_model.PartName = annotationName.Annotation step_model.PartValue = annotationValue.Annotation ###### ###### viewProviderPartObject_E(step_model.ViewObject) ################################################################# result = ['Error'] ###### result.append(step_model) self.addPartToGroup(groupParts, fileData, step_model) self.updateView() return result
# conv.py FREECAD = 'C:\\Program Files (x86)\\FreeCAD 0.16\\bin' import sys sys.path.append(FREECAD) import FreeCAD import Part file = sys.argv[1] print str(sys.argv) #part = Part.read("C:/Users/Jim/Downloads/545424.STEP") part = Part.read(file) part.exportStl(file + '.stl')