Apr 12, 2018

OpenSCAD Tutorial for Beginners (5 Easy Steps)

OpenSCAD is a powerful, free and open source modelling tool that lets you make precise 3D models with just a few lines of code. With the right setup, you can even make adaptable, "parametric" models. In this OpenSCAD tutorial, we'll get acquainted with the software, review a simple example and then discuss how to make parametric designs.

1a. Downloading and Installing OpenSCAD

Stable releases for Mac OS and Windows Source: OpenSCAD

The latest stable version of OpenSCAD can be downloaded from http://www.openscad.org/downloads.html. The normal downloads at the top of the page provide the latest “stable” version of the software, and the “Development Snapshots” provide experimental versions of OpenSCAD that have a few extra features, but can have more bugs than the stable versions.

Pick the version appropriate to your operating system, open the .exe or .dmg, then follow the instructions to install OpenSCAD.

1b. The OpenSCAD Splash Screen

Source: OpenSCAD

When you open OpenSCAD for the first time, you should be met with the splash screen. In this window, you can create a new file, open an existing one, or open an example. All of the example files are excellently written, and show off the key concepts of how to use OpenSCAD.

In the Examples box, go to Basics > CSG.scad, then click “Open Example” to open the simple CSG example file.

2a. The OpenSCAD Interface: The Text Editor

Source: Michael Jones, OpenSCAD

Let’s begin by checking out the basic sections of an OpenSCAD window. The interface of OpenSCAD is very simple, consisting of only the Text Editor, the Viewing Area and the Console. Code is entered using the Editor, and the resulting model is shown in the Viewing Area. Most of the buttons in the Editor are pretty self-explanatory (New, Open, Save, etc.). The interesting ones are the Preview, Render and Export as STL buttons.

Hitting Preview will generate a quick model in the Viewing Area. This quick model shows the general idea of what the model will look like, but it’s not the final calculated 3D model. Pressing Render tells OpenSCAD to calculate the final 3D model, which shows you the exact readout but takes longer to generate than a preview. After a model is rendered, Export as STL will open up a window to save your model as an STL.

2b. The OpenSCAD Interface: The Viewing Area

Source: Michael Jones, OpenSCAD

The Viewing Area displays the 3D model. The Preview and Render buttons are the same as in the Editor. The two middle clusters of buttons control the “camera” in the Viewer: the left-hand ones allow you to zoom or reset the view, and the right-hand ones snap the camera to standard views.

The last cluster of buttons include the Perspective/Orthogonal buttons, the Show Axes and Show Scale Marker buttons, and the Show Edges button. Switching between Orthogonal and Perspective changes whether the model is shown isometrically or with perspective. (The Orthogonal view is usually better for making mechanical models and Perspective is better for decorative models).

2c. The OpenSCAD Interface: The Console

Source: OpenSCAD

The Console appears below the Viewing Area, and shows technical information regarding calculated models. It also shows a record of when you save or export a model, and displays the readout from echo() statements. Those who aren’t concerned with the under-the-hood technical calculations needn’t worry about the Console.

3. Objects, Actions, Operators and Variables

Every model constructed by OpenSCAD is built from a combination of Objects. Objects are primitive shapes like cubes, cylinders and spheres, and form the backbone of every model. Objects are created by Actions and modified by Operators, with Variables and Comments further enhancing the code.

  • Actions are used to create objects or define variables. For example, Cube(), Cylinder() and Sphere() are actions that create their corresponding primitive Objects.
  • Operators modify Objects. There are lots of different Operators, and they are used to change many different properties of an Object, such as its size or position.
  • Variables contain values such as numbers, strings (i.e. text), vectors and lists. The information stored in variables can be used by Actions, Operators or other variables. (Variables will be discussed a little later in this OpenSCAD tutorial, in Section 5.)
  • Comments are used to provide extra information to anyone reading the code. They’re usually used to provide general information about the code (like the original author and publishing date) and explain the logic and reasoning behind particular lines. Comments do not affect Objects and are effectively ignored when OpenSCAD interprets and renders the code.

(There are also Vectors, Lists, Modules and Functions, but we’ll deal with these advanced concepts in a different OpenSCAD tutorial!)

All of the Objects, Actions and Operators usable by OpenSCAD, along with information on how to use them, can be found in the OpenSCAD User Manual. We’ll stick with the simplest ones for this tutorial, but just remember there’s a huge toolbox to use once you’ve gotten comfortable with the basics.

With that out of the way, let’s take a look at CSG.scad to see some live examples of Actions and Operators!

4a. The CSG.scad Example: Combining Objects with Union

Operators are highlighted in green and Actions are highlighted in orange. (The green text are comments.) Source: Michael Jones, OpenSCAD

Before doing anything, we should save the file under a different name. We’ll be playing around with the code in this tutorial, so we’ll want to keep a safe copy of the original version. Go to File > Save As… and save it as “CSG_tutorial.scad”. Once that’s done, hit the Render button to see the objects that CSG.scad generates. This example makes three separate Objects, using different combinations of Operators and Actions.

