Skip to content

API reference ​

Everything the library exports, module by module. Points are plain { x, y, z } objects (or { x, y } on screen). No function changes its inputs unless it says so.

Modules ​

ModuleExports
trid/index.js ("trid3d")Everything below, from one file
trid/scene.jsScene
trid/math/transform.jsPipeline, camera directions, basic transforms, constants
trid/math/projection.jsproject, screen
trid/render/draw.jsclear, point, line, drawWireframe, drawInstance
trid/render/loop.jsloop
trid/render/canvasRenderer.jsCanvasRenderer, DEFAULT_LIGHT, DEFAULT_AMBIENT, materialsOf, meshEdges
trid/render/uvMapping.jscomputeUVs, mapUVs, uvsFor, uvTransform, applyUVTransform, mappingOf, mappingKey, MAPPINGS
trid/render/webglRenderer.jsWebGLRenderer, DEFAULT_FAR
trid/render/normals.jscornerNormals, creaseOf, newell, DEFAULT_CREASE
trid/render/effects.jstoon, rim, edgeGlow, unlit, gradient, fog, buildEffects, effectsKey, uniformType, SURFACE_GLSL
trid/render/lights.jsdefaultLights, MAX_LIGHTS, sceneLights, lightAt, lightLevels, rangeFade
trid/render/shadows.jsDEFAULT_SHADOWS, POINT_SHADOW_SIZE, MAX_SHADOWS, shadowOptions, shadowFlag, shadowFrame, pointShadowFar, findGround, flattenOnGround, flattenFromPoint
trid/render/post.jsbloom, vignette, grade, grain, outline, DEFAULT_OUTLINE_CREASE, postPasses, activePost, runCanvasPost, wantsGeometry, maskedObjects, FRAME_GLSL, GEOMETRY_GLSL
trid/render/grid.jsgridMesh, gridHelper
trid/render/color.jsparseColor
trid/render/shapes.jsmakeShape, lathe, extrude, triangulate, scaleMesh
trid/render/meshUtils.jscloneMesh, transformMesh, displaceMesh, mergeMeshes, meshBounds
trid/math/noise.jsrng, noise2, noise3, fbm2, fbm3
trid/modeling/curves.jsspline, resamplePath
trid/modeling/sweep.jssweep
trid/modeling/loft.jsloft
trid/modeling/symmetry.jsmirrorMesh, symmetrizeMesh, bisectMesh, arrayMesh, radialArrayMesh, mirrorObject, arrayObject, radialArrayObject
trid/modeling/sculpt.jssculptMesh, SCULPT_BRUSHES
trid/modeling/lattice.jsmakeLattice, latticePoints, latticeMesh, latticeCage
trid/modeling/modifiers.jsapplyModifiers, MODIFIERS
trid/modeling/remesh.jsremeshMesh
trid/modeling/deform.jstaperMesh, twistMesh, bendMesh, bulgeMesh
trid/modeling/cleanup.jsweldVertices, cleanMesh, validateMesh, fixWinding
trid/modeling/subdivide.jssubdivideMesh
trid/modeling/blobs.jsblobMesh, blobField, sdfMesh
trid/modeling/bevel.jsbevelMesh
trid/modeling/boolean.jsbooleanMesh, unionMesh, subtractMesh, intersectMesh
trid/modeling/placement.jsdropOnto, attachTo, alignObjects, distributeObjects
trid/modeling/query.jsmeshQuery, raycastMesh, pointInMesh, distanceToMesh, closestPointOnMesh, isClosed, raycastScene, clearQueryCache
trid/loaders/texture.jsloadTexture, textureReady, textureSize, textureIsLive
trid/loaders/obj.jsparseOBJ, loadOBJ, loadMaterials, readOBJFile, pickOBJFile, fitMesh
trid/export/obj.jsexportOBJ
trid/export/mtl.jsexportMTL, exportModel, objMaterials, textureToBlob
trid/loaders/mtl.jsparseMTL
trid/render/proceduralTextures.jsmakeTexture, texturePixels, colorBytes, TEXTURE_STYLES
trid/export/capture.jsscreenshot, record, download
trid/tools/index.jsTools (including SelectionOutline and SculptTool), pick, pickHit, isPickable, screenBounds, worldPerPixel, screenRay, ToolManager
trid/sceneGraph.jsworldObjects, worldMatrix, worldPosition, ancestors, forEachPlaced
trid/math/matrix.jsidentityMat4, mat4FromTransform, mulMat4, invertMat4, determinantMat4, transformPoint, transformDirection, normalMatrix, transformNormal, transformOpToLocal
trid/math/rotation.jsmatFromEuler, eulerFromMat, matFromAxisAngle, mulMat, mulVec, applyTransformOp

