OpenSCAD: CAD for People Who Would Rather Type

Every CAD package I have tried wants me to draw. Click a face, drag a handle, nudge a dimension, discover an hour later that the sketch is under-constrained and the whole model collapses when you change one number. I am not a designer and I was never going to get good at it.

OpenSCAD is the one that finally made sense, because it is not a drawing program. It is a programming language whose output happens to be a solid. You write a description of the object, it compiles that into geometry, and you export the geometry as an STL. There is no mouse in the loop at all.

Which means all the things you already have work on it. The model is a text file, so it goes in git and git diff tells you what changed between the version that fitted and the version that did not. A model with a variable at the top is a model that fits a different board when you change one number. If you can write a function, you can do this.

We are going to build a parametric enclosure with a press-fit lid, because it teaches nearly everything worth knowing and because you will actually use it.

Install, and one setting worth finding

Grab a build from openscad.org/downloads.html. I am deliberately not naming a version here — the project has gone long stretches between tagged releases while shipping development snapshots, so what counts as “current” depends on when you are reading this. Everything in this post is core language that has worked for years and will keep working.

One thing to look for once it is open: if your build offers a Manifold geometry backend in Preferences, turn it on. It is a newer engine than the long-standing CGAL one and it renders complex models considerably faster. On a box with a few holes you will not notice. On anything with a lot of boolean operations you very much will.

The language, in about five minutes

There are three ideas and then you are mostly done.

Primitives. cube(), cylinder(), sphere(), and their 2D cousins square() and circle(). Units are millimetres by convention — nothing enforces it, but your slicer will assume it.

Transforms. translate(), rotate(), scale(), mirror(). The one thing that trips up every newcomer: a transform applies to the statement immediately after it, not to everything following. Group with braces when you mean several.

Booleans. union(), difference(), intersection(). This is where the thinking happens, and difference() is the one you will live in: it takes the first child and subtracts every child after it. Hollowing a box, drilling a hole, cutting a slot — all the same operation.

// a 20mm cube with a 10mm hole bored through it
difference() {
    cube([20, 20, 20], center = true);
    cylinder(h = 30, d = 10, center = true, $fn = 64);
}

// transforms bind to the NEXT statement only
translate([30, 0, 0]) cube(5);      // this cube moves
                      cube(5);      // this one does not

// so group them
translate([60, 0, 0]) {
    cube(5);
    translate([0, 0, 10]) cube(5);
}

That $fn = 64 is worth explaining. Curves do not exist — a cylinder is a prism with enough sides to look round. $fn sets that count outright; $fa and $fs set it indirectly by maximum angle and minimum fragment size. Leave it low while you work and raise it before you export, because a model full of $fn = 200 will make previewing miserable for no visible benefit.

Variables are not what you think they are

OpenSCAD looks imperative and is not. Assignments are resolved at compile time, and within a scope the last one wins — so a variable you “change” halfway down the file was never the old value at all, not even in the lines above. This bites everyone once:

w = 10;
echo(w);     // prints 20, not 10
w = 20;

Treat the variables at the top of the file as constants for that run and you will have no trouble. If you genuinely need a value to vary, that is what module parameters and for loops are for.

Parameters at the top, geometry underneath

Here is the discipline that makes this worth doing: nothing below the parameter block contains a number. If a dimension appears twice you have a bug waiting to happen, and if it appears once as a named value then changing it changes everything downstream for free.

/* [Inner cavity] */
inner_x   = 60;    // what has to fit, X
inner_y   = 40;    // what has to fit, Y
inner_z   = 25;    // what has to fit, Z

/* [Construction] */
wall_t    = 2.0;   // wall thickness
floor_t   = 2.0;   // base thickness
lid_t     = 2.0;   // lid plate thickness
lip_h     = 4.0;   // how far the lid's lip drops in
clearance = 0.25;  // per-side gap between lip and wall
corner_r  = 3.0;   // outer corner radius
$fn       = 48;

// derived -- never typed twice
outer_x = inner_x + 2 * wall_t;
outer_y = inner_y + 2 * wall_t;
outer_z = inner_z + floor_t;

Those /* [Inner cavity] */ comments are not decoration. OpenSCAD’s Customizer reads them and builds a form out of your parameters with labelled groups, so you get sliders and boxes for the values that matter without writing any UI. Hand the file to someone who does not write code and they can still resize the box.

Modules are functions that return solids

A module is OpenSCAD’s subroutine. It takes parameters, it emits geometry, and you call it like anything else. Which means you refactor a model exactly the way you refactor code: notice you have written the same shape twice, give it a name, call it twice.

Start with the shape everything else is built from. A box with sharp vertical corners prints fine but feels nasty in the hand, and there is no fillet() — so you build a rounded prism out of four cylinders and let hull() shrink-wrap them:

// rounded rectangular prism: four cylinders in a hull
module rbox(x, y, z, r) {
    hull()
        for (dx = [r, x - r], dy = [r, y - r])
            translate([dx, dy, 0]) cylinder(h = z, r = r);
}

Six lines, and it is the only place rounded corners are implemented. hull() takes the convex hull of its children, so four pillars at the corners become a solid with rounded sides. The for with two assignments iterates both — a nested loop in one line, giving the four corners.

Now the box is one subtraction, and the lid is a plate with a rim hanging off it. One more derived value first: the lip only has to locate the lid, not hold the weight of anything, so it can be thinner than the wall.

lip_t = wall_t / 2;    // derived: the lip locates, it does not carry

