Scripted objects/pt

Introduction
Besides the standard object types such as annotations, meshes and parts objects, FreeCAD also offers the amazing possibility to build 100% python-scripted parametric objects, called Python Features. Those objects will behave exactly as any other FreeCAD object, and are saved and restored automatically on file save/load.

One particularity must be understood: For security reasons, FreeCAD files never carry any embedded code. The Python code that you write to create parametric objects is never saved inside a file. This means that if you open a file containing such an object on another machine, if that python code is not available on that machine, the object won't be fully recreated. If you distribute such objects to others, you will need to distribute your Python script too, for example as a Macro.

Note: It is possible to pack python code inside a FreeCAD file using json serializing with an App::PropertyPythonObject, but that code can never directly be run, and therefore has little use for our purpose here.

Python Features follow the same rule as all FreeCAD features: they are separated into App and GUI parts. The app part, the Document Object, defines the geometry of our object, while its GUI part, the View Provider Object, defines how the object will be drawn on screen. The View Provider Object, as any other FreeCAD feature, is only available when you run FreeCAD in its own GUI. There are several properties and methods available to build your object. Properties must be of any of the predefined properties types that FreeCAD offers, and will appear in the property view window, so they can be edited by the user. This way, FeaturePython objects are truly and totally parametric. you can define properties for the Object and its ViewObject separately.

Basic example
The following sample can be found in the src/Mod/TemplatePyMod/FeaturePython.py file, together with several other examples:

Things to note
If your object relies on being recomputed as soon as it is created, you must do this manually in the function as it is not called automatically. This example does not require it because the method of the  class has the same effect as the  function, but the examples below rely on being recomputed before anything is displayed in the 3D view. In the examples, this is done manually with but in more complex scenarios you need to decide where to recompute either the whole document or the FeaturePython object.

This example produces a number of exception stack traces in the report view window. This is because the method of the  class is called each time a property is added in. When the first one is added, the Width and Height properties don't exist yet and so the attempt to access them fails.

An explanation of and  is in the forum thread obj.Proxy.Type is a dict, not a string.

Available methods
See FeaturePython methods for the complete reference.

