# OpenSCAD User Manual/Other Language Features
## Special variables

Special variables provide an alternate means of passing arguments to modules and functions. All user, or OpenSCAD, defined variables starting with a '$' are special variables, similar to special variables in lisp. Modules and function see all outside variables in addition to those passed as arguments or defined internally.
Currently valid special variable names can only be composed of $ followed by simple characters and underscores [a-zA-Z0-9_] and do not allow high-ascii or unicode characters.
The value for a regular variable is assigned at compile time and is thus static for all calls.
Special variables pass along their value from within the scope (see scope of variables) from which the module or function is called. This means that special variables can potentially have a different value each time a module or function is called.
This is useful when multiple arguments need to be passed thru several layers of module calls.
Several special variables are already defined by OpenSCAD.

### Circle resolution: $fa, $fs, and $fn

The $fa, $fs, and $fn special variables control the number of facets used to generate an arc:
$fa is the minimum angle for a fragment. Even a huge circle does not have more fragments than 360 divided by this number. The default value is 12 (i.e. 30 fragments for a full circle). The minimum allowed value is 0.01. Attempting to set a lower value causes a warning.
$fs is the minimum size of a fragment. The default value is 2 so very small circles have a smaller number of fragments than specified using $fa. The minimum allowed value is 0.01. Attempting to set a lower value causes a warning.
$fn is number of fragments and usually has the default value of 0. When this variable has a value greater than zero, the other two variables are ignored, and a full circle is rendered using this number of fragments.
The higher the number of fragments, the more memory and CPU consumed; large values can bring many systems to their knees. Depending on the design, $fn values, and the corresponding results of $fa & $fs, should be kept small, at least until the design is finalised when it can be increased for the final result. A $fn over 128 is not recommended or only for specific circumstances, and below 50 would be advisable for performance.
You can also use two different values for preview and render
TIP: If you want to create a circle/cylinder/sphere which has an axis aligned integer bounding box (i.e. a bounding box that has integral dimensions, and an integral position) use a value of $fn that is divisible by 4. The circular shape appears as a faceted polygon that is inscribed within the radius or diameter provided.
When $fa and $fs are used to determine the number of fragments for a circle, then OpenSCAD never uses fewer than 5 fragments.
This is the C code that calculates the number of fragments in a circle:
Or you can embed this OpenSCAD version in your code to work out what's going on, you need to set r= to your size
Spheres are first sliced into as many slices as the number of fragments being used to render a circle of the sphere's radius, and then every slice is rendered into as many fragments as are needed for the slice radius. You might have recognized already that the pole of a sphere is usually a pentagon. This is why.
The number of fragments for a cylinder is determined using the greater of the two radii.
The method is also used when rendering circles and arcs from DXF files. The variables have no effect when importing STL files.
You can generate high resolution spheres by resetting the $fX values in the instantiating module:
or simply by passing the special variable as parameter:
You can even scale the special variable instead of resetting it:

### Animation: $t

The $t variable is used in "rotate" and "translate" for animation, $t*360 giving complete cycles. To start animation, select Window\Animate and enter values for "FPS" and "Steps". The "Time" field shows the current value of $t as a decimal fraction.
The value of $t will repeat from 0 through (1 - 1/Steps). It never reaches 1 because this would produce a "hitch" in the animation if using it for rotation -- two consecutive frames would be at the same angle.
There is no variable to distinguish between the cases of animation running at the first frame ($t=0) and animation not running, so make $t=0 your rest position for the model.

#### Simple harmonic motion

translate ([0, 0, 10*sin($t*360)])
sphere(2);
gives a sphere that oscillates between -10 and +10 on the Z-axis.

#### Rotation

rotate ([0, 0, $t*360])
square(5);
rotates a square around one corner around the Z-axis. To rotate the square about its middle, use:
rotate ([0, 0, $t*360])
square(5, center=true);

#### Part-rotation

All parts in an animation complete one cycle of motion in the same time, $t, jump back to zero, and start again. However, the cycles can be given different numbers of steps, to give the illusion of different speeds in the same animation. This can be used to animate meshing gears of different sizes.
rotate([0, 0, $t*360/17])
gear(teeth=17);
and
rotate([0, 0, -$t*360/31])
gear(teeth=31);

#### Circular orbit

rotate ([0, 0, $t*360])
translate ([10, 0])
square(5, center=true);

#### Circular orbit without rotation

rotate ([0, 0, $t*360])
translate ([9, 0])
rotate ([0, 0, -$t*360])
square(5, center=true);

#### Elliptical orbit

translate([10*sin($t*360), 20*cos($t*360)])
square(2, center=true);
Note that with "translate", the object does not rotate.

#### Elliptical motion

