Topological Data Scripting - FreeCAD Documentation
Topological Data Scripting - FreeCAD Documentation
Introduction
Indice
Here we will explain to you how to control the Part module directly from the
Introduction
FreeCAD Python interpreter, or from any external script. Be sure to browse the
Scripting section and the FreeCAD Scripting Basics pages if you need more See also
information about how Python scripting works in FreeCAD. If you are new to Class diagram
Python, it is a good idea to first read the Introduction to Python. Geometry
Topology
See also Example: Create simple topology
Part scripting Create geometry
OpenCASCADE Arc
Line
Class diagram Put it all together
Make a prism
This is a Unified Modeling Language (UML) (http://en.wikipedia.org/wiki/Unifie Show it all
d_Modeling_Language) overview of the most important classes of the Part Create basic shapes
module: Import modules
Create a vector
Create an edge
Put the shape on screen
Create a wire
https://wiki.freecad.org/Topological_data_scripting 1/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Create a face
Create a circle
Create an arc along points
Create a polygon
Create a Bézier curve
Create a plane
Create an ellipse
Create a torus
Create a box or cuboid
Create a sphere
Create a cylinder
Create a cone
Modify shapes
Transform operations
Translate a shape
Rotate a shape
Matrix transformations
Scale a shape
Boolean operations
Subtraction
Intersection
Union
Section
Extrusion
Explore shapes
https://wiki.freecad.org/Topological_data_scripting 2/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Edge analysis
Use a selection
Example: The OCC bottle
The script
Detailed explanation
Example: Pierced box
Loading and saving
https://wiki.freecad.org/Topological_data_scripting 3/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Top
Geometry
The geometric objects are the building blocks of all topological objects:
Line A straight line in 3D, defined by starting point and end point.
Circle Circle or circle segment defined by a center point and start and end point.
Etc.
Top
Topology
Top
We will now create a topology by constructing it out of simpler geometry. As a case study we will use a part as seen
in the picture which consists of four vertices, two arcs and two lines.
Top
Create geometry
First we create the distinct geometric parts of this wire. Making sure that parts that have to be connected later share
the same vertices.
Top
Arc
https://wiki.freecad.org/Topological_data_scripting 6/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
VC1 = App.Vector(-10, 0, 0)
C1 = Part.Arc(V1, VC1, V4)
VC2 = App.Vector(40, 0, 0)
C2 = Part.Arc(V2, VC2, V3)
Top
Line
L1 = Part.LineSegment(V1, V2)
L2 = Part.LineSegment(V3, V4)
Top
https://wiki.freecad.org/Topological_data_scripting 7/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
The last step is to put the geometric base elements together and bake a topological shape:
Top
Make a prism
W = Part.Wire(S1.Edges)
P = W.extrude(App.Vector(0, 0, 10))
Top
Show it all
Part.show(P)
Top
https://wiki.freecad.org/Topological_data_scripting 8/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
makeBox(l, w, h, [p, d]) 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 the 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 from two points.
makePlane(length, width) Makes a plane with length and width.
makePolygon(list) Makes a polygon from a list of points.
makeSphere(radius) Makes a sphere with a given radius.
makeTorus(radius1, radius2) Makes a torus with the given radii.
See the Part API page for a complete list of available methods of the Part module.
Top
Import modules
First we need to import the FreeCAD and Part modules so we can use their contents in Python:
Top
Create a vector
https://wiki.freecad.org/Topological_data_scripting 9/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Vectors (http://en.wikipedia.org/wiki/Euclidean_vector) are one of the most important pieces of information when
building shapes. They usually contain three numbers (but not necessarily always): the X, Y and Z cartesian
coordinates. You create a vector like this:
myVector = App.Vector(3, 2, 0)
We just created a vector at coordinates X = 3, Y = 2, Z = 0. In the Part module, vectors are used everywhere. Part
shapes also use another kind of point representation called Vertex which is simply a container for a vector. You
access the vector of a vertex like this:
myVertex = myShape.Vertexes[0]
print(myVertex.Point)
> Vector (3, 2, 0)
Top
Create an edge
vec1 = App.Vector(0, 0, 0)
vec2 = App.Vector(10, 0, 0)
line = Part.LineSegment(vec1, vec2)
edge = line.toShape()
https://wiki.freecad.org/Topological_data_scripting 10/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
You can find the length and center of an edge like this:
edge.Length
> 10.0
edge.CenterOfMass
> Vector (5, 0, 0)
Top
So far we created an edge object, but it doesn't appear anywhere on the screen. This is because the FreeCAD 3D
scene only displays what you tell it to display. To do that, we use this simple method:
Part.show(edge)
The show function creates an object in our FreeCAD document and assigns our "edge" shape to it. Use this whenever
it is time to display your creation on screen.
Top
Create a wire
A wire is a multi-edge line and can be created from a list of edges or even a list of wires:
https://wiki.freecad.org/Topological_data_scripting 11/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
> [<Edge object at 016695F8>, <Edge object at 0197AED8>, <Edge object at 01828B20>, <Edge object at 0190A788>]
Part.show(wire3)
Part.show(wire3) will display the 4 edges that compose our wire. Other useful information can be easily retrieved:
wire3.Length
> 40.0
wire3.CenterOfMass
> Vector (5, 5, 0)
wire3.isClosed()
> True
wire2.isClosed()
> False
Top
Create a face
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
Top
https://wiki.freecad.org/Topological_data_scripting 12/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Create a circle
circle = Part.makeCircle(10)
circle.Curve
> Circle (Radius : 10, Position : (0, 0, 0), Direction : (0, 0, 1))
ccircle will be created at distance 10 from the X origin and will be facing outwards along the X axis. Note:
makeCircle() only accepts App.Vector() for the position and normal parameters, not tuples. You can also create
part of the circle by giving a start and an end angle:
Angles should be provided in degrees. If you have radians simply convert them using the formula: degrees =
radians * 180/pi or by using Python's math module:
import math
degrees = math.degrees(radians)
Top
https://wiki.freecad.org/Topological_data_scripting 13/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
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() only accepts App.Vector() for points and not tuples. You can also obtain an arc by using a portion of a
circle:
Arcs are valid edges like lines, so they can be used in wires also.
Top
Create a polygon
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:
Top
https://wiki.freecad.org/Topological_data_scripting 14/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
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)
Top
Create a plane
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 is a cuboid enclosing the plane with a diagonal starting at (3, 0, 0) and ending at (5, 0, 2). Here the
BoundBox thickness along the Y axis is zero, since our shape is totally flat.
Note: makePlane() only accepts App.Vector() for start_pnt and dir_normal and not tuples.
https://wiki.freecad.org/Topological_data_scripting 15/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Top
Create an ellipse
Part.Ellipse()
Creates an ellipse with major radius 2 and minor radius 1 with the center at (0, 0, 0).
Part.Ellipse(Ellipse)
Creates an ellipse centered on the point Center, where the plane of the ellipse is defined by Center, S1 and S2, its
major axis is defined by Center and S1, its major radius is the distance between Center and S1, and its minor radius
is the distance between S2 and the major axis.
Creates an ellipse with major and minor radii MajorRadius and MinorRadius, located in the plane defined by Center
and the normal (0, 0, 1)
https://wiki.freecad.org/Topological_data_scripting 16/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
In the above code we have passed S1, S2 and center. Similar to Arc, Ellipse creates an ellipse object not an edge, so
we need to convert it into an edge using toShape() for display.
Note: Ellipse() only accepts App.Vector() for points and not tuples.
For the above Ellipse constructor we have passed center, MajorRadius and MinorRadius.
Top
Create a torus
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)
The above code will create a torus with diameter 20 (radius 10) and thickness 4 (small circle radius 2)
https://wiki.freecad.org/Topological_data_scripting 17/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
The above code will create a semi torus; only the last parameter is changed. i.e the remaining angles are defaults.
Giving the angle 180 will create the torus from 0 to 180, that is, a half torus.
Top
Using makeBox(length, width, height, [pnt, dir]). By default pnt = Vector(0, 0, 0) and dir = Vector(0, 0,
1).
Top
Create a sphere
Using makeSphere(radius, [pnt, dir, angle1, angle2, angle3]). By default pnt = Vector(0, 0, 0), dir =
Vector(0, 0, 1), angle1 = -90, angle2 = 90 and angle3 = 360. Angle1 and angle2 are the vertical minimum and
maximum of the sphere, angle3 is the sphere diameter.
sphere = Part.makeSphere(10)
hemisphere = Part.makeSphere(10, App.Vector(0, 0, 0), App.Vector(0, 0, 1), -90, 90, 180)
Top
Create a cylinder
https://wiki.freecad.org/Topological_data_scripting 18/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Using makeCylinder(radius, height, [pnt, dir, angle]). By default pnt = Vector(0, 0, 0), dir = Vector(0, 0,
1) and angle = 360.
Top
Create a cone
Using makeCone(radius1, radius2, height, [pnt, dir, angle]). By default pnt = Vector(0, 0, 0), dir =
Vector(0, 0, 1) and angle = 360.
Top
Modify shapes
There are several ways to modify shapes. Some are simple transformation operations such as moving or rotating
shapes, others are more complex, such as unioning and subtracting one shape from another.
Top
Transform operations
Translate a shape
https://wiki.freecad.org/Topological_data_scripting 19/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
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))
Top
Rotate a shape
To rotate a shape, you need to specify the rotation center, the axis, and the rotation angle:
The above code will rotate the shape 180 degrees around the Z Axis.
Top
Matrix transformations
A matrix is a very convenient way to store transformations in the 3D world. In a single matrix, you can set
translation, rotation and scaling values to be applied to an object. For example:
myMat = App.Matrix()
myMat.move(App.Vector(2, 0, 0))
myMat.rotateZ(math.pi/2)
https://wiki.freecad.org/Topological_data_scripting 20/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Note: FreeCAD matrixes work in radians. Also, almost all matrix operations that take a vector can also take three
numbers, so these two lines do the same thing:
myMat.move(2, 0, 0)
myMat.move(App.Vector(2, 0, 0))
Once our matrix is set, we can apply it to our shape. FreeCAD provides two methods for doing that:
transformShape() and transformGeometry(). The difference is that with the first one, you are sure that no
deformations will occur (see Scaling a shape below). We can apply our transformation like this:
myShape.transformShape(myMat)
or
myShape.transformGeometry(myMat)
Top
Scale a shape
Scaling a shape is a more dangerous operation because, unlike translation or rotation, scaling non-uniformly (with
different values for X, Y and Z) can modify the structure of the shape. For example, scaling a circle with a higher
value horizontally than vertically will transform it into an ellipse, which behaves mathematically very differently.
For scaling, we cannot use the transformShape(), we must use transformGeometry():
myMat = App.Matrix()
myMat.scale(2, 1, 1)
myShape=myShape.transformGeometry(myMat)
Top
https://wiki.freecad.org/Topological_data_scripting 21/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Boolean operations
Subtraction
Subtracting a shape from another one is called "cut" in FreeCAD and is done like this:
Top
Intersection
The same way, the intersection between two shapes is called "common" and is done this way:
Top
Union
https://wiki.freecad.org/Topological_data_scripting 22/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Top
Section
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.
Top
Extrusion
Extrusion is the act of "pushing" a flat shape in a certain direction, resulting in a solid body. Think of a circle
becoming a tube by "pushing it out":
circle = Part.makeCircle(10)
tube = circle.extrude(App.Vector(0, 0, 2))
If your circle is hollow, you will obtain a hollow tube. If your circle is actually a disc with a filled face, you will obtain
a solid cylinder:
wire = Part.Wire(circle)
disc = Part.Face(wire)
cylinder = disc.extrude(App.Vector(0, 0, 2))
https://wiki.freecad.org/Topological_data_scripting 23/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Top
Explore shapes
You can easily explore the topological data structure:
import Part
b = Part.makeBox(100, 100, 100)
b.Wires
w = b.Wires[0]
w
w.Wires
w.Vertexes
Part.show(w)
w.Edges
e = w.Edges[0]
e.Vertexes
v = e.Vertexes[0]
v.Point
By typing the lines above in the Python interpreter, you will gain a good understanding of the structure of Part
objects. Here, our makeBox() command created a solid shape. This solid, like all Part solids, contains faces. Faces
always contain wires, which are lists of edges that border the face. Each face has at least one closed wire (it can have
more if the face has a hole). In the wire, we can look at each edge separately, and inside each edge, we can see the
vertices. Straight edges have only two vertices, obviously.
Top
Edge analysis
In case of an edge, which is an arbitrary curve, it's most likely you want to do a discretization. In FreeCAD the edges
are parametrized by their lengths. That means you can walk an edge/curve by its length:
import Part
box = Part.makeBox(100, 100, 100)
https://wiki.freecad.org/Topological_data_scripting 24/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
anEdge = box.Edges[0]
print(anEdge.Length)
Now you can access a lot of properties of the edge by using the length as a position. That means if the edge is 100mm
long the start position is 0 and the end position 100.
Top
Use a selection
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")
Now select some faces or edges. With this script you can iterate over all selected objects and their sub elements:
for o in Gui.Selection.getSelectionEx():
print(o.ObjectName)
for s in o.SubElementNames:
print("name: ", s)
for s in o.SubObjects:
print("object: ", s)
https://wiki.freecad.org/Topological_data_scripting 25/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Select some edges and this script will calculate the length:
length = 0.0
for o in Gui.Selection.getSelectionEx():
for s in o.SubObjects:
length += s.Length
Top
import Part
import MakeBottle
bottle = MakeBottle.makeBottle()
Part.show(bottle)
Top
The script
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.
https://wiki.freecad.org/Topological_data_scripting 26/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
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)
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
Detailed explanation
https://wiki.freecad.org/Topological_data_scripting 27/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
Here we define our makeBottleTut function. This function can be called without arguments, like we did above, in
which case default values for width, height, and thickness will be used. Then, we define a couple of points that will
be used for building our base profile.
...
aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)
aSegment1=Part.LineSegment(aPnt1, aPnt2)
aSegment2=Part.LineSegment(aPnt4, aPnt5)
Here we define the geometry: an arc, made of three points, and two line segments, made of two points.
...
aEdge1=aSegment1.toShape()
aEdge2=aArcOfCircle.toShape()
aEdge3=aSegment2.toShape()
aWire=Part.Wire([aEdge1, aEdge2, aEdge3])
Remember the difference between geometry and shapes? Here we build shapes out of our construction geometry.
Three edges (edges can be straight or curved), then a wire made of those three edges.
...
aTrsf=App.Matrix()
aTrsf.rotateZ(math.pi) # rotate around the z-axis
https://wiki.freecad.org/Topological_data_scripting 28/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
aMirroredWire=aWire.copy()
aMirroredWire.transformShape(aTrsf)
myWireProfile=Part.Wire([aWire, aMirroredWire])
So far we have built only a half profile. Instead of building the whole profile the same way, we can just mirror what
we did and glue both halves together. 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 undergo (move, rotate and scale). After we create the matrix we mirror it, then we create a copy of our
wire and apply the transformation matrix to it. We now have two wires, and we can make a third wire out of them,
since wires are actually lists of edges.
...
myFaceProfile=Part.Face(myWireProfile)
aPrismVec=App.Vector(0, 0, myHeight)
myBody=myFaceProfile.extrude(aPrismVec)
Now that we have a closed wire, it can be turned into a face. Once we have a face, we can extrude it. In doing so, we
make a solid. Then we apply a nice little fillet to our object because we care about good design, don't we?
...
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)
At this point, the body of our bottle is made, but we still need to create a neck. So we make a new solid, with a
cylinder.
...
myBody = myBody.fuse(myNeck)
https://wiki.freecad.org/Topological_data_scripting 29/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
The fuse operation is very powerful. It will take care of gluing what needs to be glued and remove parts that need to
be removed.
...
return myBody
el = makeBottleTut()
Part.show(el)
Finally, we call the function to actually create the part, then make it visible.
Top
The construction is done one side at a time. When the cube is finished, it is hollowed out by cutting a cylinder
through it.
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()
https://wiki.freecad.org/Topological_data_scripting 30/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
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))
cut_part = mySolid.cut(myCyl)
Part.show(cut_part)
Top
Saving a shape to a file is easy. There are exportBrep(), exportIges(), exportStep() and exportStl() methods
available for all shape objects. So, doing:
import Part
s = Part.makeBox(10, 10, 10)
https://wiki.freecad.org/Topological_data_scripting 31/32
01/08/23, 21:48 Topological data scripting - FreeCAD Documentation
s.exportStep("test.stp")
will save our box into a STEP file. To load a BREP, IGES or STEP file:
import Part
s = Part.Shape()
s.read("test.stp")
import Part
s = Part.Shape()
s.read("file.stp") # incoming file igs, stp, stl, brep
s.exportIges("file.igs") # outbound file igs
Top
Estratto da "http://wiki.freecad.org/index.php?title=Topological_data_scripting&oldid=1137946"
Questa pagina è stata modificata per l'ultima volta il 10 mag 2022 alle 11:47.
Il contenuto è disponibile in base alla licenza Creative Commons Attribution, se non diversamente specificato.
https://wiki.freecad.org/Topological_data_scripting 32/32