Available properties
Properties are the true building stones of FeaturePython objects. Through them, the user will be able to interact and modify your object. After creating a new FeaturePython object in your document ( obj=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Box") ), you can get a list of the available properties by issuing:

You will get a list of available properties, which are described more in depth on the FeaturePython Custom Properties page:


 * App::PropertyAcceleration
 * App::PropertyAngle
 * App::PropertyArea
 * App::PropertyBool
 * App::PropertyBoolList
 * App::PropertyColor
 * App::PropertyColorList
 * App::PropertyDirection
 * App::PropertyDistance
 * App::PropertyEnumeration
 * App::PropertyExpressionEngine
 * App::PropertyFile
 * App::PropertyFileIncluded
 * App::PropertyFloat
 * App::PropertyFloatConstraint
 * App::PropertyFloatList
 * App::PropertyFont
 * App::PropertyForce
 * App::PropertyFrequency
 * App::PropertyInteger
 * App::PropertyIntegerConstraint
 * App::PropertyIntegerList
 * App::PropertyIntegerSet
 * App::PropertyLength
 * App::PropertyLink
 * App::PropertyLinkChild
 * App::PropertyLinkGlobal
 * App::PropertyLinkHidden
 * App::PropertyLinkList
 * App::PropertyLinkListChild
 * App::PropertyLinkListGlobal
 * App::PropertyLinkListHidden
 * App::PropertyLinkSub
 * App::PropertyLinkSubChild
 * App::PropertyLinkSubGlobal
 * App::PropertyLinkSubHidden
 * App::PropertyLinkSubList
 * App::PropertyLinkSubListChild
 * App::PropertyLinkSubListGlobal
 * App::PropertyLinkSubListHidden
 * App::PropertyMap
 * App::PropertyMaterial
 * App::PropertyMaterialList
 * App::PropertyMatrix
 * App::PropertyPath
 * App::PropertyPercent
 * App::PropertyPersistentObject
 * App::PropertyPlacement
 * App::PropertyPlacementLink
 * App::PropertyPlacementList
 * App::PropertyPosition
 * App::PropertyPrecision
 * App::PropertyPressure
 * App::PropertyPythonObject
 * App::PropertyQuantity
 * App::PropertyQuantityConstraint
 * App::PropertySpeed
 * App::PropertyString
 * App::PropertyStringList
 * App::PropertyUUID
 * App::PropertyVacuumPermittivity
 * App::PropertyVector
 * App::PropertyVectorDistance
 * App::PropertyVectorList
 * App::PropertyVolume
 * App::PropertyXLink
 * App::PropertyXLinkList
 * App::PropertyXLinkSub
 * App::PropertyXLinkSubList
 * Mesh::PropertyCurvatureList
 * Mesh::PropertyMeshKernel
 * Mesh::PropertyNormalList
 * Part::PropertyFilletEdges
 * Part::PropertyGeometryList
 * Part::PropertyPartShape
 * Part::PropertyShapeHistory
 * Path::PropertyPath
 * Path::PropertyTool
 * Path::PropertyTooltable
 * Sketcher::PropertyConstraintList
 * Spreadsheet::PropertyColumnWidths
 * Spreadsheet::PropertyRowHeights
 * Spreadsheet::PropertySheet
 * Spreadsheet::PropertySpreadsheetQuantity
 * TechDraw::PropertyCenterLineList
 * TechDraw::PropertyCosmeticEdgeList
 * TechDraw::PropertyCosmeticVertexList
 * TechDraw::PropertyGeomFormatList

When adding properties to your custom objects, take care of this:
 * Do not use characters "<" or ">" in the properties descriptions (that would break the xml pieces in the .fcstd file)
 * Properties are stored alphabetically in a .fcstd file. If you have a shape in your properties, any property whose name comes after "Shape" in alphabetic order, will be loaded AFTER the shape, which can cause strange behaviours.

A complete list of property attributes can be seen in the PropertyStandard C++ header file. For instance, if you want to allow the user to enter only a limited range of values (e.g. using PropertyIntegerConstraint), in Python you will assign a tuple containing not only the property value, but also the lower and upper limit as well as the stepsize, as below:

Property Type
By default the properties can be updated. It is possible to make the properties read-only, for instance in the case one wants to show the result of a method. It is also possible to hide the property. The property type can be set using:

where mode is a short int that can be set to: 0 -- default mode, read and write 1 -- read-only 2 -- hidden

The EditorModes are not set at FreeCAD file reload. This could to be done by the __setstate__ function. See http://forum.freecadweb.org/viewtopic.php?f=18&t=13460&start=10#p108072. By using the setEditorMode the properties are only read only in PropertyEditor. They could still be changed from python. To really make them read only the setting has to be passed directly inside the addProperty function. See http://forum.freecadweb.org/viewtopic.php?f=18&t=13460&start=20#p109709 for an example.

Using the direct setting in the addProperty function, you also have more possibilities. In particular, an interesting one is mark a property as an output property. This way FreeCAD won't mark the feature as touched when changing it (so no need to recompute).

Example of output property (see also https://forum.freecadweb.org/viewtopic.php?t=24928):

The property types that can be set at last parameter of the addProperty function are: 0 -- Prop_None, No special property type 1 -- Prop_ReadOnly, Property is read-only in the editor 2 -- Prop_Transient, Property won't be saved to file 4 -- Prop_Hidden, Property won't appear in the editor 8 -- Prop_Output, Modified property doesn't touch its parent container 16 -- Prop_NoRecompute, Modified property doesn't touch its container for recompute

You can find these different property types defined in the source code C++ header for PropertyContainer.

Other more complex example
This example makes use of the Part module to create an octahedron, then creates its coin representation with pivy.

First is the Document object itself:

Then, we have the view provider object, responsible for showing the object in the 3D scene:

Finally, once our object and its viewobject are defined, we just need to call them (The Octahedron class and viewprovider class code could be copied in the FreeCAD python console directly):

Making objects selectable
If you want to make your object selectable, or at least part of it, by clicking on it in the viewport, you must include its coin geometry inside a SoFCSelection node. If your object has complex representation, with widgets, annotations, etc, you might want to include only a part of it in a SoFCSelection. Everything that is a SoFCSelection is constantly scanned by FreeCAD to detect selection/preselection, so it makes sense try not to overload it with unneeded scanning.

Once the parts of the scenegraph that are to be selectable are inside SoFCSelection nodes, you then need to provide two methods to handle the selection path. The selection path can take the form of a string giving the names of each element in the path, or of an array of scenegraph objects. The two methods you provide are, which converts from a string path to an array of scenegraph objects, and , which takes an element which has been clicked on in the scenegraph and returns its string name (note, not its string path).

Here is the molecule example above, adapted to make the elements of the molecule selectable:

Working with simple shapes
If your parametric object simply outputs a shape, you don't need to use a view provider object. The shape will be displayed using FreeCAD's standard shape representation:

Same code with use ViewProviderLine

Scenegraph Structure
You may have noticed that the examples above construct their scenegraphs in slightly different ways. Some use while others use.

Each feature in a FreeCAD document is based the following scenegraph structure:

The displays only one of its children, depending on which display mode is selection in FreeCAD.

The examples which use are constructing their scenegraphs solely out of coin3d scenegraph elements. Under the covers, adds a new child to the ; the name of that node will match the display mode it was passed.

The examples which use also construct part of their geometry using functions from the Part workbench, such as. This constructs the different display mode scenegraphs under the ; when we later come to add coin3d elements to the scenegraph, we need to add them to the existing display mode scenegraphs using rather than creating a new child of the.

When using to add geometry to the scenegraph, each display mode should have its own node which is passed to ; don't reuse the same node for this. Doing so will confuse the selection mechanism. It's okay if each display mode's node has the same geometry nodes added below it, just the root of each display mode needs to be distinct.

Here is the above molecule example, adapted to be drawn only with Coin3D scenegraph objects instead of using objects from the Part workbench:

Part Design scripted objects
When making scripted objects in Part Design the process is similar to the scripted objects discussed above, but with a few additional considerations. We must handle 2 shape properties, one for the shape we see in the 3D view and another for the shape used by the pattern tools, such as polar pattern features. The object shapes also needs to be fused to any existing material already in the Body (or cut from it in the case of Subtractive features). And we must account for the placement and attachment of our objects a little bit differently.

Part Design scripted solid object features should be based on either PartDesign::FeaturePython, PartDesign::FeatureAdditivePython, or PartDesign::FeatureSubtractivePython rather than Part::FeaturePython. Only the Additive and Subtractive variants can be used in pattern features, and if based on Part::FeaturePython when the user drops the object into a Part Design Body it becomes a BaseFeature rather than being treated by the Body as a native Part Design object. Note: all of these are expected to be solids, so if you are making a non-solid feature it should be based on Part::FeaturePython or else the next feature in the tree will attempt to fuse to as a solid and it will fail.

Here is a simple example of making a Tube primitive, similar to the Tube primitive in Part Workbench except this one will be a Part Design solid feature object. For this we will 2 separate files: pdtube.FCMacro and pdtube.py. The .FCMacro file will be executed by the user to create the object. The .py file will hold the class definitions, imported by the .FCMacro. The reason for doing it this way is to maintain the parametric nature of the object after restarting FreeCAD and opening a document containing one of our Tubes.

First, the class definition file:

And now the macro file to create the object:

Further information
Additional pages:
 * Scripted objects saving attributes
 * Scripted objects migration
 * Scripted objects with attachment
 * Viewproviders

Interesting forum threads about scripted objects:


 * Python object attributes lost at load
 * New FeaturePython is grey
 * Explanation on __getstate__ and __setstate__, official documentation
 * Eigenmode frequency always 0?
 * how to implement python feature's setEdit properly?

In addition to the examples presented here have a look at FreeCAD source code src/Mod/TemplatePyMod/FeaturePython.py for more examples.