Topological data scripting/es: Difference between revisions

From FreeCAD Documentation
(Created page with "== Creación de formas básicas == Puedes crear fácilmente objetos topológicos simples con los métodos "make...()" del Módulo Parte:")
(Updating to match new version of source page)
 
(192 intermediate revisions by 4 users not shown)
Line 1: Line 1:
<languages/>
Esta página describe diversos métodos para crear y modificar [[Part Module/es|formas de piezas]] desde Python. Antes de leer esta página, si eres nuevo en Python, es una buena idea leer la [[Introduction to python/es|Introducción a Python]] y [[FreeCAD Scripting Basics/es|como funcionan los archivos de guión en FreeCAD]].

{{Docnav
|[[Part_scripting|Part scripting]]
|[[Scripted_objects|Scripted objects]]
}}

{{TOCright}}


<span id="Introduction"></span>
== Introducción ==
== Introducción ==


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 [[Scripting/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.
Aquí te explicaremos cómo controlar el módulo [[Part_Workbench/es|Pieza]] directamente desde el intérprete de Python de FreeCAD, o desde cualquier guión externo. Asegúrate de navegar por la sección [[Scripting/es|Guionización]] y las páginas [[FreeCAD_Scripting_Basics/es|Básicos de Guionización FreeCAD]] si necesitas más información sobre cómo funciona el guionización de Python en FreeCAD. Si eres nuevo en Python, es una buena idea leer primero la [[Introduction_to_Python/es|Introducción a Python]].


<span id="See_also"></span>
=== Diagrama de clases ===
===Ver también===
É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:


* [[Part_scripting/es|Guionización Pieza]]
[[Image:Part_Classes.jpg|center|Python classes of the Part module]]
* [[OpenCASCADE/es|OpenCASCADE]]


<span id="Class_diagram"></span>
=== Geometría ===
==Diagrama de clase==


Este es un resumen [http://es.wikipedia.org/wiki/Lenguaje_Unificado_de_Modelado Lenguaje Unificado de Modelado (UML)] de las clases más importantes del módulo Pieza:
Los objetos geométricos son la piedra angular de todos los objetos topológicos:
[[Image:Part_Classes.jpg|center|Clases de Python del módulo Pieza]]
{{Top}}
<span id="Geometry"></span>
===Geometría===


Los objetos geométricos son los bloques de construcción de todos los objetos topológicos:
* '''geom''' clase base de los objetos geométricos
* '''Geom''' Clase base de los objetos geométricos.
* '''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
* '''Línea''' Una línea recta en 3D, definida por un punto inicial y un punto final.
* '''Círculo''' Círculo o segmento de círculo definido por un punto central y un punto inicial y final.
* '''......''' Y en breve más cosas
* Etc.
{{Top}}
<span id="Topology"></span>
===Topología===


=== Topología ===
Los siguientes tipos de datos topológicos están disponibles:
Los siguientes tipos de datos topológicos están disponibles:
* '''compound''' Un grupo de cualquier tipo de objetos topológicos.
* '''Compuesto''' Un grupo de cualquier tipo de objetos topológicos.
* '''compsolid''' Un sólido compuesto es un grupo de sólidos concetados por sus caras. Es una extensión de las nociones de WIRE y SHELL en el ámbito de los sólido.
* '''Sólido compuesto''' Un sólido compuesto es un conjunto de sólidos conectados por sus caras. Amplía las nociones de ALAMBRE y CASCO a los sólidos.
* '''solid''' Una región del espacio limitada por shells. Es tridimensional.
* '''Sólido''' Una parte del espacio limitada por cáscaras. Es tridimensional.
* '''shell''' Un conjunto de caras conectadas por sus bordes. Una shell puede ser abierta o cerrada.
* '''Cáscara''' Conjunto de caras conectadas por sus aristas. Una cáscara puede ser abierta o cerrada.
* '''face''' En 2D es parte de un plano; en 3D es parte de una superficie. Su geometría está limitada por sus contornos. Es un ente bidimensional.
* En 2D es parte de un plano; en 3D es parte de una superficie. Su geometría está limitada (recortada) por los contornos. Es bidimensional.
* '''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.
* '''Alambre''' Conjunto de aristas conectadas por sus vértices. Puede ser un contorno abierto o cerrado dependiendo de si las aristas están unidas o no.
* '''edge''' Un elemento topológico que corresponde a una curva limitada. Un borde está normalmente limitado por vértices. Es un ente unidimensional.
* '''Arista''' Elemento topológico que corresponde a una curva restringida. Una arista está generalmente limitada por los vértices. Tiene una dimensión.
* '''vertex''' Un elemento topológico que se corresponde con un punto. Tiene dimensión cero.
* Vértice Elemento topológico que corresponde a un punto. Tiene una dimensión cero.
* '''shape''' Un concepto genérico que abarca todos los anteriores.
* '''Forma''' Término genérico que abarca todo lo anterior.
{{Top}}
<span id="Example:_Create_simple_topology"></span>
==Ejemplo: Crear una topología simple==


[[Image:Wire.png|Hilo]]
== Ejemplo rápido: Creación de topologías básicas ==


Ahora crearemos una topología construyéndola a partir de una geometría más sencilla. Como caso de estudio utilizaremos una pieza como la que se ve en la imagen que consta de cuatro vértices, dos arcos y dos líneas.
[[Image:Wire.png|right|Wire]]
{{Top}}
<span id="Create_geometry"></span>
===Crear geometría===


Primero creamos las distintas partes geométricas de este cable. Asegurándonos de que las partes que tienen que ser conectadas más tarde comparten los mismos vértices.
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.


Así que primero creamos los puntos:
==== Creación de geometría ====


{{Code|code=
Primero tenemos que crear las distintas partes de la geometría de este contorno.
import FreeCAD as App
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!
import Part
V1 = App.Vector(0, 10, 0)
V2 = App.Vector(30, 10, 0)
V3 = App.Vector(30, -10, 0)
V4 = App.Vector(0, -10, 0)
}}
{{Top}}
<span id="Arc"></span>
===Arco===


[[Image:Circel.png|Círculo]]
Así que primero creamos los puntos:

<syntaxhighlight>

from FreeCAD import Base
Para cada arco necesitamos un punto de ayuda:
V1 = Base.Vector(0,10,0)

V2 = Base.Vector(30,10,0)
{{Code|code=
V3 = Base.Vector(30,-10,0)
V4 = Base.Vector(0,-10,0)
VC1 = App.Vector(-10, 0, 0)
C1 = Part.Arc(V1, VC1, V4)
</syntaxhighlight>
VC2 = App.Vector(40, 0, 0)
==== Arco ====
C2 = Part.Arc(V2, VC2, V3)
}}
{{Top}}
<span id="Line"></span>
===Línea===


[[Image:Circel.png|right|Circle]]
[[Image:Line.png|Línea]]


Para crear un arco de circunferencia crearemos puntos de ayuda y crearemos el arco a través de tres puntos:
<syntaxhighlight>
VC1 = Base.Vector(-10,0,0)
C1 = Part.Arc(V1,VC1,V4)
# and the second one
VC2 = Base.Vector(40,0,0)
C2 = Part.Arc(V2,VC2,V3)
</syntaxhighlight>
==== Línea ====


Los segmentos de línea se pueden crear a partir de dos puntos:
[[Image:Line.png|right|Line]]


{{Code|code=
La línea puede crearse de forma muy simple a partir de los puntos:
L1 = Part.LineSegment(V1, V2)
<syntaxhighlight>
L1 = Part.Line(V1,V2)
L2 = Part.LineSegment(V3, V4)
}}
# and the second one
{{Top}}
L2 = Part.Line(V4,V3)
<span id="Put_it_all_together"></span>
</syntaxhighlight>
==== Poniendo todo junto ====
===Poniendo todo junto===


El último paso es poner los elementos base de la geometría juntos y formar una forma topológica:
El último paso es poner los elementos base de la geometría juntos y formar una forma topológica:
<syntaxhighlight>
S1 = Part.Shape([C1,C2,L1,L2])
</syntaxhighlight>
==== Crear un prisma ====


{{Code|code=
Ahora extruir el contorno en una dirección y crear una forma 3D real:
S1 = Part.Shape([C1, L1, C2, L2])
<syntaxhighlight>
}}
{{Top}}
<span id="Make_a_prism"></span>
===Crear un prisma===

Ahora extruir el hilo en una dirección y crear una forma 3D real:

{{Code|code=
W = Part.Wire(S1.Edges)
W = Part.Wire(S1.Edges)
P = W.extrude(Base.Vector(0,0,10))
P = W.extrude(App.Vector(0, 0, 10))
}}
</syntaxhighlight>
{{Top}}
==== Mostrar todo ====
<span id="Show_it_all"></span>
<syntaxhighlight>
===Mostrar todo===

{{Code|code=
Part.show(P)
Part.show(P)
}}
</syntaxhighlight>
{{Top}}
== Creación de formas básicas ==
<span id="Create_basic_shapes"></span>
==Crear formas básicas==


<div class="mw-translate-fuzzy">
Puedes crear fácilmente objetos topológicos simples con los métodos "make...()" del Módulo Parte:
Puedes crear fácilmente objetos topológicos básicos con los métodos {{incode|make...()}} del módulo Pieza:
<syntaxhighlight>
</div>
b = Part.makeBox(100,100,100)

{{Code|code=
b = Part.makeBox(100, 100, 100)
Part.show(b)
Part.show(b)
}}
</syntaxhighlight>
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.


<div class="mw-translate-fuzzy">
==== Importing the needed modules ====
Algunos métodos disponibles {{incode|make...()}}:
First we need to import the Part module so we can use its contents in python.
* {{incode|makeBox(l, w, h, [p, d])}} Hace una caja situada en p y apuntando a la dirección d con las dimensiones (l,w,h).
We'll also import the Base module from inside the FreeCAD module:
* {{incode|makeCircle(radius)}} Hace un círculo con un radio determinado.
<syntaxhighlight>
* {{incode|makeCone(radius1, radius2, height)}} Hace un cono con los radios y la altura dados.
* {{incode|makeCylinder(radius, height)}} Hace un cilindro con un radio y altura dados.
* {{incode|makeLine((x1, y1, z1), (x2, y2, z2))}} Hace una línea desde dos puntos.
* {{incode|makePlane(length, width)}} Hace un plano con longitud y anchura.
* {{incode|makePolygon(list)}} Hace un polígono a partir de una lista de puntos.
* {{incode|makeSphere(radius)}} Hace una esfera con un radio determinado.
* {{incode|makeTorus(radius1, radius2)}} Hace un toro con los radios dados.
Ver la página [[Part_API/es|Pieza API]] para una lista completa de los métodos disponibles del módulo Pieza.
</div>
{{Top}}
<span id="Import_modules"></span>
===Módulos de importación===

<div class="mw-translate-fuzzy">
Primero necesitamos importar el módulo Pieza para poder usar su contenido en Python. También importaremos el módulo Base desde dentro del módulo FreeCAD:
</div>

{{Code|code=
import FreeCAD as App
import Part
import Part
}}
from FreeCAD import Base
{{Top}}
</syntaxhighlight>
<span id="Create_a_vector"></span>
==== Creating a Vector ====
===Crear un 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
[https://es.wikipedia.org/wiki/Vector Vectores] son una de las piezas de información más importantes cuando se construir formas. Suelen contener tres números (pero no necesariamente siempre): las coordenadas cartesianas X, Y y Z. Se crea un vector así:
usually (but not necessarily always) the x, y and z cartesian coordinates. You

create a vector like this:
{{Code|code=
<syntaxhighlight>
myVector = Base.Vector(3,2,0)
myVector = App.Vector(3, 2, 0)
}}
</syntaxhighlight>

We just created a vector at coordinates x=3, y=2, z=0. In the Part module,
Hemos creado un vector en las coordenadas X = 3, Y = 2, Z = 0. En el módulo de la pieza, los vectores se utilizan en todas partes. Las formas de la pieza también utilizan otro tipo de representación de puntos llamada Vértice que es simplemente un contenedor para un vector. Se accede al vector de un vértice así:
vectors are used everywhere. Part shapes also use another kind of point

representation, called Vertex, which is acually nothing else than a container
{{Code|code=
for a vector. You access the vector of a vertex like this:
<syntaxhighlight>
myVertex = myShape.Vertexes[0]
myVertex = myShape.Vertexes[0]
print myVertex.Point
print(myVertex.Point)
> Vector (3, 2, 0)
> Vector (3, 2, 0)
}}
</syntaxhighlight>
{{Top}}
==== Creating an Edge ====
<span id="Create_an_edge"></span>
An edge is nothing but a line with two vertexes:
===Crear un borde===
<syntaxhighlight>

edge = Part.makeLine((0,0,0), (10,0,0))
Un borde no es más que una línea con dos vértices:

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

Note: You can also create an edge by passing two vectors:
Nota: También se puede crear un borde pasando dos vectores:
<syntaxhighlight>

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

You can find the length and center of an edge like this:
Puedes encontrar la longitud y el centro de un borde así:
<syntaxhighlight>

{{Code|code=
edge.Length
edge.Length
> 10.0
> 10.0
edge.CenterOfMass
edge.CenterOfMass
> Vector (5, 0, 0)
> Vector (5, 0, 0)
}}
</syntaxhighlight>
{{Top}}
==== Putting the shape on screen ====
<span id="Put_the_shape_on_screen"></span>
So far we created an edge object, but it doesn't appear anywhere on screen.
===Poniendo la forma en la pantalla===
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
Hasta ahora hemos creado un objeto de borde, pero no aparece en ninguna parte de la pantalla. Esto se debe a que la escena 3D de FreeCAD sólo muestra lo que tú le dices que muestre. Para ello, utilizamos este sencillo método:
method:

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

An object will be created in our FreeCAD document, and our "edge" shape
La función mostrar crea un objeto en nuestro documento de FreeCAD y le asigna nuestra forma "borde". Utilízala siempre que sea el momento de mostrar tu creación en pantalla.
will be attributed to it. Use this whenever it's time to display your
{{Top}}
creation on screen.
<span id="Create_a_wire"></span>
===Crear un hilo===

Un hilo es una línea de varias aristas y puede crearse a partir de una lista de aristas o incluso de una lista de hilos:


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

Part.show(wire3) will display the 4 edges that compose our wire. Other
<div class="mw-translate-fuzzy">
useful information can be easily retrieved:
Part.show(wire3) mostrará las 4 aristas que componen nuestro contorno. Otra información útil se puede recuperar fácilmente:
<syntaxhighlight>
</div>

{{Code|code=
wire3.Length
wire3.Length
> 40.0
> 40.0
Line 191: Line 251:
wire2.isClosed()
wire2.isClosed()
> False
> False
}}
</syntaxhighlight>
{{Top}}
==== Creating a Face ====
<span id="Create_a_face"></span>
Only faces created from closed wires will be valid. In this example, wire3
<div class="mw-translate-fuzzy">
is a closed wire but wire2 is not a closed wire (see above)
==== Creación de una cara ====
<syntaxhighlight>

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)
</div>

Only faces created from closed wires will be valid. In this example, wire3 is a closed wire but wire2 is not (see above):

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


<div class="mw-translate-fuzzy">
==== Creating a Circle ====
Sólo las caras tendrán un área, ni los contornos ni las aristas.
A circle can be created as simply as this:
</div>
<syntaxhighlight>
{{Top}}
<span id="Create_a_circle"></span>
===Crear un círculo===

Se puede crear un círculo así:

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

If you want to create it at certain position and with certain direction:
Si quieres crearlo en una cierta posición y con una cierta dirección:
<syntaxhighlight>

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

ccircle will be created at distance 10 from origin on x and will be facing
<div class="mw-translate-fuzzy">
towards x axis. Note: makeCircle only accepts Base.Vector() for position
ccircle 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í:
and normal but not tuples. You can also create part of the circle by giving
</div>
start angle and end angle as:

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

Both arc1 and arc2 jointly will make a circle. Angles should be provided in
<div class="mw-translate-fuzzy">
degrees, if you have radians simply convert them using formula:
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 or using python's math module (after doing import
degrees = radians * 180/PI
math, of course):
o usando el módulo Python de matemáticas (después de importarlo, obviamente):
<syntaxhighlight>
</div>

{{Code|code=
import math
degrees = math.degrees(radians)
degrees = math.degrees(radians)
}}
</syntaxhighlight>
{{Top}}
==== Creating an Arc along points ====
<span id="Create_an_arc_along_points"></span>
Unfortunately there is no makeArc function but we have Part.Arc function to
<div class="mw-translate-fuzzy">
create an arc along three points. Basically it can be supposed as an arc
==== Creación de un arco por varios puntos ====
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,
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.
the same way as when using Part.Line instead of Part.makeLine.
</div>
<syntaxhighlight>

arc = Part.Arc(Base.Vector(0,0,0),Base.Vector(0,5,0),Base.Vector(5,5,0))
Unfortunately there is no {{incode|makeArc()}} function, but we have the {{incode|Part.Arc()}} function to create an arc through three points. It creates an arc object joining the start point to the end point through the middle point. The arc object's {{incode|toShape()}} function must be called to get an edge object, the same as when using {{incode|Part.LineSegment}} instead of {{incode|Part.makeLine}}.

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

we want which we can display using Part.show(arc_edge). You can also obtain
<div class="mw-translate-fuzzy">
an arc by using a portion of a circle:
Arc 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:
<syntaxhighlight>

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:
</div>

{{Code|code=
from math import pi
from math import pi
circle = Part.Circle(Base.Vector(0,0,0),Base.Vector(0,0,1),10)
circle = Part.Circle(App.Vector(0, 0, 0), App.Vector(0, 0, 1), 10)
arc = Part.Arc(c,0,pi)
arc = Part.Arc(circle,0,pi)
}}
</syntaxhighlight>

Arcs are valid edges, like lines. So they can be used in wires too.
<div class="mw-translate-fuzzy">
Los arcos son aristas válidas, como las líneas. Así que también pueden utilizarse en los contornos.
</div>
{{Top}}
<span id="Create_a_polygon"></span>
<div class="mw-translate-fuzzy">
==== 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:
</div>

A polygon is simply a wire with multiple straight edges. The {{incode|makePolygon()}} function takes a list of points and creates a wire through those points:

{{Code|code=
lshape_wire = Part.makePolygon([App.Vector(0, 5, 0), App.Vector(0, 0, 0), App.Vector(5, 0, 0)])
}}
{{Top}}
===Create a Bézier curve===

Bézier curves are used to model smooth curves using a series of poles (points) and optional weights. The function below makes a {{incode|Part.BezierCurve()}} from a series of {{incode|FreeCAD.Vector()}} points. Note: when "getting" and "setting" a single pole or weight, indices start at 1, not 0.


{{Code|code=
==== 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):
def makeBCurveEdge(Points):
geomCurve = Part.BezierCurve()
geomCurve = Part.BezierCurve()
Line 276: Line 378:
edge = Part.Edge(geomCurve)
edge = Part.Edge(geomCurve)
return(edge)
return(edge)
}}
</syntaxhighlight>
{{Top}}
==== Creating a Plane ====
<span id="Create_a_plane"></span>
A Plane is simply a flat rectangular surface. The method used to create one is
<div class="mw-translate-fuzzy">
this: '''makePlane(length,width,[start_pnt,dir_normal])'''. By default
==== Creación de un plano ====
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
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 facing x axis:
</div>
<syntaxhighlight>

plane = Part.makePlane(2,2)
A Plane is a flat rectangular surface. The method used to create one is {{incode|makePlane(length, width, [start_pnt, dir_normal])}}. By default start_pnt = Vector(0, 0, 0) and dir_normal = Vector(0, 0, 1). Using dir_normal = Vector(0, 0, 1) will create the plane facing in the positive Z axis direction, while dir_normal = Vector(1, 0, 0) will create the plane facing in the positive X axis direction:

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


<div class="mw-translate-fuzzy">
Note: makePlane only accepts Base.Vector() for start_pnt and dir_normal but not tuples
BoundBox 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.
</div>


<div class="mw-translate-fuzzy">
==== Creating an ellipse ====
Nota: makePlane sólo acepta Base.Vector() para start_pnt y dir_normal pero no tuplas
To create an ellipse there are several ways:
</div>
<syntaxhighlight>
{{Top}}
<span id="Create_an_ellipse"></span>
<div class="mw-translate-fuzzy">
==== Creación de una elipse ====

Para crear una elipse existen varios métodos:
</div>

There are several ways to create an ellipse:

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

Creates an ellipse with major radius 2 and minor radius 1 with the center in (0,0,0)
<div class="mw-translate-fuzzy">
<syntaxhighlight>
Crea una elipse cuyo radio mayor es 2 y el radio menor 1 con centro en el (0,0,0)
</div>

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

Create a copy of the given ellipse
<div class="mw-translate-fuzzy">
<syntaxhighlight>
Crea una copia de la elipse dada
Part.Ellipse(S1,S2,Center)
</div>
</syntaxhighlight>

Creates an ellipse centered on the point Center, where the plane of the
{{Code|code=
ellipse is defined by Center, S1 and S2, its major axis is defined by
Part.Ellipse(S1, S2, Center)
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>
<div class="mw-translate-fuzzy">
Part.Ellipse(Center,MajorRadius,MinorRadius)
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,
</syntaxhighlight>
y su radio menor es la distancia entre S2 y el eje mayor.
Creates an ellipse with major and minor radii MajorRadius and MinorRadius,
</div>
and located in the plane defined by Center and the normal (0,0,1)

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

<div class="mw-translate-fuzzy">
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)
</div>

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


<div class="mw-translate-fuzzy">
Note: Arc only accepts Base.Vector() for points but not tuples
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.
<syntaxhighlight>
</div>
eli = Part.Ellipse(Base.Vector(0,0,0),10,5)

<div class="mw-translate-fuzzy">
Nota: Arc sólo acepta Base.Vector() para puntos pero no tuplas
</div>

{{Code|code=
eli = Part.Ellipse(App.Vector(0, 0, 0), 10, 5)
Part.show(eli.toShape())
Part.show(eli.toShape())
}}
</syntaxhighlight>
for the above Ellipse constructor we have passed center, MajorRadius and MinorRadius


<div class="mw-translate-fuzzy">
==== Creating a Torus ====
para el constructor de la elipse de arriba hemos pasado el centro, MajorRadius y MinorRadius
Using the method '''makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle])'''. By
</div>
default pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle2=360 and angle=360.
{{Top}}
Consider a torus as small circle sweeping along a big circle. Radius1 is the
<span id="Create_a_torus"></span>
radius of big cirlce, radius2 is the radius of small circle, pnt is the center
<div class="mw-translate-fuzzy">
of torus and dir is the normal direction. angle1 and angle2 are angles in
==== Creación de un toro ====
radians for the small circle, the last parameter angle is to make a section of

the torus:
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.
<syntaxhighlight>
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:
</div>

Using {{incode|makeTorus(radius1, radius2, [pnt, dir, angle1, angle2, angle])}}. By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = 0, angle2 = 360 and angle = 360. Consider a torus as small circle sweeping along a big circle. Radius1 is the radius of the big circle, radius2 is the radius of the small circle, pnt is the center of the torus and dir is the normal direction. angle1 and angle2 are angles in degrees for the small circle; the last angle parameter is to make a section of the torus:

{{Code|code=
torus = Part.makeTorus(10, 2)
torus = Part.makeTorus(10, 2)
}}
</syntaxhighlight>

The above code will create a torus with diameter 20(radius 10) and thickness 4
<div class="mw-translate-fuzzy">
(small cirlce radius 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)
<syntaxhighlight>
</div>
tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,180)

</syntaxhighlight>
{{Code|code=
The above code will create a slice of the torus
tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)
<syntaxhighlight>
}}
tor=Part.makeTorus(10,5,Base.Vector(0,0,0),Base.Vector(0,0,1),0,360,180)

