Topological data scripting/ru: Difference between revisions

From FreeCAD Documentation
(Created page with "Вы можете узнать длинну и центр ребра, вот так:")
(Updating to match new version of source page)
 
(312 intermediate revisions by 5 users not shown)
Line 1: Line 1:
<languages/>
This page describes several methods for creating and modifying [[Part Module|Part shapes]] from python. Before reading this page, if you are new to python, it is a good idea to read about [[Introduction to Python|python scripting]] and [[FreeCAD Scripting Basics|how python scripting works in FreeCAD]].


{{Docnav/ru
== Introduction ==
|[[Part_scripting/ru|Part scripting]]
We will here explain you how to control the [[Part Module]] directly from the FreeCAD python interpreter, or from any external script. The basics about Topological data scripting are described in [[Part_Module#Explaining_the_concepts|Part Module Explaining the concepts]]. Be sure to browse the [[Scripting]] section and the [[FreeCAD Scripting Basics]] pages if you need more information about how python scripting works in FreeCAD.
|[[Scripted_objects/ru|Программируемые объекты]]
}}


{{TOCright}}


<span id="Introduction"></span>
Здесь мы объясним вам как управлять [[Part Module/ru|Модулем Деталей]] напрямую из интепритатора python FreeCAD, или из любого внешнего сценария. Для уверенности , просмотрите раздел [[Scripting/ru|Написание Сценариев]] и страницу [[FreeCAD Scripting Basics/ru|Основ сценариев в FreeCAD]] если вам необходимо больше информации, о том как работает написание сценариев в FreeCAD.
==Введение==


Здесь мы объясним вам, как управлять [[Part_Workbench/ru|верстаком Part]] непосредственно из интерпретатора Python FreeCAD или из любого внешнего сценария. Основы создания сценариев топологических данных описаны в [[Part_Workbench/ru#Explaining_the_concepts|объяснение концепции модуля Part]]. Обязательно просмотрите раздел [[Scripting/ru|Scripting]] и страницы [[FreeCAD_Scripting_Basics/ru|Основы скриптинга FreeCAD]], если вам нужна дополнительная информация о том, как работает python-скриптинг во FreeCAD .
Для первого использования функциональности модуля Деталей вы должны загрузить модуль Деталей в интепретатор:
<code python>
import Part
</code>


<span id="See_also"></span>
=== Диаграмма Классов ===
===Смотрите также===
Это UML обзор наиболее важных классов модуля Деталей:

[[Image:Part_Classes.jpg|center|Python классы содержащиеся в модуле Деталей]]
* [[Part_scripting|Part scripting]]
* [[OpenCASCADE|OpenCASCADE]]

<span id="Class_diagram"></span>
==Диаграмма классов==

Это обзор наиболее важных классов модуля Part через [http://en.wikipedia.org/wiki/Unified_Modeling_Language Unified Modeling Language (UML)]:
[[Image:Part_Classes.jpg|center|Классы Python, содержащиеся в модуле Part]]
{{Top}}
<span id="Geometry"></span>
===Геометрия===


=== Геометрия ===
Геометрические объекты являются строительными блоками для всех топологических объектов:
Геометрические объекты являются строительными блоками для всех топологических объектов:
* '''GEOM''' Базовый класс геометрических объектов
* '''Geom''' Базовый класс геометрических объектов.
* '''LINE''' Прямая линия в 3D, задается начальной и конечной точкой
* '''Line''' Прямая линия в 3D, задается начальной и конечной точкой.
* '''CIRCLE''' Окружность или дуга задается центром, начальной и конечной точкой
* '''Circle''' Окружность или дуга задается центром, начальной и конечной точкой.
* и так далее...
* '''......''' И вскоре еще немного
{{Top}}
<span id="Topology"></span>
===Топология===


<div class="mw-translate-fuzzy">
=== Топология ===
Доступны нижеследующие топологические типы данных:
Доступны нижеследующие топологические типы данных:
* '''COMPOUND''' Группа из топологических объектов любого типа.
* '''COMPOUND''' Группа из топологических объектов любого типа.
Line 29: Line 43:
* '''SOLID''' Часть пространства ограниченная оболочкой. Она трехмерная.
* '''SOLID''' Часть пространства ограниченная оболочкой. Она трехмерная.
* '''SHELL''' Набор граней соединенных между собой через ребра. Оболочки могут быть открытыми или закрытыми.
* '''SHELL''' Набор граней соединенных между собой через ребра. Оболочки могут быть открытыми или закрытыми.
* '''FACE''' В 2D это часть плоскости; в 3D это часть поверхности. Это геометрия ограничена (обрезана) по контуам. Она двухмерная.
* '''FACE''' В 2D это часть плоскости; в 3D это часть поверхности. Это геометрия ограничена (обрезана) по контурам. Она двухмерная.
* '''WIRE''' Набор ребер соединенных через вершины. Он может быть как открытым, так и закрытым в зависимости от того связаны ли крайние ребра или нет.
* '''WIRE''' Набор ребер соединенных через вершины. Он может быть как открытым, так и закрытым в зависимости от того связаны ли крайние ребра или нет.
* '''EDGE''' Топологический элемент соответствующий ограниченной кривой. Ребро как правило ограничивается вершинами. Оно одномерное.
* '''EDGE''' Топологический элемент соответствующий ограниченной кривой. Ребро как правило ограничивается вершинами. Оно одномерное.
* '''VERTEX''' Топологический элемент соответствующий точке. Обладает нулевой размерность.
* '''VERTEX''' Топологический элемент соответствующий точке. Обладает нулевой размерность.
* '''SHAPE''' общий термин охватывающий все выше сказанное.
* '''SHAPE''' общий термин охватывающий все выше сказанное.
</div>
{{Top}}
<span id="Example:_Create_simple_topology"></span>
==Примеры: Создание простейшей топологии==


[[Image:Wire.png|Wire]]
=== Quick example : Creating simple topology ===


<div class="mw-translate-fuzzy">
[[Image:Wire.png|right|Wire]]
Теперь мы создадим топологию из геометрических примитивов.
Для изучения мы используем деталь(part), как показано на картинке состоящую из четырех вершин, двух окружностей и двух линий.
</div>
{{Top}}
<span id="Create_geometry"></span>
===Создание геометрии===


<div class="mw-translate-fuzzy">
We will now create a topology by constructing it out of simpler geometry.
В начале мы должны создать отдельную деталь из данной ломаной.
As a case study we use a part as seen in the picture which consists of
И мы должны убедиться что вершины геометрических частей расположены '''на тех же''' позициях. В противном случае позже мы не смогли бы соединить геометрические части в топологию!
four vertexes, two circles and two lines.
</div>


Итак, сначала мы создаем точки:
==== Creating Geometry ====
First we have to create the distinct geometric parts of this wire.
And we have to take care that the vertexes of the geometric parts
are at the '''same''' position. Otherwise later on we might not be
able to connect the geometric parts to a topology!


{{Code|code=
So we create first the points:
import FreeCAD as App
<syntaxhighlight>
from FreeCAD import Base
import Part
V1 = Base.Vector(0,10,0)
V1 = App.Vector(0, 10, 0)
V2 = Base.Vector(30,10,0)
V2 = App.Vector(30, 10, 0)
V3 = Base.Vector(30,-10,0)
V3 = App.Vector(30, -10, 0)
V4 = Base.Vector(0,-10,0)
V4 = App.Vector(0, -10, 0)
}}
</syntaxhighlight>
{{Top}}
==== Arc ====
<span id="Arc"></span>
===Дуга===


[[Image:Circel.png|right|Circle]]
[[Image:Circel.png|Circle]]


To create an arc of circle we make a helper point and create the arc of
circle through three points:
<syntaxhighlight>
VC1 = Base.Vector(-10,0,0)
C1 = Part.Arc(V1,VC1,V4)
# and the second one
VC2 = Base.Vector(40,0,0)
C2 = Part.Arc(V2,VC2,V3)
</syntaxhighlight>
==== Line ====


Для каждой дуги нам нужно создать вспомогательную точку и провести дугу через три точки:
[[Image:Line.png|right|Line]]


{{Code|code=
The line can be created very simple out of the points:
VC1 = App.Vector(-10, 0, 0)
<syntaxhighlight>
L1 = Part.Line(V1,V2)
C1 = Part.Arc(V1, VC1, V4)
VC2 = App.Vector(40, 0, 0)
# and the second one
L2 = Part.Line(V4,V3)
C2 = Part.Arc(V2, VC2, V3)
}}
</syntaxhighlight>
{{Top}}
==== Putting all together ====
<span id="Line"></span>
The last step is to put the geometric base elements together
===Линия===
and bake a topological shape:

<syntaxhighlight>
[[Image:Line.png|Line]]
S1 = Part.Shape([C1,C2,L1,L2])

</syntaxhighlight>

==== Make a prism ====
Сегменты линии могут быть созданы из двух точек:
Now extrude the wire in a direction and make an actual 3D shape:

<syntaxhighlight>
{{Code|code=
L1 = Part.LineSegment(V1, V2)
L2 = Part.LineSegment(V3, V4)
}}
{{Top}}
<span id="Put_it_all_together"></span>
===Соединяем все вместе===

<div class="mw-translate-fuzzy">
Последний шаг - собираем все основные геометрические элементы вместе и получаем форму:
</div>

{{Code|code=
S1 = Part.Shape([C1, L1, C2, L2])
}}
{{Top}}
<span id="Make_a_prism"></span>
===Создание призмы===

Теперь вытягиваем ломанную по направлению и фактически получаем 3D форму:

{{Code|code=
W = Part.Wire(S1.Edges)
W = Part.Wire(S1.Edges)
P = W.extrude(Base.Vector(0,0,10))
P = W.extrude(App.Vector(0, 0, 10))
}}
</syntaxhighlight>
{{Top}}
==== Show it all ====
<span id="Show_it_all"></span>
<syntaxhighlight>
===Показать всё===

{{Code|code=
Part.show(P)
Part.show(P)
}}
</syntaxhighlight>
{{Top}}
=== Краткое описание ===
<span id="Create_basic_shapes"></span>
==Создание простых фигур==


Вы легко можете создать базовый топологический объект с помощью методов "make...()" содержащихся в модуле Деталей:
Вы легко можете создавать простые топологические объекты с помощью методов {{incode|make...()}} содержащихся в модуле Part:

<syntaxhighlight>
{{Code|code=
b = Part.makeBox(100,100,100)
b = Part.makeBox(100, 100, 100)
Part.show(b)
Part.show(b)
}}
</syntaxhighlight>

Куча других доступных make...() методов:
<div class="mw-translate-fuzzy">
* makeBox(l,w,h,[p,d]) -- Создает коробку расположенную в точке p и в указанном направлении d с размерами (l,w,h). По умолчанию p установлен как Vector(0,0,0) и d установлен как Vector(0,0,1)
Доступные make...() методы:
* makeBox(l,w,h,[p,d]) : создает прямоугольник, с началом в точке p и вытянутый в направлении d с размерами (l,w,h) По умолчанию p установлен как Vector(0,0,0) и d установлен как Vector(0,0,1)
* makeCircle(radius,[p,d,angle1,angle2]) -- Создает окружность с заданным радиусом. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0 и angle2=360
* makeCircle(radius,[p,d,angle1,angle2]) -- Создает окружность с заданным радиусом. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0 и angle2=360
* makeCompound(list) -- Создает составное тело из списка форм
* makeCone(radius1,radius2,height,[p,d,angle]) -- Создает конус с заданным радиусами и высотой. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1) и angle=360
* makeCone(radius1,radius2,height,[p,d,angle]) -- Создает конус с заданным радиусами и высотой. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1) и angle=360
* makeCylinder(radius,height,[p,d,angle]) -- Создает цилиндр с заданным радиусом и высотой. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1) и angle=360
* makeCylinder(radius,height,[p,d,angle]) -- Создает цилиндр с заданным радиусом и высотой. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1) и angle=360
Line 113: Line 155:
* makePolygon(list) -- Создает многоугольник из списка точек
* makePolygon(list) -- Создает многоугольник из списка точек
* makeSphere(radius,[p,d,angle1,angle2,angle3]) -- Создает сферу с заданным радиусом. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0, angle2=90 и angle3=360
* makeSphere(radius,[p,d,angle1,angle2,angle3]) -- Создает сферу с заданным радиусом. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0, angle2=90 и angle3=360
* makeTorus(radius1,radius2,[p,d,angle1,angle2,angle3]) -- Создает тор по заданными радиусамi.По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0, angle2=360 и angle3=360
* makeTorus(radius1,radius2,[p,d,angle1,angle2,angle3]) -- Создает тор по заданными радиусам.По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0, angle2=360 и angle3=360


На странице [[Part API]] приведен полный список доступных методов модуля Part.
See the [[Part API]] page for a complete list of available methods of the Part module.
</div>
{{Top}}
<span id="Import_modules"></span>
===Импорт необходимых модулей===


<div class="mw-translate-fuzzy">
=== Подробные объяснения ===
В начале нам нужно импортировать модуль Part, чтобы мы могли использовать его содержимое в Python. Также импортируем модуль Base из модуля FreeCAD:
</div>


{{Code|code=
Сначала импортируем следующее:
import FreeCAD as App
<syntaxhighlight>
import Part
import Part
}}
from FreeCAD import Base
{{Top}}
</syntaxhighlight>
<span id="Create_a_vector"></span>
==== Creating a Vector ====
===Создание вектора===
[http://en.wikipedia.org/wiki/Euclidean_vector Vectors] are one of the most

important pieces of information when building shapes. They contain a 3 numbers
<div class="mw-translate-fuzzy">
usually (but not necessarily always) the x, y and z cartesian coordinates. You
[http://en.wikipedia.org/wiki/Euclidean_vector Векторы] являются одними из самых важных частей информации при построении фигур. Они обычно содержат три числа (но не всегда): декартовы координаты x, y и z. Для
create a vector like this:
создания вектора введите:
<syntaxhighlight>
</div>
myVector = Base.Vector(3,2,0)

</syntaxhighlight>
{{Code|code=
We just created a vector at coordinates x=3, y=2, z=0. In the Part module,
myVector = App.Vector(3, 2, 0)
vectors are used everywhere. Part shapes also use another kind of point
}}
representation, called Vertex, which is acually nothing else than a container

for a vector. You access the vector of a vertex like this:
<div class="mw-translate-fuzzy">
<syntaxhighlight>
Мы только что создали вектор с координатами x = 3, y = 2, z = 0. В модуле Part векторы используются повсеместно. Формы детали также используют другой тип представления точек, называемый Vertex, который является просто контейнером для вектора. Вы можете получить доступ к вектору вершины следующим образом:
</div>

{{Code|code=
myVertex = myShape.Vertexes[0]
myVertex = myShape.Vertexes[0]
print myVertex.Point
print(myVertex.Point)
> Vector (3, 2, 0)
> Vector (3, 2, 0)
}}
</syntaxhighlight>
{{Top}}
====Как создать Ребро?====
<span id="Create_an_edge"></span>
===Создание ребра===


Ребра не что иное как линия с двумя вершинами:
Ребра это не что иное, как линия с двумя вершинами:

<syntaxhighlight>
{{Code|code=
edge = Part.makeLine((0,0,0), (10,0,0))
edge = Part.makeLine((0, 0, 0), (10, 0, 0))
edge.Vertexes
edge.Vertexes
> [<Vertex object at 01877430>, <Vertex object at 014888E0>]
> [<Vertex object at 01877430>, <Vertex object at 014888E0>]
}}
</syntaxhighlight>

Примечание: Вы не можете создать ребро передав две вершины.
Примечание: Вы можете создать ребро передав два вектора.
<syntaxhighlight>

vec1 = Base.Vector(0,0,0)
{{Code|code=
vec2 = Base.Vector(10,0,0)
line = Part.Line(vec1,vec2)
vec1 = App.Vector(0, 0, 0)
vec2 = App.Vector(10, 0, 0)
line = Part.LineSegment(vec1, vec2)
edge = line.toShape()
edge = line.toShape()
}}
</syntaxhighlight>

Вы можете узнать длинну и центр ребра, вот так:
Вы можете узнать длину и центр ребра, вот так:
<syntaxhighlight>

{{Code|code=
edge.Length
edge.Length
> 10.0
> 10.0
edge.CenterOfMass
edge.CenterOfMass
> Vector (5, 0, 0)
> Vector (5, 0, 0)
}}
</syntaxhighlight>
{{Top}}
==== Putting the shape on screen ====
<span id="Put_the_shape_on_screen"></span>
So far we created an edge object, but it doesn't appear anywhere on screen.
===Вывод фигуры на экран===
This is because we just manipulated python objects here. The FreeCAD 3D scene

only displays what you tell it to display. To do that, we use this simple
До сих пор мы создали объект ребро, но не увидели его на экране. Это связано с тем, что 3D-сцена FreeCAD отображает только то, что указано для отображения. Для этого мы используем этот простой метод:
method:

<syntaxhighlight>
{{Code|code=
Part.show(edge)
Part.show(edge)
}}
</syntaxhighlight>

An object will be created in our FreeCAD document, and our "edge" shape
<div class="mw-translate-fuzzy">
will be attributed to it. Use this whenever it's time to display your
Функция show создает объект "shape" в нашем FreeCAD документе. Используйте это всякий раз, когда пришло время показать свое творение на экране.
creation on screen.
</div>
{{Top}}
<span id="Create_a_wire"></span>
===Создание ломанной кривой===

Ломаная представляет собой многогранную линию и может быть создан из списка ребер или даже из списка ломаных:


{{Code|code=
==== Creating a Wire ====
edge1 = Part.makeLine((0, 0, 0), (10, 0, 0))
A wire is a multi-edge line and can be created from a list of edges
edge2 = Part.makeLine((10, 0, 0), (10, 10, 0))
or even a list of wires:
wire1 = Part.Wire([edge1, edge2])
<syntaxhighlight>
edge1 = Part.makeLine((0,0,0), (10,0,0))
edge3 = Part.makeLine((10, 10, 0), (0, 10, 0))
edge2 = Part.makeLine((10,0,0), (10,10,0))
edge4 = Part.makeLine((0, 10, 0), (0, 0, 0))
wire1 = Part.Wire([edge1,edge2])
wire2 = Part.Wire([edge3, edge4])
edge3 = Part.makeLine((10,10,0), (0,10,0))
wire3 = Part.Wire([wire1, wire2])
edge4 = Part.makeLine((0,10,0), (0,0,0))
wire2 = Part.Wire([edge3,edge4])
wire3 = Part.Wire([wire1,wire2])
wire3.Edges
wire3.Edges
> [<Edge object at 016695F8>, <Edge object at 0197AED8>, <Edge object at 01828B20>, <Edge object at 0190A788>]
> [<Edge object at 016695F8>, <Edge object at 0197AED8>, <Edge object at 01828B20>, <Edge object at 0190A788>]
Part.show(wire3)
Part.show(wire3)
}}
</syntaxhighlight>

Part.show(wire3) will display the 4 edges that compose our wire. Other
<div class="mw-translate-fuzzy">
useful information can be easily retrieved:
Part.show(wire3) пакажет 4 ребра, из которых состоит наша ломаная линяи. Другая полезная информация может быть легко найдена:
<syntaxhighlight>
</div>

{{Code|code=
wire3.Length
wire3.Length
> 40.0
> 40.0
Line 201: Line 267:
wire2.isClosed()
wire2.isClosed()
> False
> False
}}
</syntaxhighlight>
{{Top}}
==== Creating a Face ====
<span id="Create_a_face"></span>
Only faces created from closed wires will be valid. In this example, wire3
===Создание грани===
is a closed wire but wire2 is not a closed wire (see above)

<syntaxhighlight>
Только грани, созданные из замкнутых ломаных, будут действительными. В этом примере wire3 является замкнутой ломаной, но wire2 не является замкнутым (см. выше)

{{Code|code=
face = Part.Face(wire3)
face = Part.Face(wire3)
face.Area
face.Area
> 99.999999999999972
> 99.99999999999999
face.CenterOfMass
face.CenterOfMass
> Vector (5, 5, 0)
> Vector (5, 5, 0)
Line 216: Line 285:
> True
> True
sface = Part.Face(wire2)
sface = Part.Face(wire2)
face.isValid()
sface.isValid()
> False
> False
}}
</syntaxhighlight>
Only faces will have an area, not wires nor edges.


Только грани имеют поверхность, а ломанные и ребра нет.
==== Creating a Circle ====
{{Top}}
A circle can be created as simply as this:
<span id="Create_a_circle"></span>
<syntaxhighlight>
===Создание окружности===

Окружность может быть создана, например так:

{{Code|code=
circle = Part.makeCircle(10)
circle = Part.makeCircle(10)
circle.Curve
circle.Curve
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))
}}
</syntaxhighlight>

If you want to create it at certain position and with certain direction:
Если вы хотите создать её с определенным положением и в определенном направлении
<syntaxhighlight>

ccircle = Part.makeCircle(10, Base.Vector(10,0,0), Base.Vector(1,0,0))
{{Code|code=
ccircle = Part.makeCircle(10, App.Vector(10, 0, 0), App.Vector(1, 0, 0))
ccircle.Curve
ccircle.Curve
> Circle (Radius : 10, Position : (10, 0, 0), Direction : (1, 0, 0))
> Circle (Radius : 10, Position : (10, 0, 0), Direction : (1, 0, 0))
}}
</syntaxhighlight>

ccircle will be created at distance 10 from origin on x and will be facing
<div class="mw-translate-fuzzy">
towards x axis. Note: makeCircle only accepts Base.Vector() for position
ccircle будет создана на расстоянии 10 от начала координат x и будет направлена вдоль оси x. Примечание: makeCircle принимает только тип Base.Vector() в качестве позиции и нормали. Вы также можете создать часть окружности, задав начальный и конечный угол:
and normal but not tuples. You can also create part of the circle by giving
</div>
start angle and end angle as:

<syntaxhighlight>
{{Code|code=
from math import pi
from math import pi
arc1 = Part.makeCircle(10, Base.Vector(0,0,0), Base.Vector(0,0,1), 0, 180)
arc1 = Part.makeCircle(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)
arc2 = Part.makeCircle(10, Base.Vector(0,0,0), Base.Vector(0,0,1), 180, 360)
arc2 = Part.makeCircle(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 180, 360)
}}
</syntaxhighlight>

Both arc1 and arc2 jointly will make a circle. Angles should be provided in
<div class="mw-translate-fuzzy">
degrees, if you have radians simply convert them using formula:
Обе arc1 и arc2 вместе составляют окружность.
degrees = radians * 180/PI or using python's math module (after doing import
Углы задаются в градусах, если вы хотите задать радианами, просто преобразуйте используя формулу:
math, of course):
degrees = radians * 180/PI
<syntaxhighlight>
или используя math модуль python-а (прежде, конечно, выполнив import math):
degrees = math.degrees(radians)
degrees = math.degrees(radians)
</div>
</syntaxhighlight>

