Skip to content

Language Extensions

Revar Desmera edited this page Nov 16, 2026 · 34 revisions

Language Extensions

Sixteen things BelfrySCAD's language can do that OpenSCAD's cannot. Everything else on the language pages behaves as OpenSCAD does; where it falls short instead, that is a difference rather than an addition.

A script using anything here will not run correctly in OpenSCAD — and OpenSCAD will not always tell you. It rejects an unknown module, but silently ignores an unknown argument: children(separate=true) runs there and quietly does something else. Feature detection is how a script says out loud what it needs.

What it adds supported_feature()
render() as an expression Measure geometry you just built render-expr
children(separate=true) Splice forwarded children in as separate statements separate-children
minkowski_difference() Erosion — the inverse of minkowski() minkowski-diff
offset() of a solid Grow or shrink a solid: rounded, sharp or chamfered offset-3d
simplify() Cut a mesh's triangle count simplify-op
mesh_repair() Make an almost-closed mesh into a solid mesh-repair
alpha_wrap() Shrink-wrap geometry in a closed skin alpha-wrap
polyhedron() from a VNF or object Build a solid straight from mesh data polyhedron-vnf
import() in expressions Load JSON, meshes and outlines as data expr-import
import(svg, class=) Import every SVG element carrying a class svg-class
$export_name Let the model name its own export file export-name
export_as() Name the parts in an exported file export-as
sphere(style=) Choose the sphere's tessellation sphere-styles
linear_solve() Solve a linear system, and get its determinant linear-solve
levelset() Build a shape or solid from a field of values, or a function levelset
profile_time() Time a block of geometry, or an expression profile-time
Feature detection Ask, from a script, whether any of the above exist —

render() as an expression

Feature name render-expr — supported_feature("render-expr") is 1 here, 0 where it is missing. Unlike the other extensions, it changes what parses, and no guard can help with that: OpenSCAD reads the whole file before running any of it, so a file holding this form anywhere, even inside an if that never runs, does not load there at all. Keep it in files only BelfrySCAD will open; a library that must also load in OpenSCAD cannot use it.

The problem it solves: a script can build a shape but cannot ask anything about it. Volume, surface area, whether it is watertight, where its bounding box sits — those numbers only exist after the CSG runs, and the language has no way to reach back for them.

part = render() difference() {
    cube([60, 40, 20], center = true);
    cylinder(h = 99, r = 8, center = true);
};

echo(part.volume, part.genus, part.boundingbox);
if (part.genus != 0) echo("warning: this part has through-holes");

It builds its children, measures them, and then discards the geometry — nothing is drawn. The result is an object carrying the measurements and the mesh, so it can go straight back in:

polyhedron(part);        // re-draw what was measured

Full reference: Other Modules ▸ As an expression.

Costs a keyword. render is a reserved word here, so it cannot be a variable, module, function, argument or member name. And obj = render() cube(1); does not parse — the braced form render() { cube(1); } is required.


children(separate=true)

Feature name separate-children — supported_feature("separate-children") is 1 here, 0 where it is missing.

The problem it solves: a forwarded children() is a single statement, however many shapes it carries. So difference() children() gives you the union — there is nothing to subtract from — and a module cannot count, index, or recurse over the children it was handed.

module frame() { difference() children(separate=true); }

frame() {
    cube(50, center=true);   // child 0 -- the positive
    sphere(30);              // subtracted
    cylinder(h=99, r=8);     // subtracted
}

separate=true splices the forward into the surrounding block as one statement per child. Everything else follows from their being real statements — including $children counting them, which is what makes a recursive n-ary module possible:

module peel() {
    echo($children);
    if ($children > 1) peel() { children([1:$children-1], separate=true); }
}
peel() { cube(1); cube(2); cube(3); }      // 3, then 2, then 1

Without it the recursive call sees $children == 1 every time and can never make progress.

intersection() is the case with no workaround at all: for difference you could write difference() { children(0); children([1:$children-1]); }, since A - (B ∪ C) equals A - B - C. That identity does not hold for intersection.

Full reference: Syntax ▸ separate=true.

Costs $children parity. This is the one place $children differs from OpenSCAD. Worse, OpenSCAD does not reject separate=true — it silently ignores it, so a script using this runs there and quietly produces different geometry.

