Skip to content

Core Library

Purpose and Scope

The Core Library provides the foundational classes and abstractions that form the basis of Three.js. It defines renderer-agnostic representations of 3D scenes, including the scene graph hierarchy, geometry data structures, material properties, and texture management. This layer sits between the mathematical primitives and the rendering systems, enabling the creation and manipulation of 3D content independently of the rendering backend.

For information about the mathematical primitives used by these core classes, see Math Primitives. For details on how these core classes are rendered to the screen, see Rendering Architecture.

Architecture Overview

The Core Library consists of four primary subsystems that work together to represent 3D scenes:

Core Library Architecture

SVG
100%

Object3D: The Scene Graph Foundation

Object3D is the base class for all renderable and non-renderable objects in Three.js. It provides hierarchical transformation, event dispatching, and a common interface for scene graph traversal.

Object3D Core Properties and Relationships

SVG
100%

Transformation System

Object3D maintains transformations in both Euler angles and quaternions, with automatic synchronization between the two representations. The transformation hierarchy is managed through local and world matrices:

PropertyTypePurpose
positionVector3Local position relative to parent
rotationEulerLocal rotation as Euler angles (synced with quaternion)
quaternionQuaternionLocal rotation as quaternion (synced with rotation)
scaleVector3Local scale
matrixMatrix4Local transformation matrix
matrixWorldMatrix4World transformation matrix
matrixAutoUpdatebooleanAutomatically compute local matrix from position/rotation/scale
matrixWorldAutoUpdatebooleanAutomatically compute world matrix from hierarchy
pivotVector3Pivot point for rotation and scale transformations

The transformation matrices are computed by updateMatrix() and updateMatrixWorld(). When matrixAutoUpdate is true, the local matrix is composed from position, rotation, and scale each frame. When matrixWorldAutoUpdate is true, the world matrix is computed by multiplying the parent's world matrix with the local matrix.

Hierarchy Management

The scene graph is built using parent-child relationships. Key methods for hierarchy manipulation:

MethodParametersPurpose
add(object)Object3DAdd child object, fires 'added' and 'childadded' events
remove(object)Object3DRemove child object, fires 'removed' and 'childremoved' events
removeFromParent()-Remove this object from its parent
clear()-Remove all child objects
attach(object)Object3DAdd child while maintaining its world transform
traverse(callback)FunctionExecute callback on this object and all descendants
traverseVisible(callback)FunctionExecute callback only on visible objects
traverseAncestors(callback)FunctionExecute callback on all ancestors

EventDispatcher Integration

Object3D extends EventDispatcher, providing a pub-sub event system. Built-in events include:

  • added: Fired when object is added to a parent
  • removed: Fired when object is removed from a parent
  • childadded: Fired when a child is added (includes child property)
  • childremoved: Fired when a child is removed (includes child property)

BufferGeometry: Vertex Data Storage

BufferGeometry represents mesh, line, or point geometry using typed arrays stored in BufferAttribute instances. It provides efficient data transfer to the GPU and supports indexed and non-indexed geometry.

BufferGeometry Data Flow

SVG
100%

Attribute Management

Geometry attributes are stored in a dictionary (attributes) keyed by attribute name. Common attributes include:

AttributeItemSizeTypePurpose
position3Float32Vertex positions (x, y, z)
normal3Float32Vertex normals
uv2Float32Texture coordinates
uv12Float32Second set of texture coordinates
color3 or 4Float32Vertex colors (RGB or RGBA)
tangent4Float32Tangent vectors (with handedness in w)
skinIndex4Uint16Bone indices for skinned meshes
skinWeight4Float32Bone weights for skinned meshes

Key methods for attribute manipulation:

// From BufferGeometry class
setAttribute(name, attribute)    // Set an attribute
getAttribute(name)               // Retrieve an attribute
deleteAttribute(name)            // Remove an attribute
hasAttribute(name)               // Check if attribute exists

Indexed vs Non-Indexed Geometry

Geometry can be indexed (vertices shared across triangles) or non-indexed (each triangle has unique vertices):

  • Indexed Geometry: Uses an index attribute (Uint16 or Uint32) to reference vertices. Each three consecutive indices define a triangle.
  • Non-Indexed Geometry: When index is null, every three consecutive vertices define a triangle.

The toNonIndexed() method converts indexed geometry to non-indexed format by duplicating shared vertices.

Draw Groups

Groups allow rendering different parts of the geometry with different materials. Each group specifies:

PropertyTypePurpose
startnumberFirst vertex (non-indexed) or first index (indexed)
countnumberNumber of vertices or indices to render
materialIndexnumberIndex into the material array

Bounding Volume Computation

