Difference between revisions of "Code snippets"

From FreeCAD Documentation
Jump to: navigation, search
(A typical module file)
Line 48: Line 48:
 
This line must be added to the InitGui.py file to add the new file extension to the list:
 
This line must be added to the InitGui.py file to add the new file extension to the list:
  
 +
 +
<code python>
 
  # Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
 
  # Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
 
  FreeCAD.EndingAdd("Your new File Type (*.ext)","Import_Ext")  
 
  FreeCAD.EndingAdd("Your new File Type (*.ext)","Import_Ext")  
 +
</code>
  
 
Then in the Import_Ext.py file:
 
Then in the Import_Ext.py file:
  
 +
<code python>
 
  def open(filename):  
 
  def open(filename):  
 
  doc=App.newDocument()
 
  doc=App.newDocument()
 
  # here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects
 
  # here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects
 
  doc.recompute()
 
  doc.recompute()
 +
</code>
  
 
=== Adding a line ===
 
=== Adding a line ===
Line 62: Line 67:
 
A line simply has 2 points.
 
A line simply has 2 points.
  
 +
<code python>
 
  import Part,PartGui  
 
  import Part,PartGui  
 
  doc=App.activeDocument()  
 
  doc=App.activeDocument()  
Line 69: Line 75:
 
  l.e=(1.0,1.0,1.0)
 
  l.e=(1.0,1.0,1.0)
 
  doc.recompute()
 
  doc.recompute()
 +
</code>
  
 
=== Adding a polygon ===
 
=== Adding a polygon ===
Line 74: Line 81:
 
A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.
 
A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.
  
 +
<code python>
 
  import Part,PartGui  
 
  import Part,PartGui  
 
  doc=App.activeDocument()
 
  doc=App.activeDocument()
Line 89: Line 97:
 
  p.Nodes=n  
 
  p.Nodes=n  
 
  doc.recompute()
 
  doc.recompute()
 +
</code>
  
 
=== Adding an object to a group ===
 
=== Adding an object to a group ===
  
 +
<code python>
 
  doc=App.activeDocument()  
 
  doc=App.activeDocument()  
 
  grp=doc.addObject("App::DocumentObjectGroup", "Group")  
 
  grp=doc.addObject("App::DocumentObjectGroup", "Group")  
Line 98: Line 108:
 
  l.e=(0,0,5)  
 
  l.e=(0,0,5)  
 
  doc.recompute()
 
  doc.recompute()
 +
</code>
  
 
=== Adding a Mesh ===
 
=== Adding a Mesh ===
  
 +
<code python>
 
  import Mesh
 
  import Mesh
 
  doc=App.activeDocument()
 
  doc=App.activeDocument()
Line 124: Line 136:
 
  me.Mesh=m
 
  me.Mesh=m
 
  doc.recompute()
 
  doc.recompute()
 +
</code>
  
 
=== Adding an arc or a circle ===
 
=== Adding an arc or a circle ===
  
 +
<code python>
 
  import Part
 
  import Part
 
  doc = App.activeDocument()
 
  doc = App.activeDocument()
Line 134: Line 148:
 
  f.Circ = c # Assign the circle object to the Circ property  
 
  f.Circ = c # Assign the circle object to the Circ property  
 
  doc.recompute()
 
  doc.recompute()
 +
</code>
  
 
=== Accessing and changing representation of an object ===
 
=== Accessing and changing representation of an object ===
Line 139: Line 154:
 
Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how the object appear, like color, linewidth, etc...
 
Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how the object appear, like color, linewidth, etc...
  
 +
<code python>
 
  gad=Gui.activeDocument()  # access the active document containing all  
 
  gad=Gui.activeDocument()  # access the active document containing all  
 
                             # view representations of the features in the
 
                             # view representations of the features in the
Line 146: Line 162:
 
  v.ShapeColor              # prints the color to the console  
 
  v.ShapeColor              # prints the color to the console  
 
  v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white
 
  v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white
 +
</code>
  
 
=== Observing mouse events in the 3D viewer via Python ===
 
