Exemplo n.º 1
0
 def show(self):
     self.update_constraints()
     doc = self.doc_slot.input()
     if doc:
         if self.sketch is None:
             self.sketch = doc.addObject('Sketcher::SketchObject', 'Sketch')
         Gui.getDocument(doc.Name).setEdit(self.sketch.Name)
         Gui.activateWorkbench("SketcherWorkbench")
Exemplo n.º 2
0
 def tryToGetDocument(self, docName , createIfNotExist=False):
     import FreeCAD , FreeCADGui
     doc = None
     try:
         doc = FreeCADGui.getDocument(docName)
     except:
         if createIfNotExist:
             FreeCAD.newDocument(docName)
             doc =  FreeCADGui.getDocument(docName)
             #print 'create doc %s'%docName
         else:
             doc = None
     return doc
Exemplo n.º 3
0
	def draw(self):
		try:
			Gui.getDocument('yRodR')
			Gui.getDocument('yRodR').resetEdit()
			App.getDocument('yRodR').recompute()
			App.closeDocument("yRodR")
			App.setActiveDocument("")
			App.ActiveDocument=None
			Gui.ActiveDocument=None	
		except:
			pass

		#make document
		App.newDocument("yRodR")
		App.setActiveDocument("yRodR")
		App.ActiveDocument=App.getDocument("yRodR")
		Gui.ActiveDocument=Gui.getDocument("yRodR")

		#make sketch
		App.activeDocument().addObject('Sketcher::SketchObject','Sketch')
		App.activeDocument().Sketch.Placement = App.Placement(App.Vector(0.000000,0.000000,0.000000),App.Rotation(-0.707107,0.000000,0.000000,-0.707107))
		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(0,0,0),App.Vector(0,0,1),gv.yRodDiaR/2))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident',0,3,-1,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Radius',0,gv.yRodDiaR/2)) 
		App.ActiveDocument.recompute()
#		Gui.getDocument('yRodR').resetEdit()
		App.getDocument('yRodR').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.yRodLength
		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()
Exemplo n.º 4
0
def copy_part_recursive(src_obj,dst_doc,srcdstmap):
	# pylint: disable=F0401

	if src_obj.Name in srcdstmap:
		return srcdstmap[src_obj.Name]
	obj_copy = dst_doc.copyObject(src_obj)
	srcdstmap[src_obj.Name] = obj_copy
	for prop_name in src_obj.PropertiesList:
		prop = src_obj.getPropertyByName(prop_name)
		if 'ReadOnly' in src_obj.getTypeOfProperty(prop_name):
			pass
		elif isinstance(prop,tuple) or isinstance(prop,list):
			new_prop = []
			for p_item in prop:
				if isinstance(p_item,Part.Feature):
					new_prop.append(copy_part_recursive(p_item,dst_doc,srcdstmap))
				elif isinstance(p_item,Sketcher.Sketch):
					new_prop.append(dst_doc.copyObject(p_item))
				else:
					new_prop.append(p_item)
			if isinstance(prop,tuple):
				new_prop = tuple(new_prop)
			setattr(obj_copy,prop_name,new_prop)
		elif isinstance(prop,Sketcher.Sketch):
			setattr(obj_copy,prop_name,dst_doc.copyObject(prop))
		elif isinstance(prop,Part.Feature):
			setattr(obj_copy,prop_name,copy_part_recursive(prop,dst_doc,srcdstmap))
		else:
			setattr(obj_copy,prop_name,src_obj.getPropertyByName(prop_name))
	obj_copy.touch()
	gui_doc = FreeCADGui.getDocument(dst_doc.Name)
	gui_doc.getObject(obj_copy.Name).Visibility = False
	return obj_copy
Exemplo n.º 5
0
def makeSnapshotWithGui():
	from PyQt4 import QtGui
	import FreeCADGui

	def getMainWindow():
		toplevel = QtGui.qApp.topLevelWidgets()
		for i in toplevel:
			if i.metaObject().className() == "Gui::MainWindow":
				return i
		raise Exception("No main window found")

	mw=getMainWindow()
	mw.hide()
	#mw.showMinimized()

	# Create a test geometry and add it to the document
	obj=Part.makeCone(10,8,10)
	doc = FreeCAD.newDocument()
	Part.show(obj)

	# switch off animation so that the camera is moved to the final position immediately
	view = FreeCADGui.getDocument(doc.Name).activeView()
	view.setAnimationEnabled(False)
	view.viewAxometric()
	view.fitAll()
	view.saveImage('crystal.png',800,600,'Current')
	FreeCAD.closeDocument(doc.Name)
	# close the application
	QtGui.qApp.quit()
 def doubleClicked(self, vobj):
     doc = FreeCADGui.getDocument(vobj.Object.Document)
     if not doc.getInEdit():
         doc.setEdit(vobj.Object.Name)
     else:
         FreeCAD.Console.PrintError('Active Task Dialog found! Please close this one first!\n')
     return True
Exemplo n.º 7
0
	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 recompute_and_set_back_all(self):
     doc = FreeCADGui.getDocument(self.obj.Document)
     doc.Document.recompute()
     self.selectionWidget.setback_listobj_visibility()
     if self.selectionWidget.sel_server:
         FreeCADGui.Selection.removeObserver(self.selectionWidget.sel_server)
     doc.resetEdit()
Exemplo n.º 9
0
def add_part(base,params,doc):
	if isinstance(base,freecad.BaseFunction):
		module = importlib.import_module("BOLTS.freecad.%s.%s" %
			(base.collection,base.module_name))
		module.__dict__[base.name](params,doc)
	elif isinstance(base,freecad.BaseFcstd):
		#copy part to doc
		src_doc = FreeCAD.openDocument(base.path)
		src_obj = src_doc.getObject(base.objectname)
		if src_obj is None:
			raise MalformedBaseError("No object %s found" % base.objectname)
		#maps source name to destination object
		srcdstmap = {}
		dst_obj = copy_part_recursive(src_obj,doc,srcdstmap)

		#set parameters
		for obj_name,proptoparam in base.proptoparam.iteritems():
			for prop,param in proptoparam.iteritems():
				setattr(srcdstmap[obj_name],prop,params[param])

		#finish presentation
		dst_obj.touch()
		doc.recompute()
		FreeCADGui.getDocument(doc.Name).getObject(dst_obj.Name).Visibility = True
		FreeCAD.setActiveDocument(doc.Name)
		FreeCAD.closeDocument(src_doc.Name)
Exemplo n.º 10
0
    def getPoints(self):
        view=FreeCADGui.getDocument('DDA').ActiveView
        objs = view.getObjectsInfo(view.getCursorPos())
        obj = None
        for o in objs:
            if o['Object']=='ShapeModifier' or o['Object']=='ShapeMover':
                obj = o
                break
        self.__selectedAssistantNodeName = obj['Object']
        assert obj
        name , idx = Base.getRealTypeAndIndex(obj['Object'])
        print 'jointline modifier triggered by %s -> %d'%(name,idx)
        pName , pIdx = Base.getRealTypeAndIndex(obj['Component'])
        print 'jointline modifier triggered by subelement %s -> %d'%(pName,pIdx)
        object = FreeCAD.getDocument(self.docName).getObject(self.objName)
        subName , subIdx = Base.getRealTypeAndIndex(self.subElement)
        print 'jointline modifier selected sub line %s -> %d'%(subName,subIdx)

        from DDADatabase import dc_inputDatabase
        from loadDataTools import DDALine
        tmpLine = dc_inputDatabase.jointLines[subIdx-1]

        p1 = None 
        p2 = None
        if pIdx==2:
            p1 = FreeCAD.Vector(tmpLine.startPoint)
            p2 = FreeCAD.Vector(tmpLine.endPoint)
        else:  
            # pIdx==1 maybe ShapeMover or ShapeModifier, 
            # but ShapeMover doesn't care about order of p1 and p2
            p1 = FreeCAD.Vector(tmpLine.endPoint)
            p2 = FreeCAD.Vector(tmpLine.startPoint)
        return p1 , p2
Exemplo n.º 11
0
 def __addCallback(self):
     import FreeCADGui
     self.view = FreeCADGui.getDocument('DDA').ActiveView
     self.call = self.view.addEventCallback("SoEvent", self.action)
     print self.call
     assert self.call
     a=4
Exemplo n.º 12
0
    def finish(self):
        if self.center:
            import Base,FreeCADGui
            view=FreeCADGui.getDocument('DDA').ActiveView
            obj = view.getObjectInfo(view.getCursorPos())
            objName , objIdx = Base.getRealTypeAndIndex(obj['Object'])
            assert objName == 'Block'
            subName , subIdx = Base.getRealTypeAndIndex(obj['Component'])
            from DDADatabase import df_inputDatabase
            df_inputDatabase.blocks[subIdx-1].materialNo=-1
            df_inputDatabase.blocks[subIdx-1].holePointsCount+=1
#            Base.__blocksMaterials__[subIdx-1] = 11 # white color, same to the background
            FreeCAD.getDocument('DDA').getObject('Block').ViewObject.RedrawTrigger=1 # trigger colors changes
            print 'Block with hole point hided'
            
            
            ###############################
            # temporary code , for speech
            
            fps = df_inputDatabase.fixedPoints
            if len(fps)>0:
                if subIdx-1 < fps[0].blockNo:
                    for p in fps:
                        p.blockNo -=1
            
            # tepmorary code ends
            ###############################
            
        super(HolePoint,self).finish()
Exemplo n.º 13
0
 def create(self):
     if self.fileName == '' :
         FreeCAD.Console.PrintWarning("Mandatory field is empty!\n")
         return
     if not self.fileName.lower().endswith('.fcstd'):
         FreeCAD.Console.PrintWarning("Wrong file format!\n")
         return
     ##
     mainFile = FreeCAD.ActiveDocument.Label
     #
     a = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroupPython", "{0}".format(os.path.basename(self.fileName).split('.')[0]))
     mainAssemblyObject(a)
     a.File = self.fileName
     a.X = self.x
     a.Y = self.y
     a.Z = self.z
     a.RX = self.rx
     a.RY = self.ry
     a.RZ = self.rz
     viewProviderMainAssemblyObject(a.ViewObject)
     #
     try:
         FreeCADGui.ActiveDocument = FreeCADGui.getDocument(mainFile)
         FreeCADGui.ActiveDocument.activeView().viewAxometric()
         FreeCADGui.ActiveDocument.activeView().fitAll()
     except:
         pass
     FreeCAD.ActiveDocument.recompute()
Exemplo n.º 14
0
	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()
Exemplo n.º 15
0
def get_3d_data(doc,obj):
	result = {
		'facets' : [],
		'vertices' : []
	}

	if FreeCADGui:
		pos = FreeCADGui.getDocument(doc.Name).ActiveView.viewPosition().Base
		result["camera"] = {'x' : pos.x, 'y' : pos.y, 'z' : pos.z}
	else:
		result["camera"] = {'x' : 0., 'y' : 0., 'z' : 1000.}

	if obj.isDerivedFrom("Part::Feature"):
		fcmesh = obj.Shape.tessellate(0.1)
		for v in fcmesh[0]:
			result["vertices"].append((v.x,v.y,v.z))
		for f in fcmesh[1]:
			result["facets"].append(f)
	elif obj.isDerivedFrom("Mesh::Feature"):
		for p in sorted(obj.Mesh.Points,key=lambda x: x.Index):
			result["vertices"].append((p.x,p.y,p.z))
		for f in obj.Mesh.Facets:
			result["facets"].append(f.PointIndices)

	return result
Exemplo n.º 16
0
	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 = 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)
Exemplo n.º 17
0
 def doubleClicked(self, vobj):
     FreeCADGui.activateWorkbench('FemWorkbench')
     # Group meshing is only active on active analysis, we should make sure the analysis the mesh belongs too is active
     gui_doc = FreeCADGui.getDocument(vobj.Object.Document)
     if not gui_doc.getInEdit():
         # may be go the other way around and just activate the analysis the user has doubleClicked on ?!
         # not a fast one, we need to iterate over all member of all analysis to know to which analyis the object belongs too!!!
         # first check if there is an analysis in the active document
         found_an_analysis = False
         for o in gui_doc.Document.Objects:
             if o.isDerivedFrom('Fem::FemAnalysisPython'):
                     found_an_analysis = True
                     break
         if found_an_analysis:
             if FemGui.getActiveAnalysis() is not None:
                 if FemGui.getActiveAnalysis().Document is FreeCAD.ActiveDocument:
                     if self.Object in FemGui.getActiveAnalysis().Member:
                         if not gui_doc.getInEdit():
                             gui_doc.setEdit(vobj.Object.Name)
                         else:
                             FreeCAD.Console.PrintError('Activate the analysis this GMSH FEM mesh object belongs too!\n')
                     else:
                         print('GMSH FEM mesh object does not belong to the active analysis.')
                         found_mesh_analysis = False
                         for o in gui_doc.Document.Objects:
                             if o.isDerivedFrom('Fem::FemAnalysisPython'):
                                 for m in o.Member:
                                     if m == self.Object:
                                         found_mesh_analysis = True
                                         FemGui.setActiveAnalysis(o)
                                         print('The analysis the GMSH FEM mesh object belongs too was found and activated: ' + o.Name)
                                         gui_doc.setEdit(vobj.Object.Name)
                                         break
                         if not found_mesh_analysis:
                             print('GMSH FEM mesh object does not belong to an analysis. Analysis group meshing will be deactivated.')
                             gui_doc.setEdit(vobj.Object.Name)
                 else:
                     FreeCAD.Console.PrintError('Active analysis is not in active document.')
             else:
                 print('No active analysis in active document, we are going to have a look if the GMSH FEM mesh object belongs to a non active analysis.')
                 found_mesh_analysis = False
                 for o in gui_doc.Document.Objects:
                     if o.isDerivedFrom('Fem::FemAnalysisPython'):
                         for m in o.Member:
                             if m == self.Object:
                                 found_mesh_analysis = True
                                 FemGui.setActiveAnalysis(o)
                                 print('The analysis the GMSH FEM mesh object belongs to was found and activated: ' + o.Name)
                                 gui_doc.setEdit(vobj.Object.Name)
                                 break
                 if not found_mesh_analysis:
                     print('GMSH FEM mesh object does not belong to an analysis. Analysis group meshing will be deactivated.')
                     gui_doc.setEdit(vobj.Object.Name)
         else:
             print('No analysis in the active document.')
             gui_doc.setEdit(vobj.Object.Name)
     else:
         FreeCAD.Console.PrintError('Active Task Dialog found! Please close this one first!\n')
     return True
Exemplo n.º 18
0
 def accept(self):
     self.remove_active_sel_server()
     if self.has_equal_references_shape_types():
         self.obj.Material = self.material
         self.obj.References = self.references
         doc = FreeCADGui.getDocument(self.obj.Document)
         doc.resetEdit()
         doc.Document.recompute()