</syntaxhighlight>
<div class="mw-translate-fuzzy">
The above code will create a semi torus, only the last parameter is changed
El código de arriba creará una sección del toro
i.e the angle and remaining angles are defaults. Giving the angle 180 will
</div>
create the torus from 0 to 180, that is, a half torus.

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

<div class="mw-translate-fuzzy">
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.
</div>
{{Top}}
<span id="Create_a_box_or_cuboid"></span>
<div class="mw-translate-fuzzy">
==== 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)
</div>

Using {{incode|makeBox(length, width, height, [pnt, dir])}}.
By default pnt = Vector(0, 0, 0) and dir = Vector(0, 0, 1).


{{Code|code=
==== Creating a box or cuboid ====
Using '''makeBox(length,width,height,[pnt,dir])'''.
box = Part.makeBox(10, 10, 10)
By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)
<syntaxhighlight>
box = Part.makeBox(10,10,10)
len(box.Vertexes)
len(box.Vertexes)
> 8
> 8
}}
</syntaxhighlight>
{{Top}}
==== Creating a Sphere ====
<span id="Create_a_sphere"></span>
Using '''makeSphere(radius,[pnt, dir, angle1,angle2,angle3])'''. By default
<div class="mw-translate-fuzzy">
pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=-90, angle2=90 and angle3=360.
==== Creación de una esfera ====
angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3