=== Observing mouse events in the 3D viewer via Python ===
Line 151: Line 168:
 
The Inventor framework allows to add one or more callback nodes to the scenegraph of the viewer. By default in FreeCAD one callback node is installed per viewer which allows to add global or static C++ functions. In the appropriate Python binding some methods are provided to make use of this technique from within Python code.
 
The Inventor framework allows to add one or more callback nodes to the scenegraph of the viewer. By default in FreeCAD one callback node is installed per viewer which allows to add global or static C++ functions. In the appropriate Python binding some methods are provided to make use of this technique from within Python code.
  
 +
<code python>
 
  App.newDocument()
 
  App.newDocument()
 
  v=Gui.activeDocument().activeView()
 
  v=Gui.activeDocument().activeView()
Line 166: Line 184:
 
  o = ViewObserver()
 
  o = ViewObserver()
 
  c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)
 
  c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)
 +
</code>
  
 
Now, pick somewhere on the area in the 3D viewer and observe the messages in the output window. To finish the observation just call
 
Now, pick somewhere on the area in the 3D viewer and observe the messages in the output window. To finish the observation just call
  
 +
<code python>
 
  v.removeEventCallback("SoMouseButtonEvent",c)
 
  v.removeEventCallback("SoMouseButtonEvent",c)
 +
</code>
  
 
The following event types are supported
 
The following event types are supported

Revision as of 21:51, 9 October 2007

This page contains examples, pieces, chunks of FreeCAD python code collected from users experiences and discussions on the forums. Read and use it as a start for your own scripts...


A typical InitGui.py file

Every module must contain, besides your main module file, an InitGui.py file, responsible for inserting the module in the main Gui. This is an example of a simple one.

class ScriptWorkbench ( Workbench ):

	def Activate(self): 

try: import Scripts # assuming Scripts.py is your module if Gui.HasWorkbench('Scripts') == False: w = Gui.CreateWorkbench('Scripts') list = ["Script_Cmd"] # That list must contain command names, that can be defined in Scripts.py w.AppendToolbar("My Scripts",list) except: raise def GetClassName(self): return "Gui::PythonWorkbench"


Gui.AddWorkbenchHandler("Scripts",ScriptWorkbench())

A typical module file

This is an example of a main module file, containing everything your module does. It is the Scripts.py file invoked by the previous example. You can have all your custom commands here.

import FreeCAD, FreeCADGui 

class ScriptCmd: 
	def Activated(self): 
		# Here your write what your ScriptCmd does...
		FreeCAD.PrintMessage("Hello, World!\n")
	def GetResources(self): 
		return {'Pixmap' : 'path_to_an_icon/myicon.png', 'MenuText': 'Short text', 'ToolTip': 'More detailed text'} 


FreeCADGui.AddCommand('Script_Cmd', ScriptCmd())

Import a new filetype

Making an importer for a new filetype in FreeCAD is easy. FreeCAD doesn't consider that you import data in an opened document, but rather that you simply can directly open the new filetype. So what you need to do is to add the new file extension to FreeCAD's list of known extensions, and write the code that will read the file and create the FreeCAD objects you want:

This line must be added to the InitGui.py file to add the new file extension to the list:


# Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
FreeCAD.EndingAdd("Your new File Type (*.ext)","Import_Ext") 

Then in the Import_Ext.py file:

def open(filename): 
	doc=App.newDocument()
	# here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects
	doc.recompute()

Adding a line

A line simply has 2 points.

import Part,PartGui 
doc=App.activeDocument() 
# add a line element to the document and set its points 
l=doc.addObject("Part::Line","Line") 
l.b=(0.0,0.0,0.0) 
l.e=(1.0,1.0,1.0)
doc.recompute()

Adding a polygon

A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.

import Part,PartGui 
doc=App.activeDocument()
n=list() 
# create a 3D vector, set its coordinates and add it to the list 
v=App.Vector() 
v.set(0,0,0) 
n.append(v) 
v=App.Vector() 
v.set(10,0,0) 
n.append(v) 
#... repeat for all nodes 
# Create a polygon object and set its nodes 
p=doc.addObject("Part::Polygon","Polygon") 
p.Nodes=n 
doc.recompute()