Exemplo n.º 19
0
	def showSo2(self,dokname):
		for l in self.lines:
			if  l[2] == 0 and l[0] !=-1:
					r=l[7]
					if r.__class__.__name__.startswith('So'):
						dok = FreeCADGui.getDocument(dokname)
						sg=dok.ActiveView.getSceneGraph()
						sg.addChild(r)
def MakeHeader(n, params):
    
    name = HeaderName(n,params)
    
    #having a period '.' character in the model name REALLY messes with things.
    docname = name.replace(".","")
    
    newdoc = FreeCAD.newDocument(docname)
    App.setActiveDocument(docname)
    Gui.ActiveDocument=Gui.getDocument(docname)
    
    pins = MakePinRow(n,params)
    
    #duplicate pin rows
    if params.rows > 1:
        for i in range(1,params.rows):
            pins = pins.union(MakePinRow(n,params).translate((0,i*params.p,0)))
    
    base = MakeBase(n,params)
        
    #assign some colors
    base_color = (50,50,50)
    pins_color = (225,175,0)

    show(base,base_color+(0,))
    show(pins,pins_color+(0,))
    
    doc = FreeCAD.ActiveDocument
        
    objs=GetListOfObjects(FreeCAD, doc)
    FuseObjs_wColors(FreeCAD, FreeCADGui,
                   doc.Name, objs[0].Name, objs[1].Name)
    doc.Label=docname
    objs=GetListOfObjects(FreeCAD, doc)
    objs[0].Label=docname
    restore_Main_Tools()

    if (params.rot !=0):
        z_RotateObject(doc, params.rot)
    
    out_dir = "./generated_pinheaders/"
    
    doc.Label = docname
    
    #save the STEP file
    exportSTEP(doc, name, out_dir)

    #save the VRML file
    scale=0.3937001
    exportVRML(doc,name,scale,out_dir)
    
    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, name,out_dir)

    Gui.SendMsgToActiveView("ViewFit")
    Gui.activeDocument().activeView().viewAxometric()

    return 0
Exemplo n.º 21
0
	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 doubleClicked(self, vobj):
     if FreeCADGui.activeWorkbench().name() != 'FemWorkbench':
         FreeCADGui.activateWorkbench("FemWorkbench")
     doc = FreeCADGui.getDocument(vobj.Object.Document)
     if not doc.getInEdit():
         doc.setEdit(vobj.Object.Name)
     else:
         FreeCAD.Console.PrintError('Active Task Dialog found! Please close this one first!\n')
     return True
Exemplo n.º 23
0
def positionZAxis():
	App.ActiveDocument=App.getDocument("PrinterAssembly")
	Gui.ActiveDocument=Gui.getDocument("PrinterAssembly")
	xShift = 0
	yShift = 0
	zShift = gv.vertBarDistBelowZRod-gv.yRodStandoff

	Draft.move(gv.zAxisParts,App.Vector(xShift, yShift, zShift),copy=False)
	App.ActiveDocument.recompute()
def symbol_EU(depx,depy):    #symbol_EU
    try:
        App.getDocument(App.ActiveDocument.Name).removeObject("Symbol_US")
    except:
        None
    try:
        App.getDocument(App.ActiveDocument.Name).removeObject("Symbol_EU")
    except:
        None
    try:
        App.getDocument(App.ActiveDocument.Name).removeObject("SymbolUS")
    except:
        None
    try:
        App.getDocument(App.ActiveDocument.Name).removeObject("SymbolEU")
    except:
        None
    App.activeDocument().addObject('Sketcher::SketchObject','Symbol_EU')
    App.activeDocument().Symbol_EU.Placement = App.Placement(App.Vector(0.0,0.0,0.0),App.Rotation(0.000000,0.000000,0.000000,1.000000))
    App.ActiveDocument.Symbol_EU.addGeometry(Part.Line(App.Vector(-7.5,0.0,0.0),App.Vector(20.0,0.0,0.0)))

    App.ActiveDocument.Symbol_EU.Placement = App.Placement(App.Vector(0.0,0.0),App.Rotation(0.000000,0.000000,0.000000,1.000000))
    App.ActiveDocument.Symbol_EU.addGeometry(Part.Line(App.Vector(12.50,-7.5,0),App.Vector(12.50,7.5,0.0)))
    App.ActiveDocument.Symbol_EU.addGeometry(Part.Circle(App.Vector(12.50,0.0,0),App.Vector(0,0,1),2.5))
    App.ActiveDocument.Symbol_EU.addGeometry(Part.Circle(App.Vector(12.50,0.0,0),App.Vector(0,0,1),5.0))

    App.ActiveDocument.Symbol_EU.addGeometry(Part.Line(App.Vector(5.0,5.0,0.0),App.Vector(-5.0,2.5,0.0)))
    App.ActiveDocument.Symbol_EU.addGeometry(Part.Line(App.Vector(-5.0,-2.5,0.0),App.Vector(-5.0,2.5,0.0)))
    App.ActiveDocument.Symbol_EU.addGeometry(Part.Line(App.Vector(5.0,-5.0,0.0),App.Vector(-5.0,-2.5,0.0)))
    App.ActiveDocument.Symbol_EU.addGeometry(Part.Line(App.Vector(5.0,-5.0,0.0),App.Vector(5.0,5.0,0.0)))
    Gui.getDocument(App.ActiveDocument.Name).resetEdit()
    FreeCADGui.getDocument(App.ActiveDocument.Name).getObject("Symbol_EU").LineColor = (0.00,0.00,0.00)
    App.ActiveDocument.recompute()

    App.activeDocument().addObject('Drawing::FeatureViewPart','SymbolEU')
    App.activeDocument().SymbolEU.Source = App.activeDocument().Symbol_EU
    App.activeDocument().SymbolEU.Direction = (0.0,0.0,1.0)
    App.activeDocument().SymbolEU.X = depx
    App.activeDocument().SymbolEU.Y = depy
    App.activeDocument().SymbolEU.Scale = 0.8
    App.activeDocument().Page.addObject(App.activeDocument().SymbolEU)
    App.ActiveDocument.recompute()
#    App.getDocument(App.ActiveDocument.Name).removeObject("Symbol_EU")
    FreeCADGui.getDocument(App.ActiveDocument.Name).getObject("Symbol_EU").Visibility = False
Exemplo n.º 25
0
    def preview(self):
        FreeCAD.Console.PrintMessage("Preview Button\n")
        computed_parts = self.compute_parts()
        preview_doc_exist = True
        try:
            FreeCAD.getDocument("preview_parts")
        except:
            preview_doc_exist = False

        if not preview_doc_exist:
            self.preview_doc = FreeCAD.newDocument("preview_parts")
        else:
            objs = self.preview_doc.Objects
            for obj in objs:
                self.preview_doc.removeObject(obj.Name)

        self.create_new_parts(self.preview_doc, computed_parts)
        FreeCADGui.getDocument(self.preview_doc.Label).ActiveView.fitAll()
        return
 def doubleClicked(self, vobj):
     doc = FreeCADGui.getDocument(vobj.Object.Document)
     if not doc.getInEdit():
         doc.setEdit(vobj.Object.Name)
     else:
         from PySide.QtGui import QMessageBox
         message = 'Active Task Dialog found! Please close this one before opening  a new one!'
         QMessageBox.critical(None, "Error in tree view", message)
         FreeCAD.Console.PrintError(message + '\n')
     return True
def make_3D_model(models_dir, model_class, modelID):

    LIST_license = ["",]

    CheckedmodelName = modelID.replace('.', '').replace('-', '_').replace('(', '').replace(')', '')
    Newdoc = App.newDocument(CheckedmodelName)
    App.setActiveDocument(CheckedmodelName)
    Gui.ActiveDocument=Gui.getDocument(CheckedmodelName)
    destination_dir = model_class.get_dest_3D_dir(modelID)
    
    material_substitutions = model_class.make_3D_model(modelID)
    modelName = model_class.get_model_name(modelID)
    
    
    doc = FreeCAD.ActiveDocument
    doc.Label = CheckedmodelName

    objs=GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedmodelName
    restore_Main_Tools()

    script_dir=os.path.dirname(os.path.realpath(__file__))
    expVRML.say(models_dir)
    out_dir=models_dir+os.sep+destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    exportSTEP(doc, modelName, out_dir)
    if LIST_license[0]=="":
        LIST_license=Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir + os.sep, modelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale=1/2.54
    #exportVRML(doc,modelName,scale,out_dir)
    del objs
    objs=GetListOfObjects(FreeCAD, doc)
    expVRML.say("######################################################################")
    expVRML.say(objs)
    expVRML.say("######################################################################")
    export_objects, used_color_keys = expVRML.determineColors(Gui, objs, material_substitutions)
    export_file_name=out_dir+os.sep+modelName+'.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale)
    #expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license)
    #scale=0.3937001
    #exportVRML(doc,modelName,scale,out_dir)
    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, modelName,out_dir)
    #display BBox
    Gui.activateWorkbench("PartWorkbench")
    Gui.SendMsgToActiveView("ViewFit")
    Gui.activeDocument().activeView().viewAxometric()
Exemplo n.º 28
0
def assemble(part):
	#Copy part from its document to the PrinterAssembly
	App.ActiveDocument=App.getDocument(part.name)
	xRodTop = App.ActiveDocument.Pad.Shape
	App.ActiveDocument=App.getDocument("PrinterAssembly")
	App.ActiveDocument.addObject('Part::Feature',part.name).Shape=xRodTop
	
	#Get handle on part in the assembly
	App.ActiveDocument=App.getDocument("PrinterAssembly")
	listOfParts = App.ActiveDocument.getObjectsByLabel(part.name)
	assemblyPart = listOfParts[-1]
	
	#Rotate and move part into position
	Gui.ActiveDocument=Gui.getDocument("PrinterAssembly")
	App.ActiveDocument=App.getDocument("PrinterAssembly")
	if part.rotateAngle:
		Draft.rotate([assemblyPart],part.rotateAngle,part.rotateCenter,part.rotateAxis,copy=False)		
	Draft.move([assemblyPart],App.Vector(part.xShift, part.yShift, part.zShift),copy=False)
	App.ActiveDocument.recompute()
	Gui.ActiveDocument=Gui.getDocument("PrinterAssembly")
 def doubleClicked(self, vobj):
     guidoc = FreeCADGui.getDocument(vobj.Object.Document)
     # check if another VP is in edit mode, https://forum.freecadweb.org/viewtopic.php?t=13077#p104702
     if not guidoc.getInEdit():
         guidoc.setEdit(vobj.Object.Name)
     else:
         from PySide.QtGui import QMessageBox
         message = 'Active Task Dialog found! Please close this one before open a new one!'
         QMessageBox.critical(None, "Error in tree view", message)
         FreeCAD.Console.PrintError(message + '\n')
     return True
def main(argmodel_to_build, argcolor_pin_mark):
    global color_pin_mark
    global model_to_build
    global excluded_pins_xmirror
    global excluded_pins_x

    color_pin_mark = argcolor_pin_mark
    model_to_build = argmodel_to_build

    if model_to_build == "all":
        variants = all_params.keys()
    else:
        variants = [model_to_build]
    for variant in variants:
        FreeCAD.Console.PrintMessage("\r\n" + variant)
        if not variant in all_params:
            print("Parameters for %s doesn't exist in 'all_params', skipping." % variant)
            continue
        ModelName = all_params[variant].modelName
        Newdoc = FreeCAD.newDocument(ModelName)
        App.setActiveDocument(ModelName)
        Gui.ActiveDocument = Gui.getDocument(ModelName)
        case, pins = make_dip(all_params[variant])
        color_attr = case_color + (0,)
        show(case, color_attr)
        # FreeCAD.Console.PrintMessage(pins_color)
        color_attr = pins_color + (0,)
        # FreeCAD.Console.PrintMessage(color_attr)
        show(pins, color_attr)
        doc = FreeCAD.ActiveDocument
        objs = GetListOfObjects(FreeCAD, doc)
        FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name)
        doc.Label = ModelName
        objs = GetListOfObjects(FreeCAD, doc)
        objs[0].Label = ModelName
        restore_Main_Tools()
        # rotate if required
        if all_params[variant].rotation != 0:
            rot = all_params[variant].rotation
            z_RotateObject(doc, rot)
        out_dir = destination_dir
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        # out_dir="./generated_qfp/"
        # export STEP model
        exportSTEP(doc, ModelName, out_dir)
        # scale and export Vrml model
        scale = 0.3937001
        exportVRML(doc, ModelName, scale, out_dir)
        # Save the doc in Native FC format
        saveFCdoc(App, Gui, doc, ModelName, out_dir)
        # display BBox

        FreeCADGui.ActiveDocument.getObject("Part__Feature").BoundingBox = True
#coding= utf-8
import time,math
# import numpy as np
import sys
# sys.path.append('C:\\Users\\apl\\Anaconda3\\Library\\bin')
sys.path.append('C:\\Users\\ap\\anaconda3\\Library\\bin')

import FreeCAD as App
import FreeCADGui as Gui
import Part, math

Gui.showMainWindow() ##只有showMainWindow 之后能够调用GUI的所有功能
App.newDocument("Unnamed")
App.setActiveDocument("Unnamed")
App.ActiveDocument=App.getDocument("Unnamed")
Gui.ActiveDocument=Gui.getDocument("Unnamed")
# Gui.activeDocument().activeView().viewDefaultOrientation()
Gui.activateWorkbench("PartWorkbench")
D_lable=" "
x=0
y=0
z=0
Rx=0
Ry=0
Rz=0
radius=5
box_l=10
cone_r=5

def make_line(p1,p2):
    object=Part.makeLine(p1,p2)