is the sphere diameter itself.
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.
<syntaxhighlight>
</div>

Using {{incode|makeSphere(radius, [pnt, dir, angle1, angle2, angle3])}}. By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = -90, angle2 = 90 and angle3 = 360. Angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3 is the sphere diameter.

{{Code|code=
sphere = Part.makeSphere(10)
sphere = Part.makeSphere(10)
hemisphere = Part.makeSphere(10,Base.Vector(0,0,0),Base.Vector(0,0,1),-90,90,180)
hemisphere = Part.makeSphere(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), -90, 90, 180)
}}
</syntaxhighlight>
{{Top}}
==== Creating a Cylinder ====
<span id="Create_a_cylinder"></span>
Using '''makeCylinder(radius,height,[pnt,dir,angle])'''. By default
<div class="mw-translate-fuzzy">
pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360
==== Creación de un cilindro ====
<syntaxhighlight>

cylinder = Part.makeCylinder(5,20)
partCylinder = Part.makeCylinder(5,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180)
Utilizando '''makeCylinder(radius,height,[pnt,dir,angle])'''. Por defecto pnt=Vector(0,0,0),dir=Vector(0,0,1) y angle=360
</div>
</syntaxhighlight>

==== Creating a Cone ====
Using '''makeCone(radius1,radius2,height,[pnt,dir,angle])'''. By default
Using {{incode|makeCylinder(radius, height, [pnt, dir, angle])}}. By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.

