Topological data scripting/es: Difference between revisions
Renatorivo (talk | contribs) m (→Introducción) |
(Updating to match new version of source page) |
||
Line 1: | Line 1: | ||
This page describes several methods for creating and modifying [[Part Module|Part shapes]] from python. Before reading this page, if you are new to python, it is a good idea to read about [[Introduction to Python|python scripting]] and [[FreeCAD Scripting Basics|how python scripting works in FreeCAD]]. |
|||
== |
== Introduction == |
||
We will here explain you how to control the [[Part Module]] directly from the FreeCAD python interpreter, or from any external script. The basics about Topological data scripting are described in [[Part_Module#Explaining_the_concepts|Part Module Explaining the concepts]]. Be sure to browse the [[Scripting]] section and the [[FreeCAD Scripting Basics]] pages if you need more information about how python scripting works in FreeCAD. |
|||
Aquí le explicamos cómo controlar el [[Part Module/es|Módulo de Pieza]] directamente desde el intérprete de Python de FreeCAD, o desde cualquier archivo de guión externo. Asegúrate de navegar por la sección [[Power users hub/es|Archivos de guión]] y las páginas [[FreeCAD Scripting Basics/es|Conceptos básicos de archivos de guión en FreeCAD]] si necesitas más información acerca de cómo funcionan los archivos de guión de Python en FreeCAD. |
|||
=== Diagrama de clases === |
|||
Ésta es una descripción [http://es.wikipedia.org/wiki/Lenguaje_Unificado_de_Modelado Lenguaje Unificado de Modelado (UML)] de las clases más importante del módulo de Pieza: |
|||
=== Class Diagram === |
|||
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|center|Python classes of the Part module]] |
[[Image:Part_Classes.jpg|center|Python classes of the Part module]] |
||
=== |
=== Geometry === |
||
The geometric objects are the building block of all topological objects: |
|||
* '''Geom''' Base class of the geometric objects |
|||
Los objetos geométricos son la piedra angular de todos los objetos topológicos: |
|||
* '''Line''' A straight line in 3D, defined by starting point and and point |
|||
* '''Circle''' Circle or circle segment defined by a center point and start and end point |
|||
* '''geom''' clase base de los objetos geométricos |
|||
* '''......''' And soon some more |
|||
* '''line''' Una línea recta en 3D, definido por el punto de inicio y el punto final |
|||
* '''circle''' Círculo o segmento de círculo definido por un punto centro y los puntos de inicio y final |
|||
* '''......''' Y en breve más cosas ;-) |
|||
=== |
=== Topology === |
||
The following topological data types are available: |
|||
Los siguientes tipos de datos topológicos están disponibles: |
|||
* ''' |
* '''Compound''' A group of any type of topological object. |
||
* ''' |
* '''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. |
|||
* '''wire''' Un grupo de bordes conectados por sus vértices. Puede tener un contorno abierto o cerrado, dependiendo que que sus bordes estén o no conectados. |
|||
* '''Edge''' A topological element corresponding to a restrained curve. An edge is generally limited by vertices. It has one dimension. |
|||
* '''edge''' Un elemento topológico que corresponde a una curva limitada. Un borde está normalmente limitado por vértices. Es un ente unidimensional. |
|||
* '''Vertex''' A topological element corresponding to a point. It has zero dimension. |
|||
* '''vertex''' Un elemento topológico que se corresponde con un punto. Tiene dimensión cero. |
|||
* ''' |
* '''Shape''' A generic term covering all of the above. |
||
=== Quick example : Creating simple topology === |
|||
== Ejemplo rápido: Creación de topologías básicas == |
|||
[[Image:Wire.png|right|Wire]] |
[[Image:Wire.png|right|Wire]] |
||
Crearemos ahora una topología por construcción de geometría simple. Como un caso de estudio utilizaremos una pieza como se puede ver en la imagen que consiste en cuatro vértices, dos circunferencias y dos líneas. |
|||
We will now create a topology by constructing it out of simpler geometry. |
|||
==== Creación de geometría ==== |
|||
As a case study we use a part as seen in the picture which consists of |
|||
four vertexes, two circles and two lines. |
|||
==== Creating Geometry ==== |
|||
Primero tenemos que crear las distintas partes de la geometría de este contorno. |
|||
First we have to create the distinct geometric parts of this wire. |
|||
Y tenemos que tener cuidado de que los vértices de las partes de la geometría están en la '''misma''' posición. De otro modo después podríamos no ser capaces de conectar las partes de la geometría en una topología! |
|||
And we have to take care that the vertexes of the geometric parts |
|||
are at the '''same''' position. Otherwise later on we might not be |
|||
able to connect the geometric parts to a topology! |
|||
So we create first the points: |
|||
Así que primero creamos los puntos: |
|||
<syntaxhighlight> |
|||
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) |
|||
</syntaxhighlight> |
|||
==== |
==== Arc ==== |
||
[[Image:Circel.png|right|Circle]] |
[[Image:Circel.png|right|Circle]] |
||
Para crear un arco de circunferencia crearemos puntos de ayuda y crearemos el arco a través de tres puntos: |
|||
To create an arc of circle we make a helper point and create the arc of |
|||
VC1 = Base.Vector(-10,0,0) |
|||
circle through three points: |
|||
C1 = Part.Arc(V1,VC1,V4) |
|||
<syntaxhighlight> |
|||
# and the second one |
|||
VC1 = Base.Vector(-10,0,0) |
|||
C1 = Part.Arc(V1,VC1,V4) |
|||
# and the second one |
|||
VC2 = Base.Vector(40,0,0) |
|||
C2 = Part.Arc(V2,VC2,V3) |
|||
</syntaxhighlight> |
|||
==== Line ==== |
|||
==== Línea ==== |
|||
[[Image:Line.png|right|Line]] |
[[Image:Line.png|right|Line]] |
||
La línea puede crearse de forma muy simple a partir de los puntos: |
|||
The line can be created very simple out of the points: |
|||
L1 = Part.Line(V1,V2) |
|||
<syntaxhighlight> |
|||
# and the second one |
|||
L1 = Part.Line(V1,V2) |
|||
# and the second one |
|||
L2 = Part.Line(V4,V3) |
|||
==== Poniendo todo junto ==== |
|||
</syntaxhighlight> |
|||
==== Putting all together ==== |
|||
El último paso es poner los elementos base de la geometría juntos y formar una forma topológica: |
|||
The last step is to put the geometric base elements together |
|||
and bake a topological shape: |
|||
S1 = Part.Shape([C1,C2,L1,L2]) |
|||
<syntaxhighlight> |
|||
S1 = Part.Shape([C1,C2,L1,L2]) |
|||
==== Crear un prisma ==== |
|||
</syntaxhighlight> |
|||
==== Make a prism ==== |
|||
Ahora extruir el contorno en una dirección y crear una forma 3D real: |
|||
Now extrude the wire in a direction and make an actual 3D shape: |
|||
<syntaxhighlight> |
|||
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)) |
|||
</syntaxhighlight> |
|||
==== Mostrar todo ==== |
|||
==== Show it all ==== |
|||
<syntaxhighlight> |
|||
Part.show(P) |
|||
Part.show(P) |
|||
</syntaxhighlight> |
|||
== Creación de formas básicas == |
|||
== Creating basic shapes == |
|||
You can easily create basic topological objects with the "make...()" |
|||
Puedes crear fácilmente objetos topológicos simples con los métodos "make...()" del Módulo Parte: |
|||
methods from the Part Module: |
|||
<syntaxhighlight> |
|||
b = Part.makeBox(100,100,100) |
|||
b = Part.makeBox(100,100,100) |
|||
Part.show(b) |
|||
</syntaxhighlight> |
|||
Otros métodos make...() disponibles: |
|||
A couple of other make...() methods available: |
|||
* makeBox(l,w,h) -- construye una caja ubicada en p y apuntando en la dirección d con las dimensiones (l, w, h). |
|||
* '''makeBox(l,w,h)''': Makes a box located in p and pointing into the direction d with the dimensions (l,w,h) |
|||
* makeCircle(radius) -- Hace un círculo con un radio dado. |
|||
* '''makeCircle(radius)''': Makes a circle with a given radius |
|||
* makeCone(radius1,radius2,height) -- Hace un cono con un radio y altura dados. |
|||
* '''makeCone(radius1,radius2,height)''': Makes a cone with a given radii and height |
|||
* makeCylinder(radius,height) -- Hace un cilindro con un radio y altura dados. |
|||
* '''makeCylinder(radius,height)''': Makes a cylinder with a given radius and height. |
|||
* makeLine((x1,y1,z1),(x2,y2,z2)) -- Hace una línea entre 2 puntos |
|||
* '''makeLine((x1,y1,z1),(x2,y2,z2))''': Makes a line of two points |
|||
* makePlane(length,width) -- Hace un plano con longitud y anchura dados. |
|||
* '''makePlane(length,width)''': Makes a plane with length and width |
|||
* makePolygon(list) -- Hace un polígono con una lista de puntos |
|||
* '''makePolygon(list)''': Makes a polygon of a list of points |
|||
* makeSphere(radius) -- Hace una esfera con un radio dado. |
|||
* '''makeSphere(radius)''': Make a sphere with a given radius |
|||
* makeTorus(radius1,radius2) -- Hace un toro con sus radios dados. |
|||
* '''makeTorus(radius1,radius2)''': Makes a torus with a given radii |
|||
See the [[Part API]] page for a complete list of available methods of the Part module. |
|||
==== Importing the needed modules ==== |
==== Importing the needed modules ==== |
||
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: |
|||
<syntaxhighlight> |
|||
import Part |
|||
from FreeCAD import Base |
|||
</syntaxhighlight> |
|||
==== Creating a Vector ==== |
|||
[http://en.wikipedia.org/wiki/Euclidean_vector Vectors] are one of the most |
|||
important pieces of information when building shapes. They contain a 3 numbers |
|||
usually (but not necessarily always) the x, y and z cartesian coordinates. You |
|||
create a vector like this: |
|||
<syntaxhighlight> |
|||
myVector = Base.Vector(3,2,0) |
|||
</syntaxhighlight> |
|||
We just created a vector at coordinates x=3, y=2, z=0. In the Part module, |
|||
vectors are used everywhere. Part shapes also use another kind of point |
|||
representation, called Vertex, which is acually nothing else than a container |
|||
for a vector. You access the vector of a vertex like this: |
|||
<syntaxhighlight> |
|||
myVertex = myShape.Vertexes[0] |
|||
print myVertex.Point |
|||
> Vector (3, 2, 0) |
|||
</syntaxhighlight> |
|||
==== Creating an Edge ==== |
|||
An edge is nothing but a line with two vertexes: |
|||
<syntaxhighlight> |
|||
edge = Part.makeLine((0,0,0), (10,0,0)) |
|||
edge.Vertexes |
|||
> [<Vertex object at 01877430>, <Vertex object at 014888E0>] |
|||
</syntaxhighlight> |
|||
Note: You can also create an edge by passing two vectors: |
|||
<syntaxhighlight> |
|||
vec1 = Base.Vector(0,0,0) |
|||
vec2 = Base.Vector(10,0,0) |
|||
line = Part.Line(vec1,vec2) |
|||
edge = line.toShape() |
|||
</syntaxhighlight> |
|||
You can find the length and center of an edge like this: |
|||
<syntaxhighlight> |
|||
edge.Length |
|||
> 10.0 |
|||
edge.CenterOfMass |
|||
> Vector (5, 0, 0) |
|||
</syntaxhighlight> |
|||
==== Putting the shape on screen ==== |
|||
So far we created an edge object, but it doesn't appear anywhere on screen. |
|||
This is because we just manipulated python objects here. The FreeCAD 3D scene |
|||
only displays what you tell it to display. To do that, we use this simple |
|||
method: |
|||
<syntaxhighlight> |
|||
Part.show(edge) |
|||
</syntaxhighlight> |
|||
An object will be created in our FreeCAD document, and our "edge" shape |
|||
will be attributed to it. Use this whenever it's time to display your |
|||
creation on screen. |
|||
==== Creating a Wire ==== |
|||
Primero tenemos que importar el módulo de piezas así podremos utilizar su contenido en Python. |
|||
A wire is a multi-edge line and can be created from a list of edges |
|||
También importamos el módulo base desde dentro del módulo de FreeCAD: |
|||
or even a list of wires: |
|||
<syntaxhighlight> |
|||
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) |
|||
</syntaxhighlight> |
|||
Part.show(wire3) will display the 4 edges that compose our wire. Other |
|||
useful information can be easily retrieved: |
|||
<syntaxhighlight> |
|||
wire3.Length |
|||
> 40.0 |
|||
wire3.CenterOfMass |
|||
> Vector (5, 5, 0) |
|||
wire3.isClosed() |
|||
> True |
|||
wire2.isClosed() |
|||
> False |
|||
</syntaxhighlight> |
|||
==== Creating a Face ==== |
|||
Only faces created from closed wires will be valid. In this example, wire3 |
|||
is a closed wire but wire2 is not a closed wire (see above) |
|||
<syntaxhighlight> |
|||
face = Part.Face(wire3) |
|||
face.Area |
|||
> 99.999999999999972 |
|||
face.CenterOfMass |
|||
> Vector (5, 5, 0) |
|||
face.Length |
|||
> 40.0 |
|||
face.isValid() |
|||
> True |
|||
sface = Part.Face(wire2) |
|||
face.isValid() |
|||
> False |
|||
</syntaxhighlight> |
|||
Only faces will have an area, not wires nor edges. |
|||
==== Creating a Circle ==== |
|||
import Part |
|||
A circle can be created as simply as this: |
|||
from FreeCAD import Base |
|||
<syntaxhighlight> |
|||
circle = Part.makeCircle(10) |
|||
circle.Curve |
|||
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1)) |
|||
</syntaxhighlight> |
|||
If you want to create it at certain position and with certain direction: |
|||
<syntaxhighlight> |
|||
ccircle = Part.makeCircle(10, Base.Vector(10,0,0), Base.Vector(1,0,0)) |
|||
ccircle.Curve |
|||
> Circle (Radius : 10, Position : (10, 0, 0), Direction : (1, 0, 0)) |
|||
</syntaxhighlight> |
|||
ccircle will be created at distance 10 from origin on x and will be facing |
|||
towards x axis. Note: makeCircle only accepts Base.Vector() for position |
|||
and normal but not tuples. You can also create part of the circle by giving |
|||
start angle and end angle as: |
|||
<syntaxhighlight> |
|||
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) |
|||
</syntaxhighlight> |
|||
Both arc1 and arc2 jointly will make a circle. Angles should be provided in |
|||
degrees, if you have radians simply convert them using formula: |
|||
degrees = radians * 180/PI or using python's math module (after doing import |
|||
math, of course): |
|||
<syntaxhighlight> |
|||
degrees = math.degrees(radians) |
|||
</syntaxhighlight> |
|||
==== Creating an Arc along points ==== |
|||
Unfortunately there is no makeArc function but we have Part.Arc function to |
|||
create an arc along three points. Basically it can be supposed as an arc |
|||
joining start point and end point along the middle point. Part.Arc creates |
|||
an arc object on which .toShape() has to be called to get the edge object, |
|||
the same way as when using Part.Line instead of Part.makeLine. |
|||
<syntaxhighlight> |
|||
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() |
|||
</syntaxhighlight> |
|||
Arc only accepts Base.Vector() for points but not tuples. arc_edge is what |
|||
we want which we can display using Part.show(arc_edge). You can also obtain |
|||
an arc by using a portion of a circle: |
|||
<syntaxhighlight> |
|||
from math import pi |
|||
circle = Part.Circle(Base.Vector(0,0,0),Base.Vector(0,0,1),10) |
|||
arc = Part.Arc(c,0,pi) |
|||
</syntaxhighlight> |
|||
Arcs are valid edges, like lines. So they can be used in wires too. |
|||
==== |
==== Creating a polygon ==== |
||
A polygon is simply a wire with multiple straight edges. The makePolygon |
|||
function takes a list of points and creates a wire along those points: |
|||
<syntaxhighlight> |
|||
lshape_wire = Part.makePolygon([Base.Vector(0,5,0),Base.Vector(0,0,0),Base.Vector(5,0,0)]) |
|||
</syntaxhighlight> |
|||
==== Creating a Bezier curve ==== |
|||
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.) |
|||
<syntaxhighlight> |
|||
def makeBCurveEdge(Points): |
|||
geomCurve = Part.BezierCurve() |
|||
geomCurve.setPoles(Points) |
|||
edge = Part.Edge(geomCurve) |
|||
return(edge) |
|||
</syntaxhighlight> |
|||
==== Creating a Plane ==== |
|||
A Plane is simply a flat rectangular surface. The method used to create one is |
|||
this: '''makePlane(length,width,[start_pnt,dir_normal])'''. By default |
|||
start_pnt = Vector(0,0,0) and dir_normal = Vector(0,0,1). Using dir_normal = Vector(0,0,1) |
|||
will create the plane facing z axis, while dir_normal = Vector(1,0,0) will create the |
|||
plane facing x axis: |
|||
<syntaxhighlight> |
|||
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) |
|||
</syntaxhighlight> |
|||
BoundBox is a cuboid enclosing the plane with a diagonal starting at |
|||
(3,0,0) and ending at (5,0,2). Here the BoundBox thickness in y axis is zero, |
|||
since our shape is totally flat. |
|||
Note: makePlane only accepts Base.Vector() for start_pnt and dir_normal but not tuples |
|||
Los [http://en.wikipedia.org/wiki/Euclidean_vector Vectores] son una de las piezas de información más importantes cuando se construyen formas. Contienen 3 números normalmente (pero no necesariamente siempre) las coordenadas cartesianas X, Y y Z. Puedes crear un vector así: |
|||
==== Creating an ellipse ==== |
|||
myVector = Base.Vector(3,2,0) |
|||
To create an ellipse there are several ways: |
|||
<syntaxhighlight> |
|||
Part.Ellipse() |
|||
</syntaxhighlight> |
|||
Creates an ellipse with major radius 2 and minor radius 1 with the center in (0,0,0) |
|||
<syntaxhighlight> |
|||
Part.Ellipse(Ellipse) |
|||
</syntaxhighlight> |
|||
Create a copy of the given ellipse |
|||
<syntaxhighlight> |
|||
Part.Ellipse(S1,S2,Center) |
|||
</syntaxhighlight> |
|||
Creates an ellipse centered on the point Center, where the plane of the |
|||
ellipse is defined by Center, S1 and S2, its major axis is defined by |
|||
Center and S1, its major radius is the distance between Center and S1, |
|||
and its minor radius is the distance between S2 and the major axis. |
|||
<syntaxhighlight> |
|||
Part.Ellipse(Center,MajorRadius,MinorRadius) |
|||
</syntaxhighlight> |
|||
Creates an ellipse with major and minor radii MajorRadius and MinorRadius, |
|||
and located in the plane defined by Center and the normal (0,0,1) |
|||
<syntaxhighlight> |
|||
eli = Part.Ellipse(Base.Vector(10,0,0),Base.Vector(0,5,0),Base.Vector(0,0,0)) |
|||
Part.show(eli.toShape()) |
|||
</syntaxhighlight> |
|||
In the above code we have passed S1, S2 and center. Similarly to Arc, |
|||
Ellipse also creates an ellipse object but not edge, so we need to |
|||
convert it into edge using toShape() to display. |
|||
Note: Arc only accepts Base.Vector() for points but not tuples |
|||
Simplemente creamos un vector en las coordenadas X=3, Y=2, Z=0. En el módulo de pieza, los vectores se utilizan en todas partes. Las formas de las piezas también utilizan otro tipo de representaciones de punto, llamada Vértice, el cual en realidad no es más que un contenedor para un vector. Puedes acceder al vector de un vértice así: |
|||
<syntaxhighlight> |
|||
eli = Part.Ellipse(Base.Vector(0,0,0),10,5) |
|||
Part.show(eli.toShape()) |
|||
</syntaxhighlight> |
|||
for the above Ellipse constructor we have passed center, MajorRadius and MinorRadius |
|||
==== Creating a Torus ==== |
|||
myVertex = myShape.Vertexes[0] |
|||
Using the method '''makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle])'''. By |
|||
print myVertex.Point |
|||
default pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle2=360 and angle=360. |
|||
> Vector (3, 2, 0) |
|||
Consider a torus as small circle sweeping along a big circle. Radius1 is the |
|||
radius of big cirlce, radius2 is the radius of small circle, pnt is the center |
|||
of torus and dir is the normal direction. angle1 and angle2 are angles in |
|||
radians for the small circle, the last parameter angle is to make a section of |
|||
the torus: |
|||
<syntaxhighlight> |
|||
torus = Part.makeTorus(10, 2) |
|||
</syntaxhighlight> |
|||
The above code will create a torus with diameter 20(radius 10) and thickness 4 |
|||
(small cirlce radius 2) |
|||
<syntaxhighlight> |
|||
tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,180) |
|||
</syntaxhighlight> |
|||
The above code will create a slice of the torus |
|||
<syntaxhighlight> |
|||
tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,360,180) |
|||
</syntaxhighlight> |
|||
The above code will create a semi torus, only the last parameter is changed |
|||
i.e the angle and remaining angles are defaults. Giving the angle 180 will |
|||
create the torus from 0 to 180, that is, a half torus. |
|||
==== |
==== Creating a box or cuboid ==== |
||
Using '''makeBox(length,width,height,[pnt,dir])'''. |
|||
By default pnt=Vector(0,0,0) and dir=Vector(0,0,1) |
|||
Un borde no es otra cosa mas que una linea entre dos vértices: |
|||
<syntaxhighlight> |
|||
box = Part.makeBox(10,10,10) |
|||
len(box.Vertexes) |
|||
> 8 |
|||
>[<Vertex object at 01877430>, <Vertex object at 014888E0>] |
|||
</syntaxhighlight> |
|||
==== Creating a Sphere ==== |
|||
Nota: También puedes crear una arista pasándole dos vértices. |
|||
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. |
|||
vec1 = Base.Vector(0,0,0) |
|||
angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3 |
|||
vec2 = Base.Vector(10,0,0) |
|||
is the sphere diameter itself. |
|||
line = Part.Line(vec1,vec2) |
|||
<syntaxhighlight> |
|||
edge = line.toShape() |
|||
sphere = Part.makeSphere(10) |
|||
hemisphere = Part.makeSphere(10,Base.Vector(0,0,0),Base.Vector(0,0,1),-90,90,180) |
|||
Se puede determinar la longitud y el centro de un borde así: |
|||
</syntaxhighlight> |
|||
==== Creating a Cylinder ==== |
|||
edge.Length |
|||
Using '''makeCylinder(radius,height,[pnt,dir,angle])'''. By default |
|||
>10.0 |
|||
pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360 |
|||
edge.CenterOfMass |
|||
<syntaxhighlight> |
|||
>Vector (5, 0, 0) |
|||
cylinder = Part.makeCylinder(5,20) |
|||
partCylinder = Part.makeCylinder(5,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180) |
|||
==== Poniendo la forma en la pantalla ==== |
|||
</syntaxhighlight> |
|||
==== Creating a Cone ==== |
|||
Hemos creado un objeto arista, pero no aparece en ninguna parte de la pantalla. |
|||
Using '''makeCone(radius1,radius2,height,[pnt,dir,angle])'''. By default |
|||
Esto es porque simplemente manejamos objetos de Python aquí. La escena 3D de FreeCAD sólo muestra lo que le digas que se muestre. Para hacerlo, utilizamos este simple método: |
|||
pnt=Vector(0,0,0), dir=Vector(0,0,1) and angle=360 |
|||
<syntaxhighlight> |
|||
Part.show(edge) |
|||
cone = Part.makeCone(10,0,20) |
|||
semicone = Part.makeCone(10,0,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180) |
|||
Un objeto se creará en nuestro documento de FreeCAD, y nuestra forma "edge" será atribuido a él. Utiliza esto si es momento para mostrar tu creación en la pantalla. |
|||
</syntaxhighlight> |
|||
== Modifying shapes == |
|||
==== Creación de un contorno ==== |
|||
There are several ways to modify shapes. Some are simple transformation operations |
|||
Un contorno es una línea de múltiples aristas y se puede crear a partir de una lista de aristas, o incluso de una lista de contornos: |
|||
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) mostrará las 4 aristas que componen nuestro contorno. Otra información útil se puede recuperar fácilmente: |
|||
wire3.Length |
|||
> 40.0 |
|||
wire3.CenterOfMass |
|||
> Vector (5, 5, 0) |
|||
wire3.isClosed() |
|||
> True |
|||
wire2.isClosed() |
|||
> False |
|||
==== Creación de una cara ==== |
|||
Sólo serán válidas las caras creadas a partir de contornos cerrados. En este ejemplo, wire3 es un contorno cerrado pero wire2 no es un contorno cerrado (mira más arriba) |
|||
face = Part.Face(wire3) |
|||
face.Area |
|||
> 99.999999999999972 |
|||
face.CenterOfMass |
|||
> Vector (5, 5, 0) |
|||
face.Length |
|||
> 40.0 |
|||
face.isValid() |
|||
> True |
|||
sface = Part.Face(wire2) |
|||
face.isValid() |
|||
> False |
|||
Sólo las caras tendrán un área, ni los contornos ni las aristas. |
|||
==== Creación de una circunferencia ==== |
|||
Una circunferencia se puede crear de forma tan simple como esta: |
|||
circle = Part.makeCircle(10) |
|||
circle.Curve |
|||
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1)) |
|||
Si deseas crearlo en cierta posición y con cierta dirección: |
|||
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 se creará a una distancia de 10 en el eje x desde el origen, y estará orientado hacia el eje x. Nota: makeCircle sólo acepta Base.Vector() para posición y normal, pero no admite tuplas. Tambien puedes crear una parte de una circunferencia dando su ángulo de inicio y fin, así: |
|||
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) |
|||
Juntando arc1 y arc2 obtendremos una circunferencia. Los ángulos deberán indicarse en grados, si los tienes en radianes simplemente conviertelos según la fórmula: |
|||
degrees = radians * 180/PI |
|||
o usando el módulo Python de matemáticas (después de importarlo, obviamente): |
|||
degrees = math.degrees(radians) |
|||
==== Creación de un arco por varios puntos ==== |
|||
Desafortunadamente no hay ninguna función makeArc pero tenemos la función Part.Arc para crear un arco a lo largo de tres puntos. Básicamente se puede suponer como un arco de unión entre el punto de partida y el punto final, pasando por el punto medio. Part.Arc crea un objeto arco en el que .toShape() tiene que ser llamado para obtener el objeto arista, del mismo modo como utilizamos Part.Line en lugar de 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() |
|||
Arc solo acepta puntos como Base.Vector() no acepta tuplas. arc_edge es lo que queremos que podemos mostrar utilizando Part.show(arc_edge). También puedes obtener un arco utilizando una porción de una circunferencia: |
|||
arc_edge es lo que queríamos conseguir, y podemos visualizar utilizando Part.show (arc_edge). |
|||
Si desea una pequeña parte de un círculo como un arco, también es posible: |
|||
from math import pi |
|||
circle = Part.Circle(Base.Vector(0,0,0),Base.Vector(0,0,1),10) |
|||
arc = Part.Arc(c,0,pi) |
|||
Los arcos son aristas válidas, como las líneas. Así que también pueden utilizarse en los contornos. |
|||
==== Creación de un polígono ==== |
|||
Un polígono es simplemente un contorno con múltiples aristas rectas. La función makePolygon toma una lista de puntos y crea un contorno a través de dichos puntos: |
|||
lshape_wire = Part.makePolygon([Base.Vector(0,5,0),Base.Vector(0,0,0),Base.Vector(5,0,0)]) |
|||
==== Creación de un plano ==== |
|||
Un plano es simplemente una superficie rectangular plana. El método utilizado para crear uno es este: '''makePlane(length,width,[start_pnt,dir_normal])'''. Por defecto start_pnt = Vector(0,0,0) y dir_normal = Vector(0,0,1). Utilizando dir_normal = Vector(0,0,1) crearemos el plano orientado hacia el eje Z, mientras que con dir_normal = Vector(1,0,0) crearemos el plano orientado hacia el eje X: |
|||
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 es un prisma encerrando el plano con una diagonal empezando en (3,0,0) y terminando en (5,0,2). Aquí el espesor de BoundBox en el eje Y es cero, ya que nuestra forma es totalmente plana. |
|||
Nota: makePlane sólo acepta Base.Vector() para start_pnt y dir_normal pero no tuplas |
|||
==== Creación de una elipse ==== |
|||
Para crear una elipse existen varios métodos: |
|||
Part.Ellipse() |
|||
Crea una elipse cuyo radio mayor es 2 y el radio menor 1 con centro en el (0,0,0) |
|||
Part.Ellipse(Ellipse) |
|||
Crea una copia de la elipse dada |
|||
Part.Ellipse(S1,S2,Center) |
|||
Crea una elipse centrada en el punto Center, donde el plano de la elipse está definido por Center, S1 y S2, su eje mayor está definido por Center y S1, su radio mayor es la distancia entre Center y S1, |
|||
y su radio menor es la distancia entre S2 y el eje mayor. |
|||
Part.Ellipse(Center,MajorRadius,MinorRadius) |
|||
Crea una elipse con radios mayor y menor MajorRadius y MinorRadius respectivamente, y ubicada en el plano definido por Center y la normal (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()) |
|||
En el código de arriba hemos pasado S1, S2 y center. De forma similar a Arc, Ellipse también crea un objeto elipse pero no una arista, así que tenemos que convertirlo en una arista utilizando toShape() para mostrarlo. |
|||
Nota: Arc sólo acepta Base.Vector() para puntos pero no tuplas |
|||
eli = Part.Ellipse(Base.Vector(0,0,0),10,5) |
|||
Part.show(eli.toShape()) |
|||
para el constructor de la elipse de arriba hemos pasado el centro, MajorRadius y MinorRadius |
|||
==== Creación de un toro ==== |
|||
Utilizando el método '''makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle])'''. Por defecto pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle2=360 y angle=360. |
|||
Considera un toro como un pequeño circulo barrido a lo largo de una circunferencia grande. Radius1 es el radio de la circunferencia grande, radius2 es el radio del círculo pequeño, pnt es el centro del toro y dir es la dirección normal. angle1 y angle2 son ángulos en radianes para el círculo pequeño, el último parámetro angle es para hacer una sección del toro: |
|||
torus = Part.makeTorus(10, 2) |
|||
El código de arriba creará un toro con diámetro 20 (radio 10) y espesor 4 (radio del círculo pequeño 2) |
|||
tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,180) |
|||
El código de arriba creará una sección del toro |
|||
tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,360,180) |
|||
El código de arriba creará un semi toro, sólo el último parámetro se ha cambiado, dando el valor 180 creará el toro desde 0 hasta 180, eso es, medio toro. |
|||
==== Creación de un cubo o prisma ==== |
|||
Utilizando '''makeBox(length,width,height,[pnt,dir])'''. Por defecto pnt=Vector(0,0,0) y dir=Vector(0,0,1) |
|||
box = Part.makeBox(10,10,10) |
|||
len(box.Vertexes) |
|||
> 8 |
|||
==== Creación de una esfera ==== |
|||
Utilizando '''makeSphere(radius,[pnt, dir, angle1,angle2,angle3])'''. Por defecto pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=-90, angle2=90 y angle3=360. angle1 y angle2 son el punto vertical mínimo y máximo de la esfera, angle3 es el diámetro de la esfera. |
|||
sphere = Part.makeSphere(10) |
|||
hemisphere = Part.makeSphere(10,Base.Vector(0,0,0),Base.Vector(0,0,1),-90,90,180) |
|||
==== Creación de un cilindro ==== |
|||
Utilizando '''makeCylinder(radius,height,[pnt,dir,angle])'''. Por defecto pnt=Vector(0,0,0),dir=Vector(0,0,1) y angle=360 |
|||
cylinder = Part.makeCylinder(5,20) |
|||
partCylinder = Part.makeCylinder(5,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180) |
|||
==== Creación de un cono ==== |
|||
Utilizando '''makeCone(radius1,radius2,height,[pnt,dir,angle])'''. Por defecto pnt=Vector(0,0,0), dir=Vector(0,0,1) y 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) |
|||
== Modificando formas == |
|||
Existen diversos métodos para modificar formas. Algunas son simples operaciones de transformación como mover o rotar formas, otras son más complejas, como la unión y diferencia de una forma y otra. are simple transformation operations |
|||
such as moving or rotating shapes, other are more complex, such as unioning and |
such as moving or rotating shapes, other are more complex, such as unioning and |
||
subtracting one shape from another. |
subtracting one shape from another. Be aware that |
||
=== Operaciones de transformación === |
|||
==== Traslación de una forma ==== |
|||
Traslación es el acto de mover una forma de una situación a otra. |
|||
Cualquier forma (aristas, caras, cubos, etc...) se puede trasladar del mismo modo: |
|||
myShape = Part.makeBox(2,2,2) |
|||
myShape.translate(Base.Vector(2,0,0)) |
|||
Esto moverá nuestra forma "myShape" 2 unidades en la dirección del eje X. |
|||
==== Rotación de una forma ==== |
|||
Para rotar una forma, necesitas especificar el centro de rotación, el eje, y el ángulo de rotación: |
|||
myShape.rotate(Vector(0,0,0),Vector(0,0,1),180) |
|||
El código de arriba rotará la forma 180 grados alrededor del eje Z. |
|||
==== Transformaciones genéricas con matrices ==== |
|||
Una matriz es un modo muy conveniente de almacenar transformaciones en el mundo 3D. En una simple matriz, puedes establecer traslaciones, rotaciones y valores de escala a ser aplicados a un objeto. Por ejemplo: |
|||
myMat = Base.Matrix() |
|||
myMat.move(Base.Vector(2,0,0)) |
|||
myMat.rotateZ(math.pi/2) |
|||
=== Transform operations === |
|||
Nota: Las matrices de FreeCAD funcionan en radianes. También, casi todas las operaciones de matrices que toman un vector pueden tomar 3 números, así estas dos líneas hacen lo mismo: |
|||
==== Translating a shape ==== |
|||
myMat.move(2,0,0) |
|||
Translating is the act of moving a shape from one place to another. |
|||
myMat.move(Base.Vector(2,0,0)) |
|||
Any shape (edge, face, cube, etc...) can be translated the same way: |
|||
<syntaxhighlight> |
|||
myShape = Part.makeBox(2,2,2) |
|||
myShape.translate(Base.Vector(2,0,0)) |
|||
</syntaxhighlight> |
|||
This will move our shape "myShape" 2 units in the x direction. |
|||
==== Rotating a shape ==== |
|||
Cuando nuestra matriz es establecida, podemos aplicarla a nuestra forma. FreeCAD proporciona 2 métodos para hacerlo: transformShape() y transformGeometry(). La diferencia es que con el primero, estas seguro de que no ocurrirá ninguna deformación (mira "escalando una forma" más abajo). Podemos aplicar nuestra transformación así: |
|||
To rotate a shape, you need to specify the rotation center, the axis, |
|||
and the rotation angle: |
|||
<syntaxhighlight> |
|||
myShape.rotate(Vector(0,0,0),Vector(0,0,1),180) |
|||
</syntaxhighlight> |
|||
The above code will rotate the shape 180 degrees around the Z Axis. |
|||
==== Generic transformations with matrixes ==== |
|||
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: |
|||
<syntaxhighlight> |
|||
myMat = Base.Matrix() |
|||
myMat.move(Base.Vector(2,0,0)) |
|||
myMat.rotateZ(math.pi/2) |
|||
</syntaxhighlight> |
|||
Note: FreeCAD matrixes work in radians. Also, almost all matrix operations |
|||
that take a vector can also take 3 numbers, so those 2 lines do the same thing: |
|||
<syntaxhighlight> |
|||
myMat.move(2,0,0) |
|||
myMat.move(Base.Vector(2,0,0)) |
|||
</syntaxhighlight> |
|||
When our matrix is set, we can apply it to our shape. FreeCAD provides 2 |
|||
methods to do that: transformShape() and transformGeometry(). The difference |
|||
is that with the first one, you are sure that no deformations will occur (see |
|||
"scaling a shape" below). So we can apply our transformation like this: |
|||
<syntaxhighlight> |
|||
myShape.trasformShape(myMat) |
myShape.trasformShape(myMat) |
||
</syntaxhighlight> |
|||
or |
|||
<syntaxhighlight> |
|||
myShape.transformGeometry(myMat) |
|||
</syntaxhighlight> |
|||
==== Scaling 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 differenty. For scaling, we |
|||
can't use the transformShape, we must use transformGeometry(): |
|||
<syntaxhighlight> |
|||
myMat = Base.Matrix() |
|||
myMat.scale(2,1,1) |
|||
myShape=myShape.transformGeometry(myMat) |
|||
</syntaxhighlight> |
|||
=== Boolean Operations === |
|||
==== Subtraction ==== |
|||
o |
|||
Subtracting a shape from another one is called "cut" in OCC/FreeCAD jargon |
|||
and is done like this: |
|||
<syntaxhighlight> |
|||
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) |
|||
</syntaxhighlight> |
|||
==== Intersection ==== |
|||
The same way, the intersection between 2 shapes is called "common" and is done |
|||
this way: |
|||
<syntaxhighlight> |
|||
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) |
|||
</syntaxhighlight> |
|||
==== Union ==== |
|||
Union is called "fuse" and works the same way: |
|||
<syntaxhighlight> |
|||
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) |
|||
</syntaxhighlight> |
|||
==== Section ==== |
|||
A Section is the intersection between a solid shape and a plane shape. |
|||
It will return an intersection curve, a compound with edges |
|||
<syntaxhighlight> |
|||
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>] |
|||
</syntaxhighlight> |
|||
==== Extrusion ==== |
|||
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": |
|||
<syntaxhighlight> |
|||
circle = Part.makeCircle(10) |
|||
tube = circle.extrude(Base.Vector(0,0,2)) |
|||
</syntaxhighlight> |
|||
If your circle is hollow, you will obtain a hollow tube. If your circle is actually |
|||
a disc, with a filled face, you will obtain a solid cylinder: |
|||
<syntaxhighlight> |
|||
wire = Part.Wire(circle) |
|||
disc = Part.makeFace(wire) |
|||
cylinder = disc.extrude(Base.Vector(0,0,2)) |
|||
</syntaxhighlight> |
|||
== Exploring shapes == |
|||
You can easily explore the topological data structure: |
|||
<syntaxhighlight> |
|||
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 |
|||
</syntaxhighlight> |
|||
By typing the lines above in the python interpreter, you will gain a good |
|||
understanding of the structure of Part objects. Here, our makeBox() command |
|||
created a solid shape. This solid, like all Part solids, contains faces. |
|||
Faces always contain wires, which are lists of edges that border the face. |
|||
Each face has at least one closed wire (it can have more if the face has a hole). |
|||
In the wire, we can look at each edge separately, and inside each edge, we can |
|||
see the vertexes. Straight edges have only two vertexes, obviously. |
|||
=== Edge analysis === |
|||
myShape.transformGeometry(myMat) |
|||
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. |
|||
==== Escalando una forma ==== |
|||
That means you can walk an edge/curve by its length: |
|||
<syntaxhighlight> |
|||
Escalando una forma es una operación más peligrosa porque, a diferencia de la traslación o rotación, un escalado no uniforme (con diferentes valores para los ejes X,Y y Z) puede modificar la estructura de la forma. Por ejemplo, escalando una circunferencia con un valor horizontal superior al vertical la transformará en una elipse, que se comporta matemáticamente de forma muy diferente. Para el escalado, no podemos utilizar transformShape, tenemos que usar transformGeometry(): |
|||
import Part |
|||
box = Part.makeBox(100,100,100) |
|||
myMat = Base.Matrix() |
|||
anEdge = box.Edges[0] |
|||
myMat.scale(2,1,1) |
|||
print anEdge.Length |
|||
myShape.transformGeometry(myMat) |
|||
</syntaxhighlight> |
|||
Now you can access a lot of properties of the edge by using the length as a |
|||
=== Operaciones Booleanas === |
|||
position. That means if the edge is 100mm long the start position is 0 and |
|||
the end position 100. |
|||
==== Diferencia ==== |
|||
<syntaxhighlight> |
|||
anEdge.tangentAt(0.0) # tangent direction at the beginning |
|||
La diferencia de una forma con otra se llama "corte" en el argot de OCC/FreeCAD y se hace así: |
|||
anEdge.valueAt(0.0) # Point at the beginning |
|||
anEdge.valueAt(100.0) # Point at the end of the edge |
|||
cylinder = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0)) |
|||
anEdge.derivative1At(50.0) # first derivative of the curve in the middle |
|||
sphere = Part.makeSphere(5,Base.Vector(5,0,0)) |
|||
anEdge.derivative2At(50.0) # second derivative of the curve in the middle |
|||
diff = cylinder.cut(sphere) |
|||
anEdge.derivative3At(50.0) # third derivative of the curve in the middle |
|||
anEdge.centerOfCurvatureAt(50) # center of the curvature for that position |
|||
==== Intersección ==== |
|||
anEdge.curvatureAt(50.0) # the curvature |
|||
anEdge.normalAt(50) # normal vector at that position (if defined) |
|||
del mismo modo, la intersección entre dos formas es denominada "común" y se hace de este modo: |
|||
</syntaxhighlight> |
|||
=== Using the selection === |
|||
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0)) |
|||
Here we see now how we can use the selection the user did in the viewer. |
|||
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1)) |
|||
First of all we create a box and shows it in the viewer |
|||
common = cylinder1.common(cylinder2) |
|||
<syntaxhighlight> |
|||
import Part |
|||
==== Unión ==== |
|||
Part.show(Part.makeBox(100,100,100)) |
|||
Gui.SendMsgToActiveView("ViewFit") |
|||
La unión se llama "fusión" y funciona del mismo modo: |
|||
</syntaxhighlight> |
|||
Select now some faces or edges. With this script you can |
|||
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0)) |
|||
iterate all selected objects and their sub elements: |
|||
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1)) |
|||
<syntaxhighlight> |
|||
fuse = cylinder1.fuse(cylinder2) |
|||
for o in Gui.Selection.getSelectionEx(): |
|||
print o.ObjectName |
|||
==== Sección ==== |
|||
for s in o.SubElementNames: |
|||
print "name: ",s |
|||
Una sección es la intersección entre una forma de un sólido y una forma de un plano. |
|||
for s in o.SubObjects: |
|||
Devolverá una curva de intersección, un componente con aristas |
|||
print "object: ",s |
|||
</syntaxhighlight> |
|||
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0)) |
|||
Select some edges and this script will calculate the length: |
|||
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1)) |
|||
<syntaxhighlight> |
|||
section = cylinder1.section(cylinder2) |
|||
length = 0.0 |
|||
section.Wires |
|||
for o in Gui.Selection.getSelectionEx(): |
|||
> [] |
|||
for s in o.SubObjects: |
|||
section.Edges |
|||
length += s.Length |
|||
> [<Edge object at 0D87CFE8>, <Edge object at 019564F8>, <Edge object at 0D998458>, |
|||
print "Length of the selected edges:" ,length |
|||
<Edge object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>, |
|||
</syntaxhighlight> |
|||
<Edge object at 0D8F4BB0>] |
|||
== Complete example: The OCC bottle == |
|||
A typical example found on the |
|||
==== Extrusión ==== |
|||
[http://www.opencascade.org/org/gettingstarted/appli/ OpenCasCade Getting Started Page] |
|||
is how to build a bottle. This is a good exercise for FreeCAD too. In fact, |
|||
Extrusión es el acto de "empujar" una forma plana en determinada dirección resultando en un cuerpo sólido. Piensa en una círculo convirtiéndose en un tubo: |
|||
you can follow our example below and the OCC page simultaneously, you will |
|||
understand well how OCC structures are implemented in FreeCAD. The complete script |
|||
circle = Part.makeCircle(10) |
|||
below is also included in FreeCAD installation (inside the Mod/Part folder) and |
|||
tube = circle.extrude(Base.Vector(0,0,2)) |
|||
can be called from the python interpreter by typing: |
|||
<syntaxhighlight> |
|||
Si tu círculo está hueco, obtendrás un tubo hueco. Si no es hueco, obtendrás un cilindro sólido: |
|||
import Part |
|||
import MakeBottle |
|||
wire = Part.Wire(circle) |
|||
bottle = MakeBottle.makeBottle() |
|||
disc = Part.makeFace(wire) |
|||
Part.show(bottle) |
|||
cylinder = disc.extrude(Base.Vector(0,0,2)) |
|||
</syntaxhighlight> |
|||
== |
=== The complete script === |
||
Here is the complete MakeBottle script: |
|||
<syntaxhighlight> |
|||
Puedes explorar fácilmente la estructura de datos topológicos: |
|||
import Part, FreeCAD, math |
|||
from FreeCAD import Base |
|||
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 |
|||
Escribiendo las líneas de arriba en el interprete de Python, conseguirás una buena comprensión de la estructura de los objetos de piezas. Aquí, nuestro comando makeBox() crea una forma sólida. Este sólido, como todos los sólidos de piezas, contiene caras. Las caras siempre contienen contornos, que son listas de aristas que bordean la cara. Cada cara tiene al menos un contorno cerrado (puede tener más si la cara tiene huecos). En el contorno, podemos mirar en cada arista de forma separada, y dentro de cada arista, podemos ver los vértices. Las aristas rectas tienen sólo dos vértices, obviamente. |
|||
=== Análisis de aristas === |
|||
En el caso de una arista con una curva arbitraria, es más probable que quieras hacer una discretización. En FreeCAD las aristas son parametrizadas por sus longitudes. Eso significa que puedes recorrer una arista/curva por su longitud: |
|||
import Part |
|||
box = Part.makeBox(100,100,100) |
|||
anEdge = box.Edges[0] |
|||
print anEdge.Length |
|||
Ahora puedes acceder a un montón de propiedades de la arista utilizando la longitud como una posición. Eso significa que si la arista es de 100mm de longitud el punto inicial es y la posición final es 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) |
|||
=== Utilizando la selección === |
|||
Aquí vemos ahora cómo podemos utilizar la selección que el usuario hizo en la vista. |
|||
Antes de nada creamos un cubo y lo mostramos en la vista |
|||
import Part |
|||
Part.show(Part.makeBox(100,100,100)) |
|||
Gui.SendMsgToActiveView("ViewFit") |
|||
Selecciona ahora algunas caras o aristas. Con este archivo de guión puedes iterar todos los objetos seleccionados y sus subelementos: |
|||
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 |
|||
Selecciona algunas aristas y este archivo de guión calculará la longitud: |
|||
length = 0.0 |
|||
for o in Gui.Selection.getSelectionEx(): |
|||
for s in o.SubObjects: |
|||
length += s.Length |
|||
print "Length of the selected edges:" ,length |
|||
== Examen completo: La botella OCC == |
|||
Un ejemplo típico encontrado en la [http://www.opencascade.org/org/gettingstarted/appli/ página de primeros pasos de OpenCasCade] es cómo construir una botella. Este es un buen ejercicio también para FreeCAD. En realidad, puedes seguir nuestro ejemplo de abajo y la página de OCC simultáneamente, comprenderás bien cómo están implementadas las estructuras de OCC en FreeCAD. El archivo de guión completo de abajo está también incluido en la instalación de FreeCAD (dentro del directorio Mod/Part) y puede llamarse desde el interprete de Python escribiendo: |
|||
import Part |
|||
import MakeBottle |
|||
bottle = MakeBottle.makeBottle() |
|||
Part.show(bottle) |
|||
=== El archivo de guión completo === |
|||
Aquí está el archivo de guión completo MakeBottle: |
|||
import Part, FreeCAD, math |
|||
from FreeCAD import Base |
|||
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0): |
|||
aPnt1=Base.Vector(-myWidth/2.,0,0) |
|||
aPnt2=Base.Vector(-myWidth/2.,-myThickness/4.,0) |
|||
aPnt3=Base.Vector(0,-myThickness/2.,0) |
|||
aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0) |
|||
aPnt5=Base.Vector(myWidth/2.,0,0) |
|||
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4) |
|||
aSegment1=Part.Line(aPnt1,aPnt2) |
|||
aSegment2=Part.Line(aPnt4,aPnt5) |
|||
aEdge1=aSegment1.toShape() |
|||
aEdge2=aArcOfCircle.toShape() |
|||
aEdge3=aSegment2.toShape() |
|||
aWire=Part.Wire([aEdge1,aEdge2,aEdge3]) |
|||
aTrsf=Base.Matrix() |
|||
aTrsf.rotateZ(math.pi) # rotate around the z-axis |
|||
aMirroredWire=aWire.transformGeometry(aTrsf) |
|||
myWireProfile=Part.Wire([aWire,aMirroredWire]) |
|||
myFaceProfile=Part.Face(myWireProfile) |
|||
aPrismVec=Base.Vector(0,0,myHeight) |
|||
myBody=myFaceProfile.extrude(aPrismVec) |
|||
myBody=myBody.makeFillet(myThickness/12.0,myBody.Edges) |
|||
neckLocation=Base.Vector(0,0,myHeight) |
|||
neckNormal=Base.Vector(0,0,1) |
|||
myNeckRadius = myThickness / 4. |
|||
myNeckHeight = myHeight / 10 |
|||
myNeck = Part.makeCylinder(myNeckRadius,myNeckHeight,neckLocation,neckNormal) |
|||
myBody = myBody.fuse(myNeck) |
|||
faceToRemove = 0 |
|||
zMax = -1.0 |
|||
for xp in myBody.Faces: |
|||
try: |
|||
surf = xp.Surface |
|||
if type(surf) == Part.Plane: |
|||
z = surf.Position.z |
|||
if z > zMax: |
|||
zMax = z |
|||
faceToRemove = xp |
|||
except: |
|||
continue |
|||
myBody = myBody.makeThickness([faceToRemove],-myThickness/50 , 1.e-3) |
|||
return myBody |
|||
</syntaxhighlight> |
|||
=== Detailed explanation === |
|||
<syntaxhighlight> |
|||
import Part, FreeCAD, math |
|||
from FreeCAD import Base |
|||
</syntaxhighlight> |
|||
We will need,of course, the Part module, but also the FreeCAD.Base module, |
|||
which contains basic FreeCAD structures like vectors and matrixes. |
|||
<syntaxhighlight> |
|||
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0): |
|||
aPnt1=Base.Vector(-myWidth/2.,0,0) |
|||
aPnt2=Base.Vector(-myWidth/2.,-myThickness/4.,0) |
|||
aPnt3=Base.Vector(0,-myThickness/2.,0) |
|||
aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0) |
|||
aPnt5=Base.Vector(myWidth/2.,0,0) |
|||
</syntaxhighlight> |
|||
Here we define our makeBottle function. This function can be called without |
|||
arguments, like we did above, in which case default values for width, height, |
|||
and thickness will be used. Then, we define a couple of points that will be used |
|||
for building our base profile. |
|||
<syntaxhighlight> |
|||
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4) |
|||
aSegment1=Part.Line(aPnt1,aPnt2) |
|||
aSegment2=Part.Line(aPnt4,aPnt5) |
|||
</syntaxhighlight> |
|||
Here we actually define the geometry: an arc, made of 3 points, and two |
|||
line segments, made of 2 points. |
|||
<syntaxhighlight> |
|||
aEdge1=aSegment1.toShape() |
|||
aEdge2=aArcOfCircle.toShape() |
|||
aEdge3=aSegment2.toShape() |
|||
aWire=Part.Wire([aEdge1,aEdge2,aEdge3]) |
|||
</syntaxhighlight> |
|||
Remember the difference between geometry and shapes? Here we build |
|||
shapes out of our construction geometry. 3 edges (edges can be straight |
|||
or curved), then a wire made of those three edges. |
|||
<syntaxhighlight> |
|||
aTrsf=Base.Matrix() |
|||
aTrsf.rotateZ(math.pi) # rotate around the z-axis |
|||
aMirroredWire=aWire.transformGeometry(aTrsf) |
|||
myWireProfile=Part.Wire([aWire,aMirroredWire]) |
|||
</syntaxhighlight> |
|||
Until now we built only a half profile. Easier than building the whole profile |
|||
the same way, we can just mirror what we did, and glue both halfs together. |
|||
So we first create a matrix. A matrix is a very common way to apply transformations |
|||
to objects in the 3D world, since it can contain in one structure all basic |
|||
transformations that 3D objects can suffer (move, rotate and scale). Here, |
|||
after we create the matrix, we mirror it, and we create a copy of our wire |
|||
with that transformation matrix applied to it. We now have two wires, and |
|||
we can make a third wire out of them, since wires are actually lists of edges. |
|||
<syntaxhighlight> |
|||
myFaceProfile=Part.Face(myWireProfile) |
|||
aPrismVec=Base.Vector(0,0,myHeight) |
|||
myBody=myFaceProfile.extrude(aPrismVec) |
|||
myBody=myBody.makeFillet(myThickness/12.0,myBody.Edges) |
|||
</syntaxhighlight> |
|||
Now that we have a closed wire, it can be turned into a face. Once we have a face, |
|||
we can extrude it. Doing so, we actually made a solid. Then we apply a nice little |
|||
fillet to our object because we care about good design, don't we? |
|||
<syntaxhighlight> |
|||
neckLocation=Base.Vector(0,0,myHeight) |
|||
neckNormal=Base.Vector(0,0,1) |
|||
myNeckRadius = myThickness / 4. |
|||
myNeckHeight = myHeight / 10 |
|||
myNeck = Part.makeCylinder(myNeckRadius,myNeckHeight,neckLocation,neckNormal) |
|||
</syntaxhighlight> |
|||
Then, the body of our bottle is made, we still need to create a neck. So we |
|||
make a new solid, with a cylinder. |
|||
<syntaxhighlight> |
|||
myBody = myBody.fuse(myNeck) |
|||
</syntaxhighlight> |
|||
The fuse operation, which in other apps is sometimes called union, is very |
|||
powerful. It will take care of gluing what needs to be glued and remove parts that |
|||
need to be removed. |
|||
<syntaxhighlight> |
|||
return myBody |
|||
</syntaxhighlight> |
|||
Then, we return our Part solid as the result of our function. That Part solid, |
|||
like any other Part shape, can be attributed to an object in a FreeCAD document, with: |
|||
<syntaxhighlight> |
|||
myObject = FreeCAD.ActiveDocument.addObject("Part::Feature","myObject") |
|||
myObject.Shape = bottle |
|||
</syntaxhighlight> |
|||
or, more simple: |
|||
<syntaxhighlight> |
|||
Part.show(bottle) |
|||
</syntaxhighlight> |
|||
==Box pierced== |
|||
Here a complete example of building a box pierced. |
|||
The construction is done side by side and when the cube is finished, it is hollowed out of a cylinder through. |
|||
=== Explicación detallada === |
|||
<syntaxhighlight> |
|||
import Draft, Part, FreeCAD, math, PartGui, FreeCADGui, PyQt4 |
|||
from math import sqrt, pi, sin, cos, asin |
|||
from FreeCAD import Base |
|||
size = 10 |
|||
import Part, FreeCAD, math |
|||
poly = Part.makePolygon( [ (0,0,0), (size, 0, 0), (size, 0, size), (0, 0, size), (0, 0, 0)]) |
|||
from FreeCAD import Base |
|||
face1 = Part.Face(poly) |
|||
Necesitaremos, desde luego, el módulo de piezas, pero también el módulo FreeCAD.Base, que contiene estructuras básicas de FreeCAD como vectores y matrices. |
|||
face2 = Part.Face(poly) |
|||
face3 = Part.Face(poly) |
|||
face4 = Part.Face(poly) |
|||
face5 = Part.Face(poly) |
|||
face6 = Part.Face(poly) |
|||
myMat = FreeCAD.Matrix() |
|||
myMat.rotateZ(math.pi/2) |
|||
face2.transformShape(myMat) |
|||
face2.translate(FreeCAD.Vector(size, 0, 0)) |
|||
myMat.rotateZ(math.pi/2) |
|||
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0): |
|||
face3.transformShape(myMat) |
|||
aPnt1=Base.Vector(-myWidth/2.,0,0) |
|||
face3.translate(FreeCAD.Vector(size, size, 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) |
|||
myMat.rotateZ(math.pi/2) |
|||
Aquí definimos nuestra función makeBottle. Esta función se puede llamar sin argumentos, como hicimos arriba, en cuyo caso se utilizaran los valores por defecto para ancho, alto, y espesor. Luego, definimos un conjunto de puntos que serán utilizados para construir nuestro perfil base. |
|||
face4.transformShape(myMat) |
|||
face4.translate(FreeCAD.Vector(0, size, 0)) |
|||
myMat = FreeCAD.Matrix() |
|||
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4) |
|||
myMat.rotateX(-math.pi/2) |
|||
aSegment1=Part.Line(aPnt1,aPnt2) |
|||
face5.transformShape(myMat) |
|||
aSegment2=Part.Line(aPnt4,aPnt5) |
|||
face6.transformShape(myMat) |
|||
Aquí en realidad definimos la geometría: un arco, creado por 3 puntos, y dos segmentos de línea, creados por 2 puntos. |
|||
face6.translate(FreeCAD.Vector(0,0,size)) |
|||
myShell = Part.makeShell([face1,face2,face3,face4,face5,face6]) |
|||
aEdge1=aSegment1.toShape() |
|||
aEdge2=aArcOfCircle.toShape() |
|||
aEdge3=aSegment2.toShape() |
|||
aWire=Part.Wire([aEdge1,aEdge2,aEdge3]) |
|||
mySolid = Part.makeSolid(myShell) |
|||
Recuerdas la diferencia entre geometría y formas? Aquí construimos formas a partir de nuestra geometría de construcción. 3 aristas (las aristas pueden ser rectas o curvas), luego un contorno creado a partir de dichas tres aristas. |
|||
mySolidRev = mySolid.copy() |
|||
mySolidRev.reverse() |
|||
myCyl = Part.makeCylinder(2,20) |
|||
aTrsf=Base.Matrix() |
|||
myCyl.translate(FreeCAD.Vector(size/2, size/2, 0)) |
|||
aTrsf.rotateZ(math.pi) # rotate around the z-axis |
|||
aMirroredWire=aWire.transformGeometry(aTrsf) |
|||
myWireProfile=Part.Wire([aWire,aMirroredWire]) |
|||
cut_part = mySolidRev.cut(myCyl) |
|||
Hasta ahora construimos sólo medio perfil. Más sencillo que construir el perfil completo del mismo modo, simplemente podemos crear una simetría de lo que hicimos, y pegar ambas partes. Así primero creamos una matriz. Una matriz es un modo muy común para aplicar transformaciones a objetos en el mundo 3D, ya que puede contener en una estructura todas las transformaciones básicas que los objetos pueden sufrir (mover, rotar y escalar). Aquí, después de crear la matriz, creamos una simétrica, y creamos una copia de nuestro contorno con esa matriz de transformación aplicada. Ahora tenemos 2 contornos, y podemos crear un tercer contorno a partir de ellos, ya que los contornos son en realidad listas de aristas. |
|||
Part.show(cut_part) |
|||
myFaceProfile=Part.Face(myWireProfile) |
|||
</syntaxhighlight> |
|||
aPrismVec=Base.Vector(0,0,myHeight) |
|||
== Loading and Saving == |
|||
myBody=myFaceProfile.extrude(aPrismVec) |
|||
There are several ways to save your work in the Part module. You can |
|||
myBody=myBody.makeFillet(myThickness/12.0,myBody.Edges) |
|||
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. |
|||
Ahora que tenemos un contorno cerrado, se puede convertir en una cara. Una vez que tengamos una cara, podemos extruirla. Haciendo esto, creamos un sólido. Entonces aplicamos un pequeño redondeo a nuestro objeto porque queremos crear un buen diseño, no es así? |
|||
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) |
|||
El cuerpo de nuestra botella está creado, aún tenemos que crear el cuello. Así que creamos un nuevo sólido, con un cilindro. |
|||
myBody = myBody.fuse(myNeck) |
|||
La operación de fusión, que en otras aplicaciones es llamada unión, es muy potente. Tendrá cuidado de pegar lo que necesita ser pegado y eliminar las partes que necesiten ser eliminadas. |
|||
return myBody |
|||
Obtenemos nuestro sólido de pieza como resultado de nuestra función. Ese sólido de pieza, como cualquier otra forma de piezas, se puede atribuir a un objeto en el documento de FreeCAD, con: |
|||
myObject = FreeCAD.ActiveDocument.addObject("Part::Feature","myObject") |
|||
myObject.Shape = bottle |
|||
o, de forma más simple: |
|||
Part.show(bottle) |
|||
== Cargando y guardando == |
|||
Existen diversas formas de guardar tu trabajo en el módulo de piezas. Puedes desde luego guardar el documento de FreeCAD, pero también puedes guardar objetos de pieza directamente en formatos de CAD comunes, como BREP, IGS, STEP y STL. |
|||
El guardado de una forma en un archivo es sencillo. Existen los métodos exportBrep(), exportIges(), exportStl() y exportStep() disponibles para todos los objetos de forma. Así, haciendo: |
|||
import Part |
|||
s = Part.makeBox(0,0,0,10,10,10) |
|||
s.exportStep("test.stp") |
|||
se guardará nuestro cubo en un archivo STEP. Para cargar un archivo BREP, IGES o STEP, simplemente haz lo contrario: |
|||
Saving a shape to a file is easy. There are exportBrep(), exportIges(), |
|||
exportStl() and exportStep() methods availables for all shape objects. |
|||
So, doing: |
|||
<syntaxhighlight> |
|||
import Part |
|||
s = Part.makeBox(0,0,0,10,10,10) |
|||
s.exportStep("test.stp") |
|||
</syntaxhighlight> |
|||
this will save our box into a STEP file. To load a BREP, |
|||
IGES or STEP file, simply do the contrary: |
|||
<syntaxhighlight> |
|||
import Part |
|||
s = Part.Shape() |
|||
s.read("test.stp") |
|||
</syntaxhighlight> |
|||
To convert an '''.stp''' in '''.igs''' file simply : |
|||
<syntaxhighlight> |
|||
import Part |
import Part |
||
s = Part.Shape() |
s = Part.Shape() |
||
s.read(" |
s.read("file.stp") # incoming file igs, stp, stl, brep |
||
s.exportIges("file.igs") # outbound file igs |
|||
</syntaxhighlight> |
|||
Observa que la importación y apertura de archivos BREP, IGES o STEP también se puede hacer directamente desde el menú Archivo -> Abrir o Archivo -> Importar, mientras que la exportación es con Archivo -> Exportar |
|||
Note that importing or opening BREP, IGES or STEP files can also be done |
|||
directly from the File -> Open or File -> Import menu, while exporting |
|||
is with File -> Export |
|||
{{docnav |
{{docnav|Mesh Scripting|Mesh to Part}} |
||
[[Category:Poweruser Documentation]] |
|||
{{languages/es | {{en|Topological_data_scripting}} {{fr|Topological_data_scripting/fr}} {{it|Topological_data_scripting/it}} {{jp|Topological_data_scripting/jp}} {{ru|Topological_data_scripting/ru}} {{se|Topological_data_scripting/se}} }} |
|||
[[Category:Python Code]] |
|||
[[Category:Tutorials]] |
|||
{{clear}} |
|||
[[Category:Poweruser Documentation/es]] |
|||
<languages/> |
|||
[[Category:Python Code/es]] |
|||
[[Category:Tutorials/es]] |
Revision as of 16:43, 28 November 2014
This page describes several methods for creating and modifying Part shapes from python. Before reading this page, if you are new to python, it is a good idea to read about python scripting and how python scripting works in FreeCAD.
Introduction
We will here explain you how to control the Part Module directly from the FreeCAD python interpreter, or from any external script. The basics about Topological data scripting are described in Part Module Explaining the concepts. 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.
Class Diagram
This is a Unified Modeling Language (UML) overview of the most important classes of the Part module:
Geometry
The geometric objects are the building block of all topological objects:
- Geom Base class of the geometric objects
- Line A straight line in 3D, defined by starting point and and point
- Circle Circle or circle segment defined by a center point and start and end point
- ...... And soon some more
Topology
The following topological data types are available:
- Compound A group of any type of topological object.
- 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.
Quick example : Creating simple topology
We will now create a topology by constructing it out of simpler geometry. As a case study we use a part as seen in the picture which consists of four vertexes, two circles and two lines.
Creating Geometry
First we have to create the distinct geometric parts of this wire. And we have to take care that the vertexes of the geometric parts are at the same position. Otherwise later on we might not be able to connect the geometric parts to a topology!
So we create first the points:
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)
Arc
To create an arc of circle we make a helper point and create the arc of circle through three points:
VC1 = Base.Vector(-10,0,0)
C1 = Part.Arc(V1,VC1,V4)
# and the second one
VC2 = Base.Vector(40,0,0)
C2 = Part.Arc(V2,VC2,V3)
Line
The line can be created very simple out of the points:
L1 = Part.Line(V1,V2)
# and the second one
L2 = Part.Line(V4,V3)
Putting all together
The last step is to put the geometric base elements together and bake a topological shape:
S1 = Part.Shape([C1,C2,L1,L2])
Make a prism
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))
Show it all
Part.show(P)
Creating basic shapes
You can easily create basic topological objects with the "make...()" methods from the Part Module:
b = Part.makeBox(100,100,100)
Part.show(b)
A couple of other make...() methods available:
- makeBox(l,w,h): Makes a box located in p and pointing into the direction d with the dimensions (l,w,h)
- makeCircle(radius): Makes a circle with a given radius
- makeCone(radius1,radius2,height): Makes a cone with a given radii and height
- makeCylinder(radius,height): Makes a cylinder with a given radius and height.
- makeLine((x1,y1,z1),(x2,y2,z2)): Makes a line of two points
- makePlane(length,width): Makes a plane with length and width
- makePolygon(list): Makes a polygon of a list of points
- makeSphere(radius): Make a sphere with a given radius
- makeTorus(radius1,radius2): Makes a torus with a given radii
See the Part API page for a complete list of available methods of the Part module.
Importing the needed modules
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
Creating a Vector
Vectors are one of the most important pieces of information when building shapes. They contain a 3 numbers usually (but not necessarily always) the x, y and z cartesian coordinates. You create a vector like this:
myVector = Base.Vector(3,2,0)
We just created a vector at coordinates x=3, y=2, z=0. In the Part module, vectors are used everywhere. Part shapes also use another kind of point representation, called Vertex, which is acually nothing else than a container for a vector. You access the vector of a vertex like this:
myVertex = myShape.Vertexes[0]
print myVertex.Point
> Vector (3, 2, 0)
Creating an Edge
An edge is nothing but a line with two vertexes:
edge = Part.makeLine((0,0,0), (10,0,0))
edge.Vertexes
> [<Vertex object at 01877430>, <Vertex object at 014888E0>]
Note: You can also create an edge by passing two vectors:
vec1 = Base.Vector(0,0,0)
vec2 = Base.Vector(10,0,0)
line = Part.Line(vec1,vec2)
edge = line.toShape()
You can find the length and center of an edge like this:
edge.Length
> 10.0
edge.CenterOfMass
> Vector (5, 0, 0)
Putting the shape on screen
So far we created an edge object, but it doesn't appear anywhere on screen. This is because we just manipulated python objects here. The FreeCAD 3D scene only displays what you tell it to display. To do that, we use this simple method:
Part.show(edge)
An object will be created in our FreeCAD document, and our "edge" shape will be attributed to it. Use this whenever it's time to display your creation on screen.
Creating a Wire
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) will display the 4 edges that compose our wire. Other useful information can be easily retrieved:
wire3.Length
> 40.0
wire3.CenterOfMass
> Vector (5, 5, 0)
wire3.isClosed()
> True
wire2.isClosed()
> False
Creating a Face
Only faces created from closed wires will be valid. In this example, wire3 is a closed wire but wire2 is not a closed wire (see above)
face = Part.Face(wire3)
face.Area
> 99.999999999999972
face.CenterOfMass
> Vector (5, 5, 0)
face.Length
> 40.0
face.isValid()
> True
sface = Part.Face(wire2)
face.isValid()
> False
Only faces will have an area, not wires nor edges.
Creating a Circle
A circle can be created as simply as this:
circle = Part.makeCircle(10)
circle.Curve
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))
If you want to create it at certain position and with certain direction:
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 will be created at distance 10 from origin on x and will be facing towards x axis. Note: makeCircle only accepts Base.Vector() for position and normal but not tuples. You can also create part of the circle by giving start angle and end angle as:
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)
Both arc1 and arc2 jointly will make a circle. Angles should be provided in degrees, if you have radians simply convert them using formula: degrees = radians * 180/PI or using python's math module (after doing import math, of course):
degrees = math.degrees(radians)
Creating an Arc along points
Unfortunately there is no makeArc function but we have Part.Arc function to create an arc along three points. Basically it can be supposed as an arc joining start point and end point along the middle point. Part.Arc creates an arc object on which .toShape() has to be called to get the edge object, the same way as when using Part.Line 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()
Arc only accepts Base.Vector() for points but not tuples. arc_edge is what we want which we can display using Part.show(arc_edge). You can also obtain an arc by using a portion of a circle:
from math import pi
circle = Part.Circle(Base.Vector(0,0,0),Base.Vector(0,0,1),10)
arc = Part.Arc(c,0,pi)
Arcs are valid edges, like lines. So they can be used in wires too.
Creating a polygon
A polygon is simply a wire with multiple straight edges. The makePolygon function takes a list of points and creates a wire along those points:
lshape_wire = Part.makePolygon([Base.Vector(0,5,0),Base.Vector(0,0,0),Base.Vector(5,0,0)])
Creating a Bezier curve
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)
Creating a Plane
A Plane is simply a flat rectangular surface. The method used to create one is this: makePlane(length,width,[start_pnt,dir_normal]). By default start_pnt = Vector(0,0,0) and dir_normal = Vector(0,0,1). Using dir_normal = Vector(0,0,1) will create the plane facing z axis, while dir_normal = Vector(1,0,0) will create the plane facing x axis:
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 is a cuboid enclosing the plane with a diagonal starting at (3,0,0) and ending at (5,0,2). Here the BoundBox thickness in y axis is zero, since our shape is totally flat.
Note: makePlane only accepts Base.Vector() for start_pnt and dir_normal but not tuples
Creating an ellipse
To create an ellipse there are several ways:
Part.Ellipse()
Creates an ellipse with major radius 2 and minor radius 1 with the center in (0,0,0)
Part.Ellipse(Ellipse)
Create a copy of the given ellipse
Part.Ellipse(S1,S2,Center)
Creates an ellipse centered on the point Center, where the plane of the ellipse is defined by Center, S1 and S2, its major axis is defined by Center and S1, its major radius is the distance between Center and S1, and its minor radius is the distance between S2 and the major axis.
Part.Ellipse(Center,MajorRadius,MinorRadius)
Creates an ellipse with major and minor radii MajorRadius and MinorRadius, and located in the plane defined by Center and the normal (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())
In the above code we have passed S1, S2 and center. Similarly to Arc, Ellipse also creates an ellipse object but not edge, so we need to convert it into edge using toShape() to display.
Note: Arc only accepts Base.Vector() for points but not tuples
eli = Part.Ellipse(Base.Vector(0,0,0),10,5)
Part.show(eli.toShape())
for the above Ellipse constructor we have passed center, MajorRadius and MinorRadius
Creating a Torus
Using the method makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]). By default pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle2=360 and angle=360. Consider a torus as small circle sweeping along a big circle. Radius1 is the radius of big cirlce, radius2 is the radius of small circle, pnt is the center of torus and dir is the normal direction. angle1 and angle2 are angles in radians for the small circle, the last parameter angle is to make a section of the torus:
torus = Part.makeTorus(10, 2)
The above code will create a torus with diameter 20(radius 10) and thickness 4 (small cirlce radius 2)
tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,180)
The above code will create a slice of the torus
tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,360,180)
The above code will create a semi torus, only the last parameter is changed i.e the angle and remaining angles are defaults. Giving the angle 180 will create the torus from 0 to 180, that is, a half torus.
Creating a box or cuboid
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
Creating a Sphere
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 itself.
sphere = Part.makeSphere(10)
hemisphere = Part.makeSphere(10,Base.Vector(0,0,0),Base.Vector(0,0,1),-90,90,180)
Creating a Cylinder
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)
Creating a Cone
Using makeCone(radius1,radius2,height,[pnt,dir,angle]). By default pnt=Vector(0,0,0), dir=Vector(0,0,1) and angle=360
cone = Part.makeCone(10,0,20)
semicone = Part.makeCone(10,0,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180)
Modifying shapes
There are several ways to modify shapes. Some are simple transformation operations such as moving or rotating shapes, other are more complex, such as unioning and subtracting one shape from another. Be aware that
Transform operations
Translating 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.
Rotating a shape
To rotate a shape, you need to specify the rotation center, the axis, and the rotation angle:
myShape.rotate(Vector(0,0,0),Vector(0,0,1),180)
The above code will rotate the shape 180 degrees around the Z Axis.
Generic transformations with matrixes
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 3 numbers, so those 2 lines do the same thing:
myMat.move(2,0,0)
myMat.move(Base.Vector(2,0,0))
When our matrix is set, we can apply it to our shape. FreeCAD provides 2 methods to do that: transformShape() and transformGeometry(). The difference is that with the first one, you are sure that no deformations will occur (see "scaling a shape" below). So we can apply our transformation like this:
myShape.trasformShape(myMat)
or
myShape.transformGeometry(myMat)
Scaling 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 differenty. For scaling, we can't use the transformShape, we must use transformGeometry():
myMat = Base.Matrix()
myMat.scale(2,1,1)
myShape=myShape.transformGeometry(myMat)
Boolean Operations
Subtraction
Subtracting a shape from another one is called "cut" in OCC/FreeCAD jargon 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)
Intersection
The same way, the intersection between 2 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)
Union
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
A Section is the intersection between a solid shape and a plane shape. It will return an intersection curve, a compound with 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
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))
If your circle is hollow, you will obtain a hollow tube. If your circle is actually a disc, with a filled face, you will obtain a solid cylinder:
wire = Part.Wire(circle)
disc = Part.makeFace(wire)
cylinder = disc.extrude(Base.Vector(0,0,2))
Exploring shapes
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
By typing the lines above in the python interpreter, you will gain a good understanding of the structure of Part objects. Here, our makeBox() command created a solid shape. This solid, like all Part solids, contains faces. Faces always contain wires, which are lists of edges that border the face. Each face has at least one closed wire (it can have more if the face has a hole). In the wire, we can look at each edge separately, and inside each edge, we can see the vertexes. Straight edges have only two vertexes, obviously.
Edge analysis
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
Now you can access a lot of properties of the edge by using the length as a position. That means if the edge is 100mm long the start position is 0 and the end position 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)
Using the selection
Here we see now how we can use the selection the user did in the viewer. First of all we create a box and shows it in the viewer
import Part
Part.show(Part.makeBox(100,100,100))
Gui.SendMsgToActiveView("ViewFit")
Select now some faces or edges. With this script you can iterate all selected objects and their sub elements:
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
Select some edges and this script will calculate the length:
length = 0.0
for o in Gui.Selection.getSelectionEx():
for s in o.SubObjects:
length += s.Length
print "Length of the selected edges:" ,length
Complete example: The OCC bottle
A typical example found on the OpenCasCade Getting Started Page is how to build a bottle. This is a good exercise for FreeCAD too. In fact, you can follow our example below and the OCC page simultaneously, you will understand well how OCC structures are implemented in FreeCAD. The complete script below is also included in 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)
The complete script
Here is the complete MakeBottle script:
import Part, FreeCAD, math
from FreeCAD import Base
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0):
aPnt1=Base.Vector(-myWidth/2.,0,0)
aPnt2=Base.Vector(-myWidth/2.,-myThickness/4.,0)
aPnt3=Base.Vector(0,-myThickness/2.,0)
aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0)
aPnt5=Base.Vector(myWidth/2.,0,0)
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4)
aSegment1=Part.Line(aPnt1,aPnt2)
aSegment2=Part.Line(aPnt4,aPnt5)
aEdge1=aSegment1.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge3=aSegment2.toShape()
aWire=Part.Wire([aEdge1,aEdge2,aEdge3])
aTrsf=Base.Matrix()
aTrsf.rotateZ(math.pi) # rotate around the z-axis
aMirroredWire=aWire.transformGeometry(aTrsf)
myWireProfile=Part.Wire([aWire,aMirroredWire])
myFaceProfile=Part.Face(myWireProfile)
aPrismVec=Base.Vector(0,0,myHeight)
myBody=myFaceProfile.extrude(aPrismVec)
myBody=myBody.makeFillet(myThickness/12.0,myBody.Edges)
neckLocation=Base.Vector(0,0,myHeight)
neckNormal=Base.Vector(0,0,1)
myNeckRadius = myThickness / 4.
myNeckHeight = myHeight / 10
myNeck = Part.makeCylinder(myNeckRadius,myNeckHeight,neckLocation,neckNormal)
myBody = myBody.fuse(myNeck)
faceToRemove = 0
zMax = -1.0
for xp in myBody.Faces:
try:
surf = xp.Surface
if type(surf) == Part.Plane:
z = surf.Position.z
if z > zMax:
zMax = z
faceToRemove = xp
except:
continue
myBody = myBody.makeThickness([faceToRemove],-myThickness/50 , 1.e-3)
return myBody
Detailed explanation
import Part, FreeCAD, math
from FreeCAD import Base
We will need,of course, the Part module, but also the FreeCAD.Base module, which contains basic FreeCAD structures like vectors and matrixes.
def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0):
aPnt1=Base.Vector(-myWidth/2.,0,0)
aPnt2=Base.Vector(-myWidth/2.,-myThickness/4.,0)
aPnt3=Base.Vector(0,-myThickness/2.,0)
aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0)
aPnt5=Base.Vector(myWidth/2.,0,0)
Here we define our makeBottle function. This function can be called without arguments, like we did above, in which case default values for width, height, and thickness will be used. Then, we define a couple of points that will be used for building our base profile.
aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4)
aSegment1=Part.Line(aPnt1,aPnt2)
aSegment2=Part.Line(aPnt4,aPnt5)
Here we actually define the geometry: an arc, made of 3 points, and two line segments, made of 2 points.
aEdge1=aSegment1.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge3=aSegment2.toShape()
aWire=Part.Wire([aEdge1,aEdge2,aEdge3])
Remember the difference between geometry and shapes? Here we build shapes out of our construction geometry. 3 edges (edges can be straight or curved), then a wire made of those three edges.
aTrsf=Base.Matrix()
aTrsf.rotateZ(math.pi) # rotate around the z-axis
aMirroredWire=aWire.transformGeometry(aTrsf)
myWireProfile=Part.Wire([aWire,aMirroredWire])
Until now we built only a half profile. Easier than building the whole profile the same way, we can just mirror what we did, and glue both halfs together. So we first create a matrix. A matrix is a very common way to apply transformations to objects in the 3D world, since it can contain in one structure all basic transformations that 3D objects can suffer (move, rotate and scale). Here, after we create the matrix, we mirror it, and we create a copy of our wire with that transformation matrix applied to it. We now have two wires, and we can make a third wire out of them, since wires are actually lists of edges.
myFaceProfile=Part.Face(myWireProfile)
aPrismVec=Base.Vector(0,0,myHeight)
myBody=myFaceProfile.extrude(aPrismVec)
myBody=myBody.makeFillet(myThickness/12.0,myBody.Edges)
Now that we have a closed wire, it can be turned into a face. Once we have a face, we can extrude it. Doing so, we actually made a solid. Then we apply a nice little fillet to our object because we care about good design, don't we?
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)
Then, the body of our bottle is made, we still need to create a neck. So we make a new solid, with a cylinder.
myBody = myBody.fuse(myNeck)
The fuse operation, which in other apps is sometimes called union, is very powerful. It will take care of gluing what needs to be glued and remove parts that need to be removed.
return myBody
Then, we return our Part solid as the result of our function. That Part solid, like any other Part shape, can be attributed to an object in a FreeCAD document, with:
myObject = FreeCAD.ActiveDocument.addObject("Part::Feature","myObject")
myObject.Shape = bottle
or, more simple:
Part.show(bottle)
Box pierced
Here a complete example of building a box pierced.
The construction is done side by side and when the cube is finished, it is hollowed out of a cylinder through.
import Draft, Part, FreeCAD, math, PartGui, FreeCADGui, PyQt4
from math import sqrt, pi, sin, cos, asin
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 = FreeCAD.Matrix()
myMat.rotateZ(math.pi/2)
face2.transformShape(myMat)
face2.translate(FreeCAD.Vector(size, 0, 0))
myMat.rotateZ(math.pi/2)
face3.transformShape(myMat)
face3.translate(FreeCAD.Vector(size, size, 0))
myMat.rotateZ(math.pi/2)
face4.transformShape(myMat)
face4.translate(FreeCAD.Vector(0, size, 0))
myMat = FreeCAD.Matrix()
myMat.rotateX(-math.pi/2)
face5.transformShape(myMat)
face6.transformShape(myMat)
face6.translate(FreeCAD.Vector(0,0,size))
myShell = Part.makeShell([face1,face2,face3,face4,face5,face6])
mySolid = Part.makeSolid(myShell)
mySolidRev = mySolid.copy()
mySolidRev.reverse()
myCyl = Part.makeCylinder(2,20)
myCyl.translate(FreeCAD.Vector(size/2, size/2, 0))
cut_part = mySolidRev.cut(myCyl)
Part.show(cut_part)
Loading and Saving
There are several ways to save your work in the Part module. You can of course save your FreeCAD document, but you can also save Part objects directly to common CAD formats, such as BREP, IGS, STEP and STL.
Saving a shape to a file is easy. There are exportBrep(), exportIges(), exportStl() and exportStep() methods availables for all shape objects. So, doing:
import Part
s = Part.makeBox(0,0,0,10,10,10)
s.exportStep("test.stp")
this will save our box into a STEP file. To load a BREP, IGES or STEP file, simply do the contrary:
import Part
s = Part.Shape()
s.read("test.stp")
To convert an .stp in .igs file simply :
import Part
s = Part.Shape()
s.read("file.stp") # incoming file igs, stp, stl, brep
s.exportIges("file.igs") # outbound file igs
Note that importing or opening BREP, IGES or STEP files can also be done directly from the File -> Open or File -> Import menu, while exporting is with File -> Export