OpenSCAD can only do this through the global --enable=lazy-union, which also reinterprets for, if, let and the top-level union. This is per-call-site and changes nothing that does not ask for it.


minkowski_difference()

Feature name minkowski-diff — supported_feature("minkowski-diff") is 1 here, 0 where it is missing.

The problem it solves: minkowski() only ever grows a shape. Nothing in OpenSCAD shrinks one, so a 3D clearance fit cannot be expressed at all.

// Shrink a part by 0.2 mm so it drops into its pocket
minkowski_difference() {
    my_part();
    sphere(r = 0.2);
}

The first child is the body; each child after it is eroded away from it in turn. 3D only — for 2D, offset(r=-N) already erodes. To shrink a solid by a ball, cube or octahedron, offset() of a solid is simpler; this one erodes by any shape.

Full reference: Other Modules ▸ minkowski_difference.


offset() of a solid

Feature name offset-3d — supported_feature("offset-3d") is 1 here, 0 where it is missing.

The problem it solves: minkowski() with a sphere grows a solid with rounded edges, but nothing in OpenSCAD grows one with its edges kept sharp or chamfered, and nothing shrinks one at all. offset() does all of it, with the arguments it already takes in 2D:

offset(delta = 2)                 block();   // every face out 2, edges and corners sharp
offset(delta = 2, chamfer = true) block();   // edges and corners cut flat
offset(r = 2, $fn = 24)           block();   // rounded
offset(delta = -0.2) peg();                  // a clearance fit, sharp edges kept
  • delta keeps edges and corners sharp, with no miter limit, as in 2D: a sharp edge's corner reaches further than delta. Use chamfer = true to cut it instead.
  • chamfer = true: on a box, the same as minkowski() with an octahedron.
  • r rounds with a faceted ball whose corners lie on the true sphere. Its sides come from $fn/$fa/$fs as in 2D, so with the defaults r = 1 gets only five sides: set $fn.
  • A negative value shrinks: anything thinner than twice the distance disappears, and a part can split in two. A positive one can close a slot or seal a cavity. Both are kept.

The first real child decides between 2D and 3D, as for a boolean, and a child of the other kind is ignored with a warning. Cost grows with the triangle count, around 2 s for a 32-segment sphere, so it is meant for parts, not for dense scanned meshes.

OpenSCAD ignores a solid inside offset() (with a warning) and draws nothing, so guard it:

assert(!is_undef($_SUPPORTED_FEATURE) && supported_feature("offset-3d"),
       "needs BelfrySCAD: OpenSCAD's offset() is 2D only");

Full reference: Transformations ▸ offset.


simplify()

Feature name simplify-op — supported_feature("simplify-op") is 1 here, 0 where it is missing.

The problem it solves: nothing in the language can reduce a triangle count, so density from an import or a library can only be lived with.

simplify(0.05) imported_part();

Moves the surface by no more than tolerance. Works on 2D regions as well as 3D solids.

Full reference: Other Modules ▸ simplify.


mesh_repair()

Feature name mesh-repair — supported_feature("mesh-repair") is 1 here, 0 where it is missing.

The problem it solves: a mesh that is almost closed is not a solid. It draws, but it cannot take part in union(), difference() or intersection(), and nothing in the language could repair it.

mesh_repair(0.0001) isosurface(...);

Welds, drops degenerate faces, fixes the winding, fills holes and strips slivers. import(..., repair=true) has always done this; this applies it to any geometry.

Pass a tolerance. The default is deliberately tight, because welding discards vertices — see the full reference for why a repaired mesh can come out watertight but ugly.

Full reference: Other Modules ▸ mesh_repair.


alpha_wrap()

Feature name alpha-wrap — supported_feature("alpha-wrap") is 2 here (1 before points=), 0 where it is missing.

The problem it solves: a simplified outer shell of a complex model — a "space claim" for an engine, without its bolts and fins — or a closed solid around geometry too broken to use, could not be made with anything in the language. minkowski() with a sphere grows a shape but keeps every hole and slot, and it needs a valid solid to start from.

alpha_wrap(alpha=3, offset=0.5) bracket();
alpha_wrap() import("scan.stl");        // defaults scale with the model
alpha_wrap(alpha=2, points=scan_points); // a point cloud