pnt=Vector(0,0,0), dir=Vector(0,0,1) and angle=360
{{Code|code=
<syntaxhighlight>
cone = Part.makeCone(10,0,20)
cylinder = Part.makeCylinder(5, 20)
semicone = Part.makeCone(10,0,20,Base.Vector(20,0,0),Base.Vector(0,0,1),180)
partCylinder = Part.makeCylinder(5, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)
}}
</syntaxhighlight>
{{Top}}
== Modifying shapes ==
<span id="Create_a_cone"></span>
There are several ways to modify shapes. Some are simple transformation operations
<div class="mw-translate-fuzzy">
==== 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
</div>

Using {{incode|makeCone(radius1, radius2, height, [pnt, dir, angle])}}. By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1) and angle = 360.

{{Code|code=
cone = Part.makeCone(10, 0, 20)
semicone = Part.makeCone(10, 0, 20, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)
}}
{{Top}}
<span id="Modify_shapes"></span>
<div class="mw-translate-fuzzy">
== 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. Be aware that
subtracting one shape from another. Tenlo en cuenta
</div>


There are several ways to modify shapes. Some are simple transformation operations such as moving or rotating shapes, others are more complex, such as unioning and subtracting one shape from another.
=== Transform operations ===
{{Top}}
<span id="Transform_operations"></span>
<div class="mw-translate-fuzzy">
=== Operaciones de transformación ===
</div>


