OpenJSCAD User Guide

Welcome to OpenJSCAD User and Programming Guide.



Just for sake of providing context, OpenJSCAD.org is built on OpenJsCad (Github), which itself was inspired by OpenSCAD.org, and essentially provides a programmers approach to develop 3D models. In particular, this enhancement is tuned towards creating precise models for 3D printing.

OpenJSCAD programmers using OpenSCAD may welcome
 * ability to use JavaScript programming concepts and libraries
 * ability to create and manipulate 3D shapes, as well as 2D shapes
 * support for OpenSCAD source-code (approximately 80% of all functions)
 * additional functions to ease the transition to OpenJSCAD

Read on to find about more about OpenJSCAD.

There is also a Quick Reference.

Using OpenJSCAD via Web Browsers
OpenJSCAD can be used immediately by visiting the project website at openjscad.xyz

OpenJSCAD presents a page which shows a 3D viewer, as well as an editor:



From here, you can
 * edit online using the built-in editor, or
 * edit off-line via your favorite editor

You can start editing by dragging a file or a folder to the area indicated.



In order to use your favorite editor, make sure Auto Reload is selected. Any changes to the files will be reloaded automatically.



''Note: Each browser (Firefox, Chrome, IE, etc) supports slightly different functionality. If you are having problems then please try another browser.''

Using OpenJSCAD Offline
OpenJSCAD can be installed locally via GitHub or NPM. You can then use your browser like a locally installed application by opening 'index.html'. To find the location of your index.html you might want to find out where your OpenJSCAD resides. E.g. if OpenJSCAD was installed in /usr/local/lib/node_modules/@jscad/openjscad then will start your webbrowser (Example script works on MacOs)

Local Installation via NPM
OpenJSCAD can be easily installed using Node Version Manager (NVM)
 * 1) Down load and install NVM
 * 2) After installing, type 'nvm install v6
 * 3) Then type 'nvm use v6'

''Note: A LTS version of Node.js > 6.0.0 is required. We test OpenJSCAD using both Node.js version 6.x.x & 7.x.x.''

Now OpenJSCAD can be downloaded and installed by: npm install -g @jscad/openjscad

Local Installation via GitHub
OpenJSCAD can be easily installed from GitHub as well. This is the preferred installation if creating a website for online use. cd base-directory-of-website git clone https://github.com/jscad/OpenJSCAD.org cd OpenJSCAD.org

NOTE: You might need configuration changes to allow access to the some of the contents (examples etc).

Via Web Browser
Once installing locally, OpenJSCAD can be accessed by opening `index.html` with your browser. You can drag and drop a file or a folder to the browser.

Note: Chrome and other browsers do not support drag and drop when offline.

You can drag and drop any of the examples, as well as other designs or files.

Via Command-Line
% cd examples % openjscad logo.jscad % openjscad logo.jscad -o test.stl % openjscad logo.jscad -of stl

which creates ``logo.stl`` or ``test.stl``.

Additional you can import OpenSCAD (.scad), STL ASCII or Binary (.stl) and AMF (.amf) files, and create .jscad, .stl (ASCII or Binary), dxf or .amf: % openjscad example001.scad -o example001.jscad % openjscad example001.scad -o example001.stl % openjscad frog.stl -o frog.jscad % openjscad frog.stl -o frog2.stl            # does actually stl -> jscad -> stl (ascii) % openjscad example001.jscad -o example001.amf % openjscad example001.jscad -of amf         # creates example001.amf % openjscad example001.jscad -of stlb        # creates example001.stl (binary) % openjscad example001.jscad -of stlb -o test.stl


 * -o stands for output
 * -of stands for output format (jscad, stl (default), stla, stlb, amf, dxf)

See also how to pass variables from the CLI to main.

Supported Language / File Formats
Currently following languages and file-formats are supported:

When you drag & drop files, the language or format is set according the file extension (.jscad, etc). When you start to edit directly using your browser, the default language is JSCAD.

Sharing Designs via Direct Link for Local or Remote JSCAD, SCAD, STL and AMF
You can share designs with other people by providing creating special URL which combines OpenJSCAD and Design.