Wraps all its 3D children together in one closed, manifold skin, as if shrink-wrapped:

  • alpha — the radius of a ball rolled over the input from outside. The skin follows any hollow the ball can get into, and bridges any gap, slot or hole it cannot pass through, so the width that matters is about twice alpha. Large: close to the convex hull. Small: follows fine detail.
  • offset — every point of the skin is this far outside the input, so the result is also a rounded outward offset. Keep it small next to alpha; small keeps sharp features crisper.

With no arguments, alpha is 1/20 of the children's bounding-box diagonal and offset is alpha/30. The skin's triangles are sized by alpha, not taken from the input, so a small alpha on a big model makes a dense mesh and takes longer: a simple part wraps in milliseconds; detailed text at a fine alpha in a few seconds. The skin's flat sides are merged into as few triangles as their shape allows (from 1.91.4); a simplify() with a tolerance near offset goes further by flattening the narrow rounded strips along the edges, at a small cost in volume.

The cut-off between bridged and open is not sharp. A gap up to about 1.5 × alpha wide is bridged cleanly, and one of about 2 × alpha + offset or more stays open; in between it may be bridged only partly, leaving thin strands across it. That is the method, not a fault: CGAL's reference implementation leaves the same strands. Choose alpha clear of that band for the gaps you care about.

It wraps geometry Manifold cannot use — an open polyhedron(), or shapes that overlap without a union() — into one valid solid, so it doubles as a heavy-handed repair. A hole narrower than twice alpha can be wrapped from both sides, giving a thin shell around a sheet. 2D children are left alone, with a warning.

It only ever grows the shape, and edges and corners come out rounded. This is BelfrySCAD's own implementation of the method in Portaneri et al., Alpha Wrapping with an Offset (SIGGRAPH 2022), which CGAL also implements.

Wrapping a point cloud

alpha_wrap(alpha, offset, points=[[x,y,z], ...]); wraps a list of points with no faces, such as a scan or photogrammetry, into one closed solid:

alpha_wrap(alpha=2, points=scan_points);
vnf = render() { alpha_wrap(points=scan_points); };   // the wrapped mesh, as a value

Give points= or children, not both: both together is an error. A list that isn't all [x, y, z] numbers warns and wraps nothing. With no alpha, a point cloud gets the larger of 1/20 of its bounding-box diagonal and 1.5 × the median distance between neighbouring points: with an alpha smaller than the points' spacing, the wrap falls apart into one speck per point.


polyhedron() from a VNF or object

Feature name polyhedron-vnf — supported_feature("polyhedron-vnf") is 1 here, 0 where it is missing.

The problem it solves: mesh data in this ecosystem travels as a VNF — the 2-list [vertices, faces] — but polyhedron() upstream only takes the two halves separately, so every round-trip has to unpack it.

polyhedron(vnf);                        // BOSL2's own shape
polyhedron(spheroid(d = 30));           // any BOSL2 VNF, directly
polyhedron(part);                       // an object from render()
polyhedron(part.vnf);                   // or just its mesh

A 2-list is only read as a VNF when faces was not supplied separately, so the ordinary two-argument call is never reinterpreted.

Full reference: 3D Primitives ▸ polyhedron.


import() in expressions

Feature name expr-import — supported_feature("expr-import") is 1 here, 0 where it is missing.

The problem it solves: upstream import() produces geometry and nothing else. A script cannot read a config file, or inspect a mesh before drawing it.

data  = import("config.json");        // object / list / scalar
vnf   = import("part.stl");           // [ [verts…], [faces…] ]
paths = import("outline.svg");        // [ [[x,y], …], … ]
Extension Value
.json Objects become objects, arrays become lists, null becomes undef
.stl .obj .off .3mf A VNF: [vertices, faces]
.svg .dxf A region: a list of closed paths

Using import("x.json") as a geometry statement is an error — JSON returns data, not geometry.

Full reference: Other Modules ▸ import.


$export_name

Feature name export-name — supported_feature("export-name") is 1 here, 0 where it is missing.

The problem it solves: the export filename is something you retype, rather than a property of the model.

// saved as bracket.scad
echo($export_name);                          // "bracket"

width = 40;
$export_name = str("bracket_", width);       // Export now offers "bracket_40"

Seeded before the script runs with the input file's name minus its extension, and used as the default filename when you Export. A parametric part can name itself after the parameters it was built with.