<span id="Translate_a_shape"></span>
==== Translating a shape ====
<div class="mw-translate-fuzzy">
Translating is the act of moving a shape from one place to another.
==== Traslación de una forma ====
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.


Traslación es el acto de mover una forma de una situación a otra.
==== Rotating a shape ====
Cualquier forma (aristas, caras, cubos, etc...) se puede trasladar del mismo modo:
To rotate a shape, you need to specify the rotation center, the axis,
</div>
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.


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:
==== Generic transformations with matrixes ====

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

myMat.move(Base.Vector(2,0,0))
<div class="mw-translate-fuzzy">
Esto moverá nuestra forma "myShape" 2 unidades en la dirección del eje X.
</div>
{{Top}}
<span id="Rotate_a_shape"></span>
<div class="mw-translate-fuzzy">
==== Rotación de una forma ====

Para rotar una forma, necesitas especificar el centro de rotación, el eje, y el ángulo de rotación:
</div>

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

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

El código de arriba rotará la forma 180 grados alrededor del eje Z.
{{Top}}
<span id="Matrix_transformations"></span>
<div class="mw-translate-fuzzy">
==== 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:
</div>

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

{{Code|code=
myMat = App.Matrix()
myMat.move(App.Vector(2, 0, 0))
myMat.rotateZ(math.pi/2)
myMat.rotateZ(math.pi/2)
}}
</syntaxhighlight>

Note: FreeCAD matrixes work in radians. Also, almost all matrix operations
<div class="mw-translate-fuzzy">
that take a vector can also take 3 numbers, so those 2 lines do the same thing:
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:
<syntaxhighlight>
</div>
myMat.move(2,0,0)

myMat.move(Base.Vector(2,0,0))
{{Code|code=
</syntaxhighlight>
myMat.move(2, 0, 0)
When our matrix is set, we can apply it to our shape. FreeCAD provides 2
myMat.move(App.Vector(2, 0, 0))
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:
<div class="mw-translate-fuzzy">
<syntaxhighlight>
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í:
myShape.trasformShape(myMat)
</div>
</syntaxhighlight>

or
{{Code|code=
<syntaxhighlight>
myShape.transformShape(myMat)
}}

o

{{Code|code=
myShape.transformGeometry(myMat)
myShape.transformGeometry(myMat)
}}
</syntaxhighlight>
{{Top}}
==== Scaling a shape ====
<span id="Scale_a_shape"></span>
Scaling a shape is a more dangerous operation because, unlike translation
<div class="mw-translate-fuzzy">
or rotation, scaling non-uniformly (with different values for x, y and z)
==== Escalando una forma ====
can modify the structure of the shape. For example, scaling a circle with

a higher value horizontally than vertically will transform it into an
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():
ellipse, which behaves mathematically very differenty. For scaling, we
</div>
can't use the transformShape, we must use transformGeometry():

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

myMat.scale(2,1,1)
{{Code|code=
myMat = App.Matrix()
myMat.scale(2, 1, 1)
myShape=myShape.transformGeometry(myMat)
myShape=myShape.transformGeometry(myMat)
}}
</syntaxhighlight>
{{Top}}
=== Boolean Operations ===
<span id="Boolean_operations"></span>
<div class="mw-translate-fuzzy">
=== Operaciones Booleanas ===
</div>


==== Subtraction ====
<span id="Subtraction"></span>
<div class="mw-translate-fuzzy">
Subtracting a shape from another one is called "cut" in OCC/FreeCAD jargon
==== Diferencia ====
and is done like this:

<syntaxhighlight>
La diferencia de una forma con otra se llama "corte" en el argot de OCC/FreeCAD y se hace así:
cylinder = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
</div>
sphere = Part.makeSphere(5,Base.Vector(5,0,0))

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

{{Code|code=
cylinder = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
sphere = Part.makeSphere(5, App.Vector(5, 0, 0))
diff = cylinder.cut(sphere)
diff = cylinder.cut(sphere)
}}
</syntaxhighlight>
{{Top}}
==== Intersection ====
<span id="Intersection"></span>
The same way, the intersection between 2 shapes is called "common" and is done
<div class="mw-translate-fuzzy">
this way:
==== Intersección ====
<syntaxhighlight>

cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
del mismo modo, la intersección entre dos formas es denominada "común" y se hace de este modo:
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1))
</div>

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

{{Code|code=
cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
common = cylinder1.common(cylinder2)
common = cylinder1.common(cylinder2)
}}
</syntaxhighlight>
{{Top}}
==== Union ====
<span id="Union"></span>
<div class="mw-translate-fuzzy">
==== Unión ====

La unión se llama "fusión" y funciona del mismo modo:
</div>

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

<syntaxhighlight>
{{Code|code=
cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1))
cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
fuse = cylinder1.fuse(cylinder2)
fuse = cylinder1.fuse(cylinder2)
}}
</syntaxhighlight>
{{Top}}
==== Section ====
<span id="Section"></span>
A Section is the intersection between a solid shape and a plane shape.
<div class="mw-translate-fuzzy">
It will return an intersection curve, a compound with edges
==== Sección ====
<syntaxhighlight>

cylinder1 = Part.makeCylinder(3,10,Base.Vector(0,0,0),Base.Vector(1,0,0))
Una sección es la intersección entre una forma de un sólido y una forma de un plano.
cylinder2 = Part.makeCylinder(3,10,Base.Vector(5,0,-5),Base.Vector(0,0,1))
Devolverá una curva de intersección, un componente con aristas
</div>

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