Sharing Online Designs

 * 1) http://openjscad.org/#http://openjscad.org/examples/slices/tor.jscad
 * 2) http://openjscad.org/#http://www.thingiverse.com/download:164128 (STL)
 * 3) http://openjscad.org/#http://pastebin.com/raw.php?i=5RbzVguT (SCAD)
 * 4) http://openjscad.org/#http://amf.wikispaces.com/file/view/Rook.amf/268219202/Rook.amf (AMF)

Sharing Local Designs

 * 1) http://openjscad.org/#examples/slices/tor.jscad
 * 2) http://localhost/OpenJSCAD.org/#examples/slices/tor.jscad

OpenJSCAD Programming Guide
In general, designs are written using the JavaScript language. Training and help about JavaScript can be found online.

Creating a new design starts by writing simple scripts which call CSG functions, and other special functions, as provided by OpenJSCAD. OpenJSCAD executes the script, and renders the 3D design for viewing.

OpenJSCAD adheres to specific standards for passing parameters to functions. But most parameters are optional as default values are provided.

When 3D vectors are required, parameters can be passed as an array. If a scalar (single value) is passed for a parameter which expects a 3D vector, the scalar is used for the x, y and z values. In other words: radius: 1 will give radius: [1,1,1].

NEED EXAMPLE

Anatomy of a OpenJSCAD Script
An OpenJSCAD script must have at least one function defined, the main function, which has to return a CSG object, or an array of non-intersecting CSG objects.

or like this:

But this does not work.

Because all CSG creations, like 3D primitives, have to occur within functions which are called by the main function.

3D Primitives
All rounded solids have a resolution parameter which controls tesselation. If resolution is set to 8, then 8 polygons per 360 degree of revolution are used. Beware that rendering time will increase dramatically when increasing the resolution. For a sphere, the number of polygons increases quadratically with the resolution used. If the resolution parameter is omitted, the following two global defaults are used The former is used for 2D curves (circle, cylinder), the latter for 3D curves (sphere, 3D expand).
 * CSG.defaultResolution2D
 * CSG.defaultResolution3D

OpenSCAD like functions support the fn parameter, which is the number of segments to approximate a sphere (default 32, total polygons per sphere fn*fn).

Cube


Cube or rather boxes can be created like this:

Sphere


Spheres can be created like this:

In case of ``type: 'geodesic'`` the fn tries to match the non-geodesic fn, yet, actually changes in steps of 6 (e.g. fn=6..11 is the same), fn = 1 reveals the base form: the icosahedron.

Note: Creating spheres with high resolution and then operating with them, e.g. union, intersection, etc, slows down rendering / construction procedure due the large amount of polygons.

Cylinder


Cylinders and cones can be created like this:

whereas fn is the amount of segments to approximate the circular profile of the cylinder (default 32).

Torus


A torus is defined as such:
 * ri = inner radius (default: 1),
 * ro = outer radius (default: 4),
 * fni = inner resolution (default: 16),
 * fno = outer resolution (default: 32),
 * roti = inner rotation (default: 0)

Polyhedron
Create a polyhedron with a list of points and a list of triangles or polygons. The point list is all the vertexes of the shape, the triangle list is how the points relates to the surfaces of the polyhedron:



Additionally you can also define `polygons: [ [0,1,4,5], [..] ]` too, not just `triangles:`.

You can also create a polyhedron at a more low-level:

Text
``vector_text(x,y,string)`` and ``vector_char(x,y,char)`` give you line segments of a text or character rendered in vector:



Also multiple-line with "\n" is supported, for now just left-align is supported. If you want to dive more into the details, you can request a single character:

Center
Centering an object altogether or axis-wise:

It center and .center helps you to compose a symmetric whose complete size you don't know when composing, e.g. from parametric design.

Union


multiple objects can be added, also arrays.

Intersection


multiple objects can be intersected, also arrays.

