Skip to content

Scene Graph & Object3D

Purpose and Scope

This document covers the Object3D base class and the scene graph architecture in Three.js. It explains how 3D objects are organized into hierarchies, how transformations are managed through position/rotation/scale properties and transformation matrices, and how objects interact with the rendering pipeline through lifecycle hooks.

For information about geometry data (vertex positions, normals, UVs), see Geometry System. For material appearance properties, see Material & Texture System.

Object3D Class Overview

The Object3D class is the base class for most objects in Three.js. It implements core functionality for scene graph management, spatial transformations, and rendering lifecycle hooks. All renderable objects (Mesh, Line, Points, Sprite) and organizational objects (Group, Scene) extend from Object3D.

Key Responsibilities:

  • Maintain parent-child hierarchy relationships
  • Store local and world transformation data
  • Provide transformation methods (translate, rotate, scale)
  • Define rendering properties (visibility, layers, renderOrder)
  • Expose lifecycle hooks for render callbacks

Core Properties

PropertyTypeDefaultDescription
isObject3DbooleantrueType testing flag
idnumberauto-incrementAuto-incremented unique identifier starting at 0
uuidstringgeneratedUniversally unique identifier via generateUUID()
namestring''Optional human-readable name
typestring'Object3D'Class type identifier (e.g., "Mesh", "Group")
parentObject3D | nullnullReference to parent object
childrenArray<Object3D>[]Array of child objects
upVector3Object3D.DEFAULT_UPUp direction vector (default is (0,1,0))
userDataObject{}Custom application data storage

Scene Graph Hierarchy

The scene graph is a tree structure where each node is an Object3D. The root is typically a Scene object, with cameras, lights, and meshes as descendants. This hierarchy enables:

  • Grouped transformations: Child objects inherit parent transformations
  • Organizational structure: Logical grouping of related objects
  • Efficient culling: Entire branches can be culled or made invisible

Hierarchy Class Diagram

Title: Object3D Class Hierarchy with Key Properties

SVG
100%

Parent-Child Management

Adding Children:

// Methods defined in Object3D
add( object )              // Add one or more children
attach( object )           // Add while preserving world transform

Removing Children:

remove( object )           // Remove child
removeFromParent()         // Remove self from parent
clear()                    // Remove all children

Key Implementation Details:

  • Children maintain a reference to their parent via the parent property
  • Adding an object automatically removes it from its previous parent
  • Events are dispatched: added, removed, childadded, childremoved
  • An object cannot be added as a child of itself

Scene Graph Traversal

The scene graph can be traversed using three methods:

MethodDescription
traverse(callback)Execute callback on this object and all descendants
traverseVisible(callback)Same as traverse() but skips invisible objects
traverseAncestors(callback)Execute callback on all ancestors

Example traversal for finding objects:

  • getObjectById(id) - Find by numeric ID
  • getObjectByName(name) - Find by name string
  • getObjectByProperty(name, value) - Find by arbitrary property
  • getObjectsByProperty(name, value, result) - Find all matching objects

Transformation System

Object3D implements a dual representation of transformations:

  1. Component form: position, rotation/quaternion, scale properties
  2. Matrix form: matrix (local space) and matrixWorld (world space)

Transformation Properties

Title: Transformation Data Flow in Object3D

SVG
100%

Component Properties

PropertyTypeDefaultDescription
positionVector3(0,0,0)Local position
rotationEuler(0,0,0)Local rotation as Euler angles
quaternionQuaternion(0,0,0,1)Local rotation as quaternion
scaleVector3(1,1,1)Local scale
upVector3(0,1,0)Up vector for lookAt()

Important: rotation and quaternion are synchronized automatically. Modifying one updates the other through internal change callbacks.

Matrix Properties

PropertyTypeDescription
matrixMatrix4Local transformation matrix
matrixWorldMatrix4World transformation matrix
modelViewMatrixMatrix4Model-view matrix (computed during rendering)
normalMatrixMatrix3Normal matrix (computed during rendering)

Matrix Update Flags:

FlagTypeDefaultDescription
matrixAutoUpdatebooleantrueAuto-compute matrix from position/rotation/scale
matrixWorldAutoUpdatebooleantrueAuto-compute matrixWorld from hierarchy
matrixWorldNeedsUpdatebooleanfalseForce world matrix update this frame

Transformation Update Flow

Title: Matrix Update Process During Rendering

SVG
100%

Transformation Methods

Setting Transformations:

// Rotation
setRotationFromAxisAngle(axis, angle)
setRotationFromEuler(euler)
setRotationFromMatrix(m)
setRotationFromQuaternion(q)

// Applying transformations
applyMatrix4(matrix)            // Apply matrix to object
applyQuaternion(q)              // Apply quaternion rotation

Incremental Transformations:

// Rotation
rotateOnAxis(axis, angle)       // Rotate in local space
rotateOnWorldAxis(axis, angle)  // Rotate in world space
rotateX(angle)                  // Rotate around local X axis
rotateY(angle)                  // Rotate around local Y axis
rotateZ(angle)                  // Rotate around local Z axis

// Translation
translateOnAxis(axis, distance) // Translate in local space
translateX(distance)            // Translate along local X axis
translateY(distance)            // Translate along local Y axis
translateZ(distance)            // Translate along local Z axis

Utility Methods:

lookAt(x, y, z)                 // Orient to face target point
localToWorld(vector)            // Convert local to world coordinates
worldToLocal(vector)            // Convert world to local coordinates

World Space Queries

Methods to retrieve world-space transformation data:

MethodReturnsDescription
getWorldPosition(target)Vector3Position in world space
getWorldQuaternion(target)QuaternionRotation in world space
getWorldScale(target)Vector3Scale in world space
getWorldDirection(target)Vector3Forward direction in world space

Rendering Properties

Object3D provides properties that control how objects are rendered:

Visibility and Culling

PropertyTypeDefaultDescription
visiblebooleantrueWhether object is rendered
frustumCulledbooleantrueWhether object is culled by view frustum
renderOrdernumber0Override default rendering order

Culling Behavior:

  • Objects with frustumCulled=true are tested against the camera's view frustum
  • Invisible objects (visible=false) are skipped during rendering
  • traverseVisible() respects visibility for scene traversal

Layer System

The layers property (type Layers) provides a 32-bit mask for selective rendering:

// Object on layer 1
object.layers.set(1);

// Camera renders layers 0 and 1
camera.layers.enableAll();
camera.layers.enable(0);
camera.layers.enable(1);

// Check if object is visible to camera
if (object.layers.test(camera.layers)) {
    // Render object
}

Use Cases:

  • Selective rendering (e.g., UI layer vs. world layer)
  • Raycasting filter (exclude certain objects from picking)
  • Post-processing masks

Shadow Properties

PropertyTypeDefaultDescription
castShadowbooleanfalseWhether object casts shadows
receiveShadowbooleanfalseWhether object receives shadows
customDepthMaterialMaterialundefinedCustom material for shadow depth pass
customDistanceMaterialMaterialundefinedCustom material for point light shadows

Lifecycle Hooks

Object3D provides callback hooks that are invoked during the rendering process:

Render Lifecycle Diagram

Title: Object3D Lifecycle Hooks During Rendering

SVG
100%

Hook Signatures

Main Rendering:

onBeforeRender(renderer, scene, camera, geometry, material, group)
onAfterRender(renderer, scene, camera, geometry, material, group)

Shadow Rendering:

onBeforeShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, group)
onAfterShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, group)

Parameters:

ParameterTypeDescription
rendererWebGLRendererThe active renderer
sceneSceneThe scene being rendered
cameraCameraThe camera used for rendering
geometryBufferGeometryThe object's geometry
materialMaterialThe material being rendered
groupObjectGeometry group data (for multi-material objects)

Common Use Cases:

  • Update uniforms based on camera position
  • Modify material properties per frame
  • Toggle visibility based on distance
  • Custom depth material setup for shadows

Common Object3D Subclasses

Class Hierarchy and Usage

Title: Object3D Subclass Implementation Details

SVG
100%

Scene

