Topological data scripting/ro

Această pagină descrie mai multe metode pentru crearea și modificarea modulelor Forms of parts din Python. Înainte de a citi această pagină, dacă sunteți nou la Python, este o idee bună să citiți despre python scripting and how python scripting works in FreeCAD.

Introducere
Aici vă vom explica cum să controlați Part Module direct de la interpretorul FreeCAD Python sau de la orice script extern. Elementele de bază despre programarea script datelor topologice sunt descrise în Part Module Explaining the concepts. fiți siguri că a-ți răsfoit secțiunea Scripting și paginile FreeCAD Scripting Basics dacă aveți nevoie de mai multe informații despre cum funcționaează programarea python in FreeCAD.

Class Diagram
Aceasta Unified Modeling Language (UML) o trecere în revistă a celor mai importante clase a modului Piese:

Geometrie
Obiectele geometrice reprezintă blocul de construcție al tuturor obiectelor topologice:
 * Geom Clasă de bază a obiectelor geometrice
 * Line o linie dreaptă în 3D, definită de punctul de plecare și de cel de sosire
 * Circle Cerc sau arc de cerc definit prin centru și punctele de start și de finiș
 * ...... Și în curând mai multe

Topologie
Următoarele date topologice sunt disponibile: Geometria sa este constrânsă(tăiată) de contururi. Este bidimensională.
 * Compound Un grup al oricărui tip de obiect topologic.
 * Compsolid Un solid compozit este un set de solide conectate prin fațetele lor. Extinde noțiunile de WIRE și SHELL la solide.
 * Solid O partea a spațiului limitată de cochilii. Are trei dimensiuni
 * Shell Un set da fațete conectate prin muchiile lor. O cochilie poate fi deschisă sau închisă.
 * Face In 2D este o parte a unui plan; in 3D este o  parte a unei suprafețe.
 * Wire Un set de margini conectate prin vârfurile lor. Poate fi un contur deschis sau închis, în funcție de faptul dacă marginile sunt legate sau nu.
 * Edge Un element topologic corespunzător unei curbe reținute. O margine este în general limitată de vârfuri. Este unidimensională.
 * Vertex Un element topologic corespunzător unui punct. Are dimensiune zero.
 * Shape Un termen generic care acoperă toate cele de mai sus.

Exemplul rapid: crearea unei topologii simple


Acum vom crea o topologie construind-o din geometrie mai simplă. Ca studiu de caz, folosim o parte din imaginea din care face parte patru vârfuri, două cercuri și două linii.

Crearea Geometriei
Mai întâi trebuie să creăm părțile geometrice distincte ale acestui fir. Și trebuie să avem grijă de vârfurile părților geometrice se se afle în aceeași poziție. Altfel, mai târziu, s-ar putea să nu fim capabil să conectăm părțile geometrice la o topologie!

Așa creăm primul dintre puncte:

Arc


Pentru a crea un arc de cerc vom face un punct ca reper și vom crea arcul de cerc prin trei puncte:

Linie


Segmentul de linie poate fi creat foarte simplu din punctele:

Notă: in FreeCAD 0.16 Part.Line a fost utilizată, pentru FreeCAD 0.17 Part.LineSegment va fi folosit

Punem totul laolaltă
Ultimul pas este de a pune împreună elementele de bază geometrice și coaceți o formă topologică:

Facem o prismă
Acum extrudem firul într-o direcție și facem o formă 3D :

Crearea formelor de bază
Puteți crea cu ușurință obiecte topologice de bază cu ajutorul funcției "Make ... " metode de la modulul Part:

Câteva metode disponibile de make... : Vezi pagina Part API pentru o listă completa a metodelor disponibile în modulul Part.
 * makeBox(l,w,h): Construirea unui paralelipiped localizat în punctul p orientat în direcția d având dimensiunile (l,w,h)
 * makeCircle(radius): Construirea cercului cu o rază dată
 * makeCone(radius1,radius2,height): Construirea unui con cu (raza1,raza2,înălțime)
 * makeCylinder(radius,height): Construirea unui cilindru cunoscând raza și înălțimea.
 * makeLine((x1,y1,z1),(x2,y2,z2)): Construirea unei linii între 2 puncte
 * makePlane(length,width): construirea unui plan cunoscând lungimea și lățimea
 * makePolygon(list): construirea unui poligon având o listă de puncte
 * makeSphere(radius): Construirea unei sfere de rază dată
 * makeTorus(radius1,radius2): construirea unui torus cuoscând raza 1 și raza 2

Importare modulelor necesare
Mai întâi trebuie să importem modulul Partajare astfel încât să putem folosi conținutul său în Python. De asemenea, vom importa modulul Base din interiorul modulului FreeCAD:

Crearea unui Vector
Vectorssunt una dintre cele mai importante piese de informații când construim forme geometrice. Acestea conțin 3 numere de obicei (dar nu este obligatoriu întotdeauna) coordonatele carteziene x, y și z. Creați un vector ca acesta un vector ca acesta:

Tocmai am creat un vector la coordonatele x = 3, y = 2, z = 0. În modulul Part, vectorii sunt folosiți peste tot. Formele de Piese utilizează de asemenea un alt tip de punct reprezentare, numită Vertex, care nu este nimic altceva decât un container pentru un vector. Accesați vectorul unui vârf ca acesta:

Crearea unei muchii
O margine nu este altceva decât o linie cu două vârfuri:

Notă: De asemenea, puteți crea o margine definită de doi vectori:

You can find the length and center of an edge like this:

Putting the shape on screen
So far we created an edge object, but it doesn't appear anywhere on screen. This is because we just manipulated python objects here. The FreeCAD 3D scene only displays what you tell it to display. To do that, we use this simple method:

An object will be created in our FreeCAD document, and our "edge" shape will be attributed to it. Use this whenever it's time to display your creation on screen.

Creating a Wire
A wire is a multi-edge line and can be created from a list of edges or even a list of wires:

Part.show(wire3) will display the 4 edges that compose our wire. Other useful information can be easily retrieved:

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

Only faces will have an area, not wires nor edges.

Creating a Circle
A circle can be created as simply as this:

If you want to create it at certain position and with certain direction:

ccircle will be created at distance 10 from origin on x and will be facing towards x axis. Note: makeCircle only accepts Base.Vector for position and normal but not tuples. You can also create part of the circle by giving start angle and end angle as:

Both arc1 and arc2 jointly will make a circle. Angles should be provided in degrees, if you have radians simply convert them using formula: degrees = radians * 180/PI or using python's math module (after doing import math, of course):

Creating an Arc along points
Unfortunately there is no makeArc function but we have Part.Arc function to create an arc along three points. Basically it can be supposed as an arc joining start point and end point along the middle point. Part.Arc creates an arc object on which .toShape has to be called to get the edge object, the same way as when using Part.LineSegment instead of Part.makeLine.

Arc only accepts Base.Vector for points but not tuples. arc_edge is what we want which we can display using Part.show(arc_edge). You can also obtain an arc by using a portion of a circle:

Arcs are valid edges, like lines. So they can be used in wires too.

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

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

Creating a Plane
A Plane is simply a flat rectangular surface. The method used to create one is this: makePlane(length,width,[start_pnt,dir_normal]). By default start_pnt = Vector(0,0,0) and dir_normal = Vector(0,0,1). Using dir_normal = Vector(0,0,1) will create the plane facing z axis, while dir_normal = Vector(1,0,0) will create the plane facing x axis:

BoundBox is a cuboid enclosing the plane with a diagonal starting at (3,0,0) and ending at (5,0,2). Here the BoundBox thickness in y axis is zero, since our shape is totally flat.

Note: makePlane only accepts Base.Vector for start_pnt and dir_normal but not tuples

Creating an ellipse
To create an ellipse there are several ways:

Creates an ellipse with major radius 2 and minor radius 1 with the center in (0,0,0)

Create a copy of the given 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, and located in the plane defined by Center and the normal (0,0,1)

In the above code we have passed S1, S2 and center. Similarly to Arc, Ellipse also creates an ellipse object but not edge, so we need to convert it into edge using toShape to display.

Note: Arc only accepts Base.Vector for points but not tuples

for the above Ellipse constructor we have passed center, MajorRadius and MinorRadius

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

The above code will create a torus with diameter 20(radius 10) and thickness 4 (small cirlce radius 2)

The above code will create a slice of the torus

The above code will create a semi torus, only the last parameter is changed i.e the angle and remaining angles are defaults. Giving the angle 180 will create the torus from 0 to 180, that is, a half torus.

Creating a box or cuboid
Using makeBox(length,width,height,[pnt,dir]). By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)

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

Creating a Cylinder
Using makeCylinder(radius,height,[pnt,dir,angle]). By default pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360

Creating a Cone
Using makeCone(radius1,radius2,height,[pnt,dir,angle]). By default pnt=Vector(0,0,0), dir=Vector(0,0,1) and angle=360

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

Translating a shape
Translating is the act of moving a shape from one place to another. Any shape (edge, face, cube, etc...) can be translated the same way: This will move our shape "myShape" 2 units in the x direction.

Rotating a shape
To rotate a shape, you need to specify the rotation center, the axis, and the rotation angle: The above code will rotate the shape 180 degrees around the Z Axis.

Generic transformations with matrixes
A matrix is a very convenient way to store transformations in the 3D world. In a single matrix, you can set translation, rotation and scaling values to be applied to an object. For example: Note: FreeCAD matrixes work in radians. Also, almost all matrix operations that take a vector can also take 3 numbers, so those 2 lines do the same thing: When our matrix is set, we can apply it to our shape. FreeCAD provides 2 methods to do that: transformShape and transformGeometry. The difference is that with the first one, you are sure that no deformations will occur (see "scaling a shape" below). So we can apply our transformation like this: or

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

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

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

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

Section
A Section is the intersection between a solid shape and a plane shape. It will return an intersection curve, a compound with edges

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

Exploring shapes
You can easily explore the topological data structure: By typing the lines above in the python interpreter, you will gain a good understanding of the structure of Part objects. Here, our makeBox command created a solid shape. This solid, like all Part solids, contains faces. Faces always contain wires, which are lists of edges that border the face. Each face has at least one closed wire (it can have more if the face has a hole). In the wire, we can look at each edge separately, and inside each edge, we can see the vertexes. Straight edges have only two vertexes, obviously.

Edge analysis
In case of an edge, which is an arbitrary curve, it's most likely you want to do a discretization. In FreeCAD the edges are parametrized by their lengths. That means you can walk an edge/curve by its length: 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.

Using the selection
Here we see now how we can use the selection the user did in the viewer. First of all we create a box and shows it in the viewer Select now some faces or edges. With this script you can iterate all selected objects and their sub elements: Select some edges and this script will calculate the length:

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

The complete script
Here is the complete MakeBottle script:

Detailed explanation
We will need,of course, the Part module, but also the FreeCAD.Base module, which contains basic FreeCAD structures like vectors and matrixes. 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. Here we actually define the geometry: an arc, made of 3 points, and two line segments, made of 2 points. 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. 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. 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? Then, the body of our bottle is made, we still need to create a neck. So we make a new solid, with a cylinder. 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. Then, we return our Part solid as the result of our function. At the end we call the definite function and make the part visible.

Box pierced
Here a complete example of building a box pierced.

The construction is done side by side and when the cube is finished, it is hollowed out of a cylinder through.

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

Saving a shape to a file is easy. There are exportBrep, exportIges, exportStl and exportStep methods availables for all shape objects. So, doing: this will save our box into a STEP file. To load a BREP, IGES or STEP file, simply do the contrary: To convert an .stp in .igs file simply : 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