Embedding FreeCAD/ja: Difference between revisions

From FreeCAD Documentation
(Created page with "他のプログラムやスタンドアローンのPythonコンソールにFreeCADをPythonモジュールとしてインポートするための機能は驚くほど充実し...")
 
(Updating to match new version of source page)
(27 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<languages/>
<languages/>
他のプログラムやスタンドアローンのPythonコンソールにFreeCADをPythonモジュールとしてインポートするための機能は驚くほど充実しています。FreeCADのモジュールとコンポーネントの全てをまとめてインポートできるのです。FreeCADのGUIをPythonモジュールとしてインポートすることさえできます・・多少の制約はありますが。


{{TOCright}}
=== Using FreeCAD without GUI ===

== Introduction ==

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


<div class="mw-translate-fuzzy">
One first, direct, easy and useful application you can make of this is to import FreeCAD documents into your program. In the following example, we'll import the Part geometry of a FreeCAD document into [http://www.blender.org blender]. Here is the complete script. I hope you'll be impressed by its simplicity:<syntaxhighlight>
=== GUIなしでFreeCADを使用 ===
</div>


<div class="mw-translate-fuzzy">
まずはじめに思いつく直接的で簡単で便利な応用はFreeCADドキュメントをあなたのプログラムにインポートすることです。次の例ではFreeCADドキュメントのPartジオメトリーを[http://www.blender.org blender]にインポートしています。スクリプトはこれで全てです。このシンプルさにあなたが感動してくれるといいのですが:
</div>
{{Code|lang=python|code=
<nowiki>
FREECADPATH = '/opt/FreeCAD/lib' # path to your FreeCAD.so or FreeCAD.dll file
FREECADPATH = '/opt/FreeCAD/lib' # path to your FreeCAD.so or FreeCAD.dll file
import Blender, sys
import Blender, sys
Line 40: Line 52:
if __name__=='__main__':
if __name__=='__main__':
main()
main()
</nowiki>
</syntaxhighlight>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.
}}


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


{{Code|lang=python|code=
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!
FREECADPATH = '/opt/FreeCAD/lib' # path to your FreeCAD.so or FreeCAD.dll file
import Blender, sys
sys.path.append(FREECADPATH)
}}


<div class="mw-translate-fuzzy">
Of course this script is very simple (in fact I made a more advanced [http://yorik.orgfree.com/scripts/import_freecad.py 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.
いったんライブラリのロード(try/except部分)が行われれば、いよいよFreeCADを使って作業を行うことができます。やり方はFreeCAD独自の内部Pythonインタプリタの時と同じです。main()関数を使って渡されたFreeCADドキュメントを開き、そのオブジェクトのリストを作成しています。それから関心のあるPartジオメトリーだけを選び出すために各オブジェクトのTypeプロパティに "Part"が入っているかどうか確認し、それをモザイク構造(tessellate)に変換します。
</div>


{{Code|lang=python|code=
=== Using FreeCAD with GUI ===
import Part
doc = FreeCAD.open(filename)
objects = doc.Objects
for ob in objects:
if ob.Type[:4] == 'Part':
}}


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


{{Code|lang=python|code=
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.
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()
}}


<div class="mw-translate-fuzzy">
The whole python code to achieve that has only two lines
もちろんこのスクリプトは非常に簡単なものなので(実を言うともっと応用的なものも[http://yorik.orgfree.com/scripts/import_freecad.py 作ってあります])、あなたはこれを拡張したくなるでしょう。例えばメッシュオブジェクトのインポート、面の無いPartジオメトリーのインポート、FreeCADで読める他のファイルフォーマットのインポートといったものが考えられます。またジオメトリーをFreeCADドキュメントとしてエクスポートしたいと思うかもしれません。同じようにしてできます。あるいはダイアログを使ってユーザーが何をインポートするか選べるようにしたいと思うかも。他にもあるでしょう。実際の所、これら全てに共通して言える利点はあなたが選んだプログラムの結果出力用にFreeCADに基礎となる作業をさせることができる、ということなのです。
</div>


{{Emphasis|Note:}} checkout [[Headless_FreeCAD|Headless FreeCAD]] for running FreeCAD without the GUI.
<syntaxhighlight>

<div class="mw-translate-fuzzy">
=== GUIありでFreeCADを使用 ===
</div>

バージョン4.2からQtには興味深い機能が追加されました。Qt-GUI依存のプラグインを非Qtなホストアプリケーションに埋め込み、ホスト側のイベントループを共有できるようになったのです。

特にFreeCADについて言えば、これは別のアプリケーション内から全体のユーザーインターフェイスごとFreeCADをインポートでき、ホストアプリケーションがFreeCADを完全に制御できるということを意味します。

これを行うためのPythonコードは全部でたったのニ行です。

{{Code|code=
import FreeCADGui
import FreeCADGui
FreeCADGui.showMainWindow()
FreeCADGui.showMainWindow()
}}
</syntaxhighlight>


もしホストアプリケーションがQtベースであればこの方法はQtがサポートされている全てのプラットフォームで動作します。ただしホスト側はFreeCADと同じバージョンのQtとリンクされている必要があります。さもないと予期しない実行時エラーが起きる可能性があります。
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.


非Qtなアプリケーションでも知っておく必要のある制約はごくわずかです。この方法は恐らく他のツールキットと一緒に使っても動作しません。
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.
Windowsの場合、ホストアプリケーションはWin32を直接使用しているかwxWidgets、MFC、WinFormなど内部でWin32APIを使用しているツールキットを使用していなければなりません。X11下で動作するためにはホストアプリケーションは"glib"ライブラリをリンクしている必要があります。
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 ===
== 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.
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:
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:
{{Code|code=

<syntaxhighlight>
>>> import sys
>>> import sys
>>> sys.version
>>> sys.version
'2.7.13 (default, Dec 17 2016, 23:03:43) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]'
'2.7.13 (default, Dec 17 2016, 23:03:43) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]'
}}
</syntaxhighlight>

== Related ==


* [[Headless_FreeCAD|Headless FreeCAD]]


{{docnav|Scripted objects|Code snippets}}


{{Powerdocnavi{{#translation:}}}}
[[Category:Poweruser Documentation]]
[[Category:Python Code]]
[[Category:Developer Documentation{{#translation:}}]]
[[Category:Python Code{{#translation:}}]]
{{clear}}

Revision as of 11:29, 13 March 2021

Introduction

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

GUIなしでFreeCADを使用

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

FREECADPATH = '/opt/FreeCAD/lib' # path to your FreeCAD.so or FreeCAD.dll file
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'))    
 
# This lets you import the script without running it
if __name__=='__main__':
   main()

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

FREECADPATH = '/opt/FreeCAD/lib' # path to your FreeCAD.so or FreeCAD.dll file
import Blender, sys
sys.path.append(FREECADPATH)

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

import Part
       doc = FreeCAD.open(filename)
       objects = doc.Objects
       for ob in objects:
           if ob.Type[:4] == 'Part':

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

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()

もちろんこのスクリプトは非常に簡単なものなので(実を言うともっと応用的なものも作ってあります)、あなたはこれを拡張したくなるでしょう。例えばメッシュオブジェクトのインポート、面の無いPartジオメトリーのインポート、FreeCADで読める他のファイルフォーマットのインポートといったものが考えられます。またジオメトリーをFreeCADドキュメントとしてエクスポートしたいと思うかもしれません。同じようにしてできます。あるいはダイアログを使ってユーザーが何をインポートするか選べるようにしたいと思うかも。他にもあるでしょう。実際の所、これら全てに共通して言える利点はあなたが選んだプログラムの結果出力用にFreeCADに基礎となる作業をさせることができる、ということなのです。

Note: checkout Headless FreeCAD for running FreeCAD without the GUI.

GUIありでFreeCADを使用

バージョン4.2からQtには興味深い機能が追加されました。Qt-GUI依存のプラグインを非Qtなホストアプリケーションに埋め込み、ホスト側のイベントループを共有できるようになったのです。

特にFreeCADについて言えば、これは別のアプリケーション内から全体のユーザーインターフェイスごとFreeCADをインポートでき、ホストアプリケーションがFreeCADを完全に制御できるということを意味します。

これを行うためのPythonコードは全部でたったのニ行です。

import FreeCADGui 
FreeCADGui.showMainWindow()

もしホストアプリケーションがQtベースであればこの方法はQtがサポートされている全てのプラットフォームで動作します。ただしホスト側はFreeCADと同じバージョンのQtとリンクされている必要があります。さもないと予期しない実行時エラーが起きる可能性があります。

非Qtなアプリケーションでも知っておく必要のある制約はごくわずかです。この方法は恐らく他のツールキットと一緒に使っても動作しません。 Windowsの場合、ホストアプリケーションはWin32を直接使用しているかwxWidgets、MFC、WinFormなど内部でWin32APIを使用しているツールキットを使用していなければなりません。X11下で動作するためにはホストアプリケーションは"glib"ライブラリをリンクしている必要があります。

またコンソールアプリケーションではこの方法は使えないことに注意してください。なぜならイベントループ実行が存在しないからです。

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:

>>> import sys
>>> sys.version
'2.7.13 (default, Dec 17 2016, 23:03:43) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]'

Related