The Scene class is typically the root of the scene graph:

Additional Properties:

  • background - Background color or texture
  • environment - Environment map for reflections
  • fog - Fog settings (linear or exponential)
  • overrideMaterial - Override all object materials

Group

An empty container for organizing objects:

  • No geometry or material
  • Used purely for transformation hierarchy
  • Lightweight organizational tool

Mesh

Combines geometry and material for renderable triangular surfaces:

Additional Properties:

  • geometry - BufferGeometry instance
  • material - Material or array of materials
  • morphTargetInfluences - Morph target weights
  • morphTargetDictionary - Morph target name-to-index map

Methods:

  • raycast(raycaster, intersects) - Ray intersection testing
  • updateMorphTargets() - Initialize morph target data

Sprite

A billboard that always faces the camera:

  • Uses SpriteMaterial
  • Does not cast shadows
  • Efficient for particles and UI elements

Raycasting Integration

Object3D provides the abstract raycast() method, implemented by renderable subclasses:

raycast(raycaster, intersects)

Raycaster Flow:

Title: Raycasting Process Through Scene Graph

SVG
100%

Intersection Result Structure:

{
    distance: number,          // Distance from ray origin
    point: Vector3,            // World space intersection point
    face: Face,                // Face index (if applicable)
    faceIndex: number,         // Face index
    object: Object3D,          // The intersected object
    uv: Vector2,               // UV coordinates at intersection
    instanceId: number         // Instance ID (for InstancedMesh)
}

Serialization and Cloning

JSON Serialization

Object3D and its subclasses support JSON serialization via ObjectLoader:

Serialized Structure:

{
    metadata: { version: 4.7, type: 'Object', generator: 'Object3D.toJSON' },
    object: {
        uuid: string,
        type: string,        // Class name
        name: string,
        
        // Transformation
        matrix: [16 numbers],
        
        // Hierarchy
        children: [ ... ],
        
        // Rendering
        visible: boolean,
        castShadow: boolean,
        receiveShadow: boolean,
        frustumCulled: boolean,
        renderOrder: number,
        
        // Type-specific properties
        geometry: string,     // UUID reference (Mesh)
        material: string,     // UUID reference (Mesh)
        // ...
        
        userData: { ... }
    }
}

Parsing Process:

Title: ObjectLoader.parse() Pipeline

SVG
100%

Cloning

The clone() and copy() methods enable object duplication:

// Deep clone (includes children)
const clone = object.clone();

// Shallow copy (no children)
const copy = new Object3D().copy(object, false);

Copy Behavior:

  • Transformation properties are copied
  • Children are optionally cloned recursively
  • Parent reference is not copied (clone is orphaned)
  • Geometry and material references are shared (not cloned)

Additional Properties

Custom Data

object.userData = {};  // Empty object for application data

The userData property is preserved during serialization and cloning but should not contain function references.

Animation Clips

object.animations = [];  // Array of AnimationClip instances

Animation clips associated with the object, typically populated by loaders.

Static Optimization (WebGPU)

object.static = false;  // Mark object as unchanging

When true, indicates the object won't change after initial render, allowing WebGPU renderer optimizations.

Pivot Point

object.pivot = new Vector3(0.5, 0.5, 0);  // Custom pivot point

When set, rotation and scale transformations occur around this point instead of the origin.

Key Architectural Patterns

Composite Pattern

The scene graph implements the Composite Pattern:

  • Object3D is the component interface
  • Leaf nodes (Mesh, Sprite, Camera) and composite nodes (Group, Scene) share the same interface
  • Operations (traverse, transform, render) work uniformly on individual objects or hierarchies

Observer Pattern

Object3D extends EventDispatcher for event-driven communication:

  • Hierarchy changes dispatch added, removed, childadded, childremoved events
  • Materials and geometries use dispose events for cleanup

Matrix Caching

The transformation system uses lazy evaluation:

  • Local matrix computed only when matrixAutoUpdate=true or updateMatrix() called
  • World matrix computed only when needed or flagged with matrixWorldNeedsUpdate
  • Reduces unnecessary matrix multiplications in static scenes