Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add vegetation addon: branching trees, grass, scattering and level of detail

Nguyen Xuan Anfac88fc0d536
diff --git a/.gitignore b/.gitignore
index 4278ef3c..0559ee1a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -18,6 +18,7 @@ public/mesh-query.md
public/primitives.md
public/shrinkwrap.md
public/spume.md
+public/vegetation.md
public/scene-graph.md
public/modeling.md
public/animation-curves.md
diff --git a/README.md b/README.md
index 1fef3b72..feca4992 100644
--- a/README.md
+++ b/README.md
@@ -209,6 +209,7 @@ The source [shrinkwrap addon](docs/shrinkwrap.md) wraps static vertices with nea
Compatible results can become relative GPU morph targets, so animation reuses the computed shape instead of repeating the vertex queries every frame.
The source [Spume addon](docs/spume.md) plays back liquid baked by the [Spume](https://github.com/codepawl/spume) GPU solver, with whitewater, through `renderer.replaceParts`.
+The source [Vegetation addon](docs/vegetation.md) grows seeded trees with real branches and leaf cards, grass, Poisson-disk scattering on terrain and distance level of detail.
The solver runs offline; the browser only reads the compact cache.
The current source adds [surface attachments](docs/surface-attachment.md) for rigid accessories following a selected triangle through morphing and skinning.
diff --git a/docs/guide.md b/docs/guide.md
index 1a12525c..c3f156aa 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -174,6 +174,16 @@ Patches and shrinkwrap are static operations. They do not follow skin or morph d
The [Spume contract](/spume.md) covers the cache format, whitewater options, placement and measured cost.
The scene must stay rigid and untextured while frames are replaced.
+## Trees and grass
+
+`67js/addons/vegetation` is in the current source and not yet published. It grows seeded trees with real branches and leaf cards, grass and flowers.
+
+1. Scatter with `scatterVegetation({ area, density, terrainHeight, slopeLimit, exclusion, mix, leaves })`.
+2. Pick detail per camera with `selectLevels(forest.instances, eye)`.
+3. Pass `view.parts` to `Renderer67` and rebuild when `view.changed` is true.
+
+Use `leaves: 'mesh'` until the renderer honors alpha masks. The [Vegetation contract](/vegetation.md) lists species, triangle budgets and limits.
+
## Retained surface attachments
`createSurfaceAttachment` is introduced in `0.4.1`. Published npm `0.4.0` does not include this addon.
diff --git a/docs/vegetation.md b/docs/vegetation.md
new file mode 100644
index 00000000..212dcbf1
--- /dev/null
+++ b/docs/vegetation.md
@@ -0,0 +1,99 @@
+# Vegetation
+
+`67js/addons/vegetation` grows seeded trees, bushes and grass, scatters them on terrain and switches detail by distance.
+It is in the current source and not yet published. Everything returns plain renderer parts: geometry, a matrix and a material.
+
+```js
+import { Renderer67 } from '67js';
+import { scatterVegetation, selectLevels } from '67js/addons/vegetation';
+
+const forest = scatterVegetation({
+ area: { minX: -40, maxX: 40, minZ: -40, maxZ: 40 },
+ density: 0.016,
+ terrainHeight: (x, z) => Math.sin(x * 0.1) * 1.5,
+ slopeLimit: 30,
+ exclusion: (x, z) => Math.hypot(x, z) < 8,
+ mix: { broadleaf: 3, birch: 1.5, conifer: 2, bush: 2.5 },
+ leaves: 'cards',
+ seed: 11,
+});
+const view = selectLevels(forest.instances, camera.eye, { cullDistance: 120 });
+const renderer = new Renderer67(canvas, [terrain, ...view.parts], options);
+```
+
+## Trees
+
+`createTree(species | { species, height, leaves }, seed)` grows one tree. Species: `broadleaf`, `birch`, `conifer`, `palm`, `bush`.
+The same species and seed always give the same tree.
+
+The skeleton is a parametric recursive branching model: each generation has a length, wander, tropism (up or droop), taper and child spread.
+It was chosen over space colonization because a species is a short readable preset, the cost is known before growing, and conifer whorls and palm fronds fit the same code.
+Branches are swept tubes with parallel-transported rings, a taper, a root flare below the ground line and bark UVs (`u` around, `v` along, one tile per 0.6 m).
+Leaves sit on terminal twigs, face outward and up with jitter, and carry vertex colors that darken toward the crown center, so the canopy has depth.
+Shading normals blend toward the crown, so a flat card lights like part of a rounded crown.
+
+The tree has three levels of detail, each listing parts with a `role`, `geometry`, `material` and `tintable` flag:
+
+| Level | Content | Default switch distance |
+| --- | --- | --- |
+| 0 | Full skeleton, every leaf site | up to 38 m |
+| 1 | Twigs dropped, fewer sides, one third of the leaves 1.7 times larger | 38 to 95 m |
+| 2 | Trunk and main limbs, crown as merged clumps (low-poly blobs or crossed cards) | beyond 95 m |
+
+Measured triangle counts for seed 4 (level 0 / 1 / 2):
+
+| Species | `cards` | `mesh` |
+| --- | --- | --- |
+| broadleaf | 7.4k / 2.4k / 0.7k | 16.0k / 5.3k / 3.0k |
+| birch | 10.7k / 3.3k / 0.8k | 21.9k / 7.0k / 2.8k |
+| conifer | 26.1k / 7.2k / 2.3k | 63.9k / 19.8k / 3.4k |
+| palm | 6.4k / 1.9k / 1.1k | 11.8k / 3.7k / 2.9k |
+| bush | 4.7k / 1.7k / 0.5k | 10.9k / 3.7k / 1.9k |
+
+## Leaves: cards or mesh
+
+`leaves: 'cards'` (default) uses a procedural RGBA leaf texture (`material.map`) on crossed, slightly curved cards with `alphaMode: 'mask'`, `alphaCutoff: 0.5` and `doubleSided: true`.
+Until the renderer honors alpha masking, cards draw as opaque quads: use `leaves: 'mesh'` there.
+Cards also carry both faces in the geometry, so they stay visible with back-face culling. Once `doubleSided` is honored, that duplicate costs triangles you can drop.
+`leaves: 'mesh'` builds real leaf silhouettes (ovate, fir spray, palm leaflet) as folded, drooping meshes with the `foliage` tag. It needs no alpha support and costs about twice the triangles.
+
+Wind: the vertex shader sways only the `foliage` and `grass` tags, by local height. Mesh leaves and grass blades therefore sway, and bark (a standard material) stays still.
+Textured materials must use a standard tag, so `cards` do not sway yet. A small shader hook that reads the tag for textured materials would add it.
+
+## Grass and flowers
+
+`createGrassClump({ blades, height, radius, style, seed })` builds `blades` (curved tapered blades with the `grass` tag, level 1 has half the blades) or `cards` (three crossed alpha cards).
+`createFlowerPatch({ flowers, height, color, seed })` builds stems, six petals and a center; color lives in vertex colors.
+`createGrassField(options)` is `scatterVegetation` with a grass and flower mix at 2.5 clumps per square meter.
+
+## Scattering
+
+`scatterVegetation({ area, density, terrainHeight, slopeLimit, exclusion, seed, mix, variants, leaves, scale, spacing })`:
+
+- Poisson-disk spacing (Bridson with restarts, so exclusion zones cannot strand regions). `density` is instances per square meter; spacing defaults to `sqrt(0.6 / density)`.
+- `slopeLimit` is in degrees, measured from `terrainHeight` over a 1.2 m span. `exclusion(x, z)` returns true to keep a spot clear.
+- `mix` weighs species (`broadleaf`, `birch`, `conifer`, `palm`, `bush`, `grass`, `flowers`); low-frequency noise groups species into stands.
+- `variants` (default 3) variants per species are shared by every instance, so the renderer batches each part by geometry identity. Instances differ by yaw, scale and tint.
+
+It returns `{ instances, parts, variants, counts }`; `parts` shows every instance at level 0.
+
+## Level of detail
+
+`selectLevels(instances, eye, { distanceScale, hysteresis, cullDistance })` sets each instance's level from its distance to `eye`.
+A level changes only after the distance passes its threshold by `hysteresis` (default 0.12), so instances on a boundary do not flicker.
+It returns `{ parts, changed, levelCounts, culled, triangles }`. Part objects are cached per instance and level, so unchanged instances keep their identity.
+When `changed` is true, build a new renderer from the new parts. Grass switches at 24 m; set `cullDistance` to drop far instances.
+
+`vegetationParts(variant, matrix, level, name)` places one tree or clump yourself.
+
+## Measured
+
+On the demo clearing (125 trees and bushes, 1,941 grass clumps and 129 flower patches, camera at the clearing edge), headless Chrome with GPU:
+`mesh` leaves with level of detail draw 2.28M triangles in 65 draws (3.78M without level of detail); `cards` draw 1.15M. Building the scene takes about 1 s; a frame takes under 0.2 s.
+Meshes and textures are built in plain JavaScript, so tests run in Node.
+
+## Limits
+
+- Cards need the renderer's alpha mask to look right, and do not sway under the current shader.
+- Level changes pop; there is no cross-fade. Level 2 crowns are blobs or crossed cards, not baked imposters.
+- Species are fixed presets; there is no seasonal color, wind-bent skeleton or collision with other trees.
diff --git a/package.json b/package.json
index 6b3e12a7..5c1d906d 100644
--- a/package.json
+++ b/package.json
@@ -50,7 +50,8 @@
"docs/agent-render-jobs.md",
"docs/agent-motion.md",
"docs/agent-character-motion.md",
- "docs/agent-review.md"
+ "docs/agent-review.md",
+ "docs/vegetation.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -76,6 +77,7 @@
"./addons/surface-attachment": "./build/surface-attachment.js",
"./addons/physics": "./build/physics.js",
"./addons/spume": "./build/spume.js",
+ "./addons/vegetation": "./build/vegetation.js",
"./addons/agent-scene": "./build/agent-scene.js",
"./addons/agent-asset": "./build/agent-asset.js",
"./package.json": "./package.json"
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index 2bf49817..74f34e62 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -39,7 +39,7 @@ await copyFile(resolve(root, 'docs/gltf.md'), resolve(root, 'public/gltf.md'));
const sourceDocuments = [
'scene-graph.md', 'modeling.md', 'animation-curves.md', 'animation-mixer.md',
'gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md',
- 'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md', 'spume.md',
+ 'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md', 'spume.md', 'vegetation.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
];
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 53f585d1..e732fa72 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -13,7 +13,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
## Choose the surface
- An object studio uses `src/model.js` and `src/main.js`.
-- An outdoor world uses `src/nature.js` and `src/nature-viewer.js`.
+- An outdoor world uses `src/nature.js` and `src/nature-viewer.js`. Real trees, bushes, grass and forest scattering use optional `src/vegetation.js` and `docs/vegetation.md` (`leaves: 'mesh'` needs no alpha support).
- A deterministic film uses `src/film.js` and `src/film-player.js`.
- A keyframe scene uses `src/animation.js`, `src/motion.js` and `src/motion-player.js`.
- An authored camera uses `src/camera-path.js` and the checkout's `docs/camera-path.md`.
diff --git a/src/vegetation-geometry.js b/src/vegetation-geometry.js
new file mode 100644
index 00000000..7c9f57a0
--- /dev/null
+++ b/src/vegetation-geometry.js
@@ -0,0 +1,233 @@
+// Low-level geometry helpers for the vegetation addon: vector math, seeded noise,
+// a mesh builder, swept tubes (branches) and leaf surfaces (leaf meshes and cards).
+
+export const FULL_TURN = Math.PI * 2;
+export const WORLD_UP = [0, 1, 0];
+
+export function createRandom(seed) {
+ let state = Math.floor(seed) >>> 0;
+ return () => {
+ state += 0x6d2b79f5;
+ let mixed = Math.imul(state ^ state >>> 15, state | 1);
+ mixed ^= mixed + Math.imul(mixed ^ mixed >>> 7, mixed | 61);
+ return ((mixed ^ mixed >>> 14) >>> 0) / 4294967296;
+ };
+}
+
+export function lerp(first, second, amount) {
+ return first + (second - first) * amount;
+}
+
+export function clamp(value, minimum, maximum) {
+ return Math.min(maximum, Math.max(minimum, value));
+}
+
+export function randomInRange(random, range) {
+ return lerp(range[0], range[1], random());
+}
+
+function hashLattice(latticeX, latticeY, seed) {
+ let mixed = Math.imul(latticeX, 374761393) ^ Math.imul(latticeY, 668265263) ^ Math.imul(seed, 2147483647);
+ mixed = Math.imul(mixed ^ mixed >>> 13, 1274126177);
+ return ((mixed ^ mixed >>> 16) >>> 0) / 4294967296;
+}
+
+/** Smooth value noise in [0, 1]; a positive period makes it tile on that axis. */
+export function valueNoise(x, y, seed, periodX = 0, periodY = 0) {
+ const cellX = Math.floor(x);
+ const cellY = Math.floor(y);
+ const fractionX = x - cellX;
+ const fractionY = y - cellY;
+ const smoothX = fractionX * fractionX * (3 - 2 * fractionX);
+ const smoothY = fractionY * fractionY * (3 - 2 * fractionY);
+ const wrap = (value, period) => period > 0 ? ((value % period) + period) % period : value;
+ const corner = (offsetX, offsetY) => hashLattice(wrap(cellX + offsetX, periodX), wrap(cellY + offsetY, periodY), seed);
+ const top = lerp(corner(0, 0), corner(1, 0), smoothX);
+ const bottom = lerp(corner(0, 1), corner(1, 1), smoothX);
+ return lerp(top, bottom, smoothY);
+}
+
+export function addVectors(first, second) {
+ return [first[0] + second[0], first[1] + second[1], first[2] + second[2]];
+}
+
+export function subtractVectors(first, second) {
+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];
+}
+
+export function scaleVector(vector, amount) {
+ return [vector[0] * amount, vector[1] * amount, vector[2] * amount];
+}
+
+export function addScaled(base, direction, amount) {
+ return [base[0] + direction[0] * amount, base[1] + direction[1] * amount, base[2] + direction[2] * amount];
+}
+
+export function dotProduct(first, second) {
+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];
+}
+
+export function crossProduct(first, second) {
+ return [
+ first[1] * second[2] - first[2] * second[1],
+ first[2] * second[0] - first[0] * second[2],
+ first[0] * second[1] - first[1] * second[0],
+ ];
+}
+
+export function vectorLength(vector) {
+ return Math.hypot(vector[0], vector[1], vector[2]);
+}
+
+export function normalized(vector) {
+ const length = vectorLength(vector);
+ if (length < 1e-9) return [0, 1, 0];
+ return [vector[0] / length, vector[1] / length, vector[2] / length];
+}
+
+export function lerpVectors(first, second, amount) {
+ return [lerp(first[0], second[0], amount), lerp(first[1], second[1], amount), lerp(first[2], second[2], amount)];
+}
+
+/** Two unit vectors perpendicular to the direction and to each other. */
+export function createFrame(direction) {
+ const helperAxis = Math.abs(direction[1]) < 0.9 ? WORLD_UP : [1, 0, 0];
+ const first = normalized(crossProduct(direction, helperAxis));
+ const second = crossProduct(direction, first);
+ return { first, second };
+}
+
+function transportFrame(frame, direction) {
+ const first = normalized(addScaled(frame.first, direction, -dotProduct(frame.first, direction)));
+ return { first, second: crossProduct(direction, first) };
+}
+
+export function createMeshBuilder({ withColors = false } = {}) {
+ const positions = [];
+ const normals = [];
+ const uvs = [];
+ const colors = [];
+ const indices = [];
+ return {
+ get vertexCount() {
+ return positions.length / 3;
+ },
+ get triangleCount() {
+ return indices.length / 3;
+ },
+ addVertex(position, normal, u, v, color = [1, 1, 1]) {
+ positions.push(position[0], position[1], position[2]);
+ normals.push(normal[0], normal[1], normal[2]);
+ uvs.push(u, v);
+ if (withColors) colors.push(color[0], color[1], color[2]);
+ return positions.length / 3 - 1;
+ },
+ addTriangle(first, second, third) {
+ if (first === second || second === third || first === third) return;
+ indices.push(first, second, third);
+ },
+ build() {
+ const geometry = {
+ positions: new Float32Array(positions),
+ normals: new Float32Array(normals),
+ uvs: new Float32Array(uvs),
+ indices: new Uint32Array(indices),
+ };
+ if (withColors) geometry.colors = new Float32Array(colors);
+ return geometry;
+ },
+ };
+}
+
+/** Sweeps a tapered round tube along a polyline with parallel-transported rings. */
+export function addTube(builder, points, radii, sides, tileSize, color = [1, 1, 1]) {
+ const repeatAround = Math.max(1, Math.round(FULL_TURN * radii[0] / tileSize));
+ const firstVertex = builder.vertexCount;
+ const lastIndex = points.length - 1;
+ let frame = null;
+ let distance = 0;
+ points.forEach((point, index) => {
+ const tangent = normalized(subtractVectors(points[Math.min(index + 1, lastIndex)], points[Math.max(index - 1, 0)]));
+ frame = frame ? transportFrame(frame, tangent) : createFrame(tangent);
+ if (index > 0) distance += vectorLength(subtractVectors(point, points[index - 1]));
+ for (let side = 0; side <= sides; side++) {
+ const angle = side / sides * FULL_TURN;
+ const radial = addVectors(scaleVector(frame.first, Math.cos(angle)), scaleVector(frame.second, Math.sin(angle)));
+ builder.addVertex(addScaled(point, radial, radii[index]), radial, side / sides * repeatAround, distance / tileSize, color);
+ }
+ });
+ const ringSize = sides + 1;
+ for (let ring = 0; ring < lastIndex; ring++) {
+ for (let side = 0; side < sides; side++) {
+ const current = firstVertex + ring * ringSize + side;
+ const next = current + ringSize;
+ builder.addTriangle(current, current + 1, next);
+ builder.addTriangle(current + 1, next + 1, next);
+ }
+ }
+}
+
+function lobeNormal(forwardTilt, lateralTilt, normalAxis, forward, right) {
+ return normalized(addVectors(addVectors(normalAxis, scaleVector(forward, forwardTilt)), scaleVector(right, lateralTilt)));
+}
+
+/**
+ * Orthonormal frame for a leaf: `right` is horizontal so the face tilts toward the sky,
+ * `normal` is the face normal, and `roll` turns the leaf about its own axis.
+ */
+export function createLeafFrame(forward, roll) {
+ const horizontalRight = crossProduct(forward, WORLD_UP);
+ const right = vectorLength(horizontalRight) < 1e-4 ? createFrame(forward).first : normalized(horizontalRight);
+ const turned = addVectors(scaleVector(right, Math.cos(roll)), scaleVector(crossProduct(forward, right), Math.sin(roll)));
+ return { forward, right: turned, normal: crossProduct(turned, forward) };
+}
+
+/**
+ * Adds a curved leaf or card as rows of 2 or 3 columns, both faces, with shading
+ * normals blended toward the canopy so a flat quad lights like part of a rounded crown.
+ */
+export function addLeafSurface(builder, surface) {
+ const { origin, frame, length, width, rows, droop = 0, fold = 0, canopyNormal, canopyBlend = 0.5, colorBase, colorTip, brightness = 1 } = surface;
+ const columns = fold > 0 ? [-1, 0, 1] : [-1, 1];
+ const sides = surface.backFaces === false ? [1] : [1, -1];
+ const rowIndicesBySide = sides.map((side) => rows.map(([progress, widthFactor]) => {
+ const center = addScaled(addScaled(origin, frame.forward, length * progress), frame.normal, -droop * length * progress * progress);
+ const half = width / 2 * widthFactor;
+ const forwardTilt = 2 * droop * progress;
+ const color = colorBase ? lerpVectors(colorBase, colorTip ?? colorBase, progress).map(channel => channel * brightness) : [brightness, brightness, brightness];
+ const makeVertex = (column) => {
+ const lateralTilt = column * fold;
+ const faceNormal = scaleVector(lobeNormal(forwardTilt, lateralTilt, frame.normal, frame.forward, frame.right), side);
+ const shading = normalized(addVectors(scaleVector(faceNormal, 1 - canopyBlend), scaleVector(canopyNormal, canopyBlend)));
+ const lifted = column === 0 ? addScaled(center, frame.normal, fold * half) : center;
+ return builder.addVertex(addScaled(lifted, frame.right, column * half), shading, (column + 1) / 2, 1 - progress, color);
+ };
+ if (half <= 0) {
+ const shared = makeVertex(0);
+ return columns.map(() => shared);
+ }
+ return columns.map(makeVertex);
+ }));
+ rowIndicesBySide.forEach((rowIndices, sideIndex) => {
+ const front = sides[sideIndex] > 0;
+ for (let row = 0; row < rows.length - 1; row++) {
+ for (let column = 0; column < columns.length - 1; column++) {
+ const a = rowIndices[row][column];
+ const b = rowIndices[row][column + 1];
+ const c = rowIndices[row + 1][column];
+ const d = rowIndices[row + 1][column + 1];
+ if (front) {
+ builder.addTriangle(a, b, c);
+ builder.addTriangle(b, d, c);
+ } else {
+ builder.addTriangle(a, c, b);
+ builder.addTriangle(b, c, d);
+ }
+ }
+ }
+ });
+}
+
+export function triangleCountOf(geometry) {
+ return geometry.indices.length / 3;
+}
diff --git a/src/vegetation-species.js b/src/vegetation-species.js
new file mode 100644
index 00000000..ca3667e0
--- /dev/null
+++ b/src/vegetation-species.js
@@ -0,0 +1,132 @@
+// Species presets for the parametric branching model.
+//
+// Each entry in `levels` describes one branch generation. Level 0 is the trunk and its
+// `children` describe where the next generation sprouts: `start`/`end` are fractions along
+// the parent, `angle` is radians away from the parent's direction, `lengthRatio` is relative
+// to the parent's length and `profile` shapes the length along the parent ('crown' is
+// rounded, 'cone' shrinks toward the top). Lengths are meters; colors: bark `tint` and
+// `foliageColor` are linear RGB, leaf texture `color` is display RGB 0-255.
+
+const OVATE_LEAF = [[0, 0], [0.28, 0.85], [0.62, 0.95], [1, 0]];
+const NARROW_LEAF = [[0, 0], [0.3, 0.7], [0.65, 0.75], [1, 0]];
+const FIR_SPRAY = [[0, 0], [0.12, 0.55], [0.22, 0.4], [0.36, 0.85], [0.48, 0.6], [0.62, 1], [0.76, 0.7], [0.9, 0.5], [1, 0]];
+
+export const SPECIES = {
+ broadleaf: {
+ label: 'Broadleaf (oak-like)',
+ height: [8, 11],
+ trunkRadiusRatio: 0.03,
+ rootFlare: 1.45,
+ bark: { texture: 'rough', tint: [0.5, 0.4, 0.31] },
+ sides: [10, 7, 5, 4],
+ levels: [
+ { segments: 8, gnarl: 0.09, tropism: 0.02, tipRadius: 0.4, lean: 0.07, lengthScale: 0.66,
+ children: { count: [6, 8], start: 0.34, end: 0.97, angle: [0.7, 1.15], lengthRatio: [0.42, 0.58], radiusRatio: 0.52, profile: 'crown' } },
+ { segments: 5, gnarl: 0.16, tropism: 0.1, tipRadius: 0.35,
+ children: { count: [3, 4], start: 0.3, end: 0.95, angle: [0.55, 0.95], lengthRatio: [0.4, 0.6], radiusRatio: 0.55 } },
+ { segments: 3, gnarl: 0.2, tropism: 0.04, tipRadius: 0.4,
+ children: { count: [2, 4], start: 0.3, end: 1, angle: [0.5, 0.9], lengthRatio: [0.35, 0.55], radiusRatio: 0.6 } },
+ { segments: 2, gnarl: 0.25, tropism: -0.02, tipRadius: 0.3 },
+ ],
+ leaf: {
+ texture: 'sprig', color: [64, 110, 36], foliageColor: [0.085, 0.24, 0.04], tint: [1.05, 1, 0.85],
+ sitesPerMeter: 5, start: 0.2, upBias: 0.35,
+ meshLength: 0.62, meshWidth: 0.4, meshPerSite: 4, meshSpread: 0.75, profile: OVATE_LEAF, droop: 0.28, fold: 0.14,
+ cardSize: [1.05, 1.1], cardsPerSite: 2,
+ },
+ },
+ birch: {
+ label: 'Birch',
+ height: [9, 12],
+ trunkRadiusRatio: 0.018,
+ rootFlare: 1.35,
+ bark: { texture: 'birch', tint: [0.95, 0.94, 0.88] },
+ sides: [8, 6, 4, 4],
+ levels: [
+ { segments: 10, gnarl: 0.05, tropism: 0.02, tipRadius: 0.3, lean: 0.05, lengthScale: 0.84,
+ children: { count: [9, 12], start: 0.3, end: 0.98, angle: [0.42, 0.8], lengthRatio: [0.2, 0.34], radiusRatio: 0.38, profile: 'crown' } },
+ { segments: 5, gnarl: 0.12, tropism: 0.06, tipRadius: 0.35,
+ children: { count: [3, 4], start: 0.25, end: 0.95, angle: [0.5, 0.9], lengthRatio: [0.4, 0.55], radiusRatio: 0.55 } },
+ { segments: 3, gnarl: 0.14, tropism: -0.12, tipRadius: 0.4,
+ children: { count: [2, 4], start: 0.3, end: 1, angle: [0.5, 0.9], lengthRatio: [0.4, 0.55], radiusRatio: 0.6 } },
+ { segments: 3, gnarl: 0.16, tropism: -0.22, tipRadius: 0.3 },
+ ],
+ leaf: {
+ texture: 'sprig', color: [112, 150, 52], foliageColor: [0.2, 0.34, 0.06], tint: [1.05, 1.02, 0.85],
+ sitesPerMeter: 5, start: 0.15, upBias: 0.1,
+ meshLength: 0.42, meshWidth: 0.26, meshPerSite: 3, meshSpread: 0.8, profile: OVATE_LEAF, droop: 0.3, fold: 0.12,
+ cardSize: [0.8, 0.85], cardsPerSite: 2,
+ },
+ },
+ conifer: {
+ label: 'Conifer (spruce-like)',
+ height: [11, 15],
+ trunkRadiusRatio: 0.021,
+ rootFlare: 1.5,
+ bark: { texture: 'rough', tint: [0.38, 0.27, 0.2] },
+ sides: [10, 5, 4, 3],
+ levels: [
+ { segments: 12, gnarl: 0.015, tropism: 0.0, tipRadius: 0.06, lean: 0.02, lengthScale: 0.93,
+ children: { whorls: 13, perWhorl: [4, 6], start: 0.14, end: 0.98, angle: [1.3, 1.6], lengthRatio: [0.27, 0.33], radiusRatio: 0.34, profile: 'cone' } },
+ { segments: 5, gnarl: 0.05, tropism: -0.1, tipRadius: 0.3,
+ children: { count: [6, 8], start: 0.12, end: 0.95, angle: [0.95, 1.2], lengthRatio: [0.2, 0.3], radiusRatio: 0.5, profile: 'cone' } },
+ { segments: 2, gnarl: 0.05, tropism: -0.08, tipRadius: 0.4 },
+ ],
+ leaf: {
+ texture: 'needles', color: [34, 78, 52], foliageColor: [0.03, 0.12, 0.07], tint: [0.9, 1, 0.95],
+ sitesPerMeter: 3, start: 0.1, upBias: 0.15,
+ meshLength: 0.7, meshWidth: 0.36, meshPerSite: 1, meshSpread: 0, profile: FIR_SPRAY, droop: 0.18, fold: 0.1,
+ cardSize: [0.95, 0.95], cardsPerSite: 2,
+ },
+ },
+ palm: {
+ label: 'Palm',
+ height: [6, 9],
+ trunkRadiusRatio: 0.026,
+ rootFlare: 1.4,
+ bark: { texture: 'rough', tint: [0.46, 0.4, 0.33] },
+ sides: [10, 4, 3, 3],
+ levels: [
+ { segments: 12, gnarl: 0.015, tropism: 0.0, tipRadius: 0.62, lean: 0.14,
+ children: { count: [11, 14], start: 1, end: 1, angle: [0.2, 1.75], lengthRatio: [0.36, 0.46], radiusRatio: 0.1 } },
+ { segments: 8, gnarl: 0.015, tropism: -0.42, tipRadius: 0.3, pairedLeaves: true },
+ ],
+ leaf: {
+ texture: 'single', color: [70, 118, 40], foliageColor: [0.1, 0.27, 0.04], tint: [1.05, 1, 0.9],
+ sitesPerMeter: 7, start: 0.14, upBias: 0.0,
+ meshLength: 0.95, meshWidth: 0.16, meshPerSite: 1, meshSpread: 0, profile: NARROW_LEAF, droop: 0.35, fold: 0.1,
+ cardSize: [0.28, 1.1], cardsPerSite: 1,
+ },
+ },
+ bush: {
+ label: 'Bush',
+ height: [1.1, 1.9],
+ trunkRadiusRatio: 0.018,
+ rootFlare: 1.2,
+ bark: { texture: 'rough', tint: [0.4, 0.32, 0.25] },
+ sides: [5, 4, 3, 3],
+ levels: [
+ { segments: 3, gnarl: 0.05, tropism: 0.0, tipRadius: 0.8, lean: 0.0, lengthScale: 0.28,
+ children: { count: [7, 10], start: 0.5, end: 1, angle: [0.35, 0.85], lengthRatio: [2, 2.8], radiusRatio: 0.55 } },
+ { segments: 4, gnarl: 0.18, tropism: 0.1, tipRadius: 0.4,
+ children: { count: [3, 4], start: 0.3, end: 1, angle: [0.6, 1.0], lengthRatio: [0.35, 0.5], radiusRatio: 0.6 } },
+ { segments: 2, gnarl: 0.2, tropism: 0.02, tipRadius: 0.4,
+ children: { count: [2, 3], start: 0.3, end: 1, angle: [0.6, 1.0], lengthRatio: [0.45, 0.65], radiusRatio: 0.6 } },
+ { segments: 2, gnarl: 0.2, tropism: 0.0, tipRadius: 0.4 },
+ ],
+ leaf: {
+ texture: 'sprig', color: [54, 104, 40], foliageColor: [0.06, 0.2, 0.045], tint: [1, 1, 0.9],
+ sitesPerMeter: 9, start: 0.1, upBias: 0.3,
+ meshLength: 0.22, meshWidth: 0.14, meshPerSite: 3, meshSpread: 0.9, profile: OVATE_LEAF, droop: 0.25, fold: 0.12,
+ cardSize: [0.4, 0.42], cardsPerSite: 2,
+ },
+ },
+};
+
+/** Level of detail: sides and leaf density multipliers per level, and default switch distances in meters. */
+export const LEVEL_SETTINGS = [
+ { sideScale: 1, leafKeep: 1, leafScale: 1, maximumBranchLevel: Infinity },
+ { sideScale: 0.6, leafKeep: 0.34, leafScale: 1.7, maximumBranchLevel: -1 },
+ { sideScale: 0.4, leafKeep: 0, leafScale: 1, maximumBranchLevel: 1 },
+];
+export const TREE_LEVEL_DISTANCES = [38, 95];
diff --git a/src/vegetation-textures.js b/src/vegetation-textures.js
new file mode 100644
index 00000000..eb7223e9
--- /dev/null
+++ b/src/vegetation-textures.js
@@ -0,0 +1,202 @@
+// Procedural RGBA textures for vegetation: leaf sprigs with alpha, bark and grass cards.
+// Pixel arrays are built in plain JavaScript so tests and Node tools can use them without a canvas.
+
+import { FULL_TURN, clamp, createRandom, valueNoise } from './vegetation-geometry.js';
+
+const TEXTURE_SIZE = 128;
+const descriptorCache = new Map();
+
+function createPixels(fillColor) {
+ const data = new Uint8ClampedArray(TEXTURE_SIZE * TEXTURE_SIZE * 4);
+ for (let offset = 0; offset < data.length; offset += 4) {
+ data[offset] = fillColor[0];
+ data[offset + 1] = fillColor[1];
+ data[offset + 2] = fillColor[2];
+ data[offset + 3] = 0;
+ }
+ return { width: TEXTURE_SIZE, height: TEXTURE_SIZE, data };
+}
+
+function compositePixel(pixels, x, y, color, coverage) {
+ const offset = (y * pixels.width + x) * 4;
+ const existingAlpha = pixels.data[offset + 3] / 255;
+ const outputAlpha = coverage + existingAlpha * (1 - coverage);
+ if (outputAlpha <= 0) return;
+ for (let channel = 0; channel < 3; channel++) {
+ const mixed = (color[channel] * coverage + pixels.data[offset + channel] * existingAlpha * (1 - coverage)) / outputAlpha;
+ pixels.data[offset + channel] = mixed;
+ }
+ pixels.data[offset + 3] = outputAlpha * 255;
+}
+
+// Angle zero points up the image; the leaf grows from (baseX, baseY) along that axis.
+function paintLeaf(pixels, { baseX, baseY, angle, length, width, color, shade }) {
+ const axisX = Math.sin(angle);
+ const axisY = -Math.cos(angle);
+ const sideX = -axisY;
+ const sideY = axisX;
+ const reach = Math.ceil(length + width);
+ const minimumY = Math.max(0, Math.floor(baseY - reach));
+ const maximumY = Math.min(pixels.height - 1, Math.ceil(baseY + reach));
+ const minimumX = Math.max(0, Math.floor(baseX - reach));
+ const maximumX = Math.min(pixels.width - 1, Math.ceil(baseX + reach));
+ for (let y = minimumY; y <= maximumY; y++) {
+ for (let x = minimumX; x <= maximumX; x++) {
+ const offsetX = x + 0.5 - baseX;
+ const offsetY = y + 0.5 - baseY;
+ const along = (offsetX * axisX + offsetY * axisY) / length;
+ if (along < 0 || along > 1) continue;
+ const across = offsetX * sideX + offsetY * sideY;
+ const halfWidth = width / 2 * Math.sin(Math.PI * along ** 0.7);
+ const coverage = clamp(halfWidth - Math.abs(across) + 0.5, 0, 1);
+ if (coverage <= 0) continue;
+ const sideDistance = Math.abs(across) / (halfWidth + 1e-3);
+ const midrib = Math.abs(across) < 0.7 ? 0.2 : 0;
+ const vein = (along * 7 + sideDistance * 0.9) % 1 < 0.1 ? -0.1 : 0;
+ const brightness = shade * (0.82 + 0.3 * (1 - sideDistance) + midrib + vein);
+ compositePixel(pixels, x, y, color.map(channel => channel * brightness), coverage);
+ }
+ }
+}
+
+function paintStem(pixels, fromX, fromY, toX, toY, color) {
+ const steps = Math.ceil(Math.hypot(toX - fromX, toY - fromY) * 2);
+ for (let step = 0; step <= steps; step++) {
+ const progress = step / steps;
+ const x = Math.round(fromX + (toX - fromX) * progress);
+ const y = Math.round(fromY + (toY - fromY) * progress);
+ for (let spread = 0; spread < 2; spread++) {
+ if (x + spread < pixels.width) compositePixel(pixels, x + spread, y, color, 1);
+ }
+ }
+}
+
+function paintSprig(pixels, color, random) {
+ const stemColor = [color[0] * 0.55, color[1] * 0.5, color[2] * 0.4];
+ paintStem(pixels, 64, 126, 64, 30, stemColor);
+ for (let pair = 0; pair < 6; pair++) {
+ const baseY = 106 - pair * 13;
+ const length = 22 + 10 * Math.sin((pair + 1) / 6 * Math.PI);
+ for (const side of [-1, 1]) {
+ const angle = side * (1.0 + random() * 0.3);
+ paintLeaf(pixels, { baseX: 64, baseY: baseY - (side > 0 ? 6 : 0), angle, length, width: length * 0.55, color, shade: 0.85 + random() * 0.3 });
+ }
+ }
+ paintLeaf(pixels, { baseX: 64, baseY: 44, angle: 0, length: 40, width: 25, color, shade: 1.05 });
+}
+
+function paintNeedleSpray(pixels, color, random) {
+ const stemColor = [color[0] * 0.7, color[1] * 0.6, color[2] * 0.5];
+ paintStem(pixels, 64, 126, 64, 6, stemColor);
+ for (let step = 0; step < 24; step++) {
+ const baseY = 118 - step * 4.6;
+ const length = 30 - step * 0.45 + random() * 4;
+ for (const side of [-1, 1]) {
+ paintLeaf(pixels, { baseX: 64, baseY, angle: side * (1.0 + random() * 0.2), length, width: 3.4, color, shade: 0.85 + random() * 0.3 });
+ }
+ }
+}
+
+function paintBlades(pixels, color, random, count, width) {
+ for (let blade = 0; blade < count; blade++) {
+ const spread = count > 1 ? (blade / (count - 1) - 0.5) * 0.9 : 0;
+ const length = 96 + random() * 28;
+ paintLeaf(pixels, { baseX: 64 + spread * 40, baseY: 127, angle: spread + (random() - 0.5) * 0.12, length, width, color, shade: 0.8 + random() * 0.4 });
+ }
+}
+
+function paintClump(pixels, color, random) {
+ for (let leaf = 0; leaf < 150; leaf++) {
+ const angle = random() * FULL_TURN;
+ const radius = Math.sqrt(random()) * 46;
+ paintLeaf(pixels, {
+ baseX: 64 + Math.cos(angle) * radius,
+ baseY: 64 + Math.sin(angle) * radius * 0.8,
+ angle: random() * FULL_TURN,
+ length: 24 + random() * 12,
+ width: 16 + random() * 8,
+ color,
+ shade: 0.6 + random() * 0.6,
+ });
+ }
+}
+
+function bleedColorIntoTransparentPixels(pixels, color) {
+ for (let offset = 0; offset < pixels.data.length; offset += 4) {
+ if (pixels.data[offset + 3] > 0) continue;
+ pixels.data[offset] = color[0] * 0.8;
+ pixels.data[offset + 1] = color[1] * 0.8;
+ pixels.data[offset + 2] = color[2] * 0.8;
+ }
+}
+
+const LEAF_PAINTERS = {
+ sprig: paintSprig,
+ needles: paintNeedleSpray,
+ single: (pixels, color, random) => paintBlades(pixels, color, random, 1, 38),
+ grass: (pixels, color, random) => paintBlades(pixels, color, random, 9, 7),
+ clump: paintClump,
+};
+
+/** RGBA leaf texture: the stem base sits at the bottom edge, transparent elsewhere. */
+export function createLeafPixels(kind, color, seed = 1) {
+ const painter = LEAF_PAINTERS[kind];
+ if (!painter) throw new RangeError(`Unknown leaf texture kind: ${kind}`);
+ const pixels = createPixels(color);
+ painter(pixels, color, createRandom(seed));
+ bleedColorIntoTransparentPixels(pixels, color);
+ return pixels;
+}
+
+const BARK_STYLES = {
+ rough: { base: [168, 142, 118], crevice: 0.28, stretch: 2 },
+ birch: { base: [238, 235, 224], crevice: 0.12, stretch: 2 },
+};
+
+/** Opaque, tileable bark luminance texture with vertical furrows (rough) or dark lenticels (birch). */
+export function createBarkPixels(kind, seed = 1) {
+ const style = BARK_STYLES[kind];
+ if (!style) throw new RangeError(`Unknown bark texture kind: ${kind}`);
+ const pixels = createPixels(style.base);
+ for (let y = 0; y < TEXTURE_SIZE; y++) {
+ for (let x = 0; x < TEXTURE_SIZE; x++) {
+ const unitX = x / TEXTURE_SIZE;
+ const unitY = y / TEXTURE_SIZE;
+ const furrow = valueNoise(unitX * 8, unitY * style.stretch, seed, 8, style.stretch);
+ const fine = valueNoise(unitX * 24, unitY * 12, seed + 5, 24, 12);
+ let brightness = 1 - style.crevice + style.crevice * (0.65 * furrow + 0.35 * fine) * 1.6;
+ if (kind === 'birch') {
+ const mark = valueNoise(unitX * 6, unitY * 40, seed + 9, 6, 40);
+ if (mark > 0.7) brightness *= 0.28 + (1 - mark) * 1.6;
+ } else {
+ brightness *= 0.55 + 0.9 * furrow ** 1.4;
+ }
+ const offset = (y * TEXTURE_SIZE + x) * 4;
+ for (let channel = 0; channel < 3; channel++) pixels.data[offset + channel] = clamp(style.base[channel] * brightness, 0, 255);
+ pixels.data[offset + 3] = 255;
+ }
+ }
+ return pixels;
+}
+
+/**
+ * Texture descriptor for `material.map`. Descriptors are cached per key so every tree of
+ * a species shares one GPU texture. In the browser the pixels become an ImageData.
+ */
+export function createTextureDescriptor(cacheKey, createPixelsForKey, { repeat }) {
+ if (descriptorCache.has(cacheKey)) return descriptorCache.get(cacheKey);
+ const pixels = createPixelsForKey();
+ const image = typeof ImageData === 'undefined' ? pixels : new ImageData(pixels.data, pixels.width, pixels.height);
+ const wrap = repeat ? 10497 : 33071;
+ const descriptor = { image, colorSpace: 'srgb', wrapS: wrap, wrapT: wrap, minFilter: 9987, magFilter: 9729 };
+ descriptorCache.set(cacheKey, descriptor);
+ return descriptor;
+}
+
+export function leafTextureDescriptor(kind, color) {
+ return createTextureDescriptor(`leaf:${kind}:${color.join(',')}`, () => createLeafPixels(kind, color), { repeat: false });
+}
+
+export function barkTextureDescriptor(kind) {
+ return createTextureDescriptor(`bark:${kind}`, () => createBarkPixels(kind), { repeat: true });
+}
diff --git a/src/vegetation.js b/src/vegetation.js
new file mode 100644
index 00000000..f9c5bb38
--- /dev/null
+++ b/src/vegetation.js
@@ -0,0 +1,635 @@
+// Procedural vegetation for 67.js: branching trees, bushes, grass, Poisson-disk scattering
+// on terrain and distance level of detail.
+//
+// Trees use a parametric recursive branching model (not space colonization): every branch
+// generation is a handful of numbers per species, so a species is a small readable preset,
+// the same seed always grows the same tree, and branch count and triangle cost are known
+// before growing. Space colonization needs attractor clouds and many iterations for the
+// same silhouette and is harder to budget.
+
+import { mat4, quat } from 'gl-matrix';
+import {
+ FULL_TURN, WORLD_UP, addLeafSurface, addScaled, addTube, addVectors, clamp, createFrame, createLeafFrame,
+ createMeshBuilder, createRandom, crossProduct, lerp, lerpVectors, normalized, randomInRange, scaleVector,
+ subtractVectors, valueNoise, vectorLength,
+} from './vegetation-geometry.js';
+import { LEVEL_SETTINGS, SPECIES, TREE_LEVEL_DISTANCES } from './vegetation-species.js';
+import { barkTextureDescriptor, leafTextureDescriptor } from './vegetation-textures.js';
+
+export { SPECIES };
+
+const BARK_TILE_SIZE = 0.6;
+const LEAF_MODES = ['cards', 'mesh'];
+const GRASS_LEVEL_DISTANCES = [24];
+const LEAF_COLOR_BASE = [0.85, 0.95, 0.8];
+const LEAF_COLOR_TIP = [1.1, 1.05, 0.9];
+const DEFAULT_MIX = { broadleaf: 3, birch: 1.5, conifer: 2, bush: 2.5 };
+
+function rotateAroundUp(vector, angle) {
+ const cosine = Math.cos(angle);
+ const sine = Math.sin(angle);
+ return [vector[0] * cosine + vector[2] * sine, vector[1], -vector[0] * sine + vector[2] * cosine];
+}
+
+function randomUnitOffset(random) {
+ return [random() - 0.5, random() - 0.5, random() - 0.5];
+}
+
+function sampleBranch(branch, fraction) {
+ const { points, radii } = branch;
+ const scaled = clamp(fraction, 0, 1) * (points.length - 1);
+ const index = Math.min(Math.floor(scaled), points.length - 2);
+ const local = scaled - index;
+ return {
+ position: lerpVectors(points[index], points[index + 1], local),
+ direction: normalized(subtractVectors(points[index + 1], points[index])),
+ radius: lerp(radii[index], radii[index + 1], local),
+ };
+}
+
+function lengthProfile(profile, progress) {
+ if (profile === 'crown') return 0.62 + 0.38 * Math.sin(Math.PI * clamp(progress * 0.85 + 0.1, 0, 1));
+ if (profile === 'cone') return 1 - 0.9 * progress;
+ return 1;
+}
+
+function createChildSlots(spec, random) {
+ const slots = [];
+ if (spec.whorls) {
+ for (let whorl = 0; whorl < spec.whorls; whorl++) {
+ const fraction = lerp(spec.start, spec.end, spec.whorls > 1 ? whorl / (spec.whorls - 1) : 0);
+ const count = Math.round(randomInRange(random, spec.perWhorl));
+ for (let member = 0; member < count; member++) {
+ slots.push({ fraction, azimuth: member / count * FULL_TURN + whorl * 0.9 + (random() - 0.5) * 0.5 });
+ }
+ }
+ return slots;
+ }
+ const count = Math.round(randomInRange(random, spec.count));
+ for (let index = 0; index < count; index++) {
+ slots.push({ fraction: lerp(spec.start, spec.end, (index + random() * 0.5) / count), azimuth: index * 2.399963 + random() * 0.5 });
+ }
+ return slots;
+}
+
+function growSkeleton(preset, height, random) {
+ const lastLevel = preset.levels.length - 1;
+ const branches = [];
+ const leafSites = [];
+
+ function addLeafSites(branch) {
+ const spec = preset.leaf;
+ const paired = preset.levels[branch.level].pairedLeaves;
+ const count = Math.max(2, Math.round(branch.length * spec.sitesPerMeter));
+ for (let index = 0; index < count; index++) {
+ const sample = sampleBranch(branch, lerp(spec.start, 1, index / (count - 1)));
+ const sideAxis = normalized(crossProduct(sample.direction, WORLD_UP));
+ const directions = paired
+ ? [-1, 1].map(side => normalized(addVectors(scaleVector(sample.direction, 0.5), scaleVector(sideAxis, 0.85 * side))))
+ : [normalized(addVectors(addVectors(sample.direction, scaleVector(WORLD_UP, spec.upBias)), scaleVector(randomUnitOffset(random), 0.9)))];
+ for (const direction of directions) {
+ leafSites.push({ position: sample.position, direction, scale: 0.8 + random() * 0.45, roll: (random() - 0.5) * 0.8 });
+ }
+ }
+ }
+
+ function spawnChildren(branch, spec) {
+ for (const slot of createChildSlots(spec, random)) {
+ const sample = sampleBranch(branch, slot.fraction);
+ const frame = createFrame(sample.direction);
+ const axis = addVectors(scaleVector(frame.first, Math.cos(slot.azimuth)), scaleVector(frame.second, Math.sin(slot.azimuth)));
+ const angle = randomInRange(random, spec.angle);
+ const direction = normalized(addVectors(scaleVector(sample.direction, Math.cos(angle)), scaleVector(axis, Math.sin(angle))));
+ const progress = (slot.fraction - spec.start) / Math.max(spec.end - spec.start, 1e-6);
+ growBranch({
+ origin: sample.position,
+ direction,
+ length: branch.length * randomInRange(random, spec.lengthRatio) * lengthProfile(spec.profile, progress),
+ radius: sample.radius * spec.radiusRatio,
+ level: branch.level + 1,
+ });
+ }
+ }
+
+ function growBranch({ origin, direction, length, radius, level }) {
+ const parameters = preset.levels[level];
+ const points = [origin];
+ const radii = [radius];
+ const stepLength = length / parameters.segments;
+ let current = direction;
+ for (let step = 1; step <= parameters.segments; step++) {
+ const wander = scaleVector(randomUnitOffset(random), parameters.gnarl * 2);
+ current = normalized(addVectors(addVectors(current, wander), [0, parameters.tropism, 0]));
+ points.push(addScaled(points[step - 1], current, stepLength));
+ radii.push(radius * lerp(1, parameters.tipRadius, step / parameters.segments));
+ }
+ const branch = { level, points, radii, length };
+ branches.push(branch);
+ if (parameters.children) spawnChildren(branch, parameters.children);
+ if (level === lastLevel) addLeafSites(branch);
+ }
+
+ const trunkSettings = preset.levels[0];
+ const leanAngle = random() * FULL_TURN;
+ const lean = trunkSettings.lean ?? 0;
+ growBranch({
+ origin: [0, 0, 0],
+ direction: normalized([Math.cos(leanAngle) * lean, 1, Math.sin(leanAngle) * lean]),
+ length: height * (trunkSettings.lengthScale ?? 1),
+ radius: height * preset.trunkRadiusRatio,
+ level: 0,
+ });
+ return { branches, leafSites, crown: describeCrown(leafSites) };
+}
+
+function describeCrown(leafSites) {
+ const center = scaleVector(leafSites.reduce((sum, site) => addVectors(sum, site.position), [0, 0, 0]), 1 / leafSites.length);
+ const radius = Math.max(...leafSites.map(site => vectorLength(subtractVectors(site.position, center))), 0.1);
+ return { center, radius };
+}
+
+function buildBark(skeleton, preset, setting) {
+ const lastLevel = preset.levels.length - 1;
+ const maximumLevel = setting.maximumBranchLevel < 0 ? lastLevel + setting.maximumBranchLevel : setting.maximumBranchLevel;
+ const builder = createMeshBuilder();
+ for (const branch of skeleton.branches) {
+ if (branch.level > maximumLevel) continue;
+ const baseSides = preset.sides[Math.min(branch.level, preset.sides.length - 1)];
+ const sides = Math.max(3, Math.round(baseSides * setting.sideScale));
+ let { points, radii } = branch;
+ if (branch.level === 0) {
+ const direction = normalized(subtractVectors(points[1], points[0]));
+ points = [addScaled(points[0], direction, -0.3), ...points];
+ radii = [radii[0] * preset.rootFlare, ...radii];
+ }
+ addTube(builder, points, radii, sides, BARK_TILE_SIZE);
+ }
+ return builder.build();
+}
+
+function crownShading(skeleton, position) {
+ const { center, radius } = skeleton.crown;
+ const offset = subtractVectors(position, center);
+ const distanceFraction = clamp(vectorLength(offset) / radius, 0, 1);
+ const heightFraction = clamp(offset[1] / radius * 0.5 + 0.5, 0, 1);
+ return {
+ brightness: lerp(0.55, 1.1, distanceFraction ** 0.8) + 0.12 * heightFraction,
+ canopyNormal: normalized(addVectors(normalized(offset), scaleVector(WORLD_UP, 0.35))),
+ };
+}
+
+function addMeshLeaves(builder, skeleton, spec, site, scale, random) {
+ const { brightness, canopyNormal } = crownShading(skeleton, site.position);
+ for (let index = 0; index < spec.meshPerSite; index++) {
+ const yaw = (index - (spec.meshPerSite - 1) / 2) * spec.meshSpread;
+ const direction = normalized(addScaled(rotateAroundUp(site.direction, yaw), WORLD_UP, (random() - 0.5) * 0.5));
+ const length = spec.meshLength * site.scale * scale;
+ addLeafSurface(builder, {
+ origin: site.position,
+ frame: createLeafFrame(direction, site.roll + (random() - 0.5) * 0.6),
+ length,
+ width: spec.meshWidth * site.scale * scale,
+ rows: spec.profile,
+ droop: spec.droop,
+ fold: spec.fold,
+ canopyNormal,
+ canopyBlend: 0.45,
+ colorBase: LEAF_COLOR_BASE,
+ colorTip: LEAF_COLOR_TIP,
+ brightness: brightness * (0.9 + random() * 0.2),
+ });
+ }
+}
+
+function addCards(builder, skeleton, spec, site, scale, random) {
+ const { brightness, canopyNormal } = crownShading(skeleton, site.position);
+ const firstRoll = (random() - 0.5) * 0.6;
+ for (let index = 0; index < spec.cardsPerSite; index++) {
+ addLeafSurface(builder, {
+ origin: site.position,
+ frame: createLeafFrame(site.direction, firstRoll + index * (Math.PI / 2 + (random() - 0.5) * 0.5)),
+ length: spec.cardSize[1] * site.scale * scale,
+ width: spec.cardSize[0] * site.scale * scale,
+ rows: [[0, 1], [0.5, 1], [1, 1]],
+ droop: 0.12,
+ canopyNormal,
+ canopyBlend: 0.55,
+ colorBase: LEAF_COLOR_BASE,
+ colorTip: LEAF_COLOR_TIP,
+ brightness: brightness * (0.9 + random() * 0.2),
+ });
+ }
+}
+
+function addBlob(builder, center, radius, shading) {
+ const segments = 8;
+ const rings = 5;
+ const firstVertex = builder.vertexCount;
+ for (let ring = 0; ring <= rings; ring++) {
+ const polar = ring / rings * Math.PI;
+ for (let segment = 0; segment <= segments; segment++) {
+ const azimuth = (segment % segments) / segments * FULL_TURN;
+ const direction = [Math.sin(polar) * Math.cos(azimuth), Math.cos(polar), Math.sin(polar) * Math.sin(azimuth)];
+ const jitter = 1 + (valueNoise(direction[0] * 2 + center[0], direction[2] * 2 + center[2], 3) - 0.5) * 0.5;
+ const position = [center[0] + direction[0] * radius * jitter, center[1] + direction[1] * radius * 0.8 * jitter, center[2] + direction[2] * radius * jitter];
+ const color = LEAF_COLOR_BASE.map(channel => channel * shading.brightness);
+ builder.addVertex(position, direction, segment / segments, ring / rings, color);
+ }
+ }
+ const ringSize = segments + 1;
+ for (let ring = 0; ring < rings; ring++) {
+ for (let segment = 0; segment < segments; segment++) {
+ const current = firstVertex + ring * ringSize + segment;
+ builder.addTriangle(current, current + 1, current + ringSize);
+ builder.addTriangle(current + ringSize, current + 1, current + ringSize + 1);
+ }
+ }
+}
+
+function addCrownClumps(builder, skeleton, spec, mode, random) {
+ const cellSize = skeleton.crown.radius / 2.1;
+ const cells = new Map();
+ for (const site of skeleton.leafSites) {
+ const key = site.position.map(value => Math.floor(value / cellSize)).join(',');
+ if (!cells.has(key)) cells.set(key, []);
+ cells.get(key).push(site);
+ }
+ for (const sites of cells.values()) {
+ const center = scaleVector(sites.reduce((sum, site) => addVectors(sum, site.position), [0, 0, 0]), 1 / sites.length);
+ const shading = crownShading(skeleton, center);
+ const radius = cellSize * (0.55 + 0.1 * Math.min(sites.length, 5));
+ if (mode === 'mesh') {
+ addBlob(builder, center, radius, shading);
+ continue;
+ }
+ for (let card = 0; card < 3; card++) {
+ const direction = card === 2 ? WORLD_UP : [Math.cos(card * 1.9 + center[0]), 0.15, Math.sin(card * 1.9 + center[2])];
+ addLeafSurface(builder, {
+ origin: addScaled(center, normalized(direction), -radius),
+ frame: createLeafFrame(normalized(direction), 0),
+ length: radius * 2,
+ width: radius * 2,
+ rows: [[0, 1], [1, 1]],
+ canopyNormal: shading.canopyNormal,
+ canopyBlend: 0.7,
+ colorBase: LEAF_COLOR_BASE,
+ colorTip: LEAF_COLOR_TIP,
+ brightness: shading.brightness,
+ });
+ }
+ }
+}
+
+function buildFoliage(skeleton, preset, mode, levelIndex, random) {
+ const setting = LEVEL_SETTINGS[levelIndex];
+ const builder = createMeshBuilder({ withColors: true });
+ if (setting.leafKeep === 0) {
+ addCrownClumps(builder, skeleton, preset.leaf, mode, random);
+ return builder.build();
+ }
+ const stride = Math.round(1 / setting.leafKeep);
+ skeleton.leafSites.forEach((site, index) => {
+ if (index % stride !== 0) return;
+ if (mode === 'mesh') addMeshLeaves(builder, skeleton, preset.leaf, site, setting.leafScale, random);
+ else addCards(builder, skeleton, preset.leaf, site, setting.leafScale, random);
+ });
+ return builder.build();
+}
+
+function createMaterials(preset, mode) {
+ const bark = { color: preset.bark.tint, roughness: 0.95, metallic: 0, emission: 0, map: barkTextureDescriptor(preset.bark.texture) };
+ if (mode === 'mesh') {
+ const foliage = { tag: 'foliage', color: preset.leaf.foliageColor, roughness: 0.8, metallic: 0, emission: 0 };
+ return { bark, foliage, crown: foliage };
+ }
+ const cardMaterial = (texture) => ({
+ color: preset.leaf.tint, roughness: 0.85, metallic: 0, emission: 0,
+ map: leafTextureDescriptor(texture, preset.leaf.color), alphaMode: 'mask', alphaCutoff: 0.5, doubleSided: true,
+ });
+ return { bark, foliage: cardMaterial(preset.leaf.texture), crown: cardMaterial('clump') };
+}
+
+function boundsOf(geometries) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (const geometry of geometries) {
+ for (let offset = 0; offset < geometry.positions.length; offset++) {
+ const axis = offset % 3;
+ minimum[axis] = Math.min(minimum[axis], geometry.positions[offset]);
+ maximum[axis] = Math.max(maximum[axis], geometry.positions[offset]);
+ }
+ }
+ return { minimum, maximum };
+}
+
+function describeLevel(parts) {
+ return { parts, triangles: parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0) };
+}
+
+/**
+ * Grows one tree. `speciesOrOptions` is a preset name ('broadleaf', 'birch', 'conifer', 'palm',
+ * 'bush') or `{ species, height, leaves }`. Returns three levels of detail; each level lists the
+ * parts (`bark`, `foliage`) with their geometry and material, in local meters with the trunk at the origin.
+ */
+export function createTree(speciesOrOptions = 'broadleaf', seed = 1) {
+ const options = typeof speciesOrOptions === 'string' ? { species: speciesOrOptions } : { ...speciesOrOptions };
+ const preset = SPECIES[options.species];
+ if (!preset) throw new RangeError(`Unknown tree species: ${options.species}`);
+ const leaves = options.leaves ?? 'cards';
+ if (!LEAF_MODES.includes(leaves)) throw new RangeError(`Leaves must be one of ${LEAF_MODES.join(', ')}.`);
+ if (!Number.isFinite(seed)) throw new TypeError('Tree seed must be a finite number.');
+ const random = createRandom(seed * 7919 + 17);
+ const height = options.height ?? randomInRange(random, preset.height);
+ const skeleton = growSkeleton(preset, height, random);
+ const materials = createMaterials(preset, leaves);
+ const levels = LEVEL_SETTINGS.map((setting, levelIndex) => {
+ const levelRandom = createRandom(seed * 104729 + levelIndex);
+ const foliageMaterial = setting.leafKeep === 0 ? materials.crown : materials.foliage;
+ return describeLevel([
+ { role: 'bark', geometry: buildBark(skeleton, preset, setting), material: materials.bark, tintable: false },
+ { role: 'foliage', geometry: buildFoliage(skeleton, preset, leaves, levelIndex, levelRandom), material: foliageMaterial, tintable: true },
+ ]);
+ });
+ return {
+ kind: 'tree', species: options.species, seed, height, leaves, levels, materials,
+ distances: TREE_LEVEL_DISTANCES,
+ bounds: boundsOf(levels[0].parts.map(part => part.geometry)),
+ };
+}
+
+function grassMaterial(style, color) {
+ if (style === 'cards') {
+ return { color: [1, 1, 1], roughness: 0.9, metallic: 0, emission: 0, map: leafTextureDescriptor('grass', [80, 128, 40]), alphaMode: 'mask', alphaCutoff: 0.5, doubleSided: true };
+ }
+ return { tag: 'grass', color, roughness: 0.9, metallic: 0, emission: 0 };
+}
+
+function buildGrassBlades(random, blades, height, radius, widthScale) {
+ const builder = createMeshBuilder({ withColors: true });
+ for (let blade = 0; blade < blades; blade++) {
+ const azimuth = random() * FULL_TURN;
+ const distance = Math.sqrt(random()) * radius;
+ const lean = 0.2 + random() * 0.4;
+ addLeafSurface(builder, {
+ origin: [Math.cos(azimuth) * distance, 0, Math.sin(azimuth) * distance],
+ frame: createLeafFrame(normalized([Math.cos(azimuth) * lean, 1, Math.sin(azimuth) * lean]), random() * FULL_TURN),
+ length: height * (0.6 + random() * 0.6),
+ width: 0.04 * widthScale * (0.8 + random() * 0.5),
+ rows: [[0, 1], [0.35, 0.85], [0.7, 0.5], [1, 0]],
+ droop: 0.3 + random() * 0.4,
+ canopyNormal: WORLD_UP,
+ canopyBlend: 0.55,
+ colorBase: [0.5, 0.58, 0.45],
+ colorTip: [1.15, 1.15, 0.9],
+ });
+ }
+ return builder.build();
+}
+
+function buildGrassCards(random, height, radius) {
+ const builder = createMeshBuilder({ withColors: true });
+ const startAngle = random() * Math.PI;
+ for (let card = 0; card < 3; card++) {
+ const angle = startAngle + card * Math.PI / 3;
+ const right = [Math.cos(angle), 0, Math.sin(angle)];
+ addLeafSurface(builder, {
+ origin: [0, 0, 0],
+ frame: { forward: WORLD_UP, right, normal: crossProduct(right, WORLD_UP) },
+ length: height * (0.9 + random() * 0.2),
+ width: radius * 2.4,
+ rows: [[0, 1], [0.5, 1], [1, 1]],
+ droop: 0.1,
+ canopyNormal: WORLD_UP,
+ canopyBlend: 0.6,
+ colorBase: [0.6, 0.65, 0.55],
+ colorTip: [1.1, 1.1, 0.95],
+ });
+ }
+ return builder.build();
+}
+
+/**
+ * A tuft of grass. `style: 'blades'` (default) is real curved blade geometry with the swaying `grass` tag;
+ * `'cards'` is three crossed alpha-masked cards. Level 1 has half the blades, wider.
+ */
+export function createGrassClump({ blades = 16, height = 0.45, radius = 0.13, style = 'blades', color = [0.2, 0.34, 0.06], seed = 1 } = {}) {
+ if (!['blades', 'cards'].includes(style)) throw new RangeError('Grass style must be blades or cards.');
+ const random = createRandom(seed * 6271 + 5);
+ const material = grassMaterial(style, color);
+ const geometries = style === 'cards'
+ ? [buildGrassCards(random, height, radius), buildGrassCards(random, height, radius)]
+ : [buildGrassBlades(random, blades, height, radius, 1), buildGrassBlades(random, Math.max(3, Math.round(blades / 2)), height, radius, 1.7)];
+ const levels = geometries.map(geometry => describeLevel([{ role: 'grass', geometry, material, tintable: true }]));
+ return { kind: 'grass', species: 'grass', seed, height, levels, materials: { grass: material }, distances: GRASS_LEVEL_DISTANCES, bounds: boundsOf(geometries) };
+}
+
+function buildFlowerPatch(random, flowers, height, petalColor) {
+ const builder = createMeshBuilder({ withColors: true });
+ const stemColor = [0.16, 0.3, 0.07];
+ for (let flower = 0; flower < flowers; flower++) {
+ const azimuth = random() * FULL_TURN;
+ const distance = Math.sqrt(random()) * 0.14;
+ const base = [Math.cos(azimuth) * distance, 0, Math.sin(azimuth) * distance];
+ const stemHeight = height * (0.7 + random() * 0.5);
+ const lean = [(random() - 0.5) * 0.12, 0, (random() - 0.5) * 0.12];
+ const top = addVectors(addVectors(base, [0, stemHeight, 0]), lean);
+ const middle = addVectors(lerpVectors(base, top, 0.5), scaleVector(lean, 0.6));
+ addTube(builder, [base, middle, top], [0.005, 0.0045, 0.004], 3, 0.3, stemColor);
+ const petals = 6;
+ for (let petal = 0; petal < petals; petal++) {
+ const angle = petal / petals * FULL_TURN;
+ const forward = normalized([Math.cos(angle), 0.3, Math.sin(angle)]);
+ addLeafSurface(builder, {
+ origin: top, frame: createLeafFrame(forward, 0), length: 0.055, width: 0.04,
+ rows: [[0, 0.5], [0.5, 1], [1, 0.5]], canopyNormal: WORLD_UP, canopyBlend: 0.5, colorBase: petalColor, colorTip: petalColor,
+ });
+ }
+ addBlob(builder, addScaled(top, WORLD_UP, 0.004), 0.014, { brightness: 1 });
+ }
+ return builder.build();
+}
+
+/** A patch of small flowers on thin stems; color lives in vertex colors, so one material serves every hue. */
+export function createFlowerPatch({ flowers = 5, height = 0.4, color = [1, 0.85, 0.3], seed = 1 } = {}) {
+ const random = createRandom(seed * 3571 + 11);
+ const geometry = buildFlowerPatch(random, flowers, height, color);
+ const material = { color: [1, 1, 1], roughness: 0.8, metallic: 0, emission: 0 };
+ return { kind: 'flowers', species: 'flowers', seed, height, levels: [describeLevel([{ role: 'flowers', geometry, material, tintable: false }])], materials: { flowers: material }, distances: [], bounds: boundsOf([geometry]) };
+}
+
+const FLOWER_COLORS = [[0.95, 0.8, 0.25], [0.8, 0.35, 0.55], [0.9, 0.9, 0.85], [0.45, 0.4, 0.85]];
+
+function createVariant(species, variantSeed, variantIndex, leaves) {
+ if (species === 'grass') return createGrassClump({ seed: variantSeed, height: 0.38 + 0.12 * (variantIndex % 3) });
+ if (species === 'flowers') return createFlowerPatch({ seed: variantSeed, color: FLOWER_COLORS[variantIndex % FLOWER_COLORS.length] });
+ return createTree({ species, leaves }, variantSeed);
+}
+
+function poissonDiskPoints(area, radius, random, accept) {
+ const cellSize = radius / Math.SQRT2;
+ const columns = Math.ceil((area.maxX - area.minX) / cellSize) + 1;
+ const rows = Math.ceil((area.maxZ - area.minZ) / cellSize) + 1;
+ const grid = new Int32Array(columns * rows).fill(-1);
+ const points = [];
+ const cellOf = point => [Math.floor((point[0] - area.minX) / cellSize), Math.floor((point[1] - area.minZ) / cellSize)];
+ const isFree = (point) => {
+ if (point[0] < area.minX || point[0] > area.maxX || point[1] < area.minZ || point[1] > area.maxZ) return false;
+ const [column, row] = cellOf(point);
+ for (let rowOffset = -2; rowOffset <= 2; rowOffset++) {
+ for (let columnOffset = -2; columnOffset <= 2; columnOffset++) {
+ const neighborColumn = column + columnOffset;
+ const neighborRow = row + rowOffset;
+ if (neighborColumn < 0 || neighborRow < 0 || neighborColumn >= columns || neighborRow >= rows) continue;
+ const neighbor = grid[neighborRow * columns + neighborColumn];
+ if (neighbor >= 0 && Math.hypot(points[neighbor][0] - point[0], points[neighbor][1] - point[1]) < radius) return false;
+ }
+ }
+ return accept(point);
+ };
+ const insert = (point) => {
+ const [column, row] = cellOf(point);
+ grid[row * columns + column] = points.length;
+ points.push(point);
+ };
+ // Restarts let the fill cross regions that exclusion has cut off from the first dart.
+ for (let restart = 0; restart < 24; restart++) {
+ const start = [lerp(area.minX, area.maxX, random()), lerp(area.minZ, area.maxZ, random())];
+ if (!isFree(start)) continue;
+ const active = [points.length];
+ insert(start);
+ while (active.length) {
+ const activeIndex = Math.floor(random() * active.length);
+ const origin = points[active[activeIndex]];
+ let placed = false;
+ for (let attempt = 0; attempt < 24 && !placed; attempt++) {
+ const angle = random() * FULL_TURN;
+ const distance = radius * (1 + random());
+ const candidate = [origin[0] + Math.cos(angle) * distance, origin[1] + Math.sin(angle) * distance];
+ if (!isFree(candidate)) continue;
+ active.push(points.length);
+ insert(candidate);
+ placed = true;
+ }
+ if (!placed) active.splice(activeIndex, 1);
+ }
+ }
+ return points;
+}
+
+function slopeDegrees(terrainHeight, x, z) {
+ const step = 0.6;
+ const slopeX = (terrainHeight(x + step, z) - terrainHeight(x - step, z)) / (2 * step);
+ const slopeZ = (terrainHeight(x, z + step) - terrainHeight(x, z - step)) / (2 * step);
+ return Math.atan(Math.hypot(slopeX, slopeZ)) * 180 / Math.PI;
+}
+
+function chooseSpecies(speciesNames, weights, x, z, seed, random) {
+ const scores = speciesNames.map((name, index) => weights[name] * (0.15 + valueNoise(x / 22, z / 22, seed + index * 17)) ** 2);
+ let pick = random() * scores.reduce((total, score) => total + score, 0);
+ for (let index = 0; index < scores.length; index++) {
+ pick -= scores[index];
+ if (pick <= 0) return speciesNames[index];
+ }
+ return speciesNames[speciesNames.length - 1];
+}
+
+function instanceMatrix(position, yaw, scale) {
+ return mat4.fromRotationTranslationScale(mat4.create(), quat.setAxisAngle(quat.create(), WORLD_UP, yaw), position, [scale, scale, scale]);
+}
+
+function instanceParts(instance, levelIndex, label) {
+ if (!instance.partsByLevel[levelIndex]) {
+ instance.partsByLevel[levelIndex] = instance.variant.levels[levelIndex].parts.map((part) => ({
+ name: `${label} ${part.role}`,
+ geometry: part.geometry,
+ matrix: instance.matrix,
+ material: part.tintable ? { ...part.material, color: part.material.color.map((channel, axis) => channel * instance.tint[axis]) } : part.material,
+ }));
+ }
+ return instance.partsByLevel[levelIndex];
+}
+
+/**
+ * Scatters vegetation with Poisson-disk spacing. `area` is `{ minX, maxX, minZ, maxZ }`, `density` is
+ * instances per square meter, `slopeLimit` is degrees, `exclusion(x, z)` returns true to keep a spot clear
+ * and `mix` weighs species ('broadleaf', 'birch', 'conifer', 'palm', 'bush', 'grass', 'flowers').
+ * A few variants per species are shared by every instance, so the renderer batches them as instances.
+ * Returns `{ instances, parts, variants, counts }`; `parts` shows every instance at full detail.
+ */
+export function scatterVegetation({
+ area, density = 0.012, terrainHeight = () => 0, slopeLimit = 32, exclusion = () => false, seed = 1,
+ mix = DEFAULT_MIX, variants = 3, leaves = 'cards', scale = [0.8, 1.25], spacing,
+} = {}) {
+ if (!area || ![area.minX, area.maxX, area.minZ, area.maxZ].every(Number.isFinite) || area.maxX <= area.minX || area.maxZ <= area.minZ) {
+ throw new TypeError('Scatter area needs finite minX < maxX and minZ < maxZ.');
+ }
+ if (!(density > 0)) throw new RangeError('Scatter density must be positive.');
+ const random = createRandom(seed);
+ const speciesNames = Object.keys(mix).filter(name => mix[name] > 0);
+ const accept = ([x, z]) => slopeDegrees(terrainHeight, x, z) <= slopeLimit && !exclusion(x, z);
+ const points = poissonDiskPoints(area, spacing ?? Math.sqrt(0.6 / density), random, accept);
+ const variantsBySpecies = {};
+ const counts = {};
+ const instances = points.map(([x, z], index) => {
+ const species = chooseSpecies(speciesNames, mix, x, z, seed, random);
+ if (!variantsBySpecies[species]) {
+ variantsBySpecies[species] = Array.from({ length: variants }, (_, variantIndex) => createVariant(species, seed * 131 + variantIndex * 977 + species.length, variantIndex, leaves));
+ }
+ const variant = variantsBySpecies[species][Math.floor(random() * variants)];
+ const size = randomInRange(random, scale);
+ const yaw = random() * FULL_TURN;
+ const position = [x, terrainHeight(x, z) - 0.04, z];
+ counts[species] = (counts[species] ?? 0) + 1;
+ const tint = [0.88 + random() * 0.24, 0.9 + random() * 0.2, 0.85 + random() * 0.25];
+ return { index, species, variant, position, yaw, scale: size, tint, matrix: instanceMatrix(position, yaw, size), level: 0, partsByLevel: [] };
+ });
+ const parts = instances.flatMap(instance => instanceParts(instance, 0, `${instance.species} ${instance.index}`));
+ return { instances, parts, variants: variantsBySpecies, counts };
+}
+
+/** Dense meadow: grass clumps with a few flowers, scattered with the same rules as `scatterVegetation`. */
+export function createGrassField(options = {}) {
+ return scatterVegetation({ density: 2.5, mix: { grass: 1, flowers: 0.06 }, variants: 4, slopeLimit: 40, scale: [0.8, 1.4], ...options });
+}
+
+function nextLevel(currentLevel, distance, thresholds, hysteresis, cullDistance) {
+ const lastLevel = thresholds.length;
+ let level = currentLevel < 0 ? lastLevel : currentLevel;
+ while (level < lastLevel && distance > thresholds[level] * (1 + hysteresis)) level++;
+ while (level > 0 && distance < thresholds[level - 1] * (1 - hysteresis)) level--;
+ const cullFactor = currentLevel < 0 ? 1 - hysteresis : 1 + hysteresis;
+ return distance > cullDistance * cullFactor ? -1 : level;
+}
+
+/**
+ * Picks a level of detail per instance from its distance to `eye`. A level changes only after the
+ * distance passes its threshold by `hysteresis` (a fraction), so instances at a boundary do not flicker.
+ * Returns `{ parts, changed, levelCounts, culled, triangles }` (`culled` counts instances past `cullDistance`); rebuild or update the renderer when `changed` is true.
+ */
+export function selectLevels(instances, eye, { distanceScale = 1, hysteresis = 0.12, cullDistance = Infinity } = {}) {
+ const parts = [];
+ const levelCounts = [];
+ let changed = false;
+ let culled = 0;
+ let triangles = 0;
+ for (const instance of instances) {
+ const distance = Math.hypot(eye[0] - instance.position[0], eye[1] - instance.position[1], eye[2] - instance.position[2]);
+ const thresholds = instance.variant.distances.map(threshold => threshold * distanceScale);
+ const level = nextLevel(instance.level, distance, thresholds, hysteresis, cullDistance);
+ if (level !== instance.level) changed = true;
+ instance.level = level;
+ if (level < 0) {
+ culled++;
+ continue;
+ }
+ levelCounts[level] = (levelCounts[level] ?? 0) + 1;
+ parts.push(...instanceParts(instance, level, `${instance.species} ${instance.index}`));
+ triangles += instance.variant.levels[level].triangles;
+ }
+ return { parts, changed, levelCounts: Array.from(levelCounts, count => count ?? 0), culled, triangles };
+}
+
+/** Renderer parts for one tree (or clump) placed by `matrix`, at a level of detail. */
+export function vegetationParts(variant, matrix, levelIndex = 0, name = variant.species) {
+ return variant.levels[levelIndex].parts.map(part => ({ name: `${name} ${part.role}`, geometry: part.geometry, matrix, material: part.material }));
+}
diff --git a/tests/vegetation.test.js b/tests/vegetation.test.js
new file mode 100644
index 00000000..6937fde9
--- /dev/null
+++ b/tests/vegetation.test.js
@@ -0,0 +1,177 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createFlowerPatch, createGrassClump, createGrassField, createTree, scatterVegetation, selectLevels, SPECIES } from '../src/vegetation.js';
+import { createBarkPixels, createLeafPixels } from '../src/vegetation-textures.js';
+
+const SPECIES_NAMES = Object.keys(SPECIES);
+
+function assertValidGeometry(geometry) {
+ const vertexCount = geometry.positions.length / 3;
+ assert.ok(vertexCount > 0 && geometry.indices.length > 0);
+ assert.equal(geometry.normals.length, geometry.positions.length);
+ assert.equal(geometry.uvs.length, vertexCount * 2);
+ for (const value of [...geometry.positions, ...geometry.normals, ...geometry.uvs]) assert.ok(Number.isFinite(value));
+ for (const index of geometry.indices) assert.ok(index < vertexCount);
+ for (let offset = 0; offset < geometry.normals.length; offset += 3) {
+ const length = Math.hypot(geometry.normals[offset], geometry.normals[offset + 1], geometry.normals[offset + 2]);
+ assert.ok(Math.abs(length - 1) < 1e-3, `normal length ${length}`);
+ }
+ if (geometry.colors) assert.equal(geometry.colors.length, geometry.positions.length);
+}
+
+function digest(tree) {
+ return tree.levels.map(level => level.parts.map(part => [...part.geometry.positions.slice(0, 60), part.geometry.indices.length].join(',')).join('|')).join('#');
+}
+
+test('trees are deterministic by seed and differ between seeds', () => {
+ assert.equal(digest(createTree('broadleaf', 5)), digest(createTree('broadleaf', 5)));
+ assert.notEqual(digest(createTree('broadleaf', 5)), digest(createTree('broadleaf', 6)));
+});
+
+test('every species and leaf mode yields valid geometry on all levels', () => {
+ for (const species of SPECIES_NAMES) {
+ for (const leaves of ['cards', 'mesh']) {
+ const tree = createTree({ species, leaves }, 3);
+ assert.equal(tree.levels.length, 3);
+ for (const level of tree.levels) {
+ for (const part of level.parts) assertValidGeometry(part.geometry);
+ }
+ }
+ }
+});
+
+test('bark faces outward and leaf cards carry the alpha-mask material contract', () => {
+ const tree = createTree('broadleaf', 2);
+ const bark = tree.levels[0].parts[0].geometry;
+ let outward = 0;
+ let total = 0;
+ for (let offset = 0; offset < bark.indices.length; offset += 3) {
+ const corners = [0, 1, 2].map(corner => Array.from(bark.positions.subarray(bark.indices[offset + corner] * 3, bark.indices[offset + corner] * 3 + 3)));
+ const edgeA = corners[1].map((value, axis) => value - corners[0][axis]);
+ const edgeB = corners[2].map((value, axis) => value - corners[0][axis]);
+ const face = [edgeA[1] * edgeB[2] - edgeA[2] * edgeB[1], edgeA[2] * edgeB[0] - edgeA[0] * edgeB[2], edgeA[0] * edgeB[1] - edgeA[1] * edgeB[0]];
+ const normalOffset = bark.indices[offset] * 3;
+ const alignment = face[0] * bark.normals[normalOffset] + face[1] * bark.normals[normalOffset + 1] + face[2] * bark.normals[normalOffset + 2];
+ total++;
+ if (alignment > 0) outward++;
+ }
+ assert.ok(outward / total > 0.98, `${outward}/${total} outward`);
+ const foliage = tree.levels[0].parts[1].material;
+ assert.equal(foliage.alphaMode, 'mask');
+ assert.equal(foliage.doubleSided, true);
+ assert.ok(foliage.map.image.width > 0);
+ assert.equal(createTree({ species: 'birch', leaves: 'mesh' }, 1).levels[0].parts[1].material.tag, 'foliage');
+});
+
+test('invalid inputs are rejected', () => {
+ assert.throws(() => createTree('banana', 1), RangeError);
+ assert.throws(() => createTree({ species: 'oak', leaves: 'sprites' }, 1), RangeError);
+ assert.throws(() => scatterVegetation({ area: { minX: 0, maxX: 0, minZ: 0, maxZ: 5 } }), TypeError);
+});
+
+test('triangle budgets fall with each level of detail', () => {
+ const budgets = { broadleaf: [60000, 12000, 2500], birch: [60000, 12000, 2500], conifer: [60000, 12000, 2500], palm: [30000, 8000, 3000], bush: [20000, 5000, 2500] };
+ for (const species of SPECIES_NAMES) {
+ for (const leaves of ['cards', 'mesh']) {
+ const triangles = createTree({ species, leaves }, 4).levels.map(level => level.triangles);
+ assert.ok(triangles[0] > triangles[1] && triangles[1] > triangles[2], `${species} ${leaves} ${triangles}`);
+ const scale = leaves === 'mesh' ? 2 : 1;
+ triangles.forEach((count, level) => assert.ok(count <= budgets[species][level] * scale, `${species} ${leaves} level ${level}: ${count}`));
+ }
+ }
+});
+
+test('wind sway comes from leaves on the foliage tag while bark stays static', () => {
+ const tree = createTree({ species: 'conifer', leaves: 'mesh' }, 1);
+ assert.equal(tree.levels[0].parts[0].material.tag, undefined);
+ assert.equal(tree.levels[0].parts[1].material.tag, 'foliage');
+ assert.equal(createGrassClump({ seed: 1 }).levels[0].parts[0].material.tag, 'grass');
+});
+
+test('grass and flowers produce valid geometry', () => {
+ for (const style of ['blades', 'cards']) {
+ const clump = createGrassClump({ style, seed: 2 });
+ clump.levels.forEach(level => assertValidGeometry(level.parts[0].geometry));
+ }
+ assertValidGeometry(createFlowerPatch({ seed: 3 }).levels[0].parts[0].geometry);
+});
+
+test('textures have alpha leaves and opaque bark', () => {
+ const leaf = createLeafPixels('sprig', [60, 110, 40]);
+ const alphas = new Set(Array.from({ length: leaf.width * leaf.height }, (_, pixel) => leaf.data[pixel * 4 + 3] > 127));
+ assert.deepEqual([...alphas].sort(), [false, true]);
+ for (const kind of ['rough', 'birch']) {
+ const bark = createBarkPixels(kind);
+ assert.ok(bark.data.every((value, offset) => offset % 4 !== 3 || value === 255));
+ }
+});
+
+const AREA = { minX: -40, maxX: 40, minZ: -40, maxZ: 40 };
+const ROLLING = (x, z) => Math.sin(x * 0.12) * 2 + Math.cos(z * 0.1) * 1.5;
+
+test('scatter keeps spacing, honors exclusion and slope, and is deterministic', () => {
+ const options = { area: AREA, density: 0.02, terrainHeight: ROLLING, slopeLimit: 12, exclusion: (x, z) => Math.hypot(x, z) < 10, seed: 9 };
+ const first = scatterVegetation(options);
+ const second = scatterVegetation(options);
+ assert.ok(first.instances.length > 40);
+ assert.deepEqual(first.instances.map(instance => instance.position), second.instances.map(instance => instance.position));
+ const spacing = Math.sqrt(0.6 / 0.02);
+ for (let a = 0; a < first.instances.length; a++) {
+ const [x, , z] = first.instances[a].position;
+ assert.ok(Math.hypot(x, z) >= 10);
+ const slopeX = (ROLLING(x + 0.6, z) - ROLLING(x - 0.6, z)) / 1.2;
+ const slopeZ = (ROLLING(x, z + 0.6) - ROLLING(x, z - 0.6)) / 1.2;
+ assert.ok(Math.atan(Math.hypot(slopeX, slopeZ)) * 180 / Math.PI <= 12 + 1e-6);
+ for (let b = a + 1; b < first.instances.length; b++) {
+ const other = first.instances[b].position;
+ assert.ok(Math.hypot(x - other[0], z - other[2]) >= spacing - 1e-6);
+ }
+ }
+});
+
+test('scattered instances share geometry per variant and a species mix is respected', () => {
+ const field = scatterVegetation({ area: AREA, density: 0.03, seed: 4, variants: 3, mix: { broadleaf: 1, conifer: 1 } });
+ const geometries = new Set(field.parts.map(part => part.geometry));
+ assert.ok(geometries.size <= 2 * 3 * 2);
+ assert.ok(field.parts.length > geometries.size * 2);
+ assert.deepEqual(Object.keys(field.counts).sort(), ['broadleaf', 'conifer']);
+ assert.ok(Object.values(field.variants).every(list => list.length === 3));
+});
+
+test('level selection follows distance with hysteresis and culling', () => {
+ const field = scatterVegetation({ area: { minX: -5, maxX: 5, minZ: -5, maxZ: 5 }, density: 0.02, seed: 2, mix: { broadleaf: 1 } });
+ const instance = field.instances[0];
+ const [x, y, z] = instance.position;
+ const levelAt = (distance, options) => {
+ selectLevels([instance], [x + distance, y, z], options);
+ return instance.level;
+ };
+ assert.equal(levelAt(5), 0);
+ assert.equal(levelAt(50), 1);
+ assert.equal(levelAt(120), 2);
+ assert.equal(levelAt(40), 1, 'inside the hysteresis band the level holds');
+ assert.equal(levelAt(36), 1);
+ assert.equal(levelAt(30), 0);
+ const result = selectLevels([instance], [x + 400, y, z], { cullDistance: 300 });
+ assert.equal(instance.level, -1);
+ assert.equal(result.culled, 1);
+ assert.equal(result.parts.length, 0);
+ assert.equal(levelAt(10, { cullDistance: 300 }), 0);
+});
+
+test('selectLevels reports changes and triangle totals, and parts keep geometry identity', () => {
+ const field = scatterVegetation({ area: AREA, density: 0.02, seed: 7, mix: { broadleaf: 1, birch: 1 } });
+ const near = selectLevels(field.instances, [0, 5, 0]);
+ const far = selectLevels(field.instances, [300, 5, 300]);
+ assert.ok(far.changed);
+ assert.ok(far.triangles < near.triangles);
+ const again = selectLevels(field.instances, [300, 5, 300]);
+ assert.equal(again.changed, false);
+ assert.equal(again.parts.every((part, index) => part === far.parts[index]), true);
+});
+
+test('grass fields scatter clumps and flowers', () => {
+ const meadow = createGrassField({ area: { minX: 0, maxX: 12, minZ: 0, maxZ: 12 }, seed: 5 });
+ assert.ok(meadow.counts.grass > 50);
+ assert.ok(meadow.parts.every(part => part.geometry.indices.length > 0));
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index b90d09e4..5de9bf91 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -26,6 +26,7 @@ export default defineConfig({
'surface-attachment': 'src/surface-attachment.js',
physics: 'src/physics.js',
spume: 'src/spume.js',
+ vegetation: 'src/vegetation.js',
'agent-scene': 'src/agent-scene.js',
'agent-asset': 'src/agent-asset.js',
},