==== Creating an Arc along points ====
{{Code|code=
Unfortunately there is no makeArc function but we have Part.Arc function to
import math
create an arc along three points. Basically it can be supposed as an arc
degrees = math.degrees(radians)
joining start point and end point along the middle point. Part.Arc creates
}}
an arc object on which .toShape() has to be called to get the edge object,
{{Top}}
the same way as when using Part.Line instead of Part.makeLine.
<span id="Create_an_arc_along_points"></span>
<syntaxhighlight>
===Создать дугу по точкам===
arc = Part.Arc(Base.Vector(0,0,0),Base.Vector(0,5,0),Base.Vector(5,5,0))

<div class="mw-translate-fuzzy">
К сожалению нет функции makeArc, но у нас есть функция Part.Arc для создания дуги через три точки. Она создает объект дуги, соединяющий начальную точку с конечной точкой через среднюю точку. Функция .toShape() объекта дуги должна вызываться для получения объекта ребра, так же, как при использовании Part.LineSegment вместо Part.makeLine.
</div>

{{Code|code=
arc = Part.Arc(App.Vector(0, 0, 0), App.Vector(0, 5, 0), App.Vector(5, 5, 0))
arc
arc
> <Arc object>
> <Arc object>
arc_edge = arc.toShape()
arc_edge = arc.toShape()
Part.show(arc_edge)
</syntaxhighlight>
}}
Arc only accepts Base.Vector() for points but not tuples. arc_edge is what

we want which we can display using Part.show(arc_edge). You can also obtain
<div class="mw-translate-fuzzy">
an arc by using a portion of a circle:
Arc принимает только Base.Vector() для точек. arc_edge - это то, что нам нужно, и мы можем отобразить его с помощью Part.show(arc_edge). Вы также можете получить дугу, используя часть круга:
<syntaxhighlight>
</div>

{{Code|code=
from math import pi
from math import pi
circle = Part.Circle(Base.Vector(0,0,0),Base.Vector(0,0,1),10)
circle = Part.Circle(App.Vector(0, 0, 0), App.Vector(0, 0, 1), 10)
arc = Part.Arc(c,0,pi)
arc = Part.Arc(circle,0,pi)
}}
</syntaxhighlight>
Arcs are valid edges, like lines. So they can be used in wires too.


Дуги являются действительными ребрами, такими как линии, поэтому их можно использовать и в ломаных линиях.
==== Creating a polygon ====
{{Top}}
A polygon is simply a wire with multiple straight edges. The makePolygon
<span id="Create_a_polygon"></span>
function takes a list of points and creates a wire along those points:
===Создать многоугольник (полигон)===
<syntaxhighlight>

lshape_wire = Part.makePolygon([Base.Vector(0,5,0),Base.Vector(0,0,0),Base.Vector(5,0,0)])
<div class="mw-translate-fuzzy">
</syntaxhighlight>
Линия по нескольким точкам, не что иное как создание ломаной с множеством ребер.
==== Creating a Bezier curve ====
функция makePolygon берет список точек и создает ломанную по этим точкам:
Bézier curves are used to model smooth curves using a series of poles (points) and optional weights. The function below makes a Part.BezierCurve from a series of FreeCAD.Vector points. (Note: when "getting" and "setting" a single pole or weight indices start at 1, not 0.)
</div>
<syntaxhighlight>

{{Code|code=
lshape_wire = Part.makePolygon([App.Vector(0, 5, 0), App.Vector(0, 0, 0), App.Vector(5, 0, 0)])
}}
{{Top}}
<span id="Create_a_Bézier_curve"></span>
<div class="mw-translate-fuzzy">
===Создание кривой Безье===
</div>

