FreeCAD Scripting Basics/ru

Написание сценариев Python в FreeCAD
FreeCAD построен с нуля, чтобы быть полностью контролируемым Python сценариями. Почти все части FreeCAD, такие как интерфейс, содержимое сцены, и даже представление этого содержания в окне 3D просмотра доступны из встроенного Python интерпретатора или из своих собственных сценариев. Как результат, FreeCAD вероятно, является одной из наиболее глубоко настраиваемый инженерных приложений, доступных сегодня.

В своем нынешнем состоянии однако, FreeCAD имеет очень мало "родных" команд для взаимодействовия с вашими 3D-объектами, в основном, потому что он все еще находится в ранней стадии развития, но и потому, что философски это больше платформа для развития САD, чем пользовательское приложение. Но простота сценариев на Python внутри FreeCAD, вероятно, поможет гораздо быстрее увидеть новые функциональные возможности, разрабатываемые "продвинутыми пользователями", или, как правило, пользователями, которые немного знают о Python программировании, как мы надеемся, у себя

Если вы не знакомы с Python, мы рекомендуем Вам искать учебники по интернету, и бегло взглянуть на его структуру. Python это очень простой язык для обучения, особенно потому, он может быть сразу запущен внутри интерпритатора, где и простая команда и готовая программа может быть выполнена "на лету", без необходимости компилировать что-либо. FreeCAD имеет встроенный в Python интерпритатор.

Интерпритатор
В интерпретаторе, вы можете получить доступ к установленным в вашей системе модулям Python, а также встроенным модулям FreeCAD, и всем дополнительным модулям FreeCAD что вы установите позже. Скриншот ниже показывает, Python интерпритатор:



В интепритаторе, вы можете выполнять код Python и просматривать доступные классы и функции. FreeCAD предоставляет очень удобный браузер классов для освоения нового мира FreeCAD: Когда вы вводите имя известного класса после точки сразу же появляется (то есть вы хотите добавить что-то из этого класса), окно браузера, где вы можете перемещаться между имеющимися подклассами и методами. При выборе если существует, связанный текст справка, то он отображается:



Таким образом, сначало наберите App. илиGui. посмотрите, что происходит. Другой, более общий Python метод изучения содержимого модулей и классов является использование команды dir. Например, ввод print dir выведет список всех модулей, загруженных в FreeCAD. print dir(App) покажет вам все, что содержит App модуль и.т.д.

Another useful feature of the interpreter is the possibility to go back through the command history and retrieve a line of code that you already typed earlier. To navigate through the command history, just use CTRL+UP or CTRL+DOWN.

By right-clicking in the interpreter window, you also have several other options, such as copy the entire history (useful when you want to experiment with things before making a full script of them), or insert a filename with complete path.

Python Help
In the FreeCAD Help menu, you'll find an entry labeled 'Python help', which will open a browser window containing a complete, realtime-generated documentation of all Python modules available to the FreeCAD interpreter, including Python and FreeCAD built-in modules, system-installed modules, and FreeCAD additional modules. The documentation available there depends on how much effort each module developer put into documenting his code, but usually Python modules have a reputation for being fairly well documented. Your FreeCAD window must stay open for this documentation system to work.

Built-in modules
Since FreeCAD is designed to be run without a Graphical User Interface (GUI), almost all its functionality is separated into two groups: Core functionality, named 'App', and GUI functionality, named 'Gui'. So, our two main FreeCAD built-in modules are called App and Gui. These two modules can also be accessed from scripts outside of the interpreter, by the names 'FreeCAD' and 'FreeCADGui' respectively.


 * In the App module, you'll find everything related to the application itself, like methods for opening or closing files, and to the documents, like setting the active document or listing their contents.


 * In the Gui module, you'll find tools for accessing and managing Gui elements, like the workbenches and their toolbars, and, more interestingly, the graphical representation of all FreeCAD content.

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: where "ObjectName" is the name of your object. You can also type: To access the Gui part of the same object, you type: where "ObjectName" is the name of your object. You can also type: 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: To create a new document, type: To access the Gui part the currently open (active) document, you type: To access the current view, you type:

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

Modifying objects
Modifying an object is done the same way: Now let's change the shape by a bigger one:

Querying objects
You can always look at the type of an object like this: or know if an object is derived from one of the basic ones (Part Feature, Mesh Feature, etc): 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.