BufferGeometry computes axis-aligned bounding boxes (Box3) and bounding spheres (Sphere) for frustum culling and intersection testing:

  • computeBoundingBox(): Computes boundingBox from position attribute and morph targets
  • computeBoundingSphere(): Computes boundingSphere using a tighter-fitting algorithm than the bounding box

Both methods account for morph target positions when morphAttributes.position is defined.

Normal and Tangent Generation

Geometry provides methods to compute vertex normals and tangents from position data:

  • computeVertexNormals(): Computes face normals and averages them for shared vertices (indexed) or assigns face normals directly (non-indexed)
  • computeTangents(): Computes tangent vectors for normal mapping (requires position, normal, uv, and index attributes)

BufferAttribute: Typed Array Management

BufferAttribute wraps typed arrays with metadata for efficient GPU transfer. It provides methods for accessing and manipulating vertex data.

BufferAttribute Structure

SVG
100%

Data Access Methods

BufferAttribute provides typed accessors for common item sizes:

MethodParametersPurpose
getX(index)indexGet first component
getY(index)indexGet second component
getZ(index)indexGet third component
getW(index)indexGet fourth component
setX(index, x)index, xSet first component
setY(index, y)index, ySet second component
setZ(index, z)index, zSet third component
setW(index, w)index, wSet fourth component
setXY(index, x, y)index, x, ySet two components
setXYZ(index, x, y, z)index, x, y, zSet three components
setXYZW(index, x, y, z, w)index, x, y, z, wSet four components

Interleaved Attributes

InterleavedBuffer and InterleavedBufferAttribute enable packing multiple attributes into a single typed array, reducing memory overhead and improving cache coherency:

SVG
100%

Each InterleavedBufferAttribute references the shared buffer with an offset and itemSize, allowing efficient data layout: [x,y,z,nx,ny,nz,u,v, x,y,z,nx,ny,nz,u,v, ...]

Instanced Attributes

InstancedBufferAttribute extends BufferAttribute for instanced rendering, where each instance can have unique attribute values:

  • meshPerAttribute: Defines how many instances use each attribute value (typically 1)
  • Used with InstancedBufferGeometry for rendering multiple copies of geometry with varying properties

InstancedInterleavedBuffer provides the same functionality for interleaved data.

Material: Surface Appearance

Material is the abstract base class for all materials, defining properties that control how surfaces appear when rendered. It provides a common interface for blending, depth testing, stencil operations, and custom shader hooks.

Material Property Categories

SVG
100%

Material Property Groups

Blending and Transparency

PropertyTypeDefaultPurpose
blendingConstantNormalBlendingBlending mode (Normal, Additive, Subtractive, Multiply, Custom, None)
transparentbooleanfalseWhether material is transparent (affects render order)
opacitynumber1.0Material opacity (0.0 = fully transparent, 1.0 = opaque)
blendSrcConstantSrcAlphaFactorSource blend factor (requires CustomBlending)
blendDstConstantOneMinusSrcAlphaFactorDestination blend factor (requires CustomBlending)
blendEquationConstantAddEquationBlend equation (Add, Subtract, ReverseSubtract, Min, Max)

Depth and Stencil

PropertyTypeDefaultPurpose
depthTestbooleantrueEnable depth testing
depthWritebooleantrueWrite to depth buffer
depthFuncConstantLessEqualDepthDepth comparison function
stencilWritebooleanfalseEnable stencil operations
stencilFuncConstantAlwaysStencilFuncStencil comparison function
stencilRefnumber0Reference value for stencil test

Material Callbacks

Materials provide hooks for customization during rendering:

CallbackParametersPurpose
onBeforeRenderrenderer, scene, camera, geometry, object, groupCalled before rendering an object
onBeforeCompileshaderobject, rendererModify shader source before compilation (WebGLRenderer only)
customProgramCacheKey-Return string key for shader cache identification

The onBeforeCompile callback enables shader modification for WebGLRenderer:

material.onBeforeCompile = function(shader, renderer) {
    // Modify shader.vertexShader or shader.fragmentShader
    // Access shader.uniforms
}

Texture: Image Data Management

Texture encapsulates image data and sampling parameters for materials. It uses a Source object to share image data across multiple textures.

Texture Structure and Relationships

SVG
100%

Texture Coordinate Transformation

Textures support UV transformation through offset, repeat, center, and rotation:

  • offset: Translation in UV space
  • repeat: Scale in UV space (values > 1 tile the texture)
  • center: Rotation center in UV space
  • rotation: Rotation angle in radians

When matrixAutoUpdate is true, these properties are used to compute the matrix via updateMatrix(), which applies the transformation: matrix.setUvTransform(offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y)

Texture Source Sharing

