Grundlagen der Skripterstellung in FreeCAD

From FreeCAD Documentation
Revision as of 19:06, 4 November 2014 by Renatorivo (talk | contribs) (Created page with "* Im '''GUI-Modul''', werden Sie Werkzeuge für den Zugriff und das Management GUI-Elemente zu finden, wie die Arbeitsbereiche und ihre Symbolleisten, und, noch interessanter,...")

Python scripting in FreeCAD

FreeCAD ist von Grund auf von Python-Skripten gesteuert. Fast alle Teile von FreeCAD wie die Schnittstelle, der Szene-Inhalt, und sogar die Darstellung dieser Inhalte in den 3D-Ansichten sind vom eingebauten Python-Interpreter oder mittels Ihrer eigenen Skripte zugänglich. Infolgedessen ist FreeCAD wahrscheinlich eine der am weitesten anpassbaren Technikanwendungen auf dem Markt.

In seinem aktuellen Zustand hat jedoch FreeCAD sehr wenige "native" Befehle, um auf Ihre 3D-Objekten zu interagieren, vor allem, weil es ist immer noch im frühen Stadium der Entwicklung ist, sondern auch weil die Philosophie dahinter mehr ist, um eine Plattform für die CAD-Entwicklung zur Verfügung zu stellen, als eine spezifische Gebrauch-Anwendung. Aber die Leichtigkeit des Python-Scripting innerhalb FreeCAD ist ein schneller Weg, um neue Funktionalität durch "Power User" zu entwickeln, Benutzer, die typischerweise ein bisschen Python-Programmierung kennen. Python ist eine der populärsten Interpreter-Sprachen, und weil es im allgemeinen als leicht zu erlernen angesehen wird, können auch Sie schon bald Ihre eigenen FreeCAD "Power User"-Skripte erstelen.

Wenn Sie nicht mit Python vertraut sind, empfehlen wir Ihnen, nach Tutorien im Internet zu suchen, um so einen kurzen Blick auf seine Struktur zu bekommen. Python ist eine sehr einfache Sprache zu lernen, vor allem, weil es innerhalb eines Interpreters ausgeführt werden kann, wobei von einfachen Befehlen bis zu vollständigen Programmen alles dynamisch ausgeführt werden kann. Wenn Sie das Fenster mit der Aufschrift "Report-Ansicht", wie unten dargestellt nicht sehen, können Sie es unter der Ansicht-> Ansichten-> Berichtsansicht aktivieren, um den Interpreter anzeigen zu lassen.

Der Interpreter

Über den Interpreter, können Sie auf alle Ihre systeminstallierten Python-Module zugreifen, sowie die eingebaute FreeCAD Module und alle zusätzlichen Module, die Sie später installiert haben. Der folgende Screenshot zeigt den Python-Interpreter:

The FreeCAD Python interpreter

Im Interpreter kann man Python-Code ausführen und die verfügbaren Klassen und Funktion durchsuchen. FreeCAD stellt einen sehr handlichen Klassenbrowser für die Erforschung Ihrer neuen FreeCAD Welt zur Verfügung: Wenn Sie den Namen einer bekannten Klasse gefolgt von einem Punkt tippen (das heißt, Sie wollen etwas von dieser Klasse hinzufügen), öffnet sich ein Klassenbrowser-Fenster, wo Sie zwischen verfügbaren Unterklassen und Methoden navigieren können. Wenn Sie etwas auswählen, wird ein verbundener Hilfstext(falls bestehend) gezeigt:

The FreeCAD class browser

Als Anfang tippen wir '"App."' oder '"Gui."' ein und sehen was passiert. Ein weiterer Python-üblicher Weg zur Erkundung der Inhalte der Module und Klassen ist es, den verwenden. print dir() -Befehl zu nutzen. Zum Beispiel, das Schreiben von print dir() wird alle in FreeCAD zurzeit geladenen Module auflisten. print dir(App) wird Ihnen alles innerhalb des App Moduls anzeigen, usw.

