threejs-city
v0.1.0
Published
Procedural settlements for three.js: road networks, blocks, lots, buildings and terrain flattening
Maintainers
Readme
threejs-city
Procedural settlements for three.js on threejs-biomes
worlds: hamlets to cities placed where the land suits them, road networks grown along a tensor field, blocks and lots,
buildings matched to the local climate, procedural TSL facades and road surfaces with weather hooks, and terrain flattened
under it all. Works on flat worlds and on planets, from orbit down to street level. Everything derives from seed and the
world, and every setting is live.
npm i threejs-city threejs-biomes threethree.js
import { WebGPURenderer } from 'three/webgpu'
import { World } from 'threejs-biomes'
import { City, findSettlements } from 'threejs-city'
const world = new World({ seed: 11 })
const [site] = findSettlements(world, world.frame, { minX: -5000, minZ: -5000, maxX: 5000, maxZ: 5000 })
const city = await City.create({ world, camera, scene, center: [site.x, site.z], size: site.size, radius: site.radius })
// That's it: it updates itself (LOD, progressive generation) whenever `scene` renders.
city.set({ facade: { night: 1 } }) // lights on (a uniform: free)
city.set({ weather: { roofs: { snow: 1 } } }) // snow on every roof
city.setBuildingWeather(42, { burn: 0.9 }) // one building on fire
city.set({ style: 'organic', seed: 2 }) // layout settings regenerate
city.buildingAt(x, z) // Building | null (frame-local x, z)
city.graph?.shortestPath(a, b) // node ids along the roads
city.dispose() // also removes its terrain editsEvery settlement in a region at once, sized by how good each site is:
import { Settlements } from 'threejs-city'
const towns = await Settlements.create({ world, camera, scene, region: { minX: -20000, minZ: -20000, maxX: 20000, maxZ: 20000 } })On a planet, pass a frame: City.create({ world, frame: world.frameAt(lat, lon), … }). The city's root object is placed
and oriented on the sphere, and its flatten modifiers are converted to planet coordinates, so roads and buildings sit
exactly on the terrain.
Needs WebGPURenderer from three/webgpu (it falls back to WebGL2 by itself).
React Three Fiber
import { City, Settlements } from 'threejs-city/react'
<City world={world} size="village" center={[200, -50]} facade={{ night }} weather={{ roads: { wetness: rain } }} />
<Settlements world={world} region={{ minX: -8000, minZ: -8000, maxX: 8000, maxZ: 8000 }} city={{ facade: { night } }} />Props are the options (reset(props) on every render, update() in useFrame). ref gives the CityImpl /
SettlementsImpl instance. react and @react-three/fiber are optional peer dependencies; the core never imports them.
How it works
- Placement (
findSettlements): the frame is cut intocellSizesquares, each sampled on a grid. A site scores flatness × nearness to a river or coast (but dry) × temperate climate × not in an excluded biome. The best site per square abovethresholdbecomes a settlement, sized by importance (score × room to grow × a seeded prosperity roll), so hamlets are common and cities rare. - Roads (
growRoads): arterials grow from the centre and branch into collectors and local streets (Parish & Müller 2001), following a tensor field (Chen et al. 2008) built from grid patches, a radial centre and the terrain gradient (streets along contours and coasts). Local constraints: avoid water and steep grades (steer, else prune), snap to nearby junctions and roads, refuse acute angles, bridge narrow rivers. The result is a planarRoadGraph(crossings are always nodes). Surfaces follow class, district and size: asphalt, cobbled old-town streets, gravel and dirt farm tracks; rural roads have no kerbs. - Blocks and lots: faces of the graph (half-edge traversal), inset by each road's half width and sidewalk, split by recursive oriented-bounding-box cuts that keep street frontage. Roads through open ground get lots along both sides (villages, ribbon development, farmsteads).
- Districts: downtown, residential, industrial, park and farmland, by distance from the centre plus noise.
- Buildings: towers (podium, shaft and crown, with box, chamfered, round or inset shafts), apartment blocks
(penthouses, balconies), houses (gable, hip, skillion or flat roofs, L-shaped wings, chimneys, stilts) and sheds
(saw-tooth roofs). Materials, roofs and details come from an architecture picked from the climate at the centre:
temperate,cold(steep roofs, timber),arid(adobe, flat roofs),mediterranean,tropical,wetland(stilts). - Terrain: each road gets a graded profile (max grade, smoothed);
FlattenPathmodifiers along the roads (bridges excluded) and pads under buildings are registered on the world in one batch and removed ondispose().
Rendering
- Walls and roofs: one
BatchedMesheach, with a full and a box geometry per building; LOD swaps geometry per instance (setGeometryIdAt) and hides far buildings. - Balconies, railings, rooftop plant, tanks, antennas, chimneys, AC units and stilts: one more
BatchedMeshof eight shared unit geometries, instanced with per-instance matrices and colour. - Roads: one indexed mesh of shared-vertex strips (carriageway, kerbs, sidewalks, skirts, bridge decks, parapets, piers) and junction discs.
- Geometry is built straight into typed arrays (16-bit indices where they fit), bounds are set explicitly, and all materials are shared TSL node materials varied per vertex or instance.
Facades are a TSL shader: per-style window grids from wall coordinates (metres along the wall and above the ground
floor), frames and mullions, shopfronts, window lights hashed per window that glow with night, and procedural
plaster, brick, wood, stone, concrete, glass, adobe and metal. Roofs draw tiles, slates, shingles, standing-seam metal,
thatch and gravel. Roads draw lane markings, worn tyre tracks, cracks and patches on asphalt, cobblestones, gravel,
rutted dirt, paving slabs and kerbs. No texture assets.
Weather hooks
weather.walls, weather.roofs and weather.roads each take { wetness, snow, burn, damage } (0..1, default 0);
city.setBuildingWeather(id, partial) overrides single buildings (the larger value wins). Wet surfaces darken and turn
glossy, with puddles on roads; snow settles on upward faces and stays out of tyre tracks; burn chars surfaces with
embers near 1; damage adds cracks, holes and potholes. They are uniforms and a small data texture, so a weather system
can drive them every frame.
Data for other packages
city.data() returns a JSON-safe CityData in frame-local metres: road nodes and edges (class, surface, width,
sidewalk, lanes, speed, access, graded centreline), lots (district, polygon, street frontage and its road edge) and
buildings (style, material, roof, height, footprint, entrance). Add props to city.local, which uses the same
coordinates.
import { laneOffset, pointOnEdge, roadAnchors, routeCost } from 'threejs-city'
const data = city.data()!
roadAnchors(data, { spacing: 30, surfaces: ['asphalt'] }) // street lights
roadAnchors(data, { spacing: 45, sides: 'one', types: ['secondary'] }) // power poles
data.lots.filter((l) => l.frontage && l.building >= 0) // mailboxes at l.frontage
const route = city.graph!.shortestPath(from, to, routeCost('bicycle', city.options.roads))
const edge = data.roads.edges[e]
pointOnEdge(edge, t, laneOffset(edge, 0, 1)) // a car in the first lane, a→bOptions
All optional; every field has a default (DEFAULT_CITY). Nested objects merge field by field. Layout changes
regenerate the settlement, palette changes rebuild its meshes, everything else is a uniform.
| Option | Default | What it does |
|---|---|---|
| seed | 1 | Same seed, options and world give the same settlement. |
| center | [0, 0] | Centre, frame-local [x, z] metres. |
| size | 'town' | 'hamlet' · 'village' · 'town' · 'city': radius, height limit, layout, districts and surfaces. |
| radius | 0 | Metres; 0 = the middle of the size class's range. |
| style | 'auto' | 'grid' · 'radial' · 'organic' presets for the tensor field and road lengths. |
| siteResolution | 0 | Terrain sampling step, metres (0 = radius / 60, clamped 6–25). |
| roads | | Per class (primary, secondary, minor): width, sidewalk, segment, branchSpacing, branchChance, through, delay. Plus arms, snapRadius (14), minAngle (32°), maxGrade (0.16), maxBridge (140 m), maxSegments, extent, rural surfaces, unpavedWidth, traffic (lanes, speed), surfaceSpeed. |
| field | | Tensor field: gridAngle, grid, gridPatches, gridVariation, gridDecay, radial, radialDecay, terrain, terrainSlope, noise (degrees), noiseScale. |
| districts | | noise, patchSize, parkSize, densityFalloff, and per district styles.*: blockSize, lotArea, lotWidth, setback, coverage, floors. |
| blocks | | minArea, maxArea, margin. |
| lotJitter | 0.35 | How unevenly blocks are split. |
| roadside | | Lots along open roads: enabled, junctionClearance, margin, depth. |
| buildings | | floorHeight per style, towerFloors (12), houseFloors (2), houseWidth, houseDepth, sideGap, sawtoothRoofs, chimneys, rooftop, penthouses, variation, areaPerPerson. |
| architecture | 'auto' | 'temperate' · 'cold' · 'arid' · 'mediterranean' · 'tropical' · 'wetland'; auto reads the climate at the centre. |
| architectures | | Per architecture: weighted houseMaterials, blockMaterials, towerMaterials, houseRoofs, roofMaterials; pitch, overhang, stilts, wings, balconies, airConditioners. |
| climate | null | Override { temperature, moisture, biome } for 'auto'. |
| terrain | | flatten, flattenLots, maxGrade (0.1), step, roadFalloff, lotFalloff, bridgeClearance, foundation, roadOffset. |
| sizes | | Size classes: minScore, radius, population, maxFloors, style, arms, districts shares, surfaces, oldTown. |
| facade | | night, windowLight, lightIntensity, glass, frame, windows per style (bayWidth, windowWidth, windowHeight, sill, frame, lit), walls / roofs palettes per material, variation, patternScale. |
| roadLook | | colors per surface, sidewalk, kerb, kerbHeight, marking, centerLine, concrete, markings, wear. |
| weather | zeros | walls, roofs, roads: { wetness, snow, burn, damage }. |
| lod | | simple (450 m: box buildings), hide (9 km), roads (7 km). |
| progressive | false | Generate over several frames instead of inside create. |
| buildBudget | 6 | Milliseconds per update() when progressive. |
Object inputs (not options): world, frame, camera, scene.
Placement (findSettlements(world, frame, region, options)): seed, cellSize (5000), sampleSpacing (250),
threshold, margin, maxSlope, water, temperature ± temperatureRange, moisture ± moistureRange,
minElevation, excludeBiomes, variety, room, sizes.
The pipeline is exported piece by piece and is pure (no DOM, no GPU): planCity, growRoads, extractBlocks,
subdivideBlock, roadsideLots, planBuilding, gradeRoads, buildingGeometry, roadGeometry, cityData.
Full API docs: https://askalice.github.io/threejs-worldgen/docs/.
Performance
A town (radius ~600 m, ~200–300 buildings) plans in about 0.1 s plus terrain sampling (a few hundred ms of world
noise); a 1.5 km city (~3,600 buildings, ~6,000 road edges) in under a second plus mesh building. Use
progressive: true for big cities. The world checks every modifier's bounding box per height sample, so thousands of
pads cost terrain time; set terrain.flattenLots: false for very large cities.
License
Apache-2.0