<div class="mw-translate-fuzzy">
Кривые Безье используются для моделирования гладких кривых с использованием ряда полюсов (точек) и необязательных весов. Функция ниже делает Part.BezierCurve из ряда точек FreeCAD.Vector. (Примечание: при «получении» и «установке» одного полюса или веса индексы начинаются с 1, а не с 0.)
</div>

{{Code|code=
def makeBCurveEdge(Points):
def makeBCurveEdge(Points):
geomCurve = Part.BezierCurve()
geomCurve = Part.BezierCurve()
Line 286: Line 387:
edge = Part.Edge(geomCurve)
edge = Part.Edge(geomCurve)
return(edge)
return(edge)
}}
</syntaxhighlight>
{{Top}}
==== Creating a Plane ====
<span id="Create_a_plane"></span>
A Plane is simply a flat rectangular surface. The method used to create one is
===Создание плоскости===
this: '''makePlane(length,width,[start_pnt,dir_normal])'''. By default

start_pnt = Vector(0,0,0) and dir_normal = Vector(0,0,1). Using dir_normal = Vector(0,0,1)
<div class="mw-translate-fuzzy">
will create the plane facing z axis, while dir_normal = Vector(1,0,0) will create the
Плоскость это ровная поверхность, в смысле 2D грань. Метод создания её это
plane facing x axis:
'''makePlane(length,width,[start_pnt,dir_normal])'''. По умолчанию
<syntaxhighlight>
start_pnt=Vector(0,0,0) и dir_normal=Vector(0,0,1). Используя dir_normal = Vector(0,0,1)
plane = Part.makePlane(2,2)
создаёт плоскость, обращённую к положительному направлению оси z, в то время как dir_normal=Vector(1,0,0) создаёт
плоскость обращённую к положительному направлению оси х:
</div>

{{Code|code=
plane = Part.makePlane(2, 2)
plane
plane
><Face object at 028AF990>
> <Face object at 028AF990>
plane = Part.makePlane(2,2, Base.Vector(3,0,0), Base.Vector(0,1,0))
plane = Part.makePlane(2, 2, App.Vector(3, 0, 0), App.Vector(0, 1, 0))
plane.BoundBox
plane.BoundBox
> BoundBox (3, 0, 0, 5, 0, 2)
> BoundBox (3, 0, 0, 5, 0, 2)
}}
</syntaxhighlight>
BoundBox is a cuboid enclosing the plane with a diagonal starting at
(3,0,0) and ending at (5,0,2). Here the BoundBox thickness in y axis is zero,
since our shape is totally flat.


<div class="mw-translate-fuzzy">
Note: makePlane only accepts Base.Vector() for start_pnt and dir_normal but not tuples
BoundBox является параллелепипед вмещающих плоскость с диагональю, начиная с
(3,0,0) и концом в (5,0,2). Здесь толщина BoundBoxпо оси y равна нулю, поскольку его форма полностью плоская.
</div>


<div class="mw-translate-fuzzy">
==== Creating an ellipse ====
Примечание: makePlane доступны только Base.Vector() для задания start_pnt и dir_normal а не кортежи
To create an ellipse there are several ways:
</div>
<syntaxhighlight>
{{Top}}
<span id="Create_an_ellipse"></span>
===Создание эллипса===

Эллипс можно создать несколькими способами:

{{Code|code=
Part.Ellipse()
Part.Ellipse()
}}
</syntaxhighlight>

Creates an ellipse with major radius 2 and minor radius 1 with the center in (0,0,0)
<div class="mw-translate-fuzzy">
<syntaxhighlight>
Создает эллипс с большой полуосью 2 и малой полуосью 1 с центром в (0,0,0)
</div>

{{Code|code=
Part.Ellipse(Ellipse)
Part.Ellipse(Ellipse)
}}
</syntaxhighlight>

Create a copy of the given ellipse
Создает копию данного эллипса.
<syntaxhighlight>

Part.Ellipse(S1,S2,Center)
{{Code|code=
</syntaxhighlight>
Part.Ellipse(S1, S2, Center)
Creates an ellipse centered on the point Center, where the plane of the
}}
ellipse is defined by Center, S1 and S2, its major axis is defined by

Center and S1, its major radius is the distance between Center and S1,
<div class="mw-translate-fuzzy">
and its minor radius is the distance between S2 and the major axis.
Создаст эллипс с центров точке Center, где
<syntaxhighlight>
плоскость эллипса определяет Center, S1 и S2,
Part.Ellipse(Center,MajorRadius,MinorRadius)
это большая ось ззаданная Center и S1,
</syntaxhighlight>
это больший радиус расстояние между Center и S1, и
Creates an ellipse with major and minor radii MajorRadius and MinorRadius,
меньший радиус это расстояние между S2 и юольшей осью.
and located in the plane defined by Center and the normal (0,0,1)
</div>
<syntaxhighlight>

eli = Part.Ellipse(Base.Vector(10,0,0),Base.Vector(0,5,0),Base.Vector(0,0,0))
{{Code|code=
Part.Ellipse(Center, MajorRadius, MinorRadius)
}}

<div class="mw-translate-fuzzy">
Создает эллипс с большим и меньшим радиусом MajorRadius и MinorRadius, расположенными в плоскости заданной точкой Center и нормалью (0,0,1)
</div>

{{Code|code=
eli = Part.Ellipse(App.Vector(10, 0, 0), App.Vector(0, 5, 0), App.Vector(0, 0, 0))
Part.show(eli.toShape())
Part.show(eli.toShape())
}}
</syntaxhighlight>
In the above code we have passed S1, S2 and center. Similarly to Arc,
Ellipse also creates an ellipse object but not edge, so we need to
convert it into edge using toShape() to display.


<div class="mw-translate-fuzzy">
Note: Arc only accepts Base.Vector() for points but not tuples
В приведенном выше коде мы ввели S1, S2 и center. Аналогично Дуге, Эллипс также создает объект, а не ребро, так что мы должны превратить его в ребро используя toShape() для отображения
<syntaxhighlight>
</div>
eli = Part.Ellipse(Base.Vector(0,0,0),10,5)

<div class="mw-translate-fuzzy">
Примечание: Дуга допускает только Base.Vector() для задания точек, а не кортеж.
</div>

{{Code|code=
eli = Part.Ellipse(App.Vector(0, 0, 0), 10, 5)
Part.show(eli.toShape())
Part.show(eli.toShape())
}}
</syntaxhighlight>

for the above Ellipse constructor we have passed center, MajorRadius and MinorRadius
<div class="mw-translate-fuzzy">
для вышеуказанного конструктора Ellipse мы передали center, MajorRadius и MinorRadius.
</div>
{{Top}}
<span id="Create_a_torus"></span>
===Создание тора===

<div class="mw-translate-fuzzy">
Используя '''makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle])'''.
По умолчанию pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0,angle2=360 и angle=360

Рассмотрим тор как маленький круг, вытянутый вдоль большого круга. Radius1 это радиус большого круга, radius2 это радиус малого круга, pnt это центр тора и dir это направление нормали.
angle1 и angle2 углы в радианах для малого круга, последний параметр angle для создания секцию (части) тора:
</div>


{{Code|code=
==== Creating a Torus ====
Using the method '''makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle])'''. By
default pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle2=360 and angle=360.
Consider a torus as small circle sweeping along a big circle. Radius1 is the
radius of big cirlce, radius2 is the radius of small circle, pnt is the center
of torus and dir is the normal direction. angle1 and angle2 are angles in
radians for the small circle, the last parameter angle is to make a section of
the torus:
<syntaxhighlight>
torus = Part.makeTorus(10, 2)
torus = Part.makeTorus(10, 2)
}}
</syntaxhighlight>
The above code will create a torus with diameter 20(radius 10) and thickness 4
(small cirlce radius 2)
<syntaxhighlight>
tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,180)
</syntaxhighlight>
The above code will create a slice of the torus
<syntaxhighlight>
tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,360,180)
</syntaxhighlight>
The above code will create a semi torus, only the last parameter is changed
i.e the angle and remaining angles are defaults. Giving the angle 180 will
create the torus from 0 to 180, that is, a half torus.


<div class="mw-translate-fuzzy">
==== Creating a box or cuboid ====
В коде выше, был создан тор с диаметром 20 (радиус 10) и толщиной 4 (малая окружность радиусом 2)
Using '''makeBox(length,width,height,[pnt,dir])'''.
</div>
By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)

<syntaxhighlight>
{{Code|code=
box = Part.makeBox(10,10,10)
tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)
}}

В приведенном выше коде, создан кусочек тора.

{{Code|code=
tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 360, 180)
}}

<div class="mw-translate-fuzzy">
В приведенном выше коде, создан полу-тор, изменен только последний параметр. Т.е. angle а остальные углы установлены по умолчанию. Подстановка угла 180 создаст тор от 0 до 180, т.е. половину тора.
</div>
{{Top}}
<span id="Create_a_box_or_cuboid"></span>
===Создание параллелепипеда или кубоида===

<div class="mw-translate-fuzzy">
Используя '''makeBox(length,width,height,[pnt,dir])''', создаем блок расположенный в pnt с размерами (length,width,height). По умолчанию pnt=Vector(0,0,0) и dir=Vector(0,0,1).
</div>

{{Code|code=
box = Part.makeBox(10, 10, 10)
len(box.Vertexes)
len(box.Vertexes)
> 8
> 8
}}
</syntaxhighlight>
{{Top}}
==== Creating a Sphere ====
<span id="Create_a_sphere"></span>
Using '''makeSphere(radius,[pnt, dir, angle1,angle2,angle3])'''. By default
===Создание сферы===
pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=-90, angle2=90 and angle3=360.

angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3
<div class="mw-translate-fuzzy">
is the sphere diameter itself.
Используя '''makeSphere(radius,[pnt, dir, angle1,angle2,angle3])'''.
<syntaxhighlight>
По умолчанию pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=-90, angle2=90 и angle3=360.
angle1 и angle2 это вертикальный минимум и максимум сферы (срезает часть сферы снизу или сверху),
angle3 is the sphere diameter (определяет замкнутое ли это тело вращения или его секция).
</div>

{{Code|code=
sphere = Part.makeSphere(10)
sphere = Part.makeSphere(10)
hemisphere = Part.makeSphere(10,Base.Vector(0,0,0),Base.Vector(0,0,1),-90,90,180)
hemisphere = Part.makeSphere(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), -90, 90, 180)
}}
</syntaxhighlight>
{{Top}}
==== Creating a Cylinder ====
<span id="Create_a_cylinder"></span>
Using '''makeCylinder(radius,height,[pnt,dir,angle])'''. By default
===Создание цилиндра===
pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360
<syntaxhighlight>
cylinder = Part.makeCylinder(5,20)
partCylinder = Part.makeCylinder(5,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180)
</syntaxhighlight>
==== Creating a Cone ====
Using '''makeCone(radius1,radius2,height,[pnt,dir,angle])'''. By default
pnt=Vector(0,0,0), dir=Vector(0,0,1) and angle=360
<syntaxhighlight>
cone = Part.makeCone(10,0,20)
semicone = Part.makeCone(10,0,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180)
</syntaxhighlight>
== Modifying shapes ==
There are several ways to modify shapes. Some are simple transformation operations
such as moving or rotating shapes, other are more complex, such as unioning and
subtracting one shape from another. Be aware that


<div class="mw-translate-fuzzy">
=== Transform operations ===
Используя '''makeCylinder(radius,height,[pnt,dir,angle])''', создается цилиндр с указанным радиусом и высотой. По умолчанию pnt=Vector(0,0,0),dir=Vector(0,0,1) и angle=360.
</div>


{{Code|code=
==== Translating a shape ====
cylinder = Part.makeCylinder(5, 20)
Translating is the act of moving a shape from one place to another.
partCylinder = Part.makeCylinder(5, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)
Any shape (edge, face, cube, etc...) can be translated the same way:
}}
<syntaxhighlight>
{{Top}}
myShape = Part.makeBox(2,2,2)
<span id="Create_a_cone"></span>
myShape.translate(Base.Vector(2,0,0))
===Cоздание конуса===
</syntaxhighlight>

This will move our shape "myShape" 2 units in the x direction.
<div class="mw-translate-fuzzy">
Используя '''makeCone(radius1,radius2,height,[pnt,dir,angle])''', создаем конус с указанными радиусами и высотой. По умолчанию pnt=Vector(0,0,0), dir=Vector(0,0,1) и angle=360.
</div>

{{Code|code=
cone = Part.makeCone(10, 0, 20)
semicone = Part.makeCone(10, 0, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)
}}
{{Top}}
==Modify shapes==

There are several ways to modify shapes. Some are simple transformation operations such as moving or rotating shapes, others are more complex, such as unioning and subtracting one shape from another.
{{Top}}
==Transform operations==

===Translate a shape===

Translating is the act of moving a shape from one place to another. Any shape (edge, face, cube, etc...) can be translated the same way:

{{Code|code=
myShape = Part.makeBox(2, 2, 2)
myShape.translate(App.Vector(2, 0, 0))
}}

This will move our shape "myShape" 2 units in the X direction.
{{Top}}
===Rotate a shape===

To rotate a shape, you need to specify the rotation center, the axis, and the rotation angle:

{{Code|code=
myShape.rotate(App.Vector(0, 0, 0),App.Vector(0, 0, 1), 180)
}}