{{Code|code=
cylinder1 = Part.makeCylinder(3, 10, App.Vector(0, 0, 0), App.Vector(1, 0, 0))
cylinder2 = Part.makeCylinder(3, 10, App.Vector(5, 0, -5), App.Vector(0, 0, 1))
section = cylinder1.section(cylinder2)
section = cylinder1.section(cylinder2)
section.Wires
section.Wires
Line 489: Line 735:
<Edge object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>,
<Edge object at 0D86DE18>, <Edge object at 0D9B8E80>, <Edge object at 012A3640>,
<Edge object at 0D8F4BB0>]
<Edge object at 0D8F4BB0>]
}}
</syntaxhighlight>
{{Top}}
==== Extrusion ====
<span id="Extrusion"></span>
Extrusion is the act of "pushing" a flat shape in a certain direction resulting in
<div class="mw-translate-fuzzy">
a solid body. Think of a circle becoming a tube by "pushing it out":
==== Extrusión ====
<syntaxhighlight>

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:
</div>

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

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

If your circle is hollow, you will obtain a hollow tube. If your circle is actually
<div class="mw-translate-fuzzy">
a disc, with a filled face, you will obtain a solid cylinder:
Si tu círculo está hueco, obtendrás un tubo hueco. Si no es hueco, obtendrás un cilindro sólido:
<syntaxhighlight>
</div>

{{Code|code=
wire = Part.Wire(circle)
wire = Part.Wire(circle)
disc = Part.makeFace(wire)
disc = Part.Face(wire)
cylinder = disc.extrude(Base.Vector(0,0,2))
cylinder = disc.extrude(App.Vector(0, 0, 2))
}}
</syntaxhighlight>
{{Top}}
== Exploring shapes ==
<span id="Explore_shapes"></span>
<div class="mw-translate-fuzzy">
== Exploración de formas ==

Puedes explorar fácilmente la estructura de datos topológicos:
</div>

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

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


<div class="mw-translate-fuzzy">
=== Edge analysis ===
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.
In case of an edge, which is an arbitrary curve, it's most likely you want to
</div>
do a discretization. In FreeCAD the edges are parametrized by their lengths.
{{Top}}
That means you can walk an edge/curve by its length:
<span id="Edge_analysis"></span>
<syntaxhighlight>
<div class="mw-translate-fuzzy">
=== 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:
</div>

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

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

Now you can access a lot of properties of the edge by using the length as a
<div class="mw-translate-fuzzy">
position. That means if the edge is 100mm long the start position is 0 and
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.
the end position 100.
</div>
<syntaxhighlight>

anEdge.tangentAt(0.0) # tangent direction at the beginning
{{Code|code=
anEdge.valueAt(0.0) # Point at the beginning
anEdge.valueAt(100.0) # Point at the end of the edge
anEdge.tangentAt(0.0) # tangent direction at the beginning
anEdge.derivative1At(50.0) # first derivative of the curve in the middle
anEdge.valueAt(0.0) # Point at the beginning
anEdge.derivative2At(50.0) # second derivative of the curve in the middle
anEdge.valueAt(100.0) # Point at the end of the edge
anEdge.derivative3At(50.0) # third derivative of the curve in the middle
anEdge.derivative1At(50.0) # first derivative of the curve in the middle
anEdge.derivative2At(50.0) # second derivative of the curve in the middle
anEdge.derivative3At(50.0) # third derivative of the curve in the middle
anEdge.centerOfCurvatureAt(50) # center of the curvature for that position
anEdge.centerOfCurvatureAt(50) # center of the curvature for that position
anEdge.curvatureAt(50.0) # the curvature
anEdge.curvatureAt(50.0) # the curvature
anEdge.normalAt(50) # normal vector at that position (if defined)
anEdge.normalAt(50) # normal vector at that position (if defined)
}}
</syntaxhighlight>
{{Top}}
=== Using the selection ===
<span id="Use_a_selection"></span>
Here we see now how we can use the selection the user did in the viewer.
<div class="mw-translate-fuzzy">
First of all we create a box and shows it in the viewer
=== Utilizando la selección ===
<syntaxhighlight>

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
</div>

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

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

Select now some faces or edges. With this script you can
<div class="mw-translate-fuzzy">
iterate all selected objects and their sub elements:
Selecciona ahora algunas caras o aristas. Con este archivo de guión puedes iterar todos los objetos seleccionados y sus subelementos:
<syntaxhighlight>
</div>

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

Select some edges and this script will calculate the length:
Selecciona algunas aristas y este archivo de guión calculará la longitud:
<syntaxhighlight>

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

print "Length of the selected edges:" ,length
print("Length of the selected edges: ", length)
</syntaxhighlight>
}}
== Complete example: The OCC bottle ==
{{Top}}
A typical example found on the
<span id="Example:_The_OCC_bottle"></span>
[http://www.opencascade.org/org/gettingstarted/appli/ OpenCasCade Getting Started Page]
<div class="mw-translate-fuzzy">
is how to build a bottle. This is a good exercise for FreeCAD too. In fact,
== Examen completo: La botella OCC ==
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
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:
below is also included in FreeCAD installation (inside the Mod/Part folder) and
</div>
can be called from the python interpreter by typing:

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

{{Code|code=
import Part
import Part
import MakeBottle
import MakeBottle
bottle = MakeBottle.makeBottle()
bottle = MakeBottle.makeBottle()
Part.show(bottle)
Part.show(bottle)
}}
</syntaxhighlight>
{{Top}}
=== The complete script ===
<span id="The_script"></span>
Here is the complete MakeBottle script:
<div class="mw-translate-fuzzy">
<syntaxhighlight>
=== El archivo de guión completo ===
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.


Aquí está el archivo de guión completo MakeBottle:
The construction is done side by side and when the cube is finished, it is hollowed out of a cylinder through.
</div>
<syntaxhighlight>

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

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

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

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

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

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

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

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

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

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

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

return myBody

el = makeBottleTut()
Part.show(el)
}}
{{Top}}
<span id="Detailed_explanation"></span>
<div class="mw-translate-fuzzy">
=== Explicación detallada ===
</div>

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

<div class="mw-translate-fuzzy">
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.
</div>

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

<div class="mw-translate-fuzzy">
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.
</div>

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

<div class="mw-translate-fuzzy">
Aquí en realidad definimos la geometría: un arco, creado por 3 puntos, y dos segmentos de línea, creados por 2 puntos.
</div>

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

<div class="mw-translate-fuzzy">
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.
</div>

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

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

<div class="mw-translate-fuzzy">
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.
</div>

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

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

<div class="mw-translate-fuzzy">
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í?
</div>

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

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

<div class="mw-translate-fuzzy">
El cuerpo de nuestra botella está creado, aún tenemos que crear el cuello. Así que creamos un nuevo sólido, con un cilindro.
</div>

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

<div class="mw-translate-fuzzy">
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.
</div>

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

