Python scripting tutorial/ru: Difference between revisions
(Updating to match new version of source page) |
No edit summary |
||
(10 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
<languages/> |
<languages/> |
||
⚫ | |||
{{ |
{{Docnav/ru |
||
|[[Introduction_to_Python/ru|Introduction to Python]] |
|||
|Topic=Programming |
|||
|[[FreeCAD_Scripting_Basics/ru|FreeCAD Scripting Basics]] |
|||
|Level=Intermediate |
|||
|Time= |
|||
|Author= |
|||
|FCVersion= |
|||
|Files= |
|||
}} |
}} |
||
{{TOCright}} |
|||
==Введение== |
|||
⚫ | [ |
||
⚫ | [https://ru.wikipedia.org/wiki/Python Python] - это язык программирования, относительно простой в изучении и понимании. Он является многоплатформенным языком с открытым исходным кодом и может использоваться в разных целях: от программирования простых скриптов до очень сложных программ. Но он наиболее распространен как язык сценариев, внедряемых в другие приложения. Так он используется и внутри FreeCAD. Из [[Python_console/ru|консоли Python]] или с помощью собственных скриптов вы можете управлять FreeCAD, заставляя его выполнять очень сложные операции. |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
<div class="mw-translate-fuzzy"> |
<div class="mw-translate-fuzzy"> |
||
Line 45: | Line 43: | ||
</div> |
</div> |
||
There are two ways to write Python code in FreeCAD. In the [[Python console|Python console]] (select {{MenuCommand|View → Panels → Python console}} from the menu) or in the [[Std_DlgMacroExecute|Macro editor]] (select {{MenuCommand|Macro → Macros...}} from the menu). In the console you write Python commands one by one, executing them by pressing {{KEY|Enter}}, while macros can contain more complex code made up of several lines, executed only when the macro is executed. |
|||
[[Image:Screenshot_pythoninterpreter.jpg]] |
|||
<div class="mw-translate-fuzzy"> |
|||
[[Image:Screenshot_pythoninterpreter.jpg|center|frame|The FreeCAD python console]] |
[[Image:Screenshot_pythoninterpreter.jpg|center|frame|The FreeCAD python console]] |
||
</div> |
|||
<div class="mw-translate-fuzzy"> |
|||
В этом руководстве описаны оба метода: либо путем копирования / вставки по одной строчке в python консоли и нажатия {{KEY | Return}} в конце строки, либо путем копирования / вставки всего кода в новое окно макроса. |
В этом руководстве описаны оба метода: либо путем копирования / вставки по одной строчке в python консоли и нажатия {{KEY | Return}} в конце строки, либо путем копирования / вставки всего кода в новое окно макроса. |
||
</div> |
|||
<div class="mw-translate-fuzzy"> |
|||
== Изучение FreeCAD == |
== Изучение FreeCAD == |
||
Начнем с создания нового пустого документа: |
Начнем с создания нового пустого документа: |
||
</div> |
|||
Let's start by creating a new empty document: |
|||
{{Code|code= |
{{Code|code= |
||
Line 56: | Line 65: | ||
}} |
}} |
||
Если Вы вводите это в |
Если Вы вводите это в консоли Python FreeCADа, то заметите, что как только Вы ввели {{incode|FreeCAD.}} (слово FreeCAD с последующей точкой), появится окно, позволяющее быстро автозаполнить продолжение строки. Даже лучше, каждый ввод в списке автодополнения содержит подсказку. Это облегчает раскрытие имеющейся функциональности. Перед выбором {{incode|newDocument}}, взгляните на другие доступные опции. |
||
[[Image:Screenshot_classbrowser.jpg |
[[Image:Screenshot_classbrowser.jpg]] |
||
+ |
|||
{{Caption|Механизм автозаполнения python консоли FreeCAD}} |
|||
<div class="mw-translate-fuzzy"> |
<div class="mw-translate-fuzzy"> |
||
Line 64: | Line 75: | ||
</div> |
</div> |
||
Теперь вернёмся назад в документ |
Теперь вернёмся назад в документ и посмотрим, что мы можем с ним сделать: |
||
{{Code|code= |
{{Code|code= |
||
Line 82: | Line 93: | ||
}} |
}} |
||
Теперь наш куб появился в окне трёхмерного вида. Большинство кнопок панелей инструментов фактически делают две вещи: добавляют объект и выполняют |
Теперь наш куб появился в окне трёхмерного вида. Большинство кнопок панелей инструментов фактически делают две вещи: добавляют объект и выполняют пересчёт. Если Вы включите в настройках опцию {{MenuCommand|"Показывать команды скриптов в консоли python"}} и попробуете добавить сферу с соответствующей кнопкой, Вы увидите две строки Python кода, выполняемые одна за другой. |
||
Вы спросите, как насчет «Part :: Box»? Как мне узнать, как добавить другие объекты? Все здесь: |
|||
{{Code|code= |
|||
doc.supportedTypes() |
|||
⚫ | |||
Теперь рассмотрим содержимое нашего куба: |
Теперь рассмотрим содержимое нашего куба: |
||
Line 108: | Line 113: | ||
}} |
}} |
||
Если вы выберете куб с помощью мыши, вы увидите, что |
Если вы выберете куб с помощью мыши, вы увидите, что [[Property_editor/ru|Property editor]] на вкладке {{MenuCommand|Данные}} появится параметр {{PropertyData|Height}}. Все свойства объекта FreeCAD, которые появляются там (а также на вкладке {{MenuCommand|Вид}}, подробнее об этом позже), напрямую доступны также для Python по их именам, аналогично параметру {{PropertyData|Height}}. Попробуйте изменить другие размеры окна. |
||
== |
==Vectors and Placements== |
||
[http://en.wikipedia.org/wiki/Euclidean_vector Vectors] are a very fundamental concept in any 3D application. |
[http://en.wikipedia.org/wiki/Euclidean_vector Vectors] are a very fundamental concept in any 3D application. A vector is a list of 3 numbers (x, y and z), describing a point or position in 3D space. Many things can be done with vectors, such as additions, subtractions, projections and [http://en.wikipedia.org/wiki/Vector_space much more]. In FreeCAD vectors work like this: |
||
{{Code|code= |
{{Code|code= |
||
myvec = FreeCAD.Vector(2,0,0) |
myvec = FreeCAD.Vector(2,0,0) |
||
myvec |
|||
myvec.x |
myvec.x |
||
myvec.y |
myvec.y |
||
Line 122: | Line 126: | ||
}} |
}} |
||
Another common feature of FreeCAD objects is their [[Placement|placement]]. Each object has a Placement |
Another common feature of FreeCAD objects is their [[Placement|placement]]. Each object has a {{PropertyData|Placement}} property, which contains the {{PropertyData|Base}} (position) and {{PropertyData|Rotation}} (orientation) of the object. It is easy to manipulate, for example to move our object: |
||
{{Code|code= |
{{Code|code= |
||
Line 135: | Line 139: | ||
Now you must understand a couple of important concepts before we get further. |
Now you must understand a couple of important concepts before we get further. |
||
== |
==App and Gui== |
||
FreeCAD is made from the beginning to work as a command-line application, without its user interface. As a result, almost everything is separated between a "geometry" component and a "visual" component. When you work in command-line mode, the geometry part is present, but all the visual part is simply disabled. Almost any object in FreeCAD therefore is made of two parts, an Object and a ViewObject. |
|||
FreeCAD has been designed so that it can also be used without its user interface, as a command-line application. Almost every object in FreeCAD therefore consists of two parts: an {{incode|Object}}, its "geometry" component, and a {{incode|ViewObject}}, its "visual" component. When you work in command-line mode, the geometry part is present, but the visual part is disabled. |
|||
⚫ | To illustrate the concept |
||
⚫ | To illustrate the concept let's look at our cube object. The geometric properties of the cube, such as its dimensions, position, etc. are stored in the {{incode|Object}}. While its visual properties, such as its color, line thickness, etc. are stored in the {{incode|ViewObject}}. This corresponds to the '''Data''' and '''View''' tabs in the [[Property_editor|Property editor]]. The view object of an object is accessed like this: |
||
{{Code|code= |
{{Code|code= |
||
vo = box.ViewObject |
vo = box.ViewObject |
||
}} |
}} |
||
Now you can also change the properties |
Now you can also change the properties on the '''View''' tab: |
||
{{Code|code= |
{{Code|code= |
||
Line 151: | Line 156: | ||
}} |
}} |
||
When you start FreeCAD, the |
When you start FreeCAD, the Python console already loads two base modules: {{incode|FreeCAD}} and {{incode|FreeCADGui}} (which can also be accessed by their shortcuts {{incode|App}} and {{incode|Gui}}). They contain all kinds of generic functionality to work with documents and their objects. To illustrate our concept, see that both {{incode|FreeCAD}} and {{incode|FreeCADGui}} contain an {{incode|ActiveDocument}} attribute, which is the currently opened document. {{incode|FreeCAD.ActiveDocument}} and {{incode|FreeCADGui.ActiveDocument}} are not the same object however. They are the two components of a FreeCAD document, and they contain different attributes and methods. For example, {{incode|FreeCADGui.ActiveDocument}} contains {{incode|ActiveView}}, which is the currently opened [[3D_view|3D view]]. |
||
⚫ | |||
⚫ | The true power of FreeCAD lies in its faithful modules. The FreeCAD base application is more or less an empty container. Without its modules it can do little more than create new, empty documents. Each module not only adds new workbenches to the interface, but also new Python commands and new object types. As a result several different, and even totally incompatible, object types can coexist in the same document. The most important modules in FreeCAD that we'll look at in this tutorial are: [[Part_Module|Part]], [[Mesh_Module|Mesh]], [[Sketcher_Workbench|Sketcher]] and [[Draft_Module|Draft]]. |
||
⚫ | |||
⚫ | |||
[[ |
[[Sketcher_Workbench|Sketcher]] and [[Draft_Module|Draft]] both use the [[Part_Module|Part]] module to create and handle their geometry. While [[Mesh_Module|Mesh]] is totally independent, and handles its own objects. More about that below. |
||
You can check all the available base object types for the current document like this: |
You can check all the available base object types for the current document like this: |
||
Line 164: | Line 170: | ||
}} |
}} |
||
The different FreeCAD modules |
The different FreeCAD modules are not automatically loaded in the Python console. This is to avoid having a very slow startup. Modules are loaded only when you need them. So, for example, to explore what's inside the Part module: |
||
{{Code|code= |
{{Code|code= |
||
Line 173: | Line 179: | ||
But we'll talk more about the Part module below. |
But we'll talk more about the Part module below. |
||
⚫ | |||
By now, you know a bit more about the different modules of FreeCAD: The core modules (FreeCAD, FreeCADGui), and the workbench modules (Part, Mesh, Sketcher). The other important modules are the 3d scene module (pivy) and the interface module (pyside), we'll talk about them too below. |
|||
⚫ | [http://en.wikipedia.org/wiki/Polygon_mesh Meshes] are a very simple kind of 3D object, used for example by [http://en.wikipedia.org/wiki/SketchUp Sketchup], [http://en.wikipedia.org/wiki/Blender_%28software%29 Blender] and [http://en.wikipedia.org/wiki/Autodesk_3ds_Max 3D studio Max]. They are composed of 3 elements: points (also called vertices), lines (also called edges) and faces. In many applications, FreeCAD included, faces can have only 3 vertices. Of course, nothing prevents you from having a bigger face made up of several coplanar triangles. |
||
Now it's time to explore a bit deeper the important ones, which are the workbench modules. |
|||
⚫ | Meshes are simple, but because they are simple you can easily have millions of them in a single document. However, in FreeCAD they have less use and are mostly there so you can import objects in mesh formats ({{FileName|.stl}}, {{FileName|.obj}}) from other applications. The Mesh module was also used extensively as the main test module in the first month of FreeCAD's life. |
||
⚫ | |||
⚫ | [http://en.wikipedia.org/wiki/Polygon_mesh Meshes] are a very simple kind of 3D object, used for example by [http://en.wikipedia.org/wiki/SketchUp Sketchup], [http://en.wikipedia.org/wiki/Blender_%28software%29 Blender] |
||
⚫ | Meshes are simple, but because they are simple you can easily have millions of them in a single document. However, in FreeCAD they have less use and are mostly there so you can import objects in mesh formats (.stl, .obj) from other applications. The Mesh module was also used extensively as the main test module in the first month of FreeCAD's life. |
||
Mesh objects and FreeCAD objects are different things. You can see the FreeCAD object as a container for a Mesh object (and as we'll see below, for Part objects also). So in order to add a mesh object to FreeCAD, we must first create a FreeCAD object and a Mesh object, then add the Mesh object to the FreeCAD object: |
Mesh objects and FreeCAD objects are different things. You can see the FreeCAD object as a container for a Mesh object (and as we'll see below, for Part objects also). So in order to add a mesh object to FreeCAD, we must first create a FreeCAD object and a Mesh object, then add the Mesh object to the FreeCAD object: |
||
Line 188: | Line 190: | ||
import Mesh |
import Mesh |
||
mymesh = Mesh.createSphere() |
mymesh = Mesh.createSphere() |
||
mymesh. |
|||
mymesh.Facets |
mymesh.Facets |
||
mymesh.Points |
mymesh.Points |
||
Line 197: | Line 198: | ||
}} |
}} |
||
This is a standard example that uses the createSphere() method to |
This is a standard example that uses the {{incode|createSphere()}} method to create a sphere, but you can also create custom meshes from scratch by defining their vertices and faces. |
||
[[Mesh Scripting|Read more about mesh scripting...]] |
[[Mesh Scripting|Read more about mesh scripting...]] |
||
== |
==Part== |
||
⚫ | The [[Part Module|Part Module]] is the most powerful module in the whole of FreeCAD. It allows you to create and manipulate [http://en.wikipedia.org/wiki/Boundary_representation BRep] objects. |
||
⚫ | The [[Part Module|Part Module]] is the most powerful module in the whole of FreeCAD. It allows you to create and manipulate [http://en.wikipedia.org/wiki/Boundary_representation BRep] objects. BRep stands for "Boundary Representation". A BRep object is defined by surfaces that enclose and define an inner volume. Unlike meshes, BRep objects can have a wide variety of components from planar faces to very complex NURBS surfaces. |
||
⚫ | |||
⚫ | |||
The Part module works the same way as the Mesh module: You create a FreeCAD object, a Part object, then add the Part object to the FreeCAD object: |
The Part module works the same way as the Mesh module: You create a FreeCAD object, a Part object, then add the Part object to the FreeCAD object: |
||
Line 211: | Line 213: | ||
import Part |
import Part |
||
myshape = Part.makeSphere(10) |
myshape = Part.makeSphere(10) |
||
myshape. |
|||
myshape.Volume |
myshape.Volume |
||
myshape.Area |
myshape.Area |
||
Line 220: | Line 221: | ||
}} |
}} |
||
The Part module (like the Mesh module) also has a shortcut that automatically creates a FreeCAD object and adds a shape to it, so you can shorten the last three lines |
The Part module (like the Mesh module) also has a shortcut that automatically creates a FreeCAD object and adds a shape to it, so you can shorten the last three lines to: |
||
{{Code|code= |
{{Code|code= |
||
Line 226: | Line 227: | ||
}} |
}} |
||
By exploring the contents of myshape, you will notice many interesting subcomponents such as Faces, Edges, Vertexes, Solids and Shells, and a wide range of geometry operations such as cut (subtraction), common (intersection) or fuse (union). The [[ |
By exploring the contents of myshape, you will notice many interesting subcomponents such as {{incode|Faces}}, {{incode|Edges}}, {{incode|Vertexes}}, {{incode|Solids}} and {{incode|Shells}}, and a wide range of geometry operations such as {{incode|cut}} (subtraction), {{incode|common}} (intersection) or {{incode|fuse}} (union). The [[Topological_data_scripting|Topological data scripting]] page explains all that in detail. |
||
[[ |
[[Topological_data_scripting|Read more about part scripting...]] |
||
== |
==Draft== |
||
⚫ | FreeCAD features many more modules, such as [[ |
||
⚫ | FreeCAD features many more modules, such as [[Sketcher_Workbench|Sketcher]] and [[Draft_Module|Draft]], that also create Part objects. These modules add additional parameters to the objects created, or even implement a whole new way to handle the Part geometry in them. Our box example above is a perfect example of a parametric object. All you need to define the box is to specify the parameters height, width and length. Based on those, the object will automatically calculate its Part shape. FreeCAD allows you to [[Scripted_objects|create such objects in Python]]. |
||
⚫ | |||
⚫ | |||
{{Code|code= |
{{Code|code= |
||
import Draft |
import Draft |
||
Draft. |
|||
rec = Draft.makeRectangle(5,2) |
rec = Draft.makeRectangle(5,2) |
||
mvec = FreeCAD.Vector(4,4,0) |
mvec = FreeCAD.Vector(4,4,0) |
||
Line 244: | Line 245: | ||
}} |
}} |
||
== |
==Interface== |
||
The FreeCAD user interface is made with [http://en.wikipedia.org/wiki/Qt_%28framework%29 Qt], a powerful graphical interface system, responsible for drawing and handling all the controls, menus, toolbars and buttons around the 3D view. Qt provides a module, PySide, which allows |
The FreeCAD user interface is made with [http://en.wikipedia.org/wiki/Qt_%28framework%29 Qt], a powerful graphical interface system, responsible for drawing and handling all the controls, menus, toolbars and buttons around the [[3D_view|3D view]]. Qt provides a module, [[PySide]], which allows Python to access and modify Qt interfaces such as FreeCAD's. Let's try to fiddle with the Qt interface and produce a simple dialog: |
||
{{Code|code= |
{{Code|code= |
||
Line 252: | Line 254: | ||
}} |
}} |
||
Notice that the dialog that appears has the FreeCAD icon in its toolbar, meaning that Qt knows that the order has been issued from inside the FreeCAD application. |
Notice that the dialog that appears has the FreeCAD icon in its toolbar, meaning that Qt knows that the order has been issued from inside the FreeCAD application. It is possible to manipulate any part of the FreeCAD interface. |
||
Qt is a very powerful interface system that allows you to do very complex things. It also has some easy-to-use tools such as the Qt Designer with which you can design dialogs graphically and then add them to the FreeCAD interface with a few lines of |
Qt is a very powerful interface system that allows you to do very complex things. It also has some easy-to-use tools such as the Qt Designer with which you can design dialogs graphically and then add them to the FreeCAD interface with a few lines of Python code. |
||
[[PySide|Read more about PySide here...]] |
[[PySide|Read more about PySide here...]] |
||
== |
==Macros== |
||
⚫ | Now that you have a good understanding of the basics, where are we going to keep our |
||
⚫ | Now that you have a good understanding of the basics, where are we going to keep our Python scripts, and how are we going to launch them inside FreeCAD? There is an easy mechanism for that, called [[Macros|Macros]]. A macro is a Python script that can be added to a toolbar and launched via a mouse click. FreeCAD provides you with a simple text editor ({{MenuCommand|Macro → Macros... → Create}}) where you can write or paste scripts. Once the script is done, use {{MenuCommand|Tools → Customize... → Macros}} to define a button for it that can be added to toolbars. |
||
⚫ | |||
⚫ | |||
{{docnav|Introduction to Python|FreeCAD Scripting Basics}} |
|||
{{Docnav |
|||
|[[Introduction_to_Python|Introduction to Python]] |
|||
⚫ | |||
⚫ | |||
{{Powerdocnavi{{#translation:}}}} |
{{Powerdocnavi{{#translation:}}}} |
||
[[Category:Python_Code{{#translation:}}]] |
|||
{{clear}} |
{{clear}} |
Revision as of 19:08, 24 May 2020
Введение
Python - это язык программирования, относительно простой в изучении и понимании. Он является многоплатформенным языком с открытым исходным кодом и может использоваться в разных целях: от программирования простых скриптов до очень сложных программ. Но он наиболее распространен как язык сценариев, внедряемых в другие приложения. Так он используется и внутри FreeCAD. Из консоли Python или с помощью собственных скриптов вы можете управлять FreeCAD, заставляя его выполнять очень сложные операции.
Например, из сценария Python вы можете:
- Создать новые объекты.
- Изменить существующие объекты.
- Изменить трехмерное представление этих объектов.
- Изменить интерфейс FreeCAD.
Существует несколько способов использования python в FreeCAD:
- Из Интерпретатора python в FreeCAD, где вы можете запускать простые команды, симулируя интерфейс командной строки
- Из макросов, которые являются удобным способом быстрого добавления недостающего функционала в интерфейс FreeCAD
- Из внешних скриптов, которые можно использовать для программирования более сложных вещей, таких как Верстаки.
В этом руководстве мы рассмотрим несколько простых примеров, которые помогут вам начать работу. В этой вики также имеется гораздо больше документации по python сценариям. Если вы абсолютный новичок в python и хотите понять, как это работает, у нас есть базовый курс Введение в Python.
"'Важно!'" Перед написанием Python сценариев, перейдите в окно Edit-> Prefences-> General-> Output и проверьте 2 пункта:
- Перенаправить внутренний вывод Python в отчет
- Перенаправить внутренние ошибки Python в отчет
Затем перейдите в View-> Panels и проверьте:
- Отчет
Это сэкономит вам много нервов!
Написание python кода
Существует два простых способа написания Python кода в FreeCAD: в python консоли (меню «Вид-> Панели -> Консоль Python») или из редактора макросов (Инструменты -> Макросы). В консоли вы последовательно пишете python команды, которые выполняются при нажатии return. Макросы могут содержать более сложный много-строчный скрипт, который выполняется во время запуска макроса.
There are two ways to write Python code in FreeCAD. In the Python console (select View → Panels → Python console from the menu) or in the Macro editor (select Macro → Macros... from the menu). In the console you write Python commands one by one, executing them by pressing Enter, while macros can contain more complex code made up of several lines, executed only when the macro is executed.
В этом руководстве описаны оба метода: либо путем копирования / вставки по одной строчке в python консоли и нажатия Return в конце строки, либо путем копирования / вставки всего кода в новое окно макроса.
Изучение FreeCAD
Начнем с создания нового пустого документа:
Let's start by creating a new empty document:
doc = FreeCAD.newDocument()
Если Вы вводите это в консоли Python FreeCADа, то заметите, что как только Вы ввели FreeCAD.
(слово FreeCAD с последующей точкой), появится окно, позволяющее быстро автозаполнить продолжение строки. Даже лучше, каждый ввод в списке автодополнения содержит подсказку. Это облегчает раскрытие имеющейся функциональности. Перед выбором newDocument
, взгляните на другие доступные опции.
Механизм автозаполнения python консоли FreeCAD
Теперь наш новый документ будет создан. Это похоже на нажатие кнопки «новый документ» на панели инструментов. Фактически, большинство кнопок в FreeCAD ничего не делают, кроме выполнения строки или двух python кода. Еще лучше, вы можете установить параметр в Edit-> Preferences-> General-> Macro, чтобы «показать команды сценария в консоли python». Это будет выводить в консоль весь python код, который выполняется при нажатии кнопок. Очень полезно узнать, как воспроизводить действия в python.
Теперь вернёмся назад в документ и посмотрим, что мы можем с ним сделать:
doc.
Изучим доступные варианты. Обычно имена, начинающиеся с заглавной буквы, это атрибуты, они содержат значения, а имена с маленькой буквы являются функциями (называемые так же методами), они "что-то делают". Имена, начинающиеся с подчёркиваний, обычно используются для внутренних нужд модуля, и Вам не следует обращать на них внимание. Используем один из методов для добавления в документ нового объекта:
box = doc.addObject("Part::Box","myBox")
Ничего не произошло. Почему? Потому что FreeCAD создан для больших проектов. Однажды он будет работать с сотнями сложных взаимосвязанных объектов. Возможно, что внесение небольшого изменения может иметь большое значение, вам может потребоваться пересчитать весь документ, что может занять много времени ... По этой причине почти никакая команда не обновляет сцену автоматически. Вы должны сделать это вручную:
doc.recompute()
Теперь наш куб появился в окне трёхмерного вида. Большинство кнопок панелей инструментов фактически делают две вещи: добавляют объект и выполняют пересчёт. Если Вы включите в настройках опцию "Показывать команды скриптов в консоли python" и попробуете добавить сферу с соответствующей кнопкой, Вы увидите две строки Python кода, выполняемые одна за другой.
Теперь рассмотрим содержимое нашего куба:
box.
Вы немедленно увидите несколько очень интересных вещей вроде этого:
box.Height
Это покажет текущую высоту нашего куба. Теперь попробуем её изменить:
box.Height = 5
Если вы выберете куб с помощью мыши, вы увидите, что Property editor на вкладке Данные появится параметр ДанныеHeight. Все свойства объекта FreeCAD, которые появляются там (а также на вкладке Вид, подробнее об этом позже), напрямую доступны также для Python по их именам, аналогично параметру ДанныеHeight. Попробуйте изменить другие размеры окна.
Vectors and Placements
Vectors are a very fundamental concept in any 3D application. A vector is a list of 3 numbers (x, y and z), describing a point or position in 3D space. Many things can be done with vectors, such as additions, subtractions, projections and much more. In FreeCAD vectors work like this:
myvec = FreeCAD.Vector(2,0,0)
myvec.x
myvec.y
othervec = FreeCAD.Vector(0,3,0)
sumvec = myvec.add(othervec)
Another common feature of FreeCAD objects is their placement. Each object has a ДанныеPlacement property, which contains the ДанныеBase (position) and ДанныеRotation (orientation) of the object. It is easy to manipulate, for example to move our object:
box.Placement
box.Placement.Base
box.Placement.Base = sumvec
otherpla = FreeCAD.Placement()
box.Placement = otherpla
Now you must understand a couple of important concepts before we get further.
App and Gui
FreeCAD has been designed so that it can also be used without its user interface, as a command-line application. Almost every object in FreeCAD therefore consists of two parts: an Object
, its "geometry" component, and a ViewObject
, its "visual" component. When you work in command-line mode, the geometry part is present, but the visual part is disabled.
To illustrate the concept let's look at our cube object. The geometric properties of the cube, such as its dimensions, position, etc. are stored in the Object
. While its visual properties, such as its color, line thickness, etc. are stored in the ViewObject
. This corresponds to the Data and View tabs in the Property editor. The view object of an object is accessed like this:
vo = box.ViewObject
Now you can also change the properties on the View tab:
vo.Transparency = 80
vo.hide()
vo.show()
When you start FreeCAD, the Python console already loads two base modules: FreeCAD
and FreeCADGui
(which can also be accessed by their shortcuts App
and Gui
). They contain all kinds of generic functionality to work with documents and their objects. To illustrate our concept, see that both FreeCAD
and FreeCADGui
contain an ActiveDocument
attribute, which is the currently opened document. FreeCAD.ActiveDocument
and FreeCADGui.ActiveDocument
are not the same object however. They are the two components of a FreeCAD document, and they contain different attributes and methods. For example, FreeCADGui.ActiveDocument
contains ActiveView
, which is the currently opened 3D view.
Modules
The true power of FreeCAD lies in its faithful modules. The FreeCAD base application is more or less an empty container. Without its modules it can do little more than create new, empty documents. Each module not only adds new workbenches to the interface, but also new Python commands and new object types. As a result several different, and even totally incompatible, object types can coexist in the same document. The most important modules in FreeCAD that we'll look at in this tutorial are: Part, Mesh, Sketcher and Draft.
Sketcher and Draft both use the Part module to create and handle their geometry. While Mesh is totally independent, and handles its own objects. More about that below.
You can check all the available base object types for the current document like this:
doc.supportedTypes()
The different FreeCAD modules are not automatically loaded in the Python console. This is to avoid having a very slow startup. Modules are loaded only when you need them. So, for example, to explore what's inside the Part module:
import Part
Part.
But we'll talk more about the Part module below.
Mesh
Meshes are a very simple kind of 3D object, used for example by Sketchup, Blender and 3D studio Max. They are composed of 3 elements: points (also called vertices), lines (also called edges) and faces. In many applications, FreeCAD included, faces can have only 3 vertices. Of course, nothing prevents you from having a bigger face made up of several coplanar triangles.
Meshes are simple, but because they are simple you can easily have millions of them in a single document. However, in FreeCAD they have less use and are mostly there so you can import objects in mesh formats (.stl, .obj) from other applications. The Mesh module was also used extensively as the main test module in the first month of FreeCAD's life.
Mesh objects and FreeCAD objects are different things. You can see the FreeCAD object as a container for a Mesh object (and as we'll see below, for Part objects also). So in order to add a mesh object to FreeCAD, we must first create a FreeCAD object and a Mesh object, then add the Mesh object to the FreeCAD object:
import Mesh
mymesh = Mesh.createSphere()
mymesh.Facets
mymesh.Points
meshobj = doc.addObject("Mesh::Feature","MyMesh")
meshobj.Mesh = mymesh
doc.recompute()
This is a standard example that uses the createSphere()
method to create a sphere, but you can also create custom meshes from scratch by defining their vertices and faces.
Read more about mesh scripting...
Part
The Part Module is the most powerful module in the whole of FreeCAD. It allows you to create and manipulate BRep objects. BRep stands for "Boundary Representation". A BRep object is defined by surfaces that enclose and define an inner volume. Unlike meshes, BRep objects can have a wide variety of components from planar faces to very complex NURBS surfaces.
The Part module is based on the powerful OpenCasCade library, which allows a wide range of complex operations to be performed on those objects, such as boolean operations, filleting, lofts, etc.
The Part module works the same way as the Mesh module: You create a FreeCAD object, a Part object, then add the Part object to the FreeCAD object:
import Part
myshape = Part.makeSphere(10)
myshape.Volume
myshape.Area
shapeobj = doc.addObject("Part::Feature","MyShape")
shapeobj.Shape = myshape
doc.recompute()
The Part module (like the Mesh module) also has a shortcut that automatically creates a FreeCAD object and adds a shape to it, so you can shorten the last three lines to:
Part.show(myshape)
By exploring the contents of myshape, you will notice many interesting subcomponents such as Faces
, Edges
, Vertexes
, Solids
and Shells
, and a wide range of geometry operations such as cut
(subtraction), common
(intersection) or fuse
(union). The Topological data scripting page explains all that in detail.
Read more about part scripting...
Draft
FreeCAD features many more modules, such as Sketcher and Draft, that also create Part objects. These modules add additional parameters to the objects created, or even implement a whole new way to handle the Part geometry in them. Our box example above is a perfect example of a parametric object. All you need to define the box is to specify the parameters height, width and length. Based on those, the object will automatically calculate its Part shape. FreeCAD allows you to create such objects in Python.
The Draft Module adds 2D parametric object types (which are all Part objects) such as lines and circles, and also provides some generic functions that not only work on Draft objects, but on any Part object. To explore what is available, simply do:
import Draft
rec = Draft.makeRectangle(5,2)
mvec = FreeCAD.Vector(4,4,0)
Draft.move(rec,mvec)
Draft.move(box,mvec)
Interface
The FreeCAD user interface is made with Qt, a powerful graphical interface system, responsible for drawing and handling all the controls, menus, toolbars and buttons around the 3D view. Qt provides a module, PySide, which allows Python to access and modify Qt interfaces such as FreeCAD's. Let's try to fiddle with the Qt interface and produce a simple dialog:
from PySide import QtGui
QtGui.QMessageBox.information(None,"Apollo program","Houston, we have a problem")
Notice that the dialog that appears has the FreeCAD icon in its toolbar, meaning that Qt knows that the order has been issued from inside the FreeCAD application. It is possible to manipulate any part of the FreeCAD interface.
Qt is a very powerful interface system that allows you to do very complex things. It also has some easy-to-use tools such as the Qt Designer with which you can design dialogs graphically and then add them to the FreeCAD interface with a few lines of Python code.
Read more about PySide here...
Macros
Now that you have a good understanding of the basics, where are we going to keep our Python scripts, and how are we going to launch them inside FreeCAD? There is an easy mechanism for that, called Macros. A macro is a Python script that can be added to a toolbar and launched via a mouse click. FreeCAD provides you with a simple text editor (Macro → Macros... → Create) where you can write or paste scripts. Once the script is done, use Tools → Customize... → Macros to define a button for it that can be added to toolbars.
Now you are ready for more in-depth FreeCAD scripting. So head on to the Power users hub!
- FreeCAD scripting: Python, Introduction to Python, Python scripting tutorial, FreeCAD Scripting Basics
- Modules: Builtin modules, Units, Quantity
- Workbenches: Workbench creation, Gui Commands, Commands, Installing more workbenches
- Meshes and Parts: Mesh Scripting, Topological data scripting, Mesh to Part, PythonOCC
- Parametric objects: Scripted objects, Viewproviders (Custom icon in tree view)
- Scenegraph: Coin (Inventor) scenegraph, Pivy
- Graphical interface: Interface creation, Interface creation completely in Python (1, 2, 3, 4, 5), PySide, PySide examples beginner, intermediate, advanced
- Macros: Macros, How to install macros
- Embedding: Embedding FreeCAD, Embedding FreeCADGui
- Other: Expressions, Code snippets, Line drawing function, FreeCAD vector math library (deprecated)
- Hubs: User hub, Power users hub, Developer hub