==== Rotating a shape ====
To rotate a shape, you need to specify the rotation center, the axis,
and the rotation angle:
<syntaxhighlight>
myShape.rotate(Vector(0,0,0),Vector(0,0,1),180)
</syntaxhighlight>
The above code will rotate the shape 180 degrees around the Z Axis.
The above code will rotate the shape 180 degrees around the Z Axis.
{{Top}}
===Matrix transformations===

A matrix is a very convenient way to store transformations in the 3D world. In a single matrix, you can set translation, rotation and scaling values to be applied to an object. For example:


{{Code|code=
==== Generic transformations with matrixes ====
myMat = App.Matrix()
A matrix is a very convenient way to store transformations in the 3D
myMat.move(App.Vector(2, 0, 0))
world. In a single matrix, you can set translation, rotation and scaling
values to be applied to an object. For example:
<syntaxhighlight>
myMat = Base.Matrix()
myMat.move(Base.Vector(2,0,0))
myMat.rotateZ(math.pi/2)
myMat.rotateZ(math.pi/2)
}}
</syntaxhighlight>

Note: FreeCAD matrixes work in radians. Also, almost all matrix operations
that take a vector can also take 3 numbers, so those 2 lines do the same thing:
Note: FreeCAD matrixes work in radians. Also, almost all matrix operations that take a vector can also take three numbers, so these two lines do the same thing:

<syntaxhighlight>
{{Code|code=
myMat.move(2,0,0)
myMat.move(Base.Vector(2,0,0))
myMat.move(2, 0, 0)
myMat.move(App.Vector(2, 0, 0))
</syntaxhighlight>
}}
When our matrix is set, we can apply it to our shape. FreeCAD provides 2

methods to do that: transformShape() and transformGeometry(). The difference
is that with the first one, you are sure that no deformations will occur (see
Once our matrix is set, we can apply it to our shape. FreeCAD provides two methods for doing that: {{incode|transformShape()}} and {{incode|transformGeometry()}}. The difference is that with the first one, you are sure that no deformations will occur (see [[#Scaling a shape|Scaling a shape]] below). We can apply our transformation like this:

"scaling a shape" below). So we can apply our transformation like this:
{{Code|code=
<syntaxhighlight>
myShape.trasformShape(myMat)
myShape.transformShape(myMat)
}}
</syntaxhighlight>

or
или
<syntaxhighlight>

{{Code|code=
myShape.transformGeometry(myMat)
myShape.transformGeometry(myMat)
}}
</syntaxhighlight>
{{Top}}
==== Scaling a shape ====
===Scale a shape===
Scaling a shape is a more dangerous operation because, unlike translation

or rotation, scaling non-uniformly (with different values for x, y and z)
Scaling a shape is a more dangerous operation because, unlike translation or rotation, scaling non-uniformly (with different values for X, Y and Z) can modify the structure of the shape. For example, scaling a circle with a higher value horizontally than vertically will transform it into an ellipse, which behaves mathematically very differently. For scaling, we cannot use the {{incode|transformShape()}}, we must use {{incode|transformGeometry()}}:
can modify the structure of the shape. For example, scaling a circle with

a higher value horizontally than vertically will transform it into an
{{Code|code=
ellipse, which behaves mathematically very differenty. For scaling, we
myMat = App.Matrix()
can't use the transformShape, we must use transformGeometry():
myMat.scale(2, 1, 1)
<syntaxhighlight>
myMat = Base.Matrix()
myMat.scale(2,1,1)
myShape=myShape.transformGeometry(myMat)
myShape=myShape.transformGeometry(myMat)
}}
</syntaxhighlight>
{{Top}}
=== Boolean Operations ===
<span id="Boolean_operations"></span>
==Булевы Операции==


==== Subtraction ====
<span id="Subtraction"></span>
<div class="mw-translate-fuzzy">
Subtracting a shape from another one is called "cut" in OCC/FreeCAD jargon
====Как вырезать одну форму из других?====
and is done like this:

<syntaxhighlight>
cut(...) - Вычисление различий задано в топологическом классе shape.
cylinder = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
</div>
sphere = Part.makeSphere(5,Base.Vector(5,0,0))

Subtracting a shape from another one is called "cut" in FreeCAD and is done like this:

{{Code|code=
cylinder = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
sphere = Part.makeSphere(5, App.Vector(5, 0, 0))
diff = cylinder.cut(sphere)
diff = cylinder.cut(sphere)
}}
</syntaxhighlight>
{{Top}}
==== Intersection ====
<span id="Intersection"></span>
The same way, the intersection between 2 shapes is called "common" and is done
<div class="mw-translate-fuzzy">
this way:
====Как получить пересечение двух форм?====
<syntaxhighlight>
Тем же способом, пересечение между двумя фигурами называется "common(...)" (пересечение задано в топологическом классе shape) и делается так:
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
</div>
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1))

The same way, the intersection between two shapes is called "common" and is done this way:

{{Code|code=
cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
common = cylinder1.common(cylinder2)
common = cylinder1.common(cylinder2)
}}
</syntaxhighlight>
{{Top}}
==== Union ====
<span id="Union"></span>
<div class="mw-translate-fuzzy">
====Как объединить две формы?====

fuse(...) - Объединение задано в топологическом классе shape
</div>

Union is called "fuse" and works the same way:
Union is called "fuse" and works the same way:

<syntaxhighlight>
{{Code|code=
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1))
cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
fuse = cylinder1.fuse(cylinder2)
fuse = cylinder1.fuse(cylinder2)
}}
</syntaxhighlight>
{{Top}}
==== Section ====
<span id="Section"></span>
A Section is the intersection between a solid shape and a plane shape.
<div class="mw-translate-fuzzy">
It will return an intersection curve, a compound with edges
====Как получить сечение тела и заданной формы?====
<syntaxhighlight>
Section это пересечение твердого тела и плоской фигуры (сечение задано в топологическом классе shape).
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
Вернет секущую кривую, составную кривую, состоящую из ребер.
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1))
</div>

A "section" is the intersection between a solid shape and a plane shape. It will return an intersection curve, a compound curve composed of edges.

{{Code|code=
cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
section = cylinder1.section(cylinder2)
section = cylinder1.section(cylinder2)
section.Wires
section.Wires
Line 499: Line 696:
<Edge object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>,
<Edge object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>,
<Edge object at 0D8F4BB0>]
<Edge object at 0D8F4BB0>]
}}
</syntaxhighlight>
{{Top}}
==== Extrusion ====
<span id="Extrusion"></span>
Extrusion is the act of "pushing" a flat shape in a certain direction resulting in
<div class="mw-translate-fuzzy">
a solid body. Think of a circle becoming a tube by "pushing it out":
==== Выдавливание ====
<syntaxhighlight>
Выдавливание - это процесс «выпячивания» плоской фигуры в определенном направлении, становящейся твердым телом. Представьте, как «выпячивание» круга сделало его трубой:
</div>

Extrusion is the act of "pushing" a flat shape in a certain direction, resulting in a solid body. Think of a circle becoming a tube by "pushing it out":

{{Code|code=
circle = Part.makeCircle(10)
circle = Part.makeCircle(10)
tube = circle.extrude(Base.Vector(0,0,2))
tube = circle.extrude(App.Vector(0, 0, 2))
}}
</syntaxhighlight>

If your circle is hollow, you will obtain a hollow tube. If your circle is actually
<div class="mw-translate-fuzzy">
a disc, with a filled face, you will obtain a solid cylinder:
Если ваш круг полый, вы получите полую трубу. Если ваш круг это диск с заполненной поверхностью, вы получите сплошной цилиндр:
<syntaxhighlight>
</div>

{{Code|code=
wire = Part.Wire(circle)
wire = Part.Wire(circle)
disc = Part.makeFace(wire)
disc = Part.Face(wire)
cylinder = disc.extrude(Base.Vector(0,0,2))
cylinder = disc.extrude(App.Vector(0, 0, 2))
}}
</syntaxhighlight>
{{Top}}
== Exploring shapes ==
<span id="Explore_shapes"></span>
<div class="mw-translate-fuzzy">
== Исследование Форм ==
Вы легко можете исследовать структуру топологических данных:
</div>

You can easily explore the topological data structure:
You can easily explore the topological data structure:

<syntaxhighlight>
{{Code|code=
import Part
import Part
b = Part.makeBox(100,100,100)
b = Part.makeBox(100, 100, 100)
b.Wires
b.Wires
w = b.Wires[0]
w = b.Wires[0]
Line 530: Line 743:
v = e.Vertexes[0]
v = e.Vertexes[0]
v.Point
v.Point
}}
</syntaxhighlight>
By typing the lines above in the python interpreter, you will gain a good
understanding of the structure of Part objects. Here, our makeBox() command
created a solid shape. This solid, like all Part solids, contains faces.
Faces always contain wires, which are lists of edges that border the face.
Each face has at least one closed wire (it can have more if the face has a hole).
In the wire, we can look at each edge separately, and inside each edge, we can
see the vertexes. Straight edges have only two vertexes, obviously.


<div class="mw-translate-fuzzy">
=== Edge analysis ===
Если ввести строчку выше в интерпретатор python , вы получите хорошее представление об устройстве объектов Part. Здесь наша команда makeBox() создает твердое тело. Это тело, как и все тела Part, содержит грани. Грани всегда содержат ломанные, которые являются набором ребер ограничивающих грань. Каждая грань обладает минимум одной замкнутой ломаной (может больше, если есть отверстие). В ломанной мы можем посмотреть на каждое ребро отдельно, и по краям каждого ребра мы можем увидеть вершины. Прямые ребра обладают только двумя вершинами, разумеется. Вершины модуля Part являются формами OCC(OpenCascade), но они обладают атрибутом Point, который возвращает вектор FreeCAD.
In case of an edge, which is an arbitrary curve, it's most likely you want to
</div>
do a discretization. In FreeCAD the edges are parametrized by their lengths.
{{Top}}
That means you can walk an edge/curve by its length:
<span id="Edge_analysis"></span>
<syntaxhighlight>
<div class="mw-translate-fuzzy">
=== Исследование Рёбер ===
В случае ребра, которое является произвольной кривой, вы наверняка захотите произвести дискретизицию. В FreeCAD ребра задаются с помощью параметра длинны. Это означает что вы можете перемещатся вдоль ребра/кривой задавая длинну:
</div>

In case of an edge, which is an arbitrary curve, it's most likely you want to do a discretization. In FreeCAD the edges are parametrized by their lengths. That means you can walk an edge/curve by its length:

{{Code|code=
import Part
import Part
box = Part.makeBox(100,100,100)
box = Part.makeBox(100, 100, 100)
anEdge = box.Edges[0]
anEdge = box.Edges[0]
print anEdge.Length
print(anEdge.Length)
}}
</syntaxhighlight>

Now you can access a lot of properties of the edge by using the length as a
<div class="mw-translate-fuzzy">
position. That means if the edge is 100mm long the start position is 0 and
Теперь вы получить доступ ко всем свойствам ребра, с помощью длинны или позиции. Это означает, что у ребра
the end position 100.
в 100mm длинной, начальная позиция это 0 а конечная это 100.
<syntaxhighlight>
</div>
anEdge.tangentAt(0.0) # tangent direction at the beginning

anEdge.valueAt(0.0) # Point at the beginning
{{Code|code=
anEdge.valueAt(100.0) # Point at the end of the edge
anEdge.derivative1At(50.0) # first derivative of the curve in the middle
anEdge.tangentAt(0.0) # tangent direction at the beginning
anEdge.derivative2At(50.0) # second derivative of the curve in the middle
anEdge.valueAt(0.0) # Point at the beginning
anEdge.derivative3At(50.0) # third derivative of the curve in the middle
anEdge.valueAt(100.0) # Point at the end of the edge
anEdge.derivative1At(50.0) # first derivative of the curve in the middle
anEdge.derivative2At(50.0) # second derivative of the curve in the middle
anEdge.derivative3At(50.0) # third derivative of the curve in the middle
anEdge.centerOfCurvatureAt(50) # center of the curvature for that position
anEdge.centerOfCurvatureAt(50) # center of the curvature for that position
anEdge.curvatureAt(50.0) # the curvature
anEdge.curvatureAt(50.0) # the curvature
anEdge.normalAt(50) # normal vector at that position (if defined)
anEdge.normalAt(50) # normal vector at that position (if defined)
}}
</syntaxhighlight>
{{Top}}
=== Using the selection ===
<span id="Use_a_selection"></span>
Here we see now how we can use the selection the user did in the viewer.
<div class="mw-translate-fuzzy">
First of all we create a box and shows it in the viewer
=== Использование выделения(выбора) ===
<syntaxhighlight>
Здесь мы увидим как можно использовать "выделение", которое пользователь сделал в программе просмотра.
прежде всего мы создадим блок и отобразим его в окне просмотра.
</div>

Here we see now how we can use a selection the user did in the viewer. First of all we create a box and show it in the viewer.

{{Code|code=
import Part
import Part
Part.show(Part.makeBox(100,100,100))
Part.show(Part.makeBox(100, 100, 100))
Gui.SendMsgToActiveView("ViewFit")
Gui.SendMsgToActiveView("ViewFit")
}}
</syntaxhighlight>

Select now some faces or edges. With this script you can
<div class="mw-translate-fuzzy">
iterate all selected objects and their sub elements:
Теперь выберем грани или ребра. С помощью этого сценария вы можете повторить по всем выделенным объектам и их субэлементам:
<syntaxhighlight>
</div>