Exemplo n.º 32
0
 def gi(self):
     self.run()
     return FreeCADGui.getDocument("HoughLines")
    def accept(self):
        doc = FreeCADGui.getDocument(self.obj.Document)
        doc.resetEdit()

        # Velocity
        storeIfChanged(self.obj, 'PotentialFlow',
                       self.form.radioButtonPotentialFlowU.isChecked())
        storeIfChanged(self.obj, 'UseInletUValues',
                       self.form.radioButtonUseInletValuesU.isChecked())
        storeIfChanged(self.obj, 'Ux', getQuantity(self.form.Ux))
        storeIfChanged(self.obj, 'Uy', getQuantity(self.form.Uy))
        storeIfChanged(self.obj, 'Uz', getQuantity(self.form.Uz))

        # Pressure
        storeIfChanged(self.obj, 'UseOutletPValue',
                       self.form.radioButtonUseInletValuesP.isChecked())
        storeIfChanged(self.obj, 'PotentialFlowP',
                       self.form.radioButtonPotentialFlowP.isChecked())
        storeIfChanged(self.obj, 'Pressure', getQuantity(self.form.pressure))

        # Multiphase
        storeIfChanged(self.obj, 'VolumeFractions', self.alphas)

        # Thermal
        storeIfChanged(self.obj, 'UseInletTemperatureValue',
                       self.form.checkUseInletValuesThermal.isChecked())
        storeIfChanged(self.obj, 'Temperature',
                       getQuantity(self.form.inputTemperature))

        # Turbulence
        storeIfChanged(self.obj, 'UseInletTurbulenceValues',
                       self.form.checkUseInletValuesTurb.isChecked())
        storeIfChanged(self.obj, 'nuTilda',
                       getQuantity(self.form.inputnuTilda))
        storeIfChanged(self.obj, 'epsilon',
                       getQuantity(self.form.inputEpsilon))
        storeIfChanged(self.obj, 'omega', getQuantity(self.form.inputOmega))
        storeIfChanged(self.obj, 'k', getQuantity(self.form.inputk))
        storeIfChanged(self.obj, 'gammaInt',
                       getQuantity(self.form.inputGammaInt))
        storeIfChanged(self.obj, 'ReThetat',
                       getQuantity(self.form.inputReThetat))
        # LES
        storeIfChanged(self.obj, 'nut',
                       getQuantity(self.form.inputTurbulentViscosity))
        storeIfChanged(self.obj, 'kEqnk',
                       getQuantity(self.form.inputkEqnKineticEnergy))
        storeIfChanged(self.obj, 'kEqnNut',
                       getQuantity(self.form.inputkEqnTurbulentViscosity))

        boundaryU = self.form.comboBoundaryU.currentData()
        boundaryP = self.form.comboBoundaryP.currentData()
        boundaryT = self.form.comboBoundaryT.currentData()
        boundaryTurb = self.form.comboBoundaryTurb.currentData()

        if boundaryU and self.obj.UseInletUValues:
            if not self.obj.BoundaryU or boundaryU != self.obj.BoundaryU.Name:
                FreeCADGui.doCommand(
                    "FreeCAD.ActiveDocument.{}.BoundaryU = FreeCAD.ActiveDocument.{}"
                    .format(self.obj.Name, boundaryU))
        elif self.obj.BoundaryU:
            FreeCADGui.doCommand(
                "FreeCAD.ActiveDocument.{}.BoundaryU = None".format(
                    self.obj.Name))
        if boundaryP and self.obj.UseOutletPValue:
            if not self.obj.BoundaryP or boundaryP != self.obj.BoundaryP.Name:
                FreeCADGui.doCommand(
                    "FreeCAD.ActiveDocument.{}.BoundaryP = FreeCAD.ActiveDocument.{}"
                    .format(self.obj.Name, boundaryP))
        elif self.obj.BoundaryP:
            FreeCADGui.doCommand(
                "FreeCAD.ActiveDocument.{}.BoundaryP = None".format(
                    self.obj.Name))
        if boundaryT and self.obj.UseInletTemperatureValue:
            if not self.obj.BoundaryT or boundaryT != self.obj.BoundaryT.Name:
                FreeCADGui.doCommand(
                    "FreeCAD.ActiveDocument.{}.BoundaryT = FreeCAD.ActiveDocument.{}"
                    .format(self.obj.Name, boundaryT))
        elif self.obj.BoundaryT:
            FreeCADGui.doCommand(
                "FreeCAD.ActiveDocument.{}.BoundaryT = None".format(
                    self.obj.Name))
        if boundaryTurb and self.obj.UseInletTurbulenceValues:
            if not self.obj.BoundaryTurb or boundaryTurb != self.obj.BoundaryTurb.Name:
                FreeCADGui.doCommand(
                    "FreeCAD.ActiveDocument.{}.BoundaryTurb = FreeCAD.ActiveDocument.{}"
                    .format(self.obj.Name, boundaryTurb))
        elif self.obj.BoundaryTurb:
            FreeCADGui.doCommand(
                "FreeCAD.ActiveDocument.{}.BoundaryTurb = None".format(
                    self.obj.Name))
Exemplo n.º 34
0
    def accept(self):
        if "CfdFluidBoundary" in self.obj.Label:
            self.obj.Label = self.obj.BoundarySettings['BoundaryType']
        if self.selecting_references or self.selecting_direction:
            FreeCADGui.Selection.removeObserver(self)
        self.obj.BoundarySettings = self.BoundarySettings.copy()
        doc = FreeCADGui.getDocument(self.obj.Document)
        doc_name = str(self.obj.Document.Name)
        FreeCAD.getDocument(doc_name).recompute()
        doc.resetEdit()

        FreeCADGui.doCommand(
            "\n# Values are converted to SI units and stored (eg. m/s)")
        FreeCADGui.doCommand(
            "bc = FreeCAD.ActiveDocument.{}.BoundarySettings".format(
                self.obj.Name))
        # Type
        FreeCADGui.doCommand("bc['BoundaryType'] "
                             "= '{}'".format(
                                 self.BoundarySettings['BoundaryType']))
        FreeCADGui.doCommand("bc['BoundarySubtype'] "
                             "= '{}'".format(
                                 self.BoundarySettings['BoundarySubtype']))
        FreeCADGui.doCommand("bc['ThermalBoundaryType'] "
                             "= '{}'".format(
                                 self.BoundarySettings['ThermalBoundaryType']))
        # Velocity
        FreeCADGui.doCommand("bc['VelocityIsCartesian'] "
                             "= {}".format(
                                 self.BoundarySettings['VelocityIsCartesian']))
        FreeCADGui.doCommand("bc['Ux'] "
                             "= {}".format(self.BoundarySettings['Ux']))
        FreeCADGui.doCommand("bc['Uy'] "
                             "= {}".format(self.BoundarySettings['Uy']))
        FreeCADGui.doCommand("bc['Uz'] "
                             "= {}".format(self.BoundarySettings['Uz']))
        FreeCADGui.doCommand("bc['VelocityMag'] "
                             "= {}".format(
                                 self.BoundarySettings['VelocityMag']))
        FreeCADGui.doCommand("bc['DirectionFace'] "
                             "= '{}'".format(
                                 self.BoundarySettings['DirectionFace']))
        FreeCADGui.doCommand("bc['ReverseNormal'] "
                             "= {}".format(
                                 self.BoundarySettings['ReverseNormal']))
        FreeCADGui.doCommand("bc['MassFlowRate'] "
                             "= {}".format(
                                 self.BoundarySettings['MassFlowRate']))
        FreeCADGui.doCommand("bc['VolFlowRate'] "
                             "= {}".format(
                                 self.BoundarySettings['VolFlowRate']))
        # Presure
        FreeCADGui.doCommand("bc['Pressure'] "
                             "= {}".format(self.BoundarySettings['Pressure']))
        # Wall
        FreeCADGui.doCommand("bc['SlipRatio'] "
                             "= {}".format(self.BoundarySettings['SlipRatio']))
        # Turbulence
        FreeCADGui.doCommand(
            "bc['TurbulenceInletSpecification'] "
            "= '{}'".format(
                self.BoundarySettings['TurbulenceInletSpecification']))
        FreeCADGui.doCommand(
            "bc['TurbulentKineticEnergy'] "
            "= {}".format(self.BoundarySettings['TurbulentKineticEnergy']))
        FreeCADGui.doCommand(
            "bc['SpecificDissipationRate'] "
            "= {}".format(self.BoundarySettings['SpecificDissipationRate']))
        FreeCADGui.doCommand("bc['TurbulenceIntensity'] "
                             "= {}".format(
                                 self.BoundarySettings['TurbulenceIntensity']))
        FreeCADGui.doCommand(
            "bc['TurbulenceLengthScale'] "
            "= {}".format(self.BoundarySettings['TurbulenceLengthScale']))
        # Porous
        FreeCADGui.doCommand("bc['PressureDropCoeff'] "
                             "= {}".format(
                                 self.BoundarySettings['PressureDropCoeff']))
        FreeCADGui.doCommand("bc['ScreenWireDiameter'] "
                             "= {}".format(
                                 self.BoundarySettings['ScreenWireDiameter']))
        FreeCADGui.doCommand("bc['ScreenSpacing'] "
                             "= {}".format(
                                 self.BoundarySettings['ScreenSpacing']))
        FreeCADGui.doCommand("bc['PorousBaffleMethod'] "
                             "= {}".format(
                                 self.BoundarySettings['PorousBaffleMethod']))
        FreeCADGui.doCommand(
            "FreeCAD.ActiveDocument.{}.BoundarySettings = bc".format(
                self.obj.Name))
        FreeCADGui.doCommand("FreeCAD.ActiveDocument.{}.Label = '{}'".format(
            self.obj.Name, self.obj.Label))
        faces = []
        for ref in self.obj.References:
            faces.append(ref)
        self.obj.References = []
        for f in faces:
            FreeCADGui.doCommand(
                "FreeCAD.ActiveDocument.{}.References.append({})".format(
                    self.obj.Name, f))
        FreeCADGui.doCommand(
            "FreeCAD.getDocument('{}').recompute()".format(doc_name))
Exemplo n.º 35
0
 def reject(self):
     self.obj.shapeList = self.shapeListOrig
     FreeCADGui.doCommand("App.activeDocument().recompute()")
     doc = FreeCADGui.getDocument(self.obj.Document)
     doc.resetEdit()
Exemplo n.º 36
0
def MakeHeader(n, model, all_params):
    global formerDOC
    global LIST_license
    ModelName = model.replace('yy', "{n:02}".format(n=n))

    full_path = os.path.realpath(__file__)
    expVRML.say(full_path)
    scriptdir = os.path.dirname(os.path.realpath(__file__))
    expVRML.say(scriptdir)
    sub_path = full_path.split(scriptdir)
    expVRML.say(sub_path)
    sub_dir_name = full_path.split(os.sep)[-2]
    expVRML.say(sub_dir_name)
    sub_path = full_path.split(sub_dir_name)[0]
    expVRML.say(sub_path)
    models_dir = sub_path + "_3Dmodels"
    script_dir = os.path.dirname(os.path.realpath(__file__))
    #models_dir=script_dir+"/../_3Dmodels"
    expVRML.say(models_dir)
    out_dir = models_dir + all_params[model]['output_directory']
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace(
        '(', '').replace(')', '')

    newdoc = App.newDocument(CheckedModelName)
    App.setActiveDocument(CheckedModelName)
    App.ActiveDocument = App.getDocument(CheckedModelName)
    Gui.ActiveDocument = Gui.getDocument(CheckedModelName)

    header_type = all_params[model]['type']
    pitch = all_params[model]['pitch']
    rows = all_params[model]['rows']
    base_width = all_params[model]['base_width']
    base_height = all_params[model]['base_height']
    base_chamfer = all_params[model]['base_chamfer']
    pin_width = all_params[model]['pin_width']
    pin_length_above_base = all_params[model]['pin_length_above_base']

    pin_end_chamfer = all_params[model]['pin_end_chamfer']
    rotation = all_params[model]['rotation']

    if base_chamfer == 'auto':
        base_chamfer = pitch / 10.

    if pin_end_chamfer == 'auto':
        pin_end_chamfer = pin_width / 4.

    if header_type == 'Vertical_THT':
        pin_length_below_board = all_params[model]['pin_length_below_board']
        base = make_Vertical_THT_base(n, pitch, rows, base_width, base_height,
                                      base_chamfer)
        pins = make_Vertical_THT_pins(n, pitch, rows, pin_length_above_base,
                                      pin_length_below_board, base_height,
                                      pin_width, pin_end_chamfer)
    elif header_type == 'Horizontal_THT':
        pin_length_below_board = all_params[model]['pin_length_below_board']
        base_x_offset = all_params[model]['base_x_offset']
        base = make_Horizontal_THT_base(n, pitch, rows, base_width,
                                        base_height, base_x_offset,
                                        base_chamfer)
        pins = make_Horizontal_THT_pins(n, pitch, rows, pin_length_above_base,
                                        pin_length_below_board, base_height,
                                        base_width, pin_width, pin_end_chamfer,
                                        base_x_offset)
    elif header_type == 'Vertical_SMD':
        pin_length_horizontal = all_params[model]['pin_length_horizontal']
        base_z_offset = all_params[model]['base_z_offset']
        if rows == 1:
            pin_1_start = all_params[model]['pin_1_start']
        else:
            pin_1_start = None
        pins = make_Vertical_SMD_pins(n, pitch, rows, pin_length_above_base,
                                      pin_length_horizontal, base_height,
                                      base_width, pin_width, pin_end_chamfer,
                                      base_z_offset, pin_1_start)
        base = make_Vertical_SMD_base(n, pitch, base_width, base_height,
                                      base_chamfer, base_z_offset)
    else:
        print("Header type: ")
        print(header_type)
        print(" is not recognized, please check parameters")
        stop

    show(base)
    show(pins)

    doc = FreeCAD.ActiveDocument
    objs = GetListOfObjects(FreeCAD, doc)

    Color_Objects(Gui, objs[0], body_color)
    Color_Objects(Gui, objs[1], pins_color)
    #Color_Objects(Gui,objs[2],marking_color)

    col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0]
    col_pin = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
    #col_mark=Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]
    material_substitutions = {
        col_body[:-1]: body_color_key,
        col_pin[:-1]: pins_color_key,
        #col_mark[:-1]:marking_color_key
    }
    expVRML.say(material_substitutions)

    #objs=GetListOfObjects(FreeCAD, doc)
    FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name)
    doc.Label = CheckedModelName
    objs = GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedModelName
    restore_Main_Tools()

    if (rotation != 0):
        z_RotateObject(doc, rotation)

    doc.Label = CheckedModelName

    #save the STEP file
    exportSTEP(doc, ModelName, out_dir)
    if LIST_license[0] == "":
        LIST_license = Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale = 1 / 2.54
    #exportVRML(doc,ModelName,scale,out_dir)
    objs = GetListOfObjects(FreeCAD, doc)
    expVRML.say(
        "######################################################################"
    )
    expVRML.say(objs)
    expVRML.say(
        "######################################################################"
    )
    export_objects, used_color_keys = expVRML.determineColors(
        Gui, objs, material_substitutions)
    export_file_name = out_dir + os.sep + ModelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          LIST_license)

    #save the VRML file
    #scale=0.3937001
    #exportVRML(doc,name,scale,out_dir)

    if save_memory == False:
        Gui.SendMsgToActiveView("ViewFit")
        Gui.activeDocument().activeView().viewAxometric()

    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, ModelName, out_dir, False)

    check_Model = True
    if save_memory == True or check_Model == True:
        doc = FreeCAD.ActiveDocument
        FreeCAD.closeDocument(doc.Name)
    step_path = os.path.join(out_dir, ModelName + u'.step')
    if check_Model == True:
        #ImportGui.insert(step_path,ModelName)
        ImportGui.open(step_path)
        docu = FreeCAD.ActiveDocument
        if cq_cad_tools.checkUnion(docu) == True:
            FreeCAD.Console.PrintMessage('step file is correctly Unioned\n')
        else:
            FreeCAD.Console.PrintError('step file is not Unioned\n')
            FreeCAD.closeDocument(docu.Name)
            return 1
            #stop
        FC_majorV = int(FreeCAD.Version()[0])
        FC_minorV = int(FreeCAD.Version()[1])
        if FC_majorV == 0 and FC_minorV >= 17:
            for o in docu.Objects:
                if hasattr(o, 'Shape'):
                    chks = cq_cad_tools.checkBOP(o.Shape)
                    print(cq_cad_tools.mk_string(o.Label))
                    if chks != True:
                        msg = 'Checking shape \'' + o.Name + '\' \'' + cq_cad_tools.mk_string(
                            o.Label) + '\' failed.\n'
                        FreeCAD.Console.PrintError(msg)
                        FreeCAD.Console.PrintWarning(chks[0])
                        FreeCAD.closeDocument(docu.Name)
                        return 1
                        #stop
                    else:
                        msg = 'Checking shape \'' + o.Name + '\' \'' + cq_cad_tools.mk_string(
                            o.Label) + '\' passed.\n'
                        FreeCAD.Console.PrintMessage(msg)
        else:
            FreeCAD.Console.PrintError('BOP check requires FC 0.17+\n')
            # Save the doc in Native FC format
        saveFCdoc(App, Gui, docu, ModelName, out_dir, False)
        doc = FreeCAD.ActiveDocument
        FreeCAD.closeDocument(doc.Name)

    return 0
                color_pin_mark=True
    if model_to_build == "all":
        variants = all_params.keys()
    else:
        variants = [model_to_build]

    for variant in variants:
        FreeCAD.Console.PrintMessage('\r\n'+variant)
        if not variant in all_params:
            print("Parameters for %s doesn't exist in 'all_params', skipping." % variant)
            continue
        ModelName = all_params[variant].modelName
        CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace('(', '').replace(')', '')
        Newdoc = App.newDocument(CheckedModelName)
        App.setActiveDocument(CheckedModelName)
        Gui.ActiveDocument=Gui.getDocument(CheckedModelName)
        #body, base, mark, pins = make_radial_th(all_params[variant])
        body, base, mark, pins, top = make_radial_th(all_params[variant]) #body, base, mark, pins, top
        
        
        show(body)
        show(base)
        show(pins)
        show(mark)
        show(top)
        
        
        doc = FreeCAD.ActiveDocument
        objs = GetListOfObjects(FreeCAD, doc)

        Color_Objects(Gui,objs[0],body_color)
