threejs-trees
v0.1.0
Published
Procedural trees, shrubs and rocks for three.js: space-colonisation species presets, instanced and impostored
Maintainers
Readme
threejs-trees
Procedural trees, bushes, plants and rocks for three.js and react-three-fiber: 29 species presets from spruce
to oak to apple to palm to redwood, plus shrubs, flowers, grass tufts, succulents, bamboo, reeds and lily pads, and five
rock presets. Trees grow by space colonisation (Runions et al. 2007) with pipe-model radii, gravitropism, irregular
crowns and fine twigs. They can wear photographed CC0 bark (PBR, at real scale along each branch) and leaf-cluster cards
baked from CC0 leaf photos, or fall back to procedural ones. CC0 photoscanned plants and rocks, and your own glTF
(SpeedTree exports, scans), become instanced species too. Materials are TSL with hierarchical wind, translucency,
crown-depth occlusion, alpha-to-coverage, per-instance variation and weather hooks. createVegetationLayers turns a
species list into LOD'd, crossfaded, impostored layers for
threejs-scatter: that is how a biome table drives forests.
Part of threejs-worldgen.
npm i threejs-trees threejs-scatter three
# for React:
npm i @react-three/fiber reactthree.js
import * as THREE from 'three/webgpu'
import { Scatter } from 'threejs-scatter'
import {
createBarkMaterial, createFruitMaterial, createLeafMaterial, createVegetationLayers, generateTree,
setTreeEnvironment, species,
} from 'threejs-trees'
// One hero tree: one single-material mesh per part. (Avoid one mesh with a material array when it casts shadows:
// three.js shadow passes would rebuild its GPU bindings for every part, every frame.)
const params = { ...species.apple, fruit: 0.4 }
const { trunk, leaves, fruit } = generateTree(params, 7)
const materials = [createBarkMaterial(params), createLeafMaterial(params), createFruitMaterial(params)]
const tree = new THREE.Group()
;[trunk, leaves, fruit].forEach((g, i) => g && tree.add(new THREE.Mesh(g, materials[i])))
scene.add(tree)
// A forest: variants per species, full / simplified / impostor levels, scattered over the terrain.
const layers = await createVegetationLayers({
species: [
{ name: 'oak', density: 0.4, group: 'canopy', cluster: { scale: 120, threshold: 0.45, strength: 0.9 } },
{ name: 'beech', density: 0.3, group: 'canopy' }, // same group: shares the oaks' points, never overlaps them
{ name: 'fern', density: 0.6 },
{ name: 'boulder', density: 0.1 }, // rock presets work too
],
variants: 3,
density: (name, x, z) => biomes.weight('temperateForest', x, z), // optional per-species density field
renderer, // optional: bakes octahedral impostors
})
Scatter.create({ camera, scene, terrain, layers })
setTreeEnvironment({ windStrength: 0.5, sun: sunLight }) // shared by all vegetation materials
setTreeEnvironment({ snow: 0.6, wetness: 0.3 }) // global weatherPhotoreal: CC0 assets
The repository stays licence-clean: no asset is committed. node scripts/fetch-assets.mjs downloads the CC0 set listed
in cc0-assets.json (Poly Haven and ambientCG, ~124 MB, every file pinned by sha256) into
assets/cc0/ and writes assets/cc0/manifest.json:
| Kind | Assets | Used for |
|---|---|---|
| Photoscanned plants | island_tree_02, searsia_lucida, wild_rooibos_bush, fern_02, grass_medium_02, dandelion_01, cheiridopsis_succulent | olive, thornShrub / shrub, dwarfShrub, fern, tallGrassTuft, flowers, succulent |
| Photoscanned rocks | boulder_01, namaqualand_boulder_04, rock_moss_set_01, rock_07 | boulder, cliffChunk, rock, scree, pebble (scaled to the preset) |
| Bark (1K PBR) | jolcham_oak_bark_01, bark_willow_02, chinese_hackberry_bark, pine_bark, metasequoia_bark, palm_bark | every generated tree, re-tinted to its barkColor |
| Leaf photos (ambientCG) | LeafSet016 oak, LeafSet005 beech, LeafSet010 maple, LeafSet024, LeafSet022, LeafSet018, LeafSet019 conifer sprays, PineNeedles001 | baked at runtime into 2 × 2 leaf-cluster atlases |
| Ground | forest_leaves_02, forrest_ground_01 | demo forest floor |
import { createVegetationLayers, loadAssetLibrary } from 'threejs-trees'
const assets = await loadAssetLibrary('/cc0/', { anisotropy: renderer.getMaxAnisotropy() }) // null when not fetched
const layers = await createVegetationLayers({ species, renderer, assets, style: 'photoreal' }) // or 'textured' / 'procedural'With assets, every biome scatter-table species that has a photoscan uses it (photorealOptions(manifest) lists the
mapping), and generated species are dressed in the matching bark and leaf photos. Full-size CC0 tree scans are hundreds
of MB (Poly Haven's fir_tree_01 alone is 480 MB of geometry), so big canopy trees stay generated: bring your own (below).
Your own models: SpeedTree, photogrammetry, any glTF
SpeedTree trees and marketplace assets are licensed per user and must not be redistributed, so keep them out of the
repository (e.g. in the gitignored assets/) and load them at runtime:
import { createVegetationLayers, loadModelSpecies } from 'threejs-trees'
// SpeedTree: export glTF (or FBX → glTF with Blender / FBX2glTF). Several trees in one file become variants.
const myOak = await loadModelSpecies('/assets/speedtree/oak.glb', {
variants: 'nodes', // each top-level node is a variant ('single' / 'auto')
params: { spacing: 10, scaleRange: [0.9, 1.1], hueVariation: 0.05 },
dracoDecoderPath: '/draco/', // optional: Draco meshes
ktx2: { transcoderPath: '/basis/', renderer }, // optional: KTX2 textures
// isFoliage: (m) => m.name.includes('Leaf'), // optional: which materials are foliage
})
const layers = await createVegetationLayers({ species: [{ name: 'oak', density: 0.5, model: myOak }], renderer })loadModelSpecies (three's GLTFLoader, no other dependency) bakes each variant into its own space with the trunk base
at the origin, splits multi-material meshes so every part is single-material, marks alpha-tested / transparent / leaf-
named materials as foliage (two-sided, alpha-to-coverage, translucency, flutter), and adds crown-depth occlusion and a
per-leaf random for thinning, burn and damage. Levels: the original (capped at modelTriangles[0], default 200 k), a
simplified one (leaves pruned stochastically with the survivors grown to keep coverage, wood and rock vertex-clustered),
and an octahedral impostor; all materials go through the same weather pipeline as the generated trees. Keep real-world
metres in the export.
React Three Fiber
import { Forest, Tree } from 'threejs-trees/react'
<Tree species="oak" seed={7} position={[0, 0, -10]} />
<Forest terrain={ground} seed={3} species={[{ name: 'spruce', density: 0.7 }, { name: 'birch', density: 0.2 }]}
environment={{ windStrength: 0.4 }} maxDistance={800} /><Forest> takes every <Scatter> prop plus the vegetation options; it bakes impostors with the R3F renderer
(impostors={false} to skip) and picks up the first DirectionalLight as the sun.
Generators
| Export | |
|---|---|
| generateTree(params, seed, { detail }) | { trunk, leaves, fruit, bounds }. detail < 1 gives a lighter mesh with the same silhouette. Missing params come from the defaults. |
| generateTreeLevels(params, seed, details) | Several detail levels sharing one grown skeleton. |
| growSkeleton(params, rand) | The space-colonisation skeleton (nodes, parents, pipe-model radii). |
| generateRock(params, seed) | Displaced icosphere (fBm lumps, Worley facets and cracks), flattened base, moss on top. |
| mergeTreeGeometry(tree) | One geometry with groups 0 = bark, 1 = leaves, 2 = fruit. |
| createVegetationLayers(options) | ScatterLayer[] for threejs-scatter. |
| species, rocks | Presets. SpeciesName keys: oak beech maple birch spruce pine fir redwood acacia baobab palm jungleEmergent olive cypress mangrove deadSnag cactus shrub dwarfShrub thornShrub fern reed apple berryBush flowers tallGrassTuft succulent bamboo lilyPad; rocks: boulder rock pebble scree cliffChunk. |
| createBarkMaterial, createLeafMaterial, createFruitMaterial, createRockMaterial | TSL node materials (bark: { textures } for photographed PBR bark; leaves: { textures } for a baked atlas). |
| createAssetMaterial(material, role, options) | A glTF material converted into the vegetation pipeline ('bark', 'foliage', 'rock'). |
| loadAssetLibrary(url), loadModelSpecies(url), prepareModel(object) | CC0 library; load / prepare any glTF plant or rock. |
| bakeLeafAtlas(color, opacity, options) | Leaf-cluster atlas from a leaf-set photo (pure; coverage-preserving, dilated mips). |
| pruneComponents, clusterDecimate, modelLevels | Simplification used for model LODs. |
| treeUniforms, setTreeEnvironment | Shared wind, sun and global weather uniforms. |
Every geometry has position, normal, uv, color (linear) and cardRandom (one random per leaf card, frond or
branch; -1 on the trunk), built straight into typed arrays with 16-bit indices where they fit.
TreeParams
All lengths in metres; plain JSON. Spread a preset and override: { ...species.oak, height: 20 }.
| Field | Oak | |
|---|---|---|
| kind | 'colonization' | Generator: colonization, palm, cactus, fern, reed, flowers, tuft, succulent, bamboo, lilyPad. |
| height, trunkHeight | 14, 3.2 | Total height; clear trunk below the crown. |
| crownShape | 'ellipsoid' | sphere, ellipsoid, hemisphere, cone, column, umbrella, vase. |
| crownRadius, crownHeight | 7, 11 | Crown envelope. |
| attractionPoints | 2200 | Points in the crown; more = finer branching. |
| segmentLength, killDistance, influenceDistance | 0.35, 0.7, 2.8 | Space-colonisation step and radii. |
| iterations | 140 | Maximum growth steps. |
| tropism | [0, 0.04, 0] | Added to every growth direction (negative y droops). |
| jitter | 0.35 | Random wobble (gnarliness). |
| leader | false | Straight central leader (conifers). |
| stems | 1 | Basal stems (shrubs), cactus arms, reed / flower / bamboo stalks. |
| trunkLean | 0.06 | Max trunk lean, radians. |
| radiusExponent | 2.3 | Pipe model: parent^e = Σ children^e (2 = da Vinci). |
| baseRadius, tipRadius | 0.45, 0.012 | Trunk and twig radius. |
| rootFlare, buttress | 0.35, 0 | Wider base; lobed buttress roots (cypress, jungle). |
| propRoots | 0 | Arching prop roots (mangrove). |
| radialSegments | 9 | Trunk sides; branches use fewer. |
| leafShape | 'broad' | broad, needle, palm, fern, blade, none. |
| leafSize, leafDensity, leafDepth | 0.75, 2, 3 | Card size, cards per twig node, nodes from the tips that carry leaves. |
| gravitropism | 0.18 | Extra sag growing with a limb's reach from the trunk. |
| crownIrregularity | 0.5 | Seeded lobes, a lopsided side and an uneven top on the crown envelope. |
| twigs | 0.5 | Fine twig sprigs at the branch tips (foliage hangs on finer wood). |
| barkColor, barkContrast, barkMarks | #54463a, 0.75, 0 | Bark colour (also tints photographed bark), furrow depth, birch marks. |
| barkTile | 1.5 | Metres per repeat of a bark texture (set from the CC0 set's real size). |
| leafColor, leafColorVariation | #4a6b2a, 0.15 | |
| fruit, fruitSize, fruitColors | 0, 0.08, ['#b3261e'] | Fruit per twig node (apples, berries) or flower heads per stalk; seeded palette. |
| spacing | 9 | Suggested scatter spacing. |
| scaleRange, leanVariation | [0.8, 1.2], 0.03 | Per-instance scale and lean when scattered. |
| hueVariation, saturationVariation | 0.08, 0.12 | Per-instance foliage hue (± rad) and saturation (± fraction), in the shader. |
| densityVariation | 0.25 | Per-instance crown thinning: each instance drops up to this share of its leaf cards. |
RockParams: size, elongation, flatness, roughness, facets, noiseScale, detail, baseCut, color,
colorVariation, moss, mossColor, spacing.
Vegetation options
| Option | Default | |
|---|---|---|
| species | — | { name, density, params?, variants?, group?, spacing?, cluster?, scale?, tilt?, min/maxSlope?, min/maxHeight?, align?, sink?, … }[]. |
| variants | 3 | Generated variants per species. |
| seed | 1 | Variant shapes. |
| density | — | (species, x, z) => number multiplier, e.g. biome weights. |
| renderer | — | Initialised WebGPURenderer: bakes impostors. Without it the simplified mesh is the last level. |
| lodDistances | [35, 110, 600] | Full / simplified / impostor end distances for a 15 m tree, scaled by each species' size. |
| simplifiedDetail | 0.35 | Detail of the simplified level. |
| impostor | by size | bakeImpostor options; atlas 1024 px from 8 m, 512 from 2 m, else 256. |
| castShadow | true | Mesh levels (impostors never cast). |
| weather | global | Per-material weather nodes, below. |
| assets, style | —, 'photoreal' | CC0 library and how to use it ('photoreal', 'textured', 'procedural'). |
| species[].model | — | A loaded model (loadModelSpecies) to scatter instead of a generated plant. |
| triangleBudget | 3 000 000 | Mesh LOD ranges shrink until the expected triangles fit; impostors take over sooner. |
| crossfade | 0.12 | Dithered crossfade band between levels (no pops). |
| modelTriangles | [200000, 15000] | Full / simplified triangle caps for loaded models. |
Weather hooks
Bark, leaf, fruit and rock materials read four 0..1 inputs. By default they follow the global uniforms in
treeUniforms (wetness, snow, burn, damage, set with setTreeEnvironment); pass weather: { burn: node, … }
to any material factory, createVegetationLayers or <Forest> / <Tree> to drive one from your own TSL node: a
uniform(), a world-space mask sampled at positionWorld, or something derived from scatterParamsNode() per
instance.
| Input | Effect |
|---|---|
| wetness | Darker albedo, lower roughness. |
| snow | White cover on upward faces (noisy edge), all over near 1. |
| burn | Bark chars along the furrows first; leaves scorch brown then black and drop out; fruit darkens; rock gets soot. |
| damage | Side branches break off and leaf mass and fruit thin out (whole cards / branches collapse in the vertex shader, no alpha cost). No effect on rock. |
Imports from three/webgpu (WebGPURenderer; falls back to WebGL2 by itself). Full API docs:
https://askalice.github.io/threejs-worldgen/docs/.
License
Apache-2.0