{{Code|code=
for o in Gui.Selection.getSelectionEx():
for o in Gui.Selection.getSelectionEx():
print o.ObjectName
print(o.ObjectName)
for s in o.SubElementNames:
for s in o.SubElementNames:
print "name: ",s
print("name: ", s)
for s in o.SubObjects:
for s in o.SubObjects:
print "object: ",s
print("object: ", s)
}}
</syntaxhighlight>

Select some edges and this script will calculate the length:
Выделим несколько ребер и этот сценарий подсчитает их сумарную длину:
<syntaxhighlight>

{{Code|code=
length = 0.0
length = 0.0
for o in Gui.Selection.getSelectionEx():
for o in Gui.Selection.getSelectionEx():
for s in o.SubObjects:
for s in o.SubObjects:
length += s.Length
length += s.Length

print "Length of the selected edges:" ,length
print("Length of the selected edges: ", length)
</syntaxhighlight>
}}
== Complete example: The OCC bottle ==
{{Top}}
A typical example found on the
<span id="Example:_The_OCC_bottle"></span>
[http://www.opencascade.org/org/gettingstarted/appli/ OpenCasCade Getting Started Page]
<div class="mw-translate-fuzzy">
is how to build a bottle. This is a good exercise for FreeCAD too. In fact,
== Полный пример: бутыль OCC ==
you can follow our example below and the OCC page simultaneously, you will
Типовой пример, взятый на [http://www.opencascade.com/doc/occt-6.9.0/overview/html/occt__tutorial.html#sec1 OpenCasCade Technology Tutorial] - это как построить бутыль. Это отличный пример и для FreeCAD. В самом деле, если последуете нашему примеру изложенному ниже и странице OCC одновременно, вы лучше поймете как структуры OCC реализованы в FreeCAD. Готовый сценарий описанный ниже, также включен в установленный FreeCAD (в папке Mod/Part) и может быть вызван интерпретатором python, вводом:
understand well how OCC structures are implemented in FreeCAD. The complete script
</div>
below is also included in FreeCAD installation (inside the Mod/Part folder) and

can be called from the python interpreter by typing:
A typical example found on the [https://www.opencascade.com/doc/occt-6.9.0/overview/html/occt__tutorial.html OpenCasCade Technology website] is how to build a bottle. This is a good exercise for FreeCAD too. In fact, if you follow our example below and the OCC page simultaneously, you will see how well OCC structures are implemented in FreeCAD. The script is included in the FreeCAD installation (inside the {{FileName|Mod/Part}} folder) and can be called from the Python interpreter by typing:
<syntaxhighlight>

{{Code|code=
import Part
import Part
import MakeBottle
import MakeBottle
bottle = MakeBottle.makeBottle()
bottle = MakeBottle.makeBottle()
Part.show(bottle)
Part.show(bottle)
}}
</syntaxhighlight>
{{Top}}
=== The complete script ===
<span id="The_script"></span>
Here is the complete MakeBottle script:
<div class="mw-translate-fuzzy">
<syntaxhighlight>
=== Готовый сценарий ===
import Part, FreeCAD, math
from FreeCAD import Base
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0):
aPnt1=Base.Vector(-myWidth/2.,0,0)
aPnt2=Base.Vector(-myWidth/2.,-myThickness/4.,0)
aPnt3=Base.Vector(0,-myThickness/2.,0)
aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0)
aPnt5=Base.Vector(myWidth/2.,0,0)
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4)
aSegment1=Part.Line(aPnt1,aPnt2)
aSegment2=Part.Line(aPnt4,aPnt5)
aEdge1=aSegment1.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge3=aSegment2.toShape()
aWire=Part.Wire([aEdge1,aEdge2,aEdge3])
aTrsf=Base.Matrix()
aTrsf.rotateZ(math.pi) # rotate around the z-axis
aMirroredWire=aWire.transformGeometry(aTrsf)
myWireProfile=Part.Wire([aWire,aMirroredWire])
myFaceProfile=Part.Face(myWireProfile)
aPrismVec=Base.Vector(0,0,myHeight)
myBody=myFaceProfile.extrude(aPrismVec)
myBody=myBody.makeFillet(myThickness/12.0,myBody.Edges)
neckLocation=Base.Vector(0,0,myHeight)
neckNormal=Base.Vector(0,0,1)
myNeckRadius = myThickness / 4.
myNeckHeight = myHeight / 10
myNeck = Part.makeCylinder(myNeckRadius,myNeckHeight,neckLocation,neckNormal)
myBody = myBody.fuse(myNeck)
faceToRemove = 0
zMax = -1.0
for xp in myBody.Faces:
try:
surf = xp.Surface
if type(surf) == Part.Plane:
z = surf.Position.z
if z > zMax:
zMax = z
faceToRemove = xp
except:
continue
myBody = myBody.makeThickness([faceToRemove],-myThickness/50 , 1.e-3)
return myBody
</syntaxhighlight>
=== Detailed explanation ===
<syntaxhighlight>
import Part, FreeCAD, math
from FreeCAD import Base
</syntaxhighlight>
We will need,of course, the Part module, but also the FreeCAD.Base module,
which contains basic FreeCAD structures like vectors and matrixes.
<syntaxhighlight>
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0):
aPnt1=Base.Vector(-myWidth/2.,0,0)
aPnt2=Base.Vector(-myWidth/2.,-myThickness/4.,0)
aPnt3=Base.Vector(0,-myThickness/2.,0)
aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0)
aPnt5=Base.Vector(myWidth/2.,0,0)
</syntaxhighlight>
Here we define our makeBottle function. This function can be called without
arguments, like we did above, in which case default values for width, height,
and thickness will be used. Then, we define a couple of points that will be used
for building our base profile.
<syntaxhighlight>
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4)
aSegment1=Part.Line(aPnt1,aPnt2)
aSegment2=Part.Line(aPnt4,aPnt5)
</syntaxhighlight>
Here we actually define the geometry: an arc, made of 3 points, and two
line segments, made of 2 points.
<syntaxhighlight>
aEdge1=aSegment1.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge3=aSegment2.toShape()
aWire=Part.Wire([aEdge1,aEdge2,aEdge3])
</syntaxhighlight>
Remember the difference between geometry and shapes? Here we build
shapes out of our construction geometry. 3 edges (edges can be straight
or curved), then a wire made of those three edges.
<syntaxhighlight>
aTrsf=Base.Matrix()
aTrsf.rotateZ(math.pi) # rotate around the z-axis
aMirroredWire=aWire.transformGeometry(aTrsf)
myWireProfile=Part.Wire([aWire,aMirroredWire])
</syntaxhighlight>
Until now we built only a half profile. Easier than building the whole profile
the same way, we can just mirror what we did, and glue both halfs together.
So we first create a matrix. A matrix is a very common way to apply transformations
to objects in the 3D world, since it can contain in one structure all basic
transformations that 3D objects can suffer (move, rotate and scale). Here,
after we create the matrix, we mirror it, and we create a copy of our wire
with that transformation matrix applied to it. We now have two wires, and
we can make a third wire out of them, since wires are actually lists of edges.
<syntaxhighlight>
myFaceProfile=Part.Face(myWireProfile)
aPrismVec=Base.Vector(0,0,myHeight)
myBody=myFaceProfile.extrude(aPrismVec)
myBody=myBody.makeFillet(myThickness/12.0,myBody.Edges)
</syntaxhighlight>
Now that we have a closed wire, it can be turned into a face. Once we have a face,
we can extrude it. Doing so, we actually made a solid. Then we apply a nice little
fillet to our object because we care about good design, don't we?
<syntaxhighlight>
neckLocation=Base.Vector(0,0,myHeight)
neckNormal=Base.Vector(0,0,1)
myNeckRadius = myThickness / 4.
myNeckHeight = myHeight / 10
myNeck = Part.makeCylinder(myNeckRadius,myNeckHeight,neckLocation,neckNormal)
</syntaxhighlight>
Then, the body of our bottle is made, we still need to create a neck. So we
make a new solid, with a cylinder.
<syntaxhighlight>
myBody = myBody.fuse(myNeck)
</syntaxhighlight>
The fuse operation, which in other apps is sometimes called union, is very
powerful. It will take care of gluing what needs to be glued and remove parts that
need to be removed.
<syntaxhighlight>
return myBody
</syntaxhighlight>
Then, we return our Part solid as the result of our function. That Part solid,
like any other Part shape, can be attributed to an object in a FreeCAD document, with:
<syntaxhighlight>
myObject = FreeCAD.ActiveDocument.addObject("Part::Feature","myObject")
myObject.Shape = bottle
</syntaxhighlight>
or, more simple:
<syntaxhighlight>
Part.show(bottle)
</syntaxhighlight>
==Box pierced==
Here a complete example of building a box pierced.


Здесь представлен готовый сценарий MakeBottle:
The construction is done side by side and when the cube is finished, it is hollowed out of a cylinder through.
</div>
<syntaxhighlight>

import Draft, Part, FreeCAD, math, PartGui, FreeCADGui, PyQt4
For the purpose of this tutorial we will consider a reduced version of the script. In this version the bottle will not be hollowed out, and the neck of the bottle will not be threaded.
from math import sqrt, pi, sin, cos, asin

from FreeCAD import Base
{{Code|code=
import FreeCAD as App
import Part, math

def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0):
aPnt1=App.Vector(-myWidth / 2., 0, 0)
aPnt2=App.Vector(-myWidth / 2., -myThickness / 4., 0)
aPnt3=App.Vector(0, -myThickness / 2., 0)
aPnt4=App.Vector(myWidth / 2., -myThickness / 4., 0)
aPnt5=App.Vector(myWidth / 2., 0, 0)

aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)
aSegment1=Part.LineSegment(aPnt1, aPnt2)
aSegment2=Part.LineSegment(aPnt4, aPnt5)

aEdge1=aSegment1.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge3=aSegment2.toShape()
aWire=Part.Wire([aEdge1, aEdge2, aEdge3])

aTrsf=App.Matrix()
aTrsf.rotateZ(math.pi) # rotate around the z-axis

aMirroredWire=aWire.copy()
aMirroredWire.transformShape(aTrsf)
myWireProfile=Part.Wire([aWire, aMirroredWire])

myFaceProfile=Part.Face(myWireProfile)
aPrismVec=App.Vector(0, 0, myHeight)
myBody=myFaceProfile.extrude(aPrismVec)

myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges)

neckLocation=App.Vector(0, 0, myHeight)
neckNormal=App.Vector(0, 0, 1)

myNeckRadius = myThickness / 4.
myNeckHeight = myHeight / 10.
myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal)
myBody = myBody.fuse(myNeck)

return myBody

el = makeBottleTut()
Part.show(el)
}}
{{Top}}
<span id="Detailed_explanation"></span>
===Подробные объяснения===

{{Code|code=
import FreeCAD as App
import Part, math
}}

<div class="mw-translate-fuzzy">
Нам, конечно, необходимы модуль {{incode|Part}}, а также модуль {{incode|FreeCAD.Base}}, который содержит основные структуры FreeCAD, такие как векторы и матрицы.
</div>

{{Code|code=
def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0):
aPnt1=App.Vector(-myWidth / 2., 0, 0)
aPnt2=App.Vector(-myWidth / 2., -myThickness / 4., 0)
aPnt3=App.Vector(0, -myThickness / 2., 0)
aPnt4=App.Vector(myWidth / 2., -myThickness / 4., 0)
aPnt5=App.Vector(myWidth / 2., 0, 0)
}}

<div class="mw-translate-fuzzy">
Здесь мы задаем нашу функцию {{incode|makeBottleTut}}. Эта функция может быть вызвана без аргументов, как мы делали выше, в этом случае будут использоваться значения по умолчанию для ширины, высоты и толщины. Затем мы определили несколько точек которые будут использоваться для построения базового сечения.
</div>

{{Code|code=
...
aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)
aSegment1=Part.LineSegment(aPnt1, aPnt2)
aSegment2=Part.LineSegment(aPnt4, aPnt5)
}}

Здесь мы задаём геометрию: дугу, созданую по 3 точкам, и два линейных сегмента, созданные по 2 точкам.

{{Code|code=
...
aEdge1=aSegment1.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge3=aSegment2.toShape()
aWire=Part.Wire([aEdge1, aEdge2, aEdge3])
}}

<div class="mw-translate-fuzzy">
Запомнили различие между геометрией и формой? Здесь мы создаем форму из нашей строительной геометрии. Три рёбра (ребра могут быть прямыми или кривыми), затем из этих трёх рёбер создается ломанная.
</div>

{{Code|code=
...
aTrsf=App.Matrix()
aTrsf.rotateZ(math.pi) # rotate around the z-axis

aMirroredWire=aWire.copy()
aMirroredWire.transformShape(aTrsf)
myWireProfile=Part.Wire([aWire, aMirroredWire])
}}

<div class="mw-translate-fuzzy">
Пока мы построили только половину сечения. Вместо построения таким же образом целого профиля, мы можем просто отразить то, что мы сделали, и склеить две половинки. Сначала создадим матрицу. Матрица является распространенным способом произвести изменения над объектом в трёхмерном пространстве, поскольку она может содержать в одной структуре все базовые преобразования, которым могут подвергаться трёхмерные объекты (перемещение, вращение и масштабирование). После создания матрицы, мы отражаем её, затем создаем копию нашей ломанной и применяем к ней трансформационную матрицу. Теперь мы получили две ломанные и мы можем создать из них третью ломаную, так как ломанные это всего лишь список ребер.
</div>

