Three.js Procedural City Generator (Day/Night Skyline)

A procedural city in Three.js, with recursive lot subdivision on a street grid, a downtown skyline peak, a single-draw instanced facade shader with lit windows at night, a full day/night cycle, street lamps and traffic.

Key topics: procedural city, city generator, three.js buildings, instancedmesh, window shader, day night cycle

What this code does

- Street Grid: a 9 × 9 grid of 24 m blocks separated by roads; some blocks become parks according to the density setting.
- Lot Subdivision: each block is recursively bisected along its longer side at a random 35–65% cut, giving a mix of narrow and wide lots.
- Skyline: height falls off as a Gaussian from downtown plus noise, snapped to 3 m floors; very tall buildings become glass towers.
- Facade Shader: one InstancedMesh with a custom shader that draws window grids by fract(position / bay size); a per-cell hash decides which windows glow at night.
- Day/Night: the sun travels an arc, and sky, fog, light intensities and the shader's night blend follow it.
- Controls: time of day, animation, city seed, block density, downtown height and traffic.

Continue Learning

JavaScript Implementation

ES6+
// Procedural city: recursive lot subdivision → one instanced box per building

function split (x, z, w, d, depth) {
  if (depth > 2 || Math.random() < 0.25) return lots.push([x, z, w, d])
  const k = 0.35 + Math.random() * 0.3                      // cut along the longer side
  if (w > d) { split(x, z, w * k, d, depth + 1); split(x + w * k, z, w * (1 - k), d, depth + 1) }
  else { split(x, z, w, d * k, depth + 1); split(x, z + d * k, w, d * (1 - k), depth + 1) }
}
lots.forEach(([x, z, w, d], i) => {
  const h = 140 * Math.exp(-3 * (distanceFromCentre / radius) ** 2) + noise * 30  // downtown peak
  buildings.setMatrixAt(i, new THREE.Matrix4().makeScale(w - 1.5, h, d - 1.5).setPosition(x + w / 2, 0, z + d / 2))
})
// Facade shader: fract(uv / (bay, floor)) → window mask; hash(cell) decides which are lit at night