Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Break up flat ground and even grass with layered variation

Nguyen Xuan Anc52bbfce257f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f36e35f3..517642bb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,8 @@
- 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
+- Break up grass fields with `patchiness` (short, thin and dense patches), seed `stalks` and folded blades, and let sunlight glow through backlit blades
+- Add splat `variation` (brightness and hue drift at three scales that grows with distance) and `edgeNoise` (ragged layer borders), both on by default
## 0.10.0
diff --git a/docs/grass.md b/docs/grass.md
index 4532cb58..fc0f22d2 100644
--- a/docs/grass.md
+++ b/docs/grass.md
@@ -34,7 +34,10 @@ The technique follows the grass of Ghost of Tsushima (GDC 2021) and the open por
- 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.
+- Field patches (`patchiness`) break up the even carpet: two octaves of noise at about 8 m and 25 m make some patches short and thin and others tall, dense and darker.
+- A small share of blades are seed stalks (`stalks`): a thin stem with a straw head that rises above the sward. About 6 % of blades fold over at the middle, as trampled grass does.
- 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.
+- Sunlight shines through the blades: when the camera looks toward the light, blades glow yellow-green, most at their thin tips.
## Options
@@ -49,6 +52,8 @@ The technique follows the grass of Ghost of Tsushima (GDC 2021) and the open por
| `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). |
+| `patchiness` | from preset | Field-scale variation of height, density and shade (0 to 1). Zero gives an even field. |
+| `stalks` | from preset | Share of seed stalks (0 to 1). `lawn` has none. |
| `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. |
@@ -61,7 +66,7 @@ The technique follows the grass of Ghost of Tsushima (GDC 2021) and the open por
- `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.
+- `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, darken every layer the grass covers, not only the grass layer: soil under a sward sits in the blades' shade, and a bright floor between blades is what makes a field look fake.
## Level of detail
@@ -79,10 +84,12 @@ A tile moves to a coarser level only when it is 10 % past the boundary, so tiles
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 |
+| View | Visible tiles | Triangles | Geometry | Build |
+| --- | --- | --- | --- | --- |
+| Eye height 1.3 m | 344 | 1.21 M | about 94 MB | 3.0 s |
+| Eye height 7 m | 316 | 0.74 M | about 61 MB | 2.1 s |
+
+Thin patches drop blades, so the default meadow builds about 12 % faster than the same field with `patchiness: 0` (measured in Node).
Set `memoryBudgetMiB` high enough for the grass geometry. Lower `density` or `cullDistance` for phones.
diff --git a/docs/terrain.md b/docs/terrain.md
index bc6214c8..f11acd69 100644
--- a/docs/terrain.md
+++ b/docs/terrain.md
@@ -65,6 +65,8 @@ A material with `layers` (1 to 4) draws as splat ground. It needs a standard PBR
Other `splat` options: `heightBlend` (0.22) and `heightInfluence` (1) control how strongly the height maps decide who wins at layer edges, so grass fills the gaps between rocks instead of fading linearly; `triplanarStart` and `triplanarEnd` (38 and 52 degrees) set where side projection fades in; `antiTiling` (0 to 1, default 1); `cavity` (0 to 1, default 0.55) darkens low parts of the height map; `textureSize` caps the common layer size.
+Two options keep large ground from looking flat. `variation` (0 to 2, default 1) drifts brightness and hue at three scales, about 120 m, 20 m and 3 m, with dry and lush patches. The 3 m octave grows with distance, where texture detail averages out. `edgeNoise` (0 to 2, default 1) jitters the slope and height that the rules see, by up to 9 degrees and 1.6 m, so a mud flat or a rock band gets a ragged border instead of a contour line. Set either to 0 to turn it off.
+
Shading: world-space XZ UVs, a second rotated sample at 0.58 times the scale mixed by low-frequency noise (with contrast restored) so repetition is not visible from afar, normal tilts added in world space, roughness from the maps, and a slow macro brightness and dryness variation.
Materials batch together only when they share the same `layers` array and `splat` object, so build them once and assign them to every chunk.
diff --git a/public/previews/grass.webp b/public/previews/grass.webp
index 8253b251..ce332acc 100644
Binary files a/public/previews/grass.webp and b/public/previews/grass.webp differ
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 7f3a9060..e78e6e14 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -14,7 +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 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. Darken every ground layer under the grass toward `grass.groundColor` (a bright floor between blades looks fake); 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`.
@@ -25,7 +25,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Relative facial or shape deformation uses `src/morph.js` and the checkout's `docs/morph-targets.md`. Check source versus published support first.
- Recorded contacts or articulated physics use optional `src/physics.js` and the checkout's `docs/physics.md`.
- Humanoid clips moved between rigs, or crowds of skinned characters, use optional `src/retarget.js` and the checkout's `docs/retarget.md`. Mixamo downloads need the owner's Adobe login.
-- Realistic ground (rolling hills to ridges, scanned grass/forest/mud/rock layers) uses optional `src/terrain.js`, `src/texture-set.js` and the checkout's `docs/terrain.md`. Feed `terrain.heightAt` to vegetation and vehicles; never fake ground with the `terrain` tag.
+- Realistic ground (rolling hills to ridges, scanned grass/forest/mud/rock layers) uses optional `src/terrain.js`, `src/texture-set.js` and the checkout's `docs/terrain.md`. Feed `terrain.heightAt` to vegetation and vehicles; never fake ground with the `terrain` tag. Splat `variation` and `edgeNoise` (on by default) keep wide ground from reading as one flat colour; leave them on unless a stylised look needs flat ground.
- Baked liquid (jets, geysers, torrents, whitewater) uses optional `src/spume.js` and the checkout's `docs/spume.md`. Bake with the Spume solver first; never fake it with displaced primitives.
- Wheeled vehicles driving a path (wheel spin, steering, body roll and pitch, ground following) use optional `src/vehicle.js` and the checkout's `docs/vehicle.md`.
- A flat scene or axis view uses `src/canvas2d.js`, `src/camera.js` and `src/view2d.js`.
diff --git a/src/grass.js b/src/grass.js
index dbd12e31..ae6fb4cb 100644
--- a/src/grass.js
+++ b/src/grass.js
@@ -14,15 +14,37 @@ export const GRASS_LEVELS = Object.freeze([
]);
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] }),
+ meadow: Object.freeze({ height: [0.25, 0.6], width: 0.022, density: 260, clumpSize: 0.55, clumpStrength: 0.55, dryness: 0.25, patchiness: 0.55, stalks: 0.012, 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, patchiness: 0.2, stalks: 0, 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, patchiness: 0.65, stalks: 0.035, 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, patchiness: 0.75, stalks: 0.025, 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;
+// Share of blades that fold over at the middle, as trampled or overgrown grass does.
+const FOLDED_SHARE = 0.06;
+// A seed stalk is this much thinner than a blade below its head; the head swells to HEAD_WIDTH past HEAD_START.
+const STALK_WIDTH = 0.22;
+const HEAD_START = 0.7;
+const HEAD_WIDTH = 0.75;
+
+/**
+ * Field-scale entropy at (x, z): `height` and `density` multipliers and a `lush` shade, from two octaves of value noise
+ * (about 8 m and 25 m). With `patchiness` 0 the field is uniform; at 1 some patches are short and thin, others tall and dense.
+ */
+function fieldPatch(x, z, settings) {
+ const amount = settings.patchiness;
+ const broad = valueNoise(x * 0.04, z * 0.04, settings.seed + 57);
+ const local = valueNoise(x * 0.13, z * 0.13, settings.seed + 83);
+ const growth = broad * 0.6 + local * 0.4;
+ return {
+ height: lerp(1, lerp(0.45, 1.35, growth), amount),
+ density: lerp(1, smoothstep(0.28, 0.62, growth), amount * 0.85),
+ lush: lerp(1, lerp(0.68, 1.2, valueNoise(x * 0.07, z * 0.07, settings.seed + 97)), amount),
+ };
+}
function tileSeed(seed, column, row) {
let mixed = Math.imul(column + 7919, 374761393) ^ Math.imul(row - 104729, 668265263) ^ Math.imul(seed, 2246822519);
@@ -75,10 +97,12 @@ function planTileBlades(column, row, settings, keepLimit) {
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;
+ const shapeRolls = [random(), random(), random(), random(), random(), random(), random(), random()];
// 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;
+ if (keepKey >= keepLimit) continue;
+ const coverage = mask ? clamp(mask(x, z), 0, 1) : 1;
+ const patch = fieldPatch(x, z, settings);
+ if (maskRoll >= coverage * patch.density) continue;
const clump = nearestClump(x, z, settings.clumpSize, seed);
const pull = settings.clumpStrength * 0.35;
x = lerp(x, clump.centerX, pull);
@@ -90,14 +114,21 @@ function planTileBlades(column, row, settings, keepLimit) {
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;
+ // One roll picks the blade kind: a seed stalk at the low end, a folded blade at the high end, a plain blade between.
+ const stalk = shapeRolls[7] < settings.stalks;
+ const folded = !stalk && shapeRolls[7] > 1 - FOLDED_SHARE;
+ const bladeHeight = lerp(settings.height[0], settings.height[1], shapeRolls[1]) * clump.heightScale * patch.height;
+ // Stalks rise above the sward around them but stay under 1.5 times the tallest blade.
+ const stalkHeight = Math.min(bladeHeight * lerp(1.3, 1.6, shapeRolls[3]), settings.height[1] * 1.5);
+ const height = (stalk ? stalkHeight : bladeHeight) * coverage ** 0.35;
const dryPatch = smoothstep(0.45, 0.8, valueNoise(x * 0.09, z * 0.09, seed + 31)) * settings.dryness;
+ const bend = lerp(settings.bend[0], settings.bend[1], shapeRolls[3]) * clump.bendScale;
blades.push({
- x, z, y: terrainHeight(x, z), keepKey, height,
+ x, z, y: terrainHeight(x, z), keepKey, height, stalk,
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]),
+ bend: stalk ? bend * 0.35 : (folded ? Math.min(1.6, bend * 2.4 + 0.5) : bend),
+ shade: clump.shade * patch.lush * 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),
});
@@ -118,6 +149,13 @@ function bladeCurve(blade, progress) {
}
function bladeColor(blade, progress, settings) {
+ if (blade.stalk) {
+ // Green stem ripening to a straw seed head.
+ const stem = lerpVectors(settings.base, lerpVectors(settings.tip, settings.dry, 0.35), progress ** 0.6);
+ const head = settings.dry.map(channel => channel * 0.5);
+ const colour = lerpVectors(stem, head, smoothstep(HEAD_START - 0.08, HEAD_START + 0.05, progress));
+ return colour.map(channel => channel * blade.shade * lerp(0.4, 1, smoothstep(0, 0.3, progress)));
+ }
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);
@@ -127,6 +165,12 @@ function bladeColor(blade, progress, settings) {
return mixed.map((channel, index) => channel * occlusion * blade.shade * hue[index]);
}
+/** Width of a seed stalk along its length: a thin stem, then a spindle-shaped head that closes at the tip. */
+function stalkProfile(progress) {
+ if (progress <= HEAD_START) return STALK_WIDTH;
+ return STALK_WIDTH + HEAD_WIDTH * Math.sin(Math.PI * (progress - HEAD_START) / (1 - HEAD_START));
+}
+
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]);
@@ -137,7 +181,7 @@ function addBlade(builder, blade, tileX, tileZ, level, settings) {
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 halfWidth = width * 0.5 * (blade.stalk ? stalkProfile(progress) : 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.
@@ -177,6 +221,9 @@ function resolveSettings(options) {
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.');
+ for (const name of ['patchiness', 'stalks', 'dryness']) {
+ if (!(settings[name] >= 0 && settings[name] <= 1)) throw new RangeError(`Grass ${name} must be between 0 and 1.`);
+ }
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']) {
@@ -192,7 +239,8 @@ function resolveSettings(options) {
* 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`.
+ * `bend` [min, max], `dryness`, `patchiness` (0..1 field-scale height and density patches), `stalks` (share of seed
+ * stalks), 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.
*/
diff --git a/src/renderer.js b/src/renderer.js
index 0f033e01..2d68f36f 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -59,7 +59,7 @@ const SPLAT_COLOR_UNIT = 11;
const SPLAT_NORMAL_UNIT = 12;
const SPLAT_PACKED_UNIT = 13;
const SPLAT_MASK_UNIT = 14;
-const SPLAT_UNIFORMS = ['splatEnabled', 'splatColor', 'splatNormal', 'splatPacked', 'splatMask', 'splatLayer[0]', 'splatTint[0]', 'splatSlope[0]', 'splatHeightRange[0]', 'splatMaskChannel[0]', 'splatMaskInvert[0]', 'splatBlend', 'splatOptions', 'splatMaskBounds'];
+const SPLAT_UNIFORMS = ['splatEnabled', 'splatColor', 'splatNormal', 'splatPacked', 'splatMask', 'splatLayer[0]', 'splatTint[0]', 'splatSlope[0]', 'splatHeightRange[0]', 'splatMaskChannel[0]', 'splatMaskInvert[0]', 'splatBlend', 'splatOptions', 'splatMaskBounds', 'splatVariation'];
function validateMaterialMaps(material) {
if (PROCEDURAL_MATERIAL_TAGS.has(material.tag)) {
@@ -561,6 +561,7 @@ export class Renderer67 {
context.uniform4fv(uniforms.splatBlend, parameters.blend);
context.uniform4fv(uniforms.splatOptions, parameters.options);
context.uniform4fv(uniforms.splatMaskBounds, parameters.maskBounds);
+ context.uniform4fv(uniforms.splatVariation, parameters.variation);
}
disposeSplatResources() {
diff --git a/src/shaders.js b/src/shaders.js
index 5f34d06f..ec7a2e38 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -620,6 +620,13 @@ void main() {
vec3 keyResponse = keyColor / mix(vec3(5.2, 4.7, 4.1), vec3(3.7, 3.4, 2.9), worldMode);
keyResponse *= mix(daylight, 1.0, worldMode);
if (surface.w == 4.0 || surface.w == 7.0) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * keyResponse;
+ if (surface.w == 7.0) {
+ // Sun through thin blades: they glow yellow-green when the camera looks toward the light, most at the thin tips
+ // (uv.y runs 1 at the root to 0 at the tip; grass without UVs gets a middle value).
+ float towardSun = pow(max(dot(-viewDirection, normalize(lightDirection)), 0.0), 3.0);
+ float thinness = textureUV.x > -0.5 ? 1.0 - textureUV.y * 0.8 : 0.6;
+ radiance += color * vec3(1.1, 1.25, 0.55) * towardSun * thinness * 1.4 * keyResponse * visibility;
+ }
radiance += emission;
if (surface.w == 3.0) {
float reflectivity = 0.20 + 0.65 * pow(1.0 - max(dot(normal, viewDirection), 0.0), 3.0);
diff --git a/src/splat-shader.js b/src/splat-shader.js
index 604e11f2..32e70400 100644
--- a/src/splat-shader.js
+++ b/src/splat-shader.js
@@ -15,6 +15,7 @@ uniform float splatMaskInvert[4];
uniform vec4 splatBlend;
uniform vec4 splatOptions;
uniform vec4 splatMaskBounds;
+uniform vec4 splatVariation;
const mat2 SPLAT_ROTATION = mat2(0.8253, 0.5646, -0.5646, 0.8253);
const float SPLAT_SECOND_SCALE = 0.58;
@@ -34,6 +35,28 @@ float splatRange(float value, float minimum, float maximum, float softness) {
return smoothstep(minimum - width, minimum + width, value) * (1.0 - smoothstep(maximum - width, maximum + width, value));
}
+// Three octaves of value noise in [0, 1]; one octave alone shows its grid as soft blobs.
+float splatOctaves(vec2 position) {
+ return terrainNoise(position).x * 0.5 + terrainNoise(position * 2.03 + 7.1).x * 0.3 + terrainNoise(position * 4.11 + 13.7).x * 0.2;
+}
+
+// Brightness and hue drift at field (about 120 m), patch (20 m) and clump (3 m) scale. Texture detail averages
+// out at a distance, so the clump octave grows with the pixel footprint and far ground does not read as one flat colour.
+vec3 splatVariationTint(float footprint) {
+ float amount = splatVariation.x;
+ if (amount < 0.001) return vec3(1.0);
+ float fieldScale = splatOctaves(worldPosition.xz * 0.008 + 3.7) - 0.5;
+ float patchScale = splatOctaves(worldPosition.xz * 0.05 + 21.0) - 0.5;
+ float clumpScale = splatOctaves(worldPosition.xz * 0.35 + 41.0) - 0.5;
+ float distant = smoothstep(0.02, 0.2, footprint);
+ float brightness = 1.0 + (fieldScale * 0.8 + patchScale * 0.9 + clumpScale * mix(0.35, 0.7, distant)) * amount;
+ float dryness = smoothstep(0.4, 0.68, splatOctaves(worldPosition.xz * 0.02 + 11.0));
+ float lush = smoothstep(0.48, 0.75, splatOctaves(worldPosition.xz * 0.04 + 57.0));
+ vec3 hue = mix(vec3(1.0), vec3(1.3, 1.05, 0.55), dryness * 0.8);
+ hue = mix(hue, vec3(0.72, 0.92, 0.8), lush * 0.7);
+ return mix(vec3(1.0), hue, min(amount, 1.0)) * max(brightness, 0.35);
+}
+
float splatMaskValue(int layerIndex) {
float channel = splatMaskChannel[layerIndex];
if (channel < -0.5) return 1.0;
@@ -140,9 +163,11 @@ void applySplat(inout vec3 color, inout vec3 normal, inout float roughness, inou
float lowFrequency = terrainNoise(worldPosition.xz * 0.045).x;
float blend = splatOptions.x > 0.0 ? mix(0.5, lowFrequency, 0.7) : 0.0;
- float macro = 0.78 + terrainNoise(worldPosition.xz * 0.011 + 3.7).x * 0.44;
- float dryness = smoothstep(0.45, 0.78, terrainNoise(worldPosition.xz * 0.021 + 11.0).x);
- vec3 dryTint = mix(vec3(1.0), vec3(1.2, 1.0, 0.72), dryness * 0.45);
+ vec3 variationTint = splatVariationTint(length(fwidth(worldPosition.xz)));
+ // Real layer borders wander: jitter the slope and height the rules see, so a mud flat or rock band has a ragged edge.
+ float edgeJitter = (splatOctaves(worldPosition.xz * 0.3 + 71.0) - 0.5) * 2.0 * splatVariation.y;
+ float ruleSlope = slope + edgeJitter * 9.0;
+ float ruleHeight = worldPosition.y + edgeJitter * 1.6;
float weights[4] = float[4](0.0, 0.0, 0.0, 0.0);
float covered = 0.0;
@@ -150,8 +175,8 @@ void applySplat(inout vec3 color, inout vec3 normal, inout float roughness, inou
if (index >= layerCount) break;
if (splatLayer[index].w < 0.5) continue;
float weight = 1.0;
- if (splatSlope[index].w > 0.5) weight *= splatRange(slope, splatSlope[index].x, splatSlope[index].y, splatSlope[index].z);
- if (splatHeightRange[index].w > 0.5) weight *= splatRange(worldPosition.y, splatHeightRange[index].x, splatHeightRange[index].y, splatHeightRange[index].z);
+ if (splatSlope[index].w > 0.5) weight *= splatRange(ruleSlope, splatSlope[index].x, splatSlope[index].y, splatSlope[index].z);
+ if (splatHeightRange[index].w > 0.5) weight *= splatRange(ruleHeight, splatHeightRange[index].x, splatHeightRange[index].y, splatHeightRange[index].z);
weight *= splatMaskValue(index);
weights[index] = weight;
covered = max(covered, weight);
@@ -214,7 +239,7 @@ void applySplat(inout vec3 color, inout vec3 normal, inout float roughness, inou
blendedHeight += packedSamples[index].y * weight;
}
- color *= blendedColor * macro * dryTint;
+ color *= blendedColor * variationTint;
normal = normalize(geometric + blendedTilt);
roughness = blendedRoughness;
cavity = mix(1.0, mix(0.55, 1.0, smoothstep(0.1, 0.85, blendedHeight)), splatOptions.w);
diff --git a/src/splat.js b/src/splat.js
index 86187a4e..5614ddcf 100644
--- a/src/splat.js
+++ b/src/splat.js
@@ -13,6 +13,8 @@ const DEFAULT_SPLAT = Object.freeze({
triplanarEnd: 52,
antiTiling: 1,
cavity: 0.55,
+ variation: 1,
+ edgeNoise: 1,
});
const DEFAULT_RULE_SOFTNESS = Object.freeze({ slope: 4, height: 1.5 });
@@ -86,10 +88,11 @@ export function validateSplatMaterial(material) {
if (splat.rules !== undefined && (!Array.isArray(splat.rules) || splat.rules.length > layers.length)) throw new RangeError('splat.rules needs one entry per layer at most.');
splat.rules?.forEach((rule, index) => validateRule(rule, index, splat));
validateMaskMap(splat);
- for (const field of ['heightBlend', 'heightInfluence', 'antiTiling', 'cavity']) {
+ for (const field of ['heightBlend', 'heightInfluence', 'antiTiling', 'cavity', 'variation', 'edgeNoise']) {
if (splat[field] !== undefined && requireFiniteNumber(splat[field], `splat.${field}`) < 0) throw new RangeError(`splat.${field} must not be negative.`);
}
if (splat.antiTiling > 1 || splat.cavity > 1) throw new RangeError('splat.antiTiling and splat.cavity must be at most 1.');
+ if (splat.variation > 2 || splat.edgeNoise > 2) throw new RangeError('splat.variation and splat.edgeNoise must be at most 2.');
for (const field of ['triplanarStart', 'triplanarEnd']) {
if (splat[field] !== undefined) requireRange([splat[field], splat[field]], `splat.${field}`, 0, 90);
}
@@ -147,6 +150,7 @@ export function packSplatParameters(material) {
blend: new Float32Array([splat.heightBlend, splat.heightInfluence, splat.triplanarStart, splat.triplanarEnd]),
options: new Float32Array([splat.antiTiling, splat.maskMap ? 1 : 0, layerCount, splat.cavity]),
maskBounds: new Float32Array(splat.maskBounds ?? [0, 0, 1, 1]),
+ variation: new Float32Array([splat.variation, splat.edgeNoise, 0, 0]),
};
material.layers.forEach((layer, index) => writeRule(material.splat?.rules?.[index], index, parameters, layer));
return parameters;
diff --git a/tests/grass.test.js b/tests/grass.test.js
index c57345fd..80b248a8 100644
--- a/tests/grass.test.js
+++ b/tests/grass.test.js
@@ -1,7 +1,7 @@
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';
+import { fragmentShader, 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.
@@ -102,9 +102,27 @@ test('every preset builds, and bad options fail with clear errors', () => {
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, patchiness: 2 }), /patchiness/);
+ assert.throws(() => createGrass({ ...quick, stalks: -0.1 }), /stalks/);
assert.throws(() => createGrass({ ...quick }).update([0, 1]), /eye/);
});
+test('patchiness thins and shortens parts of the field, and zero keeps it uniform', () => {
+ const uniform = createGrass({ ...quick, area: { minX: -20, maxX: 20, minZ: -20, maxZ: 20 }, density: 10, patchiness: 0, eye: [0, 1.5, 0] }).stats();
+ const patchy = createGrass({ ...quick, area: { minX: -20, maxX: 20, minZ: -20, maxZ: 20 }, density: 10, patchiness: 1, eye: [0, 1.5, 0] }).stats();
+ assert.ok(patchy.triangles < uniform.triangles * 0.9, 'thin patches drop blades');
+ assert.ok(patchy.triangles > uniform.triangles * 0.3, 'dense patches keep most of them');
+});
+
+test('seed stalks rise above the blades but stay under 1.5 times the tallest blade', () => {
+ const tallest = (grass) => Math.max(...grass.parts.flatMap(part => [...part.geometry.positions].filter((_, index) => index % 3 === 1)));
+ const options = { ...quick, preset: 'savanna', patchiness: 1, eye: [0, 1.5, 0] };
+ const blades = tallest(createGrass({ ...options, stalks: 0 }));
+ const stalks = tallest(createGrass({ ...options, stalks: 1 }));
+ assert.ok(stalks > blades, 'stalks stand taller than the blades around them');
+ assert.ok(stalks <= GRASS_PRESETS.savanna.height[1] * 1.5 + 1e-4);
+});
+
test('groundColor sits between the root and tip colours', () => {
const grass = createGrass({ ...quick });
const { base, tip } = GRASS_PRESETS.meadow;
@@ -115,4 +133,5 @@ 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 = /);
+ assert.match(fragmentShader, /float towardSun = pow\(max\(dot\(-viewDirection, normalize\(lightDirection\)\)/, 'blades glow when backlit');
});
diff --git a/tests/splat.test.js b/tests/splat.test.js
index c7bfd622..fc437e34 100644
--- a/tests/splat.test.js
+++ b/tests/splat.test.js
@@ -62,6 +62,20 @@ test('packs per-layer rules for the shader', () => {
assert.deepEqual([...parameters.tint.slice(4, 7)], [0.5, 1, 1]);
});
+test('variation and edge noise default on, can be switched off and are bounded', () => {
+ assert.deepEqual([...packSplatParameters({ layers: [layer()] }).variation], [1, 1, 0, 0]);
+ assert.deepEqual([...packSplatParameters({ layers: [layer()], splat: { variation: 0, edgeNoise: 0.5 } }).variation], [0, 0.5, 0, 0]);
+ assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { variation: 3 } }), /at most 2/);
+ assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { edgeNoise: -1 } }), /negative/);
+});
+
+test('the splat shader drifts colour at several scales and jitters rule edges', async () => {
+ const { splatGlsl } = await import('../src/splat-shader.js');
+ assert.match(splatGlsl, /vec3 splatVariationTint\(float footprint\)/);
+ assert.match(splatGlsl, /ruleSlope = slope \+ edgeJitter/);
+ assert.match(splatGlsl, /splatRange\(ruleHeight,/);
+});
+
test('resizes layers to a common size and counts the texture bytes', () => {
const material = { layers: [layer(8), layer(16)] };
assert.equal(resolveSplatSize(material, 4096), 16);