<div class="mw-translate-fuzzy">
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:
</div>

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

<div class="mw-translate-fuzzy">
o, de forma más simple:
</div>
{{Top}}
==Example: Pierced box==

Here is a complete example of building a pierced box.

The construction is done one side at a time. When the cube is finished, it is hollowed out by cutting a cylinder through it.

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


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


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

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


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


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

myMat = App.Matrix()


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


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

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


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


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


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


Part.show(cut_part)
Part.show(cut_part)
}}
</syntaxhighlight>
{{Top}}
== Loading and Saving ==
<span id="Loading_and_saving"></span>
There are several ways to save your work in the Part module. You can
<div class="mw-translate-fuzzy">
of course save your FreeCAD document, but you can also save Part
== Cargando y guardando ==
objects directly to common CAD formats, such as BREP, IGS, STEP and STL.


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.
Saving a shape to a file is easy. There are exportBrep(), exportIges(),
</div>
exportStl() and exportStep() methods availables for all shape objects.

So, doing:
There are several ways to save your work. You can of course save your FreeCAD document, but you can also save [[Part_Workbench|Part]] objects directly to common CAD formats, such as BREP, IGS, STEP and STL.
<syntaxhighlight>

<div class="mw-translate-fuzzy">
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:
</div>

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

this will save our box into a STEP file. To load a BREP,
<div class="mw-translate-fuzzy">
IGES or STEP file, simply do the contrary:
se guardará nuestro cubo en un archivo STEP. Para cargar un archivo BREP, IGES o STEP, simplemente haz lo contrario:
<syntaxhighlight>
</div>

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

To convert an '''.stp''' in '''.igs''' file simply :
To convert a STEP file to an IGS file:
<syntaxhighlight>

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


<div class="mw-translate-fuzzy">
{{docnav|Mesh Scripting|Mesh to Part}}
{{docnav/es|Mesh Scripting/es|Mesh to Part/es}}
</div>


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

{{clear}}
<languages/>

Latest revision as of 18:55, 12 October 2023

Introducción

Aquí te explicaremos cómo controlar el módulo Pieza directamente desde el intérprete de Python de FreeCAD, o desde cualquier guión externo. Asegúrate de navegar por la sección Guionización y las páginas Básicos de Guionización FreeCAD si necesitas más información sobre cómo funciona el guionización de Python en FreeCAD. Si eres nuevo en Python, es una buena idea leer primero la Introducción a Python.

Ver también

Diagrama de clase

Este es un resumen Lenguaje Unificado de Modelado (UML) de las clases más importantes del módulo Pieza:

Clases de Python del módulo Pieza
Clases de Python del módulo Pieza

Inicio

Geometría

Los objetos geométricos son los bloques de construcción de todos los objetos topológicos:

  • Geom Clase base de los objetos geométricos.
  • Línea Una línea recta en 3D, definida por un punto inicial y un punto final.
  • Círculo Círculo o segmento de círculo definido por un punto central y un punto inicial y final.
  • Etc.

Inicio

Topología

Los siguientes tipos de datos topológicos están disponibles:

  • Compuesto Un grupo de cualquier tipo de objetos topológicos.
  • Sólido compuesto Un sólido compuesto es un conjunto de sólidos conectados por sus caras. Amplía las nociones de ALAMBRE y CASCO a los sólidos.
  • Sólido Una parte del espacio limitada por cáscaras. Es tridimensional.
  • Cáscara Conjunto de caras conectadas por sus aristas. Una cáscara puede ser abierta o cerrada.
  • En 2D es parte de un plano; en 3D es parte de una superficie. Su geometría está limitada (recortada) por los contornos. Es bidimensional.
  • Alambre Conjunto de aristas conectadas por sus vértices. Puede ser un contorno abierto o cerrado dependiendo de si las aristas están unidas o no.
  • Arista Elemento topológico que corresponde a una curva restringida. Una arista está generalmente limitada por los vértices. Tiene una dimensión.
  • Vértice Elemento topológico que corresponde a un punto. Tiene una dimensión cero.
  • Forma Término genérico que abarca todo lo anterior.

Inicio

Ejemplo: Crear una topología simple

Hilo

Ahora crearemos una topología construyéndola a partir de una geometría más sencilla. Como caso de estudio utilizaremos una pieza como la que se ve en la imagen que consta de cuatro vértices, dos arcos y dos líneas.

Inicio

Crear geometría

Primero creamos las distintas partes geométricas de este cable. Asegurándonos de que las partes que tienen que ser conectadas más tarde comparten los mismos vértices.

Así que primero creamos los puntos:

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

Inicio

Arco

Círculo


Para cada arco necesitamos un punto de ayuda:

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

Inicio

Línea

Línea


Los segmentos de línea se pueden crear a partir de dos puntos:

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

Inicio

Poniendo todo junto

El último paso es poner los elementos base de la geometría juntos y formar una forma topológica:

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

Inicio

Crear un prisma

Ahora extruir el hilo en una dirección y crear una forma 3D real:

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

Inicio

Mostrar todo

Part.show(P)

Inicio

Crear formas básicas

Puedes crear fácilmente objetos topológicos básicos con los métodos make...() del módulo Pieza:

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

Algunos métodos disponibles make...():

  • makeBox(l, w, h, [p, d]) Hace una caja situada en p y apuntando a la dirección d con las dimensiones (l,w,h).
  • makeCircle(radius) Hace un círculo con un radio determinado.
  • makeCone(radius1, radius2, height) Hace un cono con los radios y la altura dados.
  • makeCylinder(radius, height) Hace un cilindro con un radio y altura dados.
  • makeLine((x1, y1, z1), (x2, y2, z2)) Hace una línea desde dos puntos.
  • makePlane(length, width) Hace un plano con longitud y anchura.
  • makePolygon(list) Hace un polígono a partir de una lista de puntos.
  • makeSphere(radius) Hace una esfera con un radio determinado.
  • makeTorus(radius1, radius2) Hace un toro con los radios dados.

Ver la página Pieza API para una lista completa de los métodos disponibles del módulo Pieza.

Inicio

Módulos de importación

Primero necesitamos importar el módulo Pieza para poder usar su contenido en Python. También importaremos el módulo Base desde dentro del módulo FreeCAD:

import FreeCAD as App
import Part

Inicio

Crear un vector

Vectores son una de las piezas de información más importantes cuando se construir formas. Suelen contener tres números (pero no necesariamente siempre): las coordenadas cartesianas X, Y y Z. Se crea un vector así:

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

Hemos creado un vector en las coordenadas X = 3, Y = 2, Z = 0. En el módulo de la pieza, los vectores se utilizan en todas partes. Las formas de la pieza también utilizan otro tipo de representación de puntos llamada Vértice que es simplemente un contenedor para un vector. Se accede al vector de un vértice así:

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