Let’s take a closer look at the code. When reading OpenSCAD code, it’s easier to think of things as “blocks” of code, rather than reading it line-by-line. There are three blocks in CSG.scad, whose boundaries are marked by the black lines on the left side of the code. Each block contains two Actions (Cube and Sphere) along with one or two Operators (Translate, Union, Intersection, Difference). 

Let’s take a look at the first block of code (starting at the 3rd line and ending at the 8th line). This block defines the shape on the left of the Viewing Area, the sphere inside the cube. This block of code contains two Operators and two Actions:

  • Translate is an Operator that moves an object according to the given [X,Y,Z] parameters. In this case, it moves an Object -24 mm down the X-axis.
  • Union is an Operator that combines all of the Objects within its curly brackets into a single Object.
  • Cube is an Action that creates a cube Object. In this case, the side of each cube is set to 15 mm, and the “center=true” statement tells the Action to draw the cube from the center.
  • Sphere is an Action that creates a sphere Object. Because the number hasn’t been defined as either a radius or a diameter, OpenSCAD assumes it’s a radius.

This block demonstrates two critical concepts for working in OpenSCAD. The first is that Operators are applied only to the Objects within its boundaries. The Union Operator in this first block only combines the Cube and Sphere that are within its boundaries, and none of the other Objects within this file. Similarly, the Translate Operator in this first block only applies to the Unioned Object. If it didn’t, all the Objects in this file would be centered at -24 on the X-axis! (Also note that the boundary of an Operator is defined with a pair of curly braces, and that everything inside its boundary is indented by one level.)

The next important concept is that OpenSCAD always performs Operations sequentially, starting from the Operator that’s closest to the Object and working outwards. So in this block, the Union operation is performed on the Cube and Sphere first, then the Unioned Object is moved by Translate. Even when working with large, complex combinations of Operators and Actions, start at the innermost Objects/Actions and work backwards until you reach the uppermost Operator.

(Sharp-eyed readers might notice that swapping the Operators in this block wouldn’t have any effect on the resulting Object, as Union would work the same even if the Cube and Sphere were moved first. However, there are lots of times where you need to apply Operations in a specific order, so get used to thinking about applying Operators in sequence!)

4b. The CSG.scad Example: A Note on Syntax

Source: OpenSCAD

This is a good time to mention some important points on syntax. We’ve just seen that the boundaries of Operators are defined by curly braces. However, other bits of syntax like semicolons and indents can also be found throughout the code. Some of these are critical for the file to run, while others are non-essential.

Critical syntax is absolutely necessary for the code to run. If it’s missing or written incorrectly, OpenSCAD will throw an error message when you try to Preview or Render the model. The following are critical syntax in OpenSCAD:

  • The end of each Action statement must end with a semicolon. This includes the Actions that make Objects as well as the Actions that define Variables (see Section 5 for more details about Variable statements).
  • As mentioned above, curly braces (a.k.a. braces, curly brackets) indicate the boundaries of an Operator statement. When working on a complex OpenSCAD project, it can be easy to lose track of all the braces. However, when you click on a brace, OpenSCAD highlights its matching partner, which makes things a little easier when things get complicated.

