Skip to content

Documentation / @ripl/3d

@ripl/3d ​

npmlicensesize

3D rendering for Ripl: shapes, lights, materials and textures, drawn onto a 2D canvas with a depth-sorted painter's algorithm, or on the GPU through @ripl/webgpu.

Features ​

  • Nine shapes — cube, sphere, cylinder, cone, plane, torus, mesh (raw faces), parametric (a tessellated surface function) and bezier surface (bicubic patches).
  • Five light types — createAmbientLight, createHemisphereLight, createDirectionalLight, createPointLight and createSpotLight, each with colour, intensity and an enabled flag; directed lights are fixed in world space or locked to the camera. Point and spot lights add distance falloff (distance, decay) and spot lights a cone (angle, penumbra).
  • Materials — color, opacity, emissive, emissiveIntensity, specular, shininess, side ('front' | 'back' | 'double'), wireframe, flatShading, vertexColors and map. Every property is optional; an element with only a fill shades as it always did.
  • Textures — createTexture from an ImageBitmap, <img>, <canvas>, <video>, OffscreenCanvas or ImageData, or loadTexture from a URL. Per-axis wrapping ('clamp' | 'repeat' | 'mirror'), separate magnification and minification filters ('nearest' | 'linear'), and a UV transform of repeat, offset and flipY. Every built-in shape emits the coordinates, and both backends sample them the same way.
  • Perspective and orthographic camera — createCamera drives the context's view and projection, batches changes through a microtask, and handles orbit, pan and pinch/wheel zoom with per-interaction sensitivity.
  • Fog — 'linear' or 'exponential' haze blending distant geometry towards a colour, computed identically on both backends.
  • Triangle raycasting — context.raycast(x, y) builds a world-space ray and context.raycastAll(scene, x, y) returns every shape it meets, nearest first, with the hit point, face, interpolated normal and UV.
  • Group3D — a group whose transform composes into the model matrix of every shape beneath it, so a subtree orbits, tilts and scales as a unit.
  • Animation and events — shapes are Ripl elements, so renderer.transition, pointer events and scene querying all apply. interpolateVector3 tweens 3D positions — declare it in a custom element's interpolators to animate a vector-valued property.

Installation ​

bash
# npm
npm install @ripl/3d @ripl/web

# yarn
yarn add @ripl/3d @ripl/web

# pnpm
pnpm add @ripl/3d @ripl/web

The scene and renderer come from @ripl/web; this package supplies the 3D context, camera, lights and shapes. For GPU rasterization, add @ripl/webgpu and import createContext from there instead.

Quick start ​

typescript
import {
    createCamera,
    createContext,
    createDirectionalLight,
    createTorus,
} from '@ripl/3d';

import {
    createRenderer,
    createScene,
} from '@ripl/web';

const context = createContext('.mount-element');
const scene = createScene(context);

createCamera(context, {
    position: [0, 2, 5],
    target: [0, 0, 0],
    interactions: true,
});

context.lights.add(createDirectionalLight({
    direction: [-1, -1, -0.5],
    intensity: 0.8,
}));

scene.add(createTorus({
    radius: 1.2,
    tube: 0.4,
    material: {
        color: '#4488ff',
        specular: '#ffffff',
        shininess: 48,
    },
}));

createRenderer(scene, {
    autoStop: false,
});

Key API ​

ExportWhat it does
createContextCanvas-backed Context3D that projects and depth-sorts faces
createCameraPerspective or orthographic camera with orbit, pan and zoom
createAmbientLight … createSpotLightThe five light constructors, added via context.lights
createMaterialHow a surface responds to light
createTexture / loadTextureImages mapped across a surface
createCube … createBezierSurfaceThe nine built-in shapes
createGroup3DA group carrying a 3D transform for its subtree
Context3D.raycastAllEvery shape under a point, nearest first
computeFaceNormal / shadeFaceColorShading helpers for custom geometry
  • @ripl/web — the browser entry point supplying the scene, renderer and animation
  • @ripl/webgpu — GPU backend for the same Shape3D elements
  • @ripl/core — the element, scene and animation model these shapes build on

Documentation ​

Guides, live demos and the full API reference are at ripl.run/docs/3d.

License ​

MIT

Classes ​