Math ​

Pipeline ​

From trid/math/transform.js.

js
localToWorld(v, inst)            // → point
worldToCamera(p, camera)         // → point
cameraToScreen(p, camera, w, h)  // → { x, y }
worldToScreen(p, camera, w, h)   // → { x, y }
clipNear(a, b, near)             // → [a, b] or null
  • localToWorld moves a mesh vertex into world space using an object's transform: scale, then rotate (X → Y → Z), then translate by pos. inst needs pos, rot and scale.
  • worldToCamera moves a world point into camera space: subtracts the camera position, then undoes its yaw and pitch. In camera space the camera sits at the origin looking down +Z, so z is the distance in front of it.
  • cameraToScreen projects a camera-space point to canvas pixels, using camera.fov and the aspect ratio w / h. p.z must be > 0 — clip segments with clipNear first if they can cross behind the camera.
  • worldToScreen is worldToCamera followed by cameraToScreen. Handy for placing labels on top of 3D points.
  • clipNear clips a camera-space segment against the plane z = near. Returns the segment unchanged if both ends are in front, null if both are behind, or a shortened segment with the hidden end moved onto the plane.

Camera directions ​

js
cameraForward(camera)  // → point
cameraRight(camera)    // → point
cameraUp(camera)       // → point

Unit vectors in world space for where the camera looks, the screen's right side and the screen's top side. Use them to move things relative to the view.

Basic transforms ​

js
scale(p, sx, sy, sz)       // → point
translate(p, dx, dy, dz)   // → point
rotateX(p, angle)          // → point  (pitch, YZ plane)
rotateY(p, angle)          // → point  (yaw, XZ plane)
rotateZ(p, angle)          // → point  (roll, XY plane)
rotateXYZ(p, { x, y, z })  // → point  (X, then Y, then Z)

Each returns a new point. Angles are in radians. Rotation order matters: rotateXYZ always applies X first, then Y, then Z.

Constants ​

NameValue
DEFAULT_FOV50° vertical field of view, in radians (50 * Math.PI / 180)
DEFAULT_NEAR0.01 — near plane distance

Projection ​

From trid/math/projection.js.

js
project(p, fov = DEFAULT_FOV, aspect = 1)  // → { x, y }
screen(p, w, h)                            // → { x, y }
  • project is the perspective projection of a camera-space point to normalized coordinates (−1 to +1). X is divided by aspect so shapes don't stretch on wide canvases. p.z must be > 0.
  • screen converts normalized coordinates to canvas pixels. Y is flipped: +1 is the top of the canvas.

Rendering ​

Drawing ​

From trid/render/draw.js.

js
clear(ctx, w, h, color)
point(ctx, p, color, size = 20)
line(ctx, p1, p2, color, width = 4)
drawWireframe(ctx, points2, edges, color, width = 4)
drawInstance(ctx, inst, camera, w, h, color, lineWidth = 3)
edgeSegments(edges)
wireEdges(mesh)
  • clear clears the whole canvas, then fills it with color. With "transparent" or null, it stays see-through.
  • point draws a filled square centered on screen point p. Useful for debugging vertices.
  • line draws one line between two screen points.
  • drawWireframe connects already-projected screen points using index edges (2 indices = segment, 3+ = closed loop). Everything is stroked as one path. No clipping is done.
  • drawInstance is the main drawing call: it transforms an object's mesh, clips every edge against the camera's near plane, projects it and strokes it as one path. The canvas renderer uses it for scenes with only wireframe objects.
  • edgeSegments turns edge definitions into [a, b] index pairs (a generator), expanding closed loops. Missing edges give no pairs.
  • wireEdges is what a wireframe draws for a mesh: its edges, or the outline of each face when it has none.

CanvasRenderer ​

From trid/render/canvasRenderer.js. The default scene.renderer: it draws wireframes and filled faces with the canvas 2D context.

js
new CanvasRenderer({ maxFaceSize = null } = {})
renderer.render(scene)
  • maxFaceSize splits faces bigger than that fraction of their mesh's size into triangles, so they sort better (see Splitting big faces). Off by default.
  • render(scene) clears the canvas and draws every object of the scene. Scene.render calls it, then lets tools draw.
  • DEFAULT_LIGHT is { x: -0.5, y: 1, z: -0.8 } and DEFAULT_AMBIENT is 0.25.