Eine weitere nützliche Funktion des Interpreters ist die Möglichkeit, zurück zu gehen in Kommando-History und eine Zeile des Codes wiederzubekommen, den Sie bereits früher tippten. Um in der zu navigieren, benutzen Sie einfach STRG + HOCH oder STRG + RUNTER.

Mit der rechten Maustaste in der Interpreter-Fenster haben Sie auch einige andere Optionen, wie z. B. Kopie der gesamten Geschichte (nützlich, um hier etwas experimentieren, dann machen Sie eine vollständige Skript davon), oder fügen Sie Dateinamen mit dem ganzen Pfad ein.

Python Hilfe

Im FreeCAD-Hilfsmenü finden Sie einen Eintrag mit der Bezeichnung "Python-Hilfe", der ein Browser-Fenster mit einem vollständigen Überblick in Echtzeit generierter Dokumentation aller Python-Module, die im FreeCAD Interpreter zur Verfügung stehen, einschließlich der Python- und FreeCAD eingebauten Module, systeminstallierten Module, und FreeCAD's zusätzlicher Module. Die vorhandenen Dokumentation hängt davon ab, wie viel Aufwand jeder Modul-Entwickler bei der Dokumentation seines Code einsetzt, aber in der Regel haben Python-Module einen Ruf als ziemlich gut dokumentiert. Damit dieses Dokumentationssystem funktioniert, muss Ihr FreeCAD Fenster offen sein.

Eingebaute Module

Da FreeCAD dafür entworfen ist, ohne Graphische Benutzerschnittstelle geführt zu werden, wird fast seine ganze Funktionalität in zwei Gruppen getrennt: Kernfunktionalität, genannt App, und Gui Funktionalität, genannt Gui. Also sind unsere beiden wichtigsten eingebauten FreeCAD Module die, namens App und GUI. Auf diese zwei Module kann auch von Scripten außerhalb des Interpreters, durch die jeweiligen Namen von FreeCAD und FreeCADGui zugegriffen werden.

  • Im App-Modul, finden Sie alles im Zusammenhang mit der Anwendung selbst, wie Methoden zum Öffnen oder Schließen von Dateien, und zu den Dokumenten, wie z.B. die Einstellung des aktiven Dokuments oder wie sie ihre Inhalte auflisten.
  • Im GUI-Modul, werden Sie Werkzeuge für den Zugriff und das Management GUI-Elemente zu finden, wie die Arbeitsbereiche und ihre Symbolleisten, und, noch interessanter, die grafische Darstellung aller Inhalte in FreeCAD.

Listing all the content of those modules is a bit counter-productive task, since they grow quite fast with FreeCAD development. But the two browsing tools provided (the class browser and the Python help) should give you, at any moment, complete and up-to-date documentation of these modules.

The App and Gui objects

As we said, in FreeCAD, everything is separated between core and representation. This includes the 3D objects too. You can access defining properties of objects (called features in FreeCAD) via the App module, and change the way they are represented on screen via the Gui module. For example, a cube has properties that define it, (like width, length, height) that are stored in an App object, and representation properties, (like faces color, drawing mode) that are stored in a corresponding Gui object.

This way of doing things allows a very wide range of uses, like having algorithms work only on the definition part of features, without the need to care about any visual part, or even redirect the content of the document to non-graphical application, such as lists, spreadsheets, or element analysis.

For every App object in your document, there exists a corresponding Gui object. Infact the document itself has both App and a Gui objects. This, of course, is only valid when you run FreeCAD with its full interface. In the command-line version no GUI exists, so only App objects are availible. Note that the Gui part of objects is re-generated every time an App object is marked as 'to be recomputed' (for example when one of its parameters changes), so changes you might have made directly to the Gui object may be lost.

To access the App part of something, you type:

 myObject = App.ActiveDocument.getObject("ObjectName")

where "ObjectName" is the name of your object. You can also type:

 myObject = App.ActiveDocument.ObjectName