Full reference: Special Variables ▸ $export_name.


export_as()

Feature name export-as — supported_feature("export-as") is 1 here, 0 where it is missing.

The problem it solves: a file holding several parts gives them no names, and splits them by color — so two touching parts in the same color weld into one, and a slicer lists what is left as Object 1, Object 2.

export_as("jar") jar();
export_as("lid") translate([80, 0, 0]) lid();

Exported as 3MF, OBJ or AMF, that is two objects named jar and lid, whatever their colors and however they touch. The other formats have no object names, and write the geometry as they always have.

  • A named part is always split into its connected pieces. A part that comes out as several objects — disconnected pieces, or several colors — is numbered jar_1, jar_2, ...

  • Geometry outside any export_as() is split and named as before.

  • The name survives transforms, color(), the modifier characters, render() and your own modules. An export_as() inside another one keeps its own name; the outer one names whatever is left.

  • A boolean, hull() or an extrude loses it, because it merges the part with its neighbors into new geometry. That warns:

    WARNING: export_as("jar") is inside union(), which merges it with its siblings, so the name is lost
    

    Put export_as() outside the operation instead: export_as("jar") difference() { ... }.

  • The same name twice warns, and the two become one part.

  • In 3MF the name is the object's name, in OBJ its o line (spaces become _), in AMF its name metadata.

In OpenSCAD, export_as() is an unknown module: it warns and draws nothing inside it. A script meant for both guards it:

module part(name) {
    if (!is_undef($_SUPPORTED_FEATURE) && supported_feature("export-as"))
        export_as(name) children();
    else
        children();
}

part("jar") jar();
part("lid") translate([80, 0, 0]) lid();

See Exporting.


sphere(style=)

Feature name sphere-styles — supported_feature("sphere-styles") is 1 here, 0 where it is missing.

The problem it solves: a sphere's tessellation matters when you are going to boolean against it or print it, and upstream offers only one.

sphere(r = 10, style = "icosa");

"orig" (the default) and "octa" are what OpenSCAD builds; "aligned", "stagger" and "icosa" match BOSL2's spheroid().

Full reference: 3D Primitives ▸ style=.

OpenSCAD is adding style= with "orig" and "octa" (2026.10 test builds); both render the same there as here. The other three styles exist only here, and fall back to "orig" in OpenSCAD. See 3D Primitives ▸ style=.


linear_solve()

r = linear_solve([[2,1],[1,3]], [5,10]);

r.x          // [1, 3]      the solution
r.det        // 5           the determinant
r.singular   // false

One pivoted LU factorization, three answers. They come from the same pass, so asking for all three costs no more than asking for one.

⚠️ BOSL2 defines linear_solve() too, and BOSL2's wins

A user-defined function shadows a builtin of the same name — correct behavior, matching OpenSCAD. So in any script that does include <BOSL2/std.scad>, linear_solve() is BOSL2's, not this one, and it returns the bare solution rather than an object:

include <BOSL2/std.scad>
x = linear_solve(A, b);      // BOSL2's -- a vector, [] if singular
r = linear_solve(A, b).x;    // ERROR: BOSL2's result has no .x

Without the include you get the builtin. The two are intended to converge — BOSL2 dropping its own implementation is the plan — but until then, know which one you are calling.

Leave b out and you get the determinant on its own:

d = linear_solve(A).det;

Solve against the identity and r.x is the inverse:

inv = linear_solve(A, [[1,0,0],[0,1,0],[0,0,1]]).x;

