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 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, those objects are saved in FreeCAD FcStd files with python's json module. That module turns a python object as a string, allowing it to be added to the saved file. On load, the json module uses that string to recreate the original object, provided it has access to the source code that created the object. This means that if you save such a custom object and open it on a machine where the python code that generated the object is not present, the object won't be recreated. If you distribute such objects to others, you will need to distribute the python script that created it together.

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.

Hint: In former versions we used Python's cPickle module. However, this module executes arbitrary code and thus causes a security problem. Thus, we moved to Python's json module.

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 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:

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:

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.