Inicio

Crear un borde

Un borde no es más que una línea con dos vértices:

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

Nota: También se puede crear un borde pasando dos vectores:

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

Puedes encontrar la longitud y el centro de un borde así:

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

Inicio

Poniendo la forma en la pantalla

Hasta ahora hemos creado un objeto de borde, pero no aparece en ninguna parte de la pantalla. Esto se debe a que la escena 3D de FreeCAD sólo muestra lo que tú le dices que muestre. Para ello, utilizamos este sencillo método:

Part.show(edge)

La función mostrar crea un objeto en nuestro documento de FreeCAD y le asigna nuestra forma "borde". Utilízala siempre que sea el momento de mostrar tu creación en pantalla.

Inicio

Crear un hilo

Un hilo es una línea de varias aristas y puede crearse a partir de una lista de aristas o incluso de una lista de hilos:

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

Inicio

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)

Only faces created from closed wires will be valid. In this example, wire3 is a closed wire but wire2 is not (see above):

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

Sólo las caras tendrán un área, ni los contornos ni las aristas.

Inicio

Crear un círculo

Se puede crear un círculo así:

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

Si quieres crearlo en una cierta posición y con una cierta dirección:

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

ccircle 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, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)
arc2 = Part.makeCircle(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 180, 360)

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

import math
degrees = math.degrees(radians)

Inicio

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.

Unfortunately there is no makeArc() function, but we have the Part.Arc() function to create an arc through three points. It creates an arc object joining the start point to the end point through the middle point. The arc object's toShape() function must be called to get an edge object, the same as when using Part.LineSegment instead of Part.makeLine.

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

Arc 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(App.Vector(0, 0, 0), App.Vector(0, 0, 1), 10)
arc = Part.Arc(circle,0,pi)

Los arcos son aristas válidas, como las líneas. Así que también pueden utilizarse en los contornos.

Inicio

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:

A polygon is simply a wire with multiple straight edges. The makePolygon() function takes a list of points and creates a wire through those points:

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

Inicio

Create a Bézier 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)

Inicio

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:

A Plane is a flat rectangular surface. The method used to create one is makePlane(length, width, [start_pnt, dir_normal]). By default start_pnt = Vector(0, 0, 0) and dir_normal = Vector(0, 0, 1). Using dir_normal = Vector(0, 0, 1) will create the plane facing in the positive Z axis direction, while dir_normal = Vector(1, 0, 0) will create the plane facing in the positive X axis direction:

plane = Part.makePlane(2, 2)
plane
> <Face object at 028AF990>
plane = Part.makePlane(2, 2, App.Vector(3, 0, 0), App.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

Inicio

Creación de una elipse

Para crear una elipse existen varios métodos:

There are several ways to create an ellipse:

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(App.Vector(10, 0, 0), App.Vector(0, 5, 0), App.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(App.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

Inicio

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:

Using makeTorus(radius1, radius2, [pnt, dir, angle1, angle2, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = 0, angle2 = 360 and angle = 360. Consider a torus as small circle sweeping along a big circle. Radius1 is the radius of the big circle, radius2 is the radius of the small circle, pnt is the center of the torus and dir is the normal direction. angle1 and angle2 are angles in degrees for the small circle; the last angle parameter is to make a section of the torus:

torus = Part.makeTorus(10, 2)

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, App.Vector(0, 0, 0), App.Vector(0, 0, 1), 0, 180)

El código de arriba creará una sección del toro

tor=Part.makeTorus(10, 5, App.Vector(0, 0, 0), App.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.

Inicio

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)

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

Inicio

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.

Using makeSphere(radius, [pnt, dir, angle1, angle2, angle3]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0, 1), angle1 = -90, angle2 = 90 and angle3 = 360. Angle1 and angle2 are the vertical minimum and maximum of the sphere, angle3 is the sphere diameter.

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

Inicio

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

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, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)

Inicio

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

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, App.Vector(20, 0, 0), App.Vector(0, 0, 1), 180)

Inicio

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 subtracting one shape from another. Tenlo en cuenta

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

Inicio

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:

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

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

Esto moverá nuestra forma "myShape" 2 unidades en la dirección del eje X.

Inicio

Rotación de una forma

Para rotar una forma, necesitas especificar el centro de rotación, el eje, y el ángulo de rotación:

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

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

El código de arriba rotará la forma 180 grados alrededor del eje Z.

Inicio

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:

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

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

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:

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

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

myShape.transformShape(myMat)

o

myShape.transformGeometry(myMat)

Inicio

Escalando una forma

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

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

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

Inicio

Operaciones Booleanas

Diferencia

La diferencia de una forma con otra se llama "corte" en el argot de OCC/FreeCAD y se hace así:

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

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

Inicio

Intersección

del mismo modo, la intersección entre dos formas es denominada "común" y se hace de este modo:

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

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

Inicio

Unión

La unión se llama "fusión" y funciona del mismo modo:

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

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

Inicio

Sección

Una sección es la intersección entre una forma de un sólido y una forma de un plano. Devolverá una curva de intersección, un componente con aristas

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

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

Inicio

Extrusión

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:

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

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

Si tu círculo está hueco, obtendrás un tubo hueco. Si no es hueco, obtendrás un cilindro sólido:

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

Inicio

Exploración de formas

Puedes explorar fácilmente la estructura de datos topológicos:

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

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.

Inicio

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:

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)

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)

Inicio

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

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

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

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)

Inicio

Examen completo: La botella OCC

Un ejemplo típico encontrado en la 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:

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

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

Inicio

El archivo de guión completo

Aquí está el archivo de guión completo MakeBottle:

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

import FreeCAD as App
import Part, math

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

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

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

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

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

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

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

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

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

    return myBody

el = makeBottleTut()
Part.show(el)

Inicio

Explicación detallada

import FreeCAD as App
import Part, math

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.

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

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.

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

Aquí en realidad definimos la geometría: un arco, creado por 3 puntos, y dos segmentos de línea, creados por 2 puntos.

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

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.

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

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

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.

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

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

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=App.Vector(0, 0, myHeight)
    neckNormal=App.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:

el = makeBottleTut()
Part.show(el)

o, de forma más simple:

Inicio

Example: Pierced box

Here is a complete example of building a pierced box.

The construction is done one side at a time. When the cube is finished, it is hollowed out by cutting a cylinder through it.

import FreeCAD as App
import Part, math

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

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

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

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

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

myMat = App.Matrix()

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

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

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

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

cut_part = mySolid.cut(myCyl)

Part.show(cut_part)

Inicio

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.

There are several ways to save your work. You can of course save your FreeCAD document, but you can also save Part objects directly to common CAD formats, such as BREP, IGS, STEP and STL.

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

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

To convert a STEP file to an IGS file:

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

Inicio

Mesh Scripting/es
Mesh to Part/es