OpenSCAD User Manual/Language Guide

= Objects =

Primitive Solids
OpenSCAD provides four 3D primitive solids: cube, sphere, cylinder, and polyhedron. Note that surface and import may also be considered as primitive solids.

Primitive Shapes
OpenSCAD provides four 2D primitive shapes: square, circle, polygon, and text.

Transformations
Syntactically, there's no difference between transformations and primitives, both accepts zero or more quantities and zero or more children objects as input and produce a 2D or 3D object as output. However, primitives require no input object (any children are ignored) and generally create an object from quantitative input. Transformations, in general, require input objects as children. If transformations are given no children, most of them behave benignly, producing neither any output, error, nor warning. It is useful to note the syntactical equivalence between primitives and transformation when coding a user defined module, since a user is free to create modules that behave as both primitives and transformations.

The full list of built-in transformations are given below according to this categorization:

projection: 3D to 2D projection
Projection creates either a cross-section or a projection of a 3D object onto the X-Y plane. Cross-section works like a saw that cut the object along the X-Y plane and leaving behind only the 2D shape that is on the plane. Projection works like a sun that is infinitely far away and casting its parallel rays on the object. The projection is the shadow of that object on the X-Y plane. Note that parts of the object both below and above the X-Y plane contribute to the shadow. The original 3D object is discarded after a projection. If a cross-section or projection is needed in addition to the original object, that object has to be recreated separately. This is most conveniently achieved by packing all the code to create the 3D object into a module. Skip the cut parameter or set it  to create a projection. Set the boolean parameter  to create a cross-section.

In order to create projection along an arbitrary direction or a cross-section thru an arbitrary plane, use a combination of rotate and translate prior to projection.

Projections and cross-sections are very useful for extrusion and exportation to DXF formation.

Examples: Consider example002.scad, that comes with OpenSCAD (look in File->Examples->Old): make a cross-section. makes a projection. To make a projection in the Y-axis direction, first rotate it around the X-axis 90 degrees, :

Some additional examples are found in:
 * example021.scad from Clifford Wolf's site.
 * More complicated example from Giles Bathgate's blog

if ... else ...
The conditional object performs a test (evaluates the query expr_Q), and renders either object_T or object_F depending on the truth value of the test result. If object_F was to be nothing, then the portion is optional.

More commonly, the compound statement form of if is used, as exemplified by:

If the result of the conditional evaluation is not an object, but a quantity, use the ? : conditional operator.

While it is allowed to assign variables in the compound form, the scope of those variables is limited to the curly brackets.

The outcome is a small and a large sphere, and in the console:

Note that "a is 10" within the scope of the curly bracket, the corresponding statement need not precede the echo and sphere statements for its effect to apply. After the if statement, the assignment to a is lost, so we "recall" a is still 5. See Scope of variables for more details.


 * Nested if

Since a complete if statement is an object, it can be nested in another if statement. A common form is multiply nested "else if" statements:

if (a > 100) { echo("HUGE!"); sphere(a); // etc... } else if (a > 10) { echo("big."); translate([0,0,10]) sphere(a); // etc... } else if (a > 1) { echo("not so big..."); color("red") sphere(a); } else { echo("Sorry, I lost it."); }

Imported Objects
A number of file formats, including DXF, STL, JPG and TXT can be interpreted by OpenSCAD as objects.

OpenSCAD can also export objects into a number of file formats, however, those are performed by a menu command in the integrated development environment, therefore there are no export counterparts to the import and surface commands.

Null Object
Echo is an exception when classifying OpenSCAD statements. Its functionality has nothing to do with rendering objects, but syntactically it is neither a variable assignment nor an expression (which evaluates to a quantity). Therefore, it is classified as an object, like primitives and transformations, but it produces a null object.

echo
Echo prints out its input parameters as comma-delimited text in the Console (the compilation window). No formatting option is provided. Strings are surrounded by double quotation marks, vectors by square brackets. Multi-dimension vectors are fully represented with the appropriate number of nesting square brackets. It is in general possible to copy/paste the output of echo to use as literals in an OpenSCAD program. Numeric values are rounded to 5 significant digits.

The primary intention of echo is not to format and print beautiful text message to the end-user, but to expose the contents of variables to the programmer for debugging purpose. It is possible to improve the appearance of the output message with some variant forms of echo and using the str function.

The OpenSCAD console supports a subset of HTML markup language. See here for details.

Echo accepts parameters in the format  and produces as output   in which quant is the result of evaluating expr. This form is both decent looking and conveniently can be copied/pasted as valid OpenSCAD code.

Usage examples:

my_h=50; my_r=100; echo("This is a cylinder with h=", my_h, " and r=", my_r); echo(my_h=my_h,my_r=my_r); // shortcut cylinder(h=my_h, r=my_r); // echo( "Hello Qt!" );

Shows in the Console as ECHO: "This is a cylinder with h=", 50, " and r=", 100 ECHO: my_h = 50, my_r = 100 ECHO: "Hello Qt!"

= Operators =

Arithmetic Operators
The scalar arithmetical operators take numbers as operands and produce a new number.

Conditional Operator ? :
An operator that returns either of two expressions depending on the truth value of a query expression. For example:

The expression expr_Q is evaluated and if it's true, expr_T is evaluated and assigned to var; otherwise expr_F is evaluated and assigned to var. If expr_Q evaluated to a non-Boolean result, it gets converted to Boolean, see here.

The conditional operator is essential when creating a recursive function call, since it is used to terminate the recursion, see here.

The conditional operator can be used like a nested  if  also, as in the following example:

= Functions =

Trigonometric Functions
The trigonometric functions use the C Language mathematics library functions. Remember all numbers in OpenSCAD are IEEE double floating points. A good reference for the specifics of the C math library are (math.h) and (acos) at the Open Group website. For a quick reference to the relevant mathematics, see Trigonometric functions.

Note that the trigonometric functions do not work on vectors. Invalid inputs produce nan (e.g. acos(2)) or undef (e.g. sin("2")).

Real Functions
Real functions require numeric inputs and produce numbers, except for rands, which returns a vector of numbers.

Some examples: echo(ceil(4.4),ceil(-4.4));     // ECHO: 5, -4 echo(floor(4.4),floor(-4.4));   // ECHO: 4, -5 echo(exp(1),exp(ln(3)*4));      // ECHO: 2.71828, 81 sign(-5.0); // ECHO -1 sign(0);// ECHO 0 sign(8.0);// ECHO 1 round(5.4); //-> 5 round(5.5); //-> 6 round(5.6); //-> 6 round(-5.4); //-> -5 round(-5.5); //-> -6 round(-5.6); //-> -6

Pseudo Random number generator
Generates a vector of pseudo random numbers. A seed value can be supplied optionally. From the moment a seed value is given, the sequence of pseudo random numbers being generated is deterministic. This provide a convenient way to debug the program using a constant seed value between repeated execution of the program.

always return a vector, which is not the most convenient data type when only a single random number is needed. In order to generate a single random value as a number, use.

Parameters
 * min_value : Minimum value of random number range
 * max_value : Maximum value of random number range
 * value_count : Number of random numbers to return as a vector
 * seed_value (optional) : Seed value for random number generator for repeatable results. On versions before late 2015, seed_value gets rounded to the nearest integer

Usage Examples: // get a single number vec_rand = rands(0,10,1); single_rand = rands(0,10,1)[0]; echo(vec_rand);   // ECHO: [4.44795] echo(single_rand); // ECHO: 7.86455 // get a vector of 4 random numbers with seed value 42 random_vect=rands(5,15,4,42); echo(random_vect); // ECHO: [8.7454, 12.9654, 14.5071, 6.83435]

Vector Functions
cross, norm

max, min

len, concat

lookup

search

String Functions
str,   chr

search

Importing Functions
dxf_cross

dxf_dim

version
= Special Expressions =

List Comprehension
= Functions and Module Definitions =

Function Definition
Note that inside a function definition, variables defined in the main scope is accessible. See variables and scopes.

Recursive function calls
Recursive function calls are supported. Using the Conditional Operator it's possible to ensure the recursion is terminated. Note: There is a built-in recursion limit to prevent an application crash. If the limit is hit, the function returns undef.


 * example

// recursion - find the sum of the values in a vector (array) by calling itself // from the start (or s'th element) to the i'th element - remember elements are zero based function sumv(v,i,s=0) = (i==s ? v[i] : v[i] + sumv(v,i-1,s)); vec=[ 10, 20, 30, 40 ]; echo("sum vec=", sumv(vec,2,1)); // calculates 20+30=50

children
= Pre-processor Commands = include <>

use <>

Note on Library management
= Special Variables = $t

$fn etc

$vpn etc

$parent_modules

= Modifiers = A modifier, when preceding an object, modifies the behavior of the interpreter during preview and rendering for that object or all other objects in the program. They are essential aids to the user when designing even a minimally complicated object.