0% found this document useful (0 votes)
161 views60 pages

Free Cad

The document discusses using Python for scripting in FreeCAD. It describes how Python can be used to control FreeCAD, perform operations, and access FreeCAD modules. It provides examples of using Python to create geometric shapes like boxes, spheres, and cylinders from the Part module and perform operations like extrusion, fusion, and subtraction on shapes. The document also discusses using Python to access properties of objects, modify shapes by moving, rotating, and scaling them, and control the FreeCAD user interface.

Uploaded by

Namrata Ghag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
161 views60 pages

Free Cad

The document discusses using Python for scripting in FreeCAD. It describes how Python can be used to control FreeCAD, perform operations, and access FreeCAD modules. It provides examples of using Python to create geometric shapes like boxes, spheres, and cylinders from the Part module and perform operations like extrusion, fusion, and subtraction on shapes. The document also discusses using Python to access properties of objects, modify shapes by moving, rotating, and scaling them, and control the FreeCAD user interface.

Uploaded by

Namrata Ghag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

FREECAD

• Python is a programming language that it relatively easy to learn and


understand.

• It is open-source and multi-platform, and can be used for many purposes:


from simple shell scripts to very complex programs.

• But its most widespread use is as a scripting language embedded in other


applications. That is how it is used inside FreeCAD.

• From the Python console, or from custom scripts, you can control FreeCAD
and make it perform very complex operations.
• There are several ways to use Python in FreeCAD:

– From the FreeCAD Python interpreter, where you can issue commands
in a "command line"-style interface.

– From macros, which are a convenient way to quickly add a missing tool
to the FreeCAD interface.

– From external scripts, which can used to create quite complex


solutions, even entire Workbenches.
• Before proceeding with Python scripting, go to Edit → Preferences →
General → Output window and check two boxes:

– Redirect internal Python output to report view.

– Redirect internal Python errors to report view.


• Then go to View → Panels and check:

– Report view.
• There are two ways to write Python code in FreeCAD.

– Python console (select View → Panels → Python console)

– Macro editor (select Macro → Macros...).

• In the console you write Python commands one by one, executing them
by pressing Enter, while macros can contain more complex code made up
of several lines, executed only when the macro is executed.
Python console
• To create a new empty document, type the following command in the
Python Console.

doc=FreeCAD.newDocument()
• Usually names that begin with a capital letter are attributes, they contain
a value, while names that begin with a lower case letter are functions (also
called methods), they "do something". Names that begin with an
underscore are usually there for the internal working of the module, and
you shouldn't care about them.
box=doc.addObject("Part::Box", "Box1")

doc.recompute()

box.Height

box.Height = 5
• Vectors

– Vectors are a very fundamental concept in any 3D application. A vector


is a list of 3 numbers (x, y and z), describing a point or position in 3D
space.
• Placement

box.Placement

box.Placement.Base

box.Placement.Base = sumvec
The geometric properties of the cube, such as its dimensions, position, etc.
are stored in the Object. While its visual properties, such as its color, line
thickness, etc. are stored in the ViewObject.

vo = box.ViewObject

vo.Transparency = 80

vo.hide()

vo.show()
Modules
• The different FreeCAD modules are not automatically loaded in the Python
console. This is to avoid having a very slow startup. Modules are loaded
only when you need them.

import Part

Part
Mesh
• Meshes are a very simple kind of 3D object, used for example
by Sketchup, Blender and 3D Studio Max. They are composed of 3
elements: points (also called vertices), lines (also called edges) and faces.

• Mesh objects and FreeCAD objects are different things. You can see the
FreeCAD object as a container for a Mesh object. So in order to add a
mesh object to FreeCAD, we must first create a FreeCAD object and a
Mesh object, then add the Mesh object to the FreeCAD object:
doc=FreeCAD.newDocument()

import Mesh

mymesh = Mesh.createSphere()

mymesh.Facets

mymesh.Points

meshobj = doc.addObject("Mesh::Feature", "MyMesh")

meshobj.Mesh = mymesh

doc.recompute()
Part
• The Part Module is the most powerful module in the whole of FreeCAD. It
allows you to create and manipulate BRep objects. BRep stands for
"Boundary Representation". A BRep object is defined by surfaces that
enclose and define an inner volume.

• The Part module works the same way as the Mesh module: You create a
FreeCAD object, a Part object, then add the Part object to the FreeCAD
object:
doc=FreeCAD.newDocument()

import Part

myshape = Part.makeSphere(10)

myshape.Volume

myshape.Area

shapeobj = doc.addObject("Part::Feature", "MyShape")

shapeobj.Shape = myshape

doc.recompute()

#Note: you can shorten the last three lines to:

#Part.show(myshape)
• FreeCAD features many more modules, such as Sketcher and Draft that
also create Part objects. These modules add additional parameters to the
objects created, or even implement a whole new way to handle the Part
geometry in them. Our box example above is a perfect example of a
parametric object. All you need to define the box is to specify the
parameters height, width and length. Based on those, the object will
automatically calculate its Part shape. FreeCAD allows you to create such
objects in Python.
doc=FreeCAD.newDocument()