ClassDescription
AmbientLightA light that reaches every surface equally, regardless of orientation.
BezierSurfaceA surface tessellated from one or more bicubic Bézier patches.
CameraAn interactive camera controlling the 3D context's view and projection, with mouse/touch orbit, pan, and zoom.
CanvasContext3DCanvas 2D–backed 3D rendering context with face buffer and painter's algorithm sorting.
ConeA 3D cone shape with configurable radius, height, and segment resolution.
Context3DBase 3D rendering context providing view/projection matrices, camera, lighting, and projection. Subclassed by CanvasContext3D and WebGPUContext3D.
CubeA 3D cube shape with uniform edge size.
CylinderA 3D cylinder shape with independent top and bottom radii for truncated cones.
DirectionalLightA light infinitely far away, casting parallel rays in a single direction.
Group3DA group whose transform composes into the model matrix of every Shape3D beneath it.
HemisphereLightA two-colour light that fades from Light.color overhead to groundColor underfoot.
LightBase class for every light, carrying the colour, intensity and enabled state they share.
LightListAn ordered, mutable collection of the lights illuminating a scene.
MeshA mesh built from an explicit list of faces.
ParametricA surface tessellated from a function of two parameters.
PlaneA flat rectangular 3D plane oriented along the XY plane.
PointLightA light radiating equally in every direction from a point.
PositionalLightBase class for lights that radiate from a position and fall off with distance.
Shape3DBase class for 3D shapes, handling model transforms, face projection, shading, and hit testing.
SphereA 3D sphere shape tessellated with configurable segments and rings.
SpotLightA light radiating from a point, confined to a cone with an optionally soft edge.
TextureAn image mapped onto a surface, usable by either backend.
TorusA 3D torus (donut) shape with configurable major radius, tube radius, and tessellation.

Interfaces ​

InterfaceDescription
BezierSurfaceOptionsOptions for constructing a BezierSurface.
BezierSurfaceStateState for a surface tessellated from Bézier patches.
CameraInteractionConfigFine-grained configuration for a single camera interaction.
CameraInteractionsConfigures which camera interactions (zoom, pivot, pan) are enabled.
CameraOptionsOptions for constructing a camera, including position, projection type, and interaction config.
ConeStateState interface for a cone, defining radius, height, and segment count.
Context3DMetaTyped metadata for 3D contexts.
Context3DOptionsOptions for the 3D rendering context, extending the base context options with camera parameters.
CubeStateState interface for a cube, defining uniform edge size.
CylinderStateState interface for a cylinder, defining top/bottom radii, height, and segment count.
DirectedLightOptionsOptions for a light that has an orientation.
Face3DA single face of a 3D mesh, defined by its vertices and an optional precomputed normal.
FogAtmospheric haze blending distant geometry towards a colour.
Group3DOptionsOptions for constructing a Group3D.
HemisphereLightOptionsOptions for HemisphereLight.
Intersection3DWhere a ray met a shape's geometry.
LightOptionsOptions shared by every light.
MaterialHow a surface responds to light.
MeshOptionsOptions for constructing a Mesh.
MeshStateState for a mesh built from an explicit face list.
MeshSubmissionA mesh submission queued for a single frame.
ModelUniformInputEverything the per-model uniform needs, independent of any particular backend.
ParametricOptionsOptions for constructing a Parametric.
ParametricStateState for a surface tessellated from a parametric function.
PlaneStateState interface for a plane, defining width and height.
PositionalLightOptionsOptions for a light that radiates from a point.
ProjectedFace3DA projected face ready for 2D rendering with screen-space points, fill/stroke styles, and depth.
ProjectedFaceState3DThe 2D drawing state resolved for an element at the moment its faces were projected.
RayA half-line in world space, used for picking and intersection queries.
Raycast3DOptionsOptions for a raycast against 3D geometry.
RayTriangleHitWhere a Ray met a triangle, in both distance and barycentric terms.
ResolvedFogFog reduced to the numeric form the scene uniform carries.
ResolvedLightA light reduced to the flat numeric form both the CPU painter and the WGSL shader consume.
ResolvedMaterialA material with every property resolved, as the render path consumes it.
ResolvedSurfaceA surface reduced to the numeric material terms the shading maths consumes.
SceneUniformInputEverything the scene uniform needs, independent of any particular backend.
Shape3DStateState interface for a 3D shape, defining position and rotation around each axis.
SphereStateState interface for a sphere, defining radius, longitudinal segments, and latitudinal rings.
SpotLightOptionsOptions for SpotLight.
SurfaceIlluminationThe light arriving at a surface, split so the diffuse term stays a plain multiplier.
TextureOptionsOptions for creating a Texture.
TexturePatternThe tile geometry and repetition a Texture maps onto, and the pattern built from it.
TorusStateState interface for a torus, defining major radius, tube radius, and segment counts.
UniformFieldA single field within a uniform struct.
ViewportViewport dimensions used for projection.