The non-critical syntax is not necessary for the model to compile. However, it makes the code much easier to read and edit. Examples of non-critical syntax include the following:

  • Indentation is usually increased when you’re within a new Operator, and decreased when the Operator is finished. (In this example, because the Union Operator is inside the Translate Operator, Union is indented by one level. Because Cube and Sphere are inside Union, they’re indented by two levels.) Indenting is not actually necessary for OpenSCAD to run, but keeps the code looking neat and tidy.
  • Line breaks (i.e. hitting the Enter button) and spaces are not strictly necessary for OpenSCAD to run. In theory, you could write the entire first block as a single line and the code will still work: translate(){union(){cube(15,center=true);sphere(10);}} However, taking them out makes the code incredibly hard to read.
  • Comments are denoted with a pair of slashes (“//”).  Everything following a pair of slashes is ignored by OpenSCAD until the beginning of the next line.

(Side Note: For anyone familiar with computer programming, you’ll probably notice that this syntax is essentially the same as C++. OpenSCAD is mostly written in C++ and as a result, inherrits most of its syntax from its parent language. So to anyone familiar with Arduino programming, this should be a breeze!)

4c. The CSG.scad Example: The Intersection Operator

Intersection overlaps: component parts in grey, final part in yellow Source: Michael Jones, OpenSCAD

For the middle Object, a Cube and Sphere are used once again, but are combined using the Intersection Operator instead of Union. When given multiple Objects, Intersection produces an Object that is made from only the parts of each Object that overlap. In other words, if any part of one Object does not intersect with any part of the other Object(s), it’s removed from the final Intersected shape.

After the Sphere Action in the second block, add the following line to the code, then hit the Render button to visualize your changes:

translate([7.5, 0, 0]) { cube(15, center=true); }

This adds an extra cube, which is shifted by half of its length to the right by the extra Translate statement. Notice how only the segment that belongs to all three objects is considered by the Intersection Operator, and the parts that don’t overlap with the other two Objects aren’t included in the final Intersected Object.

Also notice how this second Translate only operates on this second Cube statement. Operators work sequentially, so the Intersection Operation is only performed after the second cube is moved.

4d. The CSG.scad Example: The Difference Operator

Source: Michael Jones, OpenSCAD

The rightmost shape is made using the Difference Operator. Difference subtracts an Object from another Object, making it useful for creating holes and other spaces.

One big change in how Difference works (versus Union or Intersection) is that the Object created depends on the order in which the Actions/Objects appear in the Operator. Try switching the order of Cube and Sphere in this third block. Notice how in the original version of the code, the Sphere is subtracted from the Cube, but switching them around forces the opposite.

5. Parametric OpenSCAD

Now that we’ve walked through the CSG.scad example, let’s talk about parametric design.

In Parametric Design, the user can change certain elements of the model and the rest of the design adapts to accomodate these changes. This allows one, for example, to define different screw diameters without having to manually sift through the code and replace each of the values.

Lets try making the three objects in our CSG_tutorial.scad bigger. Start with the spheres by replacing all of the instances of “sphere(10)” with “sphere(15)“. We also need to make the cubes bigger, so replace “cube(15, center=true)” with “cube(20, center=true)“. If you render the code with these changes, you can see a few problems:

  • The proportion of the sphere radius versus cube size has been thrown off, meaning the final objects don’t look much like the originals anymore
  • For our modified middle (Intersection) object, the object isn’t split down the middle anymore because we didn’t shift our second cube enough
  • The Intersection and Difference objects are overlapping with each other because they haven’t been shifted far enough apart using the Translate Operators.

For the last section of this OpenSCAD tutorial, we’ll be turning our simple example design into a parametric one.

5a. Making a Parametric Model: Defining Variables

Source: Michael Jones, OpenSCAD

We could try to fix these problems manually, but then we’d need to fix them every time we wanted to change the size of the objects. Instead, let’s make this a proper parametric design.

The key step in making a parametric file is defining variables instead of using plain numbers. A variable is made using a type of Action statement, and once it’s defined, we can use the variable anywhere we could use a number.

Add the following Action statement somewhere in the top of the file (it can be before or after the comment on the first line, but not after the first block of code):

sphere_radius = 10;

This creates a variable named “sphere_radius” and makes it equal to 10. 

Next, go through the code and replace every number inside every Sphere Action with sphere_radius (like in the image above). Try rendering the file, then changing sphere_radius and render the file again. You should see the radius of every sphere changing in response to sphere_radius.

5b. Making a Parametric Model: Defining More Variables

Source: Michael Jones, OpenSCAD

Make the cube size parameterized in the same way as the sphere radius by defining a variable cube_length and setting it to 15 (for now). Like above, replace all of the numbers inside each Cube statement with cube_length.

Now we can set both the sphere radius and the cube length for all of the objects in the model. But how can we keep the Cube and Sphere proportional to each other without calculating it ourselves? Time to make some Dependent Variables!

5c. Making a Parametric Model: Dependent Variables

Source: Michael Jones, OpenSCAD

One convenient thing about variables is that they can be defined using other variables. Variables that use other variables in their definitions are known as Dependent Variables (as opposed to Independent Variables, which don’t rely on anything).

If we have sphere_radius and cube_length set independently, we have the potential to lose the original proportions of the cube size versus the sphere size. However, we can change cube_length to a Dependent Variable by changing the definition of cube_length to the following:

cube_length = sphere_radius * 1.5;

While we’re on the topic, you can also change the Translate operator we added in Step 4c from a firm X-coordinate to a parametric one by replacing translate([7.5, 0, 0]) with translate(). Now, the middle Object will be cleanly cut down the middle every time!

Note that a Dependent Variable always needs to be defined after the Variable definition(s) it uses. OpenSCAD reads the code line-by-line, so if you try to define cube_length without defining sphere_radius, OpenSCAD won’t know what to do.

5d. Making a Parametric Model: Additional Dependent Variables

Source: Michael Jones, OpenSCAD

The last thing to fix is the poor spacing between the objects whenever the sphere size is changed. To remedy this, create a variable to control the spacing between each object:

object_separation = sphere_radius * 2 + 4;

Insert this Action after the definition of cube_length, then replace the  in Line 7 and [24,0,0] in Line 20 with  and , respectively. Now, try rendering the code with different values of sphere_radius: even when the objects get bigger, they should always be separated from each other by 4 mm!

What's Next?

Perfect re-scaling with a parametric design Source: Michael Jones, OpenSCAD

Now that you’ve mastered the basics with this OpenSCAD tutorial, it’s time to start making some designs of your own! Read over the documentation and play around with the different Operators and Actions that OpenSCAD offers. You can even start looking into trickier concepts like Vectors and Loops, which make it easier to design complex models.

And of course, practice makes perfect! Just sit yourself down and try designing something you can print. You’ll surprise yourself with what you can do on your first try!

License: The text of "OpenSCAD Tutorial for Beginners (5 Easy Steps)" by All3DP is licensed under a Creative Commons Attribution 4.0 International License.

Subscribe to updates from All3DP

You are subscribed to updates from All3DP

You can’t subscribe to updates from All3DP. Learn more…Subscribe

You can’t subscribe to updates from All3DP. Learn more…