Note intersection (openscad like) vs intersect (function vs CSG objects' built in methods)

Difference (Subtraction)


multiple objects can be differentiated (subtracted) from the first element, also arrays.

Note: difference (openscad like) vs subtract (method, object-oriented)

2D Paths
A path is simply a series of points, connected by lines. A path can be open or closed (an additional line is drawn between the first and last point). 2D paths are supported through the CSG.Path2D class. The difference between a 2D Path and a 2D CAG is that a path is a 'thin' line, whereas a CAG is an enclosed area.

Paths can be constructed either by giving the constructor an array of 2D coordinates, or through the various CSG.Path2D member functions, which include: Paths can be concatenated with .concat, the result is a new path.
 * arc(endpoint, options): return a circular or ellipsoid curved path (see example below for usage).
 * appendPoint([x,y]): create & return a new Path2D containing the callee's points followed by the given point.
 * appendPoints([[x,y],...]): create & return a new Path2D containing the callee's points followed by the given points. [Note: as of 2016/08/13, this method also modifies the callee; this is probably a bug and might be changed in the future; see issue:165]
 * appendBezier([[x,y],...], options): create & return a new Path2D containing the callee's points followed by a Bezier curve ending at the last point given; all but the last point given are the control points of the Bezier; a null initial control point means use the last two points of the callee as control points for the new Bezier curve. options can specify {resolution: }.

A path can be converted to a CAG in two ways:
 * expandToCAG(pathradius, resolution) traces the path with a circle, in effect making the path's line segments thick.
 * innerToCAG creates a CAG bounded by the path. The path should be a closed path.

Creating a 3D solid is currently supported by the rectangularExtrude function. This creates a 3D shape by following the path with a 2D rectangle (upright, perpendicular to the path direction):

Hull


You can convex hull multiple 2D polygons (e.g. circle, square, polygon) together.

Chain Hull


Chained hulling is a variant of hull on multiple 2D forms, essentially sequential hulling and then union those, based on an idea by Whosa whatsis:

Linear Extrude


Extruding 2D shapes into 3D, given height, twist (degrees), and slices (if twist is made):

Linear extrusion of 2D shape, with optional twist. The 2d shape is placed in in z=0 plane and extruded into direction &lt;offset&gt; (a CSG.Vector3D). The final face is rotated degrees. Rotation is done around the origin of the 2d shape (i.e. x=0, y=0) twiststeps determines the resolution of the twist (should be >= 1), returns a CSG object:

Rectangular Extrude


Extrude the path by following it with a rectangle (upright, perpendicular to the path direction), returns a CSG solid.

Simplified (openscad like, even though OpenSCAD doesn't provide this) via rectangular_extrude, where as
 * w: width (default: 1),
 * h: height (default: 1),
 * fn: resolution (default: 8), and
 * closed: whether path is closed or not (default: false)

or more low-level via rectangularExtrude, with following unnamed variables:
 * 1) width of the extrusion, in the z=0 plane
 * 2) height of the extrusion in the z direction
 * 3) resolution, number of segments per 360 degrees for the curve in a corner
 * 4) roundEnds: if true, the ends of the polygon will be rounded, otherwise they will be flat

Rotate Extrude


Additional also rotate_extrude is available:

You can essentially extrude any 2D polygon (circle, square or polygon).

Properties
The 'property' property of a solid can be used to store metadata for the object, for example the coordinate of a specific point of interest of the solid. Whenever the object is transformed (i.e. rotated, scaled or translated), the properties are transformed with it. So the property will keep pointing to the same point of interest even after several transformations have been applied to the solid.

Properties can have any type, but only the properties of classes supporting a 'transform' method will actually be transformed. This includes CSG.Vector3D, CSG.Plane and CSG.Connector. In particular CSG.Connector properties (see below) can be very useful: these can be used to attach a solid to another solid at a predetermined location regardless of the current orientation.

It's even possible to include a CSG solid as a property of another solid. This could be used for example to define the cutout cylinders to create matching screw holes for an object. Those 'solid properties' get the same transformations as the owning solid but they will not be visible in the result of CSG operations such as union.