Exemplo n.º 38
0
 def doubleClicked(self, vobj):
     # Group meshing is only active on active analysis
     # we should make sure the analysis the mesh belongs too is active
     gui_doc = FreeCADGui.getDocument(vobj.Object.Document)
     if not gui_doc.getInEdit():
         # may be go the other way around and just activate the
         # analysis the user has doubleClicked on ?!
         # not a fast one, we need to iterate over all member of all
         # analysis to know to which analysis the object belongs too!!!
         # first check if there is an analysis in the active document
         found_an_analysis = False
         for o in gui_doc.Document.Objects:
             if o.isDerivedFrom('Fem::FemAnalysisPython'):
                 found_an_analysis = True
                 break
         if found_an_analysis:
             if FemGui.getActiveAnalysis() is not None:
                 if FemGui.getActiveAnalysis(
                 ).Document is FreeCAD.ActiveDocument:
                     if self.Object in FemGui.getActiveAnalysis().Group:
                         if not gui_doc.getInEdit():
                             gui_doc.setEdit(vobj.Object.Name)
                         else:
                             FreeCAD.Console.PrintError(
                                 'Activate the analysis this Gmsh FEM '
                                 'mesh object belongs too!\n')
                     else:
                         print(
                             'Gmsh FEM mesh object does not belong to the active analysis.'
                         )
                         found_mesh_analysis = False
                         for o in gui_doc.Document.Objects:
                             if o.isDerivedFrom('Fem::FemAnalysisPython'):
                                 for m in o.Group:
                                     if m == self.Object:
                                         found_mesh_analysis = True
                                         FemGui.setActiveAnalysis(o)
                                         print(
                                             'The analysis the Gmsh FEM mesh object '
                                             'belongs to was found and activated: {}'
                                             .format(o.Name))
                                         gui_doc.setEdit(vobj.Object.Name)
                                         break
                         if not found_mesh_analysis:
                             print(
                                 'Gmsh FEM mesh object does not belong to an analysis. '
                                 'Analysis group meshing will be deactivated.'
                             )
                             gui_doc.setEdit(vobj.Object.Name)
                 else:
                     FreeCAD.Console.PrintError(
                         'Active analysis is not in active document.')
             else:
                 print(
                     'No active analysis in active document, '
                     'we are going to have a look if the Gmsh FEM mesh object '
                     'belongs to a non active analysis.')
                 found_mesh_analysis = False
                 for o in gui_doc.Document.Objects:
                     if o.isDerivedFrom('Fem::FemAnalysisPython'):
                         for m in o.Group:
                             if m == self.Object:
                                 found_mesh_analysis = True
                                 FemGui.setActiveAnalysis(o)
                                 print(
                                     'The analysis the Gmsh FEM mesh object '
                                     'belongs to was found and activated: {}'
                                     .format(o.Name))
                                 gui_doc.setEdit(vobj.Object.Name)
                                 break
                 if not found_mesh_analysis:
                     print(
                         'Gmsh FEM mesh object does not belong to an analysis. '
                         'Analysis group meshing will be deactivated.')
                     gui_doc.setEdit(vobj.Object.Name)
         else:
             print('No analysis in the active document.')
             gui_doc.setEdit(vobj.Object.Name)
     else:
         from PySide.QtGui import QMessageBox
         message = 'Active Task Dialog found! Please close this one before opening  a new one!'
         QMessageBox.critical(None, "Error in tree view", message)
         FreeCAD.Console.PrintError(message + '\n')
     return True
Exemplo n.º 39
0
 def reject(self):
     self.setback_listobj_visibility()
     self.remove_active_sel_server()
     doc = FreeCADGui.getDocument(self.obj.Document)
     doc.resetEdit()
Exemplo n.º 40
0
def exportAssembly():
    doc = FreeCAD.ActiveDocument

    tmpobjs = []
    objs = []
    for i in doc.Objects:
        if not i.ViewObject.Visibility or not hasattr(i,'Shape') or not hasattr(i,'Proxy'):
            continue
        if hasattr(i.Proxy, "Type") and i.Proxy.Type in [['PCBannotation'], 'PCBpart_E']:
            continue
        if not i.isDerivedFrom("Sketcher::SketchObject") and len(i.Shape.Solids):

            # We are trying to combining all objects into one single compound object. However,
            # FreeCAD has a bug such that after compound, it will sometimes refuse to display
            # any color if the compound contain some overlapped pads with holes, even though
            # the color of all faces stored in DiffuseColor is still intact. 
            # 
            # The walkaround is to explode the pad object, and recombine all the solid inside
            # using 'Part::Compound'. 
            #
            # Only apply this trick to layerSilkObject(pads) and layerPathObject(path) and 
            # having holes.
            if not doc.Board.Display or len(i.Shape.Solids)==1 or \
                    (i.Proxy.__class__.__name__ != 'layerSilkObject' and \
                     i.Proxy.__class__.__name__ != 'layerPathObject') :
                objs.append(i)
                continue
            subobjs = []
            for j in i.Shape.Solids:
                tmpobj = doc.addObject('Part::Feature','obj')
                tmpobj.Shape = j
                tmpobj.ViewObject.ShapeColor = i.ViewObject.ShapeColor
                tmpobjs.append(tmpobj)
                subobjs.append(tmpobj)
            subobj = doc.addObject('Part::Compound','obj')
            subobj.Links = subobjs
            objs.append(subobj)
            tmpobjs.append(subobj)

    if not len(objs):
        FreeCAD.Console.PrintWarning('no parts found')
        return
    obj = doc.addObject('Part::Compound','Compound')
    obj.Links = objs
    doc.recompute()
    tmpobjs.append(obj)

    import random
    newDoc = FreeCAD.newDocument(doc.Name+'_'+str(random.randrange(10000,99999)))

    copy = newDoc.addObject('Part::Feature','Compound')
    copy.Shape = obj.Shape
    copy.ViewObject.DiffuseColor = obj.ViewObject.DiffuseColor
    copy.ViewObject.DisplayMode = 'Shaded'
    newDoc.recompute()

    for i in objs:
        i.ViewObject.Visibility = True
    for i in reversed(tmpobjs):
        doc.removeObject(i.Name)

    view = FreeCADGui.getDocument(newDoc.Name).activeView()
    view.viewAxometric()
    view.fitAll()
