# 09. The scene graph: a tiny solar system, explained

**Goal:** understand parent/child transforms by building a sun, planets and a moon, where each body orbits its parent.

## The key idea

Every `Object3D` (meshes, lights, cameras, groups) has `position`, `rotation` and `scale` **relative to its parent**. When a parent moves or rotates, all children move with it. To make something orbit a point, put it inside an empty pivot object at that point and rotate the pivot.

```text
scene
├── sun (scaled x4)
├── earth.orbit (pivot at 0,0,0, rotates)
│   ├── earth.planet (x = 16, spins)
│   └── earthSystem (x = 16)
│       └── moon.orbit (rotates)
│           └── moon.planet (x = 2.5)
└── mars.orbit
    └── mars.planet (x = 24)
```

## Walkthrough

```js
const sunLight = new THREE.PointLight(0xffffff, 3, 0, 0);
```
`PointLight(color, intensity, distance, decay)`. Physically correct lights fade with the square of distance (`decay = 2`), which would make the outer planets very dark at this scale. Setting `decay = 0` gives constant brightness, a deliberate cheat for a toy scene.

```js
const sun = new THREE.Mesh(sphere, new THREE.MeshBasicMaterial({ color: 0xffcc33 }));
sun.scale.setScalar(4);
```
`MeshBasicMaterial` ignores lights, so the sun looks self-lit even though the light is inside it. The sun is not a parent of the planets: its `scale` of 4 would also scale their distances.

```js
const orbit = new THREE.Object3D();
parent.add(orbit);
planet.position.x = distance;
orbit.add(planet);
```
The planet sits `distance` units from the pivot. Rotating `orbit.rotation.y` swings it around. Spinning `planet.rotation.y` turns it around its own axis independently.

```js
const earthSystem = new THREE.Object3D();
earthSystem.position.x = 16;
earth.orbit.add(earthSystem);
```
The moon's pivot must follow the Earth's position but not inherit the Earth's spin or scale, so it is a sibling of the Earth mesh inside the same orbit pivot.

```js
b.orbit.rotation.y += b.orbitSpeed * dt;
```
Delta-time animation again. Pressing Space sets `dt` to 0, which pauses everything without stopping rendering.

## Useful scene graph APIs

| API | What it does |
| --- | --- |
| `object.add(child)` / `remove(child)` | Change hierarchy (`add` re-parents) |
| `parent.attach(child)` | Re-parent while keeping the child's world position |
| `object.getWorldPosition(v)` | Position in world space (after all parents) |
| `object.localToWorld(v)` / `worldToLocal(v)` | Convert points between spaces |
| `object.traverse(fn)` | Visit every descendant (e.g. enable shadows on a loaded model) |
| `scene.getObjectByName('Earth')` | Find by name |
| `new THREE.Group()` | Same as `Object3D`, but signals "this is just a container" |

## Try this

1. Add a camera as a child of the Earth so it rides along: remember to remove OrbitControls first.
2. Tilt Earth's axis: `earth.planet.rotation.z = THREE.MathUtils.degToRad(23.4)`.
3. Print `earth.planet.getWorldPosition(new THREE.Vector3())` every second.