Other kind of properties (for example, strings) will still be included in the properties of the transformed solid, but the properties will not get any transformation when the owning solid is transformed.

All primitive solids have some predefined properties, such as the center point of a sphere (TODO: document).

The solid resulting from CSG operations (union, subtract, intersect) will get the merged properties of both source solids. If identically named properties exist, only one of them will be kept.

Connectors
The CSG.Connector class is intended to facilitate attaching two solids to each other at a predetermined location and orientation. For example suppose we have a CSG solid depicting a servo motor and a solid of a servo arm: by defining a Connector property for each of them, we can easily attach the servo arm to the servo motor at the correct position (i.e. the motor shaft) and orientation (i.e. arm perpendicular to the shaft) even if we don't know their current position and orientation in 3D space.

In other words Connector give us the freedom to rotate and translate objects at will without the need to keep track of their positions and boundaries. And if a third party library exposes connectors for its solids, the user of the library does not have to know the actual dimensions or shapes, only the names of the connector properties.

A CSG.Connector consist of 3 properties:
 * point: a CSG.Vector3D defining the connection point in 3D space
 * axis: a CSG.Vector3D defining the direction vector of the connection (in the case of the servo motor example it would point in the direction of the shaft)
 * normal: a CSG.Vector3D direction vector somewhat perpendicular to axis; this defines the "12 o'clock" orientation of the connection.

When connecting two connectors, the solid is transformed such that the point properties will be identical, the axis properties will have the same direction (or opposite direction if mirror == true), and the normals match as much as possible.

Connectors can be connected by means of two methods: A CSG solid's connectTo function transforms a solid such that two connectors become connected. Alternatively we can use a connector's getTransformationTo method to obtain a transformation matrix which would connect the connectors. This can be used if we need to apply the same transform to multiple solids.

Bounds & Surface Laying
The getBounds function can be used to retrieve the bounding box of an object, returning an array with two CSG.Vector3Ds specifying the minimum X,Y,Z coordinates and the maximum X,Y,Z coordinates.

The lieFlat function lays an object onto the Z surface, in such a way that the Z-height is minimized and the object is centered around the Z axis. This can be useful for CNC milling, allowing an object to be transform into the space of the stock material during milling. Or for 3D printing: it is laid in such a way that it can be printed with minimal number of layers. Instead of the lieFlat function, the getTransformationToFlatLying function can be used, which returns a CSG.Matrix4x4 for the transformation.

Colors
OpenSCAD-like: Whereas the named colors are case-insensitive, e.g. 'RED' is the same as 'red'.

using CSG objects' built in methods (r, g, b must be between 0 and 1, not 0 and 255):

Examples:

See the Extended Color Keywords for all available colors.



Code excerpt:



Code:

Note: There are some OpenGL Transparency Limitations, e.g. and depending on the order of colors, you might not see through otherwise partially transparent objects.

Color Spacing Conversion
Following functions to convert between color spaces:

whereas
 * r,g,b (red, green, blue)
 * h,s,l (hue, saturation, lightness)
 * h,s,v (hue, saturation, value)

E.g. to create a rainbow, t = 0..1 and .setColor(hsl2rgb(t,1,0.5))



See the Tor (multi-color) for an example.

Echo
prints out on the JavaScript console: a=1, b=2

Mathematical Functions
Javascript provides several functions through the Math library. In addition, the following OpenSCAD compatible functions are available:

Direct OpenSCAD Source Import
An OpenSCAD to OpenJSCAD translator is included, however the following features aren't working yet:
 * DXF import and manipulation (e.g. import_dxf, dxf-cross, dxf_dim functions).
 * rotate_extrude (Note: OpenJSCAD supports rotate_extrude )
 * minkowski and hull transformations (Note: OpenJSCAD supports hull )
 * global variable such as $fa, $fs
 * Modifier characters: #, !, %
 * List Comprehension such as: list = [ for (i = [2, 3, 5, 7, 11]) i * i ];

You can edit OpenSCAD source in the built-in editor, just make sure the first line says: then the source-code is shown with OpenSCAD syntax.

Further CAD languages support might arrive at a later time.