Adding an object to a group

doc=App.activeDocument() 
grp=doc.addObject("App::DocumentObjectGroup", "Group") 
l=grp.addObject("Part::Line", "Line") 
l.b=(0,0,0) 
l.e=(0,0,5) 
doc.recompute()

Adding a Mesh

import Mesh
doc=App.activeDocument()
# create a new empty mesh
m = Mesh.mesh()
# build up box out of 12 facets
m.addFacet(0.0,0.0,0.0, 0.0,0.0,1.0, 0.0,1.0,1.0)
m.addFacet(0.0,0.0,0.0, 0.0,1.0,1.0, 0.0,1.0,0.0)
m.addFacet(0.0,0.0,0.0, 1.0,0.0,0.0, 1.0,0.0,1.0)
m.addFacet(0.0,0.0,0.0, 1.0,0.0,1.0, 0.0,0.0,1.0)
m.addFacet(0.0,0.0,0.0, 0.0,1.0,0.0, 1.0,1.0,0.0)
m.addFacet(0.0,0.0,0.0, 1.0,1.0,0.0, 1.0,0.0,0.0)
m.addFacet(0.0,1.0,0.0, 0.0,1.0,1.0, 1.0,1.0,1.0)
m.addFacet(0.0,1.0,0.0, 1.0,1.0,1.0, 1.0,1.0,0.0)
m.addFacet(0.0,1.0,1.0, 0.0,0.0,1.0, 1.0,0.0,1.0)
m.addFacet(0.0,1.0,1.0, 1.0,0.0,1.0, 1.0,1.0,1.0)
m.addFacet(1.0,1.0,0.0, 1.0,1.0,1.0, 1.0,0.0,1.0)
m.addFacet(1.0,1.0,0.0, 1.0,0.0,1.0, 1.0,0.0,0.0)
# scale to a edge langth of 100
m.scale(100.0)
# add the mesh to the active document
me=doc.addObject("Mesh::Feature","Cube")
me.Mesh=m
doc.recompute()

Adding an arc or a circle

import Part
doc = App.activeDocument()
c = Part.circle() # create a circle object with undefined radius 
c.setRadius(10)  
f = doc.addObject("Part::Circle", "Circle") # create a document with a circle feature 
f.Circ = c # Assign the circle object to the Circ property 
doc.recompute()

Accessing and changing representation of an object

Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how the object appear, like color, linewidth, etc...

gad=Gui.activeDocument()   # access the active document containing all 
                           # view representations of the features in the
                           # corresponding App document 

v=gad.getObject("Cube")    # access the view representation to the Mesh feature 'Cube' 
v.ShapeColor               # prints the color to the console 
v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white

Observing mouse events in the 3D viewer via Python

The Inventor framework allows to add one or more callback nodes to the scenegraph of the viewer. By default in FreeCAD one callback node is installed per viewer which allows to add global or static C++ functions. In the appropriate Python binding some methods are provided to make use of this technique from within Python code.

App.newDocument()
v=Gui.activeDocument().activeView()

#This class logs any mouse button events. As the registered callback function fires twice for 'down' and
#'up' events we need a boolean flag to handle this.
class ViewObserver:
	down=True
	def logPosition(self, x, y):
		if (self.down):
			FreeCAD.PrintMessage("Clicked on position: ("+str(x)+", "+str(y)+")\n")
		self.down = not self.down


o = ViewObserver()
c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)

Now, pick somewhere on the area in the 3D viewer and observe the messages in the output window. To finish the observation just call

v.removeEventCallback("SoMouseButtonEvent",c)

The following event types are supported

  • SoEvent -- all kind of events
  • SoButtonEvent -- all mouse button and key events
  • SoLocation2Event -- 2D movement events (normally mouse movements)
  • SoMotion3Event -- 3D movement events (normally spaceball)
  • SoKeyboradEvent -- key down and up events
  • SoMouseButtonEvent -- mouse button down and up events
  • SoSpaceballButtonEvent -- spaceball button down and up events