Three.js Overview
Purpose and Scope
This document provides a high-level overview of the Three.js library architecture, including its module organization, distribution formats, core systems, and how different subsystems interact. For detailed information about specific subsystems, see:
- Build system and distribution formats: Build System & Module Exports
- Core mathematical and scene graph primitives: Core Library
- WebGL and WebGPU rendering backends: Rendering Architecture
- 3D file format import/export: Asset Pipeline
- Developer tools and ecosystem: Developer Tools
What is Three.js
Three.js is a cross-platform JavaScript 3D graphics library designed to simplify WebGL and WebGPU programming. It provides a high-level abstraction over GPU APIs, offering a scene graph-based architecture for rendering 3D content in web browsers.
Current Version: REVISION = '183dev' as defined in src/constants.js1
Primary Capabilities:
- Hardware-accelerated 3D rendering via WebGL 2 and WebGPU
- Scene graph management with hierarchical transformations
- Material system with physically-based rendering (PBR)
- Animation, skeletal rigging, and morph targets
- Import/export of common 3D file formats (GLTF, FBX, OBJ)
- Post-processing effects and shadows
Distribution Formats
Three.js is distributed in multiple build variants to support different use cases and rendering backends:
| Build Output | Entry Point | Format | Purpose |
|---|---|---|---|
| three.core.js | src/Three.Core.js | ESM | Core math, scene graph, geometry systems |
| three.module.js | src/Three.js | ESM | Core + WebGL renderer |
| three.webgpu.js | src/Three.WebGPU.js | ESM | Core + WebGPU renderer + node material system |
| three.cjs | src/Three.Core.js | CommonJS | Node.js compatibility |
| three.tsl.js | src/Three.TSL.js | ESM | Three Shading Language (TSL) exports for WebGPU |
Package Exports (from package.json8-20):
"exports": {
".": {
"import": "./build/three.module.js",
"require": "./build/three.cjs"
},
"./webgpu": "./build/three.webgpu.js",
"./tsl": "./build/three.tsl.js",
"./addons": "./examples/jsm/Addons.js"
}High-Level Architecture
System Organization Diagram
Core Subsystems
Scene Graph and Rendering Pipeline
Three.js follows a scene graph paradigm where 3D objects are organized in a hierarchical tree structure. The rendering process transforms this logical scene representation into GPU commands.
Key Classes:
Scenesrc/scenes/Scene.js10-194 - Root container for renderable objects, lights, fog, backgroundObject3Dsrc/core/Object3D.js1-1164 - Base class for all scene graph nodes with transformation hierarchyWebGLRenderersrc/renderers/WebGLRenderer.js64-2500 - Main rendering orchestration and WebGL API wrapper
Math and Transformation System
The core mathematics layer provides the primitives for 3D transformations, spatial queries, and geometric calculations.
Transformation Hierarchy: Each Object3D maintains both a local transform (matrix) and a world-space transform (matrixWorld). World matrices are computed by multiplying parent world matrices down the scene graph during traversal.
Material and Shader System
Materials define surface appearance and control shader generation. Three.js uses a template-based shader system where GLSL code is assembled from reusable chunks based on material properties.
Shader Compilation Process:
- Material properties determine required shader features (e.g.,
USE_MAP,USE_NORMALMAP) WebGLProgramsgenerates a program configuration hash- If not cached, GLSL source is assembled from
ShaderLibtemplates andShaderChunkincludes - Shader is compiled and linked via
WebGLProgramsrc/renderers/webgl/WebGLProgram.js309-495
Geometry and Buffer Management
Geometry data is stored in BufferGeometry using typed arrays, which are efficiently uploaded to GPU buffers.
Key Classes:
BufferGeometrysrc/core/BufferGeometry.js1-1283 - Container for vertex attributesBufferAttributesrc/core/BufferAttribute.js1-400 - Wrapper for typed arrays with metadataWebGLAttributesbuild/three.module.js61-294 - GPU buffer lifecycle managementWebGLBindingStates- Manages Vertex Array Objects (VAOs) for efficient attribute binding
Rendering Backend: WebGL vs WebGPU
Three.js supports two rendering backends with different architectures:
| Feature | WebGLRenderer | WebGPURenderer |
|---|---|---|
| Entry Point | src/renderers/WebGLRenderer.js | Included in three.webgpu.js |
| API | WebGL 2 | WebGPU |
| Material System | Fixed material types | Node-based (NodeMaterial) |
| Shader Language | GLSL (template-based) | WGSL (node-graph) |
| Coordinate System | WebGLCoordinateSystem | WebGPUCoordinateSystem |
| Multi-target | Single render target | Multiple Render Targets (MRT) |
WebGL Architecture src/renderers/WebGLRenderer.js64-2500:
- Manages 20+ subsystems (state, programs, textures, geometries, etc.)
- Shader compilation via
WebGLProgramscaching system - State management minimizes redundant GPU calls via
WebGLState
WebGPU Architecture build/three.webgpu.js1-2485272:
- Node-based material system where shaders are constructed from node graphs
- TSL (Three Shading Language) for expressing shader logic in JavaScript
- Modern GPU features: compute shaders, storage buffers, MRT
Constants System
Three.js uses numeric and string constants throughout the codebase for configuration. These are centralized in src/constants.js1-1071
Key Constant Categories:
| Category | Examples | Purpose |
|---|---|---|
| Blending | NoBlending, NormalBlending, AdditiveBlending | Control alpha compositing |
| Culling | CullFaceNone, CullFaceBack, FrontSide, DoubleSide | Face visibility |
| Depth Testing | LessDepth, LessEqualDepth, AlwaysDepth | Z-buffer comparison |
| Texture Filtering | NearestFilter, LinearFilter, LinearMipmapLinearFilter | Texture sampling |
| Texture Formats | RGBAFormat, RGBFormat, DepthFormat | Pixel format specification |
| Shadow Mapping | BasicShadowMap, PCFShadowMap, VSMShadowMap | Shadow filtering algorithms |
| Tone Mapping | NoToneMapping, ACESFilmicToneMapping, AgXToneMapping | HDR to LDR conversion |
Build System
The build system uses Rollup to produce multiple distribution formats from TypeScript-free JavaScript source code.
Build Configuration utils/build/rollup.config.js66-143:
Build Outputs:
three.core.js: Core library without renderersthree.module.js: Core + WebGLRendererthree.webgpu.js: Core + WebGPURenderer + node material systemthree.tsl.js: TSL (Three Shading Language) re-exports for WebGPU- Minified versions (
.min.js) for production
GLSL Processing utils/build/rollup.config.js4-36: The glsl() plugin minifies GLSL shader code by removing comments and excess whitespace from template literals marked with /* glsl */.
Module Organization
The source code is organized into logical directories:
src/
├── constants.js # System-wide constants
├── Three.js # WebGL entry point
├── Three.Core.js # Core-only entry point
├── Three.WebGPU.js # WebGPU entry point
├── Three.TSL.js # TSL re-exports
├── animation/ # Animation system
├── cameras/ # Camera types
├── core/ # Object3D, BufferGeometry, Raycaster
├── geometries/ # Procedural geometry generators
├── lights/ # Light types
├── loaders/ # Loader base classes
├── materials/ # Material base classes
├── math/ # Math primitives
├── objects/ # Mesh, Line, Points, Sprite
├── renderers/ # WebGLRenderer and subsystems
│ ├── webgl/ # WebGL backend components
│ ├── shaders/ # GLSL shader library
│ └── webxr/ # WebXR support
├── scenes/ # Scene, Fog
└── textures/ # Texture classes
examples/jsm/ # Add-on modules (not in core)
├── loaders/ # GLTFLoader, FBXLoader, etc.
├── controls/ # OrbitControls, etc.
├── postprocessing/ # Post-processing effects
└── exporters/ # Scene exportersCore vs Examples:
- Core (
src/): Bundled in main distribution, stable API - Examples (
examples/jsm/): Add-on modules, imported separately via/addons/*paths
Usage Patterns
Basic Rendering Setup
The typical Three.js application follows this pattern (from README.md24-58):
import * as THREE from 'three';
// 1. Create scene
const scene = new THREE.Scene();
// 2. Create camera
const camera = new THREE.PerspectiveCamera(
70, // FOV
window.innerWidth / window.innerHeight, // aspect ratio
0.01, // near plane
10 // far plane
);
// 3. Create geometry and material
const geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
const material = new THREE.MeshNormalMaterial();
// 4. Create mesh and add to scene
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
// 5. Create renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 6. Animation loop
renderer.setAnimationLoop((time) => {
mesh.rotation.x = time / 2000;
mesh.rotation.y = time / 1000;
renderer.render(scene, camera);
});Key Technical Details
Coordinate System
- Right-handed coordinate system: +X right, +Y up, +Z toward viewer
- WebGL: Maps to OpenGL conventions src/constants.js1071
- WebGPU: Different clip space mapping src/constants.js1071
Color Space Management
- Linear workflow: Internally operates in linear color space
- Automatic conversion: sRGB textures converted to linear on GPU
- Tone mapping: HDR to LDR conversion applied in final shader pass
- Color spaces:
SRGBColorSpace,LinearSRGBColorSpace,NoColorSpacesrc/constants.js804-840
Memory Management
- Manual disposal: GPU resources must be explicitly freed via
.dispose()methods - Resource tracking:
WebGLPropertiesuses WeakMap to associate GPU objects with JS objects - Context loss: Automatic recovery via
webglcontextlostevents src/renderers/WebGLRenderer.js1073-1103
Performance Considerations
Rendering Optimization
- Draw call batching:
BatchedMeshcombines multiple objects into single draw call - Instanced rendering:
InstancedMeshfor rendering many copies of same geometry - Frustum culling: Automatic visibility determination via bounding volumes
- Level of Detail (LOD): Automatic mesh switching based on distance
Shader Compilation
- Program caching:
WebGLProgramscaches compiled shaders by material+lighting hash - Lazy compilation: Shaders compiled on first render, not construction
- Warm-up:
renderer.compile(scene, camera)pre-compiles all materials src/renderers/WebGLRenderer.js1350-1420
Extension Points
Custom Materials
ShaderMaterial: Full control over vertex and fragment shadersonBeforeCompile: Hook to modify built-in material shaders before compilationNodeMaterial(WebGPU): Node-graph-based material system
Custom Geometry
BufferGeometry: Direct manipulation of vertex attributes- Procedural generation: Create geometry programmatically in JavaScript
- Compute shaders (WebGPU): GPU-side geometry generation
Render Pipeline
onBeforeRender/onAfterRender: Per-object callbacks during rendering- Render targets: Off-screen rendering for effects and shadows
- Multi-pass rendering: Manual control over render sequence