e=10;
rotate([0, 0, $t*360])
translate([e, 0])
rotate([0, 0, -$t*720])
square([2*e, 2], center=true);
If "Dump Pictures" is checked, then images are created in the same directory as the .scad file. The exported PNG files can be turned into a gif via command line:
where -delay 10 is the duration of each frame in milliseconds, and -loop 0 specifies the number of loops (0 = loop forever).
The Linux convert command is part of ImageMagick, which can also be installed on macOS and Windows. Additional parameters are possible for cropping and scaling.

### Viewport: $vpr, $vpt, $vpf and $vpd

These contain the current viewport rotation and translation and camera distance - at the time of doing the rendering. Moving the viewport does not update them. During an animation they are updated for each frame.
* $vpr shows rotation
* $vpt shows translation (i.e. won't be affected by rotate and zoom)
* $vpf shows the FOV (Field of View) of the view [Note: Requires version 2021.01]
* $vpd shows the camera distance [Note: Requires version 2015.03]
Example
which makes the cube change size based on the view angle, if an animation loop is active (which does not need to use the $t variable)
You can also make bits of a complex model vanish as you change the view.
All four variables are writable, but only assignments at the top-level of the main file has an effect on the viewport. [Note: Requires version 2015.03]
Example
which allows a simple 360 degree rotation around the Z axis in animation mode.
The menu command Edit - Paste Viewport Rotation/Translation copies the current value of the viewport, but not the current $vpr or $vpt.

### Execution mode: $preview

[Note: Requires version 2019.05]
$preview is true, when in OpenCSG preview (F5). $preview is false, when in render (F6).
This can, for example, be used to reduce detail during preview to save time, without losing detail in the final rendered result:
Note that the render module does not affect $preview:
Another use could be to make the preview show an assembly view and the render generate just the printed parts laid out for printing.
If printed parts need extra features that are removed post printing, for example support for suspended holes, then the preview can omit these to show the finished part after post processing.
When OpenSCAD is run from the command line $preview is only true when generating a PNG image with OpenCSG. It is false when generating STL, DXF and SVG files with CGAL. It is also false when generating CSG and ECHO files. This may or may not be what you want, but you can always override it on the command line like any other variable with the -D option.

## Echo module

The echo module prints the contents to the compilation window (aka Console). Useful for debugging code. Also see the String function str.
Numeric values are rounded to 5 significant digits.
It can be handy to use 'variable=variable' as the expression to easily label the variables, see the example below.
Usage examples:
Shows in the Console as
Note that the output will not have the extra double quotes and commas if converted to a string using str.

### Rounding examples

An example for the rounding:
Shows in the Console as

### HTML

HTML output is not officially supported, however depending on the OpenSCAD version, some HTML tags were rendered in the console window.

## Echo function

[Note: Requires version 2019.05]
Echo can be used in expression context to print information while the function/expression is evaluated. The output is generated before the expression evaluation to allow debugging of recursive functions.
Example
A more complex example shows how echo can be used in both descending and ascending path of a recursive function. The result helper function is a simple way to output the value of an expression after evaluation.
Example printing both input values and result of recursive sum

## render

Forces the generation of a mesh even in preview mode. This is useful in certain situations, e.g. when the boolean operations become too slow to track.
Render can also be used (typically in conjunction with convexity) to avoid/workaround preview artifacts. See also OpenSCAD User Manual/FAQ#Why are some parts (e.g. holes) of the model not rendered correctly?
Usage examples: (Needs description)

## surface

Surface reads Heightmap information from text or image files.
Parameters

### file

    String. The path to the file containing the heightmap data.

### center

    Boolean. This determines the positioning of the generated object. If true, object is centered in X- and Y-axis. Otherwise, the object is placed in the positive quadrant. Defaults to false.

### invert

    Boolean. Inverts how the color values of imported images are translated into height values. This has no effect when importing text data files. Defaults to false.: The geometry that results from using this parameter is positioned with its top in the z = 0 plane. A thin "footprint" layer, one unit thick, is added automatically just below the height map.:: [Note: Requires version 2015.03]

### convexity

    Integer. The convexity parameter specifies the maximum number of front sides (back sides) a ray intersecting the object might penetrate. This parameter is only needed for correctly displaying the object in OpenCSG preview mode and has no effect on the final rendering.

### Text file format

The format for text based height maps is a matrix of numbers which represent the heights for specific points. Rows are mapped in Y-axis direction, columns in X axis direction, with one unit increment between adjacent rows and columns. The numbers must be separated by spaces or tabs. Empty lines and lines starting with a # character are ignored.

### Images

[Note: Requires version 2015.03]
Currently only PNG images are supported. Alpha channel information of the image is ignored and the height for the pixel is determined by converting the color value to Grayscale using the linear luminance for the sRGB color space (Y = 0.2126R + 0.7152G + 0.0722B). The gray scale values are scaled to be in the range 0 to 100.
A thin "footprint" layer, one unit thick, is added automatically just below the height map.

### Examples

Example 1:
Result:
Example 2
Example 3:
[Note: Requires version 2015.03]
Example 4:
[Note: Requires version 2015.03]
* PNG Test File
* 3D Surface

## search

The search function is a general-purpose function to find one or more (or all) occurrences of a value or list of values in a vector, string or more complex list-of-list construct.

### Search usage

    search( match_value , string_or_vector [, num_returns_per_match [, index_col_num ] ] );

### Search arguments

* match_value
   * Can be a single string value. Search loops over the characters in the string and searches for each one in the second argument. The second argument must be a string or a list of lists (this second case is not recommended). The search function does not search for substrings.
   * Can be a single numerical value.
   * Can be a list of values. The search function searches for each item on the list.
   * To search for a list or a full string give the list or string as a single element list such as ["abc"] to search for the string "abc" (See Example 9) or [[6,7,8]] to search for the list [6,7,8]. Without the extra brackets, search looks separately for each item in the list.
   * If match_value is boolean then search returns undef.
* string_or_vector
   * The string or vector to search for matches.
   * If match_value is a string then this should be a string and the string is searched for individual character matches to the characters in match_value
   * If this is a list of lists, v=[[a0,a1,a2...],[b0,b1,b2,...],[c0,c1,c2,...],...] then search looks only at one index position of the sublists. By default this is position 0, so the search looks only at a0, b0, c0, etc. The index_col_num parameter changes which index is searched.
   * If match_value is a string and this parameter is a list of lists then the characters of the string are tested against the appropriate index entry in the list of lists. However, if any characters fail to find a match a warning message is printed and that return value is excluded from the output (if num_returns_per_match is 1). This means that the length of the output is unpredictable.
* num_returns_per_match (default: 1)
   * By default, search only looks for one match per element of match_value to return as a list of indices
   * If num_returns_per_match > 1, search returns a list of lists of up to num_returns_per_match index values for each element of match_value.
      * See Example 8 below.
   * If num_returns_per_match = 0, search returns a list of lists of all matching index values for each element of match_value.
      * See Example 6 below.
* index_col_num (default: 0)
   * As noted above, when searching a list of lists, search looks only at one index position of each sublist. That index position is specified by index_col_num.
   * See Example 5 below for a simple usage example.

### Search usage examples

    See example023.scad included with OpenSCAD for a renderable example.

#### Index values return as list

| Example | Code | Result |
| 1 | search("a","abcdabcd"); | [0] |
| 2 | search("e","abcdabcd"); | |
| 3 | search("a","abcdabcd",0); | [[0,4]] |
| 4 | data=[ ["a",1],["b",2],["c",3],["d",4],["a",5],["b",6],["c",7],["d",8],["e",9] ]; search("a", data, num_returns_per_match=0); | [[0,4]] (see also Example 6 below) |

#### Search on different column; return Index values

Example 5:
Outputs:

#### Search on list of values

Example 6: Return all matches per search vector element.
Returns:
Example 7: Return first match per search vector element; special case return vector.
Returns:
Example 8: Return first two matches per search vector element; vector of vectors.
Returns:

#### Search on list of strings

Example 9:
Returns

#### Getting the right results
## OpenSCAD version

version and version_num returns the OpenSCAD version number.
* The version function returns the OpenSCAD version as a vector of three numbers, e.g. [2011, 9, 23]
* The version_num function returns the OpenSCAD version as a number, e.g. 20110923

## parent_module(n) and $parent_modules

$parent_modules contains the number of modules in the instantiation stack. parent_module(i) returns the name of the module i levels above the current module in the instantiation stack. The stack is independent of where the modules are defined. It's where they're instantiated that counts. This can, for example, be used to build a BOM (Bill Of Material).
Example:

## assert

[Note: Requires version 2019.05]
see also Assertion (software development)
Assert evaluates a logical expression. If the expression evaluates to false, the generation of the preview/render is stopped, and an error condition is reported via the console. The report consists of a string representation of the expression and an additional string (optional) that is specified in the assert command.
Parameters

### condition

    Expression. The expression to be evaluated as check for the assertion.

### message

    String. Optional message to be output in case the assertion failed.

### Example

The simplest example is a simple assert(false);, e.g. in a file named assert_example1.scad.
This example has little use, but the simple assert(false); can be used in code sections that should be unreachable.

### Checking parameters

A useful example is checking the validity of input parameters:

### Adding message

When writing a library, it could be useful to output additional information to the user in case of an failed assertion.

### Using assertions in function

Assert returns its children, so when using it in a function you can write
* ↑ https://github.com/openscad/openscad/issues/4275