WebGLRenderer ​

From trid/render/webglRenderer.js. Draws with the graphics card and a depth buffer. See Renderers.

js
WebGLRenderer.isSupported()
new WebGLRenderer({ antialias = true } = {})
renderer.render(scene)
renderer.dispose()
renderer.canvas
  • isSupported() says whether the browser can create a WebGL context.
  • The constructor throws an Error if WebGL isn't available.
  • render(scene) draws on the hidden renderer.canvas, then copies the picture onto scene.canvas.
  • dispose() frees the graphics card memory; scene.destroy() calls it. Safe to call twice.
  • Meshes are uploaded once. Set mesh.dirty = true after changing a mesh's arrays in place.
  • DEFAULT_FAR is 1000, the farthest distance drawn unless the camera sets far.

Normals ​

From trid/render/normals.js.

js
cornerNormals(mesh, crease = 60)
creaseOf(smooth)
newell(points)
  • cornerNormals returns, for each face, one unit normal per corner: the average of the faces around that vertex that meet it at less than crease degrees. Faces with normals from an OBJ file use those. Cached per mesh until its arrays change or mesh.dirty is set.
  • creaseOf turns a material's smooth value into a crease angle (true → 60), or null for flat shading.
  • newell returns the (not normalized) normal of a polygon. For points clockwise as seen from a side, it points to that side. Also exported from canvasRenderer.js.
  • DEFAULT_CREASE is 60.

Effects ​

From trid/render/effects.js. The built-in effects and how to write your own are on the Effects page. The helpers below are what the renderers use:

  • buildEffects(effects) joins a list of effects into GLSL code, with names made unique per effect. Returns { code, calls, uniforms }.
  • effectsKey(effects) returns a string that's equal for lists that compile to the same shader (same code, same uniform types).
  • uniformType(value) returns the GLSL type a uniform value becomes, or null.
  • SURFACE_GLSL is the GLSL declaration of the Surface struct.

Lights ​

From trid/render/lights.js. Using lights is explained on the Lights page. The helpers below are what the renderers use:

  • sceneLights(scene, rgba) returns a scene's lights ready for shading: { ambient, ambientLevel, lights, mainDir, shadow }, colors parsed by rgba(css) and multiplied by their intensity. shadows lists the lights casting shadows, directional ones first (index in lights, point, dir or pos, range, and their settings); shadow is the first directional one, or null. A scene-like object with only light / ambient gets the default pair.
  • lightAt(lights, normal, position) returns the light reaching a point as [r, g, b]: the same math as the WebGL shader.
  • lightLevels(color, ambientLevel) returns { light, diffuse }, the numbers effects get.
  • rangeFade(dist, range) is how much of a point light reaches dist away.

Shadows ​

From trid/render/shadows.js. Using shadows is explained on the Lights page. Used by the renderers:

  • shadowOptions(value, point?) returns a light's shadow settings with the defaults (DEFAULT_SHADOWS; for a point light, size is POINT_SHADOW_SIZE) filled in.
  • shadowFlag(obj, "castShadow" | "receiveShadow") is false when the object or a group above it sets that field to false.
  • shadowFrame(casters, dir) returns { matrix, radius }: a directional light's shadow map box around the casting objects, facing along the light.
  • pointShadowFar(casters, position, range) is how far a point light's shadow map reaches: its range, or the far side of the farthest casting object.
  • findGround(receivers) returns the floor height for ground shadows, or null.
  • flattenOnGround(points, dir, ground) flattens a world polygon onto the floor along a directional light, cutting off what's below it.
  • flattenFromPoint(points, position, ground) does the same for a point light: along the rays from it, keeping only what's between the floor and the light's height.

Post effects ​

From trid/render/post.js. The built-in effects and how to write your own are on the Post effects page. Used by the renderers:

  • postPasses(effect) returns an effect's passes as { glsl, scale } (empty for a canvas-only effect).
  • activePost(list) returns the effects that are on.
  • runCanvasPost(scene, list, start) runs the effects' canvas functions on the scene's canvas.
  • FRAME_GLSL is the GLSL declaration of Frame and the frame / source helpers.
  • GEOMETRY_GLSL declares depthAt, normalAt and maskAt, added for effects with geometry: true (see Reading depth and normals).
  • wantsGeometry(effect) is true for an effect with geometry: true and GLSL.
  • maskedObjects(effect) returns the objects an effect's objects list covers, children included, as a Set (null without a list).
  • DEFAULT_OUTLINE_CREASE is the crease angle outline() uses by default: 40°.