Type Aliases ​

Type AliasDescription
AmbientLightOptionsOptions for AmbientLight.
BezierPatchThe sixteen control points of a bicubic Bézier patch, in row-major order.
CameraInteractionOptionA camera interaction can be enabled/disabled with a boolean or configured with sensitivity.
ColorUnitRGBLinear RGB triple with each channel in the 0–1 range.
ColorUnitRGBARGBA quad with each channel in the 0–1 range.
DirectionalLightOptionsOptions for DirectionalLight.
FogModeHow fog thickens with distance from the camera.
LightModeDetermines whether the light direction is fixed in world space or follows the camera.
LightSpaceWhether a light's orientation is fixed in world space or follows the camera.
LightTypeThe kind of illumination a Light contributes.
MaterialSideWhich faces of a surface are drawn, relative to their counter-clockwise winding.
Matrix4A column-major 4×4 matrix stored as a 16-element Float64Array.
ParametricSurfaceEvaluates a surface at a point in its parameter domain.
PointLightOptionsOptions for PointLight.
ProjectedPointA 2D screen-space point with a depth component for z-ordering.
RenderStrategyThe rendering strategy used by a 3D context.
Shape3DDefaultsClass-level defaults for a 3D shape. Excludes scale, which Shape3D expands itself, and zIndex, which it derives from projected depth.
Shape3DOptionsOptions for constructing a 3D shape, with all state properties optional.
TextureFilterHow a texture is sampled between texels.
TexturePatternRepetitionThe createPattern repetition modes a texture's wrap modes resolve to.
TextureSourceAn image a Texture can be built from.
TextureWrapHow a texture coordinate outside the 0–1 range is resolved.
Vector2A 2-component vector represented as a labeled tuple [x, y].
Vector3A 3-component vector represented as a labeled tuple [x, y, z].

Variables ​

VariableDescription
DEFAULT_SURFACE_COLORThe colour used when an element has no fill and no material colour.
FOG_MODE_CODENumeric discriminators for each fog mode, shared by the packer and the shader.
interpolateVector3Interpolator factory for Vector3 values, using component-wise linear interpolation.
LIGHT_DIRECTIONPre-normalized light direction vectors for common light positions.
LIGHT_STRUCT_SIZEFloats occupied by one light in the scene uniform.
LIGHT_TYPE_CODENumeric discriminators for each light type, shared by the packer and the shader.
LIGHT_UNIFORM_FIELDSThe per-light fields, in declaration order.
MATERIAL_SIDE_CODENumeric discriminators for each material side, shared by the packer and the shader.
MAX_LIGHTSThe maximum number of lights a single render pass can carry.
MODEL_UNIFORM_BYTESSize in bytes of the model uniform buffer.
MODEL_UNIFORM_FIELDSThe per-model fields, in declaration order.
MODEL_UNIFORM_FLOATSFloats occupied by the whole model uniform.
MODEL_UNIFORM_WGSLThe WGSL declaration of the per-model uniform, generated from MODEL_UNIFORM_FIELDS.
PLAIN_SURFACEA surface with no specular response and no emission — the default for an element with only a fill.
SCENE_CAMERA_POSITION_OFFSETFloat offset of the camera position within the scene uniform.
SCENE_FOG_COLOR_OFFSETFloat offset of the fog colour and mode within the scene uniform.
SCENE_FOG_PARAMS_OFFSETFloat offset of the fog distance parameters within the scene uniform.
SCENE_LIGHT_COUNT_OFFSETFloat offset of the light count, packed into the camera position's unused w component.
SCENE_LIGHTS_OFFSETFloat offset of the first light within the scene uniform.
SCENE_UNIFORM_BYTESSize in bytes of the scene uniform buffer.
SCENE_UNIFORM_FIELDSThe scene uniform fields, in declaration order.
SCENE_UNIFORM_FLOATSFloats occupied by the whole scene uniform.
SCENE_UNIFORM_WGSLThe WGSL declaration of the scene uniform, generated from SCENE_UNIFORM_FIELDS.
VERTEX_FLOATSFloats per interleaved vertex: position(3), normal(3), colour(4), uv(2).

Functions ​

