Embedding FreeCAD/ja

他のプログラムやスタンドアローンのPythonコンソールにFreeCADをPythonモジュールとしてインポートするための機能は驚くほど充実しています. FreeCADのモジュールとコンポーネントの全てをまとめてインポートできるのです. FreeCADのGUIをPythonモジュールとしてインポートすることさえできます・・多少の制約はありますが.

GUIなしでFreeCADを使用
まずはじめに思いつく直接的で簡単で便利な応用はFreeCADドキュメントをあなたのプログラムにインポートすることです. 次の例ではFreeCADドキュメントのPartジオメトリーをblenderにインポートしています. スクリプトはこれで全てです. このシンプルさにあなたが感動してくれるといいのですが：

FREECADPATH = '/opt/FreeCAD/lib' # FreeCAD.soファイルまたはFreeCAD.dllファイルのパス import Blender, sys sys.path.append(FREECADPATH) def import_fcstd(filename): try: import FreeCAD except ValueError: Blender.Draw.PupMenu('Error%t|FreeCAD library not found. Please check the FREECADPATH variable in the import script is correct') else: scene = Blender.Scene.GetCurrent import Part doc = FreeCAD.open(filename) objects = doc.Objects for ob in objects: if ob.Type[:4] == 'Part': shape = ob.Shape if shape.Faces: mesh = Blender.Mesh.New rawdata = shape.tessellate(1) for v in rawdata[0]: mesh.verts.append((v.x,v.y,v.z)) for f in rawdata[1]: mesh.faces.append.append(f) scene.objects.new(mesh,ob.Name) Blender.Redraw def main: Blender.Window.FileSelector(import_fcstd, 'IMPORT FCSTD',                        Blender.sys.makename(ext='.fcstd')) if __name__=='__main__': main
 * 1) This lets you import the script without running it

まず重要なのはPythonがちゃんとFreeCADライブラリを見つけ出しているかの確認です. それが済めば私たちが使っているPartなどFreeCADモジュール全てを自動的に利用できるようになります. そこでまずPythonがモジュールを検索する位置を示すsys.path変数を取り、そこにFreeCADのlibのパスを追加しています. ここで行った変更は一時的なものでPythonインタプリタの終了時に消えます. これとは別にFreeCADライブラリをPythonの検索パスの一つにリンクさせることもできます. 今回のスクリプトではパスを定数（FREECADPATH）に入れています. こうしておけば他のユーザーが自分のシステム用にスクリプトを調整するのが簡単になるでしょう.

いったんライブラリのロード（try/except部分）が行われれば、いよいよFreeCADを使って作業を行うことができます. やり方はFreeCAD独自の内部Pythonインタプリタの時と同じです. main関数を使って渡されたFreeCADドキュメントを開き、そのオブジェクトのリストを作成しています. それから関心のあるPartジオメトリーだけを選び出すために各オブジェクトのTypeプロパティに "Part"が入っているかどうか確認し、それをモザイク構造（tessellate）に変換します.

このモザイク構造から頂点のリストと頂点をインデックスとして定義された面のリストが作成されます. これで完璧です. 何しろblenderがメッシュを定義するのと全く同じ方法なのですから. やっていることは馬鹿馬鹿しいほど単純です. ただ両方のリストの内容をblenderのmeshのvertsとfacesに追加するだけです. 全て終わったら画面を再描画して終わりです！

もちろんこのスクリプトは非常に簡単なものなので（実を言うともっと応用的なものも作ってあります）、あなたはこれを拡張したくなるでしょう. 例えばメッシュオブジェクトのインポート、面の無いPartジオメトリーのインポート、FreeCADで読める他のファイルフォーマットのインポートといったものが考えられます. またジオメトリーをFreeCADドキュメントとしてエクスポートしたいと思うかもしれません. 同じようにしてできます. あるいはダイアログを使ってユーザーが何をインポートするか選べるようにしたいと思うかも. 他にもあるでしょう. 実際の所、これら全てに共通して言える利点はあなたが選んだプログラムの結果出力用にFreeCADに基礎となる作業をさせることができる、ということなのです. The first, important part is to make sure python will find our FreeCAD library. Once it finds it, all FreeCAD modules such as Part, that we'll use too, will be available automatically. So we simply take the sys.path variable, which is where python searches for modules, and we append the FreeCAD lib path. This modification is only temporary, and will be lost when we'll close our python interpreter. Another way could be making a link to your FreeCAD library in one of the python search paths. I kept the path in a constant (FREECADPATH) so it'll be easier for another user of the script to configure it to his own system.

Once we are sure the library is loaded (the try/except sequence), we can now work with FreeCAD, the same way as we would inside FreeCAD's own python interpreter. We open the FreeCAD document that is passed to us by the main function, and we make a list of its objects. Then, as we chose only to care about Part geometry, we check if the Type property of each object contains "Part", then we tesselate it.

The tesselation produce a list of vertices and a list of faces defined by vertices indexes. This is perfect, since it is exactly the same way as blender defines meshes. So, our task is ridiculously simple, we just add both lists contents to the verts and faces of a blender mesh. When everything is done, we just redraw the screen, and that's it!

Of course this script is very simple (in fact I made a more advanced here), you might want to extend it, for example importing mesh objects too, or importing Part geometry that has no faces, or import other file formats that FreeCAD can read. You might also want to export geometry to a FreeCAD document, which can be done the same way. You might also want to build a dialog, so the user can choose what to import, etc... The beauty of all this actually lies in the fact that you let FreeCAD do the ground work while presenting its results in the program of your choice.

Using FreeCAD with GUI
From version 4.2 on Qt has the intriguing ability to embed Qt-GUI-dependent plugins into non-Qt host applications and share the host's event loop.

Especially, for FreeCAD this means that it can be imported from within another application with its whole user interface where the host application has full control over FreeCAD, then.

The whole python code to achieve that has only two lines

If the host application is based on Qt then this solution should work on all platforms which Qt supports. However, the host should link the same Qt version as FreeCAD because otherwise you could run into unexpected runtime errors.

For non-Qt applications, however, there are a few limitations you must be aware of. This solution probably doesn't work together with all other toolkits. For Windows it works as long as the host application is directly based on Win32 or any other toolkit that internally uses the Win32 API such as wxWidgets, MFC or WinForms. In order to get it working under X11 the host application must link the "glib" library.

Note, for any console application this solution of course doesn't work because there is no event loop running.

Caveats
Although it is possible to import FreeCAD to an external Python interpreter, this is not a common usage scenario and requires some care. Generally, it is better to use the Python included with FreeCAD, run FreeCAD via command line, or as a subprocess. See Start up and Configuration for more on the last two options.

Since the FreeCAD Python module is compiled from C++ (rather than being a pure Python module), it can only be imported from a compatible Python interpreter. Generally this means that the Python interpreter must be compiled with the same C compiler as was used to build FreeCAD. Information about the compiler used to build a Python interpreter (including the one built with FreeCAD) can be found as follows: