Embedding FreeCAD

From FreeCAD Documentation
Revision as of 20:42, 10 October 2014 by Renatorivo (talk | contribs) (Created page with "När vi är säkra på att biblioteket är laddat(try/except sekvensen), så kan vi nu arbeta med FreeCAD, på samma sätt som vi skulle inuti FreeCAD's egen python tolk. Vi ...")

FreeCAD har den fantastiska förmågan att kunna importeras som en python modul i andra program eller i en python konsol, tilsammans med alla dess moduler och komponenter. Det är även möjligt att importera FreeCAD's gränssnitt som en python modul -- emellertid med några begränsningar.

Använda FreeCAD utan gränssnitt

En första, direkt, lätt och användbar sak du kan göra med detta är att importera FreeCAD dokument in till ditt program. I det följande exemplet, så kommer vi att importera Del geometrin i ett FreeCAD dokument till blender. Här är det kompletta skriptet. Jag hoppas att du kommer att bli imponerad av dess enkelhet:

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

Den första, viktiga delen är att försäkra sig om att python kan hitta vårt FreeCAD bibliotek. När den väl har hittats, så kommer alla FreeCAD moduler som Del, som vi kommer använda, automatiskat att vara tillgängliga. Så vi tar bara sys.path variabeln, vilket är var python söker efter moduler, och lägger till sökvägen till FreeCAD's bibliotek. Denna ändring är endast temporär, och kommer att förloras när vi stänger vår python tolk. Ett annat sätt kan vara att göra en länk till ditt FreeCAD bibliotek i en av python's sökvägar. Jag behöll sökvägen i en konstant (FREECADPATH) så att det blir lättare för en annan användare av skriptet att konfigurera den till sitt eget system.

När vi är säkra på att biblioteket är laddat(try/except sekvensen), så kan vi nu arbeta med FreeCAD, på samma sätt som vi skulle inuti FreeCAD's egen python tolk. Vi öppnar FreeCAD dokumentet som skickats till oss genom main() funktionen, och vi gör en lista på dess objekt. Sedan då vi valde att endast bry oss om Del geometri, så kontrollerar vi om varje objekts Typegenskap innehåller "Part", sedan tesselerar vi den.

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