Exemplo n.º 41
0
    def Activated(self):

        # you need two documents open, containing BIM objects with same IDs
        # make the main doc the active one before running this script!

        # what will be compared: IDs, geometry, materials. Everything else is discarded.

        MOVE_TOLERANCE = 0.2  # the max allowed move in mm
        VOL_TOLERANCE = 250  # the max allowed volume diff in mm^3

        documents = FreeCAD.listDocuments()

        if len(documents) == 2:

            reply = QtGui.QMessageBox.question(
                None, "",
                translate(
                    "BIM",
                    "The document currently viewed must be your main one. The other contains newer objects that you wish to merge into this one. Make sure only the objects you wish to compare are visible in both. Proceed?"
                ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                QtGui.QMessageBox.No)
            if reply == QtGui.QMessageBox.Yes:

                activedoc = FreeCAD.ActiveDocument
                if list(documents.keys())[0] == activedoc.Name:
                    otherdoc = list(documents.values())[1]
                else:
                    otherdoc = list(documents.values())[0]

                # build lists of BIM objects with IFC ID

                objswithoutid = []  # let's try to match these later on

                activedocids = {}  # main document, the original freecad one
                for obj in activedoc.Objects:
                    if hasattr(obj, "IfcData") and obj.ViewObject.Visibility:
                        if "IfcUID" in obj.IfcData:
                            activedocids[obj.IfcData["IfcUID"]] = obj
                        elif obj.isDerivedFrom(
                                "Part::Feature"):  # discard BuildingParts
                            objswithoutid.append(obj)

                otherdocids = {}  # other doc to be merged to the main one
                for obj in otherdoc.Objects:
                    if hasattr(obj, "IfcData") and obj.ViewObject.Visibility:
                        if "IfcUID" in obj.IfcData:
                            otherdocids[obj.IfcData["IfcUID"]] = obj

                toselect = []  # objects to select when finished
                additions = []  # objects added
                subtractions = []  # objects subtracted
                modified = []  # objects modified
                moved = []  # objects moved
                matchanged = []  # object is same, but material changed
                matchangedghost = [
                ]  # store shapes of objects whose material has changed to print a blue ghost later on
                renamed = {}  # object label changes
                propertieschanged = {
                }  # objects whose IFC properties are different

                for id, obj in otherdocids.items():
                    if id in activedocids:
                        # this object already exists
                        mainobj = activedocids[id]
                        if obj.Label != mainobj.Label:
                            # object has a different name
                            renamed[mainobj.Name] = obj.Label
                        if obj.IfcProperties and (obj.IfcProperties !=
                                                  mainobj.IfcProperties):
                            # properties have changed
                            propertieschanged[id] = obj.IfcProperties
                        if hasattr(obj, "Shape") and hasattr(mainobj, "Shape"):
                            v = abs(obj.Shape.Volume - mainobj.Shape.Volume)
                            if v < VOL_TOLERANCE:
                                # identical volume
                                l = (obj.Shape.BoundBox.Center.sub(
                                    mainobj.Shape.BoundBox.Center)).Length
                                if l < MOVE_TOLERANCE:
                                    # identical position
                                    if abs(obj.Shape.BoundBox.XMin - mainobj.Shape.BoundBox.XMin) < MOVE_TOLERANCE and \
                                       abs(obj.Shape.BoundBox.YMin - mainobj.Shape.BoundBox.YMin) < MOVE_TOLERANCE and \
                                       abs(obj.Shape.BoundBox.YMin - mainobj.Shape.BoundBox.YMin) < MOVE_TOLERANCE:
                                        # same boundbox
                                        if hasattr(obj, "Material") and hasattr(
                                                mainobj, "Material") and (
                                                    obj.Material
                                                    and mainobj.Material and
                                                    (obj.Material.Label
                                                     == mainobj.Material.Label)
                                                ) or (obj.Material
                                                      == mainobj.Material):
                                            # same material names
                                            obj.ViewObject.hide()
                                        else:
                                            print("Object", mainobj.Label,
                                                  "material has changed")
                                            obj.ViewObject.hide(
                                            )  # we hide these objects since the shape hasn't changed but we keep their shapes
                                            matchangedghost.append(obj.Shape)
                                            matchanged.append(obj)
                                    else:
                                        print("Object", mainobj.Label,
                                              "shape bound box has changed")
                                        toselect.append(obj)
                                        modified.append(obj)
                                else:
                                    print("Object", mainobj.Label,
                                          "position has moved by", l, "mm")
                                    toselect.append(obj)
                                    moved.append(obj)
                            else:
                                print("Object", mainobj.Label,
                                      "shape has changed by", v, "mm^3")
                                toselect.append(obj)
                                modified.append(obj)
                        else:
                            print("Object", mainobj.Label,
                                  "one of the objects has no shape")
                            toselect.append(obj)
                    else:
                        print("Object", obj.Label,
                              "doesn't exist yet in main doc")
                        toselect.append(obj)
                        additions.append(obj)

                for id, obj in activedocids.items():
                    if not id in otherdocids:
                        if obj.isDerivedFrom(
                                "Part::Feature"):  # don't count building parts
                            print("Object", obj.Label,
                                  "doesn't exist anymore in new doc")
                            subtractions.append(obj)

                # try to find our objects without ID
                newids = {}
                for obj in objswithoutid:
                    for id, otherobj in otherdocids.items():
                        if not id in activedocids:
                            if abs(otherobj.Shape.Volume -
                                   obj.Shape.Volume) < VOL_TOLERANCE:
                                if (otherobj.Shape.BoundBox.Center.sub(
                                        obj.Shape.BoundBox.Center)
                                    ).Length < MOVE_TOLERANCE:
                                    if abs(obj.Shape.BoundBox.XMin - otherobj.Shape.BoundBox.XMin) < MOVE_TOLERANCE and \
                                       abs(obj.Shape.BoundBox.YMin - otherobj.Shape.BoundBox.YMin) < MOVE_TOLERANCE and \
                                       abs(obj.Shape.BoundBox.YMin - otherobj.Shape.BoundBox.YMin) < MOVE_TOLERANCE:
                                        # shapes are identical. It's the same object!
                                        newids[obj.Name] = id
                                        break
                    else:
                        print("Object", obj.Label,
                              "has no ID and wasn't found in the new doc")
                        subtractions.append(obj)

                matnames = {}  # existing materials
                for obj in activedoc.Objects:
                    if Draft.getType(obj) == "Material":
                        matnames[obj.Label] = obj

                newmats = {}  # new materials
                for obj in otherdoc.Objects:
                    if Draft.getType(obj) == "Material":
                        if not obj.Label in matnames:
                            print("Material", obj.Label,
                                  "doesn't exist in main doc")
                            toselect.append(obj)
                            newmats[obj.Label] = obj

                if newmats:
                    group = otherdoc.addObject("App::DocumentObjectGroup",
                                               "New_materials")
                    for newmat in newmats.values():
                        group.addObject(newmat)

                if toselect:
                    FreeCAD.setActiveDocument(otherdoc.Name)
                    FreeCAD.ActiveDocument = FreeCADGui.getDocument(
                        otherdoc.Name)
                    FreeCADGui.ActiveDocument = FreeCADGui.getDocument(
                        otherdoc.Name)
                    FreeCADGui.Selection.clearSelection()
                    for obj in toselect:
                        FreeCADGui.Selection.addSelection(obj)

                if additions:
                    shape = Part.makeCompound([a.Shape for a in additions])
                    obj = activedoc.addObject("Part::Feature", "Additions")
                    obj.Shape = shape
                    obj.ViewObject.LineWidth = 5
                    obj.ViewObject.LineColor = (0.0, 1.0, 0.0)
                    obj.ViewObject.ShapeColor = (0.0, 1.0, 0.0)
                    obj.ViewObject.Transparency = 60

                if subtractions:
                    shape = Part.makeCompound([s.Shape for s in subtractions])
                    obj = activedoc.addObject("Part::Feature", "Subtractions")
                    obj.Shape = shape
                    obj.ViewObject.LineWidth = 5
                    obj.ViewObject.LineColor = (1.0, 0.0, 0.0)
                    obj.ViewObject.ShapeColor = (1.0, 0.0, 0.0)
                    obj.ViewObject.Transparency = 60

                if modified:
                    shape = Part.makeCompound([m.Shape for m in modified])
                    obj = activedoc.addObject("Part::Feature", "Modified")
                    obj.Shape = shape
                    obj.ViewObject.LineWidth = 5
                    obj.ViewObject.LineColor = (1.0, 0.5, 0.0)
                    obj.ViewObject.ShapeColor = (1.0, 0.5, 0.0)
                    obj.ViewObject.Transparency = 60

                if moved:
                    shape = Part.makeCompound([m.Shape for m in moved])
                    obj = activedoc.addObject("Part::Feature", "Moved")
                    obj.Shape = shape
                    obj.ViewObject.LineWidth = 5
                    obj.ViewObject.LineColor = (1.0, 1.0, 0.0)
                    obj.ViewObject.ShapeColor = (1.0, 1.0, 0.0)
                    obj.ViewObject.Transparency = 60

                if matchangedghost:
                    shape = Part.makeCompound(matchangedghost)
                    obj = otherdoc.addObject("Part::Feature",
                                             "Material_changed")
                    obj.Shape = shape
                    obj.ViewObject.LineWidth = 1
                    obj.ViewObject.LineColor = (0.0, 0.0, 1.0)
                    obj.ViewObject.ShapeColor = (0.0, 0.0, 1.0)
                    obj.ViewObject.Transparency = 90

                if matchanged:
                    reply = QtGui.QMessageBox.question(
                        None, "",
                        str(len(matchanged)) + " " + translate(
                            "BIM",
                            "objects still have the same shape but have a different material. Do you wish to update them in the main document?"
                        ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                        QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        for obj in matchanged:
                            mat = obj.Material
                            if mat:
                                mainobj = activedocids[obj.IfcData["IfcUID"]]
                                if mainobj.Material:
                                    mainmatlabel = mainobj.Material.Label
                                else:
                                    mainmatlabel = "None"
                                if mat.Label in matnames:
                                    # the new material already exists, just change it
                                    print("Changing material of",
                                          mainobj.Label, "from", mainmatlabel,
                                          "to", mat.Label)
                                    mainobj.Material = matnames[mat.Label]
                                else:
                                    # copy the material over
                                    newmat = activedoc.addObject(
                                        "App::MaterialObjectPython",
                                        "Material")
                                    newmat.Label = mat.Label
                                    import ArchMaterial
                                    ArchMaterial._ArchMaterial(newmat)
                                    ArchMaterial._ViewProviderArchMaterial(
                                        newmat.ViewObject)
                                    newmat.Material = mat.Material
                                    print("Changing material of",
                                          mainobj.Label, "from", mainmatlabel,
                                          "to", newmat.Label)
                                    mainobj.Material = newmat
                                    matnames[newmat.Label] = newmat

                if newids:
                    reply = QtGui.QMessageBox.question(
                        None, "",
                        str(len(newids)) + " " + translate(
                            "BIM",
                            "objects have no IFC ID in the main document, but an identical object with an ID exists in the new document. Transfer these IDs to the original objects?"
                        ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                        QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        for name, id in newids.items():
                            obj = activedoc.getObject(name)
                            if obj:
                                print("Transferring new id to object",
                                      obj.Label)
                                a = obj.IfcData
                                a["IfcUID"] = id
                                obj.IfcData = a

                if renamed:
                    reply = QtGui.QMessageBox.question(
                        None, "",
                        str(len(renamed)) + " " + translate(
                            "BIM",
                            "objects had their name changed. Rename them?"),
                        QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                        QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        for name, label in renamed.items():
                            obj = activedoc.getObject(name)
                            if obj:
                                print("Renaming object", obj.Label, "to",
                                      label)
                                obj.Label = label

                if propertieschanged:
                    reply = QtGui.QMessageBox.question(
                        None, "",
                        str(len(propertieschanged)) + " " + translate(
                            "BIM",
                            "objects had their properties changed. Update?"),
                        QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                        QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        for id, prop in propertieschanged.items():
                            obj = activedocids[id]
                            print("Updating properties of ", obj.Label)
                            obj.IfcProperties = prop

                if moved:
                    reply = QtGui.QMessageBox.question(
                        None, "",
                        str(len(moved)) + " " + translate(
                            "BIM",
                            "objects have their location changed. Move them to their new position?"
                        ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                        QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        for obj in moved:
                            mainobj = activedocids[obj.IfcData["IfcUID"]]
                            otherobj = otherdocids[obj.IfcData["IfcUID"]]
                            delta = otherobj.Shape.BoundBox.Center.sub(
                                mainobj.Shape.BoundBox.Center)
                            print("Moving object ", mainobj.Label)
                            Draft.move(mainobj, delta)
                    reply = QtGui.QMessageBox.question(
                        None, "",
                        translate(
                            "BIM",
                            "Do you wish to colorize the objects that have moved in yellow in the other file (to serve as a diff)?"
                        ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                        QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        for obj in moved:
                            otherobj = otherdocids[obj.IfcData["IfcUID"]]
                            try:
                                otherobj.ViewObject.LineColor = (1.0, 1.0, 0.0)
                                otherobj.ViewObject.ShapeColor = (1.0, 1.0,
                                                                  0.0)
                                otherobj.ViewObject.Transparency = 60
                            except:
                                print(otherobj.Label, "cannot be colorized")

                if modified:
                    reply = QtGui.QMessageBox.question(
                        None, "",
                        translate(
                            "BIM",
                            "Do you wish to colorize the objects that have been modified in orange in the other file (to serve as a diff)?"
                        ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                        QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        for obj in modified:
                            otherobj = otherdocids[obj.IfcData["IfcUID"]]
                            try:
                                otherobj.ViewObject.LineColor = (1.0, 0.5, 0.0)
                                otherobj.ViewObject.ShapeColor = (1.0, 0.5,
                                                                  0.0)
                                otherobj.ViewObject.Transparency = 60
                            except:
                                print(otherobj.Label, "cannot be colorized")

                if subtractions:
                    reply = QtGui.QMessageBox.question(
                        None, "",
                        str(len(subtractions)) + " " + translate(
                            "BIM",
                            "objects don't exist anymore in the new document. Move them to a 'To Delete' group?"
                        ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                        QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        group = activedoc.addObject("App::DocumentObjectGroup",
                                                    "ToDelete")
                        group.Label = "To Delete"
                        for obj in subtractions:
                            group.addObject(obj)
                    reply = QtGui.QMessageBox.question(
                        None, "",
                        translate(
                            "BIM",
                            "Do you wish to colorize the objects that have been removed in red in the other file (to serve as a diff)?"
                        ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                        QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        for obj in subtractions:
                            otherobj = otherdoc.addObject(
                                "Part::Feature", "Deleted")
                            otherobj.Shape = obj.Shape
                            otherobj.ViewObject.LineColor = (1.0, 0.0, 0.0)
                            otherobj.ViewObject.ShapeColor = (1.0, 0.0, 0.0)
                            otherobj.ViewObject.Transparency = 60

                if additions:
                    reply = QtGui.QMessageBox.question(
                        None, "",
                        translate(
                            "BIM",
                            "Do you wish to colorize the objects that have been added in green in the other file (to serve as a diff)?"
                        ), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                        QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        for obj in additions:
                            otherobj = otherdocids[obj.IfcData["IfcUID"]]
                            try:
                                otherobj.ViewObject.LineColor = (0.0, 1.0, 0.0)
                                otherobj.ViewObject.ShapeColor = (0.0, 1.0,
                                                                  0.0)
                                otherobj.ViewObject.Transparency = 60
                            except:
                                print(otherobj.Label, "cannot be colorized")

        else:
            reply = QtGui.QMessageBox.information(
                None, "",
                translate(
                    "BIM",
                    "You need two documents open to run this tool. One which is your main document, and one that contains new objects that you wish to compare against the existing one. Make sure only the objects you wish to compare in both documents are visible."
                ))
Exemplo n.º 42
0
    def loadTemplate(self):
        """loads the contents of a template into the current file"""

        import FreeCADGui
        from PySide import QtCore, QtGui
        filename = QtGui.QFileDialog.getOpenFileName(
            QtGui.QApplication.activeWindow(),
            translate("BIM", "Open template file"), None,
            "FreeCAD file (*.FCStd)")
        if filename:
            filename = filename[0]
            if FreeCAD.ActiveDocument:
                d = FreeCAD.ActiveDocument
                td = FreeCAD.openDocument(filename, True)  #hidden
                tname = td.Name
                values = td.Meta
                FreeCAD.closeDocument(tname)
                d.mergeProject(filename)
                FreeCADGui.ActiveDocument = FreeCADGui.getDocument(
                    d.Name)  # fix b/c hidden doc
            else:
                d = FreeCAD.openDocument(filename)
                FreeCAD.ActiveDocument = d
                values = d.Meta
            bimunit = 0
            if hasattr(FreeCAD, "DraftWorkingPlane"):
                from FreeCAD import Vector
                if "wppos" in values:
                    FreeCAD.DraftWorkingPlane.position = eval(
                        values["wpposition"])
                if "wpu" in values:
                    FreeCAD.DraftWorkingPlane.u = eval(values["wpu"])
                if "wpv" in values:
                    FreeCAD.DraftWorkingPlane.v = eval(values["wpv"])
                if "wpaxis" in values:
                    FreeCAD.DraftWorkingPlane.axis = eval(values["wpaxis"])
            if "unit" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Units").SetInt(
                        "UserSchema", int(values["unit"]))
                if hasattr(FreeCAD.Units, "setSchema"):
                    FreeCAD.Units.setSchema(int(values["unit"]))
                    bimunit = [0, 2, 3, 3, 1, 5, 0, 4][int(values["unit"])]
            if "textsize" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetFloat(
                        "textheight", float(values["textsize"]))
                if hasattr(FreeCADGui, "draftToolBar"):
                    FreeCADGui.draftToolBar.fontsizeButton.setValue(
                        float(values["textsize"]))
            if "textfont" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetString(
                        "textfont", values["textfont"])
            if "dimstyle" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetInt(
                        "dimsymbol", int(values["dimstyle"]))
            if "arrowsize" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetFloat(
                        "arrowsize", float(values["arrowsize"]))
            if "decimals" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Units").SetInt(
                        "Decimals", int(values["decimals"]))
            if "grid" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetFloat(
                        "gridSpacing", float(values["grid"]))
            if "squares" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Draft").SetInt(
                        "gridEvery", int(values["squares"]))
            if hasattr(FreeCADGui, "Snapper"):
                FreeCADGui.Snapper.setGrid()
            if "linewidth" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/View").SetInt(
                        "DefautShapeLineWidth", int(values["linewidth"]))
                if hasattr(FreeCADGui, "draftToolBar"):
                    FreeCADGui.draftToolBar.widthButton.setValue(
                        int(values["linewidth"]))
            if "colFace" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/View").SetUnsigned(
                        "DefaultShapeColor", int(values["colFace"]))
            if "colLine" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/View").SetUnsigned(
                        "DefaultShapeLineColor", int(values["colLine"]))
            if "colHelp" in values:
                FreeCAD.ParamGet(
                    "User parameter:BaseApp/Preferences/Mod/Arch").SetUnsigned(
                        "ColorHelpers", int(values["colHelp"]))
            if "colConst" in values:
                FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft"
                                 ).SetUnsigned("constructioncolor",
                                               int(values["colConst"]))

            # set the status bar widgets
            mw = FreeCADGui.getMainWindow()
            if mw:
                st = mw.statusBar()
                statuswidget = st.findChild(QtGui.QToolBar, "BIMStatusWidget")
                if statuswidget:
                    statuswidget.unitLabel.setText(
                        statuswidget.unitsList[bimunit])
                    # change the unit of the nudge button
                    nudgeactions = statuswidget.nudge.menu().actions()
                    if bimunit in [2, 3, 5, 7]:
                        nudgelabels = statuswidget.nudgeLabelsI
                    else:
                        nudgelabels = statuswidget.nudgeLabelsM
                    for i in range(len(nudgelabels)):
                        nudgeactions[i].setText(nudgelabels[i])
                    if not "auto" in statuswidget.nudge.text().replace(
                            "&", "").lower():
                        statuswidget.nudge.setText(
                            FreeCAD.Units.Quantity(
                                statuswidget.nudge.text().replace(
                                    "&", "")).UserString)

            FreeCAD.Console.PrintMessage(
                translate(
                    "BIM",
                    "Template successfully loaded into current document") +
                "\n")
            self.reject()
Exemplo n.º 43
0
 def reject(self):
     self.remove_active_sel_server()
     doc = FreeCADGui.getDocument(self.obj.Document)
     doc.resetEdit()
Exemplo n.º 44
0
    def execute(self, fp):
        if fp.need_recompute:
            fp.need_recompute = False

            document = fp.Document
            if len(fp.fromParts) > 0:
                groupObj = fp.fromParts[0]
            else:
                groupObj = document.addObject("App::DocumentObjectGroup",
                                              str(fp.Name) + "_origin_parts")

            subObjectList = groupObj.Group
            for subObj in subObjectList:
                groupObj.removeObject(subObj)

            fp.fromParts = []
            parts = []
            freedac_origin_obj = []
            freedac_origin_obj.append(groupObj)
            for part in fp.parts.lst:
                cp_part = copy.deepcopy(part)
                freecad_obj = document.getObject(cp_part.name)
                freedac_origin_obj.append(freecad_obj)
                cp_part.recomputeInit(freecad_obj)
                groupObj.addObject(freecad_obj)
                parts.append(cp_part)

            fp.fromParts = freedac_origin_obj

            tabs = []
            for tab in fp.faces.lst:
                cp_tab = copy.deepcopy(tab)
                freecad_obj = document.getObject(cp_tab.freecad_obj_name)
                freecad_face = document.getObject(
                    cp_tab.freecad_obj_name).Shape.getElement(cp_tab.face_name)
                cp_tab.recomputeInit(freecad_obj, freecad_face)
                tabs.append(cp_tab)

            computed_parts = make_tabs_joins(parts, tabs)

            previous_nameMapping = copy.copy(fp.namesMapping)
            fp.namesMapping.clear()

            freecad_obj_generated = []
            freecad_objname_tokeep = []
            for part in computed_parts:
                if part.get_new_name() in previous_nameMapping:
                    freecad_obj = document.getObject(
                        previous_nameMapping[part.get_new_name()])
                else:
                    freecad_obj = document.addObject("Part::Feature",
                                                     part.get_new_name())
                fp.namesMapping[part.get_new_name()] = freecad_obj.Name
                freecad_obj.Shape = part.get_shape()
                freecad_objname_tokeep.append(freecad_obj.Name)
                freecad_obj_generated.append(freecad_obj)

            for part in fp.generatedParts:
                if part.Name not in freecad_objname_tokeep:
                    document.removeObject(part.Name)

            fp.generatedParts = freecad_obj_generated
            fp.edit = False

            FreeCADGui.getDocument(document.Name).ActiveView.fitAll()
            document.recompute()
Exemplo n.º 45
0
 def recompute_and_set_back_all(self):
     guidoc = FreeCADGui.getDocument(self.obj.Document)
     guidoc.Document.recompute()
     guidoc.resetEdit()
     self.output_obj_mat_param()
Exemplo n.º 46
0
	def draw(self):
		try:
			Gui.getDocument(self.name)
			Gui.getDocument(self.name).resetEdit()
			App.getDocument(self.name).recompute()
			App.closeDocument(self.name)
			App.setActiveDocument("")
			App.ActiveDocument=None
			Gui.ActiveDocument=None	
		except:
			pass

		#make document
		App.newDocument(self.name)
		App.setActiveDocument(self.name)
		App.ActiveDocument=App.getDocument(self.name)
		Gui.ActiveDocument=Gui.getDocument(self.name)
		
		#extrude crossBarTop
		uf.extrudeFrameMember(self.name, gv.crossBarLength)

		if gv.zMotorMountLocation == "Bottom":
			return
					
		#Make Holes for zMotorMount plates
		#Sketch points
		p1x = 0
		p1y = 0
		p2x = p1x
		p2y = gv.frameWidth/2+gv.zRodZScrewDist-gv.zMotorMountPlateWidth/4
		p3x = p1x
		p3y = gv.frameWidth/2+gv.zRodZScrewDist+gv.zMotorMountPlateWidth/4
		p4x = p1x
		p4y = gv.crossBarLength - (gv.frameWidth/2+gv.zRodZScrewDist+gv.zMotorMountPlateWidth/4)
		p5x = p1x
		p5y = gv.crossBarLength - (gv.frameWidth/2+gv.zRodZScrewDist-gv.zMotorMountPlateWidth/4)
		p6x = p1x
		p6y = gv.crossBarLength
		
		#Make Sketch
		App.activeDocument().addObject('Sketcher::SketchObject','Sketch001')
		App.activeDocument().Sketch001.Support = (App.ActiveDocument.Pad,["Face2"])
		App.activeDocument().recompute()
#		Gui.activeDocument().setEdit('Sketch001')
		App.ActiveDocument.Sketch001.addExternal("Pad","Edge7")
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p1x,p1y,0),App.Vector(p2x,p2y,0)))
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',-1,1,0,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',0)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p2x,p2y,0),App.Vector(p3x,p3y,0)))
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',0,2,1,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p3x,p3y,0),App.Vector(p4x,p4y,0)))
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',1,2,2,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p4x,p4y,0),App.Vector(p5x,p5y,0)))
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',2,2,3,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',3)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p5x,p5y,0),App.Vector(p6x,p6y,0)))
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',3,2,4,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('PointOnObject',4,2,-3)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',4)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',1,3)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',4,0)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.toggleConstruction(0) 
		App.ActiveDocument.Sketch001.toggleConstruction(1) 
		App.ActiveDocument.Sketch001.toggleConstruction(2) 
		App.ActiveDocument.Sketch001.toggleConstruction(3) 
		App.ActiveDocument.Sketch001.toggleConstruction(4) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Circle(App.Vector(p2x,p2y,0),App.Vector(0,0,1),gv.mountToFrameDia/2))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',5,3,0,2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Circle(App.Vector(p3x,p3y,0),App.Vector(0,0,1),gv.mountToFrameDia/2))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',6,3,1,2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Circle(App.Vector(p4x,p4y,0),App.Vector(0,0,1),gv.mountToFrameDia/2))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',7,3,2,2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addGeometry(Part.Circle(App.Vector(p5x,p5y,0),App.Vector(0,0,1),gv.mountToFrameDia/2))
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',8,3,3,2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',8,7)) 
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',7,6)) 
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',6,5)) 
		App.ActiveDocument.recompute()
		
		#Add Dimensions
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Radius',8,gv.mountToFrameDia/2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('DistanceY',3,gv.zMotorMountPlateWidth/2)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('DistanceY',4,p2y)) 
		App.ActiveDocument.recompute()