import Draft

rec = Draft.makeRectangle(5, 2)

mvec = FreeCAD.Vector(4, 4, 0)

Draft.move(rec, mvec)

Draft.move(box, mvec)
Interface
• The FreeCAD user interface is made with Qt, a powerful graphical
interface system, responsible for drawing and handling all the controls,
menus, toolbars and buttons around the 3D view. Qt provides a
module, PySide, which allows Python to access and modify Qt interfaces
such as FreeCAD's.

from PySide import QtGui

QtGui.QMessageBox.information(None, "CADD Centre", "Parametric


Modelling with Python")
Hands-on
# Create Points

import Part

from FreeCAD import Base

V1 = Base.Vector(0, 10, 0)

V2 = Base.Vector(30, 10, 0)

V3 = Base.Vector(30, -10, 0)

V4 = Base.Vector(0, -10, 0)
# Create Arcs

VC1 = Base.Vector(-10, 0, 0)

C1 = Part.Arc(V1, VC1, V4)

VC2 = Base.Vector(40, 0, 0)

C2 = Part.Arc(V2, VC2, V3)


# Create Lines

L1 = Part.LineSegment(V1, V2)

L2 = Part.LineSegment(V3, V4)

# Combine

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


# Extrude

W = Part.Wire(S1.Edges)

P = W.extrude(Base.Vector(0, 0, 10))

Show it all

Part.show(P)
Make methods
• You can easily create basic topological objects with the make...() methods
from the Part Module:

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

Part.show(b)
• 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 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.


Edge
• An edge is nothing but a line with two vertices:
edge = Part.makeLine((0, 0, 0), (10, 0, 0))
edge.Vertexes

• You can also create an edge by passing two vectors:


vec1 = Base.Vector(0, 0, 0)
vec2 = Base.Vector(10, 0, 0)
line = Part.LineSegment(vec1, vec2)
edge = line.toShape()
Part.show(edge)
• You can find the length and center of an edge like this:

edge.Length

edge.CenterOfMass
Wire
• A wire is a multi-edge line and can be created from a list of edges or even a list
of wires:
edge1 = Part.makeLine((0, 0, 0), (10, 0, 0))
edge2 = Part.makeLine((10, 0, 0), (10, 10, 0))
wire1 = Part.Wire([edge1, edge2])
edge3 = Part.makeLine((10, 10, 0), (0, 10, 0))
edge4 = Part.makeLine((0, 10, 0), (0, 0, 0))
wire2 = Part.Wire([edge3, edge4])
wire3 = Part.Wire([wire1, wire2])
wire3.Edges
Part.show(wire3)
• wire3.Length

• wire3.CenterOfMass

• wire3.isClosed()

• wire2.isClosed()
Face
• Only faces created from closed wires will be valid.

face = Part.Face(wire3)

face.Area

face.CenterOfMass

face.Length

face.isValid()

sface = Part.Face(wire2)

face.isValid()
• Circle

circle = Part.makeCircle(10)

circle.Curve

• Arc

from math import pi

arc1 = Part.makeCircle(10, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 0, 180)

arc2 = Part.makeCircle(10, Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 180,


360)
• Arc along points

arc = Part.Arc(Base.Vector(0, 0, 0), Base.Vector(0, 5, 0), Base.Vector(5, 5, 0))

arc

arc_edge = arc.toShape()

Part.show(arc_edge)
• Arc as part of circle

from math import pi

circle = Part.Circle(Base.Vector(0, 0, 0), Base.Vector(0, 0, 1), 10)

arc = Part.Arc(circle,0,pi)
• Polygon

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


Base.Vector(5, 0, 0)])

• Ellipse

eli = Part.Ellipse(Base.Vector(10, 0, 0), Base.Vector(0, 5, 0), Base.Vector(0, 0,


0))

Part.show(eli.toShape())
• torus = Part.makeTorus(10, 2)

• box = Part.makeBox(10, 10, 10)

• sphere = Part.makeSphere(10)

• cylinder = Part.makeCylinder(5, 20)

• cone = Part.makeCone(10, 0, 20)


Modifying Shapes
To move our shape "myShape" 2 units in the X direction.

• myShape = Part.makeBox(2, 2, 2)

• myShape.translate(Base.Vector(2, 0, 0))

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

• myShape.rotate(Base.Vector(0, 0, 0),Base.Vector(0, 0, 1), 180)

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

circle = Part.makeCircle(10)

tube = circle.extrude(Base.Vector(0, 0, 2))

wire = Part.Wire(circle)

disc = Part.Face(wire)

cylinder = disc.extrude(Base.Vector(0, 0, 2))


• Union

cylinder1 = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))

cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1))

fuse = cylinder1.fuse(cylinder2)
• Subtract

cylinder = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))

sphere = Part.makeSphere(5, Base.Vector(5, 0, 0))

diff = cylinder.cut(sphere)
• Intersection

