3D engine that AI agents drive
Add a grass field addon with clumped, curved blades and rolling wind
Nguyen Xuan Ancb4ac4f0f48d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f8b2b379..f36e35f3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,10 @@# Changelog+## Unreleased++- Add `67js/addons/grass`: terrain-following grass fields of clumped, curved blades with rounded normals, root-to-tip colour, dry patches, masks for paths, four presets and tile level of detail+- Bend `grass` tag vertices by blade height and roll wind gusts across the field as a travelling wave+## 0.10.0- Add `67js/addons/terrain` for seeded, chunked heightfields with distance level of detail and `heightAt` for placementdiff --git a/README.md b/README.mdindex a98294ad..fbd88eac 100644--- a/README.md+++ b/README.md@@ -118,6 +118,7 @@ Each addon is a separate import, so a page loads only what it uses.| Rendering | `67js` | Instanced PBR renderer, shadows, MSAA, HDR, bloom, alpha masks and blending, render budgets. See [lighting](docs/lighting.md) and [material maps](docs/material-maps.md). || Environment | `67js/addons/hdri` | Image-based lighting from Radiance `.hdr` files, with blurred reflections. || Terrain | `67js/addons/terrain`, `67js/addons/texture-set` | [Chunked terrain](docs/terrain.md) with level of detail and a four-layer splat material from scanned textures. |+| Grass | `67js/addons/grass` | [Grass fields](docs/grass.md) of clumped, curved blades with rolling wind gusts, paths and level of detail. || Vegetation | `67js/addons/vegetation` | [Seeded trees, bushes and grass](docs/vegetation.md) with scanned leaves and bark, wind and level of detail. || Liquid | `67js/addons/spume` | [Baked liquid playback](docs/spume.md) with refraction and spray from the Spume solver. || Vehicles | `67js/addons/vehicle` | [Wheeled vehicles on a path](docs/vehicle.md): wheel spin, steering, roll, pitch and ground following. |diff --git a/docs/grass.md b/docs/grass.mdnew file mode 100644index 00000000..4532cb58--- /dev/null+++ b/docs/grass.md@@ -0,0 +1,94 @@+# Grass++`67js/addons/grass` builds a field of real grass blades that follows the terrain and sways in the wind.+It is in the current source and not yet published.++```js+import { Renderer67 } from '67js';+import { createGrass } from '67js/addons/grass';+import { createTerrain } from '67js/addons/terrain';++const terrain = createTerrain({ size: 300, seed: 4 });+const path = (x, z) => (Math.abs(x - 6 * Math.sin(z * 0.08)) < 1.1 ? 0 : 1);+const grass = createGrass({+ preset: 'meadow',+ area: { minX: -40, maxX: 40, minZ: -70, maxZ: 30 },+ terrainHeight: terrain.heightAt,+ mask: path,+ eye,+ seed: 3,+});++const renderer = new Renderer67(canvas, [...terrain.parts, ...grass.parts], { world: true, hdr: true, ground: false, memoryBudgetMiB: 1536 });+renderer.render({ eye, target, time: seconds, wind: 0.45 });++// When the camera moves:+if (grass.update(eye)) renderer.replaceParts([...terrain.parts, ...grass.parts]);+```++## How the blades are made++The technique follows the grass of Ghost of Tsushima (GDC 2021) and the open ports of it, [GodotGrass](https://github.com/2Retr0/GodotGrass) and [Quick_Grass](https://github.com/simondevyoutube/Quick_Grass).++- Each blade is a tapered strip on a quadratic curve. It rises straight from the root and bends over toward its lean at the tip.+- Blades group into clumps from cellular noise. A clump shares a height, a facing, a bend and a shade, and its blades lean away from the clump centre.+- Normals are rounded: the two edges of a blade tilt outward and lean toward the sky, so a flat strip shades like a curved leaf.+- Vertex colours run from a dark, occluded root to a light tip. Each blade drifts slightly toward yellow or blue-green, and low-frequency noise adds dry patches.+- The `grass` tag sways each vertex by how far up the blade it is (`uv.y` is 1 at the root). Gusts travel across the field as a wave along the wind direction, with a faster flutter on top. The shadow pass uses the same function.++## Options++| Option | Default | Meaning |+| --- | --- | --- |+| `area` | required | `{ minX, maxX, minZ, maxZ }` in metres. |+| `preset` | `'meadow'` | `meadow`, `lawn`, `savanna` or `wild`. Every other option overrides the preset. |+| `terrainHeight` | `() => 0` | Ground height at `(x, z)`. Pass `terrain.heightAt`. |+| `mask` | none | Coverage at `(x, z)` from 0 to 1. Zero clears paths and clearings, and partial values thin the grass and shorten it. |+| `density` | from preset | Blades per square metre at full detail. |+| `height`, `bend` | from preset | `[minimum, maximum]` blade height in metres and tip bend from 0 to 1. |+| `width` | from preset | Blade width at the root in metres. |+| `clumpSize`, `clumpStrength` | from preset | Clump cell size in metres, and how strongly blades follow their clump (0 to 1). |+| `dryness` | from preset | Share of dry patches and dry blades (0 to 1). |+| `base`, `tip`, `dry` | from preset | Linear RGB colours for the root, the green tip and the dry tip. |+| `tileSize` | `4` | Tile edge in metres. Each tile is one part and one draw. |+| `levels` | `GRASS_LEVELS` | Distance, kept share, segments and width scale per level of detail. |+| `cullDistance` | last level's distance | Tiles farther than this are dropped. |+| `castShadow` | `false` | Blade shadows cost a full extra pass of every blade. Blades still receive shadows. |+| `eye`, `seed` | area centre, `1` | Initial camera position and random seed. |++`createGrass` returns `{ parts, update(eye), material, stats(), groundColor, settings }`.++- `parts` lists the visible tiles. Each part is rigid and untextured, so `renderer.replaceParts` streams tiles in and out.+- `update(eye)` returns `true` when a tile changed level or was culled. Rebuild the part list only then.+- `stats()` returns tile counts per level, triangles, vertices and an estimate of geometry bytes.+- `groundColor` is a linear colour between the root and tip colours. Tint the ground under the grass with it, so gaps read as shaded grass and not bare soil. On a splat terrain, multiply the grass layer `tint` toward it.++## Level of detail++| Level | Distance | Blades kept | Segments | Width |+| --- | --- | --- | --- | --- |+| 0 | up to 10 m | all | 4 | 1× |+| 1 | 10 to 26 m | 35 % | 2 | 2× |+| 2 | 26 to 60 m | 12 % | 1 (a triangle) | 4.5× |++A coarser level keeps a fixed subset of the same blades, so a tile that changes level does not reshuffle.+The coarse blades are wider, so the field keeps about the same coverage.+A tile moves to a coarser level only when it is 10 % past the boundary, so tiles on an edge do not flicker.++## Measured++On the demo meadow (80 × 100 m, eye 1.3 m above the ground, RTX 3060, headless Chrome):++| View | Visible tiles | Triangles | Geometry | Build | Frame |+| --- | --- | --- | --- | --- | --- |+| Eye height 1.3 m | 344 | 1.32 M | about 105 MB | 2.9 s | about 3 ms |+| Eye height 7 m | 316 | 0.83 M | about 71 MB | 2.1 s | about 4 ms |++Set `memoryBudgetMiB` high enough for the grass geometry. Lower `density` or `cullDistance` for phones.++## Limits++- Blades are flat strips. Seen exactly edge-on they thin out. The Ghost of Tsushima view-space thickening is not implemented.+- Tiles change level with a pop, not a cross-fade.+- Wind has one fixed direction. There is no interaction with characters or vehicles.+- The build runs on the main thread. A field of this size takes 2 to 3 seconds.diff --git a/docs/guide.md b/docs/guide.mdindex 355a15c3..cd78d61c 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -211,6 +211,16 @@ The [vehicle contract](/vehicle.md) lists conventions, options and limits.Cards (`leaves: 'cards'`, the default) are single-sided, alpha-masked, double-sided `foliage` textures that sway with the wind; `'mesh'` leaves cost about twice the triangles. Pass `barkTextures` for scanned bark and `leafTextures: await loadLeafTextures('/textures/leaves')` for scanned leaf cards. The [Vegetation contract](/vegetation.md) lists species, triangle budgets and limits.+## Grass fields++`67js/addons/grass` is in the current source and not yet published. It covers terrain with clumped, curved blades in tiles with distance level of detail.++1. Create the field with `createGrass({ preset, area, terrainHeight, mask, eye })`. Presets are `meadow`, `lawn`, `savanna` and `wild`.+2. Add `grass.parts` to the renderer and pass `wind` in each frame.+3. When `grass.update(eye)` returns true, call `renderer.replaceParts` with the new part list.++Tint the ground under the grass with `grass.groundColor`. The [Grass contract](/grass.md) lists options, levels, measured budgets and limits.+## Terrain and ground textures`67js/addons/terrain` and `67js/addons/texture-set` are available from version `0.10.0`. They build a chunked, seeded heightfield with distance level of detail and a four-layer ground material (slope, height and mask rules, height-based edge blending, triplanar cliffs, anti-tiling) from CC0 scans.diff --git a/index.html b/index.htmlindex a7f7dea2..ce9429a3 100644--- a/index.html+++ b/index.html@@ -99,6 +99,7 @@ renderer.render({<a class="example" href="./assets.html"><img src="./previews/assets.webp" alt="An imported geometric study displayed in the asset viewer" width="960" height="540" loading="lazy" /><div class="example-caption"><h3>Your models</h3></div><p>Open a GLB and play its clips</p></a><a class="example" href="./terrain.md"><img src="./previews/terrain.webp" alt="Rolling hills of scanned grass and mud rising to rocky ridges under a cloudy sky" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Terrain</h3></div><p>Scanned ground layers blended by slope and height</p></a><a class="example" href="./vegetation.md"><img src="./previews/forest.webp" alt="Birch, beech and fir trees with scanned leaves over a grassy slope" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Forest</h3></div><p>Seeded trees with scanned leaves and bark</p></a>+ <a class="example" href="./grass.md"><img src="./previews/grass.webp" alt="A meadow of clumped grass blades with a path, in front of a tree line" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Grass</h3></div><p>Clumped blades that roll in the wind</p></a><a class="example" href="./spume.md"><img src="./previews/spume.webp" alt="A jet of baked liquid hitting a concrete slab, refracting the columns behind it" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Spume liquid</h3></div><p>Baked water that refracts and sprays</p></a><a class="example" href="./vehicle.md"><img src="./previews/vehicle.webp" alt="A jeep leaning into a bend as it follows a marked path" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Vehicles</h3></div><p>Steering, roll and wheels on a path</p></a><a class="example" href="./lighting.md"><img src="./previews/lighting.webp" alt="Metal spheres of rising roughness lit by an HDR environment" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>HDRI lighting</h3></div><p>Reflections that blur with roughness</p></a>diff --git a/package.json b/package.jsonindex 8c346fb9..1269e8c5 100644--- a/package.json+++ b/package.json@@ -55,7 +55,8 @@"docs/agent-character-motion.md","docs/agent-review.md","docs/vegetation.md",- "docs/terrain.md"+ "docs/terrain.md",+ "docs/grass.md"],"main": "./build/67.module.js","module": "./build/67.module.js",@@ -85,6 +86,7 @@"./addons/vehicle": "./build/vehicle.js","./addons/vegetation": "./build/vegetation.js","./addons/terrain": "./build/terrain.js",+ "./addons/grass": "./build/grass.js","./addons/texture-set": "./build/texture-set.js","./addons/agent-scene": "./build/agent-scene.js","./addons/agent-asset": "./build/agent-asset.js",diff --git a/public/previews/grass.webp b/public/previews/grass.webpnew file mode 100644index 00000000..8253b251Binary files /dev/null and b/public/previews/grass.webp differdiff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjsindex 29ee3462..d5c4935d 100644--- a/scripts/prepare-release.mjs+++ b/scripts/prepare-release.mjs@@ -42,7 +42,7 @@ const sourceDocuments = ['export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md', 'spume.md','retarget.md','vehicle.md',- 'vegetation.md', 'terrain.md',+ 'vegetation.md', 'terrain.md', 'grass.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.mdindex 112d33e9..7f3a9060 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -14,6 +14,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- An object studio uses `src/model.js` and `src/main.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 grass field, meadow, lawn or savanna over terrain uses optional `src/grass.js` and the checkout's `docs/grass.md`: clumped curved blades, tile level of detail, `mask` for paths. Tint the ground with `grass.groundColor`; prefer it over scattered `grass` clumps for anything wider than a few metres.- 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/grass.js b/src/grass.jsnew file mode 100644index 00000000..dbd12e31--- /dev/null+++ b/src/grass.js@@ -0,0 +1,281 @@+// A grass field made of real blade geometry, in the style of the Ghost of Tsushima grass talk and the open+// GodotGrass and Quick_Grass ports: curved tapered blades, clumps from cellular noise that share height, facing+// and lean, rounded normals, a dark base fading to a bright tip, dry patches, and tiles whose level of detail+// keeps a stable subset of the same blades. Wind lives in the vertex shader (`grass` tag).++import {+ FULL_TURN, WORLD_UP, clamp, createMeshBuilder, createRandom, crossProduct, lerp, lerpVectors, normalized, valueNoise,+} from './vegetation-geometry.js';++export const GRASS_LEVELS = Object.freeze([+ Object.freeze({ distance: 10, keep: 1, segments: 4, widthScale: 1 }),+ Object.freeze({ distance: 26, keep: 0.35, segments: 2, widthScale: 2 }),+ Object.freeze({ distance: 60, keep: 0.12, segments: 1, widthScale: 4.5 }),+]);++export const GRASS_PRESETS = Object.freeze({+ meadow: Object.freeze({ height: [0.25, 0.6], width: 0.022, density: 260, clumpSize: 0.55, clumpStrength: 0.55, dryness: 0.25, bend: [0.18, 0.6], base: [0.012, 0.03, 0.006], tip: [0.15, 0.27, 0.045], dry: [0.36, 0.29, 0.1] }),+ lawn: Object.freeze({ height: [0.07, 0.14], width: 0.012, density: 900, clumpSize: 0.3, clumpStrength: 0.25, dryness: 0.05, bend: [0.05, 0.25], base: [0.01, 0.035, 0.006], tip: [0.11, 0.26, 0.04], dry: [0.3, 0.3, 0.09] }),+ savanna: Object.freeze({ height: [0.45, 0.95], width: 0.018, density: 170, clumpSize: 0.8, clumpStrength: 0.7, dryness: 0.75, bend: [0.25, 0.8], base: [0.04, 0.035, 0.01], tip: [0.36, 0.3, 0.1], dry: [0.5, 0.39, 0.15] }),+ wild: Object.freeze({ height: [0.3, 0.9], width: 0.026, density: 200, clumpSize: 0.7, clumpStrength: 0.65, dryness: 0.35, bend: [0.25, 0.75], base: [0.012, 0.028, 0.008], tip: [0.14, 0.24, 0.05], dry: [0.4, 0.32, 0.12] }),+});++const MAXIMUM_BLADES_PER_TILE = 40000;+const ROUNDING_TILT = 0.55;+const CANOPY_BLEND = 0.3;++function tileSeed(seed, column, row) {+ let mixed = Math.imul(column + 7919, 374761393) ^ Math.imul(row - 104729, 668265263) ^ Math.imul(seed, 2246822519);+ mixed = Math.imul(mixed ^ mixed >>> 13, 1274126177);+ return (mixed ^ mixed >>> 16) >>> 0;+}++// Independent value in [0, 1) per clump cell; `salt` picks which property it is.+function cellHash(column, row, seed, salt) {+ return tileSeed(seed + salt * 1013, column, row) / 4294967296;+}++/** Nearest jittered clump centre around (x, z): cellular noise, as the clumping in the Ghost of Tsushima talk. */+function nearestClump(x, z, clumpSize, seed) {+ const cellColumn = Math.floor(x / clumpSize);+ const cellRow = Math.floor(z / clumpSize);+ let best = null;+ for (let offsetRow = -1; offsetRow <= 1; offsetRow++) {+ for (let offsetColumn = -1; offsetColumn <= 1; offsetColumn++) {+ const column = cellColumn + offsetColumn;+ const row = cellRow + offsetRow;+ const centerX = (column + cellHash(column, row, seed, 1)) * clumpSize;+ const centerZ = (row + cellHash(column, row, seed, 2)) * clumpSize;+ const distance = Math.hypot(x - centerX, z - centerZ);+ if (!best || distance < best.distance) best = { centerX, centerZ, distance, column, row };+ }+ }+ return {+ ...best,+ heightScale: lerp(0.72, 1.28, cellHash(best.column, best.row, seed, 3)),+ facing: cellHash(best.column, best.row, seed, 4) * FULL_TURN,+ shade: lerp(0.82, 1.15, cellHash(best.column, best.row, seed, 5)),+ bendScale: lerp(0.7, 1.3, cellHash(best.column, best.row, seed, 6)),+ };+}++function smoothstep(edgeLow, edgeHigh, value) {+ const amount = clamp((value - edgeLow) / (edgeHigh - edgeLow), 0, 1);+ return amount * amount * (3 - 2 * amount);+}++/** Every blade of one tile at full density, in a stable order; each level keeps the blades whose `keepKey` is below its share. */+function planTileBlades(column, row, settings, keepLimit) {+ const { tileSize, origin, seed, terrainHeight, mask, density } = settings;+ const random = createRandom(tileSeed(seed, column, row));+ const count = Math.min(MAXIMUM_BLADES_PER_TILE, Math.round(density * tileSize * tileSize));+ const blades = [];+ for (let index = 0; index < count; index++) {+ let x = origin[0] + (column + random()) * tileSize;+ let z = origin[1] + (row + random()) * tileSize;+ const keepKey = random();+ const maskRoll = random();+ const shapeRolls = [random(), random(), random(), random(), random(), random(), random()];+ const coverage = keepKey < keepLimit && mask ? clamp(mask(x, z), 0, 1) : 1;+ // Every roll is drawn before skipping, so a blade keeps its shape whatever share of the tile is built.+ if (keepKey >= keepLimit || maskRoll >= coverage) continue;+ const clump = nearestClump(x, z, settings.clumpSize, seed);+ const pull = settings.clumpStrength * 0.35;+ x = lerp(x, clump.centerX, pull);+ z = lerp(z, clump.centerZ, pull);+ const awayX = x - clump.centerX;+ const awayZ = z - clump.centerZ;+ const awayLength = Math.hypot(awayX, awayZ) || 1;+ const randomLean = shapeRolls[0] * FULL_TURN;+ const leanX = lerp(Math.cos(randomLean), awayX / awayLength, settings.clumpStrength);+ const leanZ = lerp(Math.sin(randomLean), awayZ / awayLength, settings.clumpStrength);+ const leanLength = Math.hypot(leanX, leanZ) || 1;+ const height = lerp(settings.height[0], settings.height[1], shapeRolls[1]) * clump.heightScale * coverage ** 0.35;+ const dryPatch = smoothstep(0.45, 0.8, valueNoise(x * 0.09, z * 0.09, seed + 31)) * settings.dryness;+ blades.push({+ x, z, y: terrainHeight(x, z), keepKey, height,+ yaw: lerp(shapeRolls[2] * FULL_TURN, clump.facing, settings.clumpStrength * 0.6),+ leanX: leanX / leanLength, leanZ: leanZ / leanLength,+ bend: lerp(settings.bend[0], settings.bend[1], shapeRolls[3]) * clump.bendScale,+ shade: clump.shade * lerp(0.85, 1.12, shapeRolls[4]),+ hue: shapeRolls[6] * 2 - 1,+ dryness: clamp(dryPatch + (shapeRolls[5] < settings.dryness * 0.25 ? 0.6 : 0), 0, 1),+ });+ }+ return blades;+}++/** Point and tangent on the blade's quadratic curve: straight up at the base, bending over toward its lean at the tip. */+function bladeCurve(blade, progress) {+ const rise = blade.height * (1 - blade.bend * 0.45);+ const reach = blade.height * blade.bend;+ const control = [0, blade.height * 0.75, 0];+ const tip = [blade.leanX * reach, rise, blade.leanZ * reach];+ const inverse = 1 - progress;+ const point = [0, 1, 2].map(axis => 2 * inverse * progress * control[axis] + progress * progress * tip[axis]);+ const tangent = normalized([0, 1, 2].map(axis => 2 * inverse * control[axis] + 2 * progress * (tip[axis] - control[axis])));+ return { point, tangent };+}++function bladeColor(blade, progress, settings) {+ const green = lerpVectors(settings.base, settings.tip, progress ** 0.75);+ const dryTip = lerpVectors(settings.base.map(channel => channel * 1.6), settings.dry, progress ** 0.6);+ const mixed = lerpVectors(green, dryTip, blade.dryness);+ const occlusion = lerp(0.3, 1, smoothstep(0, 0.45, progress));+ // Hue drift per blade: some lean yellow, some blue-green, as in a real sward.+ const hue = [1 + blade.hue * 0.14, 1, 1 - blade.hue * 0.2];+ return mixed.map((channel, index) => channel * occlusion * blade.shade * hue[index]);+}++function addBlade(builder, blade, tileX, tileZ, level, settings) {+ const right = [Math.cos(blade.yaw), 0, Math.sin(blade.yaw)];+ const width = settings.width * level.widthScale * (0.7 + 0.6 * blade.height / settings.height[1]);+ const base = [blade.x - tileX, blade.y, blade.z - tileZ];+ const rows = [];+ for (let segment = 0; segment <= level.segments; segment++) {+ const progress = segment / level.segments;+ const { point, tangent } = bladeCurve(blade, progress);+ const center = [base[0] + point[0], base[1] + point[1], base[2] + point[2]];+ const faceNormal = normalized(crossProduct(right, tangent));+ const halfWidth = width * 0.5 * (1 - progress ** 1.7);+ const color = bladeColor(blade, progress, settings);+ const vertexFor = (side) => {+ // Rounded normals: each edge tilts outward, so a flat blade shades like a curved leaf.+ const tilted = normalized(faceNormal.map((component, axis) => component + right[axis] * side * ROUNDING_TILT));+ const shading = normalized(tilted.map((component, axis) => component * (1 - CANOPY_BLEND) + WORLD_UP[axis] * CANOPY_BLEND));+ const position = center.map((component, axis) => component + right[axis] * side * halfWidth);+ return builder.addVertex(position, shading, (side + 1) / 2, 1 - progress, color);+ };+ if (segment === level.segments) {+ const tipNormal = normalized(faceNormal.map((component, axis) => component * (1 - CANOPY_BLEND) + WORLD_UP[axis] * CANOPY_BLEND));+ rows.push([builder.addVertex(center, tipNormal, 0.5, 0, color)]);+ } else {+ rows.push([vertexFor(-1), vertexFor(1)]);+ }+ }+ for (let segment = 0; segment < level.segments; segment++) {+ const [left, rightIndex] = rows[segment];+ const next = rows[segment + 1];+ if (next.length === 1) {+ builder.addTriangle(left, rightIndex, next[0]);+ } else {+ builder.addTriangle(left, rightIndex, next[0]);+ builder.addTriangle(rightIndex, next[1], next[0]);+ }+ }+}++function resolveSettings(options) {+ const preset = GRASS_PRESETS[options.preset ?? 'meadow'];+ if (!preset) throw new RangeError(`Unknown grass preset: ${options.preset}. Use ${Object.keys(GRASS_PRESETS).join(', ')}.`);+ const settings = { ...preset, ...Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined)) };+ const { area } = settings;+ if (!area || ![area.minX, area.maxX, area.minZ, area.maxZ].every(Number.isFinite) || area.maxX <= area.minX || area.maxZ <= area.minZ) {+ throw new TypeError('Grass area needs finite minX < maxX and minZ < maxZ.');+ }+ if (!(settings.density > 0)) throw new RangeError('Grass density must be a positive number of blades per square metre.');+ if (!(settings.tileSize > 0)) throw new RangeError('Grass tileSize must be positive.');+ if (!Array.isArray(settings.height) || !(settings.height[0] > 0) || !(settings.height[1] >= settings.height[0])) throw new RangeError('Grass height must be [minimum, maximum] in metres.');+ if (!(settings.width > 0)) throw new RangeError('Grass width must be positive.');+ if (settings.mask !== undefined && typeof settings.mask !== 'function') throw new TypeError('Grass mask must be a function (x, z) => 0..1.');+ if (typeof settings.terrainHeight !== 'function') throw new TypeError('Grass terrainHeight must be a function (x, z) => y.');+ for (const name of ['base', 'tip', 'dry']) {+ if (!Array.isArray(settings[name]) || settings[name].length !== 3 || !settings[name].every(Number.isFinite)) throw new TypeError(`Grass ${name} colour must be three linear RGB numbers.`);+ }+ settings.levels = settings.levels ?? GRASS_LEVELS;+ settings.cullDistance = settings.cullDistance ?? settings.levels.at(-1).distance;+ settings.origin = [area.minX, area.minZ];+ return settings;+}++/**+ * Builds a grass field over `area` ({ minX, maxX, minZ, maxZ }) in tiles of `tileSize` metres.+ * Options: `preset` ('meadow', 'lawn', 'savanna', 'wild'), `terrainHeight(x, z)`, `mask(x, z)` (0..1 coverage),+ * `density` (blades per square metre near the camera), `height` [min, max], `width`, `clumpSize`, `clumpStrength`,+ * `bend` [min, max], `dryness`, linear `base`, `tip` and `dry` colours, `castShadow`, `levels`, `cullDistance`, `seed`, `eye`.+ * Returns `{ parts, update(eye), material, stats(), groundColor }`; tint the ground under the grass with `groundColor`. `update` returns true when tiles changed level; then call+ * `renderer.replaceParts([...otherParts, ...grass.parts])`. Grass parts are rigid and untextured, so they stream.+ */+export function createGrass(options = {}) {+ const settings = resolveSettings({ tileSize: 4, seed: 1, terrainHeight: () => 0, castShadow: false, ...options });+ const material = { tag: 'grass', color: [1, 1, 1], roughness: 0.8, metallic: 0, emission: 0, doubleSided: true };+ const columns = Math.ceil((settings.area.maxX - settings.area.minX) / settings.tileSize);+ const rows = Math.ceil((settings.area.maxZ - settings.area.minZ) / settings.tileSize);+ const tiles = [];+ for (let row = 0; row < rows; row++) {+ for (let column = 0; column < columns; column++) {+ const tileX = settings.origin[0] + column * settings.tileSize;+ const tileZ = settings.origin[1] + row * settings.tileSize;+ const centerX = tileX + settings.tileSize / 2;+ const centerZ = tileZ + settings.tileSize / 2;+ tiles.push({ column, row, tileX, tileZ, centerX, centerZ, centerY: settings.terrainHeight(centerX, centerZ), level: -1, blades: null, part: null });+ }+ }++ function buildTileGeometry(tile, levelIndex) {+ const level = settings.levels[levelIndex];+ if (!tile.blades || tile.plannedKeep < level.keep) {+ tile.blades = planTileBlades(tile.column, tile.row, settings, level.keep);+ tile.plannedKeep = level.keep;+ }+ const builder = createMeshBuilder({ withColors: true });+ for (const blade of tile.blades) {+ if (blade.keepKey < level.keep) addBlade(builder, blade, tile.tileX, tile.tileZ, level, settings);+ }+ return builder.vertexCount > 0 ? builder.build() : null;+ }++ function levelFor(tile, eye) {+ const distance = Math.max(0, Math.hypot(eye[0] - tile.centerX, eye[1] - tile.centerY, eye[2] - tile.centerZ) - settings.tileSize * 0.5);+ if (distance > settings.cullDistance) return -1;+ let target = settings.levels.findIndex(level => distance <= level.distance);+ if (target === -1) target = settings.levels.length - 1;+ // Hysteresis: a tile only moves to a coarser level once it is clearly past the boundary, so tiles on an edge do not flicker.+ if (tile.level >= 0 && target > tile.level && distance <= settings.levels[tile.level].distance * 1.1) return tile.level;+ return target;+ }++ let visibleParts = [];+ function update(eye) {+ if (!eye || eye.length < 3 || ![eye[0], eye[1], eye[2]].every(Number.isFinite)) throw new TypeError('update needs an eye position [x, y, z].');+ let changed = false;+ for (const tile of tiles) {+ const target = levelFor(tile, eye);+ if (target === tile.level) continue;+ changed = true;+ tile.level = target;+ if (target === -1) {+ tile.part = null;+ continue;+ }+ const geometry = buildTileGeometry(tile, target);+ tile.part = geometry ? {+ name: `Grass tile ${tile.column},${tile.row}`,+ geometry,+ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tile.tileX, 0, tile.tileZ, 1]),+ material,+ castShadow: settings.castShadow,+ } : null;+ }+ if (changed) visibleParts = tiles.filter(tile => tile.part).map(tile => tile.part);+ return changed;+ }++ function stats() {+ const levelCounts = settings.levels.map(() => 0);+ let triangles = 0;+ let vertices = 0;+ for (const tile of tiles) {+ if (!tile.part) continue;+ levelCounts[tile.level] += 1;+ triangles += tile.part.geometry.indices.length / 3;+ vertices += tile.part.geometry.positions.length / 3;+ }+ return { tiles: tiles.length, visibleTiles: visibleParts.length, levelCounts, triangles, vertices, geometryBytes: vertices * 11 * 4 + triangles * 12 };+ }++ update(settings.eye ?? [(settings.area.minX + settings.area.maxX) / 2, 2, (settings.area.minZ + settings.area.maxZ) / 2]);+ // Colour for the ground under the blades: gaps then read as shaded grass instead of bare soil.+ const groundColor = lerpVectors(settings.base, settings.tip, 0.3);+ return { get parts() { return visibleParts; }, update, material, stats, settings, groundColor };+}diff --git a/src/renderer.js b/src/renderer.jsindex 808ab8f0..0f033e01 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -611,7 +611,8 @@ export class Renderer67 {} else {if (hasMaterialMap(parts[0].material)) throw new Error('Textured geometry requires UV channel 0.');context.disableVertexAttribArray(13);- context.vertexAttrib2f(13, 0, 0);+ // (-1, -1) marks "no UVs": grass wind then bends by local height instead of by blade position.+ context.vertexAttrib2f(13, -1, -1);}if (geometry.colors) {if (geometry.colors.length !== geometry.positions.length) throw new Error('Geometry colors must contain RGB for every vertex.');diff --git a/src/shaders.js b/src/shaders.jsindex 83edcccb..5f34d06f 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -62,7 +62,23 @@ mat4 skinTransform() {// more than the crown centre) but is capped, because bark never moves and leaves must stay near their twigs.// uv.y is 1 at a leaf's base and 0 at its tip, which drives the faster flutter.const windShader = `+// Grass bends by how far up the blade a vertex is (uv.y is 1 at the root), so it ignores terrain height.+// Gusts roll across the field as a travelling wave along the wind direction, like the rolling bands in a meadow.+vec3 grassWind(vec3 worldPoint, vec2 leafUv, float seconds, float strength) {+ float tip = clamp(1.0 - leafUv.y, 0.0, 1.0);+ float bendWeight = tip * tip;+ vec2 windDirection = vec2(0.94, 0.34);+ float along = dot(worldPoint.xz, windDirection);+ float gust = 0.5 + 0.5 * sin(along * 0.32 - seconds * 1.7 + 2.0 * sin(worldPoint.x * 0.05 - worldPoint.z * 0.04 + seconds * 0.23));+ float push = (0.3 + 0.7 * gust * gust) * strength;+ float flutter = sin(seconds * 4.7 + worldPoint.x * 2.3 + worldPoint.z * 1.9) * strength;+ vec2 offset = windDirection * (push * 0.42 + flutter * 0.05) + vec2(-windDirection.y, windDirection.x) * flutter * 0.04;+ return vec3(offset.x, -push * 0.14, offset.y) * bendWeight;+}+vec3 windOffset(vec3 localPosition, vec3 worldPoint, vec2 leafUv, float surfaceTag, float seconds, float strength) {+ // Grass without UVs (uv is (-1, -1)) has no blade coordinate, so it keeps the height-based sway below.+ if (surfaceTag == 7.0 && leafUv.x > -0.5) return grassWind(worldPoint, leafUv, seconds, strength);if (surfaceTag != 4.0 && surfaceTag != 7.0) return vec3(0.0);float heightReach = min(max(localPosition.y + 0.5, 0.0), 2.5);float branchReach = 1.0 + 0.3 * min(length(localPosition.xz), 3.0);diff --git a/tests/grass.test.js b/tests/grass.test.jsnew file mode 100644index 00000000..c57345fd--- /dev/null+++ b/tests/grass.test.js@@ -0,0 +1,118 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { GRASS_LEVELS, GRASS_PRESETS, createGrass } from '../src/grass.js';+import { vertexShader } from '../src/shaders.js';++const smallArea = { minX: -6, maxX: 6, minZ: -6, maxZ: 6 };+// A light density keeps the suite fast; blade shape and level rules do not depend on it.+const quick = { area: smallArea, density: 40 };++function bladeRoots(part) {+ const { positions, uvs } = part.geometry;+ const roots = [];+ for (let vertex = 0; vertex < positions.length / 3; vertex++) {+ // The two root vertices are consecutive; their midpoint is the blade's root whatever its width.+ if (uvs[vertex * 2 + 1] === 1 && uvs[vertex * 2] === 0) {+ const x = (positions[vertex * 3] + positions[vertex * 3 + 3]) / 2 + part.matrix[12];+ const z = (positions[vertex * 3 + 2] + positions[vertex * 3 + 5]) / 2 + part.matrix[14];+ roots.push([x, z]);+ }+ }+ return roots;+}++test('the same options and seed build identical blades', () => {+ const first = createGrass({ ...quick, seed: 4, eye: [0, 1.5, 0] });+ const second = createGrass({ ...quick, seed: 4, eye: [0, 1.5, 0] });+ assert.equal(first.parts.length, second.parts.length);+ first.parts.forEach((part, index) => assert.deepEqual(part.geometry.positions, second.parts[index].geometry.positions));+ const other = createGrass({ ...quick, seed: 5, eye: [0, 1.5, 0] });+ assert.notDeepEqual(first.parts[0].geometry.positions, other.parts[0].geometry.positions);+});++test('parts are rigid, untextured, double-sided grass with no shadow by default', () => {+ const grass = createGrass({ ...quick, eye: [0, 1.5, 0] });+ assert.ok(grass.parts.length > 0);+ for (const part of grass.parts) {+ assert.equal(part.material.tag, 'grass');+ assert.equal(part.material.doubleSided, true);+ assert.equal(part.material.map, undefined);+ assert.equal(part.castShadow, false);+ assert.ok(part.geometry.colors && part.geometry.uvs);+ }+ assert.equal(createGrass({ ...quick, castShadow: true }).parts[0].castShadow, true);+});++test('coarser levels keep a stable subset of the same blades', () => {+ const near = createGrass({ area: { minX: 0, maxX: 4, minZ: 0, maxZ: 4 }, eye: [2, 1, 2] });+ const nearRoots = bladeRoots(near.parts[0]);+ const coarse = createGrass({ area: { minX: 0, maxX: 4, minZ: 0, maxZ: 4 }, eye: [2, 1, 2 + GRASS_LEVELS[1].distance - 1] });+ assert.equal(coarse.stats().levelCounts[1], 1);+ const coarseRoots = bladeRoots(coarse.parts[0]);+ assert.ok(coarseRoots.length > 0 && coarseRoots.length < nearRoots.length * 0.5);+ // Float32 midpoints of blades of different widths differ in the last bits, so match within a millimetre.+ const hasNearTwin = ([x, z]) => nearRoots.some(([nearX, nearZ]) => Math.abs(nearX - x) < 1e-3 && Math.abs(nearZ - z) < 1e-3);+ for (const root of coarseRoots) assert.ok(hasNearTwin(root), 'every coarse blade also exists at full detail');+});++test('blades stand on the terrain and taper from a dark root to a light tip', () => {+ const terrainHeight = (x, z) => 2 + x * 0.1 + Math.sin(z * 0.5);+ const grass = createGrass({ ...quick, terrainHeight, eye: [0, 3, 0] });+ const part = grass.parts.find(candidate => grass.stats().levelCounts[0] > 0 && candidate.geometry.positions.length > 0);+ const { positions, uvs, colors } = part.geometry;+ let rootBrightness = 0;+ let tipBrightness = 0;+ for (let vertex = 0; vertex < positions.length / 3; vertex++) {+ const brightness = colors[vertex * 3] + colors[vertex * 3 + 1] + colors[vertex * 3 + 2];+ if (uvs[vertex * 2 + 1] === 1) {+ const x = positions[vertex * 3] + part.matrix[12];+ const z = positions[vertex * 3 + 2] + part.matrix[14];+ assert.ok(Math.abs(positions[vertex * 3 + 1] - terrainHeight(x, z)) < 0.02, 'roots sit on the ground');+ rootBrightness += brightness;+ }+ if (uvs[vertex * 2 + 1] === 0) tipBrightness += brightness;+ }+ assert.ok(tipBrightness > rootBrightness * 0.5, 'tips (one vertex per blade) outshine roots (two per blade)');+});++test('a zero mask clears grass and partial masks thin it', () => {+ assert.equal(createGrass({ ...quick, mask: () => 0 }).parts.length, 0);+ const full = createGrass({ ...quick, eye: [0, 1.5, 0] }).stats().triangles;+ const half = createGrass({ ...quick, eye: [0, 1.5, 0], mask: (x) => (x < 0 ? 1 : 0) }).stats().triangles;+ assert.ok(half > full * 0.35 && half < full * 0.65);+});++test('update reports level changes, culls far tiles and stays quiet when nothing moves', () => {+ const grass = createGrass({ area: { minX: -60, maxX: 60, minZ: -60, maxZ: 60 }, density: 4, eye: [0, 1.5, 0] });+ const before = grass.stats();+ assert.equal(grass.update([0, 1.5, 0]), false);+ assert.ok(before.levelCounts[0] > 0 && before.levelCounts[2] > 0);+ assert.ok(before.visibleTiles < before.tiles, 'corners beyond the cull distance are dropped');+ assert.equal(grass.update([30, 1.5, 30]), true);+ assert.notDeepEqual(grass.stats().levelCounts, before.levelCounts);+ assert.equal(grass.update([300, 1.5, 300]), true);+ assert.equal(grass.parts.length, 0);+});++test('every preset builds, and bad options fail with clear errors', () => {+ for (const preset of Object.keys(GRASS_PRESETS)) assert.ok(createGrass({ ...quick, preset }).parts.length > 0, preset);+ assert.throws(() => createGrass({ ...quick, preset: 'moss' }), /Unknown grass preset/);+ assert.throws(() => createGrass({}), /area/);+ assert.throws(() => createGrass({ ...quick, density: 0 }), /density/);+ assert.throws(() => createGrass({ ...quick, height: [0.5, 0.2] }), /height/);+ assert.throws(() => createGrass({ ...quick, tip: [1, 1] }), /tip colour/);+ assert.throws(() => createGrass({ ...quick, mask: 1 }), /mask/);+ assert.throws(() => createGrass({ ...quick }).update([0, 1]), /eye/);+});++test('groundColor sits between the root and tip colours', () => {+ const grass = createGrass({ ...quick });+ const { base, tip } = GRASS_PRESETS.meadow;+ grass.groundColor.forEach((channel, index) => assert.ok(channel >= base[index] && channel <= tip[index]));+});++test('grass wind bends by blade height (uv) and rolls across the field as gusts', () => {+ assert.match(vertexShader, /vec3 grassWind\(/);+ assert.match(vertexShader, /if \(surfaceTag == 7\.0 && leafUv\.x > -0\.5\) return grassWind\(/, 'grass without UVs keeps the height-based sway');+ assert.match(vertexShader, /float gust = /);+});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex 6cfb69b3..fb9d72d0 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -30,6 +30,7 @@ export default defineConfig({vehicle: 'src/vehicle.js',vegetation: 'src/vegetation.js',terrain: 'src/terrain.js',+ grass: 'src/grass.js','texture-set': 'src/texture-set.js','agent-scene': 'src/agent-scene.js','agent-asset': 'src/agent-asset.js',