The Source class (src/textures/Source.js) holds the actual image data and can be shared across multiple Texture instances. This is useful for:

  • Creating multiple textures with different sampling parameters from the same image
  • Implementing texture atlases where multiple textures reference the same source but with different UV transforms

Serialization and Loading

The Core Library includes loaders for deserializing Three.js objects from JSON format, supporting complete scene graphs with geometry, materials, textures, animations, and skeletal hierarchies.

ObjectLoader Data Flow

SVG
100%

ObjectLoader Pipeline

ObjectLoader parses JSON-serialized scenes in stages:

  1. Shapes (src/loaders/ObjectLoader.js270-288): Parse 2D shapes for extrude geometries
  2. Geometries (src/loaders/ObjectLoader.js321-368): Parse geometry data using BufferGeometryLoader or procedural geometry classes
  3. Images (src/loaders/ObjectLoader.js423-633): Load images via ImageLoader or deserialize embedded data textures
  4. Textures (src/loaders/ObjectLoader.js635-740): Create Texture instances with sampling parameters
  5. Materials (src/loaders/ObjectLoader.js371-399): Parse materials using MaterialLoader
  6. Objects (src/loaders/ObjectLoader.js743-1045): Recursively construct Object3D hierarchy
  7. Skeletons (src/loaders/ObjectLoader.js290-318): Parse skeletal data for skinned meshes
  8. Binding (src/loaders/ObjectLoader.js1047-1108): Attach skeletons to meshes and resolve light targets

MaterialLoader

MaterialLoader deserializes material properties from JSON, creating instances of concrete material classes:

// Material types recognized by createMaterialFromType()
MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, 
MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial,
MeshNormalMaterial, MeshMatcapMaterial, MeshDepthMaterial,
MeshDistanceMaterial, LineBasicMaterial, LineDashedMaterial,
PointsMaterial, SpriteMaterial, ShaderMaterial, RawShaderMaterial,
ShadowMaterial

The loader sets material properties and resolves texture references from a texture dictionary.

Serialization Format

Object3D.toJSON() and Material.toJSON() serialize objects to JSON format compatible with ObjectLoader:

MetadataContent
metadata.version4.7
metadata.type'Object' or 'Material'
metadata.generator'Object3D.toJSON' or 'Material.toJSON'

The serialization captures:

  • Object hierarchy and transformations
  • Geometry and material references (via UUID)
  • Custom properties in userData
  • Animation clips
  • Skeletal bindings for SkinnedMesh

WebGL Resource Management

While the Core Library is renderer-agnostic, it interfaces with WebGL through specialized resource management systems:

WebGL Resource Management Flow

SVG
100%

WebGLGeometries

WebGLGeometries manages the lifecycle of geometry resources:

  • Tracks geometries via WeakMap using geometry IDs
  • Registers disposal handlers via EventDispatcher 'dispose' events
  • Updates attribute buffers through WebGLAttributes
  • Generates wireframe indices for wireframe rendering mode
  • Manages InstancedBufferGeometry instance counts

WebGLAttributes

WebGLAttributes manages WebGL buffer objects for BufferAttribute data:

  • Creates VBOs with gl.createBuffer() and uploads data via gl.bufferData()
  • Updates buffers incrementally using updateRanges via gl.bufferSubData()
  • Merges adjacent update ranges to minimize GPU command overhead
  • Maps TypedArray types to WebGL constants (FLOAT, HALF_FLOAT, UNSIGNED_SHORT, etc.)

WebGLBindingStates

WebGLBindingStates manages Vertex Array Objects (VAOs) to cache attribute bindings:

  • Creates unique VAO per (object, geometry, program, material) combination
  • Caches vertex attribute pointer configurations
  • Reduces state changes by binding cached VAOs
  • Handles instanced attributes for InstancedMesh
  • Tracks wireframe vs solid geometry variants

WebGLObjects

WebGLObjects orchestrates geometry and attribute updates per frame:

  • Updates geometries once per frame using frame tracking
  • Updates instance matrices for InstancedMesh
  • Triggers skeleton updates for SkinnedMesh
  • Manages disposal of instanced mesh resources

WebGLProperties

WebGLProperties provides a generic property store using WeakMap, allowing renderer-specific metadata to be attached to core objects without modifying their class definitions.

Relationship to Other Systems

The Core Library serves as the foundation for other Three.js systems:

SystemRelationship
Math Primitives (#2.1)Core Library uses Vector3, Matrix4, Quaternion, etc. for transformations
Constants (#2.2)Core Library references constants for blending modes, texture formats, etc.
Rendering (#3)Renderers consume Core Library objects to generate GPU commands
Asset Pipeline (#4)Loaders create Core Library objects from external file formats
Interaction Systems (#5)Raycasting and animation systems operate on Core Library scene graphs