Docs · WebAssembly

In a web page

The readers, the mesher, a viewer and the kernel, compiled to WebAssembly: an ES module for any browser, with typings. Files are read on the visitor's machine and never uploaded. The viewer, the forge and the notebook on this site run on the same module.

Get it

One package, every build

Each release carries cadaclysm-<version>-web.zip: the readers, the mesher, the kernel and the viewer, in every build a web license covers (releases before 0.14.2 split them between two zips). In a checkout of the SDK:

python fetch.py --license KEY     # cadaclysm.lic from the store
python fetch.py --web             # the package, into web/

The module comes in five builds, one folder each, so a page loads only what it uses:

Each folder holds the module (cadaclysm.js, cadaclysm_bg.wasm, index.js and their typings); the builds with the viewer add view.js, and the ones with the kernel add cadaclysm_blacksmith.js and blacksmith.js. Beside them, example/ is a page and its worker. Serve the folder with any static server and open /example/.

View

Draw it

The View draws on a canvas, through WebGPU where the browser has it and WebGL2 where it does not, with a grid, edges and an orbit camera. What it draws is meshed inside the module, so the geometry never passes through JavaScript.

import { load, open, View } from "./pkg/index.js";
import { attachControls } from "./pkg/view.js";

await load({ license: "/cadaclysm.lic" });
const canvas = document.querySelector("canvas");    // sized by CSS: the viewer draws at that size
const viewer = await View.create(canvas);         // WebGPU, else WebGL2
viewer.showScene(open(bytes, "step"));              // framed on what it shows
attachControls(canvas, viewer);                     // drag, right-drag, wheel, pinch
viewer.start();

open(bytes, format) names the format as an extension would: "step", "iges", "ifc" and so on. A "zip" or "stpz" (STEP-Z, the STEP file zipped) opens its first readable member, and a gzip stream is named by what it holds, then .gz: open(bytes, "step.gz") decompresses it inside the module, so a page can serve its models compressed. preview(bytes, "scad") reads an OpenSCAD file the quick way, as meshes faceted at the file's $fn -- the same parts in the same colours, in a fraction of the time the exact solids take -- for a page that shows something at once and then the scene open returns; it has no exact surfaces, and any other format throws.

showScene(scene) draws a file as read, showSolid(handle, { tolerance, colour, fill }) a kernel solid (colour paints all of it, over its faces' and edges' own paint; fill only where a face has neither paint of its own nor the solid's colour, never over paint -- a page's palette colour for a solid that brought none), and showMesh({ positions, normals, indices, edges, colour, xray }) typed arrays of your own (xray: true draws it over everything, through whatever is in front of it, for an overlay inside other parts; its own edges stay depth-tested, hidden where something is in front; face picks ignore x-ray: pick finds a face by the depth-tested texel under the cursor, so a tap cannot reach one inside a part, and one in front of a part is picked in its place, while its edges are picked and snapped through whatever covers them); each returns an id, for setColour(id, [r, g, b]), remove(id) and frame(id) (no id frames everything), and clear() takes all of it away. setVisible(kind, on) turns a layer on or off: surfaces, edges, curves, isocurves, grid, text. The camera moves with orbit, pan and zoom, jumps to view("top"), front, right or iso, and setOrthographic(true) makes it parallel. setLod({ minTriangles, motion }) turns on levels of detail, for a device that needs them: every part of minTriangles (2048) or more gets coarser levels, built in the background after it is shown; motion: "detailed" (the default) draws every frame whole but for levels that cannot be seen, "smooth" holds the frame rate while the camera moves and refines the picture once it rests, with a resting frame owed chiefly under this policy (a page drawing on demand keeps asking for frames while restPending is true). setLod(null), the default, builds none. start() draws on animation frames, only when something changed, until stop(); draw() draws one frame now. maxDrawingSize is the largest side the drawing takes, in device pixels (the device's largest texture, often 4096 or 8192 on WebGL2): resize(width, height, ratio) clamps each side to it, so a page that sizes its canvas's backing store itself, rather than calling start(), caps its ratio at min(ratio, maxDrawingSize / width, maxDrawingSize / height) and uses that one ratio for the canvas, its viewports' rects and its picks alike. onError((message) => ...) is told, after a draw or an animation frame, when drawing goes wrong: once when the GPU device is lost (the message says to reload the page -- nothing draws on that viewer again), and with a GPU error a frame raised; onError(null) stops it. backend says which API is drawing. View.create(canvas, options) takes background, upAxis ("z" or "y"), antiAlias, grid (as setGrid below) and backend ("webgl2" forces the fallback), and surfaces: "triangles", the default, draws the mesh; "exact" draws a read file's and a kernel solid's faces as the trimmed surfaces they are, evaluated on the GPU, and their B-rep edges as exact curves, on WebGPU -- worth it for a part or a few hundred; a large assembly costs CPU every moving frame. setSurfaces(mode) switches live, and viewer.surfaces says which is drawn ("triangles" on WebGL2, or where the exact shaders did not build). It can read "triangles" right after create({ surfaces: "exact" }), until something exact is shown, and may turn to "triangles" a frame later on a device whose exact shaders fail. A kernel solid's face colours are kept in exact mode; meshes of your own and STL draw triangles in either mode. The viewer keeps what a shown scene or solid was made from (the file's document, the solid's B-rep) until remove or clear, so a later setSurfaces("exact") can build its exact surfaces; the Scene and the solid's handle can still be freed. setLighting("studio") lights plain parts with a key light fixed above the model, ambient and a fill from the camera, so a top reads brighter than its sides from anywhere; setLighting("headlight"), the default, lights whatever faces the camera. setLighting("showroom") puts plain parts in a showroom fixed in the world — a dark floor, a bright horizon, a grey ceiling, softboxes overhead and either side — mirrored in a clear coat over their colours, so paint reads by the reflections running across it as the camera goes round. A solid in one of the forge's looks keeps its own lamps either way, and viewer.lighting says which is in use. pkg/view.js is the pointer: attachControls(canvas, viewer) on the page's thread, or forwardControls and receiveControls across a worker, each built on listen(canvas, sink) (every pointer, wheel and key event View.input takes, handed to sink) and normalise(canvas, event), which turns one DOM event into the plain object listen feeds it.

input(event) is the one gesture handler behind attachControls: the event is {kind, ...} -- "down" {pointerId, pointer, button, x, y, shift?, alt?, time?}, "move" {pointerId, pointer, x, y}, "up" {pointerId, pointer, x, y, time?}, "cancel" {pointerId}, "wheel" {deltaY, x?, y?} (x and y where the wheel turned; left out, where the pointer last was), "key" {code, down} -- pointer is "mouse", "touch" or "pen", button 0/1/2 as a DOM event's, x and y device pixels from the canvas's top left, time milliseconds. Each gesture is read by the camera of the viewport under the press (the built-in orbit camera while no viewports are set), and a drag stays with the viewport it started in: the left drag (or one finger) orbits an orbit camera, looks with a fly camera and pans an orthographic one; Alt and the left button orbit the viewport's pivot (setPivot; an orthographic camera pans), and an Alt press never picks; the right drag, or Shift and the left, pans every kind; the wheel zooms an orbit camera, dollies a fly camera and zooms an orthographic one about the cursor, a step per hundred pixels of deltaY (a sideways-only scroll does nothing); two fingers pan and pinch; a tap picks and a double tap picks again with clicks 2 (framing what it hit, in its viewport, only after setDoubleClickFrames(true)); T/F/R/I give the standard views, O orthographic, Space frames everything -- each in the viewport under the pointer; X switches exact and triangles; W/S/A/D/E/Q fly the fly camera under the pointer (else the first one; an orbit camera with none set) while held, four times as fast with Shift, and Tab turns fly mode on or off. For a tap or a double tap it returns a promise of {item, node, face, clicks, point} or null, the same shape as pick; otherwise undefined. setTap(px, ms) sets how far a tap may travel (device pixels, default 10) and how long it may last (milliseconds, default 500; 0 for no limit) -- a page wanting 3 CSS pixels calls setTap(3 * ratio, 0). setPickOnTap(false) is for a page that hit-tests on its own: a tap then answers { tap: [x, y], viewport, double } at once (x, y device pixels from that viewport's top left; double true for the second tap of a double one), runs no GPU pick, and frames nothing, so a double tap is the page's to read. A field that does not fit its kind throws, naming it. A double tap no longer frames what it hit by itself: the camera stays, and the page acts on the answer's clicks -- setDoubleClickFrames(true) brings the framing back, as the site's own viewers do. focus([x, y, z]) orbits about a point in world coordinates (a pick answer's point): the target moves there, the eye keeps its direction and distance; it returns false while the page's viewports are set, and throws for a point that is not three finite numbers. A fly key puts the view in fly mode, and it stays after the key is let go: the left drag (of the orbit camera the fly keys move, once viewports are set) then turns the view about the eye, until Tab, frame, a standard view, a double tap that frames or focus brings orbiting back. navigation is a getter, "orbit" or "fly", for a page that shows the mode. flying is a getter, true while a fly key is held -- a host drawing on demand keeps drawing while it is. needsDraw is a getter too, true when the next draw would show something new -- a host drawing on demand draws after an input only when it or flying is set, so a hover that moved nothing costs no frame. new Gestures() is the same handler alone, for a host with a camera of its own: feed(event) takes what input takes and returns the commands it makes, as {orbit: [dx, dy]}, {zoom: steps}, "frame_all" and the like. attachControls makes the canvas focusable and hands it keys while it has focus: a key with Ctrl, Meta or Alt held stays the browser's, a bound key (BOUND_KEYS, Space and Tab among them) has its default prevented, Shift+Tab stays the browser's so focus can leave the canvas, and the canvas or the window losing focus, or the page going hidden, calls clearKeys so a held fly key cannot fly on.