#		Gui.getDocument(self.name).resetEdit()
		App.getDocument(self.name).recompute()
		
		#Cut holes through All
		App.activeDocument().addObject("PartDesign::Pocket","Pocket")
		App.activeDocument().Pocket.Sketch = App.activeDocument().Sketch001
		App.activeDocument().Pocket.Length = 5.0
		App.ActiveDocument.recompute()
		Gui.activeDocument().hide("Sketch001")
		Gui.activeDocument().hide("Pad")
#		Gui.ActiveDocument.Pocket.ShapeColor=Gui.ActiveDocument.Pad.ShapeColor
#		Gui.ActiveDocument.Pocket.LineColor=Gui.ActiveDocument.Pad.LineColor
#		Gui.ActiveDocument.Pocket.PointColor=Gui.ActiveDocument.Pad.PointColor
		App.ActiveDocument.Pocket.Length = 5.000000
		App.ActiveDocument.Pocket.Type = 1
		App.ActiveDocument.Pocket.UpToFace = None
		App.ActiveDocument.recompute()
Exemplo n.º 47
0
def make_3D_model(models_dir, model_class, modelName):
    r"""Creates a 3D model and exports it to STEO and VRML.
    :param models_dir: directory name for STEP and VRML 3D model file export
    :type  models_dir: ``string``
    :param model_class: Class containing functions and parameter to generate the 3D model
    :type  model_class: ``class``
    :param modelName: The KiCad file name of the 3D model. 
    :type  modelName: ``string``

    """
    if not model_class.isValidModel ():
        FreeCAD.Console.PrintMessage("Model: " + modelName + ' has invalid parameter and was skipped.\r\n')
        return

    LIST_license = ["",]

    CheckedmodelName = modelName.replace('.', '').replace('-', '_').replace('(', '').replace(')', '')
    Newdoc = App.newDocument(CheckedmodelName)
    App.setActiveDocument(CheckedmodelName)
    Gui.ActiveDocument=Gui.getDocument(CheckedmodelName)
    destination_dir = model_class.get_dest_3D_dir()
    
    material_substitutions = model_class.make_3D_model()
    
    doc = FreeCAD.ActiveDocument
    doc.Label = CheckedmodelName

    objs=GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedmodelName
    restore_Main_Tools()

    script_dir=os.path.dirname(os.path.realpath(__file__))
    expVRML.say(models_dir)
    out_dir=models_dir+os.sep+destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    exportSTEP(doc, modelName, out_dir)
    if LIST_license[0]=="":
        LIST_license=Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', modelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale=1/2.54
    #exportVRML(doc,modelName,scale,out_dir)
    del objs
    objs=GetListOfObjects(FreeCAD, doc)
    expVRML.say("######################################################################")
    expVRML.say(objs)
    expVRML.say("######################################################################")
    export_objects, used_color_keys = expVRML.determineColors(Gui, objs, material_substitutions)
    export_file_name=out_dir + os.sep + modelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale)
    #expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license)
    #scale=0.3937001
    #exportVRML(doc,modelName,scale,out_dir)
    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, modelName,out_dir)
    #display BBox
    Gui.activateWorkbench("PartWorkbench")
    Gui.SendMsgToActiveView("ViewFit")
    Gui.activeDocument().activeView().viewAxometric()
Exemplo n.º 48
0
 def doubleClicked(self, vobj):
     FreeCADGui.activateWorkbench('FemWorkbench')
     # Group meshing is only active on active analysis, we should make sure the analysis the mesh belongs too is active
     gui_doc = FreeCADGui.getDocument(vobj.Object.Document)
     if not gui_doc.getInEdit():
         # may be go the other way around and just activate the analysis the user has doubleClicked on ?!
         # not a fast one, we need to iterate over all member of all analysis to know to which analyis the object belongs too!!!
         # first check if there is an analysis in the active document
         found_an_analysis = False
         for o in gui_doc.Document.Objects:
             if o.isDerivedFrom('Fem::FemAnalysisPython'):
                 found_an_analysis = True
                 break
         if found_an_analysis:
             if FemGui.getActiveAnalysis() is not None:
                 if FemGui.getActiveAnalysis(
                 ).Document is FreeCAD.ActiveDocument:
                     if self.Object in FemGui.getActiveAnalysis().Member:
                         if not gui_doc.getInEdit():
                             gui_doc.setEdit(vobj.Object.Name)
                         else:
                             FreeCAD.Console.PrintError(
                                 'Activate the analysis this GMSH FEM mesh object belongs too!\n'
                             )
                     else:
                         print(
                             'GMSH FEM mesh object does not belong to the active analysis.'
                         )
                         found_mesh_analysis = False
                         for o in gui_doc.Document.Objects:
                             if o.isDerivedFrom('Fem::FemAnalysisPython'):
                                 for m in o.Member:
                                     if m == self.Object:
                                         found_mesh_analysis = True
                                         FemGui.setActiveAnalysis(o)
                                         print(
                                             'The analysis the GMSH FEM mesh object belongs too was found and activated: '
                                             + o.Name)
                                         gui_doc.setEdit(vobj.Object.Name)
                                         break
                         if not found_mesh_analysis:
                             print(
                                 'GMSH FEM mesh object does not belong to an analysis. Analysis group meshing will be deactivated.'
                             )
                             gui_doc.setEdit(vobj.Object.Name)
                 else:
                     FreeCAD.Console.PrintError(
                         'Active analysis is not in active document.')
             else:
                 print(
                     'No active analysis in active document, we gone have a look if the GMSH FEM mesh object belongs to a non active analysis.'
                 )
                 found_mesh_analysis = False
                 for o in gui_doc.Document.Objects:
                     if o.isDerivedFrom('Fem::FemAnalysisPython'):
                         for m in o.Member:
                             if m == self.Object:
                                 found_mesh_analysis = True
                                 FemGui.setActiveAnalysis(o)
                                 print(
                                     'The analysis the GMSH FEM mesh object belongs too was found and activated: '
                                     + o.Name)
                                 gui_doc.setEdit(vobj.Object.Name)
                                 break
                 if not found_mesh_analysis:
                     print(
                         'GMSH FEM mesh object does not belong to an analysis. Analysis group meshing will be deactivated.'
                     )
                     gui_doc.setEdit(vobj.Object.Name)
         else:
             print('No analysis in the active document.')
             gui_doc.setEdit(vobj.Object.Name)
     else:
         FreeCAD.Console.PrintError(
             'Active Task Dialog found! Please close this one first!\n')
     return True
Exemplo n.º 49
0
def export_one_part(modul, variant, with_plug=False):
    if not variant in modul.all_params:
        FreeCAD.Console.PrintMessage("Parameters for %s doesn't exist in 'M.all_params', skipping." % variant)
        return

    destination_dir="Connectors_Phoenix.3dshapes"
    if with_plug:
        destination_dir="Connectors_Phoenix__with_plug.3dshapes"
    ModelName = variant
    ModelName = ModelName.replace(".","_")
    FileName = modul.all_params[variant].file_name
    Newdoc = FreeCAD.newDocument(ModelName)
    App.setActiveDocument(ModelName)
    App.ActiveDocument=App.getDocument(ModelName)
    Gui.ActiveDocument=Gui.getDocument(ModelName)
    #App.setActiveDocument(ModelName)
    #Gui.ActiveDocument=Gui.getDocument(ModelName)
    (pins, body, insert, mount_screw, plug, plug_screws) = modul.generate_part(variant, with_plug)

    color_attr = body_color + (0,)
    show(body, color_attr)

    color_attr = pins_color + (0,)
    show(pins, color_attr)

    if insert is not None:
        color_attr = insert_color + (0,)
        show(insert, color_attr)
    if mount_screw is not None:
        color_attr = screw_color + (0,)
        show(mount_screw, color_attr)
    if plug is not None:
        color_attr = body_color + (0,)
        show(plug, color_attr)

        color_attr = screw_color + (0,)
        show(plug_screws, color_attr)

    doc = FreeCAD.ActiveDocument
    doc.Label=ModelName
    objs=FreeCAD.ActiveDocument.Objects
    FreeCAD.Console.PrintMessage(objs)

    i=0
    objs[i].Label = ModelName + "__body"
    i+=1
    objs[i].Label = ModelName + "__pins"
    i+=1
    if insert is not None:
        objs[i].Label = ModelName + "__thread_insert"
        i+=1
    if mount_screw is not None:
        objs[i].Label = ModelName + "__mount_screw"
        i+=1
    if plug is not None:
        objs[i].Label = ModelName + "__plug"
        i+=1
        objs[i].Label = ModelName + "__plug_screws"
    restore_Main_Tools()

    out_dir=destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    used_color_keys = [body_color_key, pins_color_key]
    export_file_name=destination_dir+os.sep+FileName+'.wrl'

    export_objects = []
    i=0
    export_objects.append(expVRML.exportObject(freecad_object = objs[i],
            shape_color=body_color_key,
            face_colors=None))
    i+=1
    export_objects.append(expVRML.exportObject(freecad_object = objs[i],
            shape_color=pins_color_key,
            face_colors=None))
    i+=1
    if insert is not None:
        export_objects.append(expVRML.exportObject(freecad_object = objs[i],
                shape_color=insert_color_key,
                face_colors=None))
        used_color_keys.append(insert_color_key)
        i+=1
    if mount_screw is not None:
        export_objects.append(expVRML.exportObject(freecad_object = objs[i],
                shape_color=screw_color_key,
                face_colors=None))
        used_color_keys.append(screw_color_key)
        i+=1
    if plug is not None:
        export_objects.append(expVRML.exportObject(freecad_object = objs[i],
                shape_color=body_color_key,
                face_colors=None))
        i+=1
        export_objects.append(expVRML.exportObject(freecad_object = objs[i],
                shape_color=screw_color_key,
                face_colors=None))
    scale=1/2.54
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale)
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license)

    fusion = multiFuseObjs_wColors(FreeCAD, FreeCADGui,
                     ModelName, objs, keepOriginals=True)

    exportSTEP(doc,FileName,out_dir,fusion)
    L.addLicenseToStep(out_dir+'/', FileName+".step", LIST_license,\
        STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licPreProc)

    saveFCdoc(App, Gui, doc, FileName,out_dir)

    FreeCAD.activeDocument().recompute()
    # FreeCADGui.activateWorkbench("PartWorkbench")
    FreeCADGui.SendMsgToActiveView("ViewFit")
    FreeCADGui.activeDocument().activeView().viewAxometric()
