Scripted objects/zh-cn

Introduction
除了象标注，网格和零件这些标准物体类型外, FreeCAD还提供100%用python脚本构建的物体, 叫做Python Features. 这些物体将和其他FreeCAD物体有一样的行为, 并将在文件save/load.r时自动保存和加载.

一个需特别注意的是这些物体是保存在FreeCAD的FcStd文件中. 这是用python的json 实现的. 这一模块把python物体变成字串, 以便添加到保存的文件里. 加载时json模块用这一字串，再建为原来的物体. 前提是能够使用创建物体的源码. 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.

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.

初级例子
如下例子的源码在src/Mod/TemplatePyMod/FeaturePython.py 文件中. 该目录下里面还有一些其他例子:

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.

可用属性
属性是真正构成FeaturePython物体的基石. 通过属性，用户可以控制和修改物体. 你在文档中创建一个新的FeaturePython物体后 ( obj=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Box") ), 要得到可用属性的列表，你可执行:

你可以列出所有属性:
 * 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

在给定制物体添加属性时需注意如下事项:
 * 不要在属性的描述里使用字符 "<" or ">" (这将破坏 .fcstd 文件中xml部分. )
 * 属性在 .fcstd 文件中是按字母顺序保存的. 假如在你的属性中有一个shape属性, 那些名字排在"Shape"之后的属性将在shape之后加载. 这会导致一下意外的行为.

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:

属性的类别
缺省状态下属性可以被更新. 让属性只读是可以的, 比如在希望显示执行一个方法后结果的情况下. 隐藏属性也是可以的. 可用如下方法设置属性的类别

其中mode是一个短整型变量，按如下设置: 0 -- 缺省设置, 可读写 1 -- 只读 2 -- 隐藏

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

其它更复杂的例子
这个例子利用 零件模块 来创建一个八面体, 然后用pivy创建它的coin表达.

首先是Document文档物体本身:

然后是负责物体在3D场景中显示的物体:

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.