Textures ​

From trid/loaders/texture.js. Using textures is explained on the Textures page.

  • loadTexture(url) returns a promise for a loaded <img> (with CORS enabled).
  • textureReady(src) says whether an image, canvas or video has pixels to draw yet.
  • textureSize(src) returns { w, h } in pixels.
  • textureIsLive(src, material?) is true for textures read again every frame: videos, or any source whose material has liveTexture: true (liveTexture: false freezes a video).
  • updateTexture(src) tells the renderers a canvas (or image) changed: it's read again once, on the next frame. See Changing a canvas.
  • textureVersion(src) is how many times updateTexture was called for a source (0 when never); renderers compare it with the version they read last.

Texture mapping ​

From trid/render/uvMapping.js. Using mappings is explained on the Textures page.

  • computeUVs(mesh, mapping) returns { uvs, faceUVs } made from the mesh's shape. The mesh isn't changed.
  • mapUVs(mesh, mapping) writes them into the mesh and returns it.
  • uvsFor(mesh, mapping) returns the coordinates a renderer uses: the mesh's own, or computed for the mapping and cached until the mesh changes.
  • uvTransform(material) turns textureRepeat, textureOffset and textureRotation into a 2D matrix [a, b, c, d, e, f] (u' = a·u + c·v + e, v' = b·u + d·v + f), or null when they change nothing. applyUVTransform(m, uv) applies it to one coordinate.
  • mappingOf(mapping) returns the mapping as { type, axis } and throws for an unknown one. mappingKey(mapping) is a short string for caches. MAPPINGS lists the mapping types.
  • materialsOf(obj) (from canvasRenderer.js) returns an object's materials as a list, or null for a wireframe.
  • meshEdges(mesh) (from canvasRenderer.js) returns each edge of a mesh's faces once, as { a, b, f1, f2 }: its two vertices and the faces on its sides (f2 is -1 on an open border). Vertices at the same spot count as one, so texture seams aren't borders. Cached per mesh. The canvas renderer uses it for outlines.

parseColor ​

From trid/render/color.js.

js
parseColor(ctx, color)

Turns any CSS color into [r, g, b, a] (0..255, alpha 0..1), using a 2D context to read it. Unknown colors come out black.

Frame loop ​

From trid/render/loop.js.

js
const stop = loop(update, { maxDt = 0.1 } = {})

Calls update(dt, time) every animation frame with requestAnimationFrame. dt is the seconds since the last frame (0 on the first, capped at maxDt) and time is the seconds since the loop started. Call the returned stop() to end it.

Using the pipeline without Scene ​

Scene is a thin layer over these functions. You can drive them yourself:

js
import { clear, drawInstance, point, loop, makeShape, worldToScreen } from "./trid/index.js";

export default function (canvas) {
  canvas.width = 800;
  canvas.height = 300;
  const ctx = canvas.getContext("2d");
  const { width: w, height: h } = canvas;

  const camera = { z: -1.5, fov: Math.PI / 3 };
  const box = {
    mesh: makeShape("box", { w: 0.8, h: 0.4, d: 0.4 }),
    pos: { x: 0, y: 0, z: 0 },
    rot: { x: 0.4, y: 0, z: 0 },
    scale: { x: 1, y: 1, z: 1 },
  };

  const stop = loop((dt, time) => {
    box.rot.y = time * 0.8;
    clear(ctx, w, h, "#141414");
    drawInstance(ctx, box, camera, w, h, "#e5c07b", 2);

    // A dot circling the box, projected by hand
    const p = { x: Math.cos(time) * 0.7, y: 0, z: Math.sin(time) * 0.7 };
    point(ctx, worldToScreen(p, camera, w, h), "#E9806E", 8);
  });

  return stop;
}

Helpers ​

From trid/tools/helpers.js (also exported by trid/tools/index.js).

pick ​

js
pick(scene, x, y, { filter, padding = 4, exact = false } = {})  // → object or null

Returns the object under canvas pixel (x, y). An object is hit when the point is inside its screen-space bounding box, grown by padding pixels. If several are hit, the one whose center is closest to the camera wins. filter(obj) can exclude objects.

INFO

Bounding boxes are approximate: clicking the empty corner around a sphere still picks it, and of two objects overlapping on screen, the one with the nearer center wins even where the other is in front. Pass exact: true to test triangles instead (same as pickHit).

pickHit ​

js
pickHit(scene, x, y, { filter, padding = 4, objects = scene.objects } = {})  // → hit or null