module box() {
    difference() {
        rbox(outer_x, outer_y, outer_z, corner_r);

        // the cavity. deliberately taller than the box so the top is open --
        // a cut that stops exactly flush is a coincident face, see below
        translate([wall_t, wall_t, floor_t])
            rbox(inner_x, inner_y, outer_z + 1, max(corner_r - wall_t, 0.1));
    }
}

module lid() {
    rbox(outer_x, outer_y, lid_t, corner_r);

    // the lip: a rim that drops into the cavity, inset by the clearance
    translate([0, 0, -lip_h])
    difference() {
        translate([wall_t + clearance, wall_t + clearance, 0])
            rbox(inner_x - 2 * clearance, inner_y - 2 * clearance, lip_h,
                 max(corner_r - wall_t - clearance, 0.1));

        translate([wall_t + clearance + lip_t, wall_t + clearance + lip_t, -1])
            rbox(inner_x - 2 * (clearance + lip_t),
                 inner_y - 2 * (clearance + lip_t), lip_h + 2,
                 max(corner_r - wall_t - clearance - lip_t, 0.1));
    }
}

// lay both out for printing: lid flipped so its plate is on the bed
box();
translate([0, outer_y + 10, lid_t]) rotate([180, 0, 0]) lid();

That is the entire enclosure. Change inner_x and both parts follow, because the lid was never given its own dimensions — it derives them from the same numbers the box did. This is the whole reason to work this way.

Notice clearance appears four times in the lid and nowhere in the box. That asymmetry is the one thing standing between a lid that fits and a lid that does not.

Section through the joint: the lid, its lip, and the wall it drops into lid plate lip wall clearance: 0.2-0.3 mm per side lip_h wall_t
The lip is deliberately narrower than the cavity it drops into. That gap is the whole game: model the box and the lid at their nominal sizes and they will not go together, because a nozzle lays down plastic slightly wider than the path it was told to follow. Two or three tenths of a millimetre per side is the usual starting point, and your printer has an opinion you will discover by testing.

Tolerance is the whole game

Model a 40 mm cavity and a 40 mm lip and they will not go together. Not because the maths is wrong — because a 0.4 mm nozzle dragging molten plastic along a path lays down a bead slightly wider than the path, every wall comes out a fraction thick, and every hole a fraction small. Your slicer has opinions, your filament has opinions, and the ambient temperature gets a vote.

So you design the gap in deliberately. For a press-fit lid, 0.2 to 0.3 mm per side is the usual starting point: tight enough to stay shut, loose enough to open without a screwdriver. Snug sliding fits want a little more, and anything that has to rotate wants more again.

Do not test-print the box

Printing a whole enclosure to find out the lid is 0.1 mm too tight costs you two hours. Print one corner instead — wrap the parts in a 20 mm cube intersection, print both fragments, and you have the answer in ten minutes:

intersection() {
    box();                       // or lid()
    cube([20, 20, 100]);
}

Once you know your printer’s number, it is the same number forever. Write it down.

Preview lies. Render tells the truth.

Two keys do different jobs and the difference matters. Preview (F5) is fast and approximate — it draws the CSG operations visually without ever computing the resulting mesh. Render (F6) actually evaluates the geometry, takes much longer, and is what gets exported.

Which means preview will happily show you a model that cannot exist. The classic case is the coincident face: subtract a cavity whose top sits exactly flush with the top of the box, and the two surfaces occupy the same plane. Preview shrugs. Render produces a zero-thickness artefact or a hole in the mesh, and your slicer either repairs it silently or does something baffling.

The fix is in the code above and is worth naming: when you subtract, overshoot. The cavity is outer_z + 1 tall and the lip’s inner void starts at -1 and runs lip_h + 2. Those stray millimetres cut through empty air and cost nothing, and they mean no two surfaces are ever exactly coplanar. Always leave a margin on the thing doing the cutting; never on the thing being kept.

Then F6, then File → Export → Export as STL (or 3MF, which carries units properly), and into the slicer. Print the box as modelled; the lid goes plate-down so the lip prints upward into free air rather than needing support.

Where it stops being the right tool

I like OpenSCAD a great deal and I am not going to pretend it wins everywhere.

  • Fillets and chamfers are genuinely painful. There is no native operation; you build them from hulls and minkowski(), and minkowski() on anything complex is slow enough to make you reconsider your choices. The usual answer is the BOSL2 library, which adds rounding, threads and attachment helpers — worth installing before you need it.
  • There is no constraint solver. Parametric CAD proper lets you say “this face stays tangent to that curve”. Here you say “this is at x = 12.5” and the arithmetic is yours to keep correct.
  • Organic shapes are miserable. If the thing you want is sculpted rather than constructed, this is the wrong room entirely.
  • You cannot measure the model. No click-two-faces-and-read-the-distance. You work out dimensions from the variables that produced them, which is fine when the variables are the point and awkward when you are reverse-engineering someone else’s file.

For brackets, spacers, enclosures, jigs, adapters and anything with a hole pattern to match — which is most of what actually gets printed — it is comfortably the fastest route from idea to STL.

The one-sentence version

OpenSCAD is a programming language that emits solids, so put every dimension in a named variable at the top, build your own primitives as modules and never type a number twice, design the clearance in because the printer will not give it to you, overshoot every cut so no two faces are coplanar, and render with F6 before you believe anything you see.

Next in this series: taking this same file and making it an actual case for something — specifically a weatherproof-ish box for the LoRa repeater, which needs a gland for the antenna, a slot for a solar lead, and a lid I can get off with cold hands.