FreeCAD einbinden

From FreeCAD Documentation
Revision as of 20:25, 10 October 2014 by Renatorivo (talk | contribs) (Created page with "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 Fre...")

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

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 Blender importieren. Hier ist das komplette Skript.

Ich hoffe, Sie werden durch seine Einfachheit beeindruckt sein:

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

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.

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. tesselate

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