FunctionDescription
bernstein3Evaluates the four cubic Bernstein basis functions at t.
composeSurfaceColorComposes a shaded CSS colour from a surface's base colour and the light reaching it.
computeDistanceAttenuationComputes distance falloff for a positional light.
computeFaceBrightnessComputes a 0–1 brightness value for a face given its normal and a light direction.
computeFaceNormalComputes the surface normal of a face from its first three vertices via the cross product.
computeFogFactorComputes how far a surface has faded towards the fog colour.
computeSpotAttenuationComputes the cone falloff for a spot light.
contextIsContext3DType guard that checks whether a rendering context is a Context3D.
createAmbientLightCreates an AmbientLight.
createBezierSurfaceCreates a BezierSurface.
createCameraFactory function that creates a new Camera bound to a 3D context.
createConeFactory function that creates a new Cone instance.
createContextCreates a Canvas 2D–backed 3D rendering context attached to the given DOM target.
createCubeFactory function that creates a new Cube instance.
createCylinderFactory function that creates a new Cylinder instance.
createDirectionalLightCreates a DirectionalLight.
createGroup3DCreates a Group3D.
createHemisphereLightCreates a HemisphereLight.
createMaterialCreates a Material, filling in the defaults.
createMeshCreates a Mesh from an explicit face list.
createParametricCreates a Parametric surface.
createPlaneFactory function that creates a new Plane instance.
createPointLightCreates a PointLight.
createRayCreates a ray from an origin and a direction, normalising the direction.
createShape3DFactory function that creates a new Shape3D instance.
createSphereFactory function that creates a new Sphere instance.
createSpotLightCreates a SpotLight.
createSurfaceIlluminationCreates a zeroed SurfaceIllumination for shadeSurface to write into.
createTextureCreates a Texture from an image source.
createTorusFactory function that creates a new Torus instance.
elementIsBezierSurfaceType guard that checks whether a value is a BezierSurface instance.
elementIsConeType guard that checks whether a value is a Cone instance.
elementIsCubeType guard that checks whether a value is a Cube instance.
elementIsCylinderType guard that checks whether a value is a Cylinder instance.
elementIsGroup3DType guard that checks whether a value is a Group3D.
elementIsMeshType guard that checks whether a value is a Mesh instance.
elementIsParametricType guard that checks whether a value is a Parametric instance.
elementIsPlaneType guard that checks whether a value is a Plane instance.
elementIsShape3DType guard that checks whether a value is a Shape3D instance.
elementIsSphereType guard that checks whether a value is a Sphere instance.
elementIsTorusType guard that checks whether a value is a Torus instance.
evaluateBezierPatchEvaluates a bicubic Bézier patch at (u, v).
lightIsAmbientType guard that narrows a light to an AmbientLight.
lightIsCameraSpaceWhether a light's orientation follows the camera rather than being fixed in world space.
lightIsDirectionalType guard that narrows a light to a DirectionalLight.
lightIsHemisphereType guard that narrows a light to a HemisphereLight.
lightIsPointType guard that narrows a light to a PointLight.
lightIsPositionalType guard that narrows a light to one that radiates from a position.
lightIsSpotType guard that narrows a light to a SpotLight.
loadTextureLoads an image from a URL and wraps it in a Texture.
mat4CloneReturns a copy of the given matrix.
mat4ComposeComposes a transform from translation, per-axis rotation and scale, applied in that order.
mat4CreateCreates a zeroed 4×4 matrix.
mat4IdentityCreates a 4×4 identity matrix.
mat4InvertInverts a 4×4 matrix, or returns null when it is singular.
mat4LookAtConstructs a view matrix looking from eye toward target with the given up direction.
mat4MultiplyMultiplies two 4×4 matrices.
mat4NormalMatrixBuilds the normal matrix for a model matrix — the inverse transpose of its upper-3×3.
mat4OrthographicConstructs an orthographic projection matrix.
mat4PerspectiveConstructs a perspective projection matrix.
mat4RotateXApplies a rotation around the X axis to a matrix.
mat4RotateYApplies a rotation around the Y axis to a matrix.
mat4RotateZApplies a rotation around the Z axis to a matrix.
mat4ScaleApplies a scale transform to a matrix.
mat4TransformDirectionTransforms a direction vector by the upper-3×3 of a 4×4 matrix, ignoring translation.
mat4TransformDirectionInverseTransforms a direction vector by the transposed upper-3×3 of a 4×4 matrix, ignoring translation. For a rigid transform (rotation plus translation, such as a view matrix) the transposed rotation is its inverse, so this undoes mat4TransformDirection — use it to carry a direction from view space back into world space.
mat4TransformPointTransforms a 3D point by a 4×4 matrix, performing the perspective divide.
mat4TranslateApplies a translation to a matrix.
mat4TransposeReturns the transpose of a 4×4 matrix.
materialDrawsFaceWhether a face wound counter-clockwise should be drawn, given its signed screen area.
materialSideCodeThe numeric discriminator for a material side, as the model uniform carries it.
packModelUniformWrites the per-model uniform into a Float32Array laid out per MODEL_UNIFORM_FIELDS.
packSceneUniformWrites the scene uniform into a Float32Array laid out per SCENE_UNIFORM_FIELDS.
parametricNormalApproximates a parametric surface's normal at (u, v) from its numeric partial derivatives.
projectPointProjects a 3D world-space point onto 2D screen-space via a view-projection matrix and viewport.
rayAtReturns the point at distance along a ray.
rayFromScreenBuilds the world-space ray passing through a screen-space point.
rayHitBarycentricReconstructs a point on a triangle from the barycentric weights of a RayTriangleHit.
rayIntersectsBoxTests a ray against an axis-aligned bounding box using the slab method.
rayIntersectTriangleIntersects a ray with a triangle using the Möller–Trumbore algorithm.
rayIntersectTriangleBufferIntersects a ray with a triangle read straight out of a packed vertex buffer.
releaseTexturePatternCacheDrops every texture pattern cached against a context, together with the offscreen tile canvases the mirrored and ImageData-backed ones hold. Call it when the context is torn down.
resolveColorParses a CSS colour into 0–255 RGBA channels, caching the result.
resolveColorUnitRGBParses a CSS colour straight into unit-range RGB, falling back to fallback when unparseable.
resolveFogResolves fog into the numeric form the scene uniform and the CPU painter consume.
resolveLightFlattens a light into the numeric form shadeSurface and the scene uniform consume.
resolveLightColorResolves a light's colour and intensity into the premultiplied unit RGB the shading maths uses.
resolveMaterialResolves a material and an element's fill into the numeric form the render path consumes.
resolveTexturePatternBuilds the repeating CanvasPattern that maps a texture across a surface, caching it per context and texture version.
rgbaToUnitConverts 0–255 RGBA channels to the 0–1 range the shading maths and GPU buffers use.
rgbToUnitConverts 0–255 RGB channels to the 0–1 range the shading maths and GPU buffers use.
sampleTextureSamples a texture on the CPU, honouring its wrap modes, filter, flip and transform.
shadeFaceColorShades a color by a brightness factor (0–1), darkening or lightening the RGB channels.
shadeSurfaceResolves the light arriving at a surface point, writing into out rather than allocating.
tessellateParametricTessellates a parametric surface into a grid of quads with normals and UVs.
texturePatternRepetitionMaps a texture's wrap modes onto the createPattern repetition that reproduces them.
textureSourceHeightReturns an image source's height in pixels, or 0 when it has no intrinsic size yet.
textureSourceWidthReturns an image source's width in pixels, or 0 when it has no intrinsic size yet.
textureTransformUVApplies a texture's repeat and offset to a raw surface coordinate.
textureWrapCoordinateResolves a coordinate outside the unit range according to a wrap mode.
triangulateFacesFlatFlattens faces into the interleaved vertex buffer a GPU backend uploads.
triangulateFacesIndicesFan-triangulates faces into an index buffer addressing triangulateFacesFlat's vertices.
typeIsLightType guard that checks whether a value is any kind of Light.
typeIsTextureType guard that checks whether a value is a Texture.
typeIsVector2Type guard that checks whether a value is a Vector2 tuple.
typeIsVector3Type guard that checks whether a value is a Vector3 tuple.
unprojectPointReverses projectPoint, mapping a screen-space point at a given clip depth back into world space.
vec2AddReturns the component-wise sum of two vectors.
vec2DotComputes the dot product of two vectors.
vec2LengthReturns the Euclidean length of a vector.
vec2LerpLinearly interpolates between two vectors by factor t.
vec2MultiplyReturns the component-wise product of two vectors.
vec2NormalizeReturns the unit-length direction of a vector, or the zero vector if length is 0.
vec2ScaleScales a vector by a scalar.
vec2SubReturns the component-wise difference of two vectors.
vec3AddReturns the component-wise sum of two vectors.
vec3CrossComputes the cross product of two vectors.
vec3DistanceReturns the Euclidean distance between two points.
vec3DotComputes the dot product of two vectors.
vec3LengthReturns the Euclidean length of a vector.
vec3LerpLinearly interpolates between two vectors by factor t.
vec3NegateNegates all components of a vector.
vec3NormalizeReturns the unit-length direction of a vector, or the zero vector if length is 0.
vec3ScaleScales a vector by a scalar.
vec3SubReturns the component-wise difference of two vectors.
vec3TriangleNormalReturns the unit-length normal of the triangle a → b → c, wound counter-clockwise.