(Spelled out rather than using BOSL2's ident() — including BOSL2 is exactly what shadows this function, per the warning above.)

Setting up a system of equations

Each equation is one row of A — its coefficients, in a consistent variable order — and its right-hand side is one entry of b. Four equations in four unknowns:

 2w +  x +  y +  z = 11          [2, 1, 1, 1]        11
  w + 3x + 2y +  z = 17    ->    [1, 3, 2, 1]        17
 3w +  x + 4y + 2z = 25          [3, 1, 4, 2]        25
  w + 2x +  y + 5z = 28          [1, 2, 1, 5]        28
A = [[2, 1, 1, 1],
     [1, 3, 2, 1],
     [3, 1, 4, 2],
     [1, 2, 1, 5]];

b = [11, 17, 25, 28];

r = linear_solve(A, b);

echo(w = r.x[0], x = r.x[1], y = r.x[2], z = r.x[3]);
//   ECHO: w = 1, x = 2, y = 3, z = 4

r.x comes back in the same variable order you wrote the columns in. Nothing about the call changes with size — 2x2 or 20x20, it is the same two arguments.

Two things worth doing:

Write a missing variable as 0. If one equation is w + z = 5, its row is [1, 0, 0, 1], not [1, 1]. Every row needs an entry for every unknown — a short row leaves the rows unequal, which is not a matrix at all, and the call warns and returns undef.

Check singular before trusting x. Four equations are not necessarily four independent equations — if one is a combination of the others there is no unique answer, and you get singular = true, det = 0, x = undef:

r = linear_solve(A, b);
assert(!r.singular, "these equations do not pin down a unique answer");

For instance, if the fourth equation is just the first two added together, it tells you nothing new — and you get:

ECHO: singular = true, det = 0, x = undef
ERROR: Assertion '!r.singular' failed: "these equations do not pin down a
       unique answer"

Multiplying the answer back is a cheap way to confirm you transcribed the system correctly:

echo(check = A * r.x);      // must equal b
//   ECHO: check = [11, 17, 25, 28]

Why it exists

BOSL2 has linear_solve() and determinant(), both written in OpenSCAD itself. Doing the arithmetic in the evaluator instead is between two and three orders of magnitude quicker.

Solving. Per solve, with BOSL2's load time subtracted and enough repetitions to measure:

n BOSL2's, in OpenSCAD this builtin
4 280 µs 1.5 µs 187×
8 780 µs 2.5 µs 312×
16 2.58 ms 4.0 µs 644×
32 9.6 ms 11 µs 873×
64 42.5 ms 43 µs 988×

A single solve of a small system is fast enough either way — 280 µs is nothing in a render. The difference is worth having when you solve in a loop, or on anything larger.

Two things keep this comparison honest: BOSL2 uses QR where the square path here uses LU, which is less work, and it validates its arguments on every call. It is not the same algorithm being run twice.

Determinants. A bigger gap, because BOSL2's determinant() expands by cofactors for n ≥ 5, which grows as n!:

n BOSL2's determinant() this builtin's .det
10 3.17 s 0.33 s
11 31.49 s 0.33 s

Same matrices, same answers. BOSL2's time multiplies by roughly ten with each extra row; this does not. (Both figures include ~0.22 s of BOSL2 load time, which is most of what linear_solve costs here.)

Singularity is judged relative to the matrix

A singular matrix is reported, not treated as an error — asking whether one is singular is a fair question:

r = linear_solve([[1,2],[2,4]], [1,2]);
r.singular   // true
r.det        // 0
r.x          // undef

The threshold scales with the size of the entries, which matters more than it sounds. BOSL2 compares against a fixed absolute 1e-9, so a perfectly well-conditioned matrix that happens to hold small numbers is declared singular there:

A = [[2e-10, 0], [0, 2e-10]];   // 2*I scaled down -- nothing wrong with it
// BOSL2's:      returns []  -- "singular"
// this builtin: .singular is false, and .x is correct

Any shape of system

The method follows the shape, so you do not choose one:

shape what you get .det
square the solution, by pivoted LU the determinant
more equations than unknowns the least-squares fit, by Householder QR undef
more unknowns than equations the minimum-norm solution undef
// four points, two unknowns -- fit y = a + b*x
fit = linear_solve([[1,0],[1,1],[1,2],[1,3]], [0,1,2,10]).x;   // [-1.4, 3.1]

// one equation, two unknowns -- x + y = 2, smallest such x
mn  = linear_solve([[1,1]], [2]).x;                            // [1, 1]

.det is undef for a non-square matrix, because a determinant is not defined for one.

A non-numeric or ragged matrix warns and returns undef.

One honest limit: rank detection uses a relative tolerance on the diagonal rather than column pivoting, so it cannot always separate a genuinely rank-deficient matrix from a very ill-conditioned one.

Feature name linear-solve — supported_feature("linear-solve") is 1 here, 0 where it is missing.


levelset()

Build a solid — or a 2D shape — from an implicit surface: something defined by a formula or by sampled data rather than by construction. Metaballs, gyroids, blends, scanned fields.

// straight from a function
levelset(function(x,y,z) sqrt(x*x + y*y + z*z),
         bounds   = [[-30,-30,-30],[30,30,30]],
         isovalue = 20,
         edge     = 1.2);          // sample spacing

That is a sphere of radius 20: every point where the distance from the origin equals 20. Change the formula and you change the shape.

blended blobs a gyroid

Neither is reachable any other way. The blobs merge smoothly where they meet — a union() would leave a crease. The gyroid exists only as an equation; there is nothing to build it out of.

Or hand it a grid you already have, field[i][j][k] with i,j,k running along x, y and z:

N = 50;
field = [for (i=[0:N-1]) [for (j=[0:N-1]) [for (k=[0:N-1])
            let(x = -30 + 60*i/(N-1), y = -30 + 60*j/(N-1), z = -30 + 60*k/(N-1))
            sqrt(x*x + y*y + z*z) ]]];

levelset(field, bounds = [[-30,-30,-30],[30,30,30]], isovalue = 20);

bounds is the box the field spans, corner sample to corner sample. Values below isovalue are inside, which is what a distance field wants; pass invert=true for a field where larger means inside.

Placing a grid: bounds, edge, or both

A grid needs one of the two to say where it sits:

  • bounds alone: the corner samples sit on the box corners, and the spacing is worked out from the box and the array size.

  • edge alone: the samples are edge apart (a number, or one spacing per axis), and the grid is centered on the origin, as BOSL2's isosurface() places an array given voxel_size. 2D or 3D comes from the array itself. (Since BelfrySCAD 1.72.0.)

    // the same sphere as above: 50 samples 60/49 apart, centered
    levelset(field, edge = 60/49, isovalue = 20);

In both cases the surface is built directly on your grid, one cube of samples at a time: a voxel's corners are the array's own points, and every vertex lies on a line between two neighboring samples.

  • Both: edge then asks for a different spacing. The field is re-sampled at edge inside bounds, reading between your samples (trilinear interpolation in 3D, bilinear in 2D), and meshed on that new lattice, so voxel corners no longer coincide with the array's points. An edge equal to the grid's own spacing changes nothing. (BOSL2's isosurface() refuses this combination; here it is how to mesh a grid finer or coarser than it was sampled.) A 2D grid is re-sampled the same way, bilinearly.

Ranges: a slice between two levels

Give isovalue two numbers and you get the region between them — a shell rather than a solid:

levelset(function(x,y,z) sqrt(x*x + y*y + z*z),
         bounds   = [[-30,-30,-30],[30,30,0]],   // top half cut away
         isovalue = [15, 20],      // hollow: r=15 to r=20
         edge     = 1);

[low, INF] means at or above, which is the opposite of what a plain number means. That is deliberate — it is the form other libraries pass around, so a range you already have works unchanged.

The top is cut away so the wall thickness shows.

One number is shorthand for [-INF, number]. It is a single pass either way: you could subtract one level set from another and get the same shape, but that builds two meshes and then cuts one from the other.

2D: give it a flat box

Make bounds a pair of 2D corners and you get a shape instead of a solid. Everything else is the same:

// an annulus, ready to extrude
linear_extrude(3)
    levelset(function(x,y) sqrt(x*x + y*y),
             bounds   = [[-30,-30],[30,30]],
             isovalue = [15, 20],
             edge     = 0.5);

A 2D field is field[i][j]. The dimension always comes from bounds, never from guessing at the field, so a mismatch tells you rather than doing something surprising.

Which form to use

Neither is simply better. Measured on the same sphere at matched resolution:

grid function
edge= inferred from the grid required
50³ 0.36 s, −0.244% error 0.35 s, −0.103%
100³ 1.17 s, −0.059% 2.12 s, −0.025%
memory ~550 MB at 200³ no limit

The function form is more accurate, because the mesher chooses its own sample points and can move them toward the true surface, where a grid can only be interpolated between the samples you gave it. It is also the nicer thing to write, and has no memory ceiling.

The grid form is quicker at high resolution, because it can mesh in parallel — nothing has to call back into your script. Use it when you already have sampled data, or when 100³ and above starts to hurt.

Start with the function form; reach for the grid when size or existing data says so.

edge= is required for the function form on purpose. There is no grid to take the spacing from, and cost grows with the cube of it — a silent default would hand you either a useless mesh or a ten-minute render.

A different spacing on each axis

edge can also be a vector, one spacing per axis — [ex, ey, ez], or [ex, ey] for a 2D bounds — as BOSL2's isosurface() takes voxel_size. A thin plate wants fine sampling across it and can be coarse along it:

// 2 units thick, 120 wide: sample z five times finer than x and y
levelset(function(x,y,z) max(abs(x)/60, abs(y)/60, abs(z)),
         bounds = [[-70,-70,-3],[70,70,3]],
         isovalue = 1,
         edge     = [2, 2, 0.4]);

It works for the grid form too, where it sets how finely the grid is re-sampled. The result is exactly the mesh you would get by stretching the field to an equal spacing and stretching the mesh back, so a vector with equal parts gives the same mesh as the plain number. (Since BelfrySCAD 1.70.7.)

Against doing it in script

BOSL2's isosurface() does the same job in OpenSCAD itself. Same sphere, same spacing:

levelset() BOSL2 isosurface()
50³ 0.35 s 2.08 s — 5.9×
100³ 1.17 s (grid) 14.55 s — 12.4×

One field on one machine, so treat it as a range rather than a constant: a costlier formula shifts the balance, and BOSL2's version offers things this primitive does not — metaball specs, 2D, anchors. It is meant to sit under a library like that, not replace it.

Limits

Accuracy on the grid path is bounded by your grid, not by the mesher. It cannot see between your samples.

Two results that look alike and mean opposite things: an isovalue nothing reaches gives you nothing, while one everything satisfies gives you the whole bounds box.

Both 2D and 3D are cut exactly at the edge of bounds — the shape is clipped to the box you asked for, at any resolution, with no ragged border where the surface runs out of the box. A surface that leaves the box, like a gyroid filling it, therefore ends on a flat face rather than a torn one.

Feature name levelset — supported_feature("levelset") is 2 here (1 before per-axis edge, BelfrySCAD 1.70.6 and earlier), 0 where it is missing.


profile_time()

Feature name profile-time — supported_feature("profile-time") is 1 here, 0 where it is missing. The statement form is safe behind a guard, but the expression form (x = profile_time(...) expr;) changes what parses: a file holding it anywhere does not load in OpenSCAD at all, guarded or not.

The problem it solves: finding out which part of a slow model is slow, without commenting things out and re-rendering.

Wrap any block, with a label to tell several apart:

profile_time("gears") {
    for (i = [0:5]) rotate(i * 60) translate([20, 0, 0]) gear();
}

The console then shows how long the block took, split into the time its script code ran and the time its geometry took to build:

PROFILE: gears: 412.37 ms (script 12.40 ms, geometry 399.97 ms)

Or time an expression; the assignment still gets the expression's value:

pts = profile_time("path") bezier_curve(ctrl, 400);
PROFILE: path: 3.12 ms

Put it at the front of a function's body to time every call, and the function still returns what it did. That works for a named function and for a function literal alike:

function smooth(pts, n) = profile_time("smooth") [for (i = [0 : n - 1]) pts[i % len(pts)]];
area = function (r) profile_time("area") PI * r * r;

p = smooth(path, 3000);   // PROFILE: smooth: 2.90 ms
a = area(10);             // PROFILE: area: 0.4 µs

Each call prints its own line, so a function called inside a loop reports once per call.

Good to know:

  • The label is optional. Without one the line names where it is, as in PROFILE: line 12 of part.scad: ....
  • Geometry is reported once it is built. Script code runs first and geometry is built afterwards, so a block's line comes after the script's own ECHO output.
  • A re-render reuses unchanged geometry. When the block's geometry came from the cache, the line says geometry cached instead of a time. Change something inside the block to measure a real rebuild.
  • Short times are in microseconds. Anything under a millisecond prints as µs (script 351.8 µs), so a fast part never reads 0.00 ms.
  • Blocks nest. Each profile_time() reports its own line, and an outer block's time includes the blocks inside it.

Costs a keyword. profile_time is a reserved word here, so it cannot be a variable, module, function, argument or member name.


import(svg, class=)

Feature name svg-class — supported_feature("svg-class") is 1 here, 0 where it is missing.

The problem it solves: one SVG usually holds several jobs — a cut outline, score lines, an engraved logo. Upstream OpenSCAD can pick out one element by id=, which means naming every score line separately.

class= takes them all at once:

linear_extrude(3)   import("panel.svg", id = "outline");   // one element
linear_extrude(0.5) import("panel.svg", class = "score");  // every one marked so

A class attribute is a space-separated list, so class="cut outline" is found by either name. That is the point: a drawing marks each line with what it is, and the script asks for the ones it wants.

id= is upstream's own parameter and needs no guard. Only class= is an extension here.

See Other Modules ▸ Importing part of an SVG for the full rules — enclosing transforms, and what happens when a filter matches nothing.

layer= is not offered for SVG. SVG has no layer concept; what a drawing program calls a layer is a <g> carrying vendor-specific attributes, so the upstream layer= filter only matches files from one particular editor. class= works on any SVG.


Feature detection

The problem it solves: the extensions above fail differently in OpenSCAD, and the quiet failures are the dangerous ones. An unknown module is an error you will see. An unknown argument is silently dropped — children(separate=true) renders the wrong shape there with no warning at all.

What it cannot do: guard new syntax. Two forms are not ordinary calls — render() as an expression and the expression form of profile_time() — and OpenSCAD rejects a file holding either before any check runs, even one inside an if that is never taken. Detection works for everything else on this page, which OpenSCAD parses as plain calls and arguments.

Three things to ask with, all readable from OpenSCAD as well, so the same file works in both:

$_SUPPORTED_FEATURE                      // true here, undef in OpenSCAD
supported_feature("separate-children")   // 1 here, undef in OpenSCAD
$_BELFRYSCAD                             // [1, 38, 0] here, undef in OpenSCAD

$_SUPPORTED_FEATURE says only "supported_feature() is callable here" — it names the capability, not the vendor. Any implementation that adds the function is meant to set it, so if OpenSCAD ever does, a script guarding on it starts working there with no edit.

It also solves the bootstrapping problem: you cannot safely call supported_feature() without first knowing it exists. Check the marker first, wrapped in is_undef():

if (!is_undef($_SUPPORTED_FEATURE) && supported_feature("separate-children"))
    // the extension is available

That is completely silent in OpenSCAD — right branch, no warning. is_undef() is the one way to read a variable there without a complaint about it being unknown, and && short-circuits, so the unknown function is never reached either. Written the shorter way (if ($_SUPPORTED_FEATURE && …)) it still works, but costs one Ignoring unknown variable line.

supported_feature() returns the level at which this build implements a feature, or 0 for one it does not — including a name it has never heard of, so probing for something from a future release is always safe. A level rather than a yes/no, so a feature whose behavior changes later can be told from its earlier self.

Name Feature
render-expr render() as an expression
polyhedron-vnf polyhedron() from a VNF or object
separate-children children(separate=true)
minkowski-diff minkowski_difference()
sphere-styles sphere(style=)
export-name $export_name
export-as export_as()
simplify-op simplify()
mesh-repair mesh_repair(), and import(..., tolerance=)
expr-import import() in expressions
svg-class import(svg, class=)
object-function object() — experimental upstream, always on here
roof-op roof() — method="voronoi" only
discretization-by-error $fe — experimental upstream, always on here
linear-solve linear_solve()
levelset levelset()
profile-time profile_time()
alpha-wrap alpha_wrap()
offset-3d offset() of a solid

Everything listed is at level 1 today, except alpha-wrap, which is at 2 since points=. Nineteen names in all — every extension on this page has one.

The useful shape is an assert, which turns a silent wrong render into a clear stop:

assert(supported_feature("separate-children"),
       "this model needs BelfrySCAD -- children(separate=true) is silently ignored elsewhere");

Or degrade instead of failing:

module frame() {
    if (supported_feature("separate-children")) difference() children(separate=true);
    else difference() { children(0); children([1:$children-1]); }
}

Reading $_BELFRYSCAD or calling supported_feature() directly in OpenSCAD prints one Ignoring unknown variable/unknown function line. The value is undef — falsy — so a guard behaves correctly either way, but !is_undef($_SUPPORTED_FEATURE) && … avoids the warning entirely and is the form to prefer.


Clone this wiki locally