Exact picking: the nearest object whose drawn surface is under the pixel. Every face is projected with the renderers' own math and tested triangle by triangle, so a click always matches what's drawn: through a ring's hole, a sword guard in front of its blade. Objects without faces (wireframes) are hit within padding pixels of one of their lines.

FieldMeaning
objectThe object with the mesh that was hit
faceIndex in mesh.faces, or -1 for a line of a wireframe
depthDistance in front of the camera
pathThe object, then its groups up to the top: [part, group, ..., root]
pointWhere the hit is, in the world
localWhere the hit is, in the mesh's own space (mesh.vertices space)
triangleThe 3 vertex indices of the triangle hit (faces with more corners are cut into a fan from their first corner); null for a line
barycentricThe weights of those 3 vertices at the hit, adding up to 1 (local is their weighted sum); null for a line
normalUnit normal of the face, in the world, on its front side; null for a line
uvTexture coordinates at the hit, from the face's material mapping (before repeat, offset and rotation); null without any
textureUVWhere the texture is read at the hit: uv with the material's textureRepeat, textureOffset and textureRotation. Can be outside 0..1 when the texture repeats

The hit point is exact on tilted faces too (weighted for perspective). To paint on a model's texture, the image pixel under the mouse is:

js
const hit = pickHit(scene, x, y);
if (hit?.textureUV) {
  const u = hit.textureUV.u - Math.floor(hit.textureUV.u), v = hit.textureUV.v - Math.floor(hit.textureUV.v);
  paint(u * image.width, (1 - v) * image.height); // v goes up, image rows go down
  updateTexture(image);
}

Objects with pickable: false, or inside a group with it (like a grid), are skipped by pick and pickHit. isPickable(obj) tells whether an object can be found.

Faces with a corner behind the camera's near plane are skipped. It's one pass over the objects' vertices per call: fine for clicks and hover on models of a few thousand faces.

To cast a ray from any point in the world instead of from a pixel, see raycastScene.

screenBounds ​

js
screenBounds(scene, obj)  // → { minX, minY, maxX, maxY } or null

An object's bounding box on screen, in canvas pixels. Only vertices in front of the near plane count; returns null if the whole object is behind the camera.

worldPerPixel ​

js
worldPerPixel(scene, depth)  // → number

How many world units one canvas pixel covers at depth units in front of the camera. Multiply pointer dx / dy by it to make something follow the cursor exactly.

screenRay ​

js
screenRay(scene, x, y)  // → { origin, direction }

The ray from the camera through a canvas pixel, in world space: what's under the cursor is the first thing it meets. origin is the camera's position and direction is unit length. It's the exact inverse of how points are drawn, so it pairs with raycastScene:

js
const { origin, direction } = screenRay(scene, e.x, e.y);
const hit = raycastScene(scene, origin, direction); // the surface under the cursor

Rotations ​

From trid/math/rotation.js. 3×3 rotation matrices (row-major, m[row][col], applied as M · v), built from rotateXYZ itself so they always match the renderers, and the operations TransformGizmo reports.

js
matFromEuler(rot)              // → matrix that rotateXYZ(p, rot) applies
eulerFromMat(m)                // → rot angles for a matrix (handles looking straight along Y)
matFromAxisAngle(axis, angle)  // → right-handed turn around a unit axis
mulMat(a, b)                   // → a · b (b applied first)
mulVec(m, v)                   // → m · v
applyTransformOp(t, op)        // → new { pos, rot, scale }

Combine rotations with matrices, then turn the result back into an object's rot:

js
// Turn an object 90° around the world Y axis, whatever its current rotation
const turn = matFromAxisAngle({ x: 0, y: 1, z: 0 }, Math.PI / 2);
obj.rot = eulerFromMat(mulMat(turn, matFromEuler(obj.rot)));

applyTransformOp(t, op) applies a TransformGizmo operation to a transform and returns the new one (the input isn't changed).

ToolManager ​

From trid/tools/manager.js. Each scene creates one as scene.tools. It keeps the tool list and turns canvas pointer events into tool events. Canvas listeners are only added while at least one tool is in the list. You normally go through scene.use / scene.unuse instead.

MemberMeaning
new ToolManager(scene)Creates a manager for a scene's canvas
add(tool)Adds a tool and calls its attach. Adding the same tool twice does nothing.
remove(tool)Removes a tool (ending its drag if it holds one) and calls its detach
clear()Removes every tool
update(dt)Calls every tool's update
draw(ctx)Calls every tool's draw
listThe tools, in the order they were added