0
# Scene Management
1
2
Core scene graph functionality providing the foundation for managing 3D objects in Three.js. This includes the base Object3D class, scene containers, and object hierarchies.
3
4
## Capabilities
5
6
### Object3D Base Class
7
8
The fundamental base class for all 3D objects, providing transformation, hierarchy, and event systems.
9
10
```typescript { .api }
11
import { Object3D, Vector3, Matrix4, Quaternion, Euler, Layers, AnimationClip, Material } from 'three';
12
13
/**
14
* Base class for all 3D objects with transform, hierarchy, and event system
15
*/
16
class Object3D extends EventDispatcher {
17
/** Unique identifier for the object */
18
readonly id: number;
19
20
/** UUID string identifier */
21
readonly uuid: string;
22
23
/** Optional name for the object */
24
name: string;
25
26
/** Object type string for serialization */
27
readonly type: string;
28
29
/** Reference to parent object in hierarchy */
30
parent: Object3D | null;
31
32
/** Array of child objects */
33
children: Object3D[];
34
35
/** Up direction vector (default is Y-up) */
36
up: Vector3;
37
38
/** Local position */
39
position: Vector3;
40
41
/** Local rotation as Euler angles */
42
rotation: Euler;
43
44
/** Local rotation as quaternion */
45
quaternion: Quaternion;
46
47
/** Local scale */
48
scale: Vector3;
49
50
/** Local transformation matrix */
51
matrix: Matrix4;
52
53
/** World transformation matrix */
54
matrixWorld: Matrix4;
55
56
/** Model-view matrix */
57
readonly modelViewMatrix: Matrix4;
58
59
/** Normal matrix for transforming normals */
60
readonly normalMatrix: Matrix3;
61
62
/** Auto-update local matrix from position/rotation/scale */
63
matrixAutoUpdate: boolean;
64
65
/** Auto-update world matrix */
66
matrixWorldAutoUpdate: boolean;
67
68
/** Force world matrix update on next render */
69
matrixWorldNeedsUpdate: boolean;
70
71
/** Layer membership for selective rendering */
72
layers: Layers;
73
74
/** Visibility flag */
75
visible: boolean;
76
77
/** Cast shadows flag */
78
castShadow: boolean;
79
80
/** Receive shadows flag */
81
receiveShadow: boolean;
82
83
/** Frustum culling enabled */
84
frustumCulled: boolean;
85
86
/** Rendering order override */
87
renderOrder: number;
88
89
/** Animation clips attached to object */
90
animations: AnimationClip[];
91
92
/** Custom depth material for shadow rendering */
93
customDepthMaterial?: Material;
94
95
/** Custom distance material for point light shadows */
96
customDistanceMaterial?: Material;
97
98
/** User data object */
99
userData: Record<string, any>;
100
101
/**
102
* Constructor creates a new 3D object
103
*/
104
constructor();
105
106
/**
107
* Apply transformation matrix to object
108
* @param matrix - Transformation matrix to apply
109
* @returns This object for chaining
110
*/
111
applyMatrix4(matrix: Matrix4): this;
112
113
/**
114
* Apply quaternion rotation to object
115
* @param quaternion - Quaternion to apply
116
* @returns This object for chaining
117
*/
118
applyQuaternion(quaternion: Quaternion): this;
119
120
/**
121
* Set rotation from axis and angle
122
* @param axis - Rotation axis (normalized vector)
123
* @param angle - Rotation angle in radians
124
* @returns This object for chaining
125
*/
126
setRotationFromAxisAngle(axis: Vector3, angle: number): this;
127
128
/**
129
* Set rotation from Euler angles
130
* @param euler - Euler angles
131
* @returns This object for chaining
132
*/
133
setRotationFromEuler(euler: Euler): this;
134
135
/**
136
* Set rotation from rotation matrix
137
* @param matrix - Matrix containing rotation
138
* @returns This object for chaining
139
*/
140
setRotationFromMatrix(matrix: Matrix4): this;
141
142
/**
143
* Set rotation from quaternion
144
* @param quaternion - Quaternion rotation
145
* @returns This object for chaining
146
*/
147
setRotationFromQuaternion(quaternion: Quaternion): this;
148
149
/**
150
* Rotate around arbitrary axis in local space
151
* @param axis - Rotation axis (normalized)
152
* @param angle - Rotation angle in radians
153
* @returns This object for chaining
154
*/
155
rotateOnAxis(axis: Vector3, angle: number): this;
156
157
/**
158
* Rotate around arbitrary axis in world space
159
* @param axis - World space rotation axis (normalized)
160
* @param angle - Rotation angle in radians
161
* @returns This object for chaining
162
*/
163
rotateOnWorldAxis(axis: Vector3, angle: number): this;
164
165
/**
166
* Rotate around local X axis
167
* @param angle - Rotation angle in radians
168
* @returns This object for chaining
169
*/
170
rotateX(angle: number): this;
171
172
/**
173
* Rotate around local Y axis
174
* @param angle - Rotation angle in radians
175
* @returns This object for chaining
176
*/
177
rotateY(angle: number): this;
178
179
/**
180
* Rotate around local Z axis
181
* @param angle - Rotation angle in radians
182
* @returns This object for chaining
183
*/
184
rotateZ(angle: number): this;
185
186
/**
187
* Translate along arbitrary axis
188
* @param axis - Translation direction (normalized)
189
* @param distance - Translation distance
190
* @returns This object for chaining
191
*/
192
translateOnAxis(axis: Vector3, distance: number): this;
193
194
/**
195
* Translate along local X axis
196
* @param distance - Translation distance
197
* @returns This object for chaining
198
*/
199
translateX(distance: number): this;
200
201
/**
202
* Translate along local Y axis
203
* @param distance - Translation distance
204
* @returns This object for chaining
205
*/
206
translateY(distance: number): this;
207
208
/**
209
* Translate along local Z axis
210
* @param distance - Translation distance
211
* @returns This object for chaining
212
*/
213
translateZ(distance: number): this;
214
215
/**
216
* Transform local position to world coordinates
217
* @param vector - Local position to transform
218
* @returns World position
219
*/
220
localToWorld(vector: Vector3): Vector3;
221
222
/**
223
* Transform world position to local coordinates
224
* @param vector - World position to transform
225
* @returns Local position
226
*/
227
worldToLocal(vector: Vector3): Vector3;
228
229
/**
230
* Orient object to look at target position
231
* @param target - Target position to look at
232
* @param up - Up direction (optional, defaults to object.up)
233
*/
234
lookAt(target: Vector3): void;
235
lookAt(x: number, y: number, z: number): void;
236
237
/**
238
* Add child object to hierarchy
239
* @param object - Child object to add
240
* @returns This object for chaining
241
*/
242
add(...objects: Object3D[]): this;
243
244
/**
245
* Remove child object from hierarchy
246
* @param object - Child object to remove
247
* @returns This object for chaining
248
*/
249
remove(...objects: Object3D[]): this;
250
251
/**
252
* Remove this object from its parent
253
* @returns This object for chaining
254
*/
255
removeFromParent(): this;
256
257
/**
258
* Remove all child objects
259
* @returns This object for chaining
260
*/
261
clear(): this;
262
263
/**
264
* Attach object to new parent maintaining world transform
265
* @param object - Object to attach
266
* @returns This object for chaining
267
*/
268
attach(object: Object3D): this;
269
270
/**
271
* Find child object by ID
272
* @param id - Object ID to search for
273
* @returns Found object or undefined
274
*/
275
getObjectById(id: number): Object3D | undefined;
276
277
/**
278
* Find child object by name
279
* @param name - Object name to search for
280
* @returns Found object or undefined
281
*/
282
getObjectByName(name: string): Object3D | undefined;
283
284
/**
285
* Find child object by property value
286
* @param name - Property name
287
* @param value - Property value to match
288
* @returns Found object or undefined
289
*/
290
getObjectByProperty(name: string, value: any): Object3D | undefined;
291
292
/**
293
* Find all child objects by property value
294
* @param name - Property name
295
* @param value - Property value to match
296
* @returns Array of matching objects
297
*/
298
getObjectsByProperty(name: string, value: any): Object3D[];
299
300
/**
301
* Get world position
302
* @param target - Target vector to store result
303
* @returns World position
304
*/
305
getWorldPosition(target: Vector3): Vector3;
306
307
/**
308
* Get world quaternion
309
* @param target - Target quaternion to store result
310
* @returns World quaternion
311
*/
312
getWorldQuaternion(target: Quaternion): Quaternion;
313
314
/**
315
* Get world scale
316
* @param target - Target vector to store result
317
* @returns World scale
318
*/
319
getWorldScale(target: Vector3): Vector3;
320
321
/**
322
* Get world direction
323
* @param target - Target vector to store result
324
* @returns World direction
325
*/
326
getWorldDirection(target: Vector3): Vector3;
327
328
/**
329
* Execute callback for this object and all descendants
330
* @param callback - Function to execute
331
*/
332
traverse(callback: (object: Object3D) => void): void;
333
334
/**
335
* Execute callback for all visible descendants
336
* @param callback - Function to execute
337
*/
338
traverseVisible(callback: (object: Object3D) => void): void;
339
340
/**
341
* Execute callback for all ancestors
342
* @param callback - Function to execute
343
*/
344
traverseAncestors(callback: (object: Object3D) => void): void;
345
346
/**
347
* Update local matrix from position/rotation/scale
348
*/
349
updateMatrix(): void;
350
351
/**
352
* Update world matrix and children
353
* @param updateParents - Update parent matrices first
354
* @param updateChildren - Update child matrices
355
*/
356
updateMatrixWorld(updateParents?: boolean): void;
357
358
/**
359
* Update world matrix
360
* @param updateParents - Update parent matrices first
361
* @param updateChildren - Update child matrices
362
*/
363
updateWorldMatrix(updateParents: boolean, updateChildren: boolean): void;
364
365
/**
366
* Serialize object to JSON
367
* @param meta - Metadata for serialization
368
* @returns JSON representation
369
*/
370
toJSON(meta?: any): any;
371
372
/**
373
* Clone object
374
* @param recursive - Clone children recursively
375
* @returns Cloned object
376
*/
377
clone(recursive?: boolean): this;
378
379
/**
380
* Copy properties from another object
381
* @param source - Source object to copy from
382
* @param recursive - Copy children recursively
383
* @returns This object for chaining
384
*/
385
copy(source: Object3D, recursive?: boolean): this;
386
387
/**
388
* Called before shadow rendering
389
* Override for custom shadow behavior
390
*/
391
onBeforeShadow(
392
renderer: any,
393
object: Object3D,
394
camera: any,
395
shadowCamera: any,
396
geometry: any,
397
depthMaterial: any,
398
group: any
399
): void;
400
401
/**
402
* Called after shadow rendering
403
* Override for custom shadow behavior
404
*/
405
onAfterShadow(
406
renderer: any,
407
object: Object3D,
408
camera: any,
409
shadowCamera: any,
410
geometry: any,
411
depthMaterial: any,
412
group: any
413
): void;
414
415
/**
416
* Called before rendering
417
* Override for custom render behavior
418
*/
419
onBeforeRender(
420
renderer: any,
421
scene: any,
422
camera: any,
423
geometry: any,
424
material: any,
425
group: any
426
): void;
427
428
/**
429
* Called after rendering
430
* Override for custom render behavior
431
*/
432
onAfterRender(
433
renderer: any,
434
scene: any,
435
camera: any,
436
geometry: any,
437
material: any,
438
group: any
439
): void;
440
441
/** Default up direction for all objects */
442
static DEFAULT_UP: Vector3;
443
444
/** Default matrix auto update setting */
445
static DEFAULT_MATRIX_AUTO_UPDATE: boolean;
446
447
/** Default matrix world auto update setting */
448
static DEFAULT_MATRIX_WORLD_AUTO_UPDATE: boolean;
449
}
450
```
451
452
**Usage Examples:**
453
454
```typescript
455
import { Object3D, Vector3, Quaternion } from 'three';
456
457
// Create basic object
458
const obj = new Object3D();
459
obj.position.set(1, 2, 3);
460
obj.rotation.x = Math.PI / 4;
461
obj.scale.setScalar(2);
462
463
// Hierarchy management
464
const parent = new Object3D();
465
const child = new Object3D();
466
parent.add(child);
467
468
// Find objects
469
const found = parent.getObjectByName('myObject');
470
const byId = parent.getObjectById(123);
471
472
// Transformations
473
obj.translateX(5);
474
obj.rotateY(Math.PI / 2);
475
obj.lookAt(new Vector3(0, 0, 0));
476
477
// World coordinates
478
const worldPos = obj.getWorldPosition(new Vector3());
479
const localPos = obj.worldToLocal(worldPos.clone());
480
481
// Traversal
482
parent.traverse((child) => {
483
console.log(child.name, child.position);
484
});
485
```
486
487
### Scene Container
488
489
The root container for all 3D content, providing environment settings and rendering context.
490
491
```typescript { .api }
492
import { Scene, Object3D, Color, Texture, Fog, FogExp2, Material } from 'three';
493
494
/**
495
* Scene container for 3D content with environment settings
496
*/
497
class Scene extends Object3D {
498
/** Type flag for scene detection */
499
readonly isScene: true;
500
501
/** Background color, texture, or cube map */
502
background: Color | Texture | null;
503
504
/** Environment map for all physical materials */
505
environment: Texture | null;
506
507
/** Fog effect for the scene */
508
fog: Fog | FogExp2 | null;
509
510
/** Background blur amount for cube map backgrounds (0-1) */
511
backgroundBlurriness: number;
512
513
/** Background intensity multiplier */
514
backgroundIntensity: number;
515
516
/** Background rotation in radians */
517
backgroundRotation: Euler;
518
519
/** Environment map intensity multiplier */
520
environmentIntensity: number;
521
522
/** Environment map rotation in radians */
523
environmentRotation: Euler;
524
525
/** Override material for all objects in scene */
526
overrideMaterial: Material | null;
527
528
/**
529
* Create new scene
530
*/
531
constructor();
532
533
/**
534
* Serialize scene to JSON
535
* @param meta - Metadata object
536
* @returns JSON representation
537
*/
538
toJSON(meta?: any): any;
539
540
/**
541
* Copy properties from another scene
542
* @param source - Source scene
543
* @param recursive - Copy children recursively
544
* @returns This scene for chaining
545
*/
546
copy(source: Scene, recursive?: boolean): this;
547
}
548
```
549
550
**Usage Examples:**
551
552
```typescript
553
import { Scene, Color, CubeTextureLoader, Fog } from 'three';
554
555
// Create scene with background
556
const scene = new Scene();
557
scene.background = new Color(0x87CEEB); // Sky blue
558
559
// Environment mapping
560
const loader = new CubeTextureLoader();
561
scene.environment = loader.load([
562
'px.jpg', 'nx.jpg', 'py.jpg', 'ny.jpg', 'pz.jpg', 'nz.jpg'
563
]);
564
565
// Add fog
566
scene.fog = new Fog(0xcccccc, 10, 15);
567
568
// Background controls
569
scene.backgroundIntensity = 0.8;
570
scene.backgroundRotation.y = Math.PI / 4;
571
```
572
573
### Group Container
574
575
Empty object for logical grouping and batch transformations of child objects.
576
577
```typescript { .api }
578
import { Group, Object3D } from 'three';
579
580
/**
581
* Empty object for grouping other objects with shared transformations
582
*/
583
class Group extends Object3D {
584
/** Type flag for group detection */
585
readonly isGroup: true;
586
587
/**
588
* Create new group
589
*/
590
constructor();
591
}
592
```
593
594
**Usage Examples:**
595
596
```typescript
597
import { Group, Mesh, BoxGeometry, MeshBasicMaterial } from 'three';
598
599
// Create group for related objects
600
const buildings = new Group();
601
buildings.name = 'CityBuildings';
602
603
// Add multiple objects to group
604
for (let i = 0; i < 10; i++) {
605
const building = new Mesh(
606
new BoxGeometry(1, Math.random() * 3 + 1, 1),
607
new MeshBasicMaterial({ color: Math.random() * 0xffffff })
608
);
609
building.position.x = i * 2;
610
buildings.add(building);
611
}
612
613
// Transform entire group
614
buildings.position.y = 1;
615
buildings.rotation.y = Math.PI / 6;
616
617
// Add to scene
618
scene.add(buildings);
619
```
620
621
### EventDispatcher System
622
623
Base event system inherited by all Object3D instances for custom event handling.
624
625
```typescript { .api }
626
import { EventDispatcher } from 'three';
627
628
/**
629
* Event system base class
630
*/
631
class EventDispatcher {
632
/**
633
* Add event listener
634
* @param type - Event type string
635
* @param listener - Event handler function
636
*/
637
addEventListener(type: string, listener: (event: any) => void): void;
638
639
/**
640
* Check if has event listener
641
* @param type - Event type string
642
* @param listener - Event handler function
643
* @returns True if listener exists
644
*/
645
hasEventListener(type: string, listener: (event: any) => void): boolean;
646
647
/**
648
* Remove event listener
649
* @param type - Event type string
650
* @param listener - Event handler function
651
*/
652
removeEventListener(type: string, listener: (event: any) => void): void;
653
654
/**
655
* Dispatch event to listeners
656
* @param event - Event object with type property
657
*/
658
dispatchEvent(event: { type: string; [key: string]: any }): void;
659
}
660
```
661
662
**Usage Examples:**
663
664
```typescript
665
import { Object3D } from 'three';
666
667
// Custom event handling
668
const obj = new Object3D();
669
670
obj.addEventListener('customEvent', (event) => {
671
console.log('Custom event fired:', event.data);
672
});
673
674
// Built-in hierarchy events
675
obj.addEventListener('added', () => {
676
console.log('Object was added to parent');
677
});
678
679
obj.addEventListener('removed', () => {
680
console.log('Object was removed from parent');
681
});
682
683
// Dispatch custom events
684
obj.dispatchEvent({
685
type: 'customEvent',
686
data: { message: 'Hello World' }
687
});
688
```
689
690
## Constants and Utilities
691
692
### Default Values
693
694
```typescript { .api }
695
// Object3D static defaults
696
Object3D.DEFAULT_UP: Vector3; // (0, 1, 0)
697
Object3D.DEFAULT_MATRIX_AUTO_UPDATE: boolean; // true
698
Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE: boolean; // true
699
```
700
701
### Layer System
702
703
```typescript { .api }
704
import { Layers } from 'three';
705
706
/**
707
* Layer membership system for selective rendering
708
*/
709
class Layers {
710
/** Layer mask as 32-bit integer */
711
mask: number;
712
713
/**
714
* Set single active layer (0-31)
715
* @param layer - Layer number
716
*/
717
set(layer: number): void;
718
719
/**
720
* Enable specific layer
721
* @param layer - Layer number
722
*/
723
enable(layer: number): void;
724
725
/**
726
* Enable all layers
727
*/
728
enableAll(): void;
729
730
/**
731
* Toggle layer state
732
* @param layer - Layer number
733
*/
734
toggle(layer: number): void;
735
736
/**
737
* Disable specific layer
738
* @param layer - Layer number
739
*/
740
disable(layer: number): void;
741
742
/**
743
* Disable all layers
744
*/
745
disableAll(): void;
746
747
/**
748
* Test if layer is enabled
749
* @param layer - Layer number
750
* @returns True if enabled
751
*/
752
test(layer: number): boolean;
753
754
/**
755
* Test if any layers match between objects
756
* @param layers - Other layers object
757
* @returns True if any layers match
758
*/
759
isEnabled(layers: Layers): boolean;
760
}
761
```
762
763
### Raycaster
764
765
3D ray casting utility for mouse picking, collision detection, and 3D interaction. Essential for determining what objects are under the mouse cursor or intersected by rays.
766
767
```typescript { .api }
768
import { Raycaster, Vector3, Camera, Object3D, Intersection } from 'three';
769
770
/**
771
* Raycaster for 3D ray casting and intersection testing
772
*/
773
class Raycaster {
774
/** The ray used for raycasting */
775
ray: Ray;
776
777
/** Near distance for intersection testing */
778
near: number;
779
780
/** Far distance for intersection testing */
781
far: number;
782
783
/** Camera used for coordinate transformations */
784
camera: Camera;
785
786
/** Layers to test against */
787
layers: Layers;
788
789
/** Line threshold for line intersection testing */
790
linePrecision: number;
791
792
/** Point threshold for point intersection testing */
793
pointPrecision: number;
794
795
/**
796
* Create raycaster
797
* @param origin - Ray origin point
798
* @param direction - Ray direction (normalized)
799
* @param near - Near clipping distance
800
* @param far - Far clipping distance
801
*/
802
constructor(origin?: Vector3, direction?: Vector3, near?: number, far?: number);
803
804
/**
805
* Set ray from camera and mouse coordinates
806
* @param coords - Normalized device coordinates (-1 to 1)
807
* @param camera - Camera for ray calculation
808
*/
809
setFromCamera(coords: Vector2, camera: Camera): void;
810
811
/**
812
* Set ray from origin and direction
813
* @param origin - Ray origin point
814
* @param direction - Ray direction (normalized)
815
*/
816
set(origin: Vector3, direction: Vector3): void;
817
818
/**
819
* Test intersection with single object
820
* @param object - Object to test
821
* @param recursive - Test child objects recursively
822
* @returns Array of intersections
823
*/
824
intersectObject(object: Object3D, recursive?: boolean): Intersection[];
825
826
/**
827
* Test intersection with array of objects
828
* @param objects - Objects to test
829
* @param recursive - Test child objects recursively
830
* @returns Array of intersections
831
*/
832
intersectObjects(objects: Object3D[], recursive?: boolean): Intersection[];
833
}
834
835
interface Intersection {
836
/** Distance from ray origin to intersection */
837
distance: number;
838
839
/** Intersection point in world coordinates */
840
point: Vector3;
841
842
/** Surface normal at intersection */
843
normal?: Vector3;
844
845
/** UV coordinates at intersection */
846
uv?: Vector2;
847
848
/** Face index (for geometry intersections) */
849
faceIndex?: number;
850
851
/** Object that was intersected */
852
object: Object3D;
853
}
854
```
855
856
The scene management system forms the foundation of Three.js, providing hierarchical organization, transformation management, selective rendering capabilities through the layer system, and interaction capabilities through raycasting. All 3D objects inherit from Object3D, making them part of the scene graph with full transformation and event capabilities.