{{Code|code=
...
myFaceProfile=Part.Face(myWireProfile)
aPrismVec=App.Vector(0, 0, myHeight)
myBody=myFaceProfile.extrude(aPrismVec)

myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges)
}}

<div class="mw-translate-fuzzy">
Теперь мы получили замкнутую ломаную, которую можно обратить в грань. Когда мы имеем грань, мы можем вытянуть её. Сделав это, мы получим твердое тело. Теперь мы добавим небольшое скругление к нашему объекту, потому что мы заботимся о качественном дизайне, не так ли?
</div>

{{Code|code=
...
neckLocation=App.Vector(0, 0, myHeight)
neckNormal=App.Vector(0, 0, 1)

myNeckRadius = myThickness / 4.
myNeckHeight = myHeight / 10.
myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal)
}}

<div class="mw-translate-fuzzy">
Теперь тело нашей бутыли создано, но нам нужно создать горлышко. Так что мы создаем новое твердое тело, с цилиндром.
</div>

{{Code|code=
...
myBody = myBody.fuse(myNeck)
}}

Операция слияния очень мощная. Она заботится о склеивании, о том, что должно быть приклеено и удаляет части, которые следует удалить.

{{Code|code=
...
return myBody
}}

Теперь мы получаем нашу твёрдое тело модуля Part как результат нашей функции.

{{Code|code=
el = makeBottleTut()
Part.show(el)
}}

В итоге мы вызываем функцию для фактического создания детали, а потом делаем её видимой.
{{Top}}
==Example: Pierced box==

Here is a complete example of building a pierced box.

Конструкция делается по одной стороне за раз. Когда куб закончен, он выдалбливается вырезанием цилиндра через него.

{{Code|code=
import FreeCAD as App
import Part, math


size = 10
size = 10
poly = Part.makePolygon( [ (0,0,0), (size, 0, 0), (size, 0, size), (0, 0, size), (0, 0, 0)])
poly = Part.makePolygon([(0, 0, 0), (size, 0, 0), (size, 0, size), (0, 0, size), (0, 0, 0)])


face1 = Part.Face(poly)
face1 = Part.Face(poly)
Line 763: Line 1,019:
face6 = Part.Face(poly)
face6 = Part.Face(poly)
myMat = FreeCAD.Matrix()
myMat = App.Matrix()

myMat.rotateZ(math.pi/2)
myMat.rotateZ(math.pi / 2)
face2.transformShape(myMat)
face2.transformShape(myMat)
face2.translate(FreeCAD.Vector(size, 0, 0))
face2.translate(App.Vector(size, 0, 0))


myMat.rotateZ(math.pi/2)
myMat.rotateZ(math.pi / 2)
face3.transformShape(myMat)
face3.transformShape(myMat)
face3.translate(FreeCAD.Vector(size, size, 0))
face3.translate(App.Vector(size, size, 0))


myMat.rotateZ(math.pi/2)
myMat.rotateZ(math.pi / 2)
face4.transformShape(myMat)
face4.transformShape(myMat)
face4.translate(FreeCAD.Vector(0, size, 0))
face4.translate(App.Vector(0, size, 0))


myMat = FreeCAD.Matrix()
myMat = App.Matrix()

myMat.rotateX(-math.pi/2)
myMat.rotateX(-math.pi / 2)
face5.transformShape(myMat)
face5.transformShape(myMat)


face6.transformShape(myMat)
face6.transformShape(myMat)
face6.translate(FreeCAD.Vector(0,0,size))
face6.translate(App.Vector(0, 0, size))

myShell = Part.makeShell([face1,face2,face3,face4,face5,face6])


myShell = Part.makeShell([face1, face2, face3, face4, face5, face6])
mySolid = Part.makeSolid(myShell)
mySolid = Part.makeSolid(myShell)
mySolidRev = mySolid.copy()
mySolidRev.reverse()


myCyl = Part.makeCylinder(2,20)
myCyl = Part.makeCylinder(2, 20)
myCyl.translate(FreeCAD.Vector(size/2, size/2, 0))
myCyl.translate(App.Vector(size / 2, size / 2, 0))


cut_part = mySolidRev.cut(myCyl)
cut_part = mySolid.cut(myCyl)


Part.show(cut_part)
Part.show(cut_part)
}}
</syntaxhighlight>
{{Top}}
== Loading and Saving ==
<span id="Loading_and_saving"></span>
There are several ways to save your work in the Part module. You can
== Загрузка и Сохранение ==
of course save your FreeCAD document, but you can also save Part
objects directly to common CAD formats, such as BREP, IGS, STEP and STL.


<div class="mw-translate-fuzzy">
Saving a shape to a file is easy. There are exportBrep(), exportIges(),
Существует несколько способов сохранить вашу работу. Вы конечно можете сохранить ваш FreeCAD документ, а также вы можете сохранить Part(Деталь) объект напрямую в обычные CAD форматы, такие как BREP, IGS, STEP и STL.
exportStl() and exportStep() methods availables for all shape objects.
</div>
So, doing:

<syntaxhighlight>
<div class="mw-translate-fuzzy">
Сохранить форму в файл легко. Есть доступные для всех форм методы {{incode|exportBrep()}}, {{incode|exportIges()}}, {{incode|exportStep()}} и {{incode|exportStl()}}. Таким образом:
</div>

{{Code|code=
import Part
import Part
s = Part.makeBox(0,0,0,10,10,10)
s = Part.makeBox(10, 10, 10)
s.exportStep("test.stp")
s.exportStep("test.stp")
}}
</syntaxhighlight>

this will save our box into a STEP file. To load a BREP,
это сохранит наш блок в файл формата STEP. Для загрузки BREP, IGES или STEP файлов:
IGES or STEP file, simply do the contrary:

<syntaxhighlight>
{{Code|code=
import Part
import Part
s = Part.Shape()
s = Part.Shape()
s.read("test.stp")
s.read("test.stp")
}}
</syntaxhighlight>

To convert an '''.stp''' in '''.igs''' file simply :
Для преобразования файла STEP в файл IGS:
<syntaxhighlight>

{{Code|code=
import Part
import Part
s = Part.Shape()
s = Part.Shape()
s.read("file.stp") # incoming file igs, stp, stl, brep
s.read("file.stp") # incoming file igs, stp, stl, brep
s.exportIges("file.igs") # outbound file igs
s.exportIges("file.igs") # outbound file igs
}}
</syntaxhighlight>
{{Top}}
Note that importing or opening BREP, IGES or STEP files can also be done
directly from the File -> Open or File -> Import menu, while exporting
is with File -> Export


{{Docnav/ru
{{docnav|Mesh Scripting|Mesh to Part}}
|[[FreeCAD_Scripting_Basics/ru|FreeCAD Scripting Basics]]
|[[Mesh_Scripting/ru|Mesh Scripting]]
}}


