Difficulty:: Easy.
Next Tutorial: The Pinocchio Example
One of the advantages of using the C++ language to generate mechanical parts is that the designer has at his disposal all the tools C++ provides. The loops are a well example. If you already know OpenScad you may miss the while loop or using the loop counter as a variable.
In this example we will be creating a ring of spheres using a for loop.
The counter of the for loop will be indicate the angle (in polar coords) in which the sphere will be placed.
for (int i=0; i<360; i+=30){ //compute circle coordinates double angle = M_PI*i/180.; double r = 100.; // ... }
As you can see the radius is fixed. Now we change from polar coordinates to cartesian coordinates, as the translate function only accepts cartesian coordinates.
for (int i=0; i<360; i+=30){ //... double x = r*cos(angle); double y = r*sin(angle); //... }These are the x,y coordinates in which the sphere will be placed. Now we only need to generate the OpenScad code for each translated sphere.
We will also draw each sphere with a different color. Colors are useless when generating STL files, but they can be useful in OpenSCAD to distinguish the parts you have designed. To generate an Obj with a parituclar color you just have to invoke the color(r,g,b) function, where rgb is the rgb code in double and between 0 and 1. For example
Component mySphere = Sphere(10,20,4); mySphere.color(1,0,0); //<! set color to red
So to generate the colored spheres we will make:
#include <math.h> #include <components/Sphere.h> #include <core/IndentWriter.h> using namespace std; int main() { IndentWriter writer; // Sphere of radius 20 mm and 100 faces Component sphere = Sphere(20,100); //make a circle of radius 100 of spheres for (int i=0; i<360; i+=30){ //... Component curr_sphere = sphere.translatedCopy(x,y,0); curr_sphere.color(double(i)/360.,(360.-i)/360,0.5); //generate OpenScad Code writer << curr_sphere; //... } std::cout << writer; return 0; }
#include <math.h> #include <components/Sphere.h> #include <core/IndentWriter.h> using namespace std; int main() { IndentWriter writer; // Sphere of radius 20 mm and 100 faces Component sphere = Sphere(20,100); //make a circle of radius 100 of spheres for (int i=0; i<360; i+=30){ //compute circle coordinates double angle = M_PI*i/180.; double r = 100.; double x = r*cos(angle); double y = r*sin(angle); //translate the sphere to the coordinates and change de color Component curr_sphere = sphere.translatedCopy(x,y,0); curr_sphere.color(double(i)/360.,(360.-i)/360,0.5); //generate OpenScad Code writer << curr_sphere; } std::cout << writer; return 0; }
Next Tutorial: The Pinocchio Example