Converting OpenSCAD to OpenJSCAD
In order to translate your OpenSCAD into native OpenJSCAD code, consider this comparison.

OpenSCAD

OpenJSCAD

Essentially whenever named arguments in OpenSCAD appear func(a=1), translate it into func({a:1}), for example:

Interactive Parametric Models


Models can have interactive parameters, allowing users to change values via familiar forms, i.e. typing in numbers, sliding bars, pulling down menus, etc. This allows the user to change values and create any number of possible combinations, allowing the model to become dynamic in nature. Any number of custom designs can be created, which can then be down loaded in any supported format.

Interactive parameters are possible by adding a specific function called getParameterDefinitions. This function can be added anywhere in to your JSCAD script, but must return an array of parameter definitions.

The parameter definitions are used to create a set of fields which the user can change, i.e. options. The values of the fields are supplied to the main function of your JSCAD script. For example, the value of the 'width' parameter is supplied as the 'params.width' attribute, and so on.

All the common HTML5 field types are available as interactive parameters. This includes checkbox (boolean), color, date, email, float, int, number, password, slider, text and url. As well as two special parameter types for pull down choices, and grouping parameters.

A minimum parameter specification contains only 'name' and 'type'. However, a complete parameter specification should have a 'caption' and 'initial' value. In addition, there are 'min', 'max', 'step', 'checked', 'size, 'maxlength', and 'placeholder' which are relevant to specific parameter types. Just keep try different combinations to get a nice parameter specification. Here's an good example. In addition, there is the 'choice' type which creates a drop down list of choices for the user. The choices are provided by specifying the 'values' and 'captions'. The chosen value is passed into the main function of the model.

A complete example: There are plenty of examples of "Interactive" parameters available at openjscad.xyz. See the Quick Reference for more information about the available parameter types, and browser support.

Parameters via the Command Line Interface
The command line interface, ``openjscad``, can pass parameters for the interactive designs. Either by

key value or

key=value

For example:

Including Files
After creating a few designs using OpenJSCAD, common functions and parts will become useful. The include function allows one OpenJSCAD script to include another OpenJSCAD script.

Simple Example
see also and
 * https://github.com/BITPlan/docker-openjscad/tree/master/workspace/testinclude
 * https://github.com/gilboonet/designs/tree/master/testInclude

Note: the main must contain the call: myLib

Object oriented example
A design for a Remote Control Holder that uses a class "Box" which is included from "Box.jscad". see also https://github.com/BITPlan/docker-openjscad/tree/master/workspace/RCHolder

platonics example
See Platonics Example with a recursive use of include. Yet, it's a rather bad example of not localize the function names. A clear writing style-guide will follow how an OpenJSCAD library should look like.

Support of include
The include function is supported
 * web-online remote (e.g. https://openjscad.xyz/): given you drag & dropped the files, or they are available on the web-server (e.g. the examples)
 * web-online local (e.g. http://localhost/OpenJSCAD/): given you drag & dropped the files, or they are available on the local web-server
 * web-offline local (e.g. file://..../OpenJSCAD/index.html): given you drag & dropped the files
 * command-line interface (CLI): given they are locally available in the filesystem

Example of a setup with drag & dropped files:



File Layout of JSCAD Projects
Assuming you want to create a larger OpenJSCAD project, you might use include to split up the functionality:

Note: The file named main.jscad must be present, and must contain the "function main" declaration.

Developing with Multiple JSCAD Files
Depending on your browser and your local setup, following applies:

* Online (http://...): drag & drop entire folder, e.g. ProjectName/ to the drag & drop zone * Offline (file://...): drag & drop all jscad files (but not folder) to the drag & drop zone
 * Chrome (Version 26):
 * Firefox (Version 19+): drag & drop all jscad files of the project to the drag & drop zone
 * Opera: not yet working (WebGL support not yet available)
 * IE10: not yet working (WebGL support not yet available)

Addendum

 * Constructive Solid Geometry (CSG) Library, is a modelling technique that uses Boolean operations like union and intersection to combine 3D solids.