{{Powerdocnavi{{#translation:}}}}
[[Category:Poweruser Documentation]]
[[Category:Python Code]]
[[Category:Developer Documentation{{#translation:}}]]
[[Category:Tutorials]]
[[Category:Python Code{{#translation:}}]]

{{clear}}
<languages/>

Latest revision as of 18:55, 12 October 2023

Введение

Здесь мы объясним вам, как управлять верстаком Part непосредственно из интерпретатора Python FreeCAD или из любого внешнего сценария. Основы создания сценариев топологических данных описаны в объяснение концепции модуля Part. Обязательно просмотрите раздел Scripting и страницы Основы скриптинга FreeCAD, если вам нужна дополнительная информация о том, как работает python-скриптинг во FreeCAD .

Смотрите также

Диаграмма классов

Это обзор наиболее важных классов модуля Part через Unified Modeling Language (UML):

Классы Python, содержащиеся в модуле Part
Классы Python, содержащиеся в модуле Part

наверх

Геометрия

Геометрические объекты являются строительными блоками для всех топологических объектов:

  • Geom Базовый класс геометрических объектов.
  • Line Прямая линия в 3D, задается начальной и конечной точкой.
  • Circle Окружность или дуга задается центром, начальной и конечной точкой.
  • и так далее...

наверх

Топология

Доступны нижеследующие топологические типы данных:

  • COMPOUND Группа из топологических объектов любого типа.
  • COMPSOLID Составное твердое тело, как набор твердых тел соединенными гранями. Он расширяет понятие Ломаной кривой(WIRE) и оболочки(SHELL) для твердых тел.
  • SOLID Часть пространства ограниченная оболочкой. Она трехмерная.
  • SHELL Набор граней соединенных между собой через ребра. Оболочки могут быть открытыми или закрытыми.
  • FACE В 2D это часть плоскости; в 3D это часть поверхности. Это геометрия ограничена (обрезана) по контурам. Она двухмерная.
  • WIRE Набор ребер соединенных через вершины. Он может быть как открытым, так и закрытым в зависимости от того связаны ли крайние ребра или нет.
  • EDGE Топологический элемент соответствующий ограниченной кривой. Ребро как правило ограничивается вершинами. Оно одномерное.
  • VERTEX Топологический элемент соответствующий точке. Обладает нулевой размерность.
  • SHAPE общий термин охватывающий все выше сказанное.

наверх

Примеры: Создание простейшей топологии

Wire

Теперь мы создадим топологию из геометрических примитивов. Для изучения мы используем деталь(part), как показано на картинке состоящую из четырех вершин, двух окружностей и двух линий.

наверх

Создание геометрии

В начале мы должны создать отдельную деталь из данной ломаной. И мы должны убедиться что вершины геометрических частей расположены на тех же позициях. В противном случае позже мы не смогли бы соединить геометрические части в топологию!

Итак, сначала мы создаем точки:

import FreeCAD as App
import Part
V1 = App.Vector(0, 10, 0)
V2 = App.Vector(30, 10, 0)
V3 = App.Vector(30, -10, 0)
V4 = App.Vector(0, -10, 0)

наверх

Дуга

Circle


Для каждой дуги нам нужно создать вспомогательную точку и провести дугу через три точки:

VC1 = App.Vector(-10, 0, 0)
C1 = Part.Arc(V1, VC1, V4)
VC2 = App.Vector(40, 0, 0)
C2 = Part.Arc(V2, VC2, V3)

наверх

Линия

Line


Сегменты линии могут быть созданы из двух точек:

L1 = Part.LineSegment(V1, V2)
L2 = Part.LineSegment(V3, V4)

наверх

Соединяем все вместе

Последний шаг - собираем все основные геометрические элементы вместе и получаем форму:

S1 = Part.Shape([C1, L1, C2, L2])

наверх

Создание призмы

Теперь вытягиваем ломанную по направлению и фактически получаем 3D форму:

W = Part.Wire(S1.Edges)
P = W.extrude(App.Vector(0, 0, 10))

наверх

Показать всё

Part.show(P)

наверх

Создание простых фигур

Вы легко можете создавать простые топологические объекты с помощью методов make...() содержащихся в модуле Part:

b = Part.makeBox(100, 100, 100)
Part.show(b)

Доступные make...() методы:

  • makeBox(l,w,h,[p,d]) : создает прямоугольник, с началом в точке p и вытянутый в направлении d с размерами (l,w,h) По умолчанию p установлен как Vector(0,0,0) и d установлен как Vector(0,0,1)
  • makeCircle(radius,[p,d,angle1,angle2]) -- Создает окружность с заданным радиусом. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0 и angle2=360
  • makeCone(radius1,radius2,height,[p,d,angle]) -- Создает конус с заданным радиусами и высотой. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1) и angle=360
  • makeCylinder(radius,height,[p,d,angle]) -- Создает цилиндр с заданным радиусом и высотой. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1) и angle=360
  • makeLine((x1,y1,z1),(x2,y2,z2)) -- Создает линию проходящую через две точки
  • makePlane(length,width,[p,d]) -- Создает плоскость с заданной длинной и шириной. По умолчанию p=Vector(0,0,0) и d=Vector(0,0,1)
  • makePolygon(list) -- Создает многоугольник из списка точек
  • makeSphere(radius,[p,d,angle1,angle2,angle3]) -- Создает сферу с заданным радиусом. По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0, angle2=90 и angle3=360
  • makeTorus(radius1,radius2,[p,d,angle1,angle2,angle3]) -- Создает тор по заданными радиусам.По умолчанию p=Vector(0,0,0), d=Vector(0,0,1), angle1=0, angle2=360 и angle3=360

На странице Part API приведен полный список доступных методов модуля Part.

наверх

Импорт необходимых модулей

В начале нам нужно импортировать модуль Part, чтобы мы могли использовать его содержимое в Python. Также импортируем модуль Base из модуля FreeCAD:

import FreeCAD as App
import Part

наверх

Создание вектора

Векторы являются одними из самых важных частей информации при построении фигур. Они обычно содержат три числа (но не всегда): декартовы координаты x, y и z. Для создания вектора введите:

myVector = App.Vector(3, 2, 0)

Мы только что создали вектор с координатами x = 3, y = 2, z = 0. В модуле Part векторы используются повсеместно. Формы детали также используют другой тип представления точек, называемый Vertex, который является просто контейнером для вектора. Вы можете получить доступ к вектору вершины следующим образом:

myVertex = myShape.Vertexes[0]
print(myVertex.Point)
> Vector (3, 2, 0)

наверх

Создание ребра

Ребра это не что иное, как линия с двумя вершинами:

edge = Part.makeLine((0, 0, 0), (10, 0, 0))
edge.Vertexes
> [<Vertex object at 01877430>, <Vertex object at 014888E0>]

Примечание: Вы можете создать ребро передав два вектора.

vec1 = App.Vector(0, 0, 0)
vec2 = App.Vector(10, 0, 0)
line = Part.LineSegment(vec1, vec2)
edge = line.toShape()

Вы можете узнать длину и центр ребра, вот так:

edge.Length
> 10.0
edge.CenterOfMass
> Vector (5, 0, 0)

наверх

Вывод фигуры на экран

До сих пор мы создали объект ребро, но не увидели его на экране. Это связано с тем, что 3D-сцена FreeCAD отображает только то, что указано для отображения. Для этого мы используем этот простой метод:

Part.show(edge)

Функция show создает объект "shape" в нашем FreeCAD документе. Используйте это всякий раз, когда пришло время показать свое творение на экране.

наверх

Создание ломанной кривой

Ломаная представляет собой многогранную линию и может быть создан из списка ребер или даже из списка ломаных:

edge1 = Part.makeLine((0, 0, 0), (10, 0, 0))
edge2 = Part.makeLine((10, 0, 0), (10, 10, 0))
wire1 = Part.Wire([edge1, edge2]) 
edge3 = Part.makeLine((10, 10, 0), (0, 10, 0))
edge4 = Part.makeLine((0, 10, 0), (0, 0, 0))
wire2 = Part.Wire([edge3, edge4])
wire3 = Part.Wire([wire1, wire2])
wire3.Edges
> [<Edge object at 016695F8>, <Edge object at 0197AED8>, <Edge object at 01828B20>, <Edge object at 0190A788>]
Part.show(wire3)

Part.show(wire3) пакажет 4 ребра, из которых состоит наша ломаная линяи. Другая полезная информация может быть легко найдена:

wire3.Length
> 40.0
wire3.CenterOfMass
> Vector (5, 5, 0)
wire3.isClosed()
> True
wire2.isClosed()
> False

наверх

Создание грани

Только грани, созданные из замкнутых ломаных, будут действительными. В этом примере wire3 является замкнутой ломаной, но wire2 не является замкнутым (см. выше)

face = Part.Face(wire3)
face.Area
> 99.99999999999999
face.CenterOfMass
> Vector (5, 5, 0)
face.Length
> 40.0
face.isValid()
> True
sface = Part.Face(wire2)
sface.isValid()
> False

Только грани имеют поверхность, а ломанные и ребра нет.

наверх

Создание окружности

Окружность может быть создана, например так:

circle = Part.makeCircle(10)
circle.Curve
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))

Если вы хотите создать её с определенным положением и в определенном направлении

ccircle = Part.makeCircle(10, App.Vector(10, 0, 0), App.Vector(1, 0, 0))
ccircle.Curve
> Circle (Radius : 10, Position : (10, 0, 0), Direction : (1, 0, 0))

ccircle будет создана на расстоянии 10 от начала координат x и будет направлена вдоль оси x. Примечание: makeCircle принимает только тип Base.Vector() в качестве позиции и нормали. Вы также можете создать часть окружности, задав начальный и конечный угол:

from math import pi
arc1 = Part.makeCircle(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)
arc2 = Part.makeCircle(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 180, 360)

Обе arc1 и arc2 вместе составляют окружность. Углы задаются в градусах, если вы хотите задать радианами, просто преобразуйте используя формулу: degrees = radians * 180/PI или используя math модуль python-а (прежде, конечно, выполнив import math): degrees = math.degrees(radians)

import math
degrees = math.degrees(radians)

наверх

Создать дугу по точкам

К сожалению нет функции makeArc, но у нас есть функция Part.Arc для создания дуги через три точки. Она создает объект дуги, соединяющий начальную точку с конечной точкой через среднюю точку. Функция .toShape() объекта дуги должна вызываться для получения объекта ребра, так же, как при использовании Part.LineSegment вместо Part.makeLine.

arc = Part.Arc(App.Vector(0, 0, 0), App.Vector(0, 5, 0), App.Vector(5, 5, 0))
arc
> <Arc object>
arc_edge = arc.toShape()
Part.show(arc_edge)

Arc принимает только Base.Vector() для точек. arc_edge - это то, что нам нужно, и мы можем отобразить его с помощью Part.show(arc_edge). Вы также можете получить дугу, используя часть круга:

from math import pi
circle = Part.Circle(App.Vector(0, 0, 0), App.Vector(0, 0, 1), 10)
arc = Part.Arc(circle,0,pi)

Дуги являются действительными ребрами, такими как линии, поэтому их можно использовать и в ломаных линиях.

наверх

Создать многоугольник (полигон)

Линия по нескольким точкам, не что иное как создание ломаной с множеством ребер. функция makePolygon берет список точек и создает ломанную по этим точкам:

lshape_wire = Part.makePolygon([App.Vector(0, 5, 0), App.Vector(0, 0, 0), App.Vector(5, 0, 0)])

наверх

Создание кривой Безье

Кривые Безье используются для моделирования гладких кривых с использованием ряда полюсов (точек) и необязательных весов. Функция ниже делает Part.BezierCurve из ряда точек FreeCAD.Vector. (Примечание: при «получении» и «установке» одного полюса или веса индексы начинаются с 1, а не с 0.)

def makeBCurveEdge(Points):
   geomCurve = Part.BezierCurve()
   geomCurve.setPoles(Points)
   edge = Part.Edge(geomCurve)
   return(edge)

наверх

Создание плоскости

Плоскость это ровная поверхность, в смысле 2D грань. Метод создания её это makePlane(length,width,[start_pnt,dir_normal]). По умолчанию start_pnt=Vector(0,0,0) и dir_normal=Vector(0,0,1). Используя dir_normal = Vector(0,0,1) создаёт плоскость, обращённую к положительному направлению оси z, в то время как dir_normal=Vector(1,0,0) создаёт плоскость обращённую к положительному направлению оси х:

plane = Part.makePlane(2, 2)
plane
> <Face object at 028AF990>
plane = Part.makePlane(2, 2, App.Vector(3, 0, 0), App.Vector(0, 1, 0))
plane.BoundBox
> BoundBox (3, 0, 0, 5, 0, 2)

BoundBox является параллелепипед вмещающих плоскость с диагональю, начиная с (3,0,0) и концом в (5,0,2). Здесь толщина BoundBoxпо оси y равна нулю, поскольку его форма полностью плоская.

Примечание: makePlane доступны только Base.Vector() для задания start_pnt и dir_normal а не кортежи

наверх

Создание эллипса

Эллипс можно создать несколькими способами:

Part.Ellipse()

Создает эллипс с большой полуосью 2 и малой полуосью 1 с центром в (0,0,0)

Part.Ellipse(Ellipse)

Создает копию данного эллипса.

Part.Ellipse(S1, S2, Center)

Создаст эллипс с центров точке Center, где плоскость эллипса определяет Center, S1 и S2, это большая ось ззаданная Center и S1, это больший радиус расстояние между Center и S1, и меньший радиус это расстояние между S2 и юольшей осью.

Part.Ellipse(Center, MajorRadius, MinorRadius)

Создает эллипс с большим и меньшим радиусом MajorRadius и MinorRadius, расположенными в плоскости заданной точкой Center и нормалью (0,0,1)

eli = Part.Ellipse(App.Vector(10, 0, 0), App.Vector(0, 5, 0), App.Vector(0, 0, 0))
Part.show(eli.toShape())

В приведенном выше коде мы ввели S1, S2 и center. Аналогично Дуге, Эллипс также создает объект, а не ребро, так что мы должны превратить его в ребро используя toShape() для отображения

Примечание: Дуга допускает только Base.Vector() для задания точек, а не кортеж.

eli = Part.Ellipse(App.Vector(0, 0, 0), 10, 5)
Part.show(eli.toShape())

для вышеуказанного конструктора Ellipse мы передали center, MajorRadius и MinorRadius.

наверх

Создание тора

Используя makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]). По умолчанию pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0,angle2=360 и angle=360

Рассмотрим тор как маленький круг, вытянутый вдоль большого круга. Radius1 это радиус большого круга, radius2 это радиус малого круга, pnt это центр тора и dir это направление нормали. angle1 и angle2 углы в радианах для малого круга, последний параметр angle для создания секцию (части) тора:

torus = Part.makeTorus(10, 2)

В коде выше, был создан тор с диаметром 20 (радиус 10) и толщиной 4 (малая окружность радиусом 2)

tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)

В приведенном выше коде, создан кусочек тора.

tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 360, 180)

В приведенном выше коде, создан полу-тор, изменен только последний параметр. Т.е. angle а остальные углы установлены по умолчанию. Подстановка угла 180 создаст тор от 0 до 180, т.е. половину тора.

наверх

Создание параллелепипеда или кубоида

Используя makeBox(length,width,height,[pnt,dir]), создаем блок расположенный в pnt с размерами (length,width,height). По умолчанию pnt=Vector(0,0,0) и dir=Vector(0,0,1).

box = Part.makeBox(10, 10, 10)
len(box.Vertexes)
> 8

наверх

Создание сферы

Используя makeSphere(radius,[pnt, dir, angle1,angle2,angle3]). По умолчанию pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=-90, angle2=90 и angle3=360. angle1 и angle2 это вертикальный минимум и максимум сферы (срезает часть сферы снизу или сверху), angle3 is the sphere diameter (определяет замкнутое ли это тело вращения или его секция).

sphere = Part.makeSphere(10)
hemisphere = Part.makeSphere(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), -90, 90, 180)

наверх

Создание цилиндра

Используя makeCylinder(radius,height,[pnt,dir,angle]), создается цилиндр с указанным радиусом и высотой. По умолчанию pnt=Vector(0,0,0),dir=Vector(0,0,1) и angle=360.
cylinder = Part.makeCylinder(5, 20)
partCylinder = Part.makeCylinder(5, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)

наверх

Cоздание конуса

Используя makeCone(radius1,radius2,height,[pnt,dir,angle]), создаем конус с указанными радиусами и высотой. По умолчанию pnt=Vector(0,0,0), dir=Vector(0,0,1) и angle=360.

cone = Part.makeCone(10, 0, 20)
semicone = Part.makeCone(10, 0, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)

наверх

Modify shapes

There are several ways to modify shapes. Some are simple transformation operations such as moving or rotating shapes, others are more complex, such as unioning and subtracting one shape from another.

наверх

Transform operations

Translate a shape

Translating is the act of moving a shape from one place to another. Any shape (edge, face, cube, etc...) can be translated the same way:

myShape = Part.makeBox(2, 2, 2)
myShape.translate(App.Vector(2, 0, 0))

This will move our shape "myShape" 2 units in the X direction.

наверх

Rotate a shape

To rotate a shape, you need to specify the rotation center, the axis, and the rotation angle:

myShape.rotate(App.Vector(0, 0, 0),App.Vector(0, 0, 1), 180)

The above code will rotate the shape 180 degrees around the Z Axis.

наверх

Matrix transformations

A matrix is a very convenient way to store transformations in the 3D world. In a single matrix, you can set translation, rotation and scaling values to be applied to an object. For example:

myMat = App.Matrix()
myMat.move(App.Vector(2, 0, 0))
myMat.rotateZ(math.pi/2)

Note: FreeCAD matrixes work in radians. Also, almost all matrix operations that take a vector can also take three numbers, so these two lines do the same thing:

myMat.move(2, 0, 0)
myMat.move(App.Vector(2, 0, 0))

Once our matrix is set, we can apply it to our shape. FreeCAD provides two methods for doing that: transformShape() and transformGeometry(). The difference is that with the first one, you are sure that no deformations will occur (see Scaling a shape below). We can apply our transformation like this:

myShape.transformShape(myMat)

или

myShape.transformGeometry(myMat)

наверх

Scale a shape

Scaling a shape is a more dangerous operation because, unlike translation or rotation, scaling non-uniformly (with different values for X, Y and Z) can modify the structure of the shape. For example, scaling a circle with a higher value horizontally than vertically will transform it into an ellipse, which behaves mathematically very differently. For scaling, we cannot use the transformShape(), we must use transformGeometry():

myMat = App.Matrix()
myMat.scale(2, 1, 1)
myShape=myShape.transformGeometry(myMat)

наверх

Булевы Операции

Как вырезать одну форму из других?

cut(...) - Вычисление различий задано в топологическом классе shape.

Subtracting a shape from another one is called "cut" in FreeCAD and is done like this:

cylinder = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
sphere = Part.makeSphere(5, App.Vector(5, 0, 0))
diff = cylinder.cut(sphere)

наверх

Как получить пересечение двух форм?

Тем же способом, пересечение между двумя фигурами называется "common(...)" (пересечение задано в топологическом классе shape) и делается так:

The same way, the intersection between two shapes is called "common" and is done this way:

cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
common = cylinder1.common(cylinder2)

наверх

Как объединить две формы?

fuse(...) - Объединение задано в топологическом классе shape

Union is called "fuse" and works the same way:

cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
fuse = cylinder1.fuse(cylinder2)

наверх

Как получить сечение тела и заданной формы?

Section это пересечение твердого тела и плоской фигуры (сечение задано в топологическом классе shape). Вернет секущую кривую, составную кривую, состоящую из ребер.

A "section" is the intersection between a solid shape and a plane shape. It will return an intersection curve, a compound curve composed of edges.

cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
section = cylinder1.section(cylinder2)
section.Wires
> []
section.Edges
> [<Edge object at 0D87CFE8>, <Edge object at 019564F8>, <Edge object at 0D998458>, 
 <Edge  object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>, 
 <Edge object at 0D8F4BB0>]

наверх

Выдавливание

Выдавливание - это процесс «выпячивания» плоской фигуры в определенном направлении, становящейся твердым телом. Представьте, как «выпячивание» круга сделало его трубой:

Extrusion is the act of "pushing" a flat shape in a certain direction, resulting in a solid body. Think of a circle becoming a tube by "pushing it out":

circle = Part.makeCircle(10)
tube = circle.extrude(App.Vector(0, 0, 2))

Если ваш круг полый, вы получите полую трубу. Если ваш круг это диск с заполненной поверхностью, вы получите сплошной цилиндр:

wire = Part.Wire(circle)
disc = Part.Face(wire)
cylinder = disc.extrude(App.Vector(0, 0, 2))

наверх

Исследование Форм

Вы легко можете исследовать структуру топологических данных:

You can easily explore the topological data structure:

import Part
b = Part.makeBox(100, 100, 100)
b.Wires
w = b.Wires[0]
w
w.Wires
w.Vertexes
Part.show(w)
w.Edges
e = w.Edges[0]
e.Vertexes
v = e.Vertexes[0]
v.Point

Если ввести строчку выше в интерпретатор python , вы получите хорошее представление об устройстве объектов Part. Здесь наша команда makeBox() создает твердое тело. Это тело, как и все тела Part, содержит грани. Грани всегда содержат ломанные, которые являются набором ребер ограничивающих грань. Каждая грань обладает минимум одной замкнутой ломаной (может больше, если есть отверстие). В ломанной мы можем посмотреть на каждое ребро отдельно, и по краям каждого ребра мы можем увидеть вершины. Прямые ребра обладают только двумя вершинами, разумеется. Вершины модуля Part являются формами OCC(OpenCascade), но они обладают атрибутом Point, который возвращает вектор FreeCAD.

наверх

Исследование Рёбер

В случае ребра, которое является произвольной кривой, вы наверняка захотите произвести дискретизицию. В FreeCAD ребра задаются с помощью параметра длинны. Это означает что вы можете перемещатся вдоль ребра/кривой задавая длинну:

In case of an edge, which is an arbitrary curve, it's most likely you want to do a discretization. In FreeCAD the edges are parametrized by their lengths. That means you can walk an edge/curve by its length:

import Part
box = Part.makeBox(100, 100, 100)
anEdge = box.Edges[0]
print(anEdge.Length)

Теперь вы получить доступ ко всем свойствам ребра, с помощью длинны или позиции. Это означает, что у ребра в 100mm длинной, начальная позиция это 0 а конечная это 100.

anEdge.tangentAt(0.0)          # tangent direction at the beginning
anEdge.valueAt(0.0)            # Point at the beginning
anEdge.valueAt(100.0)          # Point at the end of the edge
anEdge.derivative1At(50.0)     # first derivative of the curve in the middle
anEdge.derivative2At(50.0)     # second derivative of the curve in the middle
anEdge.derivative3At(50.0)     # third derivative of the curve in the middle
anEdge.centerOfCurvatureAt(50) # center of the curvature for that position
anEdge.curvatureAt(50.0)       # the curvature
anEdge.normalAt(50)            # normal vector at that position (if defined)

наверх

Использование выделения(выбора)

Здесь мы увидим как можно использовать "выделение", которое пользователь сделал в программе просмотра. прежде всего мы создадим блок и отобразим его в окне просмотра.

Here we see now how we can use a selection the user did in the viewer. First of all we create a box and show it in the viewer.

import Part
Part.show(Part.makeBox(100, 100, 100))
Gui.SendMsgToActiveView("ViewFit")

Теперь выберем грани или ребра. С помощью этого сценария вы можете повторить по всем выделенным объектам и их субэлементам:

for o in Gui.Selection.getSelectionEx():
    print(o.ObjectName)
    for s in o.SubElementNames:
        print("name: ", s)
        for s in o.SubObjects:
            print("object: ", s)

Выделим несколько ребер и этот сценарий подсчитает их сумарную длину:

length = 0.0
for o in Gui.Selection.getSelectionEx():
    for s in o.SubObjects:
        length += s.Length

print("Length of the selected edges: ", length)

наверх

Полный пример: бутыль OCC

Типовой пример, взятый на OpenCasCade Technology Tutorial - это как построить бутыль. Это отличный пример и для FreeCAD. В самом деле, если последуете нашему примеру изложенному ниже и странице OCC одновременно, вы лучше поймете как структуры OCC реализованы в FreeCAD. Готовый сценарий описанный ниже, также включен в установленный FreeCAD (в папке Mod/Part) и может быть вызван интерпретатором python, вводом:

A typical example found on the OpenCasCade Technology website is how to build a bottle. This is a good exercise for FreeCAD too. In fact, if you follow our example below and the OCC page simultaneously, you will see how well OCC structures are implemented in FreeCAD. The script is included in the FreeCAD installation (inside the Mod/Part folder) and can be called from the Python interpreter by typing:

import Part
import MakeBottle
bottle = MakeBottle.makeBottle()
Part.show(bottle)

наверх

Готовый сценарий

Здесь представлен готовый сценарий MakeBottle:

For the purpose of this tutorial we will consider a reduced version of the script. In this version the bottle will not be hollowed out, and the neck of the bottle will not be threaded.

import FreeCAD as App
import Part, math

def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0):
    aPnt1=App.Vector(-myWidth / 2., 0, 0)
    aPnt2=App.Vector(-myWidth / 2., -myThickness / 4., 0)
    aPnt3=App.Vector(0, -myThickness / 2., 0)
    aPnt4=App.Vector(myWidth / 2., -myThickness / 4., 0)
    aPnt5=App.Vector(myWidth / 2., 0, 0)

    aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)
    aSegment1=Part.LineSegment(aPnt1, aPnt2)
    aSegment2=Part.LineSegment(aPnt4, aPnt5)

    aEdge1=aSegment1.toShape()
    aEdge2=aArcOfCircle.toShape()
    aEdge3=aSegment2.toShape()
    aWire=Part.Wire([aEdge1, aEdge2, aEdge3])

    aTrsf=App.Matrix()
    aTrsf.rotateZ(math.pi) # rotate around the z-axis

    aMirroredWire=aWire.copy()
    aMirroredWire.transformShape(aTrsf)
    myWireProfile=Part.Wire([aWire, aMirroredWire])

    myFaceProfile=Part.Face(myWireProfile)
    aPrismVec=App.Vector(0, 0, myHeight)
    myBody=myFaceProfile.extrude(aPrismVec)

    myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges)

    neckLocation=App.Vector(0, 0, myHeight)
    neckNormal=App.Vector(0, 0, 1)

    myNeckRadius = myThickness / 4.
    myNeckHeight = myHeight / 10.
    myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal)
    myBody = myBody.fuse(myNeck)

    return myBody