cylinder1 = Part.makeCylinder(3, 10, Base.Vector(0, 0, 0), Base.Vector(1, 0, 0))

cylinder2 = Part.makeCylinder(3, 10, Base.Vector(5, 0, -5), Base.Vector(0, 0, 1))

common = cylinder1.common(cylinder2)
Ex Selection
import Part

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

Gui.SendMsgToActiveView("ViewFit")

for o in Gui.Selection.getSelectionEx():

print(o.ObjectName)

for s in o.SubElementNames:

print("name: ", s)

for s in o.SubObjects:

print("object: ", s)
length = 0.0

for o in Gui.Selection.getSelectionEx():

for s in o.SubObjects:

length += s.Length

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


Ex Bottle
import Part, math

from FreeCAD import Base

def makeBottleTut(myWidth = 50.0, myHeight = 70.0, myThickness = 30.0):

aPnt1=Base.Vector(-myWidth / 2., 0, 0)

aPnt2=Base.Vector(-myWidth / 2., -myThickness / 4., 0)

aPnt3=Base.Vector(0, -myThickness / 2., 0)

aPnt4=Base.Vector(myWidth / 2., -myThickness / 4., 0)

aPnt5=Base.Vector(myWidth / 2., 0, 0)
aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4)

aSegment1=Part.LineSegment(aPnt1, aPnt2)

aSegment2=Part.LineSegment(aPnt4, aPnt5)

aEdge1=aSegment1.toShape()

aEdge2=aArcOfCircle.toShape()

aEdge3=aSegment2.toShape()

aWire=Part.Wire([aEdge1, aEdge2, aEdge3])


aTrsf=Base.Matrix()

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

aMirroredWire=aWire.copy()

aMirroredWire.transformShape(aTrsf)

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

myFaceProfile=Part.Face(myWireProfile)

aPrismVec=Base.Vector(0, 0, myHeight)

myBody=myFaceProfile.extrude(aPrismVec)
myBody=myBody.makeFillet(myThickness / 12.0, myBody.Edges)

neckLocation=Base.Vector(0, 0, myHeight)

neckNormal=Base.Vector(0, 0, 1)

myNeckRadius = myThickness / 4.

myNeckHeight = myHeight / 10.

myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight,


neckLocation, neckNormal)

myBody = myBody.fuse(myNeck)
return myBody

el = makeBottleTut()

Part.show(el)
Ex. Pierced Box
import Part, math

from FreeCAD import Base

size = 10

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

face1 = Part.Face(poly)

face2 = Part.Face(poly)

face3 = Part.Face(poly)

face4 = Part.Face(poly)
face5 = Part.Face(poly)

face6 = Part.Face(poly)

myMat = Base.Matrix()

myMat.rotateZ(math.pi / 2)

face2.transformShape(myMat)

face2.translate(Base.Vector(size, 0, 0))

myMat.rotateZ(math.pi / 2)

face3.transformShape(myMat)
face3.translate(Base.Vector(size, size, 0))

myMat.rotateZ(math.pi / 2)

face4.transformShape(myMat)

face4.translate(Base.Vector(0, size, 0))

myMat = Base.Matrix()

myMat.rotateX(-math.pi / 2)

face5.transformShape(myMat)
face6.transformShape(myMat)

face6.translate(Base.Vector(0, 0, size))

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

mySolid = Part.makeSolid(myShell)

myCyl = Part.makeCylinder(2, 20)

myCyl.translate(Base.Vector(size / 2, size / 2, 0))

cut_part = mySolid.cut(myCyl)

Part.show(cut_part)
• To save

import Part

s = Part.makeBox(10, 10, 10)

s.exportStep("test.stp")

• To open

import Part

s = Part.Shape()

s.read("test.stp")
Macros
• A macro is a Python script that can be added to a toolbar and launched via
a mouse click.

• FreeCAD provides you with a simple text editor (Macro → Macros... →


Create) where you can write or paste scripts.

• Once the script is done, use Tools → Customize... → Macros to define a


button for it that can be added to toolbars.
• Enable the console output in the menu Edit → Preferences → General →
Macro → Show scripts commands in python console.
Ex
• Open FreeCAD
• Create a New file
• Macro menu > Macro Recording
– Name = Cyliner
– Press the ‘Record’ button.
• Create a Cylinder
– Radius = 5
– Height = 15
• Macro menu > Stop Macro Recording
• Macro menu > Macros
• In the ‘Execute Macro’ dialog, Select the created Macro > Edit
– Check the Code
Adding shortcuts
• Of course it is not practical to load a macro in the editor in order to use it.
FreeCAD provides much better ways to use your macro, such as assigning
a keyboard shortcut to it or putting an entry in the menu. Once your
macro is created, all this can be done via the Tools → Customize menu.
Creating macros without recording
• You can also directly copy/paste python code into a macro, without
recording GUI action. Simply create a new macro, edit it, and paste your
code. You can then save your macro the same way as you save a FreeCAD
document. Next time you start FreeCAD, the macro will appear under the
"Installed Macros" item of the Macro menu.

You might also like