threejs-scenes
v3.0.0
Published
Strictly-typed factories and interfaces for building production-quality vanilla three.js (WebGL2) scenes: renderer/loop/dispose scaffolding, cameras, instancing, shaders, lighting, particles, post-processing, voxels, infinite worlds, and the context-injec
Maintainers
Readme
threejs-scenes
A Claude skill for building production-quality three.js WebGL scenes with
vanilla three.js (WebGL2) — no React-Three-Fiber, no Drei, no WebGPU. Just
three from its main entry point, authored to ship as a single self-contained
HTML artifact that runs in a sandboxed iframe with no build step.
download
- Skill package:
threejs-scenes.skill— build one locally withbun run package:skill(validatesSKILL.md, refreshes the bundled lib, zipsskill/) — the packagedskill/directory. Drop it into~/.claude/skills/(or~/.config/opencode/skills/) and unzip, or install it via Claude Code. - Live showcase: tuomashatakka.github.io/threejs-scenes-skill — semantic gallery of the runnable demos plus the full API reference.
Both are published automatically by the Publish showcase & skill GitHub
Actions workflow (.github/workflows/publish.yml) on every push to main.
what it does
When a request touches three.js / WebGL / 3D-in-the-browser, this skill gives the agent a curated body of reference docs, copy-ready script modules, and runnable HTML templates so it can build correct, performant scenes instead of re-deriving boilerplate every time.
It covers, end to end:
- scene scaffolding — renderer factory (DPR-capped, ACES, sRGB), a single
Clock-driven frame loop,
ResizeObserver-based resize, explicit disposal. - camera handling — perspective orbit, third-person follow, isometric orthographic; touch-first unified pointer gestures (mouse/touch/pen identical).
- instancing & draw-call reduction —
InstancedMeshandBatchedMeshto render thousands of objects in one draw call. - procedural generation — seeded
mulberry32RNG, value/simplex noise, Poisson-disk placement, runtime geometry/texture factories. - shaders — custom
ShaderMaterial/ GLSL (fresnel, scanlines, noise). - post-processing —
EffectComposerchains: bloom, colour grade, god rays, depth-of-field + chromatic aberration, film grain, glitch, HUD beams, stereoscopy. - voxels & infinite worlds — chunked storage, greedy meshing, origin rebasing.
- lighting — IBL environment + sun (tuned shadow frustum) + hemisphere fill.
- LLM-driven content — ai-sdk / Gemini tool schemas for generating scenes from text prompts, with validate-and-repair codegen flow.
core principles
- vanilla three.js only — portable, artifact-friendly, no framework lock-in.
- touch-first —
pointer*events exclusively,touch-action: noneon the canvas, pixel ratio capped at 2. - one writer per concern — a single camera writer (no double-lerp jitter), one frame loop, one composer.
- dispose what you own — three.js never auto-frees GPU memory; pooled/shared
materials are never disposed (see
references/production-lessons.md). - determinism — seeded factories so a scene is pixel-identical across reloads.
- draw-call discipline — instance before you add a second mesh.
package
This repo is also an importable, strictly-typed npm package that codifies
every skill pattern (and the production lessons from a shipping scene/
project) as well-typed factories and interfaces. Build it with bun run build
(emits dist/ with .d.ts files); three is a peer dependency.
The root barrel is curated: a hand-picked set of the most-used factories at
the top level, plus the full library grouped into six domain namespaces
(core, primitives, raster, compose, state, scaffold). Every namespace
is also a tree-shakeable subpath.
import {
// curated "hero" factories — the fast path to a running scene
createApp, bootstrapScene, createRenderer, createFrameLoop,
createStandardMaterial, createEmitter, createInfiniteGround,
// domain namespaces — the whole library, grouped by concern
core, primitives, raster, compose, state, scaffold,
} from 'threejs-scenes'
const app = createApp({ canvas }) // renderer + scene + camera + lighting + orbit + loop
const chunk = new primitives.VoxelChunk(16) // deep API lives in its namespace
app.start()
// or import a single domain directly (best for tree-shaking):
import { createBatchedBuildings } from 'threejs-scenes/primitives'
import { createComposer, createGradePass } from 'threejs-scenes/raster'Public entry points:
threejs-scenes— curated root: hero factories + the six domain namespacesthreejs-scenes/core— renderer, frame loop (incl. worker updates), clocks, store, createApp, input, projection, disposal, qualitythreejs-scenes/primitives— geometry, materials, procedural, instancing, voxelsthreejs-scenes/raster— lighting, cameras, post-processing, particlesthreejs-scenes/compose— scene modules, props, loaders, animation, skybox, eventsthreejs-scenes/state— controller protocol, tween/lerp transitions (store lives in/core)threejs-scenes/scaffold— one-call genre wiring (iso, orbit, tpp, rails, fps)threejs-scenes/webgpu— dedicated WebGPU post-processing and TSL effectsthreejs-scenes/jsx— declarative, reactive JSX layerthreejs-scenes/lib/*— raw, uncompiled TypeScript source (bundler-resolved; mirrorsdist/*1:1)
hooks (/jsx)
The threejs-scenes/jsx subpath exposes the library's main interfaces as
hooks (no React required). Inside a JSX function component the reconciler
provides the mounting runtime, so useScene(), useRenderer(), useCamera(),
useLoop(), useRng(), useSize(), useAspect(), useFrame(cb) and
useDispose(fn) just work; useFrameLoop(cb?, { fps }) and
useSignal / useDerived are callable anywhere.
import { render, h, useFrame, useSignal } from 'threejs-scenes/jsx'
function Spinner () {
const [angle, setAngle] = useSignal(0)
useFrame(({ delta }) => setAngle(a => a + delta))
return <mesh geometry='box' rotationY={angle} />
}
render(<Spinner />, { canvas })API reference
Generated from the built .d.ts files by bun run docs.
The vite site renders the full searchable API with runnable playgrounds at
the library page and keeps the old
api.html URL as a redirect.
threejs-scenes
A deliberately small surface: the shared type vocabulary, a hand-picked set of the most-used factories (createApp, the scaffolds, the go-to material/geometry/light/animation/prop/particle helpers), and the six domain namespaces below. The full library is grouped by concern behind core / primitives / raster / compose / state / scaffold.
applyTaper(function) — Taper: the two axes perpendicular toaxisscale from 1 tofactoralong it.function applyTaper(geo: THREE.BufferGeometry, factor: number, axis?: Axis): THREE.BufferGeometry;applyTwist(function) — Twist aroundaxis: rotation grows linearly from 0 toanglealong the axis.function applyTwist(geo: THREE.BufferGeometry, angle: number, axis?: Axis): THREE.BufferGeometry;attachPointerGesture(function) — Attach unified drag/pinch/tap/wheel gesture handling to an element.function attachPointerGesture(el: HTMLElement, callbacks: PointerGestureCallbacks, { tapThresholdMs, tapMovePx }?: PointerGestureOptions): () => void;el— Element to listen on, typically the render canvas. Itstouch-actionstyle is set tononeto disable native panning/zooming.callbacks— Gesture handlers; all optional.options— Tap detection thresholds. Defaults:tapThresholdMs: 250,tapMovePx: 8.- returns — Detach function removing all listeners. The
touch-actionoverride is not restored.
attachResizeObserver(function) — Keep the renderer and camera in sync with the canvas parent's size via a.function attachResizeObserver(renderer: THREE.WebGLRenderer, camera: THREE.Camera, canvas: HTMLCanvasElement, onResize?: ResizeHandler): () => void;- returns — Detach function that disconnects the observer.
bobClip(function) — Vertical bob (sine, seamless loop).function bobClip(amp?: number, duration?: number, name?: string): THREE.AnimationClip;bootstrapScene(function) — Bootstrap a minimal animated scene in one call: renderer, scene, perspective.function bootstrapScene({ canvas, onSetup }: BootstrapOptions): BootstrappedScene;options— Canvas plus optional setup callback; see BootstrapOptions.- returns — A BootstrappedScene exposing the live primitives and
dispose().
const { dispose } = bootstrapScene({ canvas, onSetup ({ scene }) { const mesh = new THREE.Mesh(geometry, material) scene.add(mesh) return ({ delta }) => { mesh.rotation.y += delta } }, })combineClips(function) — Merge several clips into one, layering all their tracks.function combineClips(name: string, clips: THREE.AnimationClip[]): THREE.AnimationClip;name— Name of the combined clip.clips— Clips whose tracks are concatenated; tracks targeting the same property will fight — combine complementary clips (spin + bob).- returns — One
AnimationClipplaying every input in parallel.
createAnimationController(function) — Wrap anAnimationMixerand its actions withplay/crossfade/stopand.function createAnimationController(root: THREE.Object3D, clips?: THREE.AnimationClip[], loop?: FrameLoop): AnimationController;root— Object the mixer binds to (the .glb scene or a procedural prop).clips— Clips to expose as named actions.loop— When given,tickauto-registers viaregisterUpdate.- returns — An
AnimationController.dispose()unregisters the tick, stops all actions, and uncaches the root so nothing leaks.
const anim = createAnimationController(model.scene, model.animations, ctx.loop) anim.play('walk', { fadeIn: 0.3 })createApp(function) — Build a complete unidirectional app shell: renderer, scene, camera, seeded.function createApp<S extends object = Record<string, unknown>, A = Partial<S>>({ canvas, state, reducer, seed, clock, renderer: rendererOptions, camera: cameraOptions, background, lighting, orbit, modules, onFrame, onResize, render, }: AppOptions<S, A>): App<S, A>;options— App configuration; see AppOptions. Onlycanvasis required.- returns — An App handle.
dispose()stops the loop, detaches gestures and the resize observer, disposes modules, lights, scene, and renderer.
const app = createApp({ canvas, state: { speed: 1 }, modules: [ turbineModule ], onFrame: (state, frame) => hud.update(state, frame.delta), }) app.start() // later: app.setState({ speed: 2 }); app.dispose()createClock(function) — Create an injectable simulation time source for the frame loop and.function createClock({ mode, step, maxSubSteps }?: ClockOptions): Clock;options— Mode plus fixed-step tuning. Defaults:mode: 'wall',step: 1/60,maxSubSteps: 5.- returns — A Clock;
reset()zeroes the accumulator and elapsed total.
createEmitter(function) — CPU-simulated billboard particle emitter: a fixed-capacityPointscloud.function createEmitter({ capacity, rate, bursts, lifetime, shape, speed, gravity, damping, size, sizeCurve, color, alphaCurve, rotation, texture, blending, seed, }: EmitterOptions): Emitter;options— Capacity (buffers size once), rate/bursts, lifetime range, spawn shape, motion, and appearance curves.- returns — An Emitter; add
objectto the scene andtickit.
const smoke = createEmitter({ capacity: 500, shape: { kind: 'cone', angle: 0.4 } }) scene.add(smoke.object) loop.onFrame(ctx => smoke.tick(ctx))createExtrudedMesh(function) — Extrude a 2D profile into a bevelled mesh.function createExtrudedMesh(options: ExtrudeOptions): THREE.Mesh;options— Profile,depth(default 1), bevel settings (on by default), and material (default matte standard).- returns — The extruded mesh with shadows enabled.
const gear = createExtrudedMesh({ shape: gearShape(12, 2, 1.4), depth: 0.5 })createFpsScaffold(function) — First-person scaffold: pointer-lock mouse look plus WASD/arrow movement.function createFpsScaffold<S extends object = Record<string, unknown>>({ state, speed, lookSpeed, eyeHeight, pointerLock, collide, groundHeight, ...appOptions }: FpsScaffoldOptions<S>): FpsScaffold<S>;options— State source,speed/lookSpeed/eyeHeight,pointerLocktoggle,collideandgroundHeighthooks, and the remainingAppOptions.- returns — An FpsScaffold with the app and an
orientation()reader for HUDs.
const fps = createFpsScaffold({ canvas, speed: 7, groundHeight: (x, z) => terrain.height(x, z) }) fps.app.start()createFrameLoop(function) — Create a frame loop that shares onerequestAnimationFramewith every other.function createFrameLoop({ clock: simClock, fps }?: FrameLoopOptions): FrameLoop;options— Optional sim clock and fps cap; see FrameLoopOptions.- returns — A FrameLoop.
dispose()stops the loop, clears subscribers, and terminates every worker update it owns.
createGpuEmitter(function) — GPGPU particle emitter: position and velocity live in float textures.function createGpuEmitter(renderer: THREE.WebGLRenderer, options: GpuEmitterOptions): Emitter;renderer— Renderer running the compute passes (WebGL2).options— Same appearance/motion contract as the CPU emitter.- returns — An Emitter;
burst/setRateare no-ops — particles respawn continuously as their lifetime wraps.
createInfiniteGround(function) — Endless-looking ground from a fixed grid of displaced plane tiles that.function createInfiniteGround({ tileSize, gridRadius, segments, displace, material, }?: InfiniteGroundOptions): InfiniteGround;options—tileSize(default 32),gridRadius(default 2 → 5×5 tiles), per-tilesegments, adisplace(x, z)height function, and material.- returns — An InfiniteGround;
heightAt(x, z)samples the same displacement used for the mesh.
createInstancedProp(function) — Scatter one prop as anInstancedMeshfield: builds a single sample from.function createInstancedProp(factory: PropFactory, options: InstancedPropOptions, ctx?: PropContext): InstancedPropResult;factory— Prop definition; itsinstancedhint merges underoptions.options— Count/radius/seed/placement overrides.ctx— Prop context (rng, loop).- returns — An InstancedPropResult ready to add to the scene.
createIsoCamera(function) — Orthographic isometric camera: positioned on a 45°-yaw tilted orbit and.function createIsoCamera(aspect: number, { viewSize, flavor, near, far, }?: IsoCameraOptions): THREE.OrthographicCamera;aspect— Viewport width / height.options— View size, flavor, near/far planes.- returns — A configured
OrthographicCameralooking at the origin.
createIsoScaffold(function) — Isometric-scene scaffold in one call:createAppwith an orthographic iso.function createIsoScaffold<S extends object = Record<string, unknown>>({ state, viewSize, flavor, near, far, pan, zoom, ground: groundOptions, ...appOptions }: IsoScaffoldOptions<S>): IsoScaffold<S>;options— State source, iso camera flavor, pan/zoom/ground settings, and the remainingAppOptions.- returns — An IsoScaffold exposing the app, camera, pan
focus, and ground handle.
const iso = createIsoScaffold({ canvas, state: store, ground: { tile: 8 } }) iso.app.start()createMatcapMaterial(function) — Matcap material.function createMatcapMaterial(matcap?: THREE.Texture | string): THREE.MeshMatcapMaterial;createNoise3D(function) — Seeded 3D simplex noise (classic Gustavson, seed-shuffled permutation.function createNoise3D(seed?: number): Noise3D;seed— Any integer; same seed → same field.- returns — A Noise3D with
sample,fbm, andridged.
createOrbitScaffold(function) — Product/model-viewer scaffold:createAppwith the built-in pointer orbit,.function createOrbitScaffold<S extends object = Record<string, unknown>>({ state, autoRotate, ...appOptions }: OrbitScaffoldOptions<S>): OrbitScaffold<S>;options— State source,autoRotatespeed, and the remainingAppOptions.- returns — An OrbitScaffold with the app, the
stagegroup, andfitTo(object, margin)which distances the camera so the object's bounding sphere fits withmarginheadroom (default 1.25).
const viewer = createOrbitScaffold({ canvas, autoRotate: 0.4 }) viewer.stage.add(model) viewer.fitTo(model) viewer.app.start()createProp(function) — Mount a prop definition: build its object, attach declared lights, and wire.function createProp(factory: PropFactory, ctx?: PropContext, options?: CreatePropOptions): PropInstance;factory— The prop definition (author withdefineProp).ctx— Prop context; passloopso clips advance with the frame loop.options— Setautoplay: falseto leave clips stopped.- returns — A
PropInstance;dispose()frees the controller and everything the prop built.
createPropComposite(function) — Assemble several mounted props into oneGroup, applying each part's.function createPropComposite(parts: CompositePart[]): PropComposite;parts— Props with optional local transforms.- returns — A PropComposite whose
objectis ready to add to the scene.
createRailsScaffold(function) — On-rails scaffold: an endless segment stream stitched into one curve and a.function createRailsScaffold<S extends object = Record<string, unknown>>({ state, segment, prefetchDistance, maxActive, lift, tension, yawRange, pitchRange, smoothing, speed, ...appOptions }: RailsScaffoldOptions<S>): RailsScaffold<S>;options— State source, the deterministicsegmentbuilder,prefetchDistance, plus segment-stream and path-camera tuning.- returns — A RailsScaffold with the app, the segment
stream, and the path-camerarig.
const ride = createRailsScaffold({ canvas, segment: (i, rng) => tunnelSegment(rng) }) ride.app.start()createRenderer(function) — Create aWebGLRendererwith production defaults: high-performance power.function createRenderer({ canvas, antialias, pixelRatioMax, shadows, toneMapping, toneMappingExposure, logarithmicDepthBuffer, }: RendererOptions): THREE.WebGLRenderer;options— Canvas plus overrides; see RendererOptions.- returns — The configured renderer. Create one per scene and never recreate it
per frame; call
dispose()on teardown.
createStandardMaterial(function) — Build a PBR material from a preset name (or raw params), merged with optional.function createStandardMaterial(presetOrParams?: StandardPresetName | THREE.MeshStandardMaterialParameters, overrides?: THREE.MeshStandardMaterialParameters): THREE.MeshStandardMaterial;createToonMaterial(function) — Cel-shadedMeshToonMaterialwith a nearest-filtered gradient map ofstepsbands (default 4).function createToonMaterial(options?: ToonOptions): THREE.MeshToonMaterial;createTppScaffold(function) — Third-person scaffold:createAppwith the built-in orbit disabled and a.function createTppScaffold<S extends object = Record<string, unknown>>({ state, target, offset, lookAhead, stiffness, rotationStiffness, ...appOptions }: TppScaffoldOptions<S>): TppScaffold<S>;options— State source, chasetarget, local-frameoffsetandlookAhead, damping stiffness, and the remainingAppOptions.- returns — A TppScaffold with the app and
setTarget.
const tpp = createTppScaffold({ canvas, target: hero, offset: [0, 4, -8] }) tpp.app.start()defineProp(function) — Validate + tag a prop definition.function defineProp(def: PropDefinition): PropFactory;displaceByNoise(function) — Push each vertex along its normal by seeded value noise.function displaceByNoise(geo: THREE.BufferGeometry, options?: NoiseDisplaceOptions): THREE.BufferGeometry;disposeScene(function) — Recursively free GPU resources underroot: every geometry plus every.function disposeScene(root: THREE.Object3D): void;gearShape(function) — GearShapewith square-profileteethand a center hole ofinnerRadius.function gearShape(teeth: number, outerRadius: number, innerRadius: number, toothDepth?: number): THREE.Shape;layoutGrid(function) — Arrange objects in a centered grid on thexz(default) orxyplane, mutating their positions.function layoutGrid(objects: THREE.Object3D[], options?: GridLayout): THREE.Object3D[];pulseScaleClip(function) — Uniform scale pulse betweenminandmax.function pulseScaleClip(min?: number, max?: number, duration?: number, name?: string): THREE.AnimationClip;resizeIsoCamera(function) — Rebuild an iso camera's frustum for a new aspect ratio (and any updateduserData.viewSize), then update the projection matrix.function resizeIsoCamera(camera: THREE.OrthographicCamera, aspect: number): void;roundedRectShape(function) — Rounded rectangleShapecentered on the origin;radiusclamps to half the smaller side.function roundedRectShape(width: number, height: number, radius: number): THREE.Shape;setupStandardLighting(function) — The go-to three-part lighting rig: PMREM room environment for IBL, a warm.function setupStandardLighting(scene: THREE.Scene, renderer: THREE.WebGLRenderer, options?: StandardLightingOptions): StandardLighting;scene— Scene to light.renderer— Renderer for PMREM generation.options— Per-part overrides.- returns — A StandardLighting handle for tuning and teardown.
const lights = setupStandardLighting(scene, renderer, { sun: { intensity: 2 } })spinClip(function) — Continuous 360° rotation aroundaxis.function spinClip(axis?: 'x' | 'y' | 'z', duration?: number, name?: string): THREE.AnimationClip;starShape(function) — StarShapealternating betweenouterRadiustips andinnerRadiusvalleys.function starShape(points: number, outerRadius: number, innerRadius: number): THREE.Shape;AnimationController(interface) — Wraps an AnimationMixer + its actions.Disposable(interface) — Anything that owns GPU or DOM resources and must be torn down explicitly.FrameCallback(type) — Per-frame subscriber invoked with the shared FrameContext.FrameContext(interface) — Per-frame context handed to every animated subsystem by the frame loop.FrameLoop(interface) — Self-contained Clock-driven frame loop.InstancePlaceFn(type) — Per-instance placement callback for instanced props.LoadedModel(interface) — Normalized result of loading a model file (glTF and friends).MaterialPoolLike(interface) — Minimal structural type for a material pool, so SceneContext can.ParamSpec(type) — A parameter specification used to coerce config- or LLM-driven content.ParamSpecMap(type) — Named parameter schema: one ParamSpec per parameter key.ParamValue(type) — A concrete parameter value after coercion against its ParamSpec.PlayOptions(interface) — Playback options for AnimationController.play.PointerGestureCallbacks(interface) — Unified pointer gesture callbacks.PointerGestureOptions(interface) — Tap-detection tuning forattachPointerGesture.PostEffectName(type) — Name of a built-in post-processing effect, as listed in a preset'spostFx.PropContext(interface) — Minimal context a prop needs to build + animate itself.PropDefinition(interface) — Declarative description of a reusable prop: how to build its Object3D, plus.PropFactory(type) — Alias of PropDefinition kept for API symmetry withdefineProp.PropInstance(interface) — A live, mounted prop.QualityPreset(interface) — Render budgets for one quality tier.QualitySettings(interface) — A resolved QualityPreset tagged with the tier it came from.QualityTier(type) — Device performance bucket used to pick a QualityPreset.SceneContext(interface) — Context injected into every scene module.SceneModule(interface) — A self-contained scene feature.SeededRng(interface) — Seeded pseudo-random stream.WorkerUpdateFn(type) — Off-thread frame handler run inside a Web Worker by.WorkerUpdateHandle(interface) — Handle returned by FrameLoop.registerWorkerUpdate.WorkerUpdateOptions(interface) — Options for FrameLoop.registerWorkerUpdate.import { createApp, raster, primitives } from 'threejs-scenes'
threejs-scenes/core
The canonical runtime core: the renderer and canvas, the animation-frame loop (including worker-offloaded updates) and injectable clocks, the serializable store, the createApp shell, raw pointer-gesture input, overlay compositing, screen projection, disposal, and device-tier quality detection. Nothing in this layer knows what the scene contains.
attachPointerGesture(function) — Attach unified drag/pinch/tap/wheel gesture handling to an element.function attachPointerGesture(el: HTMLElement, callbacks: PointerGestureCallbacks, { tapThresholdMs, tapMovePx }?: PointerGestureOptions): () => void;el— Element to listen on, typically the render canvas. Itstouch-actionstyle is set tononeto disable native panning/zooming.callbacks— Gesture handlers; all optional.options— Tap detection thresholds. Defaults:tapThresholdMs: 250,tapMovePx: 8.- returns — Detach function removing all listeners. The
touch-actionoverride is not restored.
attachResizeObserver(function) — Keep the renderer and camera in sync with the canvas parent's size via a.function attachResizeObserver(renderer: THREE.WebGLRenderer, camera: THREE.Camera, canvas: HTMLCanvasElement, onResize?: ResizeHandler): () => void;- returns — Detach function that disconnects the observer.
bootstrapScene(function) — Bootstrap a minimal animated scene in one call: renderer, scene, perspective.function bootstrapScene({ canvas, onSetup }: BootstrapOptions): BootstrappedScene;options— Canvas plus optional setup callback; see BootstrapOptions.- returns — A BootstrappedScene exposing the live primitives and
dispose().
const { dispose } = bootstrapScene({ canvas, onSetup ({ scene }) { const mesh = new THREE.Mesh(geometry, material) scene.add(mesh) return ({ delta }) => { mesh.rotation.y += delta } }, })createApp(function) — Build a complete unidirectional app shell: renderer, scene, camera, seeded.function createApp<S extends object = Record<string, unknown>, A = Partial<S>>({ canvas, state, reducer, seed, clock, renderer: rendererOptions, camera: cameraOptions, background, lighting, orbit, modules, onFrame, onResize, render, }: AppOptions<S, A>): App<S, A>;options— App configuration; see AppOptions. Onlycanvasis required.- returns — An App handle.
dispose()stops the loop, detaches gestures and the resize observer, disposes modules, lights, scene, and renderer.
const app = createApp({ canvas, state: { speed: 1 }, modules: [ turbineModule ], onFrame: (state, frame) => hud.update(state, frame.delta), }) app.start() // later: app.setState({ speed: 2 }); app.dispose()createClock(function) — Create an injectable simulation time source for the frame loop and.function createClock({ mode, step, maxSubSteps }?: ClockOptions): Clock;options— Mode plus fixed-step tuning. Defaults:mode: 'wall',step: 1/60,maxSubSteps: 5.- returns — A Clock;
reset()zeroes the accumulator and elapsed total.
createFrameLoop(function) — Create a frame loop that shares onerequestAnimationFramewith every other.function createFrameLoop({ clock: simClock, fps }?: FrameLoopOptions): FrameLoop;options— Optional sim clock and fps cap; see FrameLoopOptions.- returns — A FrameLoop.
dispose()stops the loop, clears subscribers, and terminates every worker update it owns.
createOverlayScene(function) — Create a second scene rendered on top of the main one with the depth buffer.function createOverlayScene(camera: THREE.Camera): OverlayHandle;camera— Camera the overlay is rendered through, usually the main scene camera.- returns — An OverlayHandle exposing the overlay
sceneand itspass.
createRenderer(function) — Create aWebGLRendererwith production defaults: high-performance power.function createRenderer({ canvas, antialias, pixelRatioMax, shadows, toneMapping, toneMappingExposure, logarithmicDepthBuffer, }: RendererOptions): THREE.WebGLRenderer;options— Canvas plus overrides; see RendererOptions.- returns — The configured renderer. Create one per scene and never recreate it
per frame; call
dispose()on teardown.
createStore(function) — Create a minimal store holding serializable app state.function createStore<S extends object, A = Partial<S>>(initial: S, reducer?: Reducer<S, A>): Store<S, A>;initial— Starting state. Keep it JSON-serializable (tuples, notVector3s) so it can be persisted and replayed.reducer— Optional Reducer enablingdispatch; without one,dispatchthrows.- returns — A Store.
detectTier(function) — Detect the device quality tier from cheap navigator/window heuristics.function detectTier(): QualityTier;disposeMaterial(function) — Dispose a material and every texture it references.function disposeMaterial(mat: THREE.Material): void;disposeScene(function) — Recursively free GPU resources underroot: every geometry plus every.function disposeScene(root: THREE.Object3D): void;getQualitySettings(function) — Resolve the preset for a tier into a QualitySettings object with the.function getQualitySettings(tier?: QualityTier): QualitySettings;projectToScreenUv(function) — Project an object's world position to 0..1 screen UV space for effect.function projectToScreenUv(object: THREE.Object3D, camera: THREE.Camera, out?: ScreenProjection): ScreenProjection;object— Object whose world position is projected; its world matrix must be current.camera— Camera defining the projection.out— Optional result object to fill; pass a reused one for zero per-frame allocation.- returns — The filled ScreenProjection (the same
outinstance when provided).
renderOverlay(function) — Composer-free path: call after renderer.render(mainScene, camera).function renderOverlay(renderer: THREE.WebGLRenderer, overlayScene: THREE.Scene, camera: THREE.Camera): void;QUALITY_PRESETS(const) — Baseline render budgets per QualityTier: pixel ratio, shadow map.App(interface) — Running app shell returned by createApp.AppCameraOptions(interface) — Perspective-camera setup for createApp.AppModule(interface) — A scene feature in the unidirectional flow.AppOptions(interface) — Configuration for createApp.BootstrapOptions(interface) — Options for bootstrapScene.BootstrappedScene(interface) — Running scene returned by bootstrapScene.BootstrapSetup(type) — One-time setup callback for bootstrapScene.BootstrapSetupContext(interface) — Scene primitives handed to the BootstrapSetup callback.Clock(interface) — A simulation time source.ClockMode(type) — Time-advance strategy:'wall'passes real deltas through,'fixed'emits fixed-size steps.ClockOptions(interface) — Options for createClock.FrameLoopOptions(interface) — Options for createFrameLoop.OverlayHandle(interface) — Handle returned by createOverlayScene.Reducer(type) — Pure state transition: returns the next state for an action, never mutates.RendererOptions(interface) — Options for createRenderer.ResizeHandler(type) — Callback invoked after a resize with the new width and height in CSS pixels.ScreenProjection(interface) — Screen-space projection result from projectToScreenUv.Store(interface) — Minimal serializable store — the single writer of app state.StoreListener(type) — Change subscriber invoked with the new state and the state it replaced.import { createRenderer, createFrameLoop, createStore } from 'threejs-scenes/core'
threejs-scenes/primitives
Things you can put in a scene: geometry construction (shapes, extrusion, lathe, tubes), vertex manipulation and merging, materials and procedural textures, seeded noise/scatter, instanced and batched high-count meshes, and voxel storage + meshing. Everything that takes a seed is deterministic.
applyBend(function) — Bend the geometry into an arc ofangleradians around itsaxisextent.function applyBend(geo: THREE.BufferGeometry, angle: number, axis?: Axis): THREE.BufferGeometry;applyTaper(function) — Taper: the two axes perpendicular toaxisscale from 1 tofactoralong it.function applyTaper(geo: THREE.BufferGeometry, factor: number, axis?: Axis): THREE.BufferGeometry;applyTwist(function) — Twist aroundaxis: rotation grows linearly from 0 toanglealong the axis.function applyTwist(geo: THREE.BufferGeometry, angle: number, axis?: Axis): THREE.BufferGeometry;createBatchedBuildings(function) — Batch N different geometries under one shared material into a single.function createBatchedBuildings({ geometries, material, transforms, sortObjects, perObjectFrustumCulled, }: BatchedBuildingsOptions): THREE.BatchedMesh;options— Geometries, shared material, and oneMatrix4per instance (geometryi % geometries.lengthis used for transformi).- returns — The
BatchedMesh; hide individual instances withsetVisibleAt(id, false).
createConnectionGraph(function) — Connect points into a nearest-neighborLineSegmentsnetwork — each node.function createConnectionGraph(nodes: ReadonlyArray<readonly [number, number, number]>, { neighbors, maxDistance, color, highlightColor, opacity, }?: ConnectionGraphOptions): ConnectionGraph;nodes— Node positions as xyz tuples.options— Neighbor count, distance cutoff, colors.- returns — A ConnectionGraph; set
progressfrom 0 to 1 to animate edges drawing in.
createExtrudedMesh(function) — Extrude a 2D profile into a bevelled mesh.function createExtrudedMesh(options: ExtrudeOptions): THREE.Mesh;options— Profile,depth(default 1), bevel settings (on by default), and material (default matte standard).- returns — The extruded mesh with shadows enabled.
const gear = createExtrudedMesh({ shape: gearShape(12, 2, 1.4), depth: 0.5 })createGradientToonMap(function) — Quantized gradient ramp for cel shading — NearestFilter keeps the bands hard.function createGradientToonMap(steps?: number): THREE.DataTexture;createHolographicMaterial(function) — Sci-fi hologramShaderMaterial: fresnel rim glow, animated scanlines, and.function createHolographicMaterial({ baseColor, fresnelStrength, scanlineDensity, opacity, }?: HolographicMaterialOptions): TickableMaterial;options— Color and effect tuning.- returns — A TickableMaterial; call
material.userData.tick(ctx)each frame (or register it with the loop) to animate.
createInfiniteGround(function) — Endless-looking ground from a fixed grid of displaced plane tiles that.function createInfiniteGround({ tileSize, gridRadius, segments, displace, material, }?: InfiniteGroundOptions): InfiniteGround;options—tileSize(default 32),gridRadius(default 2 → 5×5 tiles), per-tilesegments, adisplace(x, z)height function, and material.- returns — An InfiniteGround;
heightAt(x, z)samples the same displacement used for the mesh.
createInstancedField(function) — One geometry × N transforms as a singleInstancedMeshdraw call — grass,.function createInstancedField({ geometry, material, count, radius, seed, hueBase, hueSpread, scaleMin, scaleMax, place, }: InstancedFieldOptions): THREE.InstancedMesh;options— Geometry, material,count(buffers size once), and placement tuning.- returns — The
InstancedMeshwith per-instance colors enabled.
createLatheMesh(function) — Revolve a 2D profile of[radius, y]pairs around the Y axis — vases, columns, chess pieces.function createLatheMesh(profile: ReadonlyArray<readonly [number, number] | THREE.Vector2>, options?: LatheOptions): THREE.Mesh;createMatcapMaterial(function) — Matcap material.function createMatcapMaterial(matcap?: THREE.Texture | string): THREE.MeshMatcapMaterial;createNoise3D(function) — Seeded 3D simplex noise (classic Gustavson, seed-shuffled permutation.function createNoise3D(seed?: number): Noise3D;seed— Any integer; same seed → same field.- returns — A Noise3D with
sample,fbm, andridged.
createNoiseTexture(function) — Seamlessly tileable seeded noise as aDataTexture— the noise is sampled.function createNoiseTexture({ size, frequency, octaves, seed, channels, }?: NoiseTextureOptions): THREE.DataTexture | null;options— Size (default 256), frequency, octaves, seed, channels.- returns — The texture, or
nullin DOM-less runtimes (degrade to flat colour instead of crashing).
createPathTube(function) — Sweep a circle through parallel-transport frames alongpoints.function createPathTube(points: THREE.Vector3[], { radius, radialSegments, inward, vRepeat }?: PathTubeOptions): THREE.BufferGeometry;createProceduralBody(function) — Procedural celestial body: a noise-displaced icosphere terrestrial with.function createProceduralBody({ radius, detail, seed, type, displacement, frequency, octaves, ridged, palette, water, clouds, rings, }?: ProceduralBodySpec): ProceduralBody;spec— Body recipe; see ProceduralBodySpec.- returns — A ProceduralBody; add
objectto the scene andtickit.
const planet = createProceduralBody({ seed: 7, type: 'terrestrial', water: true }) scene.add(planet.object)createSeededRng(function) — Seeded random stream with the fork-per-consumer determinism API: seed.function createSeededRng(seed: number): SeededRng;seed— Any integer.- returns — A
SeededRngwithnext/range/int/pick/fork.
const rng = createSeededRng(42) const grass = rng.fork('grass') // stable regardless of call ordercreateShaderQuad(function) — Fullscreen fragment-shader runner: one fullscreen triangle and a.function createShaderQuad({ fragmentShader, uniforms, pointerElement }: ShaderQuadOptions): ShaderQuad;options— Fragment shader, extra uniforms, pointer element.- returns — A ShaderQuad: use
render(ctx, renderer)for shader-only scenes orupdate+ your own composition as a backdrop layer.
const quad = createShaderQuad({ fragmentShader: RAYMARCH_GLSL }) loop.onFrame(ctx => quad.render(ctx, renderer))createStandardMaterial(function) — Build a PBR material from a preset name (or raw params), merged with optional.function createStandardMaterial(presetOrParams?: StandardPresetName | THREE.MeshStandardMaterialParameters, overrides?: THREE.MeshStandardMaterialParameters): THREE.MeshStandardMaterial;createToonMaterial(function) — Cel-shadedMeshToonMaterialwith a nearest-filtered gradient map ofstepsbands (default 4).function createToonMaterial(options?: ToonOptions): THREE.MeshToonMaterial;createTriplanarMaterial(function) — World-space triplanar gridShaderMaterial: UVs are picked per fragment.function createTriplanarMaterial({ palette, tileScale, fogDistance, side, }?: TriplanarMaterialOptions): THREE.ShaderMaterial;options— Palette, tile scale, fog distance, side.- returns — The configured
ShaderMaterial.
displaceByNoise(function) — Push each vertex along its normal by seeded value noise.function displaceByNoise(geo: THREE.BufferGeometry, options?: NoiseDisplaceOptions): THREE.BufferGeometry;edgeSplit(function) — Split shared vertices across hard edges so flat-shaded creases stay sharp.function edgeSplit(geo: THREE.BufferGeometry, cutOffAngleRad?: number, keepNormals?: boolean): THREE.BufferGeometry;extrudeAlongPath(function) — Sweep a 2Dshapealong a 3D curve into a mesh — rails, pipes, ribbons.function extrudeAlongPath(shape: THREE.Shape, path: THREE.Curve<THREE.Vector3>, options?: ExtrudeAlongPathOptions): THREE.Mesh;gearShape(function) — GearShapewith square-profileteethand a center hole ofinnerRadius.function gearShape(teeth: number, outerRadius: number, innerRadius: number, toothDepth?: number): THREE.Shape;greedyMesh(function) — Greedy voxel meshing: merges coplanar same-id faces into maximal.function greedyMesh(chunk: VoxelChunk): THREE.BufferGeometry;chunk— The voxel data to mesh.- returns — An indexed
BufferGeometrywith normals and per-face vertex colors derived from voxel ids.
hash2(function) — Stateless 2D coordinate hash to [0, 1) — cheap lattice noise, no seed state.function hash2(x: number, y: number): number;hash3(function) — Stateless 3D coordinate hash to [0, 1).function hash3(x: number, y: number, z: number): number;lerp(function) — Linear interpolation fromatobbyt.function lerp(a: number, b: number, t: number): number;mergeGeometryList(function) — Merge a raw list of geometries (assumed already in a common space).function mergeGeometryList(geometries: THREE.BufferGeometry[], useGroups?: boolean): THREE.BufferGeometry;mergeMeshes(function) — Mergemeshesinto a single Mesh when they share one material, or a Group of.function mergeMeshes(meshes: THREE.Mesh[]): THREE.Object3D;mergeVertices(function) — Weld duplicate vertices withintolerance(indexes the geometry).function mergeVertices(geo: THREE.BufferGeometry, tolerance?: number): THREE.BufferGeometry;mulberry32(function) — Tiny fast seeded PRNG: returns a() => numberyielding uniform values in [0, 1).function mulberry32(seed: number): () => number;parallelTransportFrames(function) — Twist-free coordinate frames along a polyline (parallel transport).function parallelTransportFrames(points: THREE.Vector3[]): TransportFrames;poissonDisk(function) — Poisson-disk 2D sampling (Bridson): points with a guaranteed minimum.function poissonDisk({ width, height, minDist, rng, k, }: PoissonDiskOptions): Point2[];options— Regionwidth/height,minDistspacing, seededrng, andkcandidate attempts per sample (default 30).- returns — The accepted Point2 samples in [0,width]×[0,height].
polygonShape(function) — Regular polygonShapewithsidesvertices on a circle ofradius, first vertex at the top.function polygonShape(sides: number, radius: number): THREE.Shape;recomputeNormals(function) — Recompute vertex normals after deforming a geometry — call once after the last modifier.function recomputeNormals(geo: THREE.BufferGeometry): THREE.BufferGeometry;ringShape(function) — AnnulusShape: a disc ofouterRadiuswith aninnerRadiushole.function ringShape(outerRadius: number, innerRadius: number): THREE.Shape;roundedRectShape(function) — Rounded rectangleShapecentered on the origin;radiusclamps to half the smaller side.function roundedRectShape(width: number, height: number, radius: number): THREE.Shape;simplifyGeometry(function) — Collapse to roughlytargetCountvertices via SimplifyModifier.function simplifyGeometry(geo: THREE.BufferGeometry, targetCount: number): THREE.BufferGeometry;smoothstep(function) — Hermite smoothstep: 0 belowedge0, 1 aboveedge1, smooth in between.function smoothstep(edge0: number, edge1: number, x: number): number;starShape(function) — StarShapealternating betweenouterRadiustips andinnerRadiusvalleys.function starShape(points: number, outerRadius: number, innerRadius: number): THREE.Shape;tessellateGeometry(function) — Subdivide long edges.function tessellateGeometry(geo: THREE.BufferGeometry, maxEdgeLength?: number, iterations?: number): THREE.BufferGeometry;VoxelChunk(class) — Cubic voxel chunk: flatUint16Arraystorage with bounds-checked.const chunk = new VoxelChunk(16) chunk.set(0, 0, 0, 1) const geometry = greedyMesh(chunk)MATERIAL_PRESETS(const) — The tunedMeshStandardMaterialparameter sets behind each StandardPresetName.Axis(type) — A principal axis name, used by the geometry deformers and layout helpers.BatchedBuildingsOptions(interface) — Options for createBatchedBuildings: the geometry variants, ONE shared material, and per-instance transforms.ConnectionGraph(interface) — Nearest-neighbor line network.ConnectionGraphOptions(interface) — Options for createConnectionGraph:neighborsper node,maxDistanceedge cutoff, and line colors.ExtrudeAlongPathOptions(interface) — Options for extrudeAlongPath: sweepsteps, bevel toggle, curve resolution, and material.ExtrudeOptions(interface) — Options for createExtrudedMesh: the 2D profile (shapeor rawpoints), depth, bevel tuning, and material.HolographicMaterialOptions(interface) — Options for createHolographicMaterial: base color, fresnel rim strength, scanline density, and opacity.InfiniteGround(interface) — Recentering tiled terrain.InfiniteGroundOptions(interface) — Options for createInfiniteGround: tile size/radius/resolution, adisplaceheight function, and material.InstancedFieldOptions(interface) — Options for createInstancedField: geometry/material/count plus seeded scatter tuning (radius, hue, scale) or a customplace.InstancePlacement(interface) — Scratch pair handed to a PlaceFn: set theobjecttransform and instancecolor.LatheOptions(interface) — Options for createLatheMesh: radialsegments, partial-revolution angles, and material.Noise3D(interface) — Seeded 3D simplex noise field with fractalfbmandridgedsums.NoiseDisplaceOptions(interface) — Options for displaceByNoise: amplitude, frequency, and aseedor SeededRng for determinism.NoiseTextureOptions(interface) — Options for createNoiseTexture: texturesize, noise frequency/octaves/seed, and whichchannelsget independent noise.PathTubeOptions(interface) — Options for createPathTube: constant-or-variableradius, cross-section resolution, inward normals, and V-repeat.PlaceFn(type) — Places instanceindex: mutateobjectposition/rotation/scale andcolor;rngis the field's seeded stream.Point2(type) — An[x, y]sample point.PoissonDiskOptions(interface) — Options for poissonDisk: region size, minimum spacing, the random stream, and attempts-per-samplek.ProceduralBody(interface) — A generated celestial body.ProceduralBodySpec(interface) — Recipe for createProceduralBody: radius/detail/seed, bodytype, noise displacement tuning, palette, and water/cloud/ring shells.ShaderQuad(interface) — A self-contained fullscreen shader scene.ShaderQuadOptions(interface) — Options for createShaderQuad: the fragment shader, extra uniforms, and an optional pointer-tracking element.StandardPresetName(type) — Built-in PBR preset names forcreateStandardMaterial.TickableMaterial(interface) — AShaderMaterialcarrying auserData.tick(ctx)that advances its time uniform — register it on the frame loop.ToonOptions(interface) — Options for createToonMaterial: flatcolorand gradientsteps.TransportFrames(interface) — Per-point tangent/normal/binormal frames along a polyline, twist-free via parallel transport.TriplanarMaterialOptions(interface) — Options for createTriplanarMaterial: three-colorpalette, gridtileScale, fog distance, and side mode.VoxelVisitor(type) — Callback receiving each voxel's coordinates and id during iteration.import { createExtrudedMesh, VoxelChunk } from 'threejs-scenes/primitives'
threejs-scenes/raster
How the scene turns into pixels: lighting rigs, cameras, color correction and post-processing chains, and particle emitters (render-technique-bound: billboards, GPGPU, blending). WebGPU/TSL node effects stay off this barrel — import them from /webgpu.
applyEnvironment(function) — Generate a PMREM environment map and assign it asscene.environmentfor.function applyEnvironment(scene: THREE.Scene, renderer: THREE.WebGLRenderer, { intensity, envScene }?: EnvironmentOptions): THREE.Texture;scene— Scene receiving the environment.renderer— Renderer used by the PMREM generator.options— Intensity and optional custom environment scene.- returns — The environment texture — dispose it when done (the default environment scene's geometry is freed immediately).
bakeCurve(function) — Bake a scalar curve into a Float32Array LUT ofresolutionsamples.function bakeCurve(curve: ScalarCurve, resolution?: number): Float32Array;bakeCurveTexture(function) — Bake color + alpha + size curves into one 2-row RGBA DataTexture:.function bakeCurveTexture(color: ColorCurve, alpha: ScalarCurve, size: ScalarCurve, resolution?: number): THREE.DataTexture;createBlockDisplacementPass(function) — Create a ShaderPass that displaces and swaps colour channels in pseudo-random blocks for a datamosh glitch effect.function createBlockDisplacementPass(): ShaderPass;createCameraController(function) — Multi-mode camera state machine:free,flyTo,follow, andcockpit.function createCameraController(camera: THREE.PerspectiveCamera, { stiffness, lookStiffness, fovStiffness, arriveEpsilon, bounds, }?: CameraControllerOptions): CameraController;camera— The perspective camera to drive.options— Stiffness, arrival epsilon, and optional bounds.- returns — A CameraController; call
update(ctx)every frame.
const rig = createCameraController(camera, { stiffness: 5 }) rig.flyTo([0, 12, 30], [0, 0, 0], { onArrive: () => rig.follow(ship) }) loop.onFrame(ctx => rig.update(ctx))createCinematicLUT(function) — Build a cinematic colour-grading 3D LUT as aData3DTexture: a gentle.function createCinematicLUT(size?: number, { contrast, splitTone, saturation }?: CinematicLutOptions): THREE.Data3DTexture;createComposer(function) — Create an EffectComposer wired with RenderPass and OutputPass, optionally adding a DepthTexture and UnrealBloomPass.function createComposer({ renderer, scene, camera, width, height, withDepth, withBloom, bloomStrength, bloomRadius, bloomThreshold, }: ComposerOptions): ComposerHandle;createDofPass(function) — Create a ShaderPass that applies depth-of-field blur modulated by circle-of-confusion, with radial chromatic separation.function createDofPass({ focalDistance, focalRange, maxBlur, caStrength, near, far, }?: DofPassOptions): DofPass;createEmitter(function) — CPU-simulated billboard particle emitter: a fixed-capacityPointscloud.function createEmitter({ capacity, rate, bursts, lifetime, shape, speed, gravity, damping, size, sizeCurve, color, alphaCurve, rotation, texture, blending, seed, }: EmitterOptions): Emitter;options— Capacity (buffers size once), rate/bursts, lifetime range, spawn shape, motion, and appearance curves.- returns — An Emitter; add
objectto the scene andtickit.
const smoke = createEmitter({ capacity: 500, shape: { kind: 'cone', angle: 0.4 } }) scene.add(smoke.object) loop.onFrame(ctx => smoke.tick(ctx))createFilmGrainPass(function) — Create a ShaderPass that applies procedural per-fragment film grain with optional luminance-only mode and desaturation.function createFilmGrainPass({ intensity, luma, desat, }?: FilmGrainOptions): ShaderPass;createFollowCamera(function) — Chase camera: keepsoffsetin the target's local frame and looks at a.function createFollowCamera(camera: THREE.Camera, target: THREE.Object3D, { offset, lookAhead, stiffness, rotationStiffness, }: FollowCameraOptions): CameraController;camera— Camera to move.target— Object to chase; swap via the returned controller'sfollow.options— Offset (required), look-ahead, and stiffness tuning.- returns — A
CameraControllerlocked to follow mode; callupdate(ctx)every frame.
createGodRaysPass(function) — Create a GodRaysPass that ray-marches from each fragment toward the light's screen-space position, accumulating scattered brightness (GPU Gems 3 ch.13 algorithm).function createGodRaysPass(): GodRaysPass;createGpuEmitter(function) — GPGPU particle emitter: position and velocity live in float textures.function createGpuEmitter(renderer: THREE.WebGLRenderer, options: GpuEmitterOptions): Emitter;renderer— Renderer running the compute passes (WebGL2).options— Same appearance/motion contract as the CPU emitter.- returns — An Emitter;
burst/setRateare no-ops — particles respawn continuously as their lifetime wraps.
createGradePass(function) — Create a ShaderPass that applies tint, contrast, saturation, vignette, seeded grain, and radial chromatic aberration in linear HDR.function createGradePass({ tint, contrast, saturation, vignette, grain, chromatic, }?: GradePassOptions): GradePass;createHemisphereFill(function) — Soft ambient fill: aHemisphereLightblending sky and ground bounce colors (defaults: cool sky, warm earth, 0.4).function createHemisphereFill({ skyColor, groundColor, intensity, }?: HemisphereFillOptions): THREE.HemisphereLight;createHudBeamTransition(function) — Create a horizontal beam-sweep transition that reveals content with RGB-split fringes.function createHudBeamTransition({ duration, beamWidth, beamColor, onComplete, }?: HudBeamOptions): HudBeamTransition;createIsoCamera(function) — Orthographic isometric camera: positioned on a 45°-yaw tilted orbit and.function createIsoCamera(aspect: number, { viewSize, flavor, near, far, }?: IsoCameraOptions): THREE.OrthographicCamera;aspect— Viewport width / height.options— View size, flavor, near/far planes.- returns — A configured
OrthographicCameralooking at the origin.
createLightCone(function) — Fake volumetric light shaft: an open additive-blended cone fromfromto.function createLightCone(from: THREE.Vector3, to: THREE.Vector3, { color, spread }?: LightConeOptions): THREE.Mesh;from— Apex (the light source position).to— Where the beam lands; sets length and orientation.options— Color and spread.- returns — The cone mesh; dispose its geometry/material when done.
createLightingRig(function) — Preset-driven stage rig: hemisphere + key + rim + accent + spot lights and.function createLightingRig(scene: THREE.Scene, renderer: THREE.WebGLRenderer, { preset, shadows, presets }?: LightingRigOptions): LightingRig;scene— Scene the rig lights.renderer— Renderer whosetoneMappingExposurepresets control.options— Initial preset, shadow toggle, and extra presets.- returns — A LightingRig.
const rig = createLightingRig(scene, renderer, { preset: 'neon' }) rig.setPreset('dramatic')createPathCamera(function) — Rail-riding camera: advancesdistancealong the source curve atspeed,.function createPathCamera(camera: THREE.PerspectiveCamera, path: PathCameraSource, element: HTMLElement, { yawRange, pitchRange, smoothing, speed }?: PathCameraOptions): PathCamera;camera— Perspective camera to drive.source— Curve + total length; may be swapped between frames (segment streams rebuild it as segments append).element— Element whose pointer movement drives look-around.options— Ranges, smoothing, and speed.- returns — A PathCamera; call
update(ctx)once per frame.
createPostPipeline(function) — Create a PostPipeline with a named-pass registry.function createPostPipeline({ renderer, scene, camera, width, height, withDepth, }: PostPipelineOptions): PostPipeline;createRgbShiftPass(function) — Create a ShaderPass that separates RGB channels along a configurable angle for a chromatic glitch effect.function createRgbShiftPass(): ShaderPass;createScanCorruptionPass(function) — Create a ShaderPass that adds horizontal scan-line jitter and brightness spikes for a corrupt-signal glitch effect.function createScanCorruptionPass(): ShaderPass;createStereoRenderer(function) — Create a StereoRenderer for the given mode.function createStereoRenderer(renderer: THREE.WebGLRenderer, mode: StereoMode, { width, height }?: StereoSizeOptions): StereoRenderer;createSun(function) — Warm shadow-castingDirectionalLightwith a sensibly-sized orthographic.function createSun({ color, intensity, position, shadowMapSize, shadowFrustum, shadowFar, }?: SunOptions): THREE.DirectionalLight;options— Color (default warm white), intensity (default 3), position, and shadow tuning.- returns — The configured light; add both it and
light.targetto the scene.
resizeIsoCamera(function) — Rebuild an iso camera's frustum for a new aspect ratio (and any updateduserData.viewSize), then update the projection matrix.function resizeIsoCamera(camera: THREE.OrthographicCamera, aspect: number): void;sampleCurve(function) — Sample a scalar curve at t.function sampleCurve(curve: ScalarCurve, t: number): number;sampleShape(function) — Sample a spawn position + emission direction from an emitter shape.function sampleShape(shape: EmitterShape, r: () => number, out: SpawnSample): void;setupStandardLighting(function) — The go-to three-part lighting rig: PMREM room environment for IBL, a warm.function setupStandardLighting(scene: THREE.Scene, renderer: THREE.WebGLRenderer, options?: StandardLightingOptions): StandardLighting;scene— Scene to light.renderer— Renderer for PMREM generation.options— Per-part overrides.- returns — A StandardLighting handle for tuning and teardown.
const lights = setupStandardLighting(scene, renderer, { sun: { intensity: 2 } })targetFromObject(function) — Frame an object: standdistanceaway alongdirection, look at its center.function targetFromObject(object: THREE.Object3D, distance: number, direction?: Vec3Tuple): CameraTarget;tupleToVector3(function) — Copy a Vec3Tuple into aVector3, reusingoutwhen given (zero-alloc pattern).function tupleToVector3(tuple: Vec3Tuple, out?: THREE.Vector3): THREE.Vector3;vector3ToTuple(function) — Snapshot aVector3as a serializable Vec3Tuple.function vector3ToTuple(v: THREE.Vector3): Vec3Tuple;GradeShader(const) — Raw ShaderPass shader definition for colour grading: tint, contrast, saturation, vignette, grain, and radial chromatic aberration.LIGHTING_PRESETS(const) — The five built-in looks —dramatic,studio,soft,neon,sunset— as data, mergeable with custom presets via LightingRigOptions.presets.CameraBounds(interface) — Axis-aligned box the camera position is clamped into.CameraController(interface) — Multi-mode camera state machine driven byupdate(ctx)once per frame.CameraControllerOptions(interface) — Tuning for createCameraController: easing stiffnesses, fly-to arrival radius, and position bounds.CameraMode(type) — Which behavior currently drives the camera: idle, easing to a target, tracking an object, or anchored to a rig.CameraTarget(interface) — A serializable camera intent: where to stand and what to look at.CinematicLutOptions(interface) — Options for createCinematicLUT.ColorCurve(type) — [t, color] stops; color as css string or [r,g,b] in 0..1.ComposerHandle(interface) — Handle returned by createComposer, exposing the EffectComposer and helper methods.ComposerOptions(interface) — Options for createComposer.DofPass(interface) — Combined depth-of-field and chromatic-aberration pass.DofPassOptions(interface) — Options for createDofPass.Emitter(interface) — A live particle system.EmitterOptions(interface) — Options for createEmitter and createGpuEmitter: capacity, emission rate/bursts, lifetime, shape, motion, and appearance curves.EmitterShape(type) — Spawn volume for particles:point,sphere(optionally shell-only),box,cone(angle in r