To access the Gui part of the same object, you type:

 myViewObject = Gui.ActiveDocument.getObject("ObjectName")

where "ObjectName" is the name of your object. You can also type:

 myViewObject = App.ActiveDocument.ObjectName.ViewObject

If we have no GUI (for example we are in command-line mode), the last line will return 'None'.

The Document objects

In FreeCAD all your work resides inside Documents. A document contains your geometry and can be saved to a file. Several documents can be opened at the same time. The document, like the geometry contained inside, has App and Gui objects. App object contains your actual geometry definitions, while the Gui object contains the different views of your document. You can open several windows, each one viewing your work with a different zoom factor or point of view. These views are all part of your document's Gui object.

To access the App part the currently open (active) document, you type:

 myDocument = App.ActiveDocument

To create a new document, type:

 myDocument = App.newDocument("Document Name")

To access the Gui part the currently open (active) document, you type:

 myGuiDocument = Gui.ActiveDocument

To access the current view, you type:

 myView = Gui.ActiveDocument.ActiveView

Using additional modules

The FreeCAD and FreeCADGui modules are solely responsibles for creating and managing objects in the FreeCAD document. They don't actually do anything such as creating or modifying geometry. That is because that geometry can be of several types, and so it is managed by additional modules, each responsible for managing a certain geometry type. For example, the Part Module uses the OpenCascade kernel, and therefore is able to create and manipulate B-rep type geometry, which is what OpenCascade is built for. The Mesh Module is able to build and modify mesh objects. That way, FreeCAD is able to handle a wide variety of object types, that can all coexist in the same document, and new types could be added easily in the future.

Creating objects

Each module has its own way to treat its geometry, but one thing they usually all can do is create objects in the document. But the FreeCAD document is also aware of the available object types provided by the modules:

 FreeCAD.ActiveDocument.supportedTypes()

will list you all the possible objects you can create. For example, let's create a mesh (treated by the mesh module) and a part (treated by the part module):

 myMesh = FreeCAD.ActiveDocument.addObject("Mesh::Feature","myMeshName")
 myPart = FreeCAD.ActiveDocument.addObject("Part::Feature","myPartName")

The first argument is the object type, the second the name of the object. Our two objects look almost the same: They don't contain any geometry yet, and most of their properties are the same when you inspect them with dir(myMesh) and dir(myPart). Except for one, myMesh has a "Mesh" property and "Part" has a "Shape" property. That is where the Mesh and Part data are stored. For example, let's create a Part cube and store it in our myPart object:

 import Part
 cube = Part.makeBox(2,2,2)
 myPart.Shape = cube

You could try storing the cube inside the Mesh property of the myMesh object, it will return an error complaining of the wrong type. That is because those properties are made to store only a certain type. In the myMesh's Mesh property, you can only save stuff created with the Mesh module. Note that most modules also have a shortcut to add their geometry to the document:

 import Part
 cube = Part.makeBox(2,2,2)
 Part.show(cube)

Modifying objects

Modifying an object is done the same way:

 import Part
 cube = Part.makeBox(2,2,2)
 myPart.Shape = cube

Now let's change the shape by a bigger one:

 biggercube = Part.makeBox(5,5,5)
 myPart.Shape = biggercube

Querying objects

You can always look at the type of an object like this:

 myObj = FreeCAD.ActiveDocument.getObject("myObjectName")
 print myObj.Type

or know if an object is derived from one of the basic ones (Part Feature, Mesh Feature, etc):

  print myObj.isDerivedFrom("Part::Feature")

Now you can really start playing with FreeCAD! To look at what you can do with the Part Module, read the Part scripting page, or the Mesh Scripting page for working with the Mesh Module. Note that, although the Part and Mesh modules are the most complete and widely used, other modules such as the Draft Module also have scripting APIs that can be useful to you. For a complete list of each modules and their available tools, visit the Category:API section.

Python scripting tutorial
Mesh Scripting