Code snippets/ja

このページにはフォーラムでユーザーが作成したり議論した中から集めたFreeCAD用Pythonコードのサンプル、コード片、コードの一部を集めて載せています. あなたのスクリプトの参考にしてください・・・

典型的なInitGui.pyファイル
全てのモジュールにはメインモジュールファイルに加えてメインGUIにモジュールを挿入するためのInitGui.pyファイルが含まれていなければなりません. これはその単純な例です.

class ScriptWorkbench (Workbench): MenuText = "Scripts" def Initialize(self): import Scripts # Scripts.pyがあなたのモジュールとします list = ["Script_Cmd"] # このリストにはScripts.pyで定義されているであろうコマンドの名前が代入されていなければなりません self.appendToolbar("My Scripts",list) Gui.addWorkbench(ScriptWorkbench)

典型的なモジュールファイル
モジュールが行う処理の全てが記載されているメインモジュールファイルの例です. 前の例で呼び出されるScripts.pyファイルです. 自作のコマンドの全てをここに記載します.

import FreeCAD, FreeCADGui class ScriptCmd: def Activated(self): # ここにあなたのScriptCmdが行うことを書きます・・・ FreeCAD.Console.PrintMessage('Hello, World!') def GetResources(self): return {'Pixmap' : 'path_to_an_icon/myicon.png', 'MenuText': 'Short text', 'ToolTip': 'More detailed text'} FreeCADGui.addCommand('Script_Cmd', ScriptCmd)

新しいファイルタイプをインポート
FreeCADでは簡単に新しいファイルタイプ用のインポート処理を作成することができます. FreeCADはデータを開かれているドキュメントからインポートするか、たんに直接新しいファイルタイプを開くかを区別しません. やらなければならないのは新しいファイル拡張子を FreeCADのリストに追加し、そのファイルを読み込んで欲しいFreeCADオブジェクトを作成するコードを書くことだけです：

リストに新しいファイル拡張子を追加するためには以下の行をInitGui.pyに追加しなければなりません：

FreeCAD.addImportType("Your new File Type (*.ext)","Import_Ext")
 * 1) .extファイルを開いて読み込むためのコードがあるファイルをImport_Ext.pyとします

Import_Ext.pyファイルには以下のように書きます：

def open(filename): doc=App.newDocument # 読み込み、データの識別、対応するFreeCADオブジェクトの作成などfilenameを使って行う必要のある全てをここで行います doc.recompute

新しいファイルタイプへのドキュメントのエクスポートも以下の行を使用する以外は同様にして行います： FreeCAD.addExportType("Your new File Type (*.ext)","Export_Ext")

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

Then in the Import_Ext.py file:

To export your document to some new filetype works the same way, except that you use: FreeCAD.addExportType("Your new File Type (*.ext)","Export_Ext")

ラインの追加
ラインは2点を持ちます：

import Part,PartGui doc=App.activeDocument l=Part.Line l.StartPoint=(0.0,0.0,0.0) l.EndPoint=(1.0,1.0,1.0) doc.addObject("Part::Feature","Line").Shape=l.toShape doc.recompute
 * 1) ライン要素をドキュメントに追加し、その点を設定

ポリゴンの追加
ポリゴンはつながった線分の集合（AutoCADでいうポリライン）です. 線分の集合が閉じている必要はありません.

import Part,PartGui doc=App.activeDocument n=list v=App.Vector(0,0,0) n.append(v) v=App.Vector(10,0,0) n.append(v) p=doc.addObject("Part::Polygon","Polygon") p.Nodes=n doc.recompute
 * 1) 3Dベクトルを作成し、座標を設定してリストに追加
 * 1) ・・・全ての節点に対して繰り返します
 * 2) ポリゴンオブジェクトを作成し、その節点を設定

グループに対するオブジェクトの追加と削除
doc=App.activeDocument grp=doc.addObject("App::DocumentObjectGroup", "Group") lin=doc.addObject("Part::Feature", "Line") grp.addObject(lin) # linオブジェクトをグループgrpに追加 grp.removeObject(lin) # linオブジェクトをグループgrpから削除

注意：　グループにグループを追加することも可能です・・・

Note: You can even add other groups to a group...

