def assemble(self): App.ActiveDocument = App.getDocument(self.name) shape = App.ActiveDocument.ActiveObject.Shape App.ActiveDocument = App.getDocument("PrinterAssembly") App.ActiveDocument.addObject("Part::Feature", self.name).Shape = shape # Color Part # Get the feature and move it into position objs = App.ActiveDocument.getObjectsByLabel(self.name) shape = objs[-1] # Rotate into correct orientation rotateAngle = 90 rotateCenter = App.Vector(0, 0, 0) rotateAxis = App.Vector(1, 0, 0) Draft.rotate([shape], rotateAngle, rotateCenter, axis=rotateAxis, copy=False) rotateAngle = -90 rotateCenter = App.Vector(0, 0, 0) rotateAxis = App.Vector(0, 0, 1) Draft.rotate([shape], rotateAngle, rotateCenter, axis=rotateAxis, copy=False) # Define shifts and move the into place xShift = -gv.zRodSpacing / 2 + gv.zEndstopBodyThickness + gv.zRodDiaL / 2 yShift = gv.extruderNozzleStandoff - gv.zRodStandoff zShift = gv.zRodSupportLength App.ActiveDocument = App.getDocument("PrinterAssembly") Draft.move([shape], App.Vector(xShift, yShift, zShift), copy=False) App.ActiveDocument.recompute() if shape not in gv.zAxisParts: gv.zAxisParts.append(shape)
def assemble(self): App.ActiveDocument=App.getDocument(self.name) shape = App.ActiveDocument.ActiveObject.Shape App.ActiveDocument=App.getDocument("PrinterAssembly") Gui.ActiveDocument=Gui.getDocument("PrinterAssembly") App.ActiveDocument.addObject('Part::Feature',self.name).Shape= shape #Color Part # Gui.ActiveDocument.getObject(self.name).ShapeColor = (gv.printedR,gv.printedG,gv.printedB,gv.printedA) #Get the feature and move it into position objs = App.ActiveDocument.getObjectsByLabel(self.name) shape = objs[-1] #Rotate into correct orientation rotateAngle = 180 rotateCenter = App.Vector(0,0,0) rotateAxis = App.Vector(0,0,1) Draft.rotate([shape],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) #Define shifts and move the left clamp into place xShift = 0 yShift = ( gv.extruderDepth - gv.extruderEdgeToCenterLine) zShift = (-gv.xCarriageBushingHolderOR + gv.xCarriageMountHoleVertOffset - (gv.extruderMountAngleWidth-gv.extruderMountAngleThickness)/2 ) App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([shape],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute() if shape not in gv.xAxisParts: gv.xAxisParts.append(shape)
def assemble(self): App.ActiveDocument=App.getDocument(self.name) shape = App.ActiveDocument.ActiveObject.Shape App.ActiveDocument=App.getDocument("PrinterAssembly") App.ActiveDocument.addObject('Part::Feature',self.name).Shape= shape #Color Part #Get the feature and move it into position objs = App.ActiveDocument.getObjectsByLabel(self.name) shape = objs[-1] #Rotate into correct orientation rotateAngle = 180 rotateCenter = App.Vector(0,0,0) rotateAxis = App.Vector(1,0,0) Draft.rotate([shape],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) #Rotate into correct orientation rotateAngle = 90 rotateCenter = App.Vector(0,0,0) rotateAxis = App.Vector(0,0,1) Draft.rotate([shape],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) #Define shifts and move the left clamp into place xShift = gv.yMotorPulleyDia/2 yShift = 0 zShift = gv.PBBHStandoff App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([shape],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute() if shape not in gv.yAxisParts: gv.yAxisParts.append(shape)
def assemble(self): App.ActiveDocument=App.getDocument(self.name) shape = App.ActiveDocument.ActiveObject.Shape App.ActiveDocument=App.getDocument("PrinterAssembly") App.ActiveDocument.addObject('Part::Feature',self.name).Shape= shape #Color Part #Get the feature and move it into position objs = App.ActiveDocument.getObjectsByLabel(self.name) shape = objs[-1] #Rotate into correct orientation rotateAngle = 90 rotateCenter = App.Vector(0,0,0) rotateAxis = App.Vector(0,0,1) Draft.rotate([shape],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) #Define shifts and move the left clamp into place xShift = gv.zRodSpacing/2 yShift = -gv.yRodLength/2 + gv.frameWidth zShift = -gv.yRodStandoff - gv.frameHeight/2 - gv.frameSpacerLength - gv.frameHeight App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([shape],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute()
def assemble(self): App.ActiveDocument=App.getDocument(self.name) shape = App.ActiveDocument.ActiveObject.Shape App.ActiveDocument=App.getDocument("PrinterAssembly") App.ActiveDocument.addObject('Part::Feature',self.name).Shape= shape #Color Part #Get the feature and move it into position objs = App.ActiveDocument.getObjectsByLabel(self.name) shape = objs[-1] #Rotate into correct orientation # rotateAngle = 0 # rotateCenter = App.Vector(0,0,0) # rotateAxis = App.Vector(1,0,0) # Draft.rotate([shape],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) #Define shifts and move the left clamp into place xShift = +gv.zRodSpacing/2 yShift = gv.extruderNozzleStandoff - gv.zRodStandoff zShift = 0 App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([shape],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute() if shape not in gv.xAxisParts: gv.zAxisParts.append(shape)
def assemble(self): App.ActiveDocument=App.getDocument("xRodTop") xRodTop = App.ActiveDocument.Pad.Shape App.ActiveDocument=App.getDocument("PrinterAssembly") App.ActiveDocument.addObject('Part::Feature','xRodTop').Shape=xRodTop #Define shifts and move into place xShift = -gv.xRodLength/2 yShift = (gv.extruderNozzleStandoff - gv.zRodStandoff - gv.xEndZRodHolderFaceThickness - gv.xEndZRodHolderMaxNutFaceToFace/2 - gv.xMotorMountPlateThickness - gv.xRodClampThickness - gv.xRodDiaMax/2 ) zShift = gv.xRodSpacing App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([App.ActiveDocument.xRodTop],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute() xrt = App.ActiveDocument.xRodTop if xrt not in gv.xAxisParts: gv.xAxisParts.append(xrt)
def addSelection(self,docname,objname,subname,pnt): i = self.i_active_ref if i < 0: #not selecting any reference return if i > 0 and self.auto_next: prevref = LinkFromStr( self.refLines[i-1].text(), self.obj.Document ) if prevref[0].Name == objname and subname == '': # whole object was selected by double-clicking # its subelement was already written to line[i-1], so we decrease i to overwrite the lineRefChanged i -= 1 if i > len(self.refLines)-1: # all 4 references have been selected, finish assert(self.auto_next) self.i_active_ref = -1 self.updateRefButtons() return if i > -1: # assign the selected reference if objname == self.obj.Name: self.form.message.setText(_translate('AttachmentEditor',"Ignored. Can't attach object to itself!",None)) return if App.getDocument(docname).getObject(objname) in getAllDependent(self.obj): self.form.message.setText(_translate('AttachmentEditor',"{obj1} depends on object being attached, can't use it for attachment",None).format(obj1= objname)) return self.refLines[i].setText( StrFromLink(App.getDocument(docname).getObject(objname), subname) ) self.lineRefChanged(i,'') if self.auto_next: i += 1 self.i_active_ref = i self.updateRefButtons()
def assemble(self): App.ActiveDocument=App.getDocument("xEndIdlerPlate") shape = App.ActiveDocument.ActiveObject.Shape App.ActiveDocument=App.getDocument("PrinterAssembly") App.ActiveDocument.addObject('Part::Feature','xEndIdlerPlate').Shape= shape #Color Part change colors to metal #Rotate into correct orientation rotateAngle = -90 rotateCenter = App.Vector(0,0,0) rotateAxis = App.Vector(1,0,0) Draft.rotate([App.ActiveDocument.xEndIdlerPlate],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) #Define shifts and move the left clamp into place xShift = gv.xRodLength/2-gv.xRodClampPocketDepth yShift = (gv.extruderNozzleStandoff - gv.zRodStandoff - gv.xEndZRodHolderFaceThickness - gv.xEndZRodHolderMaxNutFaceToFace/2 - gv.xMotorMountPlateThickness) zShift = gv.xMotorMountPlateWidth+ (gv.xRodSpacing-gv.xMotorMountPlateWidth)/2 App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([App.ActiveDocument.xEndIdlerPlate],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute() shape = App.ActiveDocument.xEndIdlerPlate if shape not in gv.xAxisParts: gv.xAxisParts.append(shape)
def assemble(self): App.ActiveDocument=App.getDocument(self.name) shape = App.ActiveDocument.ActiveObject.Shape App.ActiveDocument=App.getDocument("PrinterAssembly") Gui.ActiveDocument=Gui.getDocument("PrinterAssembly") App.ActiveDocument.addObject('Part::Feature',self.name).Shape= shape #Color Part Gui.ActiveDocument.getObject(self.name).ShapeColor = (gv.frameR,gv.frameG,gv.frameB,gv.frameA) #Get the feature and move it into position objs = App.ActiveDocument.getObjectsByLabel(self.name) shape = objs[-1] # #Rotate into correct orientation # rotateAngle = 0 # rotateCenter = App.Vector(0,0,0) # rotateAxis = App.Vector(1,0,0) # Draft.rotate([shape],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) #Define shifts and move the left clamp into place xShift = -gv.crossBarLength/2 yShift = -gv.yRodLength/2 + gv.frameWidth/2 zShift = -gv.yRodStandoff - 1.5*gv.frameHeight - gv.frameSpacerLength App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([shape],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute()
def Activated(self): #Grab our code editor so we can interact with it mw = FreeCADGui.getMainWindow() cqCodePane = mw.findChild(QtGui.QPlainTextEdit, "cqCodePane") #Clear the old render before re-rendering clearActiveDocument() #Save our code to a tempfile and render it tempFile = tempfile.NamedTemporaryFile(delete=False) tempFile.write(cqCodePane.toPlainText().encode('utf-8')) tempFile.close() docname = os.path.splitext(os.path.basename(cqCodePane.file.path))[0] #If the matching 3D view has been closed, we need to open a new one try: FreeCAD.getDocument(docname) except: FreeCAD.newDocument(docname) #We import this way because using execfile() causes non-standard script execution in some situations imp.load_source('temp_module', tempFile.name) msg = QtGui.QApplication.translate( "cqCodeWidget", "Executed ", None, QtGui.QApplication.UnicodeUTF8) FreeCAD.Console.PrintMessage(msg + cqCodePane.file.path + "\r\n")
def assemble(self): App.ActiveDocument = App.getDocument(self.name) shape = App.ActiveDocument.ActiveObject.Shape App.ActiveDocument = App.getDocument("PrinterAssembly") Gui.ActiveDocument = Gui.getDocument("PrinterAssembly") App.ActiveDocument.addObject("Part::Feature", self.name).Shape = shape # Color Part # Gui.ActiveDocument.getObject(self.name).ShapeColor = (gv.printedR,gv.printedG,gv.printedB,gv.printedA) # Get the feature and move it into position objs = App.ActiveDocument.getObjectsByLabel(self.name) shape = objs[-1] # Rotate into correct orientation rotateAngle = 180 rotateCenter = App.Vector(0, 0, 0) rotateAxis = App.Vector(0, 0, 1) Draft.rotate([shape], rotateAngle, rotateCenter, axis=rotateAxis, copy=False) # Define shifts and move the left clamp into place xShift = 0 yShift = gv.yRodLength / 2 zShift = -gv.yRodStandoff App.ActiveDocument = App.getDocument("PrinterAssembly") Draft.move([shape], App.Vector(xShift, yShift, zShift), copy=False) App.ActiveDocument.recompute() if shape not in gv.yAxisParts: gv.yAxisParts.append(shape)
def main(): shape = Part.Shape() #shape_formats = ['.brp', '.igs', '.stp'] if in_ext in mesh_formats: print("Opening mesh file: ", in_f) Mesh.open(in_f) o = FreeCAD.getDocument("Unnamed").findObjects()[0] #print("dir: ", dir(o)) if out_ext in mesh_formats: print("Exporting to mesh file: ", out_f) Mesh.export([o], out_f) else: # TODO This is not optimizing the resulting amount of faces! # see http://www.freecadweb.org/wiki/index.php?title=Mesh_to_Part shape.makeShapeFromMesh(o.Mesh.Topology, 0.05) # tolerance for sewing exportParametric(shape, out_f, out_ext) elif out_ext in mesh_formats: print("Opening parametric file: ", in_f) Part.open(in_f) o = FreeCAD.getDocument("Unnamed").findObjects()[0] print("Exporting to mesh file: ", out_f) Mesh.export([o], out_f) else: # Parametric -> Parametric print("Opening parametric file: ", in_f) shape.read(in_f) exportParametric(shape, out_f, out_ext)
def assemble(self): App.ActiveDocument = App.getDocument("xRodBottom") xRodBottom = App.ActiveDocument.Pad.Shape App.ActiveDocument = App.getDocument("PrinterAssembly") App.ActiveDocument.addObject('Part::Feature', 'xRodBottom').Shape = xRodBottom # Define shifts and move into place xshift = -gv.xRodLength / 2 yshift = (gv.extruderNozzleStandoff - gv.zRodStandoff - gv.xEndZRodHolderFaceThickness - gv.xEndZRodHolderMaxNutFaceToFace / 2 - gv.xMotorMountPlateThickness - gv.xRodClampThickness - gv.xRodDiaMax / 2) zshift = 0 App.ActiveDocument = App.getDocument("PrinterAssembly") Draft.move([App.ActiveDocument.getObject("xRodBottom")], App.Vector(xshift, yshift, zshift), copy=False) App.ActiveDocument.recompute() # Add to xAxisParts xrb = App.ActiveDocument.getObject("xRodBottom") if xrb not in gv.xAxisParts: gv.xAxisParts.append(xrb)
def addSelection(self,doc,obj,sub,pnt): if self.beam==None and FreeCAD.getDocument(doc).getObject(obj).TypeId=='Part::FeaturePython': self.beam=FreeCAD.getDocument(doc).getObject(obj) FreeCAD.Console.PrintMessage('Beam type selected.\n') else: subObject=FreeCAD.getDocument(doc).getObject(obj).Shape.getElement(sub) if subObject.ShapeType=="Edge" and self.beam!=None: frameCmd.placeTheBeam(FreeCAD.activeDocument().copyObject(self.beam,True),subObject)
def assemble(self): App.ActiveDocument=App.getDocument(self.name) shape = App.ActiveDocument.ActiveObject.Shape App.ActiveDocument=App.getDocument("PrinterAssembly") Gui.ActiveDocument=Gui.getDocument("PrinterAssembly") App.ActiveDocument.addObject('Part::Feature',self.name+"L").Shape= shape #Color Part Gui.ActiveDocument.getObject(self.name+"L").ShapeColor = (gv.frameR,gv.frameG,gv.frameB,gv.frameA) #Get the feature and move it into position objs = App.ActiveDocument.getObjectsByLabel(self.name+"L") shape = objs[-1] #Rotate into correct orientation rotateAngle = -90 rotateCenter = App.Vector(0,0,0) rotateAxis = App.Vector(0,1,0) Draft.rotate([shape],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) rotateAngle = 90 rotateCenter = App.Vector(0,0,0) rotateAxis = App.Vector(0,0,1) Draft.rotate([shape],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) #Define shifts and move the left clamp into place xShift = -gv.zRodSpacing/2 yShift = gv.extruderNozzleStandoff+gv.frameHeight/2 # (gv.frameHeight/2 # + gv.zRodStandoff # + gv.xRodClampOverallThickness/2 # + gv.xMotorMountPlateThickness # + gv.xEndZRodHolderFaceThickness # + gv.xEndZRodHolderMaxNutFaceToFace/2) zShift = -gv.yRodStandoff App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([shape],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute() #Copy part App.ActiveDocument.addObject('Part::Feature',self.name+"R").Shape= shape.Shape verticalBarL = App.ActiveDocument.getObjectsByLabel(self.name+"R")[-1] #Color part Gui.ActiveDocument.getObject(self.name+"R").ShapeColor = (gv.frameR,gv.frameG,gv.frameB,gv.frameA) #Move copy to Right side xShift = gv.zRodSpacing yShift = 0 zShift = 0 App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([verticalBarL],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute()
def addSelection(self,doc,obj,sub,pnt): subObject=FreeCAD.getDocument(doc).getObject(obj).Shape.getElement(sub) if subObject.ShapeType=="Face": if self.faceBase==None: self.faceBase=subObject FreeCAD.Console.PrintMessage('Target face selected.\n') else: FreeCAD.activeDocument().openTransaction('alignFlange') frameCmd.rotTheBeam(FreeCAD.getDocument(doc).getObject(obj),self.faceBase,subObject) FreeCAD.activeDocument().commitTransaction()
def setup(part,view): date = datetime.date.today().strftime("%m_%d_%Y") printerDir = gv.printerDir+"Printer_"+date+"/" #part: "printBedSupport" #subpart: App.ActiveDocument.Pocket001 FreeCAD.open(printerDir+"Parts/"+part+".FCStd") App.setActiveDocument(part) view = eval('App.ActiveDocument.'+view) create(view) App.getDocument(part).save() App.closeDocument(part)
def addSelection(self,doc,obj,sub,pnt): subObject=FreeCAD.getDocument(doc).getObject(obj).Shape.getElement(sub) if subObject.ShapeType=="Face": if self.targetFace==None: self.targetFace=subObject FreeCAD.Console.PrintMessage('Target face selected.\n') else: beam=FreeCAD.getDocument(doc).getObject(obj) FreeCAD.activeDocument().openTransaction('levelTheBeam') frameCmd.levelTheBeam(beam,[self.targetFace,subObject]) FreeCAD.activeDocument().commitTransaction() FreeCAD.Console.PrintMessage('Face moved.\n') FreeCAD.Console.PrintWarning('Select another face or press [ESC].\n')
def saveAssembly(): # Make dateString and add it to the directory string date = datetime.date.today().strftime("%m_%d_%Y") # make the printer's directory if it doesn't exist printerDir = gv.printerDir + "Printer_" + date + "/" if not os.path.exists(printerDir): os.makedirs(printerDir) # Save the FCStd file if os.path.isfile(printerDir + "PrinterAssembly.FCStd"): os.remove(printerDir + "PrinterAssembly.FCStd") App.getDocument("PrinterAssembly").saveAs(printerDir + "PrinterAssembly.FCStd")
def assemble(self): App.ActiveDocument=App.getDocument(self.name) shape = App.ActiveDocument.ActiveObject.Shape App.ActiveDocument=App.getDocument("PrinterAssembly") Gui.ActiveDocument=Gui.getDocument("PrinterAssembly") App.ActiveDocument.addObject('Part::Feature',self.name).Shape= shape #Color Part Gui.ActiveDocument.getObject(self.name).ShapeColor = (gv.printedR,gv.printedG,gv.printedB,gv.printedA) #Get the feature and move it into position objs = App.ActiveDocument.getObjectsByLabel(self.name) shape = objs[-1] #Rotate into correct orientation rotateAngle = 180 rotateCenter = App.Vector(0,0,0) rotateAxis = App.Vector(0,1,0) Draft.rotate([shape],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) #Define shifts and move the left clamp into place if self.side =="Right": xShift = gv.yRodSpacing/2 else: xShift = -gv.yRodSpacing/2 yShift = -gv.yBushingNutSeparation/2 zShift = gv.PBBHStandoff App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([shape],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute() if shape not in gv.yAxisParts: gv.yAxisParts.append(shape) #Make a copy of the y bushing holder App.ActiveDocument.addObject('Part::Feature',self.name+"Rear").Shape= shape.Shape #Color Part Gui.ActiveDocument.getObject(self.name+"Rear").ShapeColor = (gv.printedR,gv.printedG,gv.printedB,gv.printedA) #Define shifts and move y bushing holder into place xShift = 0 yShift = gv.yBushingNutSeparation zShift = 0 App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([shape],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute() if shape not in gv.yAxisParts: gv.yAxisParts.append(shape)
def draw(self): try: Gui.getDocument('zRodR') Gui.getDocument('zRodR').resetEdit() App.getDocument('zRodR').recompute() App.closeDocument("zRodR") App.setActiveDocument("") App.ActiveDocument=None Gui.ActiveDocument=None except: pass #make document App.newDocument("zRodR") App.setActiveDocument("zRodR") App.ActiveDocument=App.getDocument("zRodR") Gui.ActiveDocument=Gui.getDocument("zRodR") #make sketch # sketch = App.activeDocument().addObject('Sketcher::SketchObject','Sketch') App.activeDocument().addObject('Sketcher::SketchObject','Sketch') App.activeDocument().Sketch.Placement = App.Placement(App.Vector(0.000000,0.000000,0.000000),App.Rotation(0.000000,0.000000,0.000000,1.000000)) Gui.activeDocument().activeView().setCamera('#Inventor V2.1 ascii \n OrthographicCamera {\n viewportMapping ADJUST_CAMERA\n position 87 0 0 \n orientation 0.57735026 0.57735026 0.57735026 2.0943952 \n nearDistance -112.887\n farDistance 287.28699\n aspectRatio 1\n focalDistance 87\n height 143.52005\n\n}') ## Gui.activeDocument().setEdit('Sketch') App.ActiveDocument.Sketch.addGeometry(Part.Circle(App.Vector(50,50,0),App.Vector(0,0,1),gv.zRodDiaR)) App.ActiveDocument.recompute() #sketch.addConstraint(Sketcher.Constraint('Coincident',0,3,-1,1)) App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident',0,3,-1,1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Radius',0,gv.zRodDiaR/2)) App.ActiveDocument.recompute() Gui.getDocument('zRodR').resetEdit() App.getDocument('zRodR').recompute() #Pad sketch App.activeDocument().addObject("PartDesign::Pad","Pad") App.activeDocument().Pad.Sketch = App.activeDocument().Sketch App.activeDocument().Pad.Length = 10.0 App.ActiveDocument.recompute() Gui.activeDocument().hide("Sketch") App.ActiveDocument.Pad.Length = gv.zRodLength App.ActiveDocument.Pad.Reversed = 0 App.ActiveDocument.Pad.Midplane = 0 App.ActiveDocument.Pad.Length2 = 100.000000 App.ActiveDocument.Pad.Type = 0 App.ActiveDocument.Pad.UpToFace = None App.ActiveDocument.recompute() Gui.activeDocument().resetEdit() #set view as axiometric Gui.activeDocument().activeView().viewAxometric()
def reorient_object(input_file_name, output_file_name, refinement_level): __objToExport__ = FreeCAD.getDocument("tmp").findObjects() # get the original file Import.insert(input_file_name, "tmp") # get bounding box bB = FreeCAD.getDocument("tmp").Objects[-1].Shape.BoundBox # create rotation parameters displacement = FreeCAD.Vector(2.0, 0.0, 0.0) centerRot = FreeCAD.Vector(bB.XMin, 0.5*(bB.YMin+bB.YMax), bB.ZMin) axisRot1 = FreeCAD.Vector(0.0, 0.0, 1.0) axisRot2 = FreeCAD.Vector(0.0, 1.0, 0.0) angleRot1 = 180.0 angleRot2 = 90.0 # import the draft module import Draft Draft.move(FreeCAD.getDocument("tmp").Objects[0], displacement, copy=False) # perform move Draft.rotate(FreeCAD.getDocument("tmp").Objects[0], angleRot1, centerRot,axis=axisRot1,copy=False) # perform first rotation Draft.rotate(FreeCAD.getDocument("tmp").Objects[0], angleRot2, centerRot,axis=axisRot2,copy=False) # perform second rotation # remove originalGeom originalGeom = FreeCAD.getDocument("tmp").Objects[-1].Name FreeCAD.getDocument("tmp").removeObject(originalGeom) print "Exporting RAW file..." Part.export(__objToExport__, output_file_name+".step") print "Output file " + output_file_name+".step" + " exported."
def makeAssemblyFile(): try: App.getDocument('PrinterAssembly').recompute() App.closeDocument("PrinterAssembly") App.setActiveDocument("") App.ActiveDocument = None except: pass # make document # Make Assembly file App.newDocument("PrinterAssembly") App.setActiveDocument("PrinterAssembly") App.ActiveDocument = App.getDocument("PrinterAssembly")
def assemble(self): App.ActiveDocument=App.getDocument(self.name) if self.side =="Right": xRodClamp = App.ActiveDocument.Pocket002.Shape if self.side =="Left": xRodClamp = App.ActiveDocument.Part__Mirroring.Shape App.ActiveDocument=App.getDocument("PrinterAssembly") Gui.ActiveDocument=Gui.getDocument("PrinterAssembly") App.ActiveDocument.addObject('Part::Feature',self.name).Shape=xRodClamp #Color Part Gui.ActiveDocument.getObject(self.name).ShapeColor = (gv.printedR,gv.printedG,gv.printedB,gv.printedA) objs = App.ActiveDocument.getObjectsByLabel(self.name) shape = objs[-1] #Rotate into correct orientation rotateAngle = 180 rotateCenter = App.Vector(0,0,0) rotateAxis = App.Vector(0,1,0) Draft.rotate([shape],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) rotateAngle = 90 rotateCenter = App.Vector(0,0,0) rotateAxis = App.Vector(1,0,0) Draft.rotate([shape],rotateAngle,rotateCenter,axis = rotateAxis,copy=False) #Define shifts and move the left clamp into place if self.side == "Right": xShift = +gv.xRodLength/2+gv.xRodClampWidth-gv.xRodClampPocketDepth elif self.side == "Left": xShift = -gv.xRodLength/2-gv.xRodClampWidth+gv.xRodClampPocketDepth yShift = (gv.extruderNozzleStandoff - gv.zRodStandoff - gv.xEndZRodHolderFaceThickness - gv.xEndZRodHolderMaxNutFaceToFace/2 - gv.xMotorMountPlateThickness - 2*gv.xRodClampThickness - gv.xRodDiaMax) zShift = 0 App.ActiveDocument=App.getDocument("PrinterAssembly") Draft.move([shape],App.Vector(xShift, yShift, zShift),copy=False) App.ActiveDocument.recompute() if shape not in gv.xAxisParts: gv.xAxisParts.append(shape)
def RedrawObject(self , objName): if not objName: return print 'trigger obj \'%s\' in OperationObverser'%objName obj = FreeCAD.getDocument('DDA').getObject(objName) assert obj obj.ViewObject.RedrawTrigger = True
def testSaveAndRestore(self): # saving and restoring SaveName = self.TempPath + os.sep + "SaveRestoreTests.FCStd" self.Doc.FileName = SaveName self.failUnless(self.Doc.Label_1.TypeTransient == 4711) self.Doc.Label_1.TypeTransient = 4712 # setup Linking self.Doc.Label_1.Link = self.Doc.Label_2 self.Doc.Label_2.Link = self.Doc.Label_1 self.Doc.Label_1.LinkSub = (self.Doc.Label_2,["Sub1","Sub2"]) self.Doc.Label_2.LinkSub = (self.Doc.Label_1,["Sub3","Sub4"]) # save the document self.Doc.save() FreeCAD.closeDocument("SaveRestoreTests") self.Doc = FreeCAD.open(SaveName) self.failUnless(self.Doc.Label_1.Integer == 4711) self.failUnless(self.Doc.Label_2.Integer == 4711) # test Linkage self.failUnless(self.Doc.Label_1.Link == self.Doc.Label_2) self.failUnless(self.Doc.Label_2.Link == self.Doc.Label_1) self.failUnless(self.Doc.Label_1.LinkSub == (self.Doc.Label_2,["Sub1","Sub2"])) self.failUnless(self.Doc.Label_2.LinkSub == (self.Doc.Label_1,["Sub3","Sub4"])) # do NOT save transient properties self.failUnless(self.Doc.Label_1.TypeTransient == 4711) self.failUnless(self.Doc == FreeCAD.getDocument(self.Doc.Name))
def insert(filename,docname): try: doc=FreeCAD.getDocument(docname) except: doc=FreeCAD.newDocument(docname) parse(filename,doc) doc.recompute()
def DVPartTest(): path = os.path.dirname(os.path.abspath(__file__)) print ('TDPart path: ' + path) templateFileSpec = path + '/TestTemplate.svg' FreeCAD.newDocument("TDPart") FreeCAD.setActiveDocument("TDPart") FreeCAD.ActiveDocument=FreeCAD.getDocument("TDPart") box = FreeCAD.ActiveDocument.addObject("Part::Box","Box") page = FreeCAD.ActiveDocument.addObject('TechDraw::DrawPage','Page') FreeCAD.ActiveDocument.addObject('TechDraw::DrawSVGTemplate','Template') FreeCAD.ActiveDocument.Template.Template = templateFileSpec FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template page.Scale = 5.0 # page.ViewObject.show() # unit tests run in console mode print("page created") view = FreeCAD.ActiveDocument.addObject('TechDraw::DrawViewPart','View') rc = page.addView(view) FreeCAD.ActiveDocument.View.Source = [FreeCAD.ActiveDocument.Box] FreeCAD.ActiveDocument.recompute() rc = False if ("Up-to-date" in view.State): rc = True FreeCAD.closeDocument("TDPart") return rc
def insert(filename,docname): "called when freecad imports a file" global doc global pathName groupname = os.path.splitext(os.path.basename(filename))[0] try: doc=FreeCAD.getDocument(docname) except NameError: doc=FreeCAD.newDocument(docname) #importgroup = doc.addObject("App::DocumentObjectGroup",groupname) if filename.lower().endswith('.scad'): tmpfile=callopenscad(filename) if workaroundforissue128needed(): pathName = '' #https://github.com/openscad/openscad/issues/128 #pathName = os.getcwd() #https://github.com/openscad/openscad/issues/128 else: pathName = os.path.dirname(os.path.normpath(filename)) processcsg(tmpfile) try: os.unlink(tmpfile) except OSError: pass else: pathName = os.path.dirname(os.path.normpath(filename)) processcsg(filename)
def z_RotateObject(doc, rot): # z-Rotate objs=GetListOfObjects(FreeCAD, doc) FreeCAD.getDocument(doc.Name).getObject(objs[0].Name).Placement = FreeCAD.Placement(FreeCAD.Vector(0,0,0),FreeCAD.Rotation(FreeCAD.Vector(0,0,1),rot)) return 0
def DHatchTest(): path = os.path.dirname(os.path.abspath(__file__)) print('TDHatch path: ' + path) templateFileSpec = path + '/TestTemplate.svg' hatchFileSpec = path + '/TestHatch.svg' FreeCAD.newDocument("TDHatch") FreeCAD.setActiveDocument("TDHatch") FreeCAD.ActiveDocument = FreeCAD.getDocument("TDHatch") #make source feature box = FreeCAD.ActiveDocument.addObject("Part::Box", "Box") #make a page page = FreeCAD.ActiveDocument.addObject('TechDraw::DrawPage', 'Page') FreeCAD.ActiveDocument.addObject('TechDraw::DrawSVGTemplate', 'Template') FreeCAD.ActiveDocument.Template.Template = templateFileSpec FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template page.Scale = 5.0 # page.ViewObject.show() #unit tests run in console mode #make Views view1 = FreeCAD.ActiveDocument.addObject('TechDraw::DrawViewPart', 'View') FreeCAD.ActiveDocument.View.Source = [box] rc = page.addView(view1) FreeCAD.ActiveDocument.recompute() #make hatch print("making hatch") hatch = FreeCAD.ActiveDocument.addObject('TechDraw::DrawHatch', 'Hatch') hatch.Source = (view1, ["Face0"]) hatch.HatchPattern = hatchFileSpec #comment out to use default from preferences print("adding hatch to page") rc = page.addView(hatch) print("finished hatch") FreeCAD.ActiveDocument.recompute() rc = False if ("Up-to-date" in hatch.State): rc = True FreeCAD.closeDocument("TDHatch") return rc
def getGeomPoint(self): obj = FreeCAD.getDocument(self.snapShape[0]).getObject( self.snapShape[1]) FreeCAD.Console.PrintMessage('%s\n' % str(self.snapShape)) if 'Vertex' in self.snapShape[2]: n = eval(self.snapShape[2].lstrip('Vertex')) shape = obj.Shape.Vertexes[n - 1] if 'Point' in self.snapShape[2]: # Datum Point shape = obj.Shape elif 'Edge' in self.snapShape[2]: n = eval(self.snapShape[2].lstrip('Edge')) shape = obj.Shape.Edges[n - 1] elif 'Face' in self.snapShape[2]: n = eval(self.snapShape[2].lstrip('Face')) shape = obj.Shape.Faces[n - 1] v = Part.Vertex(self.point) dist, pts, sols = v.distToShape(shape) if len(pts) == 2: self.point = pts[1]
def display_tracker_menu(self, event): self.tracker_menu = QtGui.QMenu() actions = None if self.overNode: # if user is over a node doc = self.overNode.get_doc_name() obj = App.getDocument(doc).getObject(self.overNode.get_obj_name()) ep = self.overNode.get_subelement_index() obj_gui_tools = self.get_obj_gui_tools(obj) if obj_gui_tools: actions = obj_gui_tools.get_edit_point_context_menu( self, obj, ep) else: # try if user is over an edited object pos = event.getPosition() obj = self.get_selected_obj_at_position(pos) obj_gui_tools = self.get_obj_gui_tools(obj) if obj_gui_tools: actions = obj_gui_tools.get_edit_obj_context_menu( self, obj, pos) if actions is None: return for (label, callback) in actions: def wrapper(callback=callback): callback() self.resetTrackers(obj) action = self.tracker_menu.addAction(label) action.setData(wrapper) self.tracker_menu.popup(Gui.getMainWindow().cursor().pos()) QtCore.QObject.connect(self.tracker_menu, QtCore.SIGNAL("triggered(QAction *)"), self.evaluate_menu_action)
def display_tracker_menu(self, event): self.tracker_menu = QtGui.QMenu() self.event = event actions = None if self.overNode: # if user is over a node doc = self.overNode.get_doc_name() obj = App.getDocument(doc).getObject(self.overNode.get_obj_name()) ep = self.overNode.get_subelement_index() if utils.get_type(obj) in ["Line", "Wire", "BSpline"]: actions = ["delete point"] elif utils.get_type(obj) in ["BezCurve"]: actions = ["make sharp", "make tangent", "make symmetric", "delete point"] elif utils.get_type(obj) in ["Circle"]: if obj.FirstAngle != obj.LastAngle: if ep == 0: # user is over arc start point actions = ["move arc"] elif ep == 1: # user is over arc start point actions = ["set first angle"] elif ep == 2: # user is over arc end point actions = ["set last angle"] elif ep == 3: # user is over arc mid point actions = ["set radius"] else: return else: # if user is over an edited object pos = self.event.getPosition() obj = self.get_selected_obj_at_position(pos) if utils.get_type(obj) in ["Line", "Wire", "BSpline", "BezCurve"]: actions = ["add point"] elif utils.get_type(obj) in ["Circle"] and obj.FirstAngle != obj.LastAngle: actions = ["invert arc"] if actions is None: return for a in actions: self.tracker_menu.addAction(a) self.tracker_menu.popup(Gui.getMainWindow().cursor().pos()) QtCore.QObject.connect(self.tracker_menu, QtCore.SIGNAL("triggered(QAction *)"), self.evaluate_menu_action)
def Activated(self): (fstnr, axes) = self.selection if fstnr.Document: for axisData in axes: if len(axisData) > 3: # DocName/ModelName/AppLinkName/AxisName docName = axisData[0] doc = App.getDocument(docName) if doc: model = doc.getObject(axisData[1]) if model: objLink = model.getObject(axisData[2]) if objLink: obj = objLink.getLinkedObject() axis = obj.getObject(axisData[3]) if axis and axis.Document: newFstnr = Asm4.cloneObject(fstnr) Asm4.placeObjectToLCS(newFstnr, axisData[2], axis.Document.Name, axisData[3]) Gui.Selection.clearSelection() Gui.Selection.addSelection( fstnr.Document.Name, 'Model', fstnr.Name +'.')
def insert(filename, docname, skip=[], only=[], root=None): ''' opens an Autodesk Inventor file in the current document ''' if (isFileValid(filename)): try: doc = FreeCAD.getDocument(docname) logAlways(u"Importing: %s", filename) reader = read(doc, filename, False) if (reader is not None): name = os.path.splitext(os.path.basename(filename))[0] name = decode(name) group = insertGroup(doc, name) reader.create3dModel(group, doc) releaseMemory() FreeCADGui.SendMsgToActiveView("ViewFit") logInfo(u"DONE!") except: open(filename, skip, only, root) return
def execute(self, obj): ''' Create compound part at recompute. ''' docName = str(obj.Document.Name) doc = FreeCAD.getDocument(docName) listOfFaces = [] for i in range(len(obj.References)): ref = obj.References[i] selection_object = doc.getObject(ref[0]) if selection_object is not None: # May have been deleted try: listOfFaces.append( selection_object.Shape.getElement(ref[1])) except Part.OCCError: # Face may have been deleted pass if len(listOfFaces) > 0: obj.Shape = Part.makeCompound(listOfFaces) else: obj.Shape = Part.Shape() self.updateBoundaryColors(obj) return
def test_markers(): App.newDocument('MarkerTest') App.setActiveDocument('MarkerTest') App.ActiveDocument = App.getDocument('MarkerTest') Gui.ActiveDocument = Gui.getDocument('MarkerTest') Gui.activeDocument().activeView().viewDefaultOrientation() markers1 = ['square', 'cross', 'plus', 'empty', 'quad', 'circle', 'default', 'squarecircle'] markers2 = ['DIAMOND_FILLED', 'CROSS', 'PLUS', 'SQUARE_LINE', 'SQUARE_FILLED', 'CIRCLE_LINE', 'CIRCLE_FILLED', 'CROSSDIAMOND_LINE'] pl = App.Placement() pl.Base = App.Vector(800.0, 200.0, 0.0) Draft.makeRectangle(length=1700, height=-1100, placement = pl, face=False) _y = 0.0 for marker in markers1: _x = 1000.0 for size in [5,7,9,11]: EditTracker(App.Vector(_x, _y, 0.0), 'Rectangle', marker + '_' + str(size), marker, size) _x += 100 _y -= 100 _y = 0.0 for marker in markers2: _x = 2000.0 for size in [5,7,9,11]: EditTracker(App.Vector(_x, _y, 0.0), 'Line', marker + '_' + str(size), marker, size) _x += 100 _y -= 100 App.ActiveDocument.recompute() Gui.SendMsgToActiveView('ViewFit')
def createInletBoundary(self): self.inlet_boundary = CfdFluidBoundary.makeCfdFluidBoundary('inlet') bc_set = self.inlet_boundary.BoundarySettings bc_set['BoundaryType'] = 'inlet' bc_set['BoundarySubtype'] = 'uniformVelocity' bc_set['Ux'] = 1 bc_set['Uy'] = 0 bc_set['Uz'] = 0 # Test addSelection and rebuild_list_references doc = FreeCAD.getDocument(self.__class__.__doc_name) obj = doc.getObject('inlet') vobj = obj.ViewObject import _TaskPanelCfdFluidBoundary physics_model, is_present = CfdTools.getPhysicsModel(self.analysis) material_objs = CfdTools.getMaterials(self.analysis) taskd = _TaskPanelCfdFluidBoundary.TaskPanelCfdFluidBoundary(obj, physics_model, material_objs) taskd.obj = vobj.Object taskd.selecting_references = True taskd.addSelection(doc.Name, doc.getObject(self.__class__.__part_name).Name, 'Face1') taskd.accept()
def init_fcd_doc(cls): # Create document if not already opened try: cls.fcd_doc = FreeCAD.getDocument(FCD_DOC_NAME) except NameError: cls.fcd_doc = FreeCAD.newDocument(FCD_DOC_NAME) FreeCAD.Gui.setActiveDocument(cls.fcd_doc) # Clean FreeCAD document for obj in cls.fcd_doc.Objects: # Clean robots objects if obj.Label.startswith('Robot_'): Robot.do_init_shape = False if obj.Label.startswith('Area'): Area.do_init_shape = False cls.fcd_doc.getObject(obj.Label).ViewObject.Visibility = False Robot.init_shape() Obstacle.init_shape() Area.init_shape()
def insert(filename, docname): "called when freecad imports a file" PathLog.track(filename) gfile = pythonopen(filename) gcode = gfile.read() gfile.close() # split on tool changes paths = re.split('(?=[mM]+\s?0?6)', gcode) # if there are any tool changes combine the preamble with the default tool if len(paths) > 1: paths = ["\n".join(paths[0:2])] + paths[2:] for path in paths: gcode = parse(path) doc = FreeCAD.getDocument(docname) obj = FreeCAD.ActiveDocument.addObject("Path::FeaturePython", "Custom") PathScripts.PathCustom.ObjectCustom(obj) obj.ViewObject.Proxy = 0 obj.Gcode = gcode PathScripts.PathUtils.addToJob(obj) obj.ToolController = PathScripts.PathUtils.findToolController(obj) FreeCAD.ActiveDocument.recompute()
def addSelection(self, doc, obj, sub, pnt): lastSel = FreeCAD.getDocument(doc).getObject(obj) subLastSel = lastSel.Shape.getElement(sub) if subLastSel.ShapeType == "Edge": self.edges.append(subLastSel) FreeCAD.Console.PrintMessage('Edge' + str(len(self.edges)) + ' OK.\n') if len(self.edges) == 2: try: FreeCAD.activeDocument().openTransaction('rotJoin') frameCmd.rotjoinTheBeam() FreeCAD.activeDocument().commitTransaction() FreeCAD.activeDocument().recompute() FreeCAD.Console.PrintWarning("Edges aligned.\n") except: FreeCAD.Console.PrintError( "Edges must be selected holding [Ctrl] down for the correct execution. \nRetry.\n" ) self.edges = [] FreeCADGui.Selection.clearSelection() FreeCAD.Console.PrintWarning("Repeat selection or press [ESC]\n")
def _create_document(self): """ Create a new project with default groups """ #new project dialog dlg = QtGui.QInputDialog() dlg.setWindowTitle("New Project") dlg.setLabelText('Enter project name:') dlg.setWindowModality(QtCore.Qt.ApplicationModal) dlg.setTextValue('New Project') dlg.exec_() if not dlg.result(): return #assign project name, null names not accepted. project_name = dlg.textValue() if not project_name: return App.newDocument(project_name) #substitute underscores for spaces for internal naming project_name = project_name.replace(' ', '_') #set up initial references App.setActiveDocument(project_name) App.ActiveDocument = App.getDocument(project_name) Gui.ActiveDocument = Gui.getDocument(project_name) #create default groups App.ActiveDocument.addObject('App::DocumentObjectGroup', 'Templates') App.ActiveDocument.addObject('App::DocumentObjectGroup', 'Alignments') App.ActiveDocument.addObject( 'App::DocumentObjectGroup', 'Element Lofts' )
def import_z88_mesh(filename, analysis=None, docname=None): """read a FEM mesh from a Z88 mesh file and insert a FreeCAD FEM Mesh object in the ActiveDocument """ try: doc = FreeCAD.getDocument(docname) except NameError: try: doc = FreeCAD.ActiveDocument except NameError: doc = FreeCAD.newDocument() FreeCAD.ActiveDocument = doc mesh_name = os.path.basename(os.path.splitext(filename)[0]) femmesh = read(filename) if femmesh: mesh_object = doc.addObject("Fem::FemMeshObject", mesh_name) mesh_object.FemMesh = femmesh return mesh_object
def setUp(self): """Creates a page and a view""" FreeCAD.newDocument("TDSection") FreeCAD.setActiveDocument("TDSection") FreeCAD.ActiveDocument = FreeCAD.getDocument("TDSection") self.box = FreeCAD.ActiveDocument.addObject("Part::Box", "Box") self.page = createPageWithSVGTemplate() self.page.Scale = 5.0 # page.ViewObject.show() # unit tests run in console mode print("page created") self.view = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewPart", "View") self.page.addView(self.view) self.view.Source = [self.box] self.view.Direction = (0.0, 0.0, 1.0) self.view.Rotation = 0.0 self.view.X = 30.0 self.view.Y = 150.0 print("view created")
def find_doc(doc=None): """Return the active document or find a document by name. Parameters ---------- doc: App::Document or str, optional The document that will be searched in the session. It defaults to `None`, in which case it tries to find the active document. If `doc` is a string, it will try to get the document by `Name`. Returns ------- bool, App::Document A tuple containing the information on whether the search was successful. In this case, the boolean is `True`, and the second value is the document instance. False, None If there is no active document, or the string in `doc` doesn't correspond to an open document in the session. """ FOUND = True if not doc: doc = App.activeDocument() if not doc: return not FOUND, None if isinstance(doc, str): try: doc = App.getDocument(doc) except NameError: _msg("document: {}".format(doc)) _err(_tr("Wrong input: unknown document.")) return not FOUND, None return FOUND, doc
def addSelection(self, doc, obj, sub, pnt): # Selection object # Since both 3D view clicks and manual tree selection gets into the same callback # we will determine by clicked coordinates, for manual tree selections the coordinates are (0,0,0) FCC.PrintMessage('Clicked on :' + obj + '@' + sub + '\n') if pnt != (0, 0, 0): # 3D view click # Get linked object name that handles sub-sub-assembly #subObjName = Asm4.getLinkedObjectName(doc, obj, sub) objList = App.getDocument(doc).getObject(obj).getSubObjectList(sub) # Build the name of the selected sub-object for multiple sub-assembly levels subObjName = '' for subObj in objList: if subObj.TypeId == 'App::Link': subObjName = subObjName + subObj.Name + '.' if subObjName != '': # set the selection to the selected object Gui.Selection.clearSelection() Gui.Selection.addSelection(doc, obj, subObjName) # set the selected object drop-down to this object global taskUI link = App.ActiveDocument.getObject(subObjName[0:-1]) #FCC.PrintMessage('LinkedObject = '+link.LinkedObject.Name+'\n') # try to find this link in the parents parent_found = False parent_index = 1 for item in taskUI.parentTable[1:]: if item.Name == link.Name: parent_found = True break else: parent_index = parent_index + 1 if not parent_found: parent_index = 0 taskUI.parentList.setCurrentIndex(parent_index) # select the Parent Assembly else: taskUI.parentList.setCurrentIndex(1)
def main(): doc = FreeCAD.getDocument("Gordon_1") loft = doc.getObject("Loft") profloft = loft.Shape.Face1 inter = doc.getObject("Shape") interpts = inter.Shape.Face1 loft2 = doc.getObject("Ruled_Surface") railloft = loft2.Shape.Face1 surf1 = profloft.Surface.copy() surf2 = railloft.Surface.copy() surf3 = interpts.Surface.copy() surf1.exchangeUV() matchSurfaces(surf1, surf2) matchSurfaces(surf2, surf3) matchSurfaces(surf3, surf1) checkPoles([surf1, surf2, surf3]) # Now, the 3 surfaces should have identical topologies (same degrees, knots, mults) # Only their poles, weights are different poles1 = addPoles(surf1.getPoles(), surf2.getPoles()) poles2 = subPoles(poles1, surf3.getPoles()) gordon = surf1.copy() for i in range(len(poles2)): gordon.setPoleRow(i + 1, poles2[i]) Part.show(surf1.toShape()) Part.show(surf2.toShape()) Part.show(surf3.toShape()) Part.show(gordon.toShape())
def move_object(object_lable, viewface, vector): global x, y, z, D_lable, n_x, n_y, n_z # vector=4*vector print(object_lable) print("viewface:", viewface) if D_lable != object_lable: x = 0 y = 0 z = 0 if viewface == 'Front': n_x = x - vector[0] n_y = y n_z = z - vector[1] elif viewface == 'Left': n_x = x n_y = y + vector[0] n_z = z - vector[1] elif viewface == 'Top': n_x = x - vector[0] n_y = y - vector[1] n_z = z elif viewface == 'Axonometric': n_x = x - vector[2] n_y = y - vector[0] n_z = z - vector[1] print(n_x, n_y, n_z) App.getDocument("Unnamed").getObject( object_lable).Placement = App.Placement(App.Vector(n_x, n_y, n_z), App.Rotation(Rx, Ry, Rz), App.Vector(0, 0, 0)) Gui.ActiveDocument.update() # Gui.SendMsgToActiveView("ViewFit") ###测试使用,正常注释 x = n_x y = n_y z = n_z D_lable = object_lable return x, y, z, D_lable
def createInletBoundary(self): self.inlet_boundary = CfdFluidBoundary.makeCfdFluidBoundary('inlet') self.analysis.addObject(self.inlet_boundary) bc_set = self.inlet_boundary bc_set.BoundaryType = 'inlet' bc_set.BoundarySubType = 'uniformVelocityInlet' bc_set.Ux = 1 bc_set.Uy = 0 bc_set.Uz = 0 # Test addSelection and rebuild_list_references doc = FreeCAD.getDocument(self.__class__.__doc_name) obj = doc.getObject('inlet') vobj = obj.ViewObject from CfdOF.Solve import TaskPanelCfdFluidBoundary physics_model = CfdTools.getPhysicsModel(self.analysis) material_objs = CfdTools.getMaterials(self.analysis) taskd = TaskPanelCfdFluidBoundary.TaskPanelCfdFluidBoundary(obj, physics_model, material_objs) taskd.selecting_references = True taskd.faceSelector.addSelection(doc.Name, self.__class__.__part_name, 'Face1') # Give scheduled recompute a chance to happen FreeCADGui.updateGui() taskd.accept()
def addSelection(self, doc_name, obj_name, sub, selectedPoint=None): # This is the direction selection if not self.selecting_direction: # Shouldn't be here pass if FreeCADGui.activeDocument().Document.Name != self.obj.Document.Name: return selected_object = FreeCAD.getDocument(doc_name).getObject(obj_name) # On double click on a vertex of a solid sub is None and obj is the solid print('Selection: ' + selected_object.Shape.ShapeType + ' ' + selected_object.Name + ':' + sub + " @ " + str(selectedPoint)) if hasattr(selected_object, "Shape") and sub: elt = selected_object.Shape.getElement(sub) if elt.ShapeType == 'Face': selection = (selected_object.Name, sub) if self.selecting_direction: if CfdTools.is_planar(elt): self.selecting_direction = False self.form.lineDirection.setText( selection[0] + ':' + selection[1]) # TODO: Display label, not name else: FreeCAD.Console.PrintMessage('Face must be planar\n')
def _clearDocument(): ''' remove all objects from view ''' print '###########################\n######### clearing document ####' import DDADatabase DDADatabase.enableOperationObverser(False) import FreeCAD, FreeCADGui doc = FreeCAD.getDocument('DDA') if not doc: doc = FreeCAD.newDocument('DDA') else: # make sure coin objects in DG are removed import DDAGui DDAGui.clearPlayer() DDAGui.clearCalculator() for obj in doc.Objects: doc.removeObject(obj.Label) DDADatabase.enableOperationObverser(True) print '##############################'
def openIfcFile(path: str): """ Opens an IfcFile behind path. IfcOpenShell is required! """ logger.info("Opening IFC file {} in FreeCAD".format(path)) if not os.path.exists(path): logger.error("File {} could not be found. Please supply a path that"\ "exists") return OperationResults.FAILURE if not FREECAD: logger.error("I am not running inside FreeCAD. {} can only be opened"\ "inside FreeCAD") return OperationResults.FAILURE import importIFC as ifc ifc.open(path.encode("utf-8")) docName = join(os.path.basename(path).split('.')[:-1], '') App.setActiveDocument(docName) App.ActiveDocument = App.getDocument(docName) Gui.ActiveDocument = Gui.getDocument(docName) Gui.sendMsgToActiveView("ViewFit") return OperationResults.SUCCESS
def mousePressed(self, event_callback): """ mouse button event handler, calls: startEditing, endEditing, addPoint, delPoint """ event = event_callback.getEvent() if (event.getState() == coin.SoMouseButtonEvent.DOWN and event.getButton() == event.BUTTON1): #left click if not event.wasAltDown(): if self.editing is None: pos = event.getPosition() node = self.getEditNode(pos) node_idx = self.getEditNodeIndex(node) if node_idx is None: return doc = App.getDocument(str(node.documentName.getValue())) obj = doc.getObject(str(node.objectName.getValue())) self.startEditing(obj, node_idx) else: self.endEditing(self.obj, self.editing) elif event.wasAltDown(): # left click with ctrl down self.display_tracker_menu(event)
def get_document(doc): '''get_document(doc) -> FreeCAD Document get document from name or active doc if None ''' if DEBUG: print('Check.get_document(doc=%s)' % doc) if type(doc) == 'str': doc = app.getDocument(doc) #doc.recompute() if DEBUG: print('doc.Name is %s, doc.Label is %s' % (doc.Name, doc.Label)) elif doc is None: if document_presence() == 1: doc = app.activeDocument() #doc.recompute() if DEBUG: print('doc.Name is %s, doc.Label is %s' % (doc.Name, doc.Label)) else: if DEBUG: print('doc is None') pass return doc
def addSelection(self, doc_name, obj_name, sub, selectedPoint=None): """ Add the selected sub-element (face) of the part to the Reference list. Prevent selection in other document. """ if FreeCADGui.activeDocument().Document.Name != self.obj.Document.Name: return selected_object = FreeCAD.getDocument(doc_name).getObject(obj_name) # On double click on a vertex of a solid sub is None and obj is the solid tempList = list(self.obj.References) print('Selection: ' + selected_object.Shape.ShapeType + ' ' + selected_object.Name + ':' + sub + " @ " + str(selectedPoint)) if hasattr(selected_object, "Shape") and sub: elt = selected_object.Shape.getElement(sub) if elt.ShapeType == 'Face': selection = (selected_object.Name, sub) if self.selecting_references: if selection not in self.obj.References: tempList.append(selection) # If the user hasn't picked anything for direction the selected face is used as default. if self.form.lineDirection.text( ) == "" and CfdTools.is_planar(elt): self.form.lineDirection.setText(selection[0] + ':' + selection[1]) else: FreeCAD.Console.PrintMessage( selection[0] + ':' + selection[1] + ' already in reference list\n') if self.selecting_direction: if CfdTools.is_planar(elt): self.form.lineDirection.setText(selection[0] + ':' + selection[1]) self.selecting_direction = False else: FreeCAD.Console.PrintMessage('Face must be planar\n') self.obj.References = list(tempList) self.rebuild_list_references() self.update_selectionbuttons_ui()
def makePartTransparent(self, vobj): """ Make parts transparent so that the boundary conditions and cell zones are clearly visible. """ docName = str(vobj.Object.Document.Name) doc = FreeCAD.getDocument(docName) for obj in doc.Objects: if obj.isDerivedFrom("Part::Feature") and not ("CfdFluidBoundary" in obj.Name): FreeCAD.getDocument(docName).getObject( obj.Name).ViewObject.Transparency = 70 FreeCAD.getDocument(docName).getObject( obj.Name).ViewObject.LineWidth = 1 FreeCAD.getDocument(docName).getObject( obj.Name).ViewObject.LineColor = (0.5, 0.5, 0.5) FreeCAD.getDocument(docName).getObject( obj.Name).ViewObject.PointColor = (0.5, 0.5, 0.5) if obj.isDerivedFrom("Part::Feature") and ("Compound" in obj.Name): FreeCAD.getDocument(docName).getObject( obj.Name).ViewObject.Visibility = False
def Leonardo(): global PI, move, w0, w1, t, phi0, phi1, phi2, phi3, d1, d2 move.brazo(t) phi1 = move.phi1 d1 = (move.d1 ) * 100 phi2 = move.phi2 phi3 = move.phi3 d2 = (move.d2) * 100 phi0 = move.phi0 #if d1 < 50: # d1 = 70 #if d2 < 50: # d2 = 70 #primero base App.getDocument("brazo").Part__Feature001.Placement=App.Placement(App.Vector(0,0,0), App.Rotation(math.degrees(phi1),0,0), App.Vector(0,0,0)) #primera extension App.getDocument("brazo").Part__Feature002.Placement=App.Placement(App.Vector((d1+7)*math.cos(phi1),(d1+7)*math.sin(phi1),0), App.Rotation(math.degrees(phi1),0,0), App.Vector(0,0,0)) #articulacion App.getDocument("brazo").Part__Feature003.Placement=App.Placement(App.Vector((d1+208)*math.cos(phi1),(d1+208)*math.sin(phi1),0), App.Rotation(0,0,0), App.Vector(0,0,0)) #segunda base App.getDocument("brazo").Part__Feature004.Placement=App.Placement(App.Vector((d1+210)*math.cos(phi1),(d1+210)*math.sin(phi1),0), App.Rotation(math.degrees(phi1+phi2),0,0), App.Vector(0,0,0)) #segunda extension App.getDocument("brazo").Part__Feature005.Placement=App.Placement(App.Vector((d1+210)*math.cos(phi1)+d2*math.cos(phi1+phi2),(d1+210)*math.sin(phi1)+d2*math.sin(phi1+phi2),0),App.Rotation(math.degrees(phi1+phi2),0,0), App.Vector(0,0,0)) #articulacion App.getDocument("brazo").Part__Feature006.Placement=App.Placement(App.Vector((d1+210)*math.cos(phi1)+(d2+200)*math.cos(phi1+phi2),(d1+210)*math.sin(phi1)+(d2+200)*math.sin(phi1+phi2),0), App.Rotation(0,0,0), App.Vector(0,0,0)) #pinza App.getDocument("brazo").Part__Feature007.Placement=App.Placement(App.Vector((d1+210)*math.cos(phi1)+(d2+210)*math.cos(phi1+phi2),(d1+210)*math.sin(phi1)+(d2+210)*math.sin(phi1+phi2),0), App.Rotation(math.degrees(phi1+phi2+phi3),0,0), App.Vector(0,0,0)) t+=1 if t > 20000000000000: t=0
def display_tracker_menu(self, event): self.tracker_menu = QtGui.QMenu() self.event = event actions = None if self.overNode: # if user is over a node doc = self.overNode.get_doc_name() obj = App.getDocument(doc).getObject(self.overNode.get_obj_name()) ep = self.overNode.get_subelement_index() obj_gui_tools = self.get_obj_gui_tools(obj) if obj_gui_tools: actions = obj_gui_tools.get_edit_point_context_menu(obj, ep) else: # try if user is over an edited object pos = self.event.getPosition() obj = self.get_selected_obj_at_position(pos) if utils.get_type(obj) in ["Line", "Wire", "BSpline", "BezCurve"]: actions = ["add point"] elif utils.get_type(obj) in ["Circle" ] and obj.FirstAngle != obj.LastAngle: actions = ["invert arc"] if actions is None: return for a in actions: self.tracker_menu.addAction(a) self.tracker_menu.popup(Gui.getMainWindow().cursor().pos()) QtCore.QObject.connect(self.tracker_menu, QtCore.SIGNAL("triggered(QAction *)"), self.evaluate_menu_action)
def insert(nameXLSX, docname): try: theDoc = App.getDocument(docname) except NameError: theDoc = App.newDocument(docname) App.ActiveDocument = theDoc sheetDict = dict() stringList = [] z = zipfile.ZipFile(nameXLSX) theBookFile = z.open('xl/workbook.xml') theBook = xml.dom.minidom.parse(theBookFile) handleWorkBook(theBook, sheetDict, theDoc) theBook.unlink() if 'xl/sharedStrings.xml' in z.namelist(): theStringFile = z.open('xl/sharedStrings.xml') theStrings = xml.dom.minidom.parse(theStringFile) handleStrings(theStrings, stringList) theStrings.unlink() for sheetSpec in sheetDict: #print("sheetSpec: ", sheetSpec) theSheet, sheetFile = sheetDict[sheetSpec] f = z.open('xl/worksheets/' + sheetFile) myDom = xml.dom.minidom.parse(f) handleWorkSheet(myDom, theSheet, stringList) myDom.unlink() z.close() # This is needed more than once, otherwise some references are not calculated! theDoc.recompute() theDoc.recompute() theDoc.recompute()