def export(objs, filename): """exporting to file folder""" #sayz(filename) sayz("stpZ version " + ___stpZversion___) ext = os.path.splitext(os.path.basename(filename))[1] fname = os.path.splitext(os.path.basename(filename))[0] basepath = os.path.split(filename)[0] tempdir = tempfile.gettempdir() # get the current temporary directory filepath = os.path.join(basepath, fname) + u'.stp' filepath_base = os.path.join(basepath, fname) namefpath = os.path.join(basepath, fname) outfpath = os.path.join(basepath, fname) + u'.stpZ' outfpath_stp = os.path.join(basepath, fname) + u'.stp' outfpath_base = basepath #outfpath_str = mkz_string(os.path.join(basepath,fname)) outfpath_str = os.path.join(basepath, fname) if os.path.exists(outfpath_stp): sayzw( "File cannot be compressed because a file with the same name exists '" + outfpath_stp + "'") QtGui.QApplication.restoreOverrideCursor() reply = QtGui.QMessageBox.information( None, "info", "File cannot be compressed because\na file with the same name exists\n'" + outfpath_stp + "'") else: ImportGui.export(objs, outfpath_stp) if 0: #os.path.exists(namefpath): sayzw( "File cannot be compressed because a file with the same name exists '" + namefpath + "'") QtGui.QApplication.restoreOverrideCursor() reply = QtGui.QMessageBox.information( None, "info", "File cannot be compressed because\na file with the same name exists\n'" + namefpath + "'") else: with six.builtins.open(outfpath_stp, 'rb') as f_in: file_content = f_in.read() new_f_content = file_content f_in.close() with gz.open(outfpath_str, 'wb') as f_out: f_out.write(new_f_content) f_out.close() if os.path.exists(outfpath): os.remove(outfpath) os.rename(outfpath_str, outfpath) os.remove(outfpath_stp) else: os.rename(outfpath_str, outfpath) os.remove(outfpath_stp)
def generate_mesh(self, amplification_gap=128): FreeCAD.Console.PrintMessage( 'start generate mesh {}\n'.format(amplification_gap)) doc = FreeCAD.newDocument() FreeCAD.setActiveDocument(doc.Name) self.generate_unit_cell(doc, amplification_gap * 1e-3) obj = [] obj.append(doc.getObject('Unit_Cell')) ImportGui.export( obj, u"/localscratch/micromegas/simulation/meshs/normal/{}.step".format( amplification_gap)) FreeCAD.closeDocument(doc.Name) FreeCAD.setActiveDocument("") FreeCAD.Console.PrintMessage( 'end generate mesh {}\n'.format(amplification_gap))
def export(objs,filename): """exporting to file folder""" #sayz(filename) sayz("stpZ version "+___stpZversion___) ext = os.path.splitext(os.path.basename(filename))[1] fname=os.path.splitext(os.path.basename(filename))[0] basepath=os.path.split(filename)[0] tempdir = tempfile.gettempdir() # get the current temporary directory filepath = os.path.join(basepath,fname) + u'.stp' filepath_base = os.path.join(basepath,fname) namefpath = os.path.join(basepath,fname) outfpath = os.path.join(basepath,fname)+u'.stpZ' outfpath_stp = os.path.join(basepath,fname)+u'.stp' outfpath_base = basepath #outfpath_str = mkz_string(os.path.join(basepath,fname)) outfpath_str = os.path.join(basepath,fname) if os.path.exists(outfpath_stp): sayzw("File cannot be compressed because a file with the same name exists '"+ outfpath_stp +"'") QtGui.QApplication.restoreOverrideCursor() reply = QtGui.QMessageBox.information(None,"info", "File cannot be compressed because\na file with the same name exists\n'"+ outfpath_stp + "'") else: ImportGui.export(objs,outfpath_stp) if 0: #os.path.exists(namefpath): sayzw("File cannot be compressed because a file with the same name exists '" + namefpath + "'") QtGui.QApplication.restoreOverrideCursor() reply = QtGui.QMessageBox.information(None,"info", "File cannot be compressed because\na file with the same name exists\n'"+ namefpath+ "'") else: with six.builtins.open(outfpath_stp, 'rb') as f_in: file_content = f_in.read() new_f_content = file_content f_in.close() with gz.open(outfpath_str, 'wb') as f_out: f_out.write(new_f_content) f_out.close() if os.path.exists(outfpath): os.remove(outfpath) os.rename(outfpath_str, outfpath) os.remove(outfpath_stp) else: os.rename(outfpath_str, outfpath) os.remove(outfpath_stp)
def exportSTEP(doc, modelName, dir): ## Export to STEP ## Get cwd ## outdir=os.path.dirname(os.path.realpath(__file__))+dir outdir = dir FreeCAD.Console.PrintMessage('\r\n' + outdir) StepFileName = outdir + '/' + modelName + '.step' objs = [] objs = GetListOfObjects(FreeCAD, doc) import ImportGui FreeCAD.Console.PrintMessage('\r\n' + StepFileName) # FreeCAD.Console.PrintMessage(objs) FreeCAD.Console.PrintMessage('\r\n' + outdir) ImportGui.export(objs, StepFileName) return 0
def exportSTEP(doc,modelName, dir): ## Export to STEP ## Get cwd ## outdir=os.path.dirname(os.path.realpath(__file__))+dir outdir=dir FreeCAD.Console.PrintMessage('\r\n'+outdir) StepFileName=outdir+'/'+modelName+'.step' objs=[] objs=GetListOfObjects(FreeCAD, doc) import ImportGui FreeCAD.Console.PrintMessage('\r\n'+StepFileName) # FreeCAD.Console.PrintMessage(objs) FreeCAD.Console.PrintMessage('\r\n'+outdir) ImportGui.export(objs,StepFileName) return 0
def export(format, parts, exportdir=None, name=None): """ Export components back out to given format in their assembled positions. STEP files can be exported to STL, but not the other way around. This is not in the Part class since it allows for the export of any number of objects. If exportDir is None, the assembly will be exported to one STL. If exportDir is specified, the individual components will be exported to STL. """ exportpath = os.getcwd() export_individual = False if exportdir is not None: export_individual = True exportpath = os.path.join(os.getcwd(), exportdir) if not os.path.isdir(exportpath): os.makedirs(exportpath) else: exportdir = exportpath if format.lower() in ['step', 'stp']: for obj in parts: if obj.isDerivedFrom("Mesh::Feature"): logger.warning('Component {0} is derived from an STL file. '.format(obj.Label) + 'This can not be exported to the STEP format. This component is being skipped.') continue ImportGui.export([obj], os.path.join(exportpath, obj.Label + '.step')) logger.info('Exported {0}.step to {1}.'.format(obj.Label, exportdir)) elif format.lower() in ['stl', 'mix']: if export_individual: for prt in parts: Mesh.export([prt], os.path.join(exportpath, prt.Label + '.stl')) logger.info('Exported {0}.stl to {1}.'.format(prt.Label, exportdir)) else: Mesh.export(parts, os.path.join(exportpath, FreeCAD.ActiveDocument.Name + '.stl')) logger.info('Exported {0}.stl to {1}.'.format(FreeCAD.ActiveDocument.Name, exportdir)) elif format.lower() == 'fc': if name is not None: FreeCAD.ActiveDocument.saveAs(os.path.join(exportpath, name + '.FCStd')) else: FreeCAD.ActiveDocument.saveAs(os.path.join(exportpath, FreeCAD.ActiveDocument.Name + '.FCStd')) else: exitwitherror('Requested to export parts to unsupported file format {0}.'.format(str(format.lower())))
def export(objs, filename): """exporting to file folder""" #sayz(filename) sayz("stpZ version " + ___stpZversion___) ext = os.path.splitext(os.path.basename(filename))[1] fname = os.path.splitext(os.path.basename(filename))[0] basepath = os.path.split(filename)[0] tempdir = tempfile.gettempdir() # get the current temporary directory filepath = os.path.join(basepath, fname) + u'.stp' filepath_base = os.path.join(basepath, fname) namefpath = os.path.join(basepath, fname) outfpath = os.path.join(basepath, fname) + u'.stpZ' outfpathT = os.path.join(tempdir, fname) + u'.stpZ' outfpath_stp = os.path.join(basepath, fname) + u'.stp' outfpathT_stp = os.path.join(tempdir, fname) + u'.stp' outfpath_base = basepath #outfpath_str = mkz_string(os.path.join(basepath,fname)) outfpath_str = os.path.join(basepath, fname) + u'.stp' outfpathT_str = os.path.join(tempdir, fname) + u'.stp' if os.path.exists(outfpathT_stp): os.remove(outfpathT_stp) sayzw("Old temp file with the same name removed '" + outfpathT_stp + "'") ImportGui.export(objs, outfpathT_stp) with builtin.open(outfpathT_stp, 'rb') as f_in: file_content = f_in.read() new_f_content = file_content f_in.close() with gz.open(outfpathT_str, 'wb') as f_out: f_out.write(new_f_content) f_out.close() if os.path.exists(outfpath): shutil.move(outfpathT_str, outfpath) #os.remove(outfpathT_stp) else: shutil.move(outfpathT_str, outfpath)
def exportSTEP(doc,modelName, dir, objectToExport=None): ## Export to STEP ## Get cwd ## outdir=os.path.dirname(os.path.realpath(__file__))+dir outdir=dir FreeCAD.Console.PrintMessage('\r\n'+outdir) StepFileName=outdir+os.sep+modelName+'.step' objs=[] if objectToExport is None: objs=GetListOfObjects(FreeCAD, doc) else: objs.append(objectToExport) import ImportGui FreeCAD.Console.PrintMessage('\r\n'+StepFileName) # FreeCAD.Console.PrintMessage(objs) FreeCAD.Console.PrintMessage('\r\n'+outdir) ImportGui.export(objs,StepFileName) return 0
def exportSTEP(doc, modelName, dir, objectToExport=None): ## Export to STEP ## Get cwd ## outdir=os.path.dirname(os.path.realpath(__file__))+dir outdir = dir FreeCAD.Console.PrintMessage('\r\n' + outdir) StepFileName = outdir + os.sep + modelName + '.step' objs = [] if objectToExport is None: objs = GetListOfObjects(FreeCAD, doc) else: objs.append(objectToExport) import ImportGui FreeCAD.Console.PrintMessage('\r\n' + StepFileName) # FreeCAD.Console.PrintMessage(objs) FreeCAD.Console.PrintMessage('\r\n' + outdir) ImportGui.export(objs, StepFileName) return 0
def gmshmesh(compound, NG2D, name=""): ''' export, mesh compound at gmsh, reimport as .unv (3d to be implemented) ''' if name =="": name="m_"+compound.Label # ImportGui.export([FreeCAD.activeDocument().getObject(compound.Name)], "/tmp/tmpNO2c.step") # command="/usr/bin/gmsh /tmp/tmpNO2c.step -2 -format unv -o /tmp/"+name+".unv -algo "+str(NG2D.gmshalgoname)+" -clmax " +str(NG2D.NGParamSetMaxSize)+" -clmin "+str(NG2D.NGParamSetMinSize)+" -string Geometry.OCCSewFaces=1;" #command="/usr/bin/gmsh /tmp/tmpNO2c.step -2 -format unv -o /tmp/Compound019_Mesh.unv -algo auto -string Geometry.OCCSewFaces=1;" #command="g" # #print command output = subprocess.check_output([command, '-1'], shell=True, stderr=subprocess.STDOUT,) FreeCAD.Console.PrintMessage(output) # Fem.insert("/tmp/"+name+".unv", FreeCAD.ActiveDocument.Name) #Fem.insert("/tmp/Compound019_Mesh.unv", FreeCAD.ActiveDocument.Name) femmesh=FreeCAD.ActiveDocument.Objects[len(FreeCAD.ActiveDocument.Objects)-1] FreeCADGui.ActiveDocument.getObject(femmesh.Name).DisplayMode = "Wireframe" return femmesh
vector = FreeCAD.Vector(0, 0, 70) cylinder_2.translate(vector) cylinder_1 = cylinder_1.cut(cylinder_2) Part.show(cylinder_1) DOC.recompute() __objs__=[] __objs__.append(FreeCAD.getDocument("part_capteur_de_volume").getObject("Shape")) step_file = u"part_capteur_de_volume.step" ImportGui.export(__objs__, step_file) stl_file = u"part_capteur_de_volume.stl" Mesh.export(__objs__, stl_file) del __objs__ setview() # Generate PNG files file = 'part_capteur_de_volume_' # Ombr� Gui.runCommand('Std_DrawStyle',5) i = 1 Gui.activeDocument().activeView().viewIsometric()
def proceed(self): temp_file = tempfile.mkstemp(suffix='.step')[1] selection = FreeCADGui.Selection.getSelection() if not selection: QtGui.QMessageBox.critical( None, "GMSHMesh macro", "An object has to be selected to run gmsh!") return # Export a part in step format ImportGui.export(selection, temp_file) selection_name = selection[0].Name # Mesh temporaly file file_format = self.cmb_format.currentText() temp_mesh_file = os.path.join(tempfile.tempdir, selection_name + '_Mesh.' + file_format) # OPTIONS GMSH: clmax = self.sb_max_element_size.text() clmin = self.sb_min_element_size.text() cmd_line_opt = self.le_cmd_line_opt.text() algo = self.cmb_algorithm.currentText() mesh_order = self.sb_mesh_order.text() if self.cb_optimized.isChecked(): cmd_optimize = ' -optimize' else: cmd_optimize = '' if self.rb_3D.isChecked(): dim = ' -3 ' if self.rb_2D.isChecked(): dim = ' -2 ' if self.rb_1D.isChecked(): dim = ' -1 ' if self.cb_max_elme_size.isChecked(): max_size = ' -clmax ' + clmax else: max_size = '' if self.cb_min_elme_size.isChecked(): min_size = ' -clmin ' + clmin else: min_size = '' if self.cb_mesh_order.isChecked(): order = ' -order ' + mesh_order else: order = '' options = ' -algo ' + algo + max_size + min_size + cmd_optimize + order + cmd_line_opt # RUN GMSH command = gmsh_bin + ' ' + temp_file + dim + '-format ' + file_format + ' -o ' + temp_mesh_file + '' + options FreeCAD.Console.PrintMessage("Running: \"{}\"\n".format(command)) try: output = subprocess.check_output( [command, '-1'], shell=True, stderr=subprocess.STDOUT, ) for line in output.split('\n'): if "Error" in line: FreeCAD.Console.PrintError("{}\n".format(line)) elif "Warning" in line: FreeCAD.Console.PrintWarning("{}\n".format(line)) #FreeCAD.Console.PrintMessage("Output: \"{}\"\n".format(output)) if file_format in ('unv', 'med'): Fem.insert(temp_mesh_file, FreeCAD.ActiveDocument.Name) if file_format == 'stl': Mesh.insert(temp_mesh_file, FreeCAD.ActiveDocument.Name) if file_format == 'msh': out_mesh_file = os.path.join( os.path.dirname(os.path.abspath(__file__)), "geometry.msh") shutil.move(temp_mesh_file, out_mesh_file) FreeCAD.Console.PrintMessage( "Output file written to: {}\n".format(out_mesh_file)) if self.cb_mec_anal.isChecked(): FMesh = App.activeDocument().ActiveObject MechanicalAnalysis.makeMechanicalAnalysis('MechanicalAnalysis') FemGui.setActiveAnalysis(App.activeDocument().ActiveObject) App.activeDocument().ActiveObject.Member = App.activeDocument( ).ActiveObject.Member + [FMesh] if self.rb_1D.isChecked(): FMeshG = Gui.ActiveDocument.ActiveObject FMeshG.DisplayMode = "Elements & Nodes" except: FreeCAD.Console.PrintError( "Unexpected error in GMSHMesh macro: {} {}\n".format( sys.exc_info()[0], sys.exc_info()[1])) finally: try: del temp_file except: pass try: del temp_mesh_file except: pass
exp_objects = [] for obj in FreeCAD.ActiveDocument.Objects: # select all but indivudial Spheres and Sketch if (obj.Name.find("Pin") == -1) and (obj.Name.find("Sketch") == -1): Gui.Selection.addSelection(obj) exp_objects.append(obj) else: FreeCAD.ActiveDocument.removeObject(obj.Name) App.activeDocument().addObject("Part::MultiFuse","Fusion2") App.activeDocument().Fusion2.Shapes = exp_objects App.ActiveDocument.recompute() for obj in exp_objects: FreeCAD.ActiveDocument.removeObject(obj.Name) exp_objects= [] exp_objects.append(FreeCAD.ActiveDocument.getObject("Fusion2")) ImportGui.export(exp_objects,os.path.join(directory, name + '.step')) del exp_objects # Scale to mil before export to VRML for KiCAD use Draft.scale(FreeCAD.ActiveDocument.ActiveObject, FreeCAD.Vector(MMTOMIL, MMTOMIL, MMTOMIL)) FreeCAD.ActiveDocument.removeObject("Fusion2") ### Export as a VRML model exp_objects = [] exp_objects.append(FreeCAD.ActiveDocument.getObject("Scale")) FreeCADGui.export(exp_objects,os.path.join(directory, name + '.wrl')) del exp_objects exit(1)
App.ActiveDocument.recompute() sk2.addConstraint(Sketcher.Constraint("DistanceY", 4, 2, 0, 2, 1.750603)) sk2.setDatum(18, App.Units.Quantity(str(data[10]) + " mm")) App.ActiveDocument.recompute() sk2.addConstraint(Sketcher.Constraint("Coincident", 6, 3, -1, 1)) App.ActiveDocument.recompute() poc = App.activeDocument().addObject("PartDesign::Pocket", "Pocket") poc.Sketch = sk2 poc.Length = data[10] poc.Label = name FreeCADGui.getDocument(App.ActiveDocument.Name).getObject("Pocket").LineColor = (0.0, 0.0, 0.0) FreeCADGui.getDocument(App.ActiveDocument.Name).getObject("Pocket").ShapeColor = (0.31, 0.73, 0.76) Gui.getDocument(App.ActiveDocument.Name).getObject("Sketch").Visibility = False Gui.getDocument(App.ActiveDocument.Name).getObject("Sketch001").Visibility = False Gui.getDocument(App.ActiveDocument.Name).getObject("Revolve").Visibility = False App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") App.ActiveDocument.saveAs(directory + name + ".FCStd") __objs__ = [] __objs__.append(FreeCAD.getDocument(App.ActiveDocument.Name).getObject("Pocket")) ImportGui.export(__objs__, directory + name + ".step") Mesh.export(__objs__, directory + name + ".stl") del __objs__ App.closeDocument(App.ActiveDocument.Name) print "End"
def CreateTantalumCapacitor(L, W, H, F, S, B, X, P, R, T, A, G, E, Tf, maDeg, Lamb, Hamb, newModelName, newModelPathNameExt, newStepPathNameExt, bodyName, pinsName, pin1MarkName): # Constant pi pi = 3.141592654 # Mold angle (in radians) ma = math.radians(maDeg) # Length of body after we subtract off 2 termination sheet metal thicknesses Lb = (L - (2*T)) # Pivot point height (not specified in datasheet--make something up) ppH = (H * 0.45) # Create new document App.newDocument(newModelName) App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) # Create box to model tantalum capacitor body App.ActiveDocument.addObject("Part::Box","Box") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") # Set body size FreeCAD.getDocument(newModelName).getObject("Box").Length = Lb FreeCAD.getDocument(newModelName).getObject("Box").Width = W FreeCAD.getDocument(newModelName).getObject("Box").Height = H FreeCAD.getDocument(newModelName).getObject("Box").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,0,1)) # Center the body at (0,0) FreeCAD.getDocument(newModelName).getObject("Box").Placement = App.Placement(App.Vector(-1*(Lb/2),-1*(W/2),0),App.Rotation(0,0,0,1)) # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box","Box001") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box001").Length = L FreeCAD.getDocument(newModelName).getObject("Box001").Width = L FreeCAD.getDocument(newModelName).getObject("Box001").Height = L FreeCAD.getDocument(newModelName).getObject("Box001").Placement = App.Placement(App.Vector(-1*(Lb/2),(W/2),ppH),App.Rotation(math.sin(ma/2),0,0,math.cos(ma/2))) # Perform 1st cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut") App.activeDocument().Cut.Base = App.activeDocument().Box App.activeDocument().Cut.Tool = App.activeDocument().Box001 Gui.activeDocument().hide('Box') Gui.activeDocument().hide('Box001') App.ActiveDocument.recompute() # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box","Box002") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box002").Length = L FreeCAD.getDocument(newModelName).getObject("Box002").Width = L FreeCAD.getDocument(newModelName).getObject("Box002").Height = L FreeCAD.getDocument(newModelName).getObject("Box002").Placement = App.Placement(App.Vector(-1*(Lb/2),(W/2),ppH),App.Rotation(math.sin(((3*pi)/4)-(ma/2)),0,0,math.cos(((3*pi)/4)-(ma/2)))) # Perform 2nd cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut001") App.activeDocument().Cut001.Base = App.activeDocument().Cut App.activeDocument().Cut001.Tool = App.activeDocument().Box002 Gui.activeDocument().hide('Cut') Gui.activeDocument().hide('Box002') App.ActiveDocument.recompute() ################################################################### # Rotate body to 180 degrees and get ready for next 2 cuts FreeCAD.getDocument(newModelName).getObject("Cut001").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,1,0)) ################################################################### # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box","Box003") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box003").Length = L FreeCAD.getDocument(newModelName).getObject("Box003").Width = L FreeCAD.getDocument(newModelName).getObject("Box003").Height = L FreeCAD.getDocument(newModelName).getObject("Box003").Placement = App.Placement(App.Vector(-1*(Lb/2),(W/2),ppH),App.Rotation(math.sin(ma/2),0,0,math.cos(ma/2))) ## Perform 3rd cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut002") App.activeDocument().Cut002.Base = App.activeDocument().Cut001 App.activeDocument().Cut002.Tool = App.activeDocument().Box003 Gui.activeDocument().hide('Cut001') Gui.activeDocument().hide('Box003') App.ActiveDocument.recompute() # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box","Box004") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box004").Length = L FreeCAD.getDocument(newModelName).getObject("Box004").Width = L FreeCAD.getDocument(newModelName).getObject("Box004").Height = L FreeCAD.getDocument(newModelName).getObject("Box004").Placement = App.Placement(App.Vector(-1*(Lb/2),(W/2),ppH),App.Rotation(math.sin(((3*pi)/4)-(ma/2)),0,0,math.cos(((3*pi)/4)-(ma/2)))) # Perform 4th cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut003") App.activeDocument().Cut003.Base = App.activeDocument().Cut002 App.activeDocument().Cut003.Tool = App.activeDocument().Box004 Gui.activeDocument().hide('Cut002') Gui.activeDocument().hide('Box004') App.ActiveDocument.recompute() ################################################################### # Rotate body to 90 degrees and get ready for next 2 cuts FreeCAD.getDocument(newModelName).getObject("Cut003").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,0.707107,0.707107)) ################################################################### # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box","Box005") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box005").Length = L FreeCAD.getDocument(newModelName).getObject("Box005").Width = L FreeCAD.getDocument(newModelName).getObject("Box005").Height = L FreeCAD.getDocument(newModelName).getObject("Box005").Placement = App.Placement(App.Vector(-1*(W/2),(Lb/2),ppH),App.Rotation(math.sin(ma/2),0,0,math.cos(ma/2))) ## Perform 5th cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut004") App.activeDocument().Cut004.Base = App.activeDocument().Cut003 App.activeDocument().Cut004.Tool = App.activeDocument().Box005 Gui.activeDocument().hide('Cut003') Gui.activeDocument().hide('Box005') App.ActiveDocument.recompute() # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box","Box006") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box006").Length = L FreeCAD.getDocument(newModelName).getObject("Box006").Width = L FreeCAD.getDocument(newModelName).getObject("Box006").Height = L FreeCAD.getDocument(newModelName).getObject("Box006").Placement = App.Placement(App.Vector(-1*(W/2),(Lb/2),ppH),App.Rotation(math.sin(((3*pi)/4)-(ma/2)),0,0,math.cos(((3*pi)/4)-(ma/2)))) # Perform 6th cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut005") App.activeDocument().Cut005.Base = App.activeDocument().Cut004 App.activeDocument().Cut005.Tool = App.activeDocument().Box006 Gui.activeDocument().hide('Cut004') Gui.activeDocument().hide('Box006') App.ActiveDocument.recompute() ################################################################### # Rotate body to 270 degrees and get ready for next 2 cuts FreeCAD.getDocument(newModelName).getObject("Cut005").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,1,0)) ################################################################### # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box","Box007") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box007").Length = L FreeCAD.getDocument(newModelName).getObject("Box007").Width = L FreeCAD.getDocument(newModelName).getObject("Box007").Height = L FreeCAD.getDocument(newModelName).getObject("Box007").Placement = App.Placement(App.Vector(-1*(W/2),(Lb/2),ppH),App.Rotation(math.sin(ma/2),0,0,math.cos(ma/2))) ## Perform 7th cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut006") App.activeDocument().Cut006.Base = App.activeDocument().Cut005 App.activeDocument().Cut006.Tool = App.activeDocument().Box007 Gui.activeDocument().hide('Cut005') Gui.activeDocument().hide('Box007') App.ActiveDocument.recompute() # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box","Box008") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box008").Length = L FreeCAD.getDocument(newModelName).getObject("Box008").Width = L FreeCAD.getDocument(newModelName).getObject("Box008").Height = L FreeCAD.getDocument(newModelName).getObject("Box008").Placement = App.Placement(App.Vector(-1*(W/2),(Lb/2),ppH),App.Rotation(math.sin(((3*pi)/4)-(ma/2)),0,0,math.cos(((3*pi)/4)-(ma/2)))) # Perform 8th cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut007") App.activeDocument().Cut007.Base = App.activeDocument().Cut006 App.activeDocument().Cut007.Tool = App.activeDocument().Box008 Gui.activeDocument().hide('Cut006') Gui.activeDocument().hide('Box008') App.ActiveDocument.recompute() ################################################################### # Prepare to make the bevel cut at the anode end. ################################################################### # The anode bevel needs to start at the cut-away body, not at the rectangular prism prior to all the cuts. # x === offset due to 8 degree mold angle # tan (8deg) = x / (H-ppH) # x = (H-pph) * tan(8deg) x = (H-ppH) * math.tan(ma) # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box","Box009") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box009").Length = L FreeCAD.getDocument(newModelName).getObject("Box009").Width = L FreeCAD.getDocument(newModelName).getObject("Box009").Height = L FreeCAD.getDocument(newModelName).getObject("Box009").Placement = App.Placement(App.Vector(-1*(W/2),((Lb/2)-x-B),H),App.Rotation(-0.382683,0,0,0.92388)) # Perform 9th cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut008") App.activeDocument().Cut008.Base = App.activeDocument().Cut007 App.activeDocument().Cut008.Tool = App.activeDocument().Box009 Gui.activeDocument().hide('Cut007') Gui.activeDocument().hide('Box009') App.ActiveDocument.recompute() ################################################################### # Rotate cap body into final position and prepare to add terminations. ################################################################### # Rotate into final orientation FreeCAD.getDocument(newModelName).getObject("Cut008").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,0.707107,0.707107)) # Create box to use to cut away at underside of body App.ActiveDocument.addObject("Part::Box","Box010") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box010").Length = Lb FreeCAD.getDocument(newModelName).getObject("Box010").Width = W FreeCAD.getDocument(newModelName).getObject("Box010").Height = T FreeCAD.getDocument(newModelName).getObject("Box010").Placement = App.Placement(App.Vector(-1*(Lb/2),-1*(W/2),(-1*T)),App.Rotation(0,0,0,1)) # Create box to use to cut a hole in that box to accommodate the G dimension App.ActiveDocument.addObject("Part::Box","Box011") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box011").Length = G FreeCAD.getDocument(newModelName).getObject("Box011").Width = E FreeCAD.getDocument(newModelName).getObject("Box011").Height = T FreeCAD.getDocument(newModelName).getObject("Box011").Placement = App.Placement(App.Vector(-1*(G/2),-1*(E/2),(-1*T)),App.Rotation(0,0,0,1)) # Make cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut009") App.activeDocument().Cut009.Base = App.activeDocument().Box010 App.activeDocument().Cut009.Tool = App.activeDocument().Box011 Gui.activeDocument().hide('Box010') Gui.activeDocument().hide('Box011') App.ActiveDocument.recompute() # Now that we have a template to use for all the material we need to remove underneath the cap, proceed to do so. # Position template coincident with cap FreeCAD.getDocument(newModelName).getObject("Cut009").Placement = App.Placement(App.Vector(0,0,T),App.Rotation(0,0,0,1)) # Make cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut011") App.activeDocument().Cut011.Base = App.activeDocument().Cut008 App.activeDocument().Cut011.Tool = App.activeDocument().Cut009 Gui.activeDocument().hide('Cut008') Gui.activeDocument().hide('Cut009') App.ActiveDocument.recompute() # Copy this object and call the copy "Body" newTermShape = FreeCAD.getDocument(newModelName).getObject("Cut011").Shape.copy() newTermObj = App.activeDocument().addObject("Part::Feature",bodyName) newTermObj.Shape = newTermShape ################################################################### # Add terminations ################################################################### # Create box to be left side (anode) termination App.ActiveDocument.addObject("Part::Box","Box012") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box012").Length = S FreeCAD.getDocument(newModelName).getObject("Box012").Width = F FreeCAD.getDocument(newModelName).getObject("Box012").Height = T FreeCAD.getDocument(newModelName).getObject("Box012").Placement = App.Placement(App.Vector(-1*(L/2),-1*(F/2),0),App.Rotation(0,0,0,1)) # Create box to be left side (anode) termination App.ActiveDocument.addObject("Part::Box","Box013") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box013").Length = T FreeCAD.getDocument(newModelName).getObject("Box013").Width = F FreeCAD.getDocument(newModelName).getObject("Box013").Height = (ppH-T) FreeCAD.getDocument(newModelName).getObject("Box013").Placement = App.Placement(App.Vector(-1*(L/2),-1*(F/2),T),App.Rotation(0,0,0,1)) # Fuse the two parts of termination together App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::MultiFuse","Fusion") App.activeDocument().Fusion.Shapes = [App.activeDocument().Box013,App.activeDocument().Box012,App.activeDocument().Box012] Gui.activeDocument().Box013.Visibility=False Gui.activeDocument().Box012.Visibility=False Gui.activeDocument().Box012.Visibility=False App.ActiveDocument.recompute() # Fillet the sharp edges of the termination sheet metal App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) Gui.activateWorkbench("PartDesignWorkbench") App.activeDocument().addObject("PartDesign::Fillet","Fillet") App.activeDocument().Fillet.Base = (App.ActiveDocument.Fusion,["Edge1","Edge14"]) Gui.activeDocument().hide("Fusion") Gui.activeDocument().Fusion.Visibility=False Gui.activeDocument().setEdit('Fillet') App.ActiveDocument.Fillet.Radius = Tf App.ActiveDocument.recompute() Gui.activeDocument().resetEdit() # Copy the termination to cathode newTermShape = FreeCAD.getDocument(newModelName).getObject("Fillet").Shape.copy() newTermObj = App.activeDocument().addObject("Part::Feature","Pin2") newTermObj.Shape = newTermShape FreeCAD.getDocument(newModelName).getObject("Pin2").Placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,1,0)) ################################################################### # Cut a notch in anode termination ################################################################### # If P parameter is 0, then no notch to cut if (P == 0) : # Copy fillet object and call the copy "Pin1" newTermShape = FreeCAD.getDocument(newModelName).getObject("Fillet").Shape.copy() newTermObj = App.activeDocument().addObject("Part::Feature","Pin1") newTermObj.Shape = newTermShape else: # Create box to use to cut away at anode termination App.ActiveDocument.addObject("Part::Box","Box014") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box014").Length = T FreeCAD.getDocument(newModelName).getObject("Box014").Width = R FreeCAD.getDocument(newModelName).getObject("Box014").Height = H FreeCAD.getDocument(newModelName).getObject("Box014").Placement = App.Placement(App.Vector(-1*(L/2),-1*(R/2),P),App.Rotation(0,0,0,1)) # Perform cut App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut","Cut010") App.activeDocument().Cut010.Base = App.activeDocument().Fillet App.activeDocument().Cut010.Tool = App.activeDocument().Box014 Gui.activeDocument().hide('Fillet') Gui.activeDocument().hide('Box014') App.ActiveDocument.recompute() # Copy this object and call the copy "Pin1" newTermShape = FreeCAD.getDocument(newModelName).getObject("Cut010").Shape.copy() newTermObj = App.activeDocument().addObject("Part::Feature","Pin1") newTermObj.Shape = newTermShape ################################################################### # Fuse the pins together to minimize the number of objects in the final assembly ################################################################### App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) Gui.activateWorkbench("PartWorkbench") App.activeDocument().addObject("Part::MultiFuse","Fusion001") App.activeDocument().Fusion001.Shapes = [App.activeDocument().Pin1,App.activeDocument().Pin2] App.ActiveDocument.recompute() # Copy this object and call the copy "Pins" newTermShape = FreeCAD.getDocument(newModelName).getObject("Fusion001").Shape.copy() newTermObj = App.activeDocument().addObject("Part::Feature",pinsName) newTermObj.Shape = newTermShape ################################################################### # Add anode marker bar ################################################################### # Create box to be anode marker bar App.ActiveDocument.addObject("Part::Box",pin1MarkName) App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject(pin1MarkName).Length = Lamb FreeCAD.getDocument(newModelName).getObject(pin1MarkName).Width = W-(2*x) FreeCAD.getDocument(newModelName).getObject(pin1MarkName).Height = Hamb FreeCAD.getDocument(newModelName).getObject(pin1MarkName).Placement = App.Placement(App.Vector((-1*(Lb/2))+x+B,((-1*(W/2))+x),H),App.Rotation(0,0,0,1)) ################################################################### # Wrap things up ################################################################### # Kill off various no-longer-needed objects App.getDocument(newModelName).removeObject("Pin1") App.getDocument(newModelName).removeObject("Pin2") App.getDocument(newModelName).removeObject("Cut") App.getDocument(newModelName).removeObject("Cut001") App.getDocument(newModelName).removeObject("Cut002") App.getDocument(newModelName).removeObject("Cut003") App.getDocument(newModelName).removeObject("Cut004") App.getDocument(newModelName).removeObject("Cut005") App.getDocument(newModelName).removeObject("Cut006") App.getDocument(newModelName).removeObject("Cut007") App.getDocument(newModelName).removeObject("Cut008") App.getDocument(newModelName).removeObject("Cut009") App.getDocument(newModelName).removeObject("Cut011") App.getDocument(newModelName).removeObject("Fusion") App.getDocument(newModelName).removeObject("Fusion001") App.getDocument(newModelName).removeObject("Box") App.getDocument(newModelName).removeObject("Box001") App.getDocument(newModelName).removeObject("Box002") App.getDocument(newModelName).removeObject("Box003") App.getDocument(newModelName).removeObject("Box004") App.getDocument(newModelName).removeObject("Box005") App.getDocument(newModelName).removeObject("Box006") App.getDocument(newModelName).removeObject("Box007") App.getDocument(newModelName).removeObject("Box008") App.getDocument(newModelName).removeObject("Box009") App.getDocument(newModelName).removeObject("Box010") App.getDocument(newModelName).removeObject("Box011") App.getDocument(newModelName).removeObject("Box012") App.getDocument(newModelName).removeObject("Box013") App.getDocument(newModelName).removeObject("Fillet") # If P parameter wasn't 0, clean up objects that were created if (P != 0) : App.getDocument(newModelName).removeObject("Box014") App.getDocument(newModelName).removeObject("Cut010") # Set view and zoom in Gui.activeDocument().activeView().viewFront() Gui.SendMsgToActiveView("ViewFit") #Gui.activateWorkbench("DraftWorkbench") # Color body yellow FreeCADGui.getDocument(newModelName).getObject(bodyName).ShapeColor = (0.89,0.96,0.33) # Color pins bright tin FreeCADGui.getDocument(newModelName).getObject(pinsName).ShapeColor = (0.80,0.80,0.75) # Color anode marker rust orange FreeCADGui.getDocument(newModelName).getObject(pin1MarkName).ShapeColor = (0.67,0.42,0.22) # Save to disk in native format App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.getDocument(newModelName).FileName = newModelPathNameExt App.getDocument(newModelName).Label = newModelName Gui.SendMsgToActiveView("Save") App.getDocument(newModelName).save() # Export to STEP App.ActiveDocument=None Gui.ActiveDocument=None App.setActiveDocument(newModelName) App.ActiveDocument=App.getDocument(newModelName) Gui.ActiveDocument=Gui.getDocument(newModelName) App.getDocument(newModelName).save() __objs__=[] __objs__.append(FreeCAD.getDocument(newModelName).getObject(bodyName)) __objs__.append(FreeCAD.getDocument(newModelName).getObject(pinsName)) __objs__.append(FreeCAD.getDocument(newModelName).getObject(pin1MarkName)) import ImportGui ImportGui.export(__objs__,newStepPathNameExt) del __objs__ ## # Close all documents ### App.closeDocument(newModelName) ### App.setActiveDocument("") ### App.ActiveDocument=None ### Gui.ActiveDocument=None return 0
def export(ftype, componentName, componentModel, filename, fuse=False, scale=None): """ Exports given ComponentModel object using FreeCAD. `ftype` : one of "STEP", "VRML", "FREECAD", "X3D" `componentModel` : a ComponentModel instance `filename` : name of the file, extension is important `fuse` : fuse objects together before export (preserves color) `scale` : scales the model with this factor before exporting X3D exporter doesn't support `fuse` parameter. """ objects = componentModel.parts if len(objects) < 1: raise Exception("ComponentModel is empty!") if len(objects) == 1: # can't fuse if there is only 1 object fuse = False # export to X3D or Simple VRML, continue for other exporters (VRML, FREECAD, STEP) if ftype in ["X3D", "S_VRML"]: if fuse: print("%s exporter can't do fuse, ignoring." % ftype) from export_x3d import exportX3D, Mesh from export_vrml import exportVRML meshes = [shapeToMesh(o[0].toFreecad(), o[1], scale) for o in objects] if ftype == "X3D": exportX3D(meshes, filename) else: # S_VRML exportVRML(meshes, filename) return # init FreeCADGui try: import ImportGui except ImportError: FreeCADGui.showMainWindow() FreeCADGui.getMainWindow().hide() # prevent splash of main window import ImportGui # must be after `showMainWindow` # make sure RefineShape=False pg = FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/Mod/Part/Boolean") usersRSOption = pg.GetBool("RefineModel") # will be restored, we promise pg.SetBool("RefineModel", False) # create a FreeCAD document doc = FreeCAD.newDocument() # create objects fcobjects = [ makeFCObject(doc, componentName + "_" + co[2], co[0], co[1]) for co in objects ] if fuse: fuseobj = doc.addObject("Part::MultiFuse", componentName) fuseobj.Shapes = fcobjects doc.recompute() exportObjects = [fuseobj] else: exportObjects = fcobjects if scale: import Draft v = FreeCAD.Vector(scale, scale, scale) vc = FreeCAD.Vector(0, 0, 0) # legacy=False, sometimes fail if scale < 1.0 exportObjects = [ Draft.scale(obj, delta=v, center=vc, legacy=True) for obj in exportObjects ] doc.recompute() if ftype == "STEP": # check filename if not os.path.splitext(filename)[1] in ['.stp', '.step']: raise Exception( "Filename for STEP export must end with '.stp' or '.step'.") ImportGui.export(exportObjects, filename) elif ftype == "VRML": # check filename if not os.path.splitext(filename)[1] in ['.wrl', '.vrml']: raise Exception( "Filename for VRML export must end with '.wrl' or '.vrml'.") # workaround for not exporting unselected objects (v0.16) # http://www.freecadweb.org/tracker/view.php?id=2221 FreeCADGui.Selection.clearSelection() for o in exportObjects: FreeCADGui.Selection.addSelection(o) # deal with points and lines for o in exportObjects: o.ViewObject.DisplayMode = "Shaded" FreeCADGui.export(exportObjects, filename) elif ftype == "FREECAD": for obj in list(doc.Objects): if not (obj in exportObjects): doc.removeObject(obj.Name) doc.saveAs(filename) else: raise Exception("Unknown export file type!") # restore RefineShape option pg.SetBool("RefineModel", usersRSOption)
def proceed(self): temp_file = tempfile.mkstemp(suffix='.step')[1] selection = FreeCADGui.Selection.getSelection() if not selection: QtGui.QMessageBox.critical( None, "SnappyHexMesh macro", "An object has to be selected to run snappy!") return # Export a part in step format ImportGui.export(selection, temp_file) selection_name = selection[0].Name # Mesh temporaly file file_format = self.cmb_format.currentText() temp_mesh_file = tempfile.tempdir + path_sep + selection_name + '_Mesh.' + file_format # OPTIONS snappy: clmax = self.sb_max_element_size.text() clmin = self.sb_min_element_size.text() cmd_line_opt = self.le_cmd_line_opt.text() algo = self.cmb_algorithm.currentText() mesh_order = self.sb_mesh_order.text() if self.cb_optimized.isChecked(): cmd_optimize = ' -optimize' else: cmd_optimize = '' if self.rb_3D.isChecked(): dim = ' -3 ' if self.rb_2D.isChecked(): dim = ' -2 ' if self.rb_1D.isChecked(): dim = ' -1 ' if self.cb_max_elme_size.isChecked(): max_size = ' -clmax ' + clmax else: max_size = '' if self.cb_min_elme_size.isChecked(): min_size = ' -clmin ' + clmin else: min_size = '' if self.cb_mesh_order.isChecked(): order = ' -order ' + mesh_order else: order = '' options = ' -algo ' + algo + max_size + min_size + cmd_optimize + order + cmd_line_opt # RUN Snappy command = snappy_bin + ' ' + temp_file + dim + '-format ' + file_format + ' -o ' + temp_mesh_file + '' + options FreeCAD.Console.PrintMessage("Running: {}".format(command)) try: if system() == "Linux": output = subprocess.check_output( [command, '-1'], shell=True, stderr=subprocess.STDOUT, ) elif system() == "Windows": output = subprocess.check_output( command, shell=True, stderr=subprocess.STDOUT, ) else: output = subprocess.check_output( [command, '-1'], shell=True, stderr=subprocess.STDOUT, ) FreeCAD.Console.PrintMessage(output) if file_format in ('unv', 'med'): Fem.insert(temp_mesh_file, FreeCAD.ActiveDocument.Name) if file_format == 'stl': Mesh.insert(temp_mesh_file, FreeCAD.ActiveDocument.Name) if self.cb_mec_anal.isChecked(): FMesh = App.activeDocument().ActiveObject FemAnalysis.makeFemAnalysis('MechanicalAnalysis') FemGui.setActiveAnalysis(App.activeDocument().ActiveObject) App.activeDocument().ActiveObject.Member = App.activeDocument( ).ActiveObject.Member + [FMesh] if self.rb_1D.isChecked(): FMeshG = Gui.ActiveDocument.ActiveObject FMeshG.DisplayMode = "Elements & Nodes" except: FreeCAD.Console.PrintError( "Unexpected error in snappyHexMesh macro: {}".format( sys.exc_info()[0])) finally: try: del temp_file except: pass try: del temp_mesh_file except: pass
def export(ftype, componentName, componentModel, filename, fuse=False, scale=None): """ Exports given ComponentModel object using FreeCAD. `ftype` : one of "STEP", "VRML", "FREECAD", "X3D" `componentModel` : a ComponentModel instance `filename` : name of the file, extension is important `fuse` : fuse objects together before export (preserves color) `scale` : scales the model with this factor before exporting X3D exporter doesn't support `fuse` parameter. """ objects = componentModel.parts if len(objects) < 1: raise Exception("ComponentModel is empty!") if len(objects) == 1: # can't fuse if there is only 1 object fuse = False # export to X3D or Simple VRML, continue for other exporters (VRML, FREECAD, STEP) if ftype in ["X3D", "S_VRML"]: if fuse: print("%s exporter can't do fuse, ignoring." % ftype) from export_x3d import exportX3D, Mesh from export_vrml import exportVRML meshes = [shapeToMesh(o[0].toFreecad(), o[1], scale) for o in objects] if ftype == "X3D": exportX3D(meshes, filename) else: # S_VRML exportVRML(meshes, filename) return # init FreeCADGui try: import ImportGui except ImportError: FreeCADGui.showMainWindow() FreeCADGui.getMainWindow().hide() # prevent splash of main window import ImportGui # must be after `showMainWindow` # make sure RefineShape=False pg = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Part/Boolean") usersRSOption = pg.GetBool("RefineModel") # will be restored, we promise pg.SetBool("RefineModel", False) # create a FreeCAD document doc = FreeCAD.newDocument() # create objects fcobjects = [makeFCObject(doc, componentName+"_"+co[2], co[0], co[1]) for co in objects] if fuse: fuseobj = doc.addObject("Part::MultiFuse", componentName) fuseobj.Shapes = fcobjects doc.recompute() exportObjects = [fuseobj] else: exportObjects = fcobjects if scale: import Draft v = FreeCAD.Vector(scale, scale, scale) vc = FreeCAD.Vector(0,0,0) # legacy=False, sometimes fail if scale < 1.0 exportObjects = [Draft.scale(obj, delta=v, center=vc, legacy=True) for obj in exportObjects] doc.recompute() if ftype == "STEP": # check filename if not os.path.splitext(filename)[1] in ['.stp', '.step']: raise Exception("Filename for STEP export must end with '.stp' or '.step'.") ImportGui.export(exportObjects, filename) elif ftype == "VRML": # check filename if not os.path.splitext(filename)[1] in ['.wrl', '.vrml']: raise Exception("Filename for VRML export must end with '.wrl' or '.vrml'.") # workaround for not exporting unselected objects (v0.16) # http://www.freecadweb.org/tracker/view.php?id=2221 FreeCADGui.Selection.clearSelection() for o in exportObjects: FreeCADGui.Selection.addSelection(o) # deal with points and lines for o in exportObjects: o.ViewObject.DisplayMode = "Shaded" FreeCADGui.export(exportObjects, filename) elif ftype == "FREECAD": for obj in list(doc.Objects): if not (obj in exportObjects): doc.removeObject(obj.Name) doc.saveAs(filename) else: raise Exception("Unknown export file type!") # restore RefineShape option pg.SetBool("RefineModel", usersRSOption)
def export(variant, overwrite=False, saveFCStd=False, exportDXF=False): partPrefix = variant[:-4] partPostfix = variant[5:] pinCount = int(variant[5:7]) srcName = srcDir+variant+'.stp' if not os.path.isfile(srcName): FreeCAD.Console.PrintMessage('missing ' + variant + '.stp\n') return if not os.path.exists(dstDir): os.makedirs(dstDir) bodyCutName = 'body-' + partPrefix + '#' bodyCut = None try: tmpl = App.getDocument(tmplName) except: tmpl = App.openDocument(tmplName+'.FCStd') for obj in tmpl.Objects: if obj.Label.startswith(bodyCutName): bodyCut = obj break if bodyCut == None: FreeCAD.Console.PrintMessage('missing template for ' + partPrefix + '\n') return FreeCAD.Console.PrintMessage('cehcking ' + variant + '\n') names = [x for x in obj.Label.split('#')] pitch = float(names[2]) dstName = dstDir+names[3]\ .replace('%e',partPrefix)\ .replace('%o',partPostfix)\ .replace('%c','%02d'%pinCount)\ .replace('%p','%.2f'%pitch) if os.path.isfile(dstName+'.stp'): if not overwrite: FreeCAD.Console.PrintMessage(dstName + ' already exists, skip!\n') return FreeCAD.Console.PrintMessage('exporting ' + dstName + '\n') newDoc = App.newDocument(variant+'_'+str(random.randrange(10000,99999))) guiDoc = Gui.getDocument(newDoc.Name) bodyCut = newDoc.copyObject(bodyCut,True) guiDoc.getObject(bodyCut.Name).Visibility = False; ImportGui.insert(srcName,newDoc.Name) objs = newDoc.getObjectsByLabel(bodyName) if not objs: FreeCAD.Console.PrintMessage('missing body for ' + partPrefix + '\n') return part = objs[0] guiDoc.getObject(part.Name).Visibility = False; objs = newDoc.getObjectsByLabel(fpName) if not objs: FreeCAD.Console.PrintMessage('missing footprint for ' + partPrefix + '\n') return footprint = objs[0] placement = bodyCut.Placement bodyCut.Placement = App.Placement() for obj in bodyCut.Shapes: # any better way to id array object? if 'ArrayType' in obj.PropertiesList: # TODO, we assum interval x sets the pitch, add more check later obj.IntervalX.x = pitch obj.NumberX = pinCount obj.Placement.Base.x -= (pinCount-2)*pitch/2 else: for sobj in obj.Shapes: if sobj.TypeId == 'Part::Mirroring': sobj.Source.Placement.Base.x -= (pinCount-2)*pitch/2 newDoc.recompute() colors = [] objs = [] shapes = [] def make_part(obj,isCut): names = [x for x in obj.Label.split('#')] newObj = newDoc.addObject("Part::Feature", names[0]) if isCut: newObj.Shape = part.Shape.cut(obj.Shape).removeSplitter() else: newObj.Shape = part.Shape.common(obj.Shape).removeSplitter() color = names[1] if not color in shaderColors.named_colors: FreeCAD.Console.PrintWarning('unknown color : ' + color + '\n') color = None else: newObj.ViewObject.ShapeColor = shaderColors.named_colors[color].getDiffuseFloat() if not color in colors: colors.append(color) newObj.Placement = placement shapes.append(newObj) objs.append(expVRML.exportObject(freecad_object = newObj, shape_color=color, face_colors=None)) make_part(bodyCut,True) for obj in bodyCut.Shapes: make_part(obj,False) newDoc.recompute() ImportGui.export(shapes,dstName+'.stp') if exportDXF: shapes = [] shapes.append(footprint) importDXF.export(shapes,dstName+'.dxf') scale=1/2.54 colored_meshes = expVRML.getColoredMesh(Gui, objs , scale) expVRML.writeVRMLFile(colored_meshes, dstName+'.wrl', colors) if saveFCStd: newDoc.saveAs(dstName+'.FCStd') App.closeDocument(newDoc.Name)
def export(variant, fuse=False, overwrite=False, saveFCStd=False, exportDXF=False): partPrefix = variant[:-4] partPostfix = variant[5:] pinCount = int(variant[5:7]) srcName = srcDir+variant+'.stp' if not os.path.isfile(srcName): FreeCAD.Console.PrintMessage('missing ' + variant + '.stp\n') return if not os.path.exists(dstDir): os.makedirs(dstDir) bodyCutName = 'body-' + partPrefix + '#' bodyCut = None try: tmpl = App.getDocument(libName) except: tmpl = App.openDocument(tmplDir+libName+'.FCStd') for obj in tmpl.Objects: if obj.Label.startswith(bodyCutName): bodyCut = obj break if bodyCut == None: FreeCAD.Console.PrintMessage('missing template for ' + partPrefix + '\n') return FreeCAD.Console.PrintMessage('cehcking ' + variant + '\n') names = [x for x in obj.Label.split('#')] pitch = float(names[2]) dstName = dstDir+names[3]\ .replace('%e',partPrefix)\ .replace('%o',partPostfix)\ .replace('%c','%02d'%pinCount)\ .replace('%p','%.2f'%pitch) settings = { 'align':'' } if len(names) > 4: for i in range(4,len(names)): if names[i] == '': continue option = [x for x in names[i].split(':')] if not option[0] in settings: FreeCAD.Console.PrintWarning('unknown setting : ' + option[0] + '\n') else: settings[option[0]] = option[1] if os.path.isfile(dstName+'.stp'): if not overwrite: FreeCAD.Console.PrintMessage(dstName + ' already exists, skip!\n') return FreeCAD.Console.PrintMessage('exporting ' + dstName + '\n') newDoc = App.newDocument(variant+'_'+str(random.randrange(10000,99999))) guiDoc = Gui.getDocument(newDoc.Name) bodyCut = newDoc.copyObject(bodyCut,True) FreeCAD.Console.PrintMessage(bodyCut.Name + '\n') guiDoc.getObject(bodyCut.Name).Visibility = False; ImportGui.insert(srcName,newDoc.Name) objs = newDoc.getObjectsByLabel(bodyName) if not objs: FreeCAD.Console.PrintMessage('missing body for ' + partPrefix + '\n') return part = objs[0] guiDoc.getObject(part.Name).Visibility = False; objs = newDoc.getObjectsByLabel(fpName) if not objs: FreeCAD.Console.PrintMessage('missing footprint for ' + partPrefix + '\n') return footprint = objs[0] # NOTE!!! If we don't use Placement.copy here, we will be getting a surprise # from FreeCAD. Even if we reset the bodyCut.Placement below, whenever we change # the non-copied placement, bodyCut.Placement will get an update, too! Spooky!! # There seems to be some dangling internal reference bug here. placement = bodyCut.Placement.copy() bodyCut.Placement = App.Placement() offset = (pinCount-2)*pitch/2 if settings['align'] == 'pin': placement.Base.x += offset footprint.Placement = placement.copy() for obj in bodyCut.Shapes: # any better way to id array object? if 'ArrayType' in obj.PropertiesList: # TODO, we assum interval x sets the pitch, add more check later obj.IntervalX.x = pitch obj.NumberX = pinCount obj.Placement.Base.x -= offset else: for sobj in obj.Shapes: if sobj.TypeId == 'Part::Mirroring': sobj.Source.Placement.Base.x -= offset newDoc.recompute() colors = [] objs = [] shapes = [] def make_part(obj,isCut): names = [x for x in obj.Label.split('#')] newObj = newDoc.addObject("Part::Feature", names[0]) if isCut: newObj.Shape = part.Shape.cut(obj.Shape).removeSplitter() else: newObj.Shape = part.Shape.common(obj.Shape).removeSplitter() color = names[1] if not color in shaderColors.named_colors: FreeCAD.Console.PrintWarning('unknown color : ' + color + '\n') color = None else: newObj.ViewObject.ShapeColor = shaderColors.named_colors[color].getDiffuseFloat() if not color in colors: colors.append(color) newObj.Placement = placement.copy() shapes.append(newObj) objs.append(expVRML.exportObject(freecad_object = newObj, shape_color=color, face_colors=None)) make_part(bodyCut,True) for obj in bodyCut.Shapes: make_part(obj,False) if fuse: newObj = newDoc.addObject("Part::MultiFuse", 'part') newObj.Shapes = shapes shapes = [newObj] newDoc.recompute() ImportGui.export(shapes,dstName+'.stp') if exportDXF: shapes = [] shapes.append(footprint) importDXF.export(shapes,dstName+'.dxf') scale=1/2.54 colored_meshes = expVRML.getColoredMesh(Gui, objs , scale) expVRML.writeVRMLFile(colored_meshes, dstName+'.wrl', colors) if saveFCStd: newDoc.saveAs(dstName+'.FCStd') App.closeDocument(newDoc.Name)
def proceed(self): temp_file = tempfile.mkstemp(suffix='.step')[1] selection = FreeCADGui.Selection.getSelection() if not selection: QtGui.QMessageBox.critical(None, "GMSHMesh macro", "An object has to be selected to run gmsh!") return # Export a part in step format ImportGui.export(selection, temp_file) selection_name = selection[0].Name # Mesh temporaly file file_format = self.cmb_format.currentText() temp_mesh_file = os.path.join(tempfile.tempdir, selection_name + '_Mesh.' + file_format) # OPTIONS GMSH: clmax = self.sb_max_element_size.text() clmin = self.sb_min_element_size.text() cmd_line_opt = self.le_cmd_line_opt.text() algo = self.cmb_algorithm.currentText() mesh_order = self.sb_mesh_order.text() if self.cb_optimized.isChecked(): cmd_optimize = ' -optimize' else: cmd_optimize = '' if self.rb_3D.isChecked(): dim = ' -3 ' if self.rb_2D.isChecked(): dim = ' -2 ' if self.rb_1D.isChecked(): dim = ' -1 ' if self.cb_max_elme_size.isChecked(): max_size = ' -clmax ' + clmax else: max_size = '' if self.cb_min_elme_size.isChecked(): min_size = ' -clmin ' + clmin else: min_size = '' if self.cb_mesh_order.isChecked(): order = ' -order ' + mesh_order else: order = '' options = ' -algo ' + algo + max_size + min_size + cmd_optimize + order + cmd_line_opt # RUN GMSH command = gmsh_bin + ' ' + temp_file + dim + '-format ' + file_format + ' -o ' + temp_mesh_file + '' + options FreeCAD.Console.PrintMessage("Running: \"{}\"\n".format(command)) try: output = subprocess.check_output([command, '-1'], shell=True, stderr=subprocess.STDOUT,) for line in output.split('\n'): if "Error" in line: FreeCAD.Console.PrintError("{}\n".format(line)) elif "Warning" in line: FreeCAD.Console.PrintWarning("{}\n".format(line)) #FreeCAD.Console.PrintMessage("Output: \"{}\"\n".format(output)) if file_format in ('unv', 'med'): Fem.insert(temp_mesh_file, FreeCAD.ActiveDocument.Name) if file_format == 'stl': Mesh.insert(temp_mesh_file, FreeCAD.ActiveDocument.Name) if file_format == 'msh': out_mesh_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "geometry.msh") shutil.move(temp_mesh_file, out_mesh_file) FreeCAD.Console.PrintMessage("Output file written to: {}\n".format(out_mesh_file)) if self.cb_mec_anal.isChecked(): FMesh = App.activeDocument().ActiveObject MechanicalAnalysis.makeMechanicalAnalysis('MechanicalAnalysis') FemGui.setActiveAnalysis(App.activeDocument().ActiveObject) App.activeDocument().ActiveObject.Member = App.activeDocument().ActiveObject.Member + [FMesh] if self.rb_1D.isChecked(): FMeshG = Gui.ActiveDocument.ActiveObject FMeshG.DisplayMode = "Elements & Nodes" except: FreeCAD.Console.PrintError("Unexpected error in GMSHMesh macro: {} {}\n".format(sys.exc_info()[0], sys.exc_info()[1])) finally: try: del temp_file except: pass try: del temp_mesh_file except: pass
## Export as a step model exp_objects = [] for obj in FreeCAD.ActiveDocument.Objects: # select all but indivudial Spheres and Sketch if (obj.Name.find("Sphere") == -1) and (obj.Name.find("Sketch") == -1): Gui.Selection.addSelection(obj) exp_objects.append(obj) else: FreeCAD.ActiveDocument.removeObject(obj.Name) App.activeDocument().addObject("Part::MultiFuse","Fusion2") App.activeDocument().Fusion2.Shapes = exp_objects App.ActiveDocument.recompute() for obj in exp_objects: FreeCAD.ActiveDocument.removeObject(obj.Name) exp_objects= [] exp_objects.append(FreeCAD.ActiveDocument.getObject("Fusion2")) ImportGui.export(exp_objects,os.path.join(directory, name + '.step')) del exp_objects # Scale to mil before export to VRML for KiCAD use Draft.scale(FreeCAD.ActiveDocument.ActiveObject, FreeCAD.Vector(MMTOMIL,MMTOMIL,MMTOMIL)) FreeCAD.ActiveDocument.removeObject("Fusion2") ### Export as a VRML model exp_objects = [] exp_objects.append(FreeCAD.ActiveDocument.getObject("Scale")) FreeCADGui.export(exp_objects,os.path.join(directory, name + '.wrl')) del exp_objects exit(1)
print("----------------------") myObj = objs[1] pl = FreeCAD.Placement() pl.move(FreeCAD.Vector(-2.6, -8, 10)) myObj.Placement = pl cut = App.ActiveDocument.addObject("Part::Cut","Cut") cut.Base = objs[0] cut.Tool = objs[1] App.ActiveDocument.recompute() print("objects after cutting") print("----------------------") objs = FreeCAD.ActiveDocument.Objects for obj in objs: a = obj.Name b = obj.Label try: c = obj.LabelText print(a +" "+ (b) +" "+ (c) + "\n") except: print((a) +" "+ (b) + "\n") print("----------------------") _objs = [] _objs.append(FreeCAD.getDocument(test.Name).getObject("Cut")) ImportGui.export(_objs,"C:\\temp\\testExport.STEP")
def CreateTantalumCapacitor(L, W, H, F, S, B, X, P, R, T, A, G, E, Tf, maDeg, Lamb, Hamb, newModelName, newModelPathNameExt, newStepPathNameExt, bodyName, pinsName, pin1MarkName): # Constant pi pi = 3.141592654 # Mold angle (in radians) ma = math.radians(maDeg) # Length of body after we subtract off 2 termination sheet metal thicknesses Lb = (L - (2 * T)) # Pivot point height (not specified in datasheet--make something up) ppH = (H * 0.45) # Create new document App.newDocument(newModelName) App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) # Create box to model tantalum capacitor body App.ActiveDocument.addObject("Part::Box", "Box") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") # Set body size FreeCAD.getDocument(newModelName).getObject("Box").Length = Lb FreeCAD.getDocument(newModelName).getObject("Box").Width = W FreeCAD.getDocument(newModelName).getObject("Box").Height = H FreeCAD.getDocument(newModelName).getObject( "Box").Placement = App.Placement(App.Vector(0, 0, 0), App.Rotation(0, 0, 0, 1)) # Center the body at (0,0) FreeCAD.getDocument(newModelName).getObject( "Box").Placement = App.Placement( App.Vector(-1 * (Lb / 2), -1 * (W / 2), 0), App.Rotation(0, 0, 0, 1)) # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box", "Box001") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box001").Length = L FreeCAD.getDocument(newModelName).getObject("Box001").Width = L FreeCAD.getDocument(newModelName).getObject("Box001").Height = L FreeCAD.getDocument(newModelName).getObject( "Box001").Placement = App.Placement( App.Vector(-1 * (Lb / 2), (W / 2), ppH), App.Rotation(math.sin(ma / 2), 0, 0, math.cos(ma / 2))) # Perform 1st cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut") App.activeDocument().Cut.Base = App.activeDocument().Box App.activeDocument().Cut.Tool = App.activeDocument().Box001 Gui.activeDocument().hide('Box') Gui.activeDocument().hide('Box001') App.ActiveDocument.recompute() # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box", "Box002") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box002").Length = L FreeCAD.getDocument(newModelName).getObject("Box002").Width = L FreeCAD.getDocument(newModelName).getObject("Box002").Height = L FreeCAD.getDocument(newModelName).getObject( "Box002").Placement = App.Placement( App.Vector(-1 * (Lb / 2), (W / 2), ppH), App.Rotation(math.sin(((3 * pi) / 4) - (ma / 2)), 0, 0, math.cos(((3 * pi) / 4) - (ma / 2)))) # Perform 2nd cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut001") App.activeDocument().Cut001.Base = App.activeDocument().Cut App.activeDocument().Cut001.Tool = App.activeDocument().Box002 Gui.activeDocument().hide('Cut') Gui.activeDocument().hide('Box002') App.ActiveDocument.recompute() ################################################################### # Rotate body to 180 degrees and get ready for next 2 cuts FreeCAD.getDocument(newModelName).getObject( "Cut001").Placement = App.Placement(App.Vector(0, 0, 0), App.Rotation(0, 0, 1, 0)) ################################################################### # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box", "Box003") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box003").Length = L FreeCAD.getDocument(newModelName).getObject("Box003").Width = L FreeCAD.getDocument(newModelName).getObject("Box003").Height = L FreeCAD.getDocument(newModelName).getObject( "Box003").Placement = App.Placement( App.Vector(-1 * (Lb / 2), (W / 2), ppH), App.Rotation(math.sin(ma / 2), 0, 0, math.cos(ma / 2))) ## Perform 3rd cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut002") App.activeDocument().Cut002.Base = App.activeDocument().Cut001 App.activeDocument().Cut002.Tool = App.activeDocument().Box003 Gui.activeDocument().hide('Cut001') Gui.activeDocument().hide('Box003') App.ActiveDocument.recompute() # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box", "Box004") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box004").Length = L FreeCAD.getDocument(newModelName).getObject("Box004").Width = L FreeCAD.getDocument(newModelName).getObject("Box004").Height = L FreeCAD.getDocument(newModelName).getObject( "Box004").Placement = App.Placement( App.Vector(-1 * (Lb / 2), (W / 2), ppH), App.Rotation(math.sin(((3 * pi) / 4) - (ma / 2)), 0, 0, math.cos(((3 * pi) / 4) - (ma / 2)))) # Perform 4th cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut003") App.activeDocument().Cut003.Base = App.activeDocument().Cut002 App.activeDocument().Cut003.Tool = App.activeDocument().Box004 Gui.activeDocument().hide('Cut002') Gui.activeDocument().hide('Box004') App.ActiveDocument.recompute() ################################################################### # Rotate body to 90 degrees and get ready for next 2 cuts FreeCAD.getDocument(newModelName).getObject( "Cut003").Placement = App.Placement( App.Vector(0, 0, 0), App.Rotation(0, 0, 0.707107, 0.707107)) ################################################################### # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box", "Box005") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box005").Length = L FreeCAD.getDocument(newModelName).getObject("Box005").Width = L FreeCAD.getDocument(newModelName).getObject("Box005").Height = L FreeCAD.getDocument(newModelName).getObject( "Box005").Placement = App.Placement( App.Vector(-1 * (W / 2), (Lb / 2), ppH), App.Rotation(math.sin(ma / 2), 0, 0, math.cos(ma / 2))) ## Perform 5th cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut004") App.activeDocument().Cut004.Base = App.activeDocument().Cut003 App.activeDocument().Cut004.Tool = App.activeDocument().Box005 Gui.activeDocument().hide('Cut003') Gui.activeDocument().hide('Box005') App.ActiveDocument.recompute() # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box", "Box006") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box006").Length = L FreeCAD.getDocument(newModelName).getObject("Box006").Width = L FreeCAD.getDocument(newModelName).getObject("Box006").Height = L FreeCAD.getDocument(newModelName).getObject( "Box006").Placement = App.Placement( App.Vector(-1 * (W / 2), (Lb / 2), ppH), App.Rotation(math.sin(((3 * pi) / 4) - (ma / 2)), 0, 0, math.cos(((3 * pi) / 4) - (ma / 2)))) # Perform 6th cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut005") App.activeDocument().Cut005.Base = App.activeDocument().Cut004 App.activeDocument().Cut005.Tool = App.activeDocument().Box006 Gui.activeDocument().hide('Cut004') Gui.activeDocument().hide('Box006') App.ActiveDocument.recompute() ################################################################### # Rotate body to 270 degrees and get ready for next 2 cuts FreeCAD.getDocument(newModelName).getObject( "Cut005").Placement = App.Placement(App.Vector(0, 0, 0), App.Rotation(0, 0, 1, 0)) ################################################################### # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box", "Box007") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box007").Length = L FreeCAD.getDocument(newModelName).getObject("Box007").Width = L FreeCAD.getDocument(newModelName).getObject("Box007").Height = L FreeCAD.getDocument(newModelName).getObject( "Box007").Placement = App.Placement( App.Vector(-1 * (W / 2), (Lb / 2), ppH), App.Rotation(math.sin(ma / 2), 0, 0, math.cos(ma / 2))) ## Perform 7th cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut006") App.activeDocument().Cut006.Base = App.activeDocument().Cut005 App.activeDocument().Cut006.Tool = App.activeDocument().Box007 Gui.activeDocument().hide('Cut005') Gui.activeDocument().hide('Box007') App.ActiveDocument.recompute() # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box", "Box008") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box008").Length = L FreeCAD.getDocument(newModelName).getObject("Box008").Width = L FreeCAD.getDocument(newModelName).getObject("Box008").Height = L FreeCAD.getDocument(newModelName).getObject( "Box008").Placement = App.Placement( App.Vector(-1 * (W / 2), (Lb / 2), ppH), App.Rotation(math.sin(((3 * pi) / 4) - (ma / 2)), 0, 0, math.cos(((3 * pi) / 4) - (ma / 2)))) # Perform 8th cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut007") App.activeDocument().Cut007.Base = App.activeDocument().Cut006 App.activeDocument().Cut007.Tool = App.activeDocument().Box008 Gui.activeDocument().hide('Cut006') Gui.activeDocument().hide('Box008') App.ActiveDocument.recompute() ################################################################### # Prepare to make the bevel cut at the anode end. ################################################################### # The anode bevel needs to start at the cut-away body, not at the rectangular prism prior to all the cuts. # x === offset due to 8 degree mold angle # tan (8deg) = x / (H-ppH) # x = (H-pph) * tan(8deg) x = (H - ppH) * math.tan(ma) # Create box to use to cut away at body App.ActiveDocument.addObject("Part::Box", "Box009") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box009").Length = L FreeCAD.getDocument(newModelName).getObject("Box009").Width = L FreeCAD.getDocument(newModelName).getObject("Box009").Height = L FreeCAD.getDocument(newModelName).getObject( "Box009").Placement = App.Placement( App.Vector(-1 * (W / 2), ((Lb / 2) - x - B), H), App.Rotation(-0.382683, 0, 0, 0.92388)) # Perform 9th cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut008") App.activeDocument().Cut008.Base = App.activeDocument().Cut007 App.activeDocument().Cut008.Tool = App.activeDocument().Box009 Gui.activeDocument().hide('Cut007') Gui.activeDocument().hide('Box009') App.ActiveDocument.recompute() ################################################################### # Rotate cap body into final position and prepare to add terminations. ################################################################### # Rotate into final orientation FreeCAD.getDocument(newModelName).getObject( "Cut008").Placement = App.Placement( App.Vector(0, 0, 0), App.Rotation(0, 0, 0.707107, 0.707107)) # Create box to use to cut away at underside of body App.ActiveDocument.addObject("Part::Box", "Box010") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box010").Length = Lb FreeCAD.getDocument(newModelName).getObject("Box010").Width = W FreeCAD.getDocument(newModelName).getObject("Box010").Height = T FreeCAD.getDocument(newModelName).getObject( "Box010").Placement = App.Placement( App.Vector(-1 * (Lb / 2), -1 * (W / 2), (-1 * T)), App.Rotation(0, 0, 0, 1)) # Create box to use to cut a hole in that box to accommodate the G dimension App.ActiveDocument.addObject("Part::Box", "Box011") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box011").Length = G FreeCAD.getDocument(newModelName).getObject("Box011").Width = E FreeCAD.getDocument(newModelName).getObject("Box011").Height = T FreeCAD.getDocument(newModelName).getObject( "Box011").Placement = App.Placement( App.Vector(-1 * (G / 2), -1 * (E / 2), (-1 * T)), App.Rotation(0, 0, 0, 1)) # Make cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut009") App.activeDocument().Cut009.Base = App.activeDocument().Box010 App.activeDocument().Cut009.Tool = App.activeDocument().Box011 Gui.activeDocument().hide('Box010') Gui.activeDocument().hide('Box011') App.ActiveDocument.recompute() # Now that we have a template to use for all the material we need to remove underneath the cap, proceed to do so. # Position template coincident with cap FreeCAD.getDocument(newModelName).getObject( "Cut009").Placement = App.Placement(App.Vector(0, 0, T), App.Rotation(0, 0, 0, 1)) # Make cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut011") App.activeDocument().Cut011.Base = App.activeDocument().Cut008 App.activeDocument().Cut011.Tool = App.activeDocument().Cut009 Gui.activeDocument().hide('Cut008') Gui.activeDocument().hide('Cut009') App.ActiveDocument.recompute() # Copy this object and call the copy "Body" newTermShape = FreeCAD.getDocument(newModelName).getObject( "Cut011").Shape.copy() newTermObj = App.activeDocument().addObject("Part::Feature", bodyName) newTermObj.Shape = newTermShape ################################################################### # Add terminations ################################################################### # Create box to be left side (anode) termination App.ActiveDocument.addObject("Part::Box", "Box012") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box012").Length = S FreeCAD.getDocument(newModelName).getObject("Box012").Width = F FreeCAD.getDocument(newModelName).getObject("Box012").Height = T FreeCAD.getDocument(newModelName).getObject( "Box012").Placement = App.Placement( App.Vector(-1 * (L / 2), -1 * (F / 2), 0), App.Rotation(0, 0, 0, 1)) # Create box to be left side (anode) termination App.ActiveDocument.addObject("Part::Box", "Box013") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box013").Length = T FreeCAD.getDocument(newModelName).getObject("Box013").Width = F FreeCAD.getDocument(newModelName).getObject("Box013").Height = (ppH - T) FreeCAD.getDocument(newModelName).getObject( "Box013").Placement = App.Placement( App.Vector(-1 * (L / 2), -1 * (F / 2), T), App.Rotation(0, 0, 0, 1)) # Fuse the two parts of termination together App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::MultiFuse", "Fusion") App.activeDocument().Fusion.Shapes = [ App.activeDocument().Box013, App.activeDocument().Box012, App.activeDocument().Box012 ] Gui.activeDocument().Box013.Visibility = False Gui.activeDocument().Box012.Visibility = False Gui.activeDocument().Box012.Visibility = False App.ActiveDocument.recompute() # Fillet the sharp edges of the termination sheet metal App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) Gui.activateWorkbench("PartDesignWorkbench") App.activeDocument().addObject("PartDesign::Fillet", "Fillet") App.activeDocument().Fillet.Base = (App.ActiveDocument.Fusion, ["Edge1", "Edge14"]) Gui.activeDocument().hide("Fusion") Gui.activeDocument().Fusion.Visibility = False Gui.activeDocument().setEdit('Fillet') App.ActiveDocument.Fillet.Radius = Tf App.ActiveDocument.recompute() Gui.activeDocument().resetEdit() # Copy the termination to cathode newTermShape = FreeCAD.getDocument(newModelName).getObject( "Fillet").Shape.copy() newTermObj = App.activeDocument().addObject("Part::Feature", "Pin2") newTermObj.Shape = newTermShape FreeCAD.getDocument(newModelName).getObject( "Pin2").Placement = App.Placement(App.Vector(0, 0, 0), App.Rotation(0, 0, 1, 0)) ################################################################### # Cut a notch in anode termination ################################################################### # If P parameter is 0, then no notch to cut if (P == 0): # Copy fillet object and call the copy "Pin1" newTermShape = FreeCAD.getDocument(newModelName).getObject( "Fillet").Shape.copy() newTermObj = App.activeDocument().addObject("Part::Feature", "Pin1") newTermObj.Shape = newTermShape else: # Create box to use to cut away at anode termination App.ActiveDocument.addObject("Part::Box", "Box014") App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject("Box014").Length = T FreeCAD.getDocument(newModelName).getObject("Box014").Width = R FreeCAD.getDocument(newModelName).getObject("Box014").Height = H FreeCAD.getDocument(newModelName).getObject( "Box014").Placement = App.Placement( App.Vector(-1 * (L / 2), -1 * (R / 2), P), App.Rotation(0, 0, 0, 1)) # Perform cut App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.activeDocument().addObject("Part::Cut", "Cut010") App.activeDocument().Cut010.Base = App.activeDocument().Fillet App.activeDocument().Cut010.Tool = App.activeDocument().Box014 Gui.activeDocument().hide('Fillet') Gui.activeDocument().hide('Box014') App.ActiveDocument.recompute() # Copy this object and call the copy "Pin1" newTermShape = FreeCAD.getDocument(newModelName).getObject( "Cut010").Shape.copy() newTermObj = App.activeDocument().addObject("Part::Feature", "Pin1") newTermObj.Shape = newTermShape ################################################################### # Fuse the pins together to minimize the number of objects in the final assembly ################################################################### App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) Gui.activateWorkbench("PartWorkbench") App.activeDocument().addObject("Part::MultiFuse", "Fusion001") App.activeDocument().Fusion001.Shapes = [ App.activeDocument().Pin1, App.activeDocument().Pin2 ] App.ActiveDocument.recompute() # Copy this object and call the copy "Pins" newTermShape = FreeCAD.getDocument(newModelName).getObject( "Fusion001").Shape.copy() newTermObj = App.activeDocument().addObject("Part::Feature", pinsName) newTermObj.Shape = newTermShape ################################################################### # Add anode marker bar ################################################################### # Create box to be anode marker bar App.ActiveDocument.addObject("Part::Box", pin1MarkName) App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") FreeCAD.getDocument(newModelName).getObject(pin1MarkName).Length = Lamb FreeCAD.getDocument(newModelName).getObject(pin1MarkName).Width = W - (2 * x) FreeCAD.getDocument(newModelName).getObject(pin1MarkName).Height = Hamb FreeCAD.getDocument(newModelName).getObject( pin1MarkName).Placement = App.Placement( App.Vector((-1 * (Lb / 2)) + x + B, ((-1 * (W / 2)) + x), H), App.Rotation(0, 0, 0, 1)) ################################################################### # Wrap things up ################################################################### # Kill off various no-longer-needed objects App.getDocument(newModelName).removeObject("Pin1") App.getDocument(newModelName).removeObject("Pin2") App.getDocument(newModelName).removeObject("Cut") App.getDocument(newModelName).removeObject("Cut001") App.getDocument(newModelName).removeObject("Cut002") App.getDocument(newModelName).removeObject("Cut003") App.getDocument(newModelName).removeObject("Cut004") App.getDocument(newModelName).removeObject("Cut005") App.getDocument(newModelName).removeObject("Cut006") App.getDocument(newModelName).removeObject("Cut007") App.getDocument(newModelName).removeObject("Cut008") App.getDocument(newModelName).removeObject("Cut009") App.getDocument(newModelName).removeObject("Cut011") App.getDocument(newModelName).removeObject("Fusion") App.getDocument(newModelName).removeObject("Fusion001") App.getDocument(newModelName).removeObject("Box") App.getDocument(newModelName).removeObject("Box001") App.getDocument(newModelName).removeObject("Box002") App.getDocument(newModelName).removeObject("Box003") App.getDocument(newModelName).removeObject("Box004") App.getDocument(newModelName).removeObject("Box005") App.getDocument(newModelName).removeObject("Box006") App.getDocument(newModelName).removeObject("Box007") App.getDocument(newModelName).removeObject("Box008") App.getDocument(newModelName).removeObject("Box009") App.getDocument(newModelName).removeObject("Box010") App.getDocument(newModelName).removeObject("Box011") App.getDocument(newModelName).removeObject("Box012") App.getDocument(newModelName).removeObject("Box013") App.getDocument(newModelName).removeObject("Fillet") # If P parameter wasn't 0, clean up objects that were created if (P != 0): App.getDocument(newModelName).removeObject("Box014") App.getDocument(newModelName).removeObject("Cut010") # Set view and zoom in Gui.activeDocument().activeView().viewFront() Gui.SendMsgToActiveView("ViewFit") #Gui.activateWorkbench("DraftWorkbench") # Color body yellow FreeCADGui.getDocument(newModelName).getObject(bodyName).ShapeColor = ( 0.89, 0.96, 0.33) # Color pins bright tin FreeCADGui.getDocument(newModelName).getObject(pinsName).ShapeColor = ( 0.80, 0.80, 0.75) # Color anode marker rust orange FreeCADGui.getDocument(newModelName).getObject(pin1MarkName).ShapeColor = ( 0.67, 0.42, 0.22) # Save to disk in native format App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.getDocument(newModelName).FileName = newModelPathNameExt App.getDocument(newModelName).Label = newModelName Gui.SendMsgToActiveView("Save") App.getDocument(newModelName).save() # Export to STEP App.ActiveDocument = None Gui.ActiveDocument = None App.setActiveDocument(newModelName) App.ActiveDocument = App.getDocument(newModelName) Gui.ActiveDocument = Gui.getDocument(newModelName) App.getDocument(newModelName).save() __objs__ = [] __objs__.append(FreeCAD.getDocument(newModelName).getObject(bodyName)) __objs__.append(FreeCAD.getDocument(newModelName).getObject(pinsName)) __objs__.append(FreeCAD.getDocument(newModelName).getObject(pin1MarkName)) import ImportGui ImportGui.export(__objs__, newStepPathNameExt) del __objs__ ## # Close all documents ### App.closeDocument(newModelName) ### App.setActiveDocument("") ### App.ActiveDocument=None ### Gui.ActiveDocument=None return 0
App.Vector(sr_2x[0], sr_2y[0] - 11, 0)), False) App.getDocument('Unnamed').recompute() f = FreeCAD.getDocument('Unnamed').addObject('Part::Extrusion', 'Extrude') f = App.getDocument('Unnamed').getObject('Extrude') f.Base = App.getDocument('Unnamed').getObject('Sketch') f.DirMode = "Custom" f.Dir = App.Vector(0.000000000000000, 0.000000000000000, 1.000000000000000) f.DirLink = None f.LengthFwd = 4.500000000000000 f.LengthRev = 0.000000000000000 f.Solid = True f.Reversed = False f.Symmetric = False f.TaperAngle = 0.000000000000000 f.TaperAngleRev = 0.000000000000000 # Gui.ActiveDocument.Extrude.ShapeColor=Gui.ActiveDocument.Sketch.ShapeColor # Gui.ActiveDocument.Extrude.LineColor=Gui.ActiveDocument.Sketch.LineColor # Gui.ActiveDocument.Extrude.PointColor=Gui.ActiveDocument.Sketch.PointColor f.Base.ViewObject.hide() App.ActiveDocument.recompute() __objs__ = [] __objs__.append(FreeCAD.getDocument("Unnamed").getObject("Extrude")) import ImportGui ImportGui.export(__objs__, u"C:/Users/asea2/Desktop/imyafila.step") del __objs__
def exportStep(objs, filename): ImportGui.export(objs,filename)
myEx=App.ActiveDocument.addObject("Part::Extrusion","Extrude") myEx.Base = sk1 myEx.Dir = (0,0,50) myEx.Solid = (True) myEx.TaperAngle = (0) myEx.Label = data[0] FreeCADGui.getDocument(App.ActiveDocument.Name).getObject("Extrude").LineColor = (0.0,0.0,0.0) FreeCADGui.getDocument(App.ActiveDocument.Name).getObject("Extrude").ShapeColor = (0.96,0.93,0.76) Gui.getDocument(App.ActiveDocument.Name).getObject("Sketch").Visibility=False App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") App.ActiveDocument.saveAs(directory+data[0]+'.FCStd') __objs__=[] __objs__.append(FreeCAD.getDocument(App.ActiveDocument.Name).getObject("Extrude")) ImportGui.export(__objs__,directory+data[0]+'.step') Mesh.export(__objs__,directory+data[0]+'.stl') del __objs__ App.closeDocument(App.ActiveDocument.Name) print 'End'
def exportSTEP(doc, outdir, name): filename = os.path.join(outdir, name + '.step') import ImportGui ImportGui.export(doc.Objects, filename)