Exemplo n.º 50
0
import FreeCAD as App
import FreeCADGui as Gui
import time
from FreeCAD import Base
from PyQt4 import QtCore, QtGui

# execfile("/home/judypaws/Simulacion/MecSpring.py")
FreeCAD.open("/home/judypaws/Simulacion/Spring.fcstd")
App.setActiveDocument("Spring")
App.ActiveDocument = App.getDocument("Spring")
Gui.ActiveDocument = Gui.getDocument("Spring")

pitch1 = pitch2 = FreeCAD.getDocument("Spring").getObject(
    "Helix001").Pitch.Value
height1 = ib = FreeCAD.getDocument("Spring").getObject("Helix001").Height.Value

pas = 1

#def mover():

for ii2 in range(int(60)):
    if pas == 0:
        if pitch1 > pitch2 - 1:
            pas = 1
        else:
            pitch1 += 1
            height1 = (pitch1 * 10)
    else:
        if pitch1 < 2:
            pas = 0
        else:
Exemplo n.º 51
0
 def accept(self):
     if "PorousZone" in self.obj.Name:
         try:
             self.p['PorousCorrelation'] = POROUS_CORRELATIONS[
                 self.form.comboBoxCorrelation.currentIndex()]
             self.p['D'] = [
                 float(FreeCAD.Units.Quantity(self.form.dx.text())),
                 float(FreeCAD.Units.Quantity(self.form.dy.text())),
                 float(FreeCAD.Units.Quantity(self.form.dz.text()))
             ]
             self.p['F'] = [
                 float(FreeCAD.Units.Quantity(self.form.fx.text())),
                 float(FreeCAD.Units.Quantity(self.form.fy.text())),
                 float(FreeCAD.Units.Quantity(self.form.fz.text()))
             ]
             self.p['e1'] = [
                 float(FreeCAD.Units.Quantity(self.form.e1x.text())),
                 float(FreeCAD.Units.Quantity(self.form.e1y.text())),
                 float(FreeCAD.Units.Quantity(self.form.e1z.text()))
             ]
             self.p['e2'] = [
                 float(FreeCAD.Units.Quantity(self.form.e2x.text())),
                 float(FreeCAD.Units.Quantity(self.form.e2y.text())),
                 float(FreeCAD.Units.Quantity(self.form.e2z.text()))
             ]
             self.p['e3'] = [
                 float(FreeCAD.Units.Quantity(self.form.e3x.text())),
                 float(FreeCAD.Units.Quantity(self.form.e3y.text())),
                 float(FreeCAD.Units.Quantity(self.form.e3z.text()))
             ]
             self.p['OuterDiameter'] = float(
                 FreeCAD.Units.Quantity(
                     self.form.inputOuterDiameter.text()).getValueAs('m'))
             self.p['TubeAxis'] = [
                 float(
                     FreeCAD.Units.Quantity(
                         self.form.inputTubeAxisX.text())),
                 float(
                     FreeCAD.Units.Quantity(
                         self.form.inputTubeAxisY.text())),
                 float(
                     FreeCAD.Units.Quantity(
                         self.form.inputTubeAxisZ.text()))
             ]
             self.p['TubeSpacing'] = float(
                 FreeCAD.Units.Quantity(
                     self.form.inputTubeSpacing.text()).getValueAs('m'))
             self.p['SpacingDirection'] = \
                 [float(FreeCAD.Units.Quantity(self.form.inputBundleLayerNormalX.text())),
                 float(FreeCAD.Units.Quantity(self.form.inputBundleLayerNormalY.text())),
                 float(FreeCAD.Units.Quantity(self.form.inputBundleLayerNormalZ.text()))]
             self.p['AspectRatio'] = float(
                 FreeCAD.Units.Quantity(self.form.inputAspectRatio.text()))
             self.p['VelocityEstimate'] = \
                 float(FreeCAD.Units.Quantity(self.form.inputVelocityEstimate.text()).getValueAs('m/s'))
         except ValueError:
             FreeCAD.Console.PrintError("Unrecognised value entered\n")
             return
         self.obj.porousZoneProperties = self.p
     self.obj.partNameList = self.partNameList
     doc = FreeCADGui.getDocument(self.obj.Document)
     doc.resetEdit()
 def reject(self):
     doc = FreeCADGui.getDocument(self.obj.Document)
     doc.resetEdit()
Exemplo n.º 53
0
            place_pinMark = False  ##used to exclude pin mark to build sot23-3; sot23-5; sc70 (asimmetrical pins, no pinmark)
        else:
            excluded_pins_x = ()  ##no pin excluded
            excluded_pins_xmirror = ()  ##no pin excluded
            place_pinMark = True  ##default =True used to exclude pin mark to build sot23-3; sot23-5; sc70 (asimmetrical pins, no pinmark)

        FreeCAD.Console.PrintMessage('\r\n' + variant)
        if not variant in all_params:
            print(
                "Parameters for %s doesn't exist in 'all_params', skipping." %
                variant)
            continue
        ModelName = all_params[variant].modelName
        Newdoc = FreeCAD.newDocument(ModelName)
        App.setActiveDocument(ModelName)
        Gui.ActiveDocument = Gui.getDocument(ModelName)
        case, pins, pinmark = make_gw(all_params[variant])

        color_attr = case_color + (0, )
        show(case, color_attr)
        color_attr = pins_color + (0, )
        show(pins, color_attr)
        color_attr = mark_color + (0, )
        show(pinmark, color_attr)

        doc = FreeCAD.ActiveDocument
        objs = GetListOfObjects(FreeCAD, doc)
        ## objs[0].Label='body'
        ## objs[1].Label='pins'
        ## objs[2].Label='mark'
        ###
Exemplo n.º 54
0
class mainAssemblyObject:
    def __init__(self, obj):
        self.Type = 'assemblyMain'
        obj.Proxy = self
        self.Object = obj

        obj.addProperty("App::PropertyFile", "File", "Base", "File").File = ""
        #obj.addProperty("App::PropertyPlacement", "Placement", "Base", "Placement")
        obj.addProperty("App::PropertyDistance", "X", "PCB", "X").X = 0
        obj.addProperty("App::PropertyDistance", "Y", "PCB", "Y").Y = 0
        obj.addProperty("App::PropertyDistance", "Z", "PCB", "Z").Z = 0
        obj.addProperty("App::PropertyAngle", "RX", "PCB", "RX").RX = 0
        obj.addProperty("App::PropertyAngle", "RY", "PCB", "RY").RY = 0
        obj.addProperty("App::PropertyAngle", "RZ", "PCB", "RZ").RZ = 0

        self.center = [0, 0, 0]

    def execute(self, obj):
        pass

    def __getstate__(self):
        return [self.Type, str(self.center)]

    def __setstate__(self, state):
        if state:
            self.Type = state[0]
            self.center = eval(state[1])

    def updateParts(self, obj):
        if obj.File.strip() != '':
            mainFile = FreeCAD.ActiveDocument
            # delete old parts
            try:
                for i in obj.OutList:
                    FreeCAD.ActiveDocument.removeObject(i.Name)
            except Exception, e:
                FreeCAD.Console.PrintWarning("7. {0} \n".format(e))
            # load new parts
            newFile = checkFile(obj.File)
            if not newFile[0]:
                return
            #
            center = Part.makeCompound([
                i.Shape for i in newFile[0].Objects if hasattr(i, "Shape")
            ]).BoundBox.Center
            self.center = [center[0], center[1], center[2]]
            #
            for i in newFile[0].Objects:
                if not i.ViewObject.Visibility:
                    continue

                if hasattr(i, "Proxy") and hasattr(
                        i, "Type") and i.Proxy.Type in [['PCBannotation'],
                                                        'PCBpart_E']:
                    continue

                if hasattr(i, "Shape"
                           ) and not i.isDerivedFrom("Sketcher::SketchObject"):
                    try:
                        child = mainFile.addObject("Part::FeaturePython",
                                                   "{0}".format(i.Label))
                        childAssemblyObject(child)
                        child.Shape = i.Shape
                        viewProviderChildAssemblyObject(child.ViewObject)
                        child.ViewObject.DiffuseColor = i.ViewObject.DiffuseColor

                        child.Proxy.rotZ = i.Placement.Rotation.toEuler()[0]
                        child.Proxy.rotY = i.Placement.Rotation.toEuler()[1]
                        child.Proxy.rotX = i.Placement.Rotation.toEuler()[2]

                        #
                        obj.addObject(child)
                        child.Proxy.offsetX = child.Placement.Base.x - self.center[
                            0]
                        child.Proxy.offsetY = child.Placement.Base.y - self.center[
                            1]
                        child.Proxy.offsetZ = child.Placement.Base.z - self.center[
                            2]

                    except Exception, e:
                        FreeCAD.Console.PrintWarning("1. {0} \n".format(e))
            if newFile[1]:
                FreeCAD.closeDocument(newFile[0].Label)
            FreeCAD.setActiveDocument(mainFile.Label)
            FreeCADGui.ActiveDocument = FreeCADGui.getDocument(mainFile.Label)

            FreeCADGui.ActiveDocument.activeView().viewAxometric()
            FreeCADGui.ActiveDocument.activeView().fitAll()
def generateOneModel(params, log):
    excluded_pins_x = ()  ##no pin excluded
    excluded_pins_xmirror = ()  ##no pin excluded
    place_pinMark = True  ##default =True used to exclude pin mark to build sot23-3; sot23-5; sc70 (asimmetrical pins, no pinmark)

    ModelName = params.modelName
    FreeCAD.Console.PrintMessage('\n\n##############  ' + ModelName +
                                 '  ###############\n')
    CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace(
        '(', '').replace(')', '')
    Newdoc = App.newDocument(CheckedModelName)
    App.setActiveDocument(CheckedModelName)
    Gui.ActiveDocument = Gui.getDocument(CheckedModelName)
    #case, pins, pinmark = make_case(params)
    case_bot, case, pins, pinmark = make_case(params)

    if case_bot is not None:
        show(case_bot)
    show(case)
    show(pins)
    show(pinmark)
    #stop

    doc = FreeCAD.ActiveDocument
    objs = GetListOfObjects(FreeCAD, doc)

    if case_bot is not None:
        Color_Objects(Gui, objs[0], body_bot_color)
        Color_Objects(Gui, objs[1], body_color)
        Color_Objects(Gui, objs[2], pins_color)
        Color_Objects(Gui, objs[3], marking_color)

        col_body_bot = Gui.ActiveDocument.getObject(
            objs[0].Name).DiffuseColor[0]
        col_body = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
        col_pin = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]
        col_mark = Gui.ActiveDocument.getObject(objs[3].Name).DiffuseColor[0]
        material_substitutions = {
            col_body_bot[:-1]: body_bot_color_key,
            col_body[:-1]: body_color_key,
            col_pin[:-1]: pins_color_key,
            col_mark[:-1]: marking_color_key
        }
        expVRML.say(material_substitutions)
        if (color_pin_mark == True) and (place_pinMark == True):
            CutObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[1].Name,
                            objs[3].Name)
        else:
            #removing pinMark
            App.getDocument(doc.Name).removeObject(objs[3].Name)
        ###
        #sleep
        del objs
        objs = GetListOfObjects(FreeCAD, doc)
        FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name,
                         objs[1].Name)
        objs = GetListOfObjects(FreeCAD, doc)
        FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name,
                         objs[1].Name)
    else:
        Color_Objects(Gui, objs[0], body_color)
        Color_Objects(Gui, objs[1], pins_color)
        Color_Objects(Gui, objs[2], marking_color)

        col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0]
        col_pin = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
        col_mark = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]
        material_substitutions = {
            col_body[:-1]: body_color_key,
            col_pin[:-1]: pins_color_key,
            col_mark[:-1]: marking_color_key
        }
        #expVRML.say(material_substitutions)
        if (color_pin_mark == True) and (place_pinMark == True):
            CutObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name,
                            objs[2].Name)
        else:
            #removing pinMark
            App.getDocument(doc.Name).removeObject(objs[2].Name)
        ###
        #sleep
        del objs
        objs = GetListOfObjects(FreeCAD, doc)
        FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name,
                         objs[1].Name)
    ## objs[0].Label='body'
    ## objs[1].Label='pins'
    ## objs[2].Label='mark'
    ###
    ## print objs[0].Name, objs[1].Name, objs[2].Name

    ## sleep
    doc.Label = CheckedModelName
    objs = GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedModelName
    restore_Main_Tools()
    #rotate if required
    if (params.rotation != 0):
        rot = params.rotation
        z_RotateObject(doc, rot)
    #out_dir=destination_dir+params.dest_dir_prefix+'/'
    script_dir = os.path.dirname(os.path.realpath(__file__))
    #models_dir=script_dir+"/../_3Dmodels"
    #expVRML.say(models_dir)
    if len(params.dest_dir_prefix) >= 1:
        out_dir = models_dir + destination_dir + os.sep + params.dest_dir_prefix
    else:
        out_dir = models_dir + destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    #out_dir="./generated_qfp/"
    # export STEP model
    exportSTEP(doc, ModelName, out_dir)
    global LIST_license
    if LIST_license[0] == "":
        LIST_license = Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale = 1 / 2.54
    #exportVRML(doc,ModelName,scale,out_dir)
    objs = GetListOfObjects(FreeCAD, doc)

    export_objects, used_color_keys = expVRML.determineColors(
        Gui, objs, material_substitutions)
    export_file_name = out_dir + os.sep + ModelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
    #expVRML.writeVRMLFile added creaeAngle
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          LIST_license, 0.9)
    # Save the doc in Native FC format
    #saveFCdoc(App, Gui, doc, ModelName,out_dir)
    #display BBox
    #FreeCADGui.ActiveDocument.getObject("Part__Feature").BoundingBox = True
    if footprints_dir is not None and os.path.isdir(
            footprints_dir
    ) and not save_memory and not check_Model:  #it doesn't make sense to import the footprint right before we close the file.
        #expVRML.say (ModelName)
        #stop
        sys.argv = [
            "fc", "dummy", footprints_dir + os.sep + ModelName, "savememory"
        ]
        #setup = get_setup_file()  # << You need the parentheses
        expVRML.say(sys.argv[2])
        if not ksu_present:
            try:
                import kicadStepUptools
                ksu_present = True
                expVRML.say("ksu present!")
                kicadStepUptools.KSUWidget.close()
                #kicadStepUptools.KSUWidget.setWindowState(QtCore.Qt.WindowMinimized)
                #kicadStepUptools.KSUWidget.destroy()
                #for i in QtGui.qApp.topLevelWidgets():
                #    if i.objectName() == "kicadStepUp":
                #        i.deleteLater()
                kicadStepUptools.KSUWidget.close()
            except:
                ksu_present = False
                expVRML.say("ksu not present")
        else:
            kicadStepUptools.KSUWidget.close()
            reload(kicadStepUptools)
            kicadStepUptools.KSUWidget.close()
            #kicadStepUptools.KSUWidget.setWindowState(QtCore.Qt.WindowMinimized)
            #kicadStepUptools.KSUWidget.destroy()

    #FreeCADGui.insert(u"C:\Temp\FCAD_sg\QFN_packages\QFN-12-1EP_3x3mm_Pitch0_5mm.kicad_mod")
    #FreeCADGui.insert(script_dir+os.sep+"ModelName.kicad_mod")
    if save_memory == False:
        Gui.activateWorkbench("PartWorkbench")
        Gui.SendMsgToActiveView("ViewFit")
        Gui.activeDocument().activeView().viewBottom()
        #Gui.activeDocument().activeView().viewAxometric()
    saveFCdoc(App, Gui, doc, ModelName, out_dir)

    if save_memory == True or check_Model == True:
        doc = FreeCAD.ActiveDocument
        print("closing: {}".format(doc.Name))
        FreeCAD.closeDocument(doc.Name)

    if check_Model == True:
        step_path = out_dir + '/' + ModelName + ".step"
        runGeometryCheck(App,
                         Gui,
                         step_path,
                         log,
                         ModelName,
                         save_memory=save_memory)