メッシュの追加
import Mesh doc=App.activeDocument m = Mesh.Mesh 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) m.scale(100.0) me=doc.addObject("Mesh::Feature","Cube") me.Mesh=m
 * 1) 新しい空のメッシュを作成
 * 1) 12のファセットからボックスを作成
 * 1) エッジの長さを100倍にする
 * 1) アクティブなドキュメントにメッシュを追加

円弧または円の追加
import Part doc = App.activeDocument c = Part.Circle c.Radius=10.0 f = doc.addObject("Part::Feature", "Circle") # 円フィーチャーを持つドキュメントを作成 f.Shape = c.toShape # 円シェイプをシェイププロパティに代入 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...

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.

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

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)
 * SoKeyboardEvent -- key down and up events
 * SoMouseButtonEvent -- mouse button down and up events
 * SoSpaceballButtonEvent -- spaceball button down and up events

The Python function that can be registered with addEventCallback expects a dictionary. Depending on the watched event the dictionary can contain different keys. For all events it has the keys: For all button events, i.e. keyboard, mouse or spaceball events For keyboard events: For mouse button event For spaceball events: And finally motion events:
 * Type -- the name of the event type i.e. SoMouseEvent, SoLocation2Event, ...
 * Time -- the current time as string
 * Position -- a tuple of two integers, mouse position
 * ShiftDown -- a boolean, true if Shift was pressed otherwise false
 * CtrlDown -- a boolean, true if Ctrl was pressed otherwise false
 * AltDown -- a boolean, true if Alt was pressed otherwise false
 * State -- A string 'UP' if the button was up, 'DOWN' if it was down or 'UNKNOWN' for all other cases
 * Key -- a character of the pressed key
 * Button -- The pressed button, could be BUTTON1, ..., BUTTON5 or ANY
 * Button -- The pressed button, could be BUTTON1, ..., BUTTON7 or ANY
 * Translation -- a tuple of three floats
 * Rotation -- a quaternion for the rotation, i.e. a tuple of four floats

Display keys pressed and Events command
This macro displays in the report view the keys pressed and all events command

Manipulate the scenegraph in Python
It is also possible to get and change the scenegraph in Python, with the 'pivy' module -- a Python binding for Coin.

The Python API of pivy is created by using the tool SWIG. As we use in FreeCAD some self-written nodes you cannot create them directly in Python. However, it is possible to create a node by its internal name. An instance of the type 'SoFCSelection' can be created with

Adding and removing objects to/from the scenegraph
Adding new nodes to the scenegraph can be done this way. Take care of always adding a SoSeparator to contain the geometry, coordinates and material info of a same object. The following example adds a red line from (0,0,0) to (10,0,0):

To remove it, simply issue:

Adding custom widgets to the interface
You can create custom widgets with Qt designer, transform them into a python script, and then load them into the FreeCAD interface with PySide.

The python code produced by the Ui python compiler (the tool that converts qt-designer .ui files into python code) generally looks like this (it is simple, you can also code it directly in python):

Then, all you need to do is to create a reference to the FreeCAD Qt window, insert a custom widget into it, and "transform" this widget into yours with the Ui code we just made:

Adding a Tab to the Combo View
The following code allows you to add a tab to the FreeCAD ComboView, besides the "Project" and "Tasks" tabs. It also uses the uic module to load an ui file directly in that tab.

Function resident with the mouse click action
Here with SelObserver on a object select

Other example with ViewObserver on a object select or view

Search and data extraction
Examples of research and decoding information on an object.

Each section is independently and is separated by "############" can be copied directly into the Python console, or in a macro or use this macro. The description of the macro in the commentary.

Displaying it in the "View Report" window (View > Views > View report)

Manual search of an element with label
PS: Usually the angles are given in Radian to convert :


 * 1) angle in Degrees to Radians :
 * 2) *Angle in radian = pi * (angle in degree) / 180
 * 3) *Angle in radian = math.radians(angle in degree)
 * 4) angle in Radians to Degrees :
 * 5) *Angle in degree = 180 * (angle in radian) / pi
 * 6) *Angle in degree = math.degrees(angle in radian)

Cartesian coordinates
This code displays the Cartesian coordinates of the selected item.

Change the value of "numberOfPoints" if you want a different number of points (precision)

Other method display on "Int" and "Float"

Create one object to the position of the Camera
here same code simplified

Find normal vector on the surface
This example show how to find normal vector on the surface by find the u,v parameters of one point on the surface and use u,v parameters to find normal vector