Embedding FreeCAD/de: Difference between revisions

From FreeCAD Documentation
mNo edit summary
(Updating to match new version of source page)
Line 1: Line 1:
FreeCAD has the amazing ability to be importable as a python module in other programs or in a standalone python console, together with all its modules and components. It's even possible to import the FreeCAD GUI as python module -- with some restrictions, however.
FreeCAD hat die erstaunliche Fähigkeit, wie ein Python-Modul in anderen Programmen importiert zu laufen oder in einer eigenständigen Python-Konsole importiert, zusammen mit all seinen Modulen und Komponenten.
Es ist sogar möglich, die FreeCAD GUI als Python-Modul zu importieren - mit einigen Einschränkungen allerdings.


=== FreeCAD benutzen ohne GUI ===
=== Using FreeCAD without GUI ===

Eine erste, direkte, einfache und nützliche Anwendung die für Sie daraus entsteht, ist, FreeCAD-Dokumente in Ihre Programme zu importieren.
Im folgenden Beispiel werden wir die Part-Geometrie eines FreeCAD-Dokuments in [http://www.blender.org Blender] importieren. Hier ist das komplette Skript.
Ich hoffe, Sie werden durch seine Einfachheit beeindruckt sein:


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>
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 42: Line 38:
if __name__=='__main__':
if __name__=='__main__':
main()
main()
</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.


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 choosed only to care about Part geometry, we check if the Type property of each object contains "Part", then we tesselate it.
Der erste und wichtigste Teil ist sicherzustellen, das Python unsere FreeCAD-Bibliothek finden wird.
Nachdem Python sie findet, werden alle FreeCAD-Module wie Part, dass wir auch nutzen werden, automatisch zur Verfügung stehen.
Also nehmen wir einfach die sys.path-Variable, wo Python nach Modulen suchen wird, und wir ergänzen Sie um den FreeCAD lib - Pfad.
Diese Änderungen sind nur temporär und gehen verloren, wenn wir unseren Python-Interpreter schließen.
Ein anderer Weg wäre, einen Link zu Ihrer FreeCAD-Bibliothek in einem der Python-Suchpfade anzulegen.
Ich setze den Pfad in einer konstanten (FREECADPATH), so dass es für einen anderen Benutzer des Skripts dann einfacher ist, dieses für sein eigenes System zu konfigurieren.


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!
Sobald wir sicher sind, dass die Bibliothek geladen wird (siehe try/except Sequenz), können wir jetzt auf die gleiche Weise mit FreeCAD arbeiten,
wie wir es Innerhalb des FreeCAD eigenen Python-Interpreters tun würden.
Wir öffnen das FreeCAD-Dokument, das uns von der main()-Funktion übergeben wird, und wir erstellen eine Liste der Objekte.
Da wir uns nur um die Part-geometrie kümmern wollen, überprüfen wir, ob jedes Objekt die Type-Eigenschaft "Part" enthält, dann werden wir es tessellieren. [http://en.wikipedia.org/wiki/Tessellation#Tessellations_and_computer_models tesselate]


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.
Die Tesselation erzeugt eine Liste der Knoten und eine Liste der Flächen, die durch Ecken Indizes definiert wird.
Dies ist Ideal, da es genau auf die gleiche Weise wie Blender Netze definiert.
Somit wird unsere Aufgabe lächerlich einfach, wir übergeben einfach beide Listeninhalte an die Punkte und Flächen von einem Blender-Netz.
Wenn alles fertig ist, lassen wir den Bildschirm neu zeichnen(aufbauen), und das ist alles!


=== Using FreeCAD with GUI ===
Natürlich ist es ein sehr einfaches Skript(tatsächlich habe ich eine erweiterte Version [http://yorik.orgfree.com/scripts/import_freecad.py hier]), dass Sie vielleicht erweitern möchten, z. B. auch zum importieren von Mesh-Objekten, oder importieren von Part-Geometrie ohne Flächen, oder Import anderer Dateiformate, die FreeCAD lesen kann. Vielleicht wollen Sie auch Geometrien ein FreeCAD-Dokument exportieren, was auf die gleiche Weise durchgeführt werden kann. Vielleicht wollen Sie auch einen Dialog aufbauen, womit der Benutzer wählen kann, was zu importieren ist, etc...
Die Schönheit in alle dem liegt in der Tatsache, dass Sie FreeCAD die gesaamte Grundarbeit überlassen, während der Präsentation des Ergebnisses in dem Programm Ihrer Wahl geschiet.


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.
=== FreeCAD nutzen mit GUI ===


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.
Ab der Version 4.2 hat Qt die faszinierende Fähigkeit, Qt-GUI-abhängige-plugins in nicht-Qt-Host-Anwendungen einzubetten und sich an der Ereignis-Schleife des Gastgebers zu beteiligen.


The whole python code to achieve that has only two lines<syntaxhighlight>
Insbesondere für FreeCAD bedeutet dies, dass es aus einer anderen Anwendung mit seiner ganzen Oberfläche importiert werden kann, wobei die Host-Anwendung die volle Kontrolle über FreeCAD behält.

Der ganze Python-Code dies zu erreichen, besteht nur aus zwei Zeilen
import FreeCADGui
import FreeCADGui
FreeCADGui.showMainWindow()
FreeCADGui.showMainWindow()
</syntaxhighlight>
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.
Wenn die Host-Anwendung auf Qt basiert, dann sollte diese Lösung auf allen Plattformen, die Qt unterstützt arbeiten. Allerdings sollte der Host die gleiche Qt-Version wie FreeCAD nutzen, weil man sonst unerwartete Laufzeitfehler erhalten könnte.

Für Nicht-Qt-Anwendungen aber, gibt es ein paar Einschränkungen, die Sie beachten müssen. Diese Lösung wird wahrscheinlich nicht mit allen anderen Toolkits funktionieren.
Für Windows funktioniert es, solange die Host-Anwendung direkt aufbaut auf Win32 oder andere Toolkits, die intern die Win32-API verwenden, wie z.B. wxWidgets, MFC oder WinForms. Damit es unter X11 arbeitet, muss die Host-Anwendung mit der "glib"-Bibliothek verknüpft sein.

Beachten Sie, für Konsole-Anwendungen wird diese Lösung natürlich nicht funktionieren, weil keine Ereignis-Schleife läuft.


{{docnav/de|Scripted objects/de|Code snippets/de}}
{{docnav|Scripted objects|Code snippets}}


[[Category:Poweruser Documentation]]
{{languages/de | {{en|Embedding FreeCAD}} {{cn|Embedding FreeCAD/cn}} {{es|Embedding FreeCAD/es}} {{fr|Embedding FreeCAD/fr}} {{it|Embedding FreeCAD/it}} {{jp|Embedding FreeCAD/jp}} {{se|Embedding FreeCAD/se}} {{ru|Embedding FreeCAD/ru}} }}
[[Category:Python Code]]


{{clear}}
[[Category:Poweruser Documentation/de]]
<languages/>
[[Category:Python Code/de]]

Revision as of 20:03, 10 October 2014

FreeCAD has the amazing ability to be importable as a python module in other programs or in a standalone python console, together with all its modules and components. It's even possible to import the FreeCAD GUI as python module -- with some restrictions, however.

Using FreeCAD without GUI

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 blender. Here is the complete script. I hope you'll be impressed by its simplicity:

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

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

 
 import FreeCADGui 
 FreeCADGui.showMainWindow()

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.

Scripted objects
Code snippets