Exemplo n.º 56
0
    def accept(self):
        if self.obj.Label.startswith("CfdFluidBoundary"):
            self.obj.Label = self.obj.BoundaryType
        FreeCADGui.Selection.removeObserver(self)

        doc = FreeCADGui.getDocument(self.obj.Document)
        doc.resetEdit()

        FreeCADGui.doCommand("\nbc = FreeCAD.ActiveDocument.{}".format(
            self.obj.Name))
        # Type
        FreeCADGui.doCommand("bc.BoundaryType "
                             "= '{}'".format(self.obj.BoundaryType))
        FreeCADGui.doCommand("bc.BoundarySubType "
                             "= '{}'".format(self.obj.BoundarySubType))
        FreeCADGui.doCommand(
            "bc.ThermalBoundaryType "
            "= '{}'".format(CfdFluidBoundary.THERMAL_BOUNDARY_TYPES[
                self.form.comboThermalBoundaryType.currentIndex()]))
        # Velocity
        FreeCADGui.doCommand("bc.VelocityIsCartesian "
                             "= {}".format(
                                 self.form.radioButtonCart.isChecked()))
        FreeCADGui.doCommand("bc.Ux "
                             "= '{}'".format(getQuantity(
                                 self.form.inputCartX)))
        FreeCADGui.doCommand("bc.Uy "
                             "= '{}'".format(getQuantity(
                                 self.form.inputCartY)))
        FreeCADGui.doCommand("bc.Uz "
                             "= '{}'".format(getQuantity(
                                 self.form.inputCartZ)))
        FreeCADGui.doCommand("bc.VelocityMag "
                             "= '{}'".format(
                                 getQuantity(self.form.inputVelocityMag)))
        FreeCADGui.doCommand("bc.DirectionFace "
                             "= '{}'".format(self.form.lineDirection.text()))
        FreeCADGui.doCommand("bc.ReverseNormal "
                             "= {}".format(self.form.checkReverse.isChecked()))
        FreeCADGui.doCommand("bc.MassFlowRate "
                             "= '{}'".format(
                                 getQuantity(self.form.inputMassFlowRate)))
        FreeCADGui.doCommand("bc.VolFlowRate "
                             "= '{}'".format(
                                 getQuantity(self.form.inputVolFlowRate)))
        # Presure
        FreeCADGui.doCommand("bc.Pressure "
                             "= '{}'".format(
                                 getQuantity(self.form.inputPressure)))
        # Wall
        FreeCADGui.doCommand("bc.SlipRatio "
                             "= '{}'".format(
                                 getQuantity(self.form.inputSlipRatio)))
        # Thermal
        FreeCADGui.doCommand("bc.Temperature "
                             "= '{}'".format(
                                 getQuantity(self.form.inputTemperature)))
        FreeCADGui.doCommand("bc.HeatFlux "
                             "= '{}'".format(
                                 getQuantity(self.form.inputHeatFlux)))
        FreeCADGui.doCommand(
            "bc.HeatTransferCoeff "
            "= '{}'".format(getQuantity(self.form.inputHeatTransferCoeff)))

        # Turbulence
        if self.turbModel in CfdFluidBoundary.TURBULENT_INLET_SPEC:
            turb_index = self.form.comboTurbulenceSpecification.currentIndex()
            FreeCADGui.doCommand("bc.TurbulenceInletSpecification "
                                 "= '{}'".format(
                                     CfdFluidBoundary.TURBULENT_INLET_SPEC[
                                         self.turbModel][1][turb_index]))
        else:
            FreeCADGui.doCommand("bc.TurbulenceInletSpecification "
                                 "= '{}'".format(
                                     self.obj.TurbulenceInletSpecification))
        FreeCADGui.doCommand("bc.TurbulentKineticEnergy "
                             "= '{}'".format(
                                 getQuantity(self.form.inputKineticEnergy)))
        FreeCADGui.doCommand("bc.SpecificDissipationRate "
                             "= '{}'".format(
                                 getQuantity(
                                     self.form.inputSpecificDissipationRate)))
        FreeCADGui.doCommand("bc.TurbulenceIntensity "
                             "= '{}'".format(
                                 getQuantity(self.form.inputIntensity)))
        FreeCADGui.doCommand("bc.TurbulenceLengthScale "
                             "= '{}'".format(
                                 getQuantity(self.form.inputLengthScale)))
        FreeCADGui.doCommand("bc.VolumeFractions = {}".format(self.alphas))

        # Porous
        FreeCADGui.doCommand("bc.PorousBaffleMethod "
                             "= '{}'".format(CfdFluidBoundary.POROUS_METHODS[
                                 self.form.buttonGroupPorous.checkedId()]))
        FreeCADGui.doCommand(
            "bc.PressureDropCoeff "
            "= '{}'".format(getQuantity(self.form.inputPressureDropCoeff)))
        FreeCADGui.doCommand("bc.ScreenWireDiameter "
                             "= '{}'".format(
                                 getQuantity(self.form.inputWireDiameter)))
        FreeCADGui.doCommand("bc.ScreenSpacing "
                             "= '{}'".format(
                                 getQuantity(self.form.inputSpacing)))
        FreeCADGui.doCommand("FreeCAD.ActiveDocument.{}.Label = '{}'".format(
            self.obj.Name, self.obj.Label))
        faces = []
        for ref in self.obj.References:
            faces.append(ref)
        self.obj.References = []
        FreeCADGui.doCommand(
            "FreeCAD.ActiveDocument.{}.References = []".format(self.obj.Name))
        for f in faces:
            FreeCADGui.doCommand(
                "FreeCAD.ActiveDocument.{}.References.append({})".format(
                    self.obj.Name, f))
        FreeCADGui.doCommand("FreeCAD.ActiveDocument.recompute()")
        self.faceSelector.closing()
def make_3D_model(models_dir, model_class, modelName):

    LIST_license = [
        "",
    ]

    CheckedmodelName = modelName.replace('.', '').replace('-', '_').replace(
        '(', '').replace(')', '')
    Newdoc = App.newDocument(CheckedmodelName)
    App.setActiveDocument(CheckedmodelName)
    Gui.ActiveDocument = Gui.getDocument(CheckedmodelName)
    destination_dir = model_class.get_dest_3D_dir()

    material_substitutions = model_class.make_3D_model(modelName)

    doc = FreeCAD.ActiveDocument
    doc.Label = CheckedmodelName

    objs = GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedmodelName
    restore_Main_Tools()

    script_dir = os.path.dirname(os.path.realpath(__file__))
    expVRML.say(models_dir)
    out_dir = models_dir + os.sep + destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    exportSTEP(doc, modelName, out_dir)
    if LIST_license[0] == "":
        LIST_license = Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', modelName+".step", LIST_license,\
                       STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale = 1 / 2.54
    #exportVRML(doc,modelName,scale,out_dir)
    del objs
    objs = GetListOfObjects(FreeCAD, doc)
    expVRML.say(
        "######################################################################"
    )
    expVRML.say(objs)
    expVRML.say(
        "######################################################################"
    )
    export_objects, used_color_keys = expVRML.determineColors(
        Gui, objs, material_substitutions)
    export_file_name = out_dir + os.sep + modelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
    #expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          LIST_license)
    #scale=0.3937001
    #exportVRML(doc,modelName,scale,out_dir)
    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, modelName, out_dir)
    #display BBox
    Gui.activateWorkbench("PartWorkbench")
    Gui.SendMsgToActiveView("ViewFit")
    Gui.activeDocument().activeView().viewAxometric()
Exemplo n.º 58
0
 def gm(self):
     self.runm()
     return FreeCADGui.getDocument("Model")
Exemplo n.º 59
0
# Este programa se ejecuta en la consola Python de FreeCAD con el comando "execfile(/carpeta/*.py)". Este archivo en particular permite mover los componentes con las funciones de la libreria C++

import FreeCAD as App
import FreeCADGui as Gui
from PyQt4 import QtCore, QtGui

# execfile("/home/carlos/Documents/Universidad/Simulacion/engranessim.py")
FreeCAD.open("/home/carlos/Documents/Universidad/Simulacion/engranes.fcstd")
App.setActiveDocument("engranes")
App.ActiveDocument = App.getDocument("engranes")
Gui.ActiveDocument = Gui.getDocument("engranes")
import sys

sys.path.append('/home/carlos/Documents/Universidad/Simulacion')
import MoveModule

move = MoveModule.pMovement()
PI = 3.14159
w0 = 0
t = 0


def Leonardo():
    global PI, move, w0, w1

    # Primer Engran (se mueve solo)
    w0 += PI / 8
    App.getDocument("engranes").E0.Placement = App.Placement(
        App.Vector(0, 0, 0), App.Rotation(w0, 0, 0), App.Vector(0, 0, 0))

    #Segundo y tercer engran
def make_3D_model(models_dir, variant):

    LIST_license = [
        "",
    ]
    modelName = all_params[variant].modelName

    CheckedmodelName = modelName.replace('.', '').replace('-', '_').replace(
        '(', '').replace(')', '')
    Newdoc = App.newDocument(CheckedmodelName)
    App.setActiveDocument(CheckedmodelName)
    Gui.ActiveDocument = Gui.getDocument(CheckedmodelName)

    case = make_case(all_params[variant])
    casetop = make_case_top(all_params[variant])

    if (all_params[variant].pintype == CASE_THT_TYPE):
        pins = make_pins_tht(all_params[variant])

    if (all_params[variant].pintype == CASE_THT_N_TYPE):
        pins = make_pins_tht_n(all_params[variant])

    if (all_params[variant].pintype == CASE_SMD_TYPE):
        pins = make_pins_smd(all_params[variant])

    show(case)
    show(casetop)
    show(pins)
    #show(pinmark)
    #stop
    doc = FreeCAD.ActiveDocument
    objs = GetListOfObjects(FreeCAD, doc)

    body_color_key = all_params[variant].body_color_key
    body_top_color_key = all_params[variant].body_top_color_key
    pin_color_key = all_params[variant].pin_color_key

    body_color = shaderColors.named_colors[body_color_key].getDiffuseFloat()
    body_top_color = shaderColors.named_colors[
        body_top_color_key].getDiffuseFloat()
    pin_color = shaderColors.named_colors[pin_color_key].getDiffuseFloat()

    Color_Objects(Gui, objs[0], body_color)
    Color_Objects(Gui, objs[1], body_top_color)
    Color_Objects(Gui, objs[2], pin_color)

    col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0]
    col_body_top = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
    col_pin = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]

    material_substitutions = {
        col_body[:-1]: body_color_key,
        col_body_top[:-1]: body_top_color_key,
        col_pin[:-1]: pin_color_key
    }

    expVRML.say(material_substitutions)
    while len(objs) > 1:
        FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name,
                         objs[1].Name)
        del objs
        objs = GetListOfObjects(FreeCAD, doc)
    doc.Label = CheckedmodelName

    del objs
    objs = GetListOfObjects(FreeCAD, doc)
    objs[0].Label = CheckedmodelName
    restore_Main_Tools()

    script_dir = os.path.dirname(os.path.realpath(__file__))
    expVRML.say(models_dir)
    out_dir = models_dir + destination_dir
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    exportSTEP(doc, modelName, out_dir)
    if LIST_license[0] == "":
        LIST_license = Lic.LIST_int_license
        LIST_license.append("")
    Lic.addLicenseToStep(out_dir+'/', modelName+".step", LIST_license,\
           STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)

    # scale and export Vrml model
    scale = 1 / 2.54
    #exportVRML(doc,modelName,scale,out_dir)
    del objs
    objs = GetListOfObjects(FreeCAD, doc)
    expVRML.say(
        "######################################################################"
    )
    expVRML.say(objs)
    expVRML.say(
        "######################################################################"
    )
    export_objects, used_color_keys = expVRML.determineColors(
        Gui, objs, material_substitutions)
    export_file_name = out_dir + os.sep + modelName + '.wrl'
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)
    #expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license
    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          LIST_license)
    #scale=0.3937001
    #exportVRML(doc,modelName,scale,out_dir)
    # Save the doc in Native FC format
    saveFCdoc(App, Gui, doc, modelName, out_dir)
    #display BBox
    Gui.activateWorkbench("PartWorkbench")
    Gui.SendMsgToActiveView("ViewFit")
    Gui.activeDocument().activeView().viewAxometric()