Topological data scripting/ru: Difference between revisions
No edit summary |
(Updating to match new version of source page) |
||
Line 1: | Line 1: | ||
<languages/> |
<languages/> |
||
<div class="mw-translate-fuzzy"> |
|||
{{Docnav/ru |
{{Docnav/ru |
||
|[[Mesh Scripting/ru|Mesh Scripting]] |
|[[Mesh Scripting/ru|Mesh Scripting]] |
||
|[[Mesh to Part/ru|Mesh to Part]]}} |
|[[Mesh to Part/ru|Mesh to Part]]}} |
||
</div> |
|||
{{TOCright}} |
|||
{{TutorialInfo/ru |
|||
|Topic=Programming |
|||
|Level=Intermediate |
|||
|Time= |
|||
|Author= |
|||
|FCVersion= |
|||
|Files= |
|||
}} |
|||
На этой странице описаны несколько методов создания и изменения [[Part Module/ru|Part shape]] из python. Перед прочтением этой страницы, если вы новичок в python, полезно прочитать о [[Introduction to Python/ru| скриптинге на python]] и [[FreeCAD Scripting Basics/ru|Как работает скриптинг на Python во FreeCAD]]. |
|||
<div class="mw-translate-fuzzy"> |
|||
== Введение == |
== Введение == |
||
Здесь мы объясним вам, как управлять [[Part Module/ru|модулем Part]] непосредственно из интерпретатора Python FreeCAD или из любого внешнего сценария. Основы создания сценариев топологических данных описаны в [[Part_Module/ru#Explaining_the_concepts|объяснение концепции модуля Part]]. Обязательно просмотрите раздел [[Scripting/ru|Scripting]] и страницы [[FreeCAD Scripting Basics/ru|Основы скриптинга FreeCAD]], если вам нужна дополнительная информация о том, как работает python-скриптинг во FreeCAD . |
Здесь мы объясним вам, как управлять [[Part Module/ru|модулем Part]] непосредственно из интерпретатора Python FreeCAD или из любого внешнего сценария. Основы создания сценариев топологических данных описаны в [[Part_Module/ru#Explaining_the_concepts|объяснение концепции модуля Part]]. Обязательно просмотрите раздел [[Scripting/ru|Scripting]] и страницы [[FreeCAD Scripting Basics/ru|Основы скриптинга FreeCAD]], если вам нужна дополнительная информация о том, как работает python-скриптинг во FreeCAD . |
||
</div> |
|||
Here we will explain to you how to control the [[Part_Module|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. If you are new to Python, it is a good idea to first read the [[Introduction_to_Python|Introduction to Python]]. |
|||
<div class="mw-translate-fuzzy"> |
|||
=== Диаграмма Классов === |
=== Диаграмма Классов === |
||
Это обзор наиболее важных классов модуля Part через [http://en.wikipedia.org/wiki/Unified_Modeling_Language Unified Modeling Language (UML)]: |
Это обзор наиболее важных классов модуля Part через [http://en.wikipedia.org/wiki/Unified_Modeling_Language Unified Modeling Language (UML)]: |
||
[[Image:Part_Classes.jpg|center|Классы Python, содержащиеся в модуле Part]] |
[[Image:Part_Classes.jpg|center|Классы Python, содержащиеся в модуле Part]] |
||
</div> |
|||
This is a [http://en.wikipedia.org/wiki/Unified_Modeling_Language Unified Modeling Language (UML)] overview of the most important classes of the Part module: |
|||
[[Image:Part_Classes.jpg|Python classes of the Part module]] |
|||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
=== Геометрия === |
=== Геометрия === |
||
Геометрические объекты являются строительными блоками для всех топологических объектов: |
Геометрические объекты являются строительными блоками для всех топологических объектов: |
||
Line 29: | Line 34: | ||
* '''CIRCLE''' Окружность или дуга задается центром, начальной и конечной точкой |
* '''CIRCLE''' Окружность или дуга задается центром, начальной и конечной точкой |
||
* '''......''' И вскоре еще немного |
* '''......''' И вскоре еще немного |
||
</div> |
|||
The geometric objects are the building blocks of all topological objects: |
|||
* '''Geom''' Base class of the geometric objects. |
|||
* '''Line''' A straight line in 3D, defined by starting point and end point. |
|||
* '''Circle''' Circle or circle segment defined by a center point and start and end point. |
|||
* '''......''' Etc. |
|||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
=== Топология === |
=== Топология === |
||
Доступны нижеследующие топологические типы данных: |
Доступны нижеследующие топологические типы данных: |
||
Line 41: | Line 56: | ||
* '''VERTEX''' Топологический элемент соответствующий точке. Обладает нулевой размерность. |
* '''VERTEX''' Топологический элемент соответствующий точке. Обладает нулевой размерность. |
||
* '''SHAPE''' общий термин охватывающий все выше сказанное. |
* '''SHAPE''' общий термин охватывающий все выше сказанное. |
||
</div> |
|||
The following topological data types are available: |
|||
* '''Compound''' A group of any type of topological objects. |
|||
* '''Compsolid''' A composite solid is a set of solids connected by their faces. It expands the notions of WIRE and SHELL to solids. |
|||
* '''Solid''' A part of space limited by shells. It is three dimensional. |
|||
* '''Shell''' A set of faces connected by their edges. A shell can be open or closed. |
|||
* '''Face''' In 2D it is part of a plane; in 3D it is part of a surface. Its geometry is constrained (trimmed) by contours. It is two dimensional. |
|||
* '''Wire''' A set of edges connected by their vertices. It can be an open or closed contour depending on whether the edges are linked or not. |
|||
* '''Edge''' A topological element corresponding to a restrained curve. An edge is generally limited by vertices. It has one dimension. |
|||
* '''Vertex''' A topological element corresponding to a point. It has zero dimension. |
|||
* '''Shape''' A generic term covering all of the above. |
|||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
==Примеры: Создание простейшей топологии === |
==Примеры: Создание простейшей топологии === |
||
</div> |
|||
[[Image:Wire.png|Wire]] |
[[Image:Wire.png|Wire]] |
||
<div class="mw-translate-fuzzy"> |
|||
Теперь мы создадим топологию из геометрических примитивов. |
Теперь мы создадим топологию из геометрических примитивов. |
||
Для изучения мы используем деталь(part), как показано на картинке состоящую из четырех вершин, двух окружностей и двух линий. |
Для изучения мы используем деталь(part), как показано на картинке состоящую из четырех вершин, двух окружностей и двух линий. |
||
</div> |
|||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
==== Создание Геометрии ==== |
==== Создание Геометрии ==== |
||
Cначала мы должны создать отдельную деталь из данной ломаной. |
Cначала мы должны создать отдельную деталь из данной ломаной. |
||
И мы должны убедиться что вершины геометрических частей расположены '''на тех же''' позициях. В противном случае позже мы не смогли бы соединить геометрические части в топологию! |
И мы должны убедиться что вершины геометрических частей расположены '''на тех же''' позициях. В противном случае позже мы не смогли бы соединить геометрические части в топологию! |
||
</div> |
|||
First we create the distinct geometric parts of this wire. Making sure that parts that have to be connected later |
|||
share the same vertices. |
|||
<div class="mw-translate-fuzzy"> |
|||
Итак, сначала мы создаем точки: |
Итак, сначала мы создаем точки: |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
import Part |
|||
from FreeCAD import Base |
from FreeCAD import Base |
||
V1 = Base.Vector(0,10,0) |
V1 = Base.Vector(0, 10, 0) |
||
V2 = Base.Vector(30,10,0) |
V2 = Base.Vector(30, 10, 0) |
||
V3 = Base.Vector(30,-10,0) |
V3 = Base.Vector(30, -10, 0) |
||
V4 = Base.Vector(0,-10,0) |
V4 = Base.Vector(0, -10, 0) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
==== Дуга ==== |
==== Дуга ==== |
||
</div> |
|||
[[Image:Circel.png|Circle]] |
[[Image:Circel.png|Circle]] |
||
<div class="mw-translate-fuzzy"> |
|||
Для создания дугу окружности нам нужно создать вспомогательную точку и провести дугу через три точки: |
Для создания дугу окружности нам нужно создать вспомогательную точку и провести дугу через три точки: |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
VC1 = Base.Vector(-10,0,0) |
VC1 = Base.Vector(-10, 0, 0) |
||
C1 = Part.Arc(V1,VC1,V4) |
C1 = Part.Arc(V1, VC1, V4) |
||
VC2 = Base.Vector(40, 0, 0) |
|||
# and the second one |
|||
C2 = Part.Arc(V2, VC2, V3) |
|||
C2 = Part.Arc(V2,VC2,V3) |
|||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
==== Линия ==== |
==== Линия ==== |
||
</div> |
|||
[[Image:Line.png|Line]] |
[[Image:Line.png|Line]] |
||
<div class="mw-translate-fuzzy"> |
|||
Линия может быть очень просто создана из точек: |
Линия может быть очень просто создана из точек: |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
L1 = Part.LineSegment(V1,V2) |
L1 = Part.LineSegment(V1, V2) |
||
L2 = Part.LineSegment(V3, V4) |
|||
# and the second one |
|||
L2 = Part.LineSegment(V3,V4) |
|||
}} |
}} |
||
[[#top|top]] |
|||
«Примечание: в FreeCAD 0.16 использовалась команда Part.Line, для FreeCAD 0.17 необходимо использовать Part.LineSegment» |
|||
<div class="mw-translate-fuzzy"> |
|||
==== Соединяем все вместе ==== |
==== Соединяем все вместе ==== |
||
Последний шаг - собираем все основные геометрические элементы вместе и получаем форму: |
Последний шаг - собираем все основные геометрические элементы вместе и получаем форму: |
||
</div> |
|||
The last step is to put the geometric base elements together |
|||
and bake a topological shape: |
|||
{{Code|code= |
{{Code|code= |
||
S1 = Part.Shape([C1,L1,C2,L2]) |
S1 = Part.Shape([C1, L1, C2, L2]) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
==== Создание призмы ==== |
==== Создание призмы ==== |
||
Теперь вытягиваем ломанную по направлению и фактически получаем 3D форму: |
Теперь вытягиваем ломанную по направлению и фактически получаем 3D форму: |
||
</div> |
|||
Now extrude the wire in a direction and make an actual 3D shape: |
|||
{{Code|code= |
{{Code|code= |
||
W = Part.Wire(S1.Edges) |
W = Part.Wire(S1.Edges) |
||
P = W.extrude(Base.Vector(0,0,10)) |
P = W.extrude(Base.Vector(0, 0, 10)) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
==== Показать все ==== |
==== Показать все ==== |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
Line 115: | Line 182: | ||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
== Создание основных фигур == |
== Создание основных фигур == |
||
Вы легко можете создать базовый топологический объект с помощью методов "make...()" содержащихся в модуле Part: |
Вы легко можете создать базовый топологический объект с помощью методов "make...()" содержащихся в модуле Part: |
||
</div> |
|||
You can easily create basic topological objects with the {{incode|make...()}} |
|||
methods from the Part Module: |
|||
{{Code|code= |
{{Code|code= |
||
b = Part.makeBox(100,100,100) |
b = Part.makeBox(100, 100, 100) |
||
Part.show(b) |
Part.show(b) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Доступные make...() методы: |
Доступные make...() методы: |
||
* makeBox(l,w,h,[p,d]) : создает прямоугольник, с началом в точке p и вытянутый в направлении d с размерами (l,w,h) По умолчанию p установлен как Vector(0,0,0) и d установлен как Vector(0,0,1) |
* makeBox(l,w,h,[p,d]) : создает прямоугольник, с началом в точке p и вытянутый в направлении d с размерами (l,w,h) По умолчанию p установлен как Vector(0,0,0) и d установлен как Vector(0,0,1) |
||
Line 135: | Line 210: | ||
На странице [[Part API]] приведен полный список доступных методов модуля Part. |
На странице [[Part API]] приведен полный список доступных методов модуля Part. |
||
</div> |
|||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
==== Импорт необходимых модулей ==== |
==== Импорт необходимых модулей ==== |
||
Сначала нам нужно импортировать модуль Part, чтобы мы могли использовать его содержимое в python. |
Сначала нам нужно импортировать модуль Part, чтобы мы могли использовать его содержимое в python. |
||
Также импортируем модуль Base из модуля FreeCAD: |
Также импортируем модуль Base из модуля FreeCAD: |
||
</div> |
|||
First we need to import the Part module so we can use its contents in Python. |
|||
We'll also import the Base module from inside the FreeCAD module: |
|||
{{Code|code= |
{{Code|code= |
||
Line 145: | Line 228: | ||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
==== Создание вектора ==== |
==== Создание вектора ==== |
||
[http://en.wikipedia.org/wiki/Euclidean_vector Векторы] являются одними из самых |
[http://en.wikipedia.org/wiki/Euclidean_vector Векторы] являются одними из самых |
||
Line 150: | Line 236: | ||
(но не всегда): декартовы координаты x, y и z. Для |
(но не всегда): декартовы координаты x, y и z. Для |
||
создания вектора введите: |
создания вектора введите: |
||
</div> |
|||
[http://en.wikipedia.org/wiki/Euclidean_vector Vectors] are one of the most |
|||
important pieces of information when building shapes. They usually contain three numbers |
|||
(but not necessarily always): the X, Y and Z cartesian coordinates. You |
|||
create a vector like this: |
|||
{{Code|code= |
{{Code|code= |
||
myVector = Base.Vector(3,2,0) |
myVector = Base.Vector(3, 2, 0) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Мы только что создали вектор с координатами x = 3, y = 2, z = 0. В модуле Part векторы используются повсеместно. Формы детали также используют другой тип представления точек, называемый Vertex, который является просто контейнером для вектора. Вы можете получить доступ к вектору вершины следующим образом: |
Мы только что создали вектор с координатами x = 3, y = 2, z = 0. В модуле Part векторы используются повсеместно. Формы детали также используют другой тип представления точек, называемый Vertex, который является просто контейнером для вектора. Вы можете получить доступ к вектору вершины следующим образом: |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
Line 163: | Line 257: | ||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать Ребро?==== |
====Как создать Ребро?==== |
||
Ребра не что иное как линия с двумя вершинами: |
Ребра не что иное как линия с двумя вершинами: |
||
</div> |
|||
An edge is nothing but a line with two vertices: |
|||
{{Code|code= |
{{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>] |
||
Line 175: | Line 275: | ||
{{Code|code= |
{{Code|code= |
||
vec1 = Base.Vector(0,0,0) |
vec1 = Base.Vector(0, 0, 0) |
||
vec2 = Base.Vector(10,0,0) |
vec2 = Base.Vector(10, 0, 0) |
||
line = Part.LineSegment(vec1,vec2) |
line = Part.LineSegment(vec1, vec2) |
||
edge = line.toShape() |
edge = line.toShape() |
||
}} |
}} |
||
Line 190: | Line 290: | ||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
==== Вывод фигуры на экран ==== |
==== Вывод фигуры на экран ==== |
||
До сих пор мы создали объект ребро, но не увидели его на экране. Это связано с тем, что 3D-сцена FreeCAD отображает только то, что указано для отображения. Для этого мы используем этот простой метод: |
До сих пор мы создали объект ребро, но не увидели его на экране. Это связано с тем, что 3D-сцена FreeCAD отображает только то, что указано для отображения. Для этого мы используем этот простой метод: |
||
</div> |
|||
So far we created an edge object, but it doesn't appear anywhere on the screen. |
|||
This is because the FreeCAD 3D scene |
|||
only displays what you tell it to display. To do that, we use this simple |
|||
method: |
|||
{{Code|code= |
{{Code|code= |
||
Line 197: | Line 306: | ||
}} |
}} |
||
Функция show создает объект "shape" в нашем FreeCAD документе. Используйте это всякий раз, когда пришло время показать свое творение на экране. |
Функция show создает объект "shape" в нашем FreeCAD документе. Используйте это всякий раз, когда пришло время показать свое творение на экране. |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать ломанную кривую?==== |
====Как создать ломанную кривую?==== |
||
Ломаная представляет собой многогранную линию и может быть создан из списка ребер или даже из списка ломаных: |
Ломаная представляет собой многогранную линию и может быть создан из списка ребер или даже из списка ломаных: |
||
</div> |
|||
A wire is a multi-edge line and can be created from a list of edges |
|||
or even a list of wires: |
|||
{{Code|code= |
{{Code|code= |
||
edge1 = Part.makeLine((0,0,0), (10,0,0)) |
edge1 = Part.makeLine((0, 0, 0), (10, 0, 0)) |
||
edge2 = Part.makeLine((10,0,0), (10,10,0)) |
edge2 = Part.makeLine((10, 0, 0), (10, 10, 0)) |
||
wire1 = Part.Wire([edge1,edge2]) |
wire1 = Part.Wire([edge1, edge2]) |
||
edge3 = Part.makeLine((10,10,0), (0,10,0)) |
edge3 = Part.makeLine((10, 10, 0), (0, 10, 0)) |
||
edge4 = Part.makeLine((0,10,0), (0,0,0)) |
edge4 = Part.makeLine((0, 10, 0), (0, 0, 0)) |
||
wire2 = Part.Wire([edge3,edge4]) |
wire2 = Part.Wire([edge3, edge4]) |
||
wire3 = Part.Wire([wire1,wire2]) |
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>] |
||
Line 215: | Line 331: | ||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Part.show(wire3) пакажет 4 ребра, из которых состоит наша ломаная линяи. Другая полезная информация может быть легко найдена: |
Part.show(wire3) пакажет 4 ребра, из которых состоит наша ломаная линяи. Другая полезная информация может быть легко найдена: |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
Line 228: | Line 346: | ||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать Грань?==== |
====Как создать Грань?==== |
||
Только грани, созданные из замкнутых ломаных, будут действительными. В этом примере wire3 является замкнутой ломаной, но wire2 не является замкнутым (см. выше) |
Только грани, созданные из замкнутых ломаных, будут действительными. В этом примере wire3 является замкнутой ломаной, но wire2 не является замкнутым (см. выше) |
||
</div> |
|||
Only faces created from closed wires will be valid. In this example, wire3 |
|||
is a closed wire but wire2 is not (see above) |
|||
{{Code|code= |
{{Code|code= |
||
face = Part.Face(wire3) |
face = Part.Face(wire3) |
||
face.Area |
face.Area |
||
> 99. |
> 99.99999999999999 |
||
face.CenterOfMass |
face.CenterOfMass |
||
> Vector (5, 5, 0) |
> Vector (5, 5, 0) |
||
Line 246: | Line 371: | ||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Только грани обладают поверхностью, а не ломанные и ребра. |
Только грани обладают поверхностью, а не ломанные и ребра. |
||
</div> |
|||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать окружность?==== |
====Как создать окружность?==== |
||
Круг можно создать просто введя: |
Круг можно создать просто введя: |
||
</div> |
|||
A circle can be created like this: |
|||
{{Code|code= |
{{Code|code= |
||
Line 260: | Line 393: | ||
{{Code|code= |
{{Code|code= |
||
ccircle = Part.makeCircle(10, Base.Vector(10,0,0), Base.Vector(1,0,0)) |
ccircle = Part.makeCircle(10, Base.Vector(10, 0, 0), Base.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)) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
ccircle будет создана на расстоянии 10 от начала координат x и будет направлена вдоль оси x. Примечание: makeCircle принимает только тип Base.Vector() в качестве позиции и нормали. Вы также можете создать часть окружности, задав начальный и конечный угол: |
ccircle будет создана на расстоянии 10 от начала координат x и будет направлена вдоль оси x. Примечание: makeCircle принимает только тип Base.Vector() в качестве позиции и нормали. Вы также можете создать часть окружности, задав начальный и конечный угол: |
||
</div> |
|||
{{Code|code= |
{{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, Base.Vector(0, 0, 0), Base.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, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 180, 360) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Обе arc1 и arc2 вместе составляют окружность. |
Обе arc1 и arc2 вместе составляют окружность. |
||
Углы задаются в градусах, если вы хотите задать радианами, просто преобразуйте используя формулу: |
Углы задаются в градусах, если вы хотите задать радианами, просто преобразуйте используя формулу: |
||
Line 278: | Line 414: | ||
или используя math модуль python-а (прежде, конечно, выполнив import math): |
или используя math модуль python-а (прежде, конечно, выполнив import math): |
||
degrees = math.degrees(radians) |
degrees = math.degrees(radians) |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
import math |
|||
degrees = math.degrees(radians) |
degrees = math.degrees(radians) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать Дугу по точкам?==== |
====Как создать Дугу по точкам?==== |
||
К сожалению нет функции makeArc, но у нас есть функция Part.Arc для создания дуги через три точки. Она создает объект дуги, соединяющий начальную точку с конечной точкой через среднюю точку. Функция .toShape() объекта дуги должна вызываться для получения объекта ребра, так же, как при использовании Part.LineSegment вместо Part.makeLine. |
К сожалению нет функции makeArc, но у нас есть функция Part.Arc для создания дуги через три точки. Она создает объект дуги, соединяющий начальную точку с конечной точкой через среднюю точку. Функция .toShape() объекта дуги должна вызываться для получения объекта ребра, так же, как при использовании Part.LineSegment вместо Part.makeLine. |
||
</div> |
|||
Unfortunately there is no {{incode|makeArc()}} function, but we have the {{incode|Part.Arc()}} function to |
|||
create an arc through three points. It creates an arc object |
|||
joining the start point to the end point through the middle point. |
|||
The arc object's {{incode|toShape()}} function must be called to get an edge object, |
|||
the same as when using {{incode|Part.LineSegment}} instead of {{incode|Part.makeLine}}. |
|||
{{Code|code= |
{{Code|code= |
||
arc = Part.Arc(Base.Vector(0,0,0),Base.Vector(0,5,0),Base.Vector(5,5,0)) |
arc = Part.Arc(Base.Vector(0, 0, 0), Base.Vector(0, 5, 0), Base.Vector(5, 5, 0)) |
||
arc |
arc |
||
> <Arc object> |
> <Arc object> |
||
arc_edge = arc.toShape() |
arc_edge = arc.toShape() |
||
Part.show(arc_edge) |
|||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Arc принимает только Base.Vector() для точек. arc_edge - это то, что нам нужно, и мы можем отобразить его с помощью Part.show(arc_edge). Вы также можете получить дугу, используя часть круга: |
Arc принимает только Base.Vector() для точек. arc_edge - это то, что нам нужно, и мы можем отобразить его с помощью Part.show(arc_edge). Вы также можете получить дугу, используя часть круга: |
||
</div> |
|||
{{Code|code= |
{{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(Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 10) |
||
arc = Part.Arc(circle,0,pi) |
arc = Part.Arc(circle,0,pi) |
||
}} |
}} |
||
Line 303: | Line 454: | ||
Дуги являются действительными ребрами, такими как линии, поэтому их можно использовать и в ломаных линиях. |
Дуги являются действительными ребрами, такими как линии, поэтому их можно использовать и в ломаных линиях. |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать многоугольник или линию по точкам?==== |
====Как создать многоугольник или линию по точкам?==== |
||
Линия по нескольким точкам, не что иное как создание ломаной с множеством ребер. |
Линия по нескольким точкам, не что иное как создание ломаной с множеством ребер. |
||
функция makePolygon берет список точек и создает ломанную по этим точкам: |
функция makePolygon берет список точек и создает ломанную по этим точкам: |
||
</div> |
|||
A polygon is simply a wire with multiple straight edges. The {{incode|makePolygon()}} |
|||
function takes a list of points and creates a wire through those points: |
|||
{{Code|code= |
{{Code|code= |
||
lshape_wire = Part.makePolygon([Base.Vector(0,5,0),Base.Vector(0,0,0),Base.Vector(5,0,0)]) |
lshape_wire = Part.makePolygon([Base.Vector(0, 5, 0), Base.Vector(0, 0, 0), Base.Vector(5, 0, 0)]) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
==== Создание кривой Безье ==== |
==== Создание кривой Безье ==== |
||
Кривые Безье используются для моделирования гладких кривых с использованием ряда полюсов (точек) и необязательных весов. Функция ниже делает Part.BezierCurve из ряда точек FreeCAD.Vector. (Примечание: при «получении» и «установке» одного полюса или веса индексы начинаются с 1, а не с 0.) |
Кривые Безье используются для моделирования гладких кривых с использованием ряда полюсов (точек) и необязательных весов. Функция ниже делает Part.BezierCurve из ряда точек FreeCAD.Vector. (Примечание: при «получении» и «установке» одного полюса или веса индексы начинаются с 1, а не с 0.) |
||
</div> |
|||
Bézier curves are used to model smooth curves using a series of poles (points) and optional weights. The function below makes a {{incode|Part.BezierCurve()}} from a series of {{incode|FreeCAD.Vector()}} points. Note: when "getting" and "setting" a single pole or weight, indices start at 1, not 0. |
|||
{{Code|code= |
{{Code|code= |
||
Line 322: | Line 486: | ||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать плоскость?==== |
====Как создать плоскость?==== |
||
Плоскость это ровная поверхность, в смысле 2D грань. Метод создания её это |
Плоскость это ровная поверхность, в смысле 2D грань. Метод создания её это |
||
Line 328: | Line 495: | ||
создаёт плоскость, обращённую к положительному направлению оси z, в то время как dir_normal=Vector(1,0,0) создаёт |
создаёт плоскость, обращённую к положительному направлению оси z, в то время как dir_normal=Vector(1,0,0) создаёт |
||
плоскость обращённую к положительному направлению оси х: |
плоскость обращённую к положительному направлению оси х: |
||
</div> |
|||
A Plane is a flat rectangular surface. The method used to create one is {{incode|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) |
|||
will create the plane facing in the positive Z axis direction, while dir_normal = Vector(1, 0, 0) will create the |
|||
plane facing in the positive X axis direction: |
|||
{{Code|code= |
{{Code|code= |
||
plane = Part.makePlane(2,2) |
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, Base.Vector(3, 0, 0), Base.Vector(0, 1, 0)) |
||
plane.BoundBox |
plane.BoundBox |
||
> BoundBox (3, 0, 0, 5, 0, 2) |
> BoundBox (3, 0, 0, 5, 0, 2) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
BoundBox является параллелепипед вмещающих плоскость с диагональю, начиная с |
BoundBox является параллелепипед вмещающих плоскость с диагональю, начиная с |
||
(3,0,0) и концом в (5,0,2). Здесь толщина BoundBoxпо оси y равна нулю, поскольку его форма полностью плоская. |
(3,0,0) и концом в (5,0,2). Здесь толщина BoundBoxпо оси y равна нулю, поскольку его форма полностью плоская. |
||
</div> |
|||
<div class="mw-translate-fuzzy"> |
|||
Примечание: makePlane доступны только Base.Vector() для задания start_pnt и dir_normal а не кортежи |
Примечание: makePlane доступны только Base.Vector() для задания start_pnt и dir_normal а не кортежи |
||
</div> |
|||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать эллипс?==== |
====Как создать эллипс?==== |
||
Создать эллипс можно несколькими путями: |
Создать эллипс можно несколькими путями: |
||
</div> |
|||
There are several ways to create an ellipse: |
|||
{{Code|code= |
{{Code|code= |
||
Line 350: | Line 532: | ||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Создает эллипс с большой полуосью 2 и малой полуосью 1 с центром в (0,0,0) |
Создает эллипс с большой полуосью 2 и малой полуосью 1 с центром в (0,0,0) |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
Line 359: | Line 543: | ||
{{Code|code= |
{{Code|code= |
||
Part.Ellipse(S1,S2,Center) |
Part.Ellipse(S1, S2, Center) |
||
}} |
}} |
||
Line 369: | Line 553: | ||
{{Code|code= |
{{Code|code= |
||
Part.Ellipse(Center,MajorRadius,MinorRadius) |
Part.Ellipse(Center, MajorRadius, MinorRadius) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Создает эллипс с большим и меньшим радиусом MajorRadius и MinorRadius, расположенными в плоскости заданной точкой Center и нормалью (0,0,1) |
Создает эллипс с большим и меньшим радиусом MajorRadius и MinorRadius, расположенными в плоскости заданной точкой Center и нормалью (0,0,1) |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
eli = Part.Ellipse(Base.Vector(10,0,0),Base.Vector(0,5,0),Base.Vector(0,0,0)) |
eli = Part.Ellipse(Base.Vector(10, 0, 0), Base.Vector(0, 5, 0), Base.Vector(0, 0, 0)) |
||
Part.show(eli.toShape()) |
Part.show(eli.toShape()) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
В приведенном выше коде мы ввели S1, S2 и center. Аналогично Дуге, Эллипс также создает объект, а не ребро, так что мы должны превратить его в ребро используя toShape() для отображения |
В приведенном выше коде мы ввели S1, S2 и center. Аналогично Дуге, Эллипс также создает объект, а не ребро, так что мы должны превратить его в ребро используя toShape() для отображения |
||
</div> |
|||
<div class="mw-translate-fuzzy"> |
|||
Примечание: Дуга допускает только Base.Vector() для задания точек, а не кортеж. |
Примечание: Дуга допускает только Base.Vector() для задания точек, а не кортеж. |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
eli = Part.Ellipse(Base.Vector(0,0,0),10,5) |
eli = Part.Ellipse(Base.Vector(0, 0, 0), 10, 5) |
||
Part.show(eli.toShape()) |
Part.show(eli.toShape()) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
для вышеуказанного конструктора Ellipse мы передали center, MajorRadius и MinorRadius. |
для вышеуказанного конструктора Ellipse мы передали center, MajorRadius и MinorRadius. |
||
</div> |
|||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать Тор?==== |
====Как создать Тор?==== |
||
Используя '''makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle])'''. |
Используя '''makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle])'''. |
||
Line 396: | Line 591: | ||
Рассмотрим тор как маленький круг, вытянутый вдоль большого круга. Radius1 это радиус большого круга, radius2 это радиус малого круга, pnt это центр тора и dir это направление нормали. |
Рассмотрим тор как маленький круг, вытянутый вдоль большого круга. Radius1 это радиус большого круга, radius2 это радиус малого круга, pnt это центр тора и dir это направление нормали. |
||
angle1 и angle2 углы в радианах для малого круга, последний параметр angle для создания секцию (части) тора: |
angle1 и angle2 углы в радианах для малого круга, последний параметр angle для создания секцию (части) тора: |
||
</div> |
|||
Using {{incode|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 the big circle, radius2 is the radius of the small circle, pnt is the center |
|||
of the torus and dir is the normal direction. angle1 and angle2 are angles in |
|||
degrees for the small circle; the last angle parameter is to make a section of |
|||
the torus: |
|||
{{Code|code= |
{{Code|code= |
||
Line 404: | Line 608: | ||
{{Code|code= |
{{Code|code= |
||
tor=Part.makeTorus(10, 5, Base.Vector(0,0,0), Base.Vector(0,0,1), 0, 180) |
tor=Part.makeTorus(10, 5, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 180) |
||
}} |
}} |
||
Line 410: | Line 614: | ||
{{Code|code= |
{{Code|code= |
||
tor=Part.makeTorus(10, 5, Base.Vector(0,0,0), Base.Vector(0,0,1), 0, 360, 180) |
tor=Part.makeTorus(10, 5, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 360, 180) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
В приведенном выше коде, создан полу-тор, изменен только последний параметр. Т.е. angle а остальные углы установлены по умолчанию. Подстановка угла 180 создаст тор от 0 до 180, т.е. половину тора. |
В приведенном выше коде, создан полу-тор, изменен только последний параметр. Т.е. angle а остальные углы установлены по умолчанию. Подстановка угла 180 создаст тор от 0 до 180, т.е. половину тора. |
||
</div> |
|||
[[#top|top]] |
|||
<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). |
Используя '''makeBox(length,width,height,[pnt,dir])''', создаем блок расположенный в pnt с размерами (length,width,height). По умолчанию pnt=Vector(0,0,0) и dir=Vector(0,0,1). |
||
</div> |
|||
Using {{incode|makeBox(length, width, height, [pnt, dir])}}. |
|||
By default pnt = Vector(0, 0, 0) and dir = Vector(0, 0, 1). |
|||
{{Code|code= |
{{Code|code= |
||
box = Part.makeBox(10,10,10) |
box = Part.makeBox(10, 10, 10) |
||
len(box.Vertexes) |
len(box.Vertexes) |
||
> 8 |
> 8 |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать Сферу?==== |
====Как создать Сферу?==== |
||
Используя '''makeSphere(radius,[pnt, dir, angle1,angle2,angle3])'''. |
Используя '''makeSphere(radius,[pnt, dir, angle1,angle2,angle3])'''. |
||
Line 430: | Line 646: | ||
angle1 и angle2 это вертикальный минимум и максимум сферы (срезает часть сферы снизу или сверху), |
angle1 и angle2 это вертикальный минимум и максимум сферы (срезает часть сферы снизу или сверху), |
||
angle3 is the sphere diameter (определяет замкнутое ли это тело вращения или его секция). |
angle3 is the sphere diameter (определяет замкнутое ли это тело вращения или его секция). |
||
</div> |
|||
Using {{incode|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 |
|||
is the sphere diameter. |
|||
{{Code|code= |
{{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, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), -90, 90, 180) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать Цилиндр?==== |
====Как создать Цилиндр?==== |
||
Используя '''makeCylinder(radius,height,[pnt,dir,angle])''', создается цилиндр с указанным радиусом и высотой. По умолчанию pnt=Vector(0,0,0),dir=Vector(0,0,1) и angle=360. |
Используя '''makeCylinder(radius,height,[pnt,dir,angle])''', создается цилиндр с указанным радиусом и высотой. По умолчанию pnt=Vector(0,0,0),dir=Vector(0,0,1) и angle=360. |
||
</div> |
|||
Using {{incode|makeCylinder(radius, height, [pnt, dir, angle])}}. By default |
|||
pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360. |
|||
{{Code|code= |
{{Code|code= |
||
cylinder = Part.makeCylinder(5,20) |
cylinder = Part.makeCylinder(5, 20) |
||
partCylinder = Part.makeCylinder(5,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180) |
partCylinder = Part.makeCylinder(5, 20, Base.Vector(20, 0, 0), Base.Vector(0, 0, 1), 180) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как создать Конус?==== |
====Как создать Конус?==== |
||
Используя '''makeCone(radius1,radius2,height,[pnt,dir,angle])''', создаем конус с указанными радиусами и высотой. По умолчанию pnt=Vector(0,0,0), dir=Vector(0,0,1) и angle=360. |
Используя '''makeCone(radius1,radius2,height,[pnt,dir,angle])''', создаем конус с указанными радиусами и высотой. По умолчанию pnt=Vector(0,0,0), dir=Vector(0,0,1) и angle=360. |
||
</div> |
|||
Using {{incode|makeCone(radius1, radius2, height, [pnt, dir, angle])}}. By default |
|||
pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360. |
|||
{{Code|code= |
{{Code|code= |
||
cone = Part.makeCone(10,0,20) |
cone = Part.makeCone(10, 0, 20) |
||
semicone = Part.makeCone(10,0,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180) |
semicone = Part.makeCone(10, 0, 20, Base.Vector(20, 0, 0), Base.Vector(0, 0, 1), 180) |
||
}} |
}} |
||
[[#top|top]] |
|||
== Modifying shapes == |
|||
==Modify shapes== |
|||
There are several ways to modify shapes. Some are simple transformation operations |
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 |
such as moving or rotating shapes, others are more complex, such as unioning and |
||
subtracting one shape from another. |
subtracting one shape from another. |
||
[[#top|top]] |
|||
=== Transform operations === |
|||
==Transform operations== |
|||
===Translate a shape=== |
|||
==== Translating a shape ==== |
|||
Translating is the act of moving a shape from one place to another. |
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: |
Any shape (edge, face, cube, etc...) can be translated the same way: |
||
{{Code|code= |
{{Code|code= |
||
myShape = Part.makeBox(2,2,2) |
myShape = Part.makeBox(2, 2, 2) |
||
myShape.translate(Base.Vector(2,0,0)) |
myShape.translate(Base.Vector(2, 0, 0)) |
||
}} |
}} |
||
This will move our shape "myShape" 2 units in the |
This will move our shape "myShape" 2 units in the X direction. |
||
[[#top|top]] |
|||
===Rotate a shape=== |
|||
==== Rotating a shape ==== |
|||
To rotate a shape, you need to specify the rotation center, the axis, |
To rotate a shape, you need to specify the rotation center, the axis, |
||
and the rotation angle: |
and the rotation angle: |
||
{{Code|code= |
{{Code|code= |
||
myShape.rotate(Vector(0,0,0),Vector(0,0,1),180) |
myShape.rotate(Base.Vector(0, 0, 0),Base.Vector(0, 0, 1), 180) |
||
}} |
}} |
||
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|top]] |
|||
==== Generic transformations with matrixes ==== |
|||
===Matrix transformations=== |
|||
A matrix is a very convenient way to store transformations in the 3D |
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 |
world. In a single matrix, you can set translation, rotation and scaling |
||
Line 478: | Line 726: | ||
{{Code|code= |
{{Code|code= |
||
myMat = Base.Matrix() |
myMat = Base.Matrix() |
||
myMat.move(Base.Vector(2,0,0)) |
myMat.move(Base.Vector(2, 0, 0)) |
||
myMat.rotateZ(math.pi/2) |
myMat.rotateZ(math.pi/2) |
||
}} |
}} |
||
Line 484: | Line 732: | ||
that take a vector can also take three numbers, so these two lines do the same thing: |
that take a vector can also take three numbers, so these two lines do the same thing: |
||
{{Code|code= |
{{Code|code= |
||
myMat.move(2,0,0) |
myMat.move(2, 0, 0) |
||
myMat.move(Base.Vector(2,0,0)) |
myMat.move(Base.Vector(2, 0, 0)) |
||
}} |
}} |
||
Once our matrix is set, we can apply it to our shape. FreeCAD provides two |
Once our matrix is set, we can apply it to our shape. FreeCAD provides two |
||
methods for doing that: transformShape() and transformGeometry(). The difference |
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 |
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: |
|||
{{Code|code= |
{{Code|code= |
||
myShape.transformShape(myMat) |
myShape.transformShape(myMat) |
||
Line 498: | Line 746: | ||
myShape.transformGeometry(myMat) |
myShape.transformGeometry(myMat) |
||
}} |
}} |
||
[[#top|top]] |
|||
==== Scaling a shape ==== |
|||
===Scale a shape=== |
|||
Scaling a shape is a more dangerous operation because, unlike translation |
Scaling a shape is a more dangerous operation because, unlike translation |
||
or rotation, scaling non-uniformly (with different values for |
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 |
can modify the structure of the shape. For example, scaling a circle with |
||
a higher value horizontally than vertically will transform it into an |
a higher value horizontally than vertically will transform it into an |
||
ellipse, which behaves mathematically very differently. For scaling, we |
ellipse, which behaves mathematically very differently. For scaling, we |
||
cannot use the {{incode|transformShape()}}, we must use {{incode|transformGeometry()}}: |
|||
{{Code|code= |
{{Code|code= |
||
myMat = Base.Matrix() |
myMat = Base.Matrix() |
||
myMat.scale(2,1,1) |
myMat.scale(2, 1, 1) |
||
myShape=myShape.transformGeometry(myMat) |
myShape=myShape.transformGeometry(myMat) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
=== Логические Операции === |
=== Логические Операции === |
||
</div> |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как вырезать одну форму из других?==== |
====Как вырезать одну форму из других?==== |
||
cut(...) - Вычисление различий задано в топологическом классе shape. |
cut(...) - Вычисление различий задано в топологическом классе shape. |
||
</div> |
|||
Subtracting a shape from another one is called "cut" in FreeCAD |
|||
and is done like this: |
|||
{{Code|code= |
{{Code|code= |
||
cylinder = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0)) |
cylinder = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0)) |
||
sphere = Part.makeSphere(5,Base.Vector(5,0,0)) |
sphere = Part.makeSphere(5, Base.Vector(5, 0, 0)) |
||
diff = cylinder.cut(sphere) |
diff = cylinder.cut(sphere) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как получить пересечение двух форм?==== |
====Как получить пересечение двух форм?==== |
||
Тем же способом, пересечение между двумя фигурами называется "common(...)" (пересечение задано в топологическом классе shape) и делается так: |
Тем же способом, пересечение между двумя фигурами называется "common(...)" (пересечение задано в топологическом классе shape) и делается так: |
||
</div> |
|||
The same way, the intersection between two shapes is called "common" and is done |
|||
this way: |
|||
{{Code|code= |
{{Code|code= |
||
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0)) |
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)) |
cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1)) |
||
common = cylinder1.common(cylinder2) |
common = cylinder1.common(cylinder2) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как объединить две формы?==== |
====Как объединить две формы?==== |
||
fuse(...) - Объединение задано в топологическом классе shape |
fuse(...) - Объединение задано в топологическом классе shape |
||
</div> |
|||
Union is called "fuse" and works the same way: |
|||
{{Code|code= |
{{Code|code= |
||
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0)) |
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)) |
cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1)) |
||
fuse = cylinder1.fuse(cylinder2) |
fuse = cylinder1.fuse(cylinder2) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
====Как получить сечение тела и заданной формы?==== |
====Как получить сечение тела и заданной формы?==== |
||
Section это пересечение твердого тела и плоской фигуры (сечение задано в топологическом классе shape). |
Section это пересечение твердого тела и плоской фигуры (сечение задано в топологическом классе shape). |
||
Вернет секущую кривую, составную кривую, состоящую из ребер. |
Вернет секущую кривую, составную кривую, состоящую из ребер. |
||
</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= |
{{Code|code= |
||
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0)) |
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)) |
cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1)) |
||
section = cylinder1.section(cylinder2) |
section = cylinder1.section(cylinder2) |
||
section.Wires |
section.Wires |
||
Line 549: | Line 829: | ||
<Edge object at 0D8F4BB0>] |
<Edge object at 0D8F4BB0>] |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
==== Выдавливание ==== |
==== Выдавливание ==== |
||
Выдавливание - это процесс «выпячивания» плоской фигуры в определенном направлении, становящейся твердым телом. Представьте, как «выпячивание» круга сделало его трубой: |
Выдавливание - это процесс «выпячивания» плоской фигуры в определенном направлении, становящейся твердым телом. Представьте, как «выпячивание» круга сделало его трубой: |
||
</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= |
{{Code|code= |
||
circle = Part.makeCircle(10) |
circle = Part.makeCircle(10) |
||
tube = circle.extrude(Base.Vector(0,0,2)) |
tube = circle.extrude(Base.Vector(0, 0, 2)) |
||
}} |
}} |
||
Если ваш круг полый, вы получите полую трубу. Если ваш круг это диск с заполненной поверхностью, вы получите сплошной цилиндр: |
Если ваш круг полый, вы получите полую трубу. Если ваш круг это диск с заполненной поверхностью, вы получите сплошной цилиндр: |
||
Line 559: | Line 846: | ||
wire = Part.Wire(circle) |
wire = Part.Wire(circle) |
||
disc = Part.Face(wire) |
disc = Part.Face(wire) |
||
cylinder = disc.extrude(Base.Vector(0,0,2)) |
cylinder = disc.extrude(Base.Vector(0, 0, 2)) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
== Исследование Форм == |
== Исследование Форм == |
||
Вы легко можете исследовать структуру топологических данных: |
Вы легко можете исследовать структуру топологических данных: |
||
</div> |
|||
You can easily explore the topological data structure: |
|||
{{Code|code= |
{{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 578: | Line 871: | ||
v.Point |
v.Point |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Если ввести строчку выше в интерпретатор python , вы получите хорошее представление об устройстве объектов Part. Здесь наша команда makeBox() создает твердое тело. Это тело, как и все тела Part, содержит грани. Грани всегда содержат ломанные, которые являются набором ребер ограничивающих грань. Каждая грань обладает минимум одной замкнутой ломаной (может больше, если есть отверстие). В ломанной мы можем посмотреть на каждое ребро отдельно, и по краям каждого ребра мы можем увидеть вершины. Прямые ребра обладают только двумя вершинами, разумеется. Вершины модуля Part являются формами OCC(OpenCascade), но они обладают атрибутом Point, который возвращает вектор FreeCAD. |
|||
Если ввести строчку выше в интерпретатор python , вы получите хорошее представление об устройстве объектов Part. Здесь наша команда makeBox() создает твердое тело. Это тело, как и все тела Part, содержит грани. Грани всегда содержат ломанные, которые являются набором ребер ограничивающих грань. Каждая грань обладает минимум одной замкнутой ломаной (может больше, если есть отверстие). В ломанной мы можем посмотреть на каждое ребро отдельно, и по краям каждого ребра мы можем увидеть вершины. Прямые ребра обладают только двумя вершинами, разумеется. Вершины модуля Part являются формами OCC(OpenCascade), но они обладают атрибутом Point, который возвращает вектор FreeCAD. |
|||
</div> |
|||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
=== Исследование Рёбер === |
=== Исследование Рёбер === |
||
В случае ребра, которое является произвольной кривой, вы наверняка захотите произвести дискретизицию. В FreeCAD ребра задаются с помощью параметра длинны. Это означает что вы можете перемещатся вдоль ребра/кривой задавая длинну: |
В случае ребра, которое является произвольной кривой, вы наверняка захотите произвести дискретизицию. В 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= |
{{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 |
print(anEdge.Length) |
||
}} |
}} |
||
Теперь вы получить доступ ко всем свойствам ребра, с помощью длинны или позиции. Это означает, что у ребра |
Теперь вы получить доступ ко всем свойствам ребра, с помощью длинны или позиции. Это означает, что у ребра |
||
в 100mm длинной, начальная позиция это 0 а конечная это 100. |
в 100mm длинной, начальная позиция это 0 а конечная это 100. |
||
{{Code|code= |
{{Code|code= |
||
anEdge.tangentAt(0.0) # tangent direction at the beginning |
anEdge.tangentAt(0.0) # tangent direction at the beginning |
||
anEdge.valueAt(0.0) # Point at the beginning |
anEdge.valueAt(0.0) # Point at the beginning |
||
anEdge.valueAt(100.0) # Point at the end of the edge |
anEdge.valueAt(100.0) # Point at the end of the edge |
||
anEdge.derivative1At(50.0) # first derivative of the curve in the middle |
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.derivative2At(50.0) # second derivative of the curve in the middle |
||
anEdge.derivative3At(50.0) # third 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) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
=== Использование выделения(выбора) === |
=== Использование выделения(выбора) === |
||
Здесь мы увидим как можно использовать "выделение", которое пользователь сделал в программе просмотра. |
Здесь мы увидим как можно использовать "выделение", которое пользователь сделал в программе просмотра. |
||
прежде всего мы создадим блок и отобразим его в окне просмотра. |
прежде всего мы создадим блок и отобразим его в окне просмотра. |
||
</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= |
{{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") |
||
}} |
}} |
||
Line 612: | Line 922: | ||
{{Code|code= |
{{Code|code= |
||
for o in Gui.Selection.getSelectionEx(): |
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) |
|||
}} |
}} |
||
Выделим несколько ребер и этот сценарий подсчитает их сумарную длину: |
Выделим несколько ребер и этот сценарий подсчитает их сумарную длину: |
||
Line 622: | Line 932: | ||
length = 0.0 |
length = 0.0 |
||
for o in Gui.Selection.getSelectionEx(): |
for o in Gui.Selection.getSelectionEx(): |
||
for s in o.SubObjects: |
|||
length += s.Length |
|||
print "Length of the selected edges:" ,length |
|||
print("Length of the selected edges: ", length) |
|||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
== Полный пример: бутыль OCC == |
== Полный пример: бутыль OCC == |
||
Типовой пример, взятый на [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, вводом: |
Типовой пример, взятый на [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, вводом: |
||
</div> |
|||
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: |
|||
{{Code|code= |
{{Code|code= |
||
import Part |
import Part |
||
Line 634: | Line 951: | ||
Part.show(bottle) |
Part.show(bottle) |
||
}} |
}} |
||
[[#top|top]] |
|||
==== Готовый сценарий ==== |
|||
<div class="mw-translate-fuzzy"> |
|||
=== Готовый сценарий === |
|||
Здесь представлен готовый сценарий MakeBottle: |
Здесь представлен готовый сценарий MakeBottle: |
||
</div> |
|||
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. |
|||
{{Code|code= |
{{Code|code= |
||
import Part |
import Part, math |
||
from FreeCAD import Base |
from FreeCAD import Base |
||
def |
def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0): |
||
aPnt1=Base.Vector(-myWidth/2.,0,0) |
aPnt1=Base.Vector(-myWidth / 2., 0, 0) |
||
aPnt2=Base.Vector(-myWidth/2.,-myThickness/4.,0) |
aPnt2=Base.Vector(-myWidth / 2., -myThickness / 4., 0) |
||
aPnt3=Base.Vector(0,-myThickness/2.,0) |
aPnt3=Base.Vector(0, -myThickness / 2., 0) |
||
aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0) |
aPnt4=Base.Vector(myWidth / 2., -myThickness / 4., 0) |
||
aPnt5=Base.Vector(myWidth/2.,0,0) |
aPnt5=Base.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=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.makeFillet(myThickness/12.0,myBody.Edges) |
|||
return myBody |
|||
aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4) |
|||
el = makeBottle() |
|||
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=Base.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=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) |
|||
return myBody |
|||
el = makeBottleTut() |
|||
Part.show(el) |
Part.show(el) |
||
}} |
}} |
||
[[#top|top]] |
|||
==== Подробные объяснения ==== |
|||
<div class="mw-translate-fuzzy"> |
|||
=== Подробные объяснения === |
|||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
import math |
import Part, math |
||
import Part |
|||
import FreeCAD |
|||
from FreeCAD import Base |
from FreeCAD import Base |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Нам, конечно, необходимы Part модуль, а также модуль FreeCAD.Base, который содержит основные структуры FreeCAD, такие как векторы и матрицы. |
Нам, конечно, необходимы Part модуль, а также модуль FreeCAD.Base, который содержит основные структуры FreeCAD, такие как векторы и матрицы. |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
def |
def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0): |
||
aPnt1 |
aPnt1=Base.Vector(-myWidth / 2., 0, 0) |
||
aPnt2 |
aPnt2=Base.Vector(-myWidth / 2., -myThickness / 4., 0) |
||
aPnt3 |
aPnt3=Base.Vector(0, -myThickness / 2., 0) |
||
aPnt4 |
aPnt4=Base.Vector(myWidth / 2., -myThickness / 4., 0) |
||
aPnt5 |
aPnt5=Base.Vector(myWidth / 2., 0, 0) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Здесь мы задаем нашу функцию makeBottle. Эта функция может быть вызвана без аргументов, как мы делали выше, в этом случае будут использоваться значения по умолчанию для ширины, высоты и толщины. Затем мы определили несколько точек которые будут использоваться для построения базового сечения. |
Здесь мы задаем нашу функцию makeBottle. Эта функция может быть вызвана без аргументов, как мы делали выше, в этом случае будут использоваться значения по умолчанию для ширины, высоты и толщины. Затем мы определили несколько точек которые будут использоваться для построения базового сечения. |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
... |
... |
||
aArcOfCircle = Part.Arc(aPnt2,aPnt3, aPnt4) |
aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4) |
||
aSegment1 |
aSegment1=Part.LineSegment(aPnt1, aPnt2) |
||
aSegment2 |
aSegment2=Part.LineSegment(aPnt4, aPnt5) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Здесь мы фактически задаём геометрию: дугу, созданую по 3 точкам, и два линейных сегмента, созданные по 2 точкам. |
Здесь мы фактически задаём геометрию: дугу, созданую по 3 точкам, и два линейных сегмента, созданные по 2 точкам. |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
... |
... |
||
aEdge1 |
aEdge1=aSegment1.toShape() |
||
aEdge2 |
aEdge2=aArcOfCircle.toShape() |
||
aEdge3 |
aEdge3=aSegment2.toShape() |
||
aWire |
aWire=Part.Wire([aEdge1, aEdge2, aEdge3]) |
||
}} |
}} |
||
Line 734: | Line 1,055: | ||
{{Code|code= |
{{Code|code= |
||
... |
... |
||
aTrsf |
aTrsf=Base.Matrix() |
||
aTrsf.rotateZ(math.pi) # rotate around the z-axis |
aTrsf.rotateZ(math.pi) # rotate around the z-axis |
||
aMirroredWire = aWire.transformGeometry(aTrsf) |
|||
aMirroredWire=aWire.copy() |
|||
myWireProfile = Part.Wire([aWire, aMirroredWire]) |
|||
aMirroredWire.transformShape(aTrsf) |
|||
myWireProfile=Part.Wire([aWire, aMirroredWire]) |
|||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Пока мы построили только половину сечения. Вместо построения таким же образом целого профиля, мы можем просто отразить то, что мы сделали, и склеить две половинки. Сначала создадим матрицу. Матрица является распространенным способом произвести изменения над объектом в трёхмерном пространстве, поскольку она может содержать в одной структуре все базовые преобразования, которым могут подвергаться трёхмерные объекты (перемещение, вращение и масштабирование). После создания матрицы, мы отражаем её, затем создаем копию нашей ломанной, применением к ней трансформационную матрицу. Теперь мы получили две ломанные и мы можем создать из них третью ломаную, так как ломанные это всего лишь список ребер. |
Пока мы построили только половину сечения. Вместо построения таким же образом целого профиля, мы можем просто отразить то, что мы сделали, и склеить две половинки. Сначала создадим матрицу. Матрица является распространенным способом произвести изменения над объектом в трёхмерном пространстве, поскольку она может содержать в одной структуре все базовые преобразования, которым могут подвергаться трёхмерные объекты (перемещение, вращение и масштабирование). После создания матрицы, мы отражаем её, затем создаем копию нашей ломанной, применением к ней трансформационную матрицу. Теперь мы получили две ломанные и мы можем создать из них третью ломаную, так как ломанные это всего лишь список ребер. |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
... |
... |
||
myFaceProfile |
myFaceProfile=Part.Face(myWireProfile) |
||
aPrismVec |
aPrismVec=Base.Vector(0, 0, myHeight) |
||
myBody |
myBody=myFaceProfile.extrude(aPrismVec) |
||
myBody = myBody.makeFillet(myThickness/12.0,myBody.Edges) |
|||
myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges) |
|||
}} |
}} |
||
Line 753: | Line 1,079: | ||
{{Code|code= |
{{Code|code= |
||
... |
... |
||
neckLocation |
neckLocation=Base.Vector(0, 0, myHeight) |
||
neckNormal |
neckNormal=Base.Vector(0, 0, 1) |
||
myNeckRadius = myThickness / 4.0 |
|||
myNeckRadius = myThickness / 4. |
|||
myNeckHeight = myHeight / 10. |
|||
myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal) |
myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal) |
||
}} |
}} |
||
Line 764: | Line 1,091: | ||
myBody = myBody.fuse(myNeck) |
myBody = myBody.fuse(myNeck) |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Очень мощная операция слияния, которая обычно называется в других приложениях объединением. Она заботится о склеивании, о том что должно быть приклеено и удаляет детали которые нужно удалить. |
Очень мощная операция слияния, которая обычно называется в других приложениях объединением. Она заботится о склеивании, о том что должно быть приклеено и удаляет детали которые нужно удалить. |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
... |
... |
||
Line 771: | Line 1,100: | ||
Теперь мы получаем нашу твёрдое тело модуля Part как результат нашей функции. |
Теперь мы получаем нашу твёрдое тело модуля Part как результат нашей функции. |
||
{{Code|code= |
{{Code|code= |
||
el = |
el = makeBottleTut() |
||
Part.show(el) |
Part.show(el) |
||
}} |
}} |
||
В итоге мы вызываем функцию для фактического создания детали, а потом делаем её видимой. |
В итоге мы вызываем функцию для фактического создания детали, а потом делаем её видимой. |
||
[[#top|top]] |
|||
==Box pierced== |
|||
==Example: Pierced box== |
|||
Here is a complete example of building a pierced box. |
Here is a complete example of building a pierced box. |
||
<div class="mw-translate-fuzzy"> |
|||
Конструкция делается по одной стороне за раз, когда куб закончен, он выдалбливается вырезанием цилиндра через него. |
Конструкция делается по одной стороне за раз, когда куб закончен, он выдалбливается вырезанием цилиндра через него. |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
import |
import Part, math |
||
from math import sqrt, pi, sin, cos, asin |
|||
from FreeCAD import Base |
from FreeCAD import Base |
||
size = 10 |
size = 10 |
||
poly = Part.makePolygon( |
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 795: | Line 1,128: | ||
face6 = Part.Face(poly) |
face6 = Part.Face(poly) |
||
myMat = |
myMat = Base.Matrix() |
||
myMat.rotateZ(math.pi/2) |
|||
myMat.rotateZ(math.pi / 2) |
|||
face2.transformShape(myMat) |
face2.transformShape(myMat) |
||
face2.translate( |
face2.translate(Base.Vector(size, 0, 0)) |
||
myMat.rotateZ(math.pi/2) |
myMat.rotateZ(math.pi / 2) |
||
face3.transformShape(myMat) |
face3.transformShape(myMat) |
||
face3.translate( |
face3.translate(Base.Vector(size, size, 0)) |
||
myMat.rotateZ(math.pi/2) |
myMat.rotateZ(math.pi / 2) |
||
face4.transformShape(myMat) |
face4.transformShape(myMat) |
||
face4.translate( |
face4.translate(Base.Vector(0, size, 0)) |
||
myMat = |
myMat = Base.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( |
face6.translate(Base.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( |
myCyl.translate(Base.Vector(size / 2, size / 2, 0)) |
||
cut_part = |
cut_part = mySolid.cut(myCyl) |
||
Part.show(cut_part) |
Part.show(cut_part) |
||
}} |
}} |
||
[[#top|top]] |
|||
<div class="mw-translate-fuzzy"> |
|||
== Загрузка и Сохранение == |
== Загрузка и Сохранение == |
||
Есть несколько путей чтобы сохранения вышей работы в Part модули. Вы конечно можете сохранить ваш FreeCAD документ, а также вы можете сохранить Part(Деталь) объект напрямую в обычные CAD форматы, такие как BREP, IGS, STEP и STL. |
Есть несколько путей чтобы сохранения вышей работы в Part модули. Вы конечно можете сохранить ваш FreeCAD документ, а также вы можете сохранить Part(Деталь) объект напрямую в обычные CAD форматы, такие как BREP, IGS, STEP и STL. |
||
</div> |
|||
There are several ways to save your work. You can of course save your FreeCAD document, but you can also save [[Part_workbench|Part]] objects directly to common CAD formats, such as BREP, IGS, STEP and STL. |
|||
<div class="mw-translate-fuzzy"> |
|||
Сохранить форму в файл легко. Есть доступные для всех форм методы exportBrep(), exportIges(), exportStl() и exportStep(). Таким образом: |
Сохранить форму в файл легко. Есть доступные для всех форм методы exportBrep(), exportIges(), exportStl() и exportStep(). Таким образом: |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
import Part |
import Part |
||
s = Part.makeBox( |
s = Part.makeBox(10, 10, 10) |
||
s.exportStep("test.stp") |
s.exportStep("test.stp") |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
это сохранит наш блок в файл формата STEP. Для загрузки BREP, IGES или STEP файлов: |
это сохранит наш блок в файл формата STEP. Для загрузки BREP, IGES или STEP файлов: |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
import Part |
import Part |
||
Line 844: | Line 1,186: | ||
s.read("test.stp") |
s.read("test.stp") |
||
}} |
}} |
||
<div class="mw-translate-fuzzy"> |
|||
Для преобразования файла '''.stp''' в файл '''.igs''': |
Для преобразования файла '''.stp''' в файл '''.igs''': |
||
</div> |
|||
{{Code|code= |
{{Code|code= |
||
import Part |
import Part |
||
Line 851: | Line 1,195: | ||
s.exportIges("file.igs") # outbound file igs |
s.exportIges("file.igs") # outbound file igs |
||
}} |
}} |
||
[[#top|top]] |
|||
Заметьте, что импорт или открытие BREP, IGES or STEP файлов также можно сделать напрямую с помощью меню File -> Open, или File -> Import, в то время как экспорт может быть сделан через File → Export. |
|||
<div class="mw-translate-fuzzy"> |
|||
{{Docnav/ru |
{{Docnav/ru |
||
|[[Mesh Scripting/ru|Mesh Scripting]] |
|[[Mesh Scripting/ru|Mesh Scripting]] |
||
|[[Mesh to Part/ru|Mesh to Part]]}} |
|[[Mesh to Part/ru|Mesh to Part]]}} |
||
</div> |
|||
{{Powerdocnavi{{#translation:}}}} |
{{Powerdocnavi{{#translation:}}}} |
||
[[Category:Developer Documentation{{#translation:}}]] |
|||
[[Category:Python Code{{#translation:}}]] |
[[Category:Python Code{{#translation:}}]] |
||
{{clear}} |
{{clear}} |
Revision as of 08:53, 12 June 2020
Введение
Здесь мы объясним вам, как управлять модулем Part непосредственно из интерпретатора Python FreeCAD или из любого внешнего сценария. Основы создания сценариев топологических данных описаны в объяснение концепции модуля Part. Обязательно просмотрите раздел Scripting и страницы Основы скриптинга FreeCAD, если вам нужна дополнительная информация о том, как работает python-скриптинг во FreeCAD .
Here we will explain to 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. 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. If you are new to Python, it is a good idea to first read the Introduction to Python.
Диаграмма Классов
Это обзор наиболее важных классов модуля Part через Unified Modeling Language (UML):
This is a Unified Modeling Language (UML) overview of the most important classes of the Part module:
Геометрия
Геометрические объекты являются строительными блоками для всех топологических объектов:
- GEOM Базовый класс геометрических объектов
- LINE Прямая линия в 3D, задается начальной и конечной точкой
- CIRCLE Окружность или дуга задается центром, начальной и конечной точкой
- ...... И вскоре еще немного
The geometric objects are the building blocks of all topological objects:
- Geom Base class of the geometric objects.
- Line A straight line in 3D, defined by starting point and end point.
- Circle Circle or circle segment defined by a center point and start and end point.
- ...... Etc.
Топология
Доступны нижеследующие топологические типы данных:
- COMPOUND Группа из топологических объектов любого типа.
- COMPSOLID Составное твердое тело, как набор твердых тел соединенными гранями. Он расширяет понятие Ломаной кривой(WIRE) и оболочки(SHELL) для твердых тел.
- SOLID Часть пространства ограниченная оболочкой. Она трехмерная.
- SHELL Набор граней соединенных между собой через ребра. Оболочки могут быть открытыми или закрытыми.
- FACE В 2D это часть плоскости; в 3D это часть поверхности. Это геометрия ограничена (обрезана) по контурам. Она двухмерная.
- WIRE Набор ребер соединенных через вершины. Он может быть как открытым, так и закрытым в зависимости от того связаны ли крайние ребра или нет.
- EDGE Топологический элемент соответствующий ограниченной кривой. Ребро как правило ограничивается вершинами. Оно одномерное.
- VERTEX Топологический элемент соответствующий точке. Обладает нулевой размерность.
- SHAPE общий термин охватывающий все выше сказанное.
The following topological data types are available:
- Compound A group of any type of topological objects.
- Compsolid A composite solid is a set of solids connected by their faces. It expands the notions of WIRE and SHELL to solids.
- Solid A part of space limited by shells. It is three dimensional.
- Shell A set of faces connected by their edges. A shell can be open or closed.
- Face In 2D it is part of a plane; in 3D it is part of a surface. Its geometry is constrained (trimmed) by contours. It is two dimensional.
- Wire A set of edges connected by their vertices. It can be an open or closed contour depending on whether the edges are linked or not.
- Edge A topological element corresponding to a restrained curve. An edge is generally limited by vertices. It has one dimension.
- Vertex A topological element corresponding to a point. It has zero dimension.
- Shape A generic term covering all of the above.
Примеры: Создание простейшей топологии =
Теперь мы создадим топологию из геометрических примитивов. Для изучения мы используем деталь(part), как показано на картинке состоящую из четырех вершин, двух окружностей и двух линий.
Создание Геометрии
Cначала мы должны создать отдельную деталь из данной ломаной. И мы должны убедиться что вершины геометрических частей расположены на тех же позициях. В противном случае позже мы не смогли бы соединить геометрические части в топологию!
First we create the distinct geometric parts of this wire. Making sure that parts that have to be connected later share the same vertices.
Итак, сначала мы создаем точки:
import Part
from FreeCAD import Base
V1 = Base.Vector(0, 10, 0)
V2 = Base.Vector(30, 10, 0)
V3 = Base.Vector(30, -10, 0)
V4 = Base.Vector(0, -10, 0)
Дуга
Для создания дугу окружности нам нужно создать вспомогательную точку и провести дугу через три точки:
VC1 = Base.Vector(-10, 0, 0)
C1 = Part.Arc(V1, VC1, V4)
VC2 = Base.Vector(40, 0, 0)
C2 = Part.Arc(V2, VC2, V3)
Линия
Линия может быть очень просто создана из точек:
L1 = Part.LineSegment(V1, V2)
L2 = Part.LineSegment(V3, V4)
Соединяем все вместе
Последний шаг - собираем все основные геометрические элементы вместе и получаем форму:
The last step is to put the geometric base elements together and bake a topological shape:
S1 = Part.Shape([C1, L1, C2, L2])
Создание призмы
Теперь вытягиваем ломанную по направлению и фактически получаем 3D форму:
Now extrude the wire in a direction and make an actual 3D shape:
W = Part.Wire(S1.Edges)
P = W.extrude(Base.Vector(0, 0, 10))
Показать все
Part.show(P)
Создание основных фигур
Вы легко можете создать базовый топологический объект с помощью методов "make...()" содержащихся в модуле Part:
You can easily create basic topological objects with the make...()
methods from the Part Module:
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:
First we need to import the Part module so we can use its contents in Python. We'll also import the Base module from inside the FreeCAD module:
import Part
from FreeCAD import Base
Создание вектора
Векторы являются одними из самых важных частей информации при построении фигур. Они обычно содержат три числа (но не всегда): декартовы координаты x, y и z. Для создания вектора введите:
Vectors are one of the most important pieces of information when building shapes. They usually contain three numbers (but not necessarily always): the X, Y and Z cartesian coordinates. You create a vector like this:
myVector = Base.Vector(3, 2, 0)
Мы только что создали вектор с координатами x = 3, y = 2, z = 0. В модуле Part векторы используются повсеместно. Формы детали также используют другой тип представления точек, называемый Vertex, который является просто контейнером для вектора. Вы можете получить доступ к вектору вершины следующим образом:
myVertex = myShape.Vertexes[0]
print myVertex.Point
> Vector (3, 2, 0)
Как создать Ребро?
Ребра не что иное как линия с двумя вершинами:
An edge is nothing but a line with two vertices:
edge = Part.makeLine((0, 0, 0), (10, 0, 0))
edge.Vertexes
> [<Vertex object at 01877430>, <Vertex object at 014888E0>]
Примечание: Вы можете создать ребро передав два вектора.
vec1 = Base.Vector(0, 0, 0)
vec2 = Base.Vector(10, 0, 0)
line = Part.LineSegment(vec1, vec2)
edge = line.toShape()
Вы можете узнать длину и центр ребра, вот так:
edge.Length
> 10.0
edge.CenterOfMass
> Vector (5, 0, 0)
Вывод фигуры на экран
До сих пор мы создали объект ребро, но не увидели его на экране. Это связано с тем, что 3D-сцена FreeCAD отображает только то, что указано для отображения. Для этого мы используем этот простой метод:
So far we created an edge object, but it doesn't appear anywhere on the screen. This is because the FreeCAD 3D scene only displays what you tell it to display. To do that, we use this simple method:
Part.show(edge)
Функция show создает объект "shape" в нашем FreeCAD документе. Используйте это всякий раз, когда пришло время показать свое творение на экране.
Как создать ломанную кривую?
Ломаная представляет собой многогранную линию и может быть создан из списка ребер или даже из списка ломаных:
A wire is a multi-edge line and can be created from a list of edges or even a list of wires:
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 не является замкнутым (см. выше)
Only faces created from closed wires will be valid. In this example, wire3 is a closed wire but wire2 is not (see above)
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)
face.isValid()
> False
Только грани обладают поверхностью, а не ломанные и ребра.
Как создать окружность?
Круг можно создать просто введя:
A circle can be created like this:
circle = Part.makeCircle(10)
circle.Curve
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))
Если вы хотите создать её с определенным положением и в определенном направлении
ccircle = Part.makeCircle(10, Base.Vector(10, 0, 0), Base.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, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 180)
arc2 = Part.makeCircle(10, Base.Vector(0, 0, 0), Base.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.
Unfortunately there is no makeArc()
function, but we have the Part.Arc()
function to
create an arc through three points. It creates an arc object
joining the start point to the end point through the middle point.
The arc object's toShape()
function must be called to get an edge object,
the same as when using Part.LineSegment
instead of Part.makeLine
.
arc = Part.Arc(Base.Vector(0, 0, 0), Base.Vector(0, 5, 0), Base.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(Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 10)
arc = Part.Arc(circle,0,pi)
Дуги являются действительными ребрами, такими как линии, поэтому их можно использовать и в ломаных линиях.
Как создать многоугольник или линию по точкам?
Линия по нескольким точкам, не что иное как создание ломаной с множеством ребер. функция makePolygon берет список точек и создает ломанную по этим точкам:
A polygon is simply a wire with multiple straight edges. The makePolygon()
function takes a list of points and creates a wire through those points:
lshape_wire = Part.makePolygon([Base.Vector(0, 5, 0), Base.Vector(0, 0, 0), Base.Vector(5, 0, 0)])
Создание кривой Безье
Кривые Безье используются для моделирования гладких кривых с использованием ряда полюсов (точек) и необязательных весов. Функция ниже делает Part.BezierCurve из ряда точек FreeCAD.Vector. (Примечание: при «получении» и «установке» одного полюса или веса индексы начинаются с 1, а не с 0.)
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.
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) создаёт плоскость обращённую к положительному направлению оси х:
A Plane is a flat rectangular surface. The method used to create one is 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)
will create the plane facing in the positive Z axis direction, while dir_normal = Vector(1, 0, 0) will create the
plane facing in the positive X axis direction:
plane = Part.makePlane(2, 2)
plane
> <Face object at 028AF990>
plane = Part.makePlane(2, 2, Base.Vector(3, 0, 0), Base.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 а не кортежи
Как создать эллипс?
Создать эллипс можно несколькими путями:
There are several ways to create an ellipse:
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(Base.Vector(10, 0, 0), Base.Vector(0, 5, 0), Base.Vector(0, 0, 0))
Part.show(eli.toShape())
В приведенном выше коде мы ввели S1, S2 и center. Аналогично Дуге, Эллипс также создает объект, а не ребро, так что мы должны превратить его в ребро используя toShape() для отображения
Примечание: Дуга допускает только Base.Vector() для задания точек, а не кортеж.
eli = Part.Ellipse(Base.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 для создания секцию (части) тора:
Using 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 the big circle, radius2 is the radius of the small circle, pnt is the center
of the torus and dir is the normal direction. angle1 and angle2 are angles in
degrees for the small circle; the last angle parameter is to make a section of
the torus:
torus = Part.makeTorus(10, 2)
В коде выше, был создан тор с диаметром 20 (радиус 10) и толщиной 4 (малая окружность радиусом 2)
tor=Part.makeTorus(10, 5, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 180)
В приведенном выше коде, создан кусочек тора.
tor=Part.makeTorus(10, 5, Base.Vector(0, 0, 0), Base.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).
Using makeBox(length, width, height, [pnt, dir])
.
By default pnt = Vector(0, 0, 0) and 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 (определяет замкнутое ли это тело вращения или его секция).
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
is the sphere diameter.
sphere = Part.makeSphere(10)
hemisphere = Part.makeSphere(10, Base.Vector(0, 0, 0), Base.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.
Using makeCylinder(radius, height, [pnt, dir, angle])
. By default
pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.
cylinder = Part.makeCylinder(5, 20)
partCylinder = Part.makeCylinder(5, 20, Base.Vector(20, 0, 0), Base.Vector(0, 0, 1), 180)
Как создать Конус?
Используя makeCone(radius1,radius2,height,[pnt,dir,angle]), создаем конус с указанными радиусами и высотой. По умолчанию pnt=Vector(0,0,0), dir=Vector(0,0,1) и angle=360.
Using makeCone(radius1, radius2, height, [pnt, dir, angle])
. By default
pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.
cone = Part.makeCone(10, 0, 20)
semicone = Part.makeCone(10, 0, 20, Base.Vector(20, 0, 0), Base.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(Base.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(Base.Vector(0, 0, 0),Base.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 = Base.Matrix()
myMat.move(Base.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(Base.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)
or
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 = Base.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, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))
sphere = Part.makeSphere(5, Base.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, 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))
common = cylinder1.common(cylinder2)
Как объединить две формы?
fuse(...) - Объединение задано в топологическом классе shape
Union is called "fuse" and works the same way:
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))
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, 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))
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(Base.Vector(0, 0, 2))
Если ваш круг полый, вы получите полую трубу. Если ваш круг это диск с заполненной поверхностью, вы получите сплошной цилиндр:
wire = Part.Wire(circle)
disc = Part.Face(wire)
cylinder = disc.extrude(Base.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 Part, math
from FreeCAD import Base
def makeBottleTut(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.LineSegment(aPnt1, aPnt2)
aSegment2=Part.LineSegment(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.copy()
aMirroredWire.transformShape(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)
return myBody
el = makeBottleTut()
Part.show(el)
Подробные объяснения
import Part, math
from FreeCAD import Base
Нам, конечно, необходимы Part модуль, а также модуль FreeCAD.Base, который содержит основные структуры FreeCAD, такие как векторы и матрицы.
def makeBottleTut(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)
Здесь мы задаем нашу функцию makeBottle. Эта функция может быть вызвана без аргументов, как мы делали выше, в этом случае будут использоваться значения по умолчанию для ширины, высоты и толщины. Затем мы определили несколько точек которые будут использоваться для построения базового сечения.
...
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=Base.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=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)
Очень мощная операция слияния, которая обычно называется в других приложениях объединением. Она заботится о склеивании, о том что должно быть приклеено и удаляет детали которые нужно удалить.
...
return myBody
Теперь мы получаем нашу твёрдое тело модуля Part как результат нашей функции.
el = makeBottleTut()
Part.show(el)
В итоге мы вызываем функцию для фактического создания детали, а потом делаем её видимой.
Example: Pierced box
Here is a complete example of building a pierced box.
Конструкция делается по одной стороне за раз, когда куб закончен, он выдалбливается вырезанием цилиндра через него.
import Part, math
from FreeCAD import Base
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 = Base.Matrix()
myMat.rotateZ(math.pi / 2)
face2.transformShape(myMat)
face2.translate(Base.Vector(size, 0, 0))
myMat.rotateZ(math.pi / 2)
face3.transformShape(myMat)
face3.translate(Base.Vector(size, size, 0))
myMat.rotateZ(math.pi / 2)
face4.transformShape(myMat)
face4.translate(Base.Vector(0, size, 0))
myMat = Base.Matrix()
myMat.rotateX(-math.pi / 2)
face5.transformShape(myMat)
face6.transformShape(myMat)
face6.translate(Base.Vector(0, 0, size))
myShell = Part.makeShell([face1, face2, face3, face4, face5, face6])
mySolid = Part.makeSolid(myShell)
myCyl = Part.makeCylinder(2, 20)
myCyl.translate(Base.Vector(size / 2, size / 2, 0))
cut_part = mySolid.cut(myCyl)
Part.show(cut_part)
Загрузка и Сохранение
Есть несколько путей чтобы сохранения вышей работы в Part модули. Вы конечно можете сохранить ваш FreeCAD документ, а также вы можете сохранить Part(Деталь) объект напрямую в обычные CAD форматы, такие как BREP, IGS, STEP и STL.
There are several ways to save your work. 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.
Сохранить форму в файл легко. Есть доступные для всех форм методы exportBrep(), exportIges(), exportStl() и exportStep(). Таким образом:
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")
Для преобразования файла .stp в файл .igs:
import Part
s = Part.Shape()
s.read("file.stp") # incoming file igs, stp, stl, brep
s.exportIges("file.igs") # outbound file igs
- FreeCAD scripting: Python, Introduction to Python, Python scripting tutorial, FreeCAD Scripting Basics
- Modules: Builtin modules, Units, Quantity
- Workbenches: Workbench creation, Gui Commands, Commands, Installing more workbenches
- Meshes and Parts: Mesh Scripting, Topological data scripting, Mesh to Part, PythonOCC
- Parametric objects: Scripted objects, Viewproviders (Custom icon in tree view)
- Scenegraph: Coin (Inventor) scenegraph, Pivy
- Graphical interface: Interface creation, Interface creation completely in Python (1, 2, 3, 4, 5), PySide, PySide examples beginner, intermediate, advanced
- Macros: Macros, How to install macros
- Embedding: Embedding FreeCAD, Embedding FreeCADGui
- Other: Expressions, Code snippets, Line drawing function, FreeCAD vector math library (deprecated)
- Hubs: User hub, Power users hub, Developer hub