A page that drives its own cameras — a CAD app's quad layout, say — calls setViewports([{ rect, view, projection, eye, grid }]): rect is [x, y, width, height] in device pixels on the canvas, view and projection the page's own column-major matrices (the standard WebGPU convention: depth 0 at the near plane, 1 at the far), eye the camera position, and grid "top", "front", "right" or null for the plane it draws a grid on. Such a viewport has a fixed camera: nothing in the View moves it. A record may instead carry a camera the View moves — setViewports([{ rect, camera, grid }]), with camera one of { kind: "orbit", target?, distance?, yaw?, pitch?, orthographic? } (the built-in camera's kind), { kind: "fly", eye?, yaw?, pitch?, speed?, framed?, radius? } (an eye that looks and flies), { kind: "ortho", basis: "top" | "front" | "right" | { view, right, up }, centre?, height?, radius? } (a parallel view of a plane, which pans and zooms about the cursor) or { kind: "fixed", view, projection, eye }; a field left out takes its kind's default. Then orbit(dx, dy, viewport), pan(dx, dy, viewport), zoom(steps, viewport), look(dx, dy, viewport), dolly(ratio, viewport), view(name, viewport), setOrthographic(on, viewport) (an orbit camera only) and frame(id, node, viewport) act on that viewport's camera (viewport 0 when the last argument is left out; a fixed camera stays put and frame answers false for it), and so does input, by the viewport under the press. camera(viewport) returns a camera as an object setCamera(viewport, camera) takes back, to keep and restore (null past the last viewport); aim(viewport, direction, up?) points it along a direction; frameAll(viewport) fits it to everything shown and frameSphere(viewport, centre, radius) to a sphere — a fly or orthographic camera's clip distances and zoom limits follow the radius it was last framed on; zoomAt(viewport, x, y, steps) zooms by wheel notches at a pixel of that viewport (a page wanting one notch per wheel event calls it with ±1 instead of forwarding the wheel); setPivot(viewport, point) sets the point Alt-drag orbits about (null for the camera's own target). setViewportRects(rects) moves the viewports and keeps their cameras (an empty rect hides one, as a maximised pane does), and setViewportGrid(viewport, grid) changes one viewport's grid alone. A fly camera turns by CSS pixels: resize(width, height, ratio)'s ratio is the one it divides by. frameReport() says what the last frame drew, viewport by viewport — [{ rect, view, projection, eye, kind }], the matrices Float32Arrays of sixteen (column-major, depth 0 near, 1 far) — the matrices a page projects its own overlay through; a page whose View runs in a worker posts it beside each frame (the site's pages call that message view.frame). image({ camera, width, height, layerMask?, background? }) draws one camera, in any form setCamera takes, offscreen into a picture of width × height pixels. It shows the screen's items, look and lighting on the layers layerMask keeps, with no grid and no overlays, on background ([r, g, b], 0 to 1). It resolves an RGBA Uint8Array, rows from the top, once every item shown has been uploaded. The screen and its cameras are left as they were. The site's worker host (viewer-host.js, with attachViewer in viewer-client.js on the page) posts each drawn frame's report as view.frame, handed to onFrame(viewports), and, with setPickOnTap(false), each tap as view.tapped {tap, viewport, double, seq}, handed to onTap(tap, viewport, double, seq) (seq is the one client.inputEvent(event) returned for the up that tapped). attachViewer also takes maxRatio, the largest device pixel ratio the client asks for (a page that wants no more than 2x on a 3x screen), and onResized(ratio), called with the new ratio each time the view reports a resize, so a page that places things in device pixels can place them again. setViewports(null) returns to the single built-in orbit camera. While viewports are set, showing items frames no camera: frame the ones you want with frameAll; the built-in camera is framed at the next show after setViewports(null). Every number is checked — a matrix is sixteen finite numbers, rect four whole non-negative ones, eye three — and a record or a camera that does not fit throws, naming the record and the field, and nothing changes.

setGrid({ axes, step, extent, fit }) lays the grid out; setVisible("grid", on) stays its on/off. By default the grid is sized to the model — lines 1, 2 or 5 times a power of ten apart, about a dozen cells, reaching past the model — with no line marked. axes: true draws its two lines through the world origin, where the grid reaches it, a step brighter than the rest; step fixes the spacing in model units; extent fixes the grid to -extent..extent about the world origin, rather than about the model, and lays the perspective floor on the world's z = 0 rather than under the model's lowest point — the grid an editor wants, since nothing added, edited or moved shifts it. Lines always fall on the world's multiples of the step, on the perspective floor and on every viewport's grid alike. fit says how a grid sized to the model keeps up with it as it changes: "follow" lays it again after every change, every frame of a turning part included; "steady", the default, does the same except that a part an animation moves counts at its box when the animation began, carried along but never turned, so a turntable leaves the grid as it was; "hold" lays it once, from the model as it is when set (or from the first item on an empty view), and keeps it through every edit, move and animation until setGrid is called again. Each call sets all four and lays the grid anew: a field left out, or null, is its default, and setGrid(null) is every default. A fixed grid of { axes: true, step: 10, extent: 100 } is a 10 mm sheet reaching 100 mm each way; one past 256 lines an axis is drawn at the step doubled until it fits. A step or extent that is not a positive finite number, or a fit that is none of the three, throws, naming the field. View.create takes the same object as its grid option.

showExact({ faces, loops, points, profiles, nurbs, tiles, tileDomains, tileDensitySamples, tileBoxes, beziers, bounds, colour, faceColours?, mesh?, material?, opacity? }) draws one body from arrays already in the View's exact layout — the packed trimmed surfaces its exact pass draws, copied in as they are — as trimmed exact surfaces (a kernel solid needs none of this: showSolid draws it): bounds is [minX, minY, minZ, maxX, maxY, maxZ], colour is [r, g, b], and faceColours ({ face: [r, g, b] }) overrides it face by face. mesh ({ positions, normals?, indices, faceTriangles }, faceTriangles the triangles per face in face order) is what a WebGL2 device draws, and what frames and picks the body in triangles mode; without it the item frames by bounds alone. In triangles mode the body's edges are drawn from beziers. A body with no exact faces (an empty faces) cannot be expressed exactly: show it with showMesh instead. material is one of six looks — "plastic", "metal", "matte", "paint", "brushed", "glass" — shaded with a key and a fill lamp riding the camera, their highlights following the eye; absent, the body is lit by the View's lighting (setLighting). opacity (0 to 1, default 1) dithers the body as a translucent part is, whatever its material; any other material, or an opacity outside 0 to 1, throws. showCurves(beziers, [r, g, b]) draws free curves — a sketch, a preview — as one item: beziers is sixteen floats a curve, a rational cubic's four control points as x, y, z, weight. showImage({ corners, bitmap, opacity, flipX, flipY }) drops in a reference image: corners are its four [x, y, z] corners (bottom-left, bottom-right, top-right, top-left), bitmap an ImageBitmap or { rgba, width, height } (rows top first), opacity a number from 0 to 1 (default 1). Each of these three returns an item id, like showScene and showMesh do.

setFaceColours(id, { face: [r, g, b] }) recolours the faces of an already-shown item — a hover, a selection — without re-uploading it: the keys are face numbers as showExact numbers them, the values are RGB (a fourth number is ignored), and null (or {}) clears back to the item's own colours. setColour(id, [r, g, b]) is as cheap: it rewrites the item's colour in place — its triangles, its edges, curves and isocurves, its exact surfaces and exact curves — with no re-upload, so a curve can follow a hover or a selection; a face colour set by setFaceColours still wins over it. pick(viewport, x, y) returns a promise of { item, node, face, clicks, point, viewportLabel, segment, distancePx } or null (segment a lines item's segment, a curves item's Bezier or a solid's kernel edge, null for a face or a point; distancePx from the pixel to the hit): x and y are device pixels from that viewport's own top left (the canvas's, viewport 0, while no viewports are set); clicks is 1 (2 only for a double tap's pick through input), and point the point hit, [x, y, z] in world coordinates, or null where the pick reads none (a machining's stock); viewportLabel is the index of the viewport whose label the pixel is on, or -1 when it is not on a label (setViewportLabel); it finds the face under that pixel in exact mode or, from faceTriangles, in triangles mode; a pick made while another is in flight waits its turn, and draws with the cameras as they are when it runs, not when it was asked for — so keep one pick in flight (on a pointer move, ask again once the last answer is in) and drop an answer older than the pointer's latest position.

setSnap({ kinds, aperturePx, marker }) turns snapping on: kinds is "default" (or left out: the first eight below and "point"), "all" (all twelve) or an array of "vertex", "midpoint", "centre" (a circular edge's), "quadrant", "edge", "face", "grid" and "plane", and the opt-in "end" (a lines or curves item's piece ends), "intersection" (where two drawn edges cross), "point" and "alignment" (guides through recent snaps); aperturePx is how far from the cursor a point may lie (10 by default); marker: false leaves the marker to the page. setSnap(null) turns it off, as a View starts. await snap(viewport, x, y) answers { kind, point, item, node, face, edge, tangent, axis, radius, distancePx, label, lockedAngle, guides } or null, with x, y in device pixels as pick takes them and point in world coordinates, and the View draws a marker there. Within the aperture a corner beats the edge it ends and the face it sits on. Keep one snap in flight: a pointer move that comes while one is out is asked when it lands, so the marker follows the latest position. clearSnap() hides the marker; setWorkPlane({ origin, xAxis, normal, step }) puts the "grid" and "plane" snaps on a plane of your own, and setWorkPlane(null) back on the ground grid. setSnapPoints(id, points, label) gives item id points of your own to snap to as "point", the snap's label then being yours (a hole's centre, say); setSnapBase(point, stepDeg) locks snaps that land on no point to multiples of stepDeg (15 by default) about point, the answer carrying its lockedAngle and a guide { from, to } from the base, and setSnapBase(null) lets go. pick reaches lines, points and glyphs within setPickAperture(points) of the cursor (4 by default), answering a line's or curve's segment (a solid's kernel edge for its edges) and its distancePx; pickRect(x, y, w, h, { crossing, viewport }) answers at once what lies in a rectangle, as [{ item, kind, index }] with kind "face", "node", "segment", "edge" or "point"; the rectangle is clipped to the viewport (one wholly outside answers [], as does a lost device), and an unknown viewport throws. A lost device answers null from pick and snap, and a pick the View could not draw answers item 0 with segment null. A page whose View is in a worker asks through its client: client.snap(x, y), latest wins. Measure between two points is the worked example.

showLines(segments, [r, g, b]) draws straight polylines — flaw lines, a measurement — as one item: segments is six floats a segment, x0 y0 z0 x1 y1 z1 a pair of endpoints, drawn under the curves layer, over the edges; a length that is not a whole number of six-float segments, or a value that is not finite, throws. setPlacement(id, matrix) moves item id to matrix — sixteen numbers, column-major (entry 4 * col + row), applied after the item's own coordinates (world = matrix * item) — or back to its rest pose with null: its triangles, edges, curves, isocurves, exact surfaces and box all move, a rigid matrix is expected (normals are turned by its linear part and renormalised), and it is kept across every later show and remove, with no re-upload. false for an unknown id; a matrix that is not sixteen finite numbers, or null, throws. A machining stock (below) takes a translation only — its march, pick, toolpath and tool follow it, while its cuts and its part stay in the stock's own coordinates, as the machine sees them — and throws "setPlacement: a machining stock moves only by a translation" for any other matrix, since its heightfield is marched along the world's axes. setNodeHighlights(id, nodes, tint) tints item id's local nodes toward tint's [r, g, b, strength] (0 leaves the colour, 1 is the tint) over whatever colour they already draw in, with no re-upload; null clears it. false for an unknown id; nodes that is not an array of whole numbers, or a tint that is not [r, g, b, strength] in 0..1 or null, throws. frame(id, node) fits the camera to one local node of one item (a reader page's "frame the selected part"); with no arguments, or node left out, it is frame() (everything shown) or frame(id) (one item), as before. false where there is nothing to fit: an unknown id, a node the item has no spans of, a node given with no id, a fixed camera, or no such viewport; frame(id, node, viewport) fits that viewport's camera. In fly mode, look(dx, dy) turns the view about the eye by a screen-space drag, in pixels — orbit's counterpart where the eye stays put and the target turns around it — and key(code, down) takes a keydown/keyup event's own code: "KeyW"/"KeyS" forward/back, "KeyA"/"KeyD" left/right, "KeyE"/"KeyQ" up/down along the world up (any other code is ignored), moving the camera by the held keys each frame of draw() or start()'s loop. dolly(ratio) zooms by a ratio directly, the same zoom a wheel step makes from a count of them. By default showSolid draws a solid's painted edges in their own paint, not the edge style or the part's colour — the edge's own paint wins, the same as a face's own colour already does.

showPoints(positions, colour, sizePx) draws round dots at world points as one item: positions is a Float64Array, a Float32Array or an array of three numbers a point, x y z; each point is a disc sizePx across (1 to 64; the same on screen at any zoom, scaled by the pixel ratio), anti-aliased at its rim, in colour (the edges' colour for null). It is drawn under the curves layer, depth-tested like a line, and seen through surfaces in x-ray; it picks within setPickAperture, answering the point's index as node, and it frames by its points' box. Point i is the item's node i, so setNodeHighlights reaches one dot. setXray(id, true) draws the dots over everything, through the surfaces in front of them — what handles on a surface want, since a dot is hidden whole by the depth at its centre — and setXray(id, false) depth-tests them again; it works on any shown item, as showMesh's xray does at show time, and answers false for an unknown id. Face picks ignore x-ray, but an x-ray item's lines and points are picked (pick, pickRect) and snapped through whatever covers them, so x-ray dots inside a part stay pickable. A positions that is not a whole number of points, a number that is not finite, or a sizePx outside 1..64 throws. project(viewport, [x, y, z]) is the other way about: it returns [x, y], the world point's place in device pixels from that viewport's top left — the pixels pick(viewport, x, y) takes — or null when the point is behind the eye. It is not clipped to the viewport, so a point beside the view has a position outside it, and a drag that leaves the canvas can still be followed; a viewport that does not exist, or a point that is not three finite numbers, throws.

Drafting styles, each on an item already shown, with no re-upload. setOccluded(id, mode) draws an item's lines and points where a surface is in front of them: "off" (the default), "solid" or "dashed". setLineStyle(id, { dash, gap }) gives an item's lines their own dash, both lengths in points, and setLineStyle(id, null) makes them solid again; a "solid" occluded item's hidden lines take the same dash, a "dashed" one's keep setOccludedStyle. setPointStyle(id, { shape, hollow }) sets a points item's marker, shape being "disc" (the default), "ring", "square" or "diamond", filled or hollow; setPointStates(id, states) gives each point a state, a Uint8Array of 0 to 3 or an array of "normal", "hover", "selected" and "first" (or those numbers), in the order the points were shown, so a hover or a selection is written in place; setPointStateColours({ hover, selected, first }) sets the colours those states draw in, for every points item, each as colour text or [r, g, b], a missing one back to its default. setOnTop(id, on) draws an item after everything else with no depth test, and a pick finds it first; it throws for an overlay, text, an image or an exact-surface item (a showCurves item is accepted, its exact edges drawn on top too). setViewportLabel(i, text, { colour }) writes a name inside the top left of viewport i (null clears it; the colour defaults to white; it throws for text holding a NUL) and setViewportBorder(i, colour) frames the viewport (null clears it); both throw for a viewport past the last. setViewportRects keeps them, and setViewports keeps those of a viewport that still exists. Each of the item calls answers false for an id that is not shown.

Live geometry replaces what an item draws, under the same id, so a sketch or a cloth can move every frame. setLines(id, segments) takes a showLines or showSegments item's segments again, six numbers a segment; setCurves(id, beziers) a showCurves item's curves, sixteen numbers each; setPoints(id, positions) a showPoints item's points, three numbers each; setMeshPositions(id, positions, normals?) a showMesh item's vertices, three numbers each, in the order and the number the mesh was shown with. Each array is a Float32Array, a Float64Array or a plain array. Colour, layer, dash, placement, on top and the paint of each point or node stay as they were, and the camera is not re-framed. A new number of segments, curves or points is taken; a mesh keeps its vertex count, and a mesh shown with edge segments cannot be moved. setPoints keeps the point states, highlights, ghosts, hidden flags and node colours by index, and a new point is a normal one. Leave normals out, or pass null, and they are worked out in the mesh's own shading, flat for a mesh shown without normals and smooth for one shown with them. A moved mesh's simplified levels of detail are dropped until the next scene change rebuilds them, so it draws whole meanwhile. Each call answers false for an id that is not shown, and throws, with its own name first, for an item of another kind, a number that is not finite or a mismatched count.

showGlyphs(at, { kind, sizePt?, colour?, dir? }) draws drafting symbols at world points as one item and returns its id: at is three numbers a glyph, and kind one of "arrow", "tick", "cross", "square", "triangle", "parallel", "perpendicular", "coincident", "tangent", "fixed", "horizontal" and "vertical". A glyph is sizePt points across (1 to 128, 12 by default); that follows the screen's pixel ratio and does not change as the camera moves. dir, three numbers a glyph, turns each one to that direction as it is seen on the screen (an "arrow" points along it); without it they stay upright. The colour defaults to the edge colour. Glyph i is node i: a pick finds the item and the node, and setNodeHighlights, setNodeGhosts and setOnTop reach it. A glyph hides behind a surface in front of its point unless the item is x-ray or on top. An unknown kind, a sizePt outside 1 to 128 or a number that is not finite throws.

const sketch = view.showLines([0, 0, 0, 1, 0, 0], "white");
const handle = view.showPoints([1, 0, 0], "orange", 9);
view.showGlyphs([0.5, 0, 0], { kind: "arrow", dir: [1, 0, 0] });
// the handle is dragged: the same ids, no re-show
view.setPoints(handle, [1, 0.5, 0]);
view.setLines(sketch, [0, 0, 0, 1, 0.5, 0]);

showText(text, { at, mode?, size?, colour?, align?, offset?, box?, padding?, onTop?, font?, right?, up? }) draws text as one item and returns its id. at ([x, y, z]) is required. A label, the default mode: "label", faces the camera at a constant size in pixels (default 12), its box placed on at by align — "top-left", "top", "top-right", "left", "centre" (or "center"), "right", "bottom-left" (the default), "bottom", "bottom-right" — moved by offset ([x, y] pixels), over a box colour (none by default; colour text or [r, g, b] is opaque, [r, g, b, a] sets its alpha) with padding pixels round the text (default 4), and hidden behind geometry in front of its anchor unless onTop: true. mode: "world" lays the text in the model instead, its origin at at in the plane of right and up (default +X and +Y), size in model units. colour is white by default. A pick on text answers its id, with face the line hit (0 for the first). setText(id, text) replaces the string and nothing else — the cheap path for a read-out that changes every frame — and throws for an id that is not text. loadFont(bytes), a module function beside View, takes a TTF or OTF font as a Uint8Array or an ArrayBuffer and returns its id for font, for every viewer of this module instance (a viewer hosted in a worker has its own module, and its own fonts: loadFont is not bridged to it); font 0, the default, is the bundled Liberation Sans, and bytes that are no font throw, saying why. setVisible("text", on) shows or hides every text item. A field that does not fit its kind — at, right or up not three finite numbers, offset not two, an unknown mode or align, a font that is not a whole number — throws, naming it; so do a size that is not positive, right and up parallel, and a font id never loaded.

Overlays are a HUD over the canvas, drawn after everything else and never moved by the camera. Each hangs from an anchor — the same nine names as align — x, y pixels inward: x away from the left edge for a left anchor and from the right edge for a right one, y down from the top for a top anchor and up from the bottom for a bottom one (rightward and upward for the middle column and row). showOverlay(beziers, anchor, x, y, { fill?, stroke?, strokeWidth?, order? }) draws a profile's beziers (sixteen numbers a curve, one unit a pixel, y up) as its outline: a profile is a sketch, so the stroke is white unless one is given, and a fill draws only where given — its closed loops filled by the even-odd rule, so a loop inside another is a hole. "none" or null draws no fill or no stroke; a fill with stroke: "none" is a fill alone, and neither is refused. showOverlayText(text, anchor, x, y, { size?, colour?, box?, padding?, font?, order? }) hangs the text's box from the anchor by the same point (its top-right corner for "top-right"), and setText changes it cheaply. showOverlayImage(rgba, width, height, anchor, x, y, { size?, opacity?, order? }) draws an image, size ([w, h]) pixels across or its own size. Lower order draws first; shapes, text and images share it. moveOverlay(id, anchor, x, y) moves one cheaply, for an element that moves every frame, and remove takes it away. A pick on an overlay answers its id with overlay: true and nothing beneath it; a pick through a hole reaches the scene.

stats() answers what the View has drawn: { framesDrawn, lastFrameMs, lastGpuMs, triangles, drawCalls }. framesDrawn counts every frame drawn to the canvas and every image() rendered; a draw() with nothing owed draws nothing and counts nothing, so an FPS counter read from it once a second stays right while the scene is still. lastFrameMs is the last frame's CPU time; lastGpuMs its GPU time on WebGPU where the adapter has timestamp queries, a frame or two behind, and -1 on WebGL2 or wherever it cannot be measured; triangles and drawCalls are what the last frame submitted.

Every colour the View takes — setColour, setFaceColours, setNodeHighlights, showLines, showSegments, showPoints, showCurves, showText's colour and box, showMesh's, showSolid's and showExact's colour, showSolid's fill and create's background — is [r, g, b] in 0..1 or colour text: "#rgb", "#rrggbb" or one of the 148 CSS colour names, any case (viewer.setColour(id, "tomato")). Where a fourth number is taken too — a highlight's strength, a face colour's ignored alpha — text means 1. The typings say string | [number, number, number], and view.d.ts exports it as Colour.

View

Machining: play a job, cut the stock

viewer.showMachining(options) -> Machining turns the View into a CAM simulator: a Z heightfield stock, cut on the GPU as a job's moves stamp it, coloured by deviation from a part, by tool or by height. options.stock is { min: [x, y, z], max: [x, y, z] }, the blank; options.programs is the job, [{ tool, gcode }] in run order — gcode is read by the same strict Grbl reader the native oracle uses, so any Grbl G-code plays, not only ours, and a tool is { number, shape: "flat" | "ball" | "drill" | "vbit" | "bullnose", diameter, flute_length, angle?, corner_radius? } (angle a V-bit's included angle, corner_radius a bull-nose's). options.part is optional — a solid handle, or { positions, indices } — and enables colouring by deviation. options.cell (mm) defaults to the smaller of 0.1 and the smallest tool's diameter ÷ 10, capped to fit the device's texture size (Machining.cell says so, and a warning is logged, when the cap raises it); options.tolerance (default 0.05 mm) is the "within tolerance" band for deviation colours; options.skin (default 0.3 mm) is how far outside the part's own outline still reads as the expected skin band in a deviation colouring, rather than uncut stock; options.snapshotEvery (default 200 moves) is how often a snapshot is kept for seeking backwards; options.rapidRate (mm/min, default 5000) is the machine's rapid rate, for the rapids' share of the machining time.

It returns a Machining — one per call, its stock one item, machining.id (not framed for you: viewer.frame(machining.id) fits the camera to it, as it would any other item). play(speed = 1) / pause() run the View's own timeline (below); seek(move) jumps to after move move (0 is the untouched stock), backwards as a snapshot restore plus a replay; move / moves / playing are the playhead, the total and the play state; hasPart says whether the options gave a part, for a page deciding whether to offer the "deviation" colour mode at all; cycleTime is the job's machining time in seconds (feeds, the rapid rate; dwells are not read yet) and track is this machining's track id on viewer.timeline; programAt(move) answers { program, tool, line }, for a status line; colourBy(mode) takes "deviation" (throws "showMachining: colour by deviation needs a part" without one), "tool" or "height"; showPath(on) / showTool(on) toggle the toolpath and tool overlays, both on by default; onMove(callback) is called once a frame the playhead moved, with (move, { x, y, z, tool, rapid }); pickInfo(pickResult) turns a viewer.pick() hit on the stock into { cell: [i, j], height, part, deviation, tool }; heights() is a Promise of the current heightfield as a Float32Array (row-major, y then x) carrying min, cell, nx, ny and owners (a Uint8Array, one byte a cell: 0 uncut, else the cutting tool's number plus one — Machining.pickInfo's own tool reads it the same way) — for tests and exports, and a promise because a GPU readback cannot block a browser's main thread. dispose() is viewer.remove(machining.id). Errors throw with the reader's or the kernel's own text, e.g. "gcode line 42: …".

Playback runs on viewer.timeline, one clock the View advances every frame it plays (inside start()'s own loop, or a page's own repeated draw()), shared by every track added to it — a machining job is one track, so several can play together or be scrubbed together. time / duration / playing / speed / loop are its state; tracks lists { id, kind, name, offset, duration }. play(speed = 1) / pause() / seek(t) (clamped to [0, duration]) / setLoop(on) drive it; setOffset(trackId, seconds) moves one track's start in time. segments() (a machining track: one per program, coloured by its tool) and markers() (one per tool change) feed a UI, and so does status() — one line a track, e.g. "move 370 of 638 · T1 flat 6 mm · X12.3 Y-4.0 Z7.0". onTime(callback) is called once a frame the clock moved, with (time) — one callback at a time: a later call replaces the one before it, rather than adding another. Nothing here is drawn by the renderer: attachTimelineControls(container, timeline) (a play/pause button, a speed menu, a loop toggle, a scrubber in time with segments and markers, a status line) and attachMachiningControls(container, machining) (the colour-mode menu, path/tool checkboxes, a step-by-move pair) build one over the timeline's and the machining's own members, each returning { detach() } — shipped in the package's own pkg/view.js, beside the camera controls, so attachTimelineControls takes over timeline.onTime's one slot the moment it is called; a page driving its own UI off onTime too should register after detach(), not alongside. A started View keeps itself alive until stop(): a page may let its last reference go and it plays on. A stopped one that nothing references is freed by the garbage collector, its GPU memory with it; free() frees a viewer at once, playing or not.

import { load, View } from "./pkg/index.js";
import { loadBlacksmith } from "./pkg/blacksmith.js";
import { attachTimelineControls, attachMachiningControls } from "./pkg/view.js";

const wasm = await load({ license: "/cadaclysm.lic" });
const { Profile, Solid, Frame, Stock, Tool, Job } = await loadBlacksmith(wasm);
const viewer = await View.create(document.querySelector("canvas"));

const part = Solid.extrude(Profile.rect(60, 40).withHole(Profile.circle(9)), Frame.xy(), 8);
const [min, max] = part.bounds;                                     // the stock: the part's bounds, +2 mm
const stock = { min: [min[0] - 2, min[1] - 2, min[2]], max: [max[0] + 2, max[1] + 2, max[2] + 2] };
const job = new Job(Stock.box(stock.min, stock.max), 20);
job.machine(part, Tool.flat(1, 6, 20, 800, 200, 12000));             // a Report of what it could not cut
const programs = job.gcode().map((p) => ({ tool: { number: p.tool, shape: "flat", diameter: 6 }, gcode: p.text }));

const machining = viewer.showMachining({ stock, programs, part: part._handle });
viewer.frame(machining.id);                                         // showMachining does not frame itself

attachTimelineControls(document.querySelector("#timeline"), viewer.timeline);
attachMachiningControls(document.querySelector("#controls"), machining);
viewer.start();
machining.play(4);                                                  // four times real time

loadBlacksmith is the web package's own kernel loader (the "The kernel" section below): its objects build the part and the job right on the page, so showMachining plays real G-code from the moment it loads, rather than fetching a pre-cut job's files. part._handle is the object wrapper's own solid handle, what showMachining's part option reads (a kernel solid handle, or { positions, indices }); Stock and Job read and write handles the same way but keep no bounds of their own, so the stock box is worked out from the part's bounds once and given to both Stock.box and showMachining. A later plan will bring the same simulator to the desktop app (playing a .nc file or a .camotics project on the same renderer, cadaclysm-view) and the Python notebook already plays a job the same way: show(job, part=part) there embeds a View over it, with these controls. The desktop app's doesn't exist yet.

View

Mechanisms: play a scene's joints

viewer.showMotion(id, options) -> MechanismMotion plays the mechanism a shown scene carries (a STEP assembly with kinematic pairs, read by open and shown with showScene) as one track on viewer.timeline, beside any machining. options.keyframes is [{ time, values }] or [{ time, state }], times in seconds (finite, at least 0) and increasing: values maps a joint name to a number (a one-freedom joint) or an array (one per freedom), a name addresses every joint with that name, and "#N" addresses joint number N; state names one of the file's states. Between the keyframes that name a joint, options.interpolation is "smooth" (the default, a cubic with zero end slopes) or "linear"; before its first keyframe a joint holds that keyframe's value, after its last its last value, and a joint nothing names rests. options.rates maps a joint to a rate per second (a number, or an array per freedom), added to the keyframes' value as rate × t, so a motor can spin for as long as the track runs (with timeline.setLoop(true) a rate loops seamlessly only when rate × duration is a whole turn, for a propeller a whole multiple of its blade spacing; nothing adjusts it); with rates and no keyframes options.duration (seconds) is required, and otherwise the track lasts until its last keyframe. options.ground names the link held fixed, and null is the file's own base.

A file can record its own motion as a sequence of its states (STEP AP242's interpolated configuration sequences). options.sequence plays one in place of keyframes: viewer.showMotion(id, { sequence: "tool change" }), or "#0" for the first, and a name plays every sequence so named, since a file whose mechanisms are separate can hold one of a name in each. Its parameter runs as seconds (in the file's time unit, else read as seconds), or options.duration stretches it; a closed sequence returns to its first state and, with timeline.setLoop(true), loops with no jump when every sequence played has the same period. options.rates add on top as with keyframes; the markers are the segments, labelled with the state each reaches (a segment holding the state before it marks nothing). A sequence takes no keyframes or interpolation ("showMotion: a sequence takes no keyframes or interpolation"), and a missing one is refused ("showMotion: no sequence named 'x'", "showMotion: no sequence #4").

A value outside a joint's range is used, and listed in the track's timeline.status() line (t=1.00 · shoulder=2.000 · out of range: shoulder=2.000), as is a joint the solver could not place (unsolved: …); the keyframes show on timeline.markers(), labelled with the state's name or "keyframe". A refusal throws before anything is shown, e.g. "showMotion: no joint named 'elbow'", "showMotion: keyframe times must increase (2 then 1)" or "showMotion: item 3's scene has no mechanism", "showMotion: duration must be a finite number of seconds, at least 0", "showPose: a pose needs values or a state, not both" or, for a ground that is not a string, "showPose: ground is the name of a link". motion.dispose() takes the track off and restores the rest pose; viewer.remove(id) and viewer.clear() drop it as well. viewer.showPose(id, { shoulder: [0.5] }, ground = null) (or { state: "reach" }) holds one pose without a track, with ground the name of the link held fixed ("showPose: no link named 'x' to hold fixed" if there is none), and viewer.showPose(id, null) restores the rest pose. The pose is held until a track on the same item poses it again, the next time the timeline moves (play or seek); disposing one motion poses that item again from any tracks still on it, even on a paused timeline, and leaves every other item, a held showPose included, as it was. Keep one motion per item: put every joint's keyframes and rates in a single showMotion, or a later track's pose replaces an earlier one's.

To show the mechanism beside the drawing, scene.mechanismJson() gives the file's links, joints and states as JSON -- { links: [{ name, nodes }], joints: [{ name, start, end, pair }], states: [{ name, values: [{ joint, values }] }], sequences: [{ name, closed, secondsPerUnit, segments: [{ state, t, interpolation }] }], bases, base }, a pair being null or { kind, freedoms: [{ motion, axis, lower, upper }] } with kind one of the other wrappers' thirteen names ("revolute", "prismatic", ...) and an open bound null, a segment's state indexing states, t the file's parameter and secondsPerUnit null where the file gives no time unit -- and motion.valuesJson(t) the values the motion poses at time t, [{ joint, values, outOfRange }], one entry per joint it moves; a page reading viewer.timeline.time each frame shows them as they play. The quadcopter showcase draws its mechanism tree this way.

An IFC file can carry its construction programme. scene.scheduleJson() gives its work schedules -- [{ name, identification, kind, start, finish, tasks: [{ name, identification, kind, status, milestone, parent, time: { scheduleStart, scheduleFinish, earlyStart, earlyFinish, lateStart, lateFinish, actualStart, actualFinish, duration }, nodes, calendar, durationKind, workDuration }], links: [{ from, to, kind, lag }] }], dates in seconds since 1970-01-01 that carry no time zone, so read them as UTC (new Date(seconds * 1000).toISOString(), or the getUTC* accessors), a duration in seconds, a task or schedule kind of "other" with its user-defined text in kindName (present only then), nodes the node indices a task builds -- and scene.scheduleAt(schedule, date, dates = "scheduled") what each of those elements is doing on a date: [{ node, phase, progress, variance }], phase one of "unbuilt", "building", "built", "demolishing", "demolished", and variance the seconds late (or early, below 0) against the scheduled dates where the file records actual ones. "actual" plays the as-built dates. A task's calendar is the index of the work calendar it works on, or null; durationKind is "ELAPSEDTIME", "WORKTIME", "NOTDEFINED" or null; workDuration is { days, seconds } or null (a year is 260 working days, a month 20, a week 5 and a day 1; hours, minutes and seconds are working seconds). scene.calendarsJson() gives the file's work calendars, [{ name, identification, kind, kindName, working, exceptions }] (kind one of "FIRSTSHIFT", "SECONDSHIFT", "THIRDSHIFT", "NOTDEFINED", "USERDEFINED"; kindName present only for the last), each working or exception time { name, start, finish, pattern } with pattern null or { kind, days, weekdays, months, position, interval, occurrences, periods }, periods being [start, end] pairs of seconds after midnight. scene.workingPeriods(calendar, from, to) returns the calendar's working periods between two dates as a Float64Array of start/end pairs, [start0, end0, start1, end1, ...], in seconds since 1970; it throws workingPeriods: from and to must be finite, workingPeriods: from must not be after to, workingPeriods: from and to must lie within 100 years of each other or workingPeriods: no such calendar. A task with a calendar builds over working time only, pausing at nights and weekends, and scheduleAt expands the calendars on each call, so for playback use viewer.showSchedule, which builds the windows once.

viewer.showSchedule(id, options) -> ScheduleTrack plays that programme as one track on viewer.timeline: the building going up (or coming down) on a date that runs with the clock. options.schedule is a schedule's name (the first so named) or "#N" (schedule N), and defaults to "#0"; options.dates is "scheduled" (the default), "actual" or "compare". The span runs from the earliest start of the schedule's tasks to the latest finish, under those dates ("compare" uses the actual ones), and the track lasts options.duration seconds, or span / 86400 * options.secondsPerDay seconds; give at most one of the two, and with neither the whole span plays in 30 seconds. A schedule whose tasks all sit at one instant gives a track of 0 seconds. At track time t the date is the span's start plus t scaled the same way. Each frame, an element not yet built (and one demolished) is hidden, or drawn see-through when options.unbuilt is "ghost" (the default is "hidden"); one being built is tinted orange and one being demolished red; a built one is drawn as it is. options.unassigned says what to do with the nodes no task names: "shown" (the default), "hidden" or "ghost". options.colours is { building, demolishing, ahead, behind }, each [r, g, b, a] with every value 0 to 1 (defaults [1, 0.62, 0.1, 0.55], [0.9, 0.15, 0.1, 0.55], [0.2, 0.75, 0.3, 0.45] and [0.9, 0.2, 0.15, 0.45]); the fourth value is the tint's strength, not transparency, and ghosting is the see-through option.

The track puts a marker on timeline.markers() at the start of each milestone (kind "milestone") and of each top-level task that is not a milestone (kind "task"), labelled with the task's name; a task with no dates gets none. Its timeline.status() line reads like 2026-03-14 · Pour slab (A12) 40% · Erect frame 15%: the date at the playhead (the UTC calendar day, no time zone), then the running tasks in the schedule's order with their progress, an empty identification shown without its parentheses, at most three and then +2 more; with nothing running, just the date. In "compare" mode a built element is tinted green (ahead) when the file's actual dates finished it more than a day before the scheduled ones, and red (behind) when more than a day after, and the status line always ends with the counts, · 12 behind, 3 ahead. The handle has id (the item), track (its timeline id), dispose(), dateAt(t) (seconds since 1970 at track time t), statesJson(t) ([{ node, phase, progress, variance }], as scene.scheduleAt gives) and runningJson(t) ([{ task, progress }], the running tasks as indices into the schedule's tasks). schedule.dispose() takes the track off and puts back what it hid, ghosted and tinted -- all of the item's hidden and ghosted nodes and the tints it set -- and viewer.remove(id) and viewer.clear() drop it as well. Keep one schedule track per item: while it runs it owns the item's hidden and ghosted nodes, and the highlights of the nodes it tints: a page's own highlight on such a node is overwritten while the track runs and cleared by dispose(). A schedule track and a mechanism track may share an item. A refusal throws before anything is shown, e.g. "showSchedule: no schedule named 'x'", "showSchedule: no schedule #3", "showSchedule: give duration or secondsPerDay, not both", "showSchedule: item 3's scene has no work schedule", "showSchedule: schedule 'Phase 1' has no task with dates" or, for a schedule that is not a string, showSchedule: schedule is a name, or "#N". The construction showcase plays a building's programme this way.

const id = viewer.showScene(scene);
const motion = viewer.showMotion(id, {
  keyframes: [
    { time: 0, values: { "gimbal pitch": -0.35 } },
    { time: 2, state: "look down" },
    { time: 4, values: { "#4": 0.8 } },
  ],
  rates: { "motor bearing": 2 * Math.PI * 50 },   // radians a second
  interpolation: "smooth",
});
viewer.start();
viewer.timeline.play(1);
// later
motion.dispose();                                        // the rest pose again
const id = viewer.showScene(scene);
const schedule = viewer.showSchedule(id, { dates: "compare", secondsPerDay: 0.2 });
viewer.start();
viewer.timeline.setLoop(true);
viewer.timeline.play(1);
// later
schedule.dispose();                                      // everything shown again, untinted
Use it

In a Web Worker

An open, a mesh or a boolean runs on the thread that calls it, and a browser kills a page whose main thread blocks for long. So the module can live in a worker, and draw there too: the page hands its canvas over with canvas.transferControlToOffscreen(), posts it with the file's bytes, and calls forwardControls(canvas, worker) for the pointer.

// worker.js  (new Worker("worker.js", { type: "module" }))
import { load, open, View } from "./pkg/index.js";
import { receiveControls } from "./pkg/view.js";

const ready = load({ license: "/cadaclysm.lic" });   // a URL, or the file's text
let scene, gotCanvas;
const viewer = new Promise((resolve) => { gotCanvas = resolve; });   // the canvas may come after the bytes

async function draw(canvas) {
  await ready;
  const v = await View.create(canvas);   // the page's OffscreenCanvas
  receiveControls(v);                      // orbit, pan, zoom and resize, from the page
  v.start();
  return v;
}

self.onmessage = async ({ data }) => {
  if (data.canvas) gotCanvas(draw(data.canvas));   // opens wait for this
  if (!data.bytes) return;                         // the rest are forwardControls'
  const v = await viewer;
  v.clear();
  if (scene) scene.free();   // wasm memory never shrinks: free a scene before reading the next
  scene = open(new Uint8Array(data.bytes), "step");   // step, iges, sat, 3dm, ifc, brep, scad
  v.showScene(scene);
  v.frame();
  self.postMessage({ tree: JSON.parse(scene.treeJson()) });
};

Set self.onmessage before anything awaits: a message that reaches a worker before it has a handler is lost. A page that draws for itself can still take the triangles instead: Scene hands over its vertices() (nine floats a vertex: position, normal, colour), indices(), the feature edges(), free curves(), isocurves(), the bounds(), the part spans and each part's attributesJson(part). pkg/cadaclysm.d.ts types every export.

Tutorial

A web view in ten lines

A step-by-step page builds a cuboid with the kernel and puts it on screen with the View in about ten lines of JavaScript, then does the same from a Web Worker. No framework, no bundler.

pkg/ and pkg-kernel/

The kernel

The kernel's calls are the C API's cadaclysm_blacksmith_* entry points, name for name — cadaclysm_blacksmith.h in the SDK is the reference. Handles are numbers, a frame is twelve numbers (origin, then the x, y and z axes), a failure throws with the C API's own message, and hasKernel() tells the two builds apart.

const rect = cadaclysm_blacksmith_profile_rect(60, 40);
const plate = cadaclysm_blacksmith_extrude(rect, [0,0,0, 1,0,0, 0,1,0, 0,0,1], 8);
const bore = cadaclysm_blacksmith_translate(cadaclysm_blacksmith_cylinder(9, 30), 0, 0, -10);
const part = cadaclysm_blacksmith_cut(plate, bore, 0.05);   // 0.05: the chord tolerance it meshes at
const mesh = cadaclysm_blacksmith_mesh(part, 0.05);        // { positions, normals, indices }
const step = cadaclysm_blacksmith_step(new Uint32Array([part]), ap203, 1);   // ap203: schemas/ap203.exp's text

Or as objects: Profile, Workplane, Solid, Selector and the rest of the Node.js wrapper — the same cadaclysm_blacksmith.js the SDK ships, which runs over the module. The web package carries it in pkg/ and pkg-kernel/ with its typings, and pkg/blacksmith.js puts it on the page:

import { load } from "./pkg/index.js";
import { loadBlacksmith } from "./pkg/blacksmith.js";

const wasm = await load({ license: "/cadaclysm.lic" });
const { Profile, Workplane } = await loadBlacksmith(wasm);
const outline = Profile.rect(60, 40).withHole(Profile.circle(9));
const part = Workplane.xy().extrude(outline, 8).solid();
const { positions, normals, indices } = part.mesh(0.05);
const step = part.stepText();   // the file's text, to download

A page has no disk: loadBlacksmith(wasm, { files }) takes a Map from a file's name to its bytes, which Solid.open(name) reads and part.step(name) writes into. The async verbs (joinAsync …) need a worker thread the wasm has none of, and reject: call the plain verb, in a Web Worker of your own.

Sketches

The wrapper's Sketch comes with it: a 2D sketch whose points and curves are held by dimensions and relations (coincident, horizontal, length, tangent …) and solved on request, then turned into profiles for the kernel. Ids are numbers, a refusal throws a BuildError whose ids name the constraints at fault, and close() frees the sketch. The Node.js page lists every method.

const { Sketch, Solid, Frame } = await loadBlacksmith(wasm);
const sketch = new Sketch();
const [corners, sides] = sketch.addRect([0, 0], [40, 30]);
sketch.fix(corners[0]);
sketch.length(sides[0], 60);          // widen it to 60
sketch.length(sides[1], 30);
sketch.solve().converged;             // true
sketch.point(corners[1]);             // [60, 0]
const slab = Solid.extrude(sketch.profiles()[0], Frame.xy(), 5);
sketch.close();
License

A web license, and the websites it names

A web license covers one website — a domain and its subdomains — per site bought. Hand the module the file with load({ license }) or license(text); a page cannot read a path, so a URL is fetched and text is taken as it is. If the file cannot be fetched or does not verify, load() says so on the console and the module runs unlicensed rather than failing to start; useLicense() throws instead, for a page that wants to know. The license names the websites it was bought for (asked at checkout; to change them, write to info@blitter.studio). On any other host the module runs as if unlicensed; localhost and file: pages always pass, so development never needs the license to say where the site will live.

Without a license — or on a host it does not name — everything still works, and a notice goes to the browser console on every file opened and every STEP file written. licenseInfo() says what the module runs under (customer=… scope=web sites=1 domains=acme.com); licenseNoticeCount() counts the notices, for a page that would rather show its own banner. Paid licenses cover every build dated on or before the day their updates end (buildDate()), as the native libraries' do.

← All languages