el = makeBottleTut()
Part.show(el)

наверх

Подробные объяснения

import FreeCAD as App
import Part, math

Нам, конечно, необходимы модуль Part, а также модуль FreeCAD.Base, который содержит основные структуры FreeCAD, такие как векторы и матрицы.

def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0):
    aPnt1=App.Vector(-myWidth / 2., 0, 0)
    aPnt2=App.Vector(-myWidth / 2., -myThickness / 4., 0)
    aPnt3=App.Vector(0, -myThickness / 2., 0)
    aPnt4=App.Vector(myWidth / 2., -myThickness / 4., 0)
    aPnt5=App.Vector(myWidth / 2., 0, 0)

Здесь мы задаем нашу функцию makeBottleTut. Эта функция может быть вызвана без аргументов, как мы делали выше, в этом случае будут использоваться значения по умолчанию для ширины, высоты и толщины. Затем мы определили несколько точек которые будут использоваться для построения базового сечения.

...
    aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)
    aSegment1=Part.LineSegment(aPnt1, aPnt2)
    aSegment2=Part.LineSegment(aPnt4, aPnt5)

Здесь мы задаём геометрию: дугу, созданую по 3 точкам, и два линейных сегмента, созданные по 2 точкам.

...
    aEdge1=aSegment1.toShape()
    aEdge2=aArcOfCircle.toShape()
    aEdge3=aSegment2.toShape()
    aWire=Part.Wire([aEdge1, aEdge2, aEdge3])

Запомнили различие между геометрией и формой? Здесь мы создаем форму из нашей строительной геометрии. Три рёбра (ребра могут быть прямыми или кривыми), затем из этих трёх рёбер создается ломанная.

...
    aTrsf=App.Matrix()
    aTrsf.rotateZ(math.pi) # rotate around the z-axis

    aMirroredWire=aWire.copy()
    aMirroredWire.transformShape(aTrsf)
    myWireProfile=Part.Wire([aWire, aMirroredWire])

Пока мы построили только половину сечения. Вместо построения таким же образом целого профиля, мы можем просто отразить то, что мы сделали, и склеить две половинки. Сначала создадим матрицу. Матрица является распространенным способом произвести изменения над объектом в трёхмерном пространстве, поскольку она может содержать в одной структуре все базовые преобразования, которым могут подвергаться трёхмерные объекты (перемещение, вращение и масштабирование). После создания матрицы, мы отражаем её, затем создаем копию нашей ломанной и применяем к ней трансформационную матрицу. Теперь мы получили две ломанные и мы можем создать из них третью ломаную, так как ломанные это всего лишь список ребер.

...
    myFaceProfile=Part.Face(myWireProfile)
    aPrismVec=App.Vector(0, 0, myHeight)
    myBody=myFaceProfile.extrude(aPrismVec)

    myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges)

Теперь мы получили замкнутую ломаную, которую можно обратить в грань. Когда мы имеем грань, мы можем вытянуть её. Сделав это, мы получим твердое тело. Теперь мы добавим небольшое скругление к нашему объекту, потому что мы заботимся о качественном дизайне, не так ли?

...
    neckLocation=App.Vector(0, 0, myHeight)
    neckNormal=App.Vector(0, 0, 1)

    myNeckRadius = myThickness / 4.
    myNeckHeight = myHeight / 10.
    myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal)

Теперь тело нашей бутыли создано, но нам нужно создать горлышко. Так что мы создаем новое твердое тело, с цилиндром.

...
    myBody = myBody.fuse(myNeck)

Операция слияния очень мощная. Она заботится о склеивании, о том, что должно быть приклеено и удаляет части, которые следует удалить.

...
    return myBody

Теперь мы получаем нашу твёрдое тело модуля Part как результат нашей функции.

el = makeBottleTut()
Part.show(el)

В итоге мы вызываем функцию для фактического создания детали, а потом делаем её видимой.

наверх

Example: Pierced box

Here is a complete example of building a pierced box.

Конструкция делается по одной стороне за раз. Когда куб закончен, он выдалбливается вырезанием цилиндра через него.

import FreeCAD as App
import Part, math

size = 10
poly = Part.makePolygon([(0, 0, 0), (size, 0, 0), (size, 0, size), (0, 0, size), (0, 0, 0)])

face1 = Part.Face(poly)
face2 = Part.Face(poly)
face3 = Part.Face(poly)
face4 = Part.Face(poly)
face5 = Part.Face(poly)
face6 = Part.Face(poly)
     
myMat = App.Matrix()

myMat.rotateZ(math.pi / 2)
face2.transformShape(myMat)
face2.translate(App.Vector(size, 0, 0))

myMat.rotateZ(math.pi / 2)
face3.transformShape(myMat)
face3.translate(App.Vector(size, size, 0))

myMat.rotateZ(math.pi / 2)
face4.transformShape(myMat)
face4.translate(App.Vector(0, size, 0))

myMat = App.Matrix()

myMat.rotateX(-math.pi / 2)
face5.transformShape(myMat)

face6.transformShape(myMat)               
face6.translate(App.Vector(0, 0, size))

myShell = Part.makeShell([face1, face2, face3, face4, face5, face6])   
mySolid = Part.makeSolid(myShell)

myCyl = Part.makeCylinder(2, 20)
myCyl.translate(App.Vector(size / 2, size / 2, 0))

cut_part = mySolid.cut(myCyl)

Part.show(cut_part)

наверх

Загрузка и Сохранение

Существует несколько способов сохранить вашу работу. Вы конечно можете сохранить ваш FreeCAD документ, а также вы можете сохранить Part(Деталь) объект напрямую в обычные CAD форматы, такие как BREP, IGS, STEP и STL.

Сохранить форму в файл легко. Есть доступные для всех форм методы exportBrep(), exportIges(), exportStep() и exportStl(). Таким образом:

import Part
s = Part.makeBox(10, 10, 10)
s.exportStep("test.stp")

это сохранит наш блок в файл формата STEP. Для загрузки BREP, IGES или STEP файлов:

import Part
s = Part.Shape()
s.read("test.stp")

Для преобразования файла STEP в файл IGS:

import Part
 s = Part.Shape()
 s.read("file.stp")       # incoming file igs, stp, stl, brep
 s.exportIges("file.igs") # outbound file igs

наверх