Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add chunked terrain, texture sets and a four-layer splat ground material

Nguyen Xuan An119b9604f331
diff --git a/.gitignore b/.gitignore
index bdaba057..c7848efc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,6 +21,7 @@ public/spume.md
public/retarget.md
public/vehicle.md
public/vegetation.md
+public/terrain.md
public/scene-graph.md
public/modeling.md
public/animation-curves.md
diff --git a/README.md b/README.md
index a3354811..53677304 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 [Terrain addon](docs/terrain.md) builds seeded chunked terrain with distance level of detail and a four-layer splat ground material from real CC0 scans (`loadTextureSet` loads them), and its `heightAt` feeds vegetation and vehicles.
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 source [retarget addon](docs/retarget.md) transfers humanoid clips between rigs (Mixamo, VRM, Unreal, Rigify names) and offsets crowds deterministically. Mixamo files need the owner's Adobe login to download.
diff --git a/docs/guide.md b/docs/guide.md
index 7393d696..326ec16f 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) use alpha-masked, double-sided textures; `'mesh'` leaves cost more triangles but sway with the `foliage` wind. The [Vegetation contract](/vegetation.md) lists species, triangle budgets and limits.
+## Terrain and ground textures
+
+`67js/addons/terrain` and `67js/addons/texture-set` are in the current source and not yet published. 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.
+
+1. `const set = await loadTextureSet('/textures/leafy_grass')` per layer, then `material.layers = [{ ...set, scale: 3 }, ...]` and `material.splat = { rules }`.
+2. `const terrain = createTerrain({ size, chunks, resolution, levels, seed })`; give every `terrain.parts` entry the one shared material.
+3. Pass `terrain.heightAt` to `scatterVegetation` and vehicles, and call `renderer.replaceParts` when `terrain.update(eye)` returns parts.
+
+The [Terrain contract](/terrain.md) lists every option, the texture-array memory and the 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/material-maps.md b/docs/material-maps.md
index 8de26282..3c28460b 100644
--- a/docs/material-maps.md
+++ b/docs/material-maps.md
@@ -97,6 +97,10 @@ Final alpha is the base map alpha (when `material.map` is set) times `opacity`.
glTF import maps `alphaMode` MASK and BLEND, `alphaCutoff`, `doubleSided` and `baseColorFactor[3]` (to `opacity`) onto these fields, and keeps the base color texture alpha. `exportGlb` writes them back.
+## Splat layers
+
+A standard-tag material can carry `layers` (up to four `{ color, normal, roughness, height, scale, tint, triplanar }` entries built from `loadTextureSet`) and a `splat` rule object instead of these single maps. The layers are blended by slope, height and a weight mask, sampled in world space and packed into texture arrays on units 11 to 14. They replace `map`, `normalMap`, `metallicRoughnessMap` and `occlusionMap`, which must be absent, and parts batch only when `layers` and `splat` are the same objects. See [Terrain](/terrain.md).
+
## Limits
Texture transforms, UV channels beyond zero, and vertex alpha below one remain unsupported.
diff --git a/docs/terrain.md b/docs/terrain.md
new file mode 100644
index 00000000..317ca052
--- /dev/null
+++ b/docs/terrain.md
@@ -0,0 +1,100 @@
+# Terrain and splat ground
+
+`67js/addons/terrain` and `67js/addons/texture-set` are in the current source and not yet published.
+Together they replace a flat, noise-tinted ground with a chunked heightfield and a four-layer ground material made from real scanned textures.
+
+```js
+import { Renderer67 } from '67js';
+import { loadHdri } from '67js/addons/hdri';
+import { createTerrain } from '67js/addons/terrain';
+import { loadTextureSet } from '67js/addons/texture-set';
+import { scatterVegetation } from '67js/addons/vegetation';
+
+const terrain = createTerrain({ size: 600, chunks: 10, resolution: 32, levels: 4, seed: 11 });
+const [grass, forest, mud, rock] = await Promise.all(
+ ['leafy_grass', 'forest_ground_04', 'brown_mud_leaves_01', 'aerial_rocks_02'].map(name => loadTextureSet(`/textures/${name}`)),
+);
+const material = {
+ color: [1, 1, 1], metallic: 0, roughness: 1,
+ layers: [
+ { ...grass, scale: 3.2, tint: [0.58, 0.88, 0.38] },
+ { ...forest, scale: 3.5 },
+ { ...mud, scale: 2.6 },
+ { ...rock, scale: 6, triplanar: true },
+ ],
+ splat: {
+ rules: [undefined, { height: [-9, -2] }, { mask: 'r' }, { slope: [31, 90] }],
+ maskMap: pathWeights, maskBounds: [-300, -300, 300, 300],
+ },
+};
+for (const part of terrain.parts) part.material = material;
+
+const trees = scatterVegetation({ area, terrainHeight: terrain.heightAt, slopeLimit: 24, leaves: 'cards' });
+const renderer = new Renderer67(canvas, [...terrain.parts, ...treeParts], { world: true, ground: false, hdr: true, environment: { map: await loadHdri('/hdri/sky.hdr') } });
+```
+
+Each frame, `if (terrain.update(eye).length) renderer.replaceParts(sceneParts)` swaps the chunks whose level of detail changed.
+Textured parts such as leaf cards must stay unchanged in `replaceParts`, so rebuild the renderer when the vegetation levels change.
+
+## loadTextureSet
+
+`loadTextureSet(baseUrl, { channels, extension = 'webp', colorSpaces, fetchBlob, decodeBlob })` fetches `<baseUrl>/color.webp`, `normal.webp`, `roughness.webp` and `height.webp` and returns `{ color, normal, roughness, height }` texture descriptors (`{ image, colorSpace }`).
+
+- `color` is `srgb`; `normal`, `roughness` and `height` are `linear`. Normal maps use the OpenGL convention (green up), as the Poly Haven files in `public/textures/` do.
+- Without `channels`, every channel that exists loads and a missing file is skipped (the bark scans have no height). With `channels: [...]`, a missing file throws.
+- Decoding uses `createImageBitmap` with colour conversion off. In Node, pass `fetchBlob` and `decodeBlob`; the splat code also accepts `{ width, height, data }` pixel objects.
+- The result spreads into a layer: `{ ...set, scale: 4 }`.
+
+## Splat material
+
+A material with `layers` (1 to 4) draws as splat ground. It needs a standard PBR tag (no `terrain`, `floor` and the like) and no `map`, `normalMap`, `metallicRoughnessMap` or `occlusionMap`; the layers replace them. `color` multiplies the result.
+
+| Layer field | Meaning |
+| --- | --- |
+| `color`, `normal`, `roughness`, `height` | Descriptors from `loadTextureSet`. Missing ones fall back to mid grey, a flat normal, roughness 1 and height 0.5. |
+| `scale` | Metres per texture tile (default 4). |
+| `tint` | RGB multiplier on colour. |
+| `normalStrength` | Scales the normal map tilt (default 1). |
+| `triplanar` | Project from the sides on steep slopes, so cliffs do not stretch. |
+
+`material.splat` holds `rules`, one entry per layer (or `undefined`):
+
+- `slope: [minimum, maximum]` in degrees from horizontal, `height: [minimum, maximum]` in world metres, each with `slopeSoftness` (default 4) and `heightSoftness` (default 1.5) as the half-width of the fade.
+- `mask: 'r' | 'g' | 'b' | 'a'` multiplies by a weight channel. `invertMask: true` flips it. The weights come from vertex colours (`r`, `g`, `b` only) or, when `splat.maskMap` is set, from a linear texture stretched over `splat.maskBounds = [minimumX, minimumZ, maximumX, maximumZ]`. The first image row is `minimumZ`.
+- A layer with no rule takes what the other layers leave, so put grass first with no rule.
+
+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.
+
+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.
+
+Memory: three `TEXTURE_2D_ARRAY`s on units 11 to 13 (sRGB colour, normal, roughness in red with height in green), all layers resized to the largest source (at most `MAX_TEXTURE_SIZE`), with mipmaps and up to 8x anisotropic filtering when the extension exists. The weight texture uses unit 14. The renderer counts them in `memoryBudgetMiB` and reports them as `renderer.splatBytes`. Four 1K layers take 64 MiB; set `textureSize: 512` to quarter that.
+
+## createTerrain
+
+`createTerrain({ size = 512, resolution = 32, chunks = 8, levels = 4, height, seed = 1, material, lodDistance, eye })` returns `{ parts, heightAt, normalAt, bounds, update, triangleCount, chunkSize, chunkLevels }`.
+
+- The ground spans x and z from `-size / 2` to `size / 2`. `chunks` per side, each with `resolution` cells at level 0 (so `resolution` must divide by `2 ** (levels - 1)`). Level `n` uses `resolution / 2 ** n` cells.
+- `height` is a function `(x, z) => metres`, a square `Float32Array` of metres stretched over the ground (`heightmapFromImageData(imageData, amplitude)` builds one from an image), or noise options: `amplitude` (hills, 14), `mountainAmplitude` (46), `featureSize` (160 m), `octaves`, `gain`, `lacunarity`, `warp` (domain warp in metres), `baseHeight` and `mountainMask(x, z)` (0 to 1, where ridged mountains replace hills). Hills use slope-damped octaves and mountains use ridged multifractal noise, which gives smooth flanks, sharp crests and carved valleys. The same `seed` always gives the same ground.
+- `heightAt(x, z)` walks the same triangles as the level 0 mesh, so it matches the rendered surface there (coarser levels differ by their simplification). Coordinates outside the ground clamp to its edge. `normalAt` interpolates smooth grid normals.
+- `update(eye)` picks a level per chunk from its distance (`lodDistance`, default 1.6 chunk sizes, doubling per level) and returns the parts whose geometry changed. Edges shared with a coarser neighbour are snapped onto the neighbour's edge, so there are no cracks and no skirts.
+- UVs are world metres `(x, z)`. Vertex normals are smooth and shared across chunk borders.
+
+## Measured
+
+Windows, RTX 3060, headless Chrome, 1600x900, 4x MSAA, HDRI, shadows, bloom, 600 m terrain with 10x10 chunks at resolution 32 and about 1,000 to 1,750 trees:
+
+| Camera | Terrain triangles | Scene triangles | Batches | Frame |
+| --- | --- | --- | --- | --- |
+| Low, close to the path | 50,432 | 1.23 M | 164 | 13.8 ms |
+| High, whole scene | 12,896 | 0.53 M | 124 | 9.0 ms |
+
+Splat textures take 68 MiB of 74 MiB texture memory at 1K per layer.
+
+## Limits
+
+- Up to four layers; one splat material per draw (chunks share one).
+- Overhangs are not represented: the terrain is a heightfield.
+- Changing `layers` or `splat` after the renderer exists needs a new renderer.
+- The weight texture follows its descriptor's filtering (mipmapped by default); 1024 square over 600 m gives 0.6 m texels.
+- Normal-map tilt is added to the geometric normal in world space, which is cheap and stable but not a full tangent-space blend.
diff --git a/package.json b/package.json
index fbfe384a..dcd89081 100644
--- a/package.json
+++ b/package.json
@@ -54,7 +54,8 @@
"docs/agent-motion.md",
"docs/agent-character-motion.md",
"docs/agent-review.md",
- "docs/vegetation.md"
+ "docs/vegetation.md",
+ "docs/terrain.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -83,6 +84,8 @@
"./addons/retarget": "./build/retarget.js",
"./addons/vehicle": "./build/vehicle.js",
"./addons/vegetation": "./build/vegetation.js",
+ "./addons/terrain": "./build/terrain.js",
+ "./addons/texture-set": "./build/texture-set.js",
"./addons/agent-scene": "./build/agent-scene.js",
"./addons/agent-asset": "./build/agent-asset.js",
"./addons/hdri": "./build/hdri.js",
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index 44fbbfea..29ee3462 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',
+ 'vegetation.md', 'terrain.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 2cf6ad87..112d33e9 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -24,6 +24,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.
- 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/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index ff8eff7b..9dfbe984 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -49,6 +49,7 @@ The material tags select renderer behavior.
| `foam` | Soft alpha-blended whitewater droplets drawn after liquids. Set `castShadow: false`. |
| `foliage`, `grass` | Wind movement and backlighting. |
| `terrain` | Subtle natural surface variation. |
+| Standard tag with `layers` and `splat` | Four-layer scanned ground blended by slope, height and mask; see `docs/terrain.md`. Rejects the procedural tags and single PBR maps. |
| `fire`, `smoke` | Film ignition expansion and procedural shading. |
| `unlit` | Flat linear color for vector scenes. |
| Other tags | Standard metallic/roughness shading. |
diff --git a/src/renderer.js b/src/renderer.js
index af585d00..f4bab200 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -8,6 +8,7 @@ import { createLightingState, updateLightingState } from './lighting.js';
import { resolveVolumeFog } from './volumetric.js';
import { assertEnvironmentMap, createEnvironmentResources, environmentBackgroundFragment, estimateEnvironmentBytes } from './environment.js';
import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';
+import { validateSplatMaterial, splatBatchState, splatTextureBytes, resolveSplatSize, packSplatParameters, buildSplatPixels } from './splat.js';
import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';
const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10, liquid: 11, foam: 12 };
@@ -51,6 +52,11 @@ const ENVIRONMENT_LOOKUP_UNIFORMS = ['environmentSpecular', 'environmentEnabled'
const ENVIRONMENT_UNIFORMS = [...ENVIRONMENT_LOOKUP_UNIFORMS, 'environmentBrdf', 'environmentIrradiance[0]'];
const ENVIRONMENT_SPECULAR_UNIT = 9;
const ENVIRONMENT_BRDF_UNIT = 10;
+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'];
function validateMaterialMaps(material) {
if (PROCEDURAL_MATERIAL_TAGS.has(material.tag)) {
@@ -71,7 +77,9 @@ function materialMapState(material) {
validateMaterialMaps(material);
const normalScale = material.normalScale ?? DEFAULT_NORMAL_SCALE;
const occlusionStrength = material.occlusionStrength ?? 1;
- return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength];
+ validateSplatMaterial(material);
+ if (material.layers && PROCEDURAL_MATERIAL_TAGS.has(material.tag)) throw new Error('Splat layers require a standard PBR material tag.');
+ return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...splatBatchState(material)];
}
function validateAlphaMaterial(material) {
@@ -303,6 +311,7 @@ export class Renderer67 {
this.influenceTextures = new Map();
this.morphTextures = new Map();
this.textures = new Map();
+ this.splatResources = new Map();
this.textureBytes = 4;
this.shadowsDirty = true;
const groups = groupParts(this.groundPart ? [...parts, this.groundPart] : parts, batching);
@@ -341,6 +350,15 @@ export class Renderer67 {
maps.add(map);
}
}
+ this.splatBytes = 0;
+ const splatLayerSets = new Set();
+ for (const group of groups) {
+ const material = group[0].material;
+ if (!material.layers || splatLayerSets.has(material.layers)) continue;
+ splatLayerSets.add(material.layers);
+ this.splatBytes += splatTextureBytes(resolveSplatSize(material, textureLimit), material.layers.length) + (material.splat?.maskMap ? textureDescriptorInfo(material.splat.maskMap, textureLimit).bytes : 0);
+ }
+ this.textureBytes += this.splatBytes;
this.capabilities.maximumTextureSize = textureLimit;
this.environmentResources = null;
this.environmentBackgroundProgram = null;
@@ -364,7 +382,7 @@ export class Renderer67 {
this.inverseViewProjection = mat4.create();
this.program = compileProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, benchmark ? benchmarkFragmentShader : fragmentShader);
this.depthProgram = compileProgram(this.context, depthVertexShader, depthFragmentShader);
- this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'keyColor', 'fillIntensity', 'ambientIntensity']) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -402,6 +420,7 @@ export class Renderer67 {
this.context.activeTexture(this.context.TEXTURE0 + unit);
this.context.bindTexture(this.context.TEXTURE_2D, this.whiteTexture);
}
+ this.initializeSplatPlaceholders();
this.initializeEnvironment(environment.map);
groups.forEach((group) => this.batches.push(this.uploadBatch(group)));
this.createShadowMap();
@@ -456,6 +475,95 @@ export class Renderer67 {
return texture;
}
+ initializeSplatPlaceholders() {
+ const context = this.context;
+ this.splatPlaceholder = context.createTexture();
+ context.bindTexture(context.TEXTURE_2D_ARRAY, this.splatPlaceholder);
+ context.texImage3D(context.TEXTURE_2D_ARRAY, 0, context.RGBA8, 1, 1, 1, 0, context.RGBA, context.UNSIGNED_BYTE, new Uint8Array([128, 128, 128, 255]));
+ context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_MIN_FILTER, context.LINEAR);
+ context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_MAG_FILTER, context.LINEAR);
+ context.useProgram(this.program);
+ const units = [['splatColor', SPLAT_COLOR_UNIT], ['splatNormal', SPLAT_NORMAL_UNIT], ['splatPacked', SPLAT_PACKED_UNIT]];
+ for (const [name, unit] of units) {
+ context.uniform1i(this.uniforms[name], unit);
+ context.activeTexture(context.TEXTURE0 + unit);
+ context.bindTexture(context.TEXTURE_2D_ARRAY, this.splatPlaceholder);
+ }
+ context.uniform1i(this.uniforms.splatMask, SPLAT_MASK_UNIT);
+ context.activeTexture(context.TEXTURE0 + SPLAT_MASK_UNIT);
+ context.bindTexture(context.TEXTURE_2D, this.whiteTexture);
+ context.uniform1f(this.uniforms.splatEnabled, 0);
+ }
+
+ createTextureArray(internalFormat, size, layerCount, pixels) {
+ const context = this.context;
+ const texture = context.createTexture();
+ context.bindTexture(context.TEXTURE_2D_ARRAY, texture);
+ const levels = Math.floor(Math.log2(size)) + 1;
+ context.texStorage3D(context.TEXTURE_2D_ARRAY, levels, internalFormat, size, size, layerCount);
+ context.pixelStorei(context.UNPACK_FLIP_Y_WEBGL, false);
+ context.pixelStorei(context.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ context.pixelStorei(context.UNPACK_COLORSPACE_CONVERSION_WEBGL, context.NONE);
+ context.texSubImage3D(context.TEXTURE_2D_ARRAY, 0, 0, 0, 0, size, size, layerCount, context.RGBA, context.UNSIGNED_BYTE, pixels);
+ context.generateMipmap(context.TEXTURE_2D_ARRAY);
+ context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_WRAP_S, context.REPEAT);
+ context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_WRAP_T, context.REPEAT);
+ context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_MIN_FILTER, context.LINEAR_MIPMAP_LINEAR);
+ context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_MAG_FILTER, context.LINEAR);
+ const anisotropy = context.getExtension('EXT_texture_filter_anisotropic');
+ if (anisotropy) context.texParameterf(context.TEXTURE_2D_ARRAY, anisotropy.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(8, context.getParameter(anisotropy.MAX_TEXTURE_MAX_ANISOTROPY_EXT)));
+ return texture;
+ }
+
+ createSplatResources(material) {
+ if (this.splatResources.has(material.layers)) return this.splatResources.get(material.layers);
+ const context = this.context;
+ const size = resolveSplatSize(material, context.getParameter(context.MAX_TEXTURE_SIZE));
+ const layerCount = material.layers.length;
+ const pixels = buildSplatPixels(material.layers, size);
+ const resources = {
+ size,
+ layerCount,
+ color: this.createTextureArray(context.SRGB8_ALPHA8, size, layerCount, pixels.color),
+ normal: this.createTextureArray(context.RGBA8, size, layerCount, pixels.normal),
+ packed: this.createTextureArray(context.RGBA8, size, layerCount, pixels.packed),
+ mask: material.splat?.maskMap ? this.createTexture(material.splat.maskMap) : this.whiteTexture,
+ parameters: packSplatParameters(material),
+ };
+ this.splatResources.set(material.layers, resources);
+ return resources;
+ }
+
+ bindSplat(splat) {
+ const context = this.context;
+ const uniforms = this.uniforms;
+ context.uniform1f(uniforms.splatEnabled, splat ? 1 : 0);
+ if (!splat) return;
+ const bindings = [[SPLAT_COLOR_UNIT, context.TEXTURE_2D_ARRAY, splat.color], [SPLAT_NORMAL_UNIT, context.TEXTURE_2D_ARRAY, splat.normal], [SPLAT_PACKED_UNIT, context.TEXTURE_2D_ARRAY, splat.packed], [SPLAT_MASK_UNIT, context.TEXTURE_2D, splat.mask]];
+ for (const [unit, target, texture] of bindings) {
+ context.activeTexture(context.TEXTURE0 + unit);
+ context.bindTexture(target, texture);
+ }
+ const parameters = splat.parameters;
+ context.uniform4fv(uniforms['splatLayer[0]'], parameters.layer);
+ context.uniform4fv(uniforms['splatTint[0]'], parameters.tint);
+ context.uniform4fv(uniforms['splatSlope[0]'], parameters.slope);
+ context.uniform4fv(uniforms['splatHeightRange[0]'], parameters.height);
+ context.uniform1fv(uniforms['splatMaskChannel[0]'], parameters.mask);
+ context.uniform1fv(uniforms['splatMaskInvert[0]'], parameters.maskInvert);
+ context.uniform4fv(uniforms.splatBlend, parameters.blend);
+ context.uniform4fv(uniforms.splatOptions, parameters.options);
+ context.uniform4fv(uniforms.splatMaskBounds, parameters.maskBounds);
+ }
+
+ disposeSplatResources() {
+ for (const resources of this.splatResources?.values() ?? []) {
+ for (const texture of [resources.color, resources.normal, resources.packed]) this.context.deleteTexture(texture);
+ }
+ this.splatResources?.clear();
+ if (this.splatPlaceholder) this.context.deleteTexture(this.splatPlaceholder);
+ }
+
uploadBatch(parts) {
const context = this.context;
const vertexArray = context.createVertexArray();
@@ -527,6 +635,7 @@ export class Renderer67 {
const map = parts[0].material.map ?? null;
const mapState = materialMapState(parts[0].material);
const textures = mapState.slice(0, 5).map(descriptor => this.createTexture(descriptor));
+ const splat = parts[0].material.layers ? this.createSplatResources(parts[0].material) : null;
const skin = parts[0].skin ?? null;
const skinTexture = skin ? this.createSkinTexture(this.skinTextures, skin, skin.jointMatrices, 4) : null;
const influenceTexture = skin ? this.createSkinTexture(this.influenceTextures, geometry, null, 2) : null;
@@ -534,7 +643,7 @@ export class Renderer67 {
const morphTexture = morph ? this.createMorphTexture(geometry, morph) : null;
const morphWeights = morph ? new Float32Array(morph.weights) : null;
const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);
- const batch = { alphaMode, alphaCutoff, opacity, doubleSided, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), pass: renderPass(parts[0].material) };
+ const batch = { alphaMode, alphaCutoff, opacity, doubleSided, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), pass: renderPass(parts[0].material) };
parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
return batch;
}
@@ -1268,6 +1377,7 @@ export class Renderer67 {
}
this.context.uniform2f(this.uniforms.normalScale, batch.mapState[5], batch.mapState[6]);
this.context.uniform1f(this.uniforms.occlusionStrength, batch.mapState[7]);
+ this.bindSplat(batch.splat);
}
this.context.bindVertexArray(batch.vertexArray);
this.context.drawElementsInstanced(this.context.TRIANGLES, batch.indexCount, this.context.UNSIGNED_INT, 0, batch.instanceCount);
@@ -1373,6 +1483,7 @@ export class Renderer67 {
if (this.environmentBackgroundProgram) this.context.deleteProgram(this.environmentBackgroundProgram);
this.environmentResources?.dispose();
for (const texture of this.textures.values()) this.context.deleteTexture(texture);
+ this.disposeSplatResources();
this.textures.clear();
for (const cache of [this.skinTextures, this.influenceTextures, this.morphTextures]) {
for (const record of cache?.values() ?? []) this.context.deleteTexture(record.texture);
diff --git a/src/shaders.js b/src/shaders.js
index 01af1c4e..1ea62772 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -1,5 +1,6 @@
import { MAX_MORPH_TARGETS } from './morph.js';
import { environmentLookupGlsl, environmentShadingGlsl } from './environment.js';
+import { splatGlsl } from './splat-shader.js';
const morphingShader = `
uniform float morphEnabled;
@@ -454,6 +455,8 @@ vec3 mappedNormal(vec3 normal) {
return dot(mapped, mapped) > 1e-12 ? normalize(mapped) : normal;
}
+${splatGlsl}
+
// Opaque draws 1, mask resolves to a cutout (smooth coverage with MSAA) and blend keeps the fraction.
float surfaceAlpha(float textureAlpha) {
if (alphaMode < 0.5) return 1.0;
@@ -475,7 +478,7 @@ void main() {
if (hasNormalMap > 0.5) normal = mappedNormal(normal);
vec3 viewDirection = normalize(eye - worldPosition);
vec3 color = mix(baseColor, armorColor, step(0.5, surface.w) * (1.0 - step(1.5, surface.w)));
- color *= vertexTint;
+ if (splatEnabled < 0.5) color *= vertexTint;
float textureAlpha = 1.0;
if (hasBaseMap > 0.5) {
vec4 sampledBase = texture(baseMap, textureUV);
@@ -501,6 +504,8 @@ void main() {
metallic *= sampled.b;
roughness *= sampled.g;
}
+ float splatCavity = 1.0;
+ if (splatEnabled > 0.5) applySplat(color, normal, roughness, splatCavity);
roughness = clamp(roughness, 0.075, 1.0);
vec3 normalChange = max(abs(dFdx(normal)), abs(dFdy(normal)));
roughness = clamp(sqrt(roughness * roughness + dot(normalChange, normalChange) * 0.3), 0.075, 1.0);
@@ -559,6 +564,7 @@ void main() {
vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(vec3(0.04), color, metallic));
float occlusion = 1.0;
if (hasOcclusionMap > 0.5) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);
+ occlusion *= splatCavity;
if (environmentEnabled > 0.5) {
radiance += environmentLighting(normal, viewDirection, color, metallic, roughness, occlusion, ambientIntensity);
} else {
diff --git a/src/splat-shader.js b/src/splat-shader.js
new file mode 100644
index 00000000..604e11f2
--- /dev/null
+++ b/src/splat-shader.js
@@ -0,0 +1,222 @@
+// Fragment shader chunk for the splat ground material. It is spliced into the main fragment shader after terrainNoise.
+// Texture arrays: unit 11 color (sRGB), unit 12 normal (linear), unit 13 roughness (red) and height (green), unit 14 weight mask.
+export const splatGlsl = `
+uniform float splatEnabled;
+uniform highp sampler2DArray splatColor;
+uniform highp sampler2DArray splatNormal;
+uniform highp sampler2DArray splatPacked;
+uniform sampler2D splatMask;
+uniform vec4 splatLayer[4];
+uniform vec4 splatTint[4];
+uniform vec4 splatSlope[4];
+uniform vec4 splatHeightRange[4];
+uniform float splatMaskChannel[4];
+uniform float splatMaskInvert[4];
+uniform vec4 splatBlend;
+uniform vec4 splatOptions;
+uniform vec4 splatMaskBounds;
+
+const mat2 SPLAT_ROTATION = mat2(0.8253, 0.5646, -0.5646, 0.8253);
+const float SPLAT_SECOND_SCALE = 0.58;
+const vec2 SPLAT_SECOND_OFFSET = vec2(0.37, 0.71);
+
+struct SplatPlane {
+ vec2 uv;
+ vec2 dx;
+ vec2 dy;
+ vec3 tangent;
+ vec3 bitangent;
+ vec3 face;
+};
+
+float splatRange(float value, float minimum, float maximum, float softness) {
+ float width = max(softness, 0.0001);
+ return smoothstep(minimum - width, minimum + width, value) * (1.0 - smoothstep(maximum - width, maximum + width, value));
+}
+
+float splatMaskValue(int layerIndex) {
+ float channel = splatMaskChannel[layerIndex];
+ if (channel < -0.5) return 1.0;
+ vec4 weights = vec4(vertexTint, 1.0);
+ if (splatOptions.y > 0.5) {
+ vec2 maskUv = (worldPosition.xz - splatMaskBounds.xy) / (splatMaskBounds.zw - splatMaskBounds.xy);
+ weights = texture(splatMask, clamp(maskUv, 0.0, 1.0));
+ }
+ float value = channel < 0.5 ? weights.r : (channel < 1.5 ? weights.g : (channel < 2.5 ? weights.b : weights.a));
+ return splatMaskInvert[layerIndex] > 0.5 ? 1.0 - value : value;
+}
+
+// Mixing two samples lowers contrast by this factor; dividing it back keeps the texture looking sharp.
+float splatContrastDivisor(float blend) {
+ return sqrt(blend * blend + (1.0 - blend) * (1.0 - blend));
+}
+
+vec4 splatTapTwoScale(highp sampler2DArray source, SplatPlane plane, float layer, float blend) {
+ vec4 first = textureGrad(source, vec3(plane.uv, layer), plane.dx, plane.dy);
+ if (blend < 0.003) return first;
+ vec2 secondUv = SPLAT_ROTATION * plane.uv * SPLAT_SECOND_SCALE + SPLAT_SECOND_OFFSET;
+ vec2 secondDx = SPLAT_ROTATION * plane.dx * SPLAT_SECOND_SCALE;
+ vec2 secondDy = SPLAT_ROTATION * plane.dy * SPLAT_SECOND_SCALE;
+ vec4 mixed = mix(first, textureGrad(source, vec3(secondUv, layer), secondDx, secondDy), blend);
+ vec4 mean = textureLod(source, vec3(0.5, 0.5, layer), 12.0);
+ return mean + (mixed - mean) / splatContrastDivisor(blend);
+}
+
+// The second sample is rotated, so its tangent-space normal must be rotated back before mixing.
+vec3 splatNormalTwoScale(SplatPlane plane, float layer, float blend) {
+ vec3 first = textureGrad(splatNormal, vec3(plane.uv, layer), plane.dx, plane.dy).xyz * 2.0 - 1.0;
+ if (blend < 0.003) return first;
+ vec2 secondUv = SPLAT_ROTATION * plane.uv * SPLAT_SECOND_SCALE + SPLAT_SECOND_OFFSET;
+ vec2 secondDx = SPLAT_ROTATION * plane.dx * SPLAT_SECOND_SCALE;
+ vec2 secondDy = SPLAT_ROTATION * plane.dy * SPLAT_SECOND_SCALE;
+ vec3 second = textureGrad(splatNormal, vec3(secondUv, layer), secondDx, secondDy).xyz * 2.0 - 1.0;
+ second.xy = second.xy * SPLAT_ROTATION;
+ vec3 mixed = mix(first, second, blend);
+ mixed.xy /= splatContrastDivisor(blend);
+ return mixed;
+}
+
+SplatPlane splatPlane(vec2 worldCoordinates, vec2 worldDx, vec2 worldDy, float scale, vec3 tangent, vec3 bitangent, vec3 face) {
+ return SplatPlane(worldCoordinates / scale, worldDx / scale, worldDy / scale, tangent, bitangent, face);
+}
+
+// Packed roughness (x) and height (y) of one layer, blended across the projections that cover this pixel.
+vec2 splatPackedSample(int layerIndex, SplatPlane top, SplatPlane sideX, SplatPlane sideZ, vec3 projection, float blend) {
+ float layer = float(layerIndex);
+ vec2 result = vec2(0.0);
+ if (projection.y > 0.002) result += splatTapTwoScale(splatPacked, top, layer, blend).xy * projection.y;
+ if (projection.x > 0.002) result += splatTapTwoScale(splatPacked, sideX, layer, blend).xy * projection.x;
+ if (projection.z > 0.002) result += splatTapTwoScale(splatPacked, sideZ, layer, blend).xy * projection.z;
+ return result;
+}
+
+vec3 splatTilt(vec3 tangentNormal, SplatPlane plane, float strength) {
+ return (plane.tangent * tangentNormal.x + plane.bitangent * tangentNormal.y) * strength;
+}
+
+// Color in xyz and the world-space tilt of the surface normal in the second vec3.
+void splatColorSample(int layerIndex, SplatPlane top, SplatPlane sideX, SplatPlane sideZ, vec3 projection, float blend, out vec3 color, out vec3 tilt) {
+ float layer = float(layerIndex);
+ float strength = splatLayer[layerIndex].y;
+ color = vec3(0.0);
+ tilt = vec3(0.0);
+ if (projection.y > 0.002) {
+ color += splatTapTwoScale(splatColor, top, layer, blend).rgb * projection.y;
+ tilt += splatTilt(splatNormalTwoScale(top, layer, blend), top, strength) * projection.y;
+ }
+ if (projection.x > 0.002) {
+ color += splatTapTwoScale(splatColor, sideX, layer, blend).rgb * projection.x;
+ tilt += splatTilt(splatNormalTwoScale(sideX, layer, blend), sideX, strength) * projection.x;
+ }
+ if (projection.z > 0.002) {
+ color += splatTapTwoScale(splatColor, sideZ, layer, blend).rgb * projection.z;
+ tilt += splatTilt(splatNormalTwoScale(sideZ, layer, blend), sideZ, strength) * projection.z;
+ }
+ color *= splatTint[layerIndex].rgb;
+}
+
+void applySplat(inout vec3 color, inout vec3 normal, inout float roughness, inout float cavity) {
+ int layerCount = int(splatOptions.z);
+ vec3 geometric = normal;
+ float slope = degrees(acos(clamp(geometric.y, -1.0, 1.0)));
+ float zSign = geometric.z < 0.0 ? -1.0 : 1.0;
+ float xSign = geometric.x < 0.0 ? -1.0 : 1.0;
+ // Image rows run downward, so a texture's v grows toward world -y on walls and toward +z seen from above.
+ vec2 topCoordinates = worldPosition.xz;
+ vec2 topDx = dFdx(worldPosition.xz);
+ vec2 topDy = dFdy(worldPosition.xz);
+ vec2 sideXCoordinates = vec2(-xSign * worldPosition.z, -worldPosition.y);
+ vec2 sideXDx = vec2(-xSign * dFdx(worldPosition.z), -dFdx(worldPosition.y));
+ vec2 sideXDy = vec2(-xSign * dFdy(worldPosition.z), -dFdy(worldPosition.y));
+ vec2 sideZCoordinates = vec2(zSign * worldPosition.x, -worldPosition.y);
+ vec2 sideZDx = vec2(zSign * dFdx(worldPosition.x), -dFdx(worldPosition.y));
+ vec2 sideZDy = vec2(zSign * dFdy(worldPosition.x), -dFdy(worldPosition.y));
+ vec3 up = vec3(0.0, 1.0, 0.0);
+ vec3 topTangent = vec3(1.0, 0.0, 0.0);
+ vec3 topBitangent = vec3(0.0, 0.0, -1.0);
+ vec3 sideXTangent = vec3(0.0, 0.0, -xSign);
+ vec3 sideZTangent = vec3(zSign, 0.0, 0.0);
+ vec3 sideUp = vec3(0.0, 1.0, 0.0);
+
+ 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);
+
+ float weights[4] = float[4](0.0, 0.0, 0.0, 0.0);
+ float covered = 0.0;
+ for (int index = 0; index < 4; index++) {
+ 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);
+ weight *= splatMaskValue(index);
+ weights[index] = weight;
+ covered = max(covered, weight);
+ }
+ for (int index = 0; index < 4; index++) {
+ if (index >= layerCount) break;
+ if (splatLayer[index].w < 0.5) weights[index] = 1.0 - covered;
+ }
+
+ float triplanarAmount = smoothstep(splatBlend.z, splatBlend.w, slope);
+ vec2 sideShare = pow(abs(geometric.xz), vec2(4.0));
+ sideShare /= max(sideShare.x + sideShare.y, 0.0001);
+
+ vec2 packedSamples[4] = vec2[4](vec2(0.5), vec2(0.5), vec2(0.5), vec2(0.5));
+ vec3 projections[4] = vec3[4](vec3(0.0, 1.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 1.0, 0.0));
+ float scores[4] = float[4](-1.0, -1.0, -1.0, -1.0);
+ float highestScore = -1.0;
+ for (int index = 0; index < 4; index++) {
+ if (index >= layerCount) break;
+ if (weights[index] < 0.002) continue;
+ float scale = splatLayer[index].x;
+ float tri = splatLayer[index].z > 0.5 ? triplanarAmount : 0.0;
+ vec3 projection = vec3(tri * sideShare.x, 1.0 - tri, tri * sideShare.y);
+ SplatPlane top = splatPlane(topCoordinates, topDx, topDy, scale, topTangent, topBitangent, up);
+ SplatPlane sideX = splatPlane(sideXCoordinates, sideXDx, sideXDy, scale, sideXTangent, sideUp, vec3(xSign, 0.0, 0.0));
+ SplatPlane sideZ = splatPlane(sideZCoordinates, sideZDx, sideZDy, scale, sideZTangent, sideUp, vec3(0.0, 0.0, zSign));
+ projections[index] = projection;
+ packedSamples[index] = splatPackedSample(index, top, sideX, sideZ, projection, blend);
+ scores[index] = weights[index] + packedSamples[index].y * splatBlend.y;
+ highestScore = max(highestScore, scores[index]);
+ }
+
+ float total = 0.0;
+ for (int index = 0; index < 4; index++) {
+ if (index >= layerCount) break;
+ float weight = scores[index] < 0.0 ? 0.0 : max(scores[index] - (highestScore - splatBlend.x), 0.0) * step(0.002, weights[index]);
+ weights[index] = weight;
+ total += weight;
+ }
+ total = max(total, 0.0001);
+
+ vec3 blendedColor = vec3(0.0);
+ vec3 blendedTilt = vec3(0.0);
+ float blendedRoughness = 0.0;
+ float blendedHeight = 0.0;
+ for (int index = 0; index < 4; index++) {
+ if (index >= layerCount) break;
+ float weight = weights[index] / total;
+ if (weight < 0.004) continue;
+ float scale = splatLayer[index].x;
+ SplatPlane top = splatPlane(topCoordinates, topDx, topDy, scale, topTangent, topBitangent, up);
+ SplatPlane sideX = splatPlane(sideXCoordinates, sideXDx, sideXDy, scale, sideXTangent, sideUp, vec3(xSign, 0.0, 0.0));
+ SplatPlane sideZ = splatPlane(sideZCoordinates, sideZDx, sideZDy, scale, sideZTangent, sideUp, vec3(0.0, 0.0, zSign));
+ vec3 layerColor;
+ vec3 layerTilt;
+ splatColorSample(index, top, sideX, sideZ, projections[index], blend, layerColor, layerTilt);
+ blendedColor += layerColor * weight;
+ blendedTilt += layerTilt * weight;
+ blendedRoughness += packedSamples[index].x * weight;
+ blendedHeight += packedSamples[index].y * weight;
+ }
+
+ color *= blendedColor * macro * dryTint;
+ 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
new file mode 100644
index 00000000..86187a4e
--- /dev/null
+++ b/src/splat.js
@@ -0,0 +1,214 @@
+// Validation, GPU parameter packing and texel packing for the multi-layer splat ground material.
+// The renderer owns the GL objects; everything here is plain data so it can be tested without a GPU.
+import { estimateTextureBytes } from './budget.js';
+
+export const SPLAT_MAXIMUM_LAYERS = 4;
+export const SPLAT_LAYER_CHANNELS = Object.freeze(['color', 'normal', 'roughness', 'height']);
+const MASK_CHANNELS = Object.freeze({ r: 0, g: 1, b: 2, a: 3 });
+const DEFAULT_SCALE_METRES = 4;
+const DEFAULT_SPLAT = Object.freeze({
+ heightBlend: 0.22,
+ heightInfluence: 1,
+ triplanarStart: 38,
+ triplanarEnd: 52,
+ antiTiling: 1,
+ cavity: 0.55,
+});
+const DEFAULT_RULE_SOFTNESS = Object.freeze({ slope: 4, height: 1.5 });
+
+function imageSize(image) {
+ const width = image?.naturalWidth ?? image?.width;
+ const height = image?.naturalHeight ?? image?.height;
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) throw new Error('Splat texture image dimensions are invalid.');
+ return Math.max(width, height);
+}
+
+function requireFiniteNumber(value, name) {
+ if (typeof value !== 'number' || !Number.isFinite(value)) throw new TypeError(`${name} must be a finite number.`);
+ return value;
+}
+
+function requireRange(range, name, lowest, highest) {
+ if (!Array.isArray(range) || range.length !== 2) throw new TypeError(`${name} must be a [minimum, maximum] pair.`);
+ const [minimum, maximum] = range;
+ requireFiniteNumber(minimum, `${name}[0]`);
+ requireFiniteNumber(maximum, `${name}[1]`);
+ if (minimum > maximum) throw new RangeError(`${name} minimum must not exceed its maximum.`);
+ if (minimum < lowest || maximum > highest) throw new RangeError(`${name} must stay within ${lowest} and ${highest}.`);
+}
+
+function validateLayer(layer, index) {
+ if (!layer || typeof layer !== 'object') throw new TypeError(`layers[${index}] must be an object.`);
+ const present = SPLAT_LAYER_CHANNELS.filter(channel => layer[channel]);
+ if (present.length === 0) throw new Error(`layers[${index}] needs at least one of ${SPLAT_LAYER_CHANNELS.join(', ')}.`);
+ for (const channel of present) {
+ imageSize(layer[channel].image);
+ const colorSpace = layer[channel].colorSpace ?? (channel === 'color' ? 'srgb' : 'linear');
+ const expected = channel === 'color' ? 'srgb' : 'linear';
+ if (colorSpace !== expected) throw new Error(`layers[${index}].${channel} requires a ${expected} texture descriptor.`);
+ }
+ const scale = layer.scale ?? DEFAULT_SCALE_METRES;
+ if (requireFiniteNumber(scale, `layers[${index}].scale`) <= 0) throw new RangeError(`layers[${index}].scale must be positive.`);
+ if (layer.tint !== undefined && (!Array.isArray(layer.tint) || layer.tint.length !== 3 || !layer.tint.every(Number.isFinite))) throw new TypeError(`layers[${index}].tint must be three finite numbers.`);
+ const normalStrength = layer.normalStrength ?? 1;
+ if (requireFiniteNumber(normalStrength, `layers[${index}].normalStrength`) < 0) throw new RangeError(`layers[${index}].normalStrength must not be negative.`);
+}
+
+function validateRule(rule, index, splat) {
+ if (rule === undefined || rule === null) return;
+ if (typeof rule !== 'object') throw new TypeError(`splat.rules[${index}] must be an object.`);
+ if (rule.slope !== undefined) requireRange(rule.slope, `splat.rules[${index}].slope`, 0, 90);
+ if (rule.height !== undefined) requireRange(rule.height, `splat.rules[${index}].height`, -1e6, 1e6);
+ for (const field of ['slopeSoftness', 'heightSoftness']) {
+ if (rule[field] !== undefined && requireFiniteNumber(rule[field], `splat.rules[${index}].${field}`) < 0) throw new RangeError(`splat.rules[${index}].${field} must not be negative.`);
+ }
+ if (rule.mask !== undefined) {
+ if (!Object.hasOwn(MASK_CHANNELS, rule.mask)) throw new RangeError(`splat.rules[${index}].mask must be r, g, b or a.`);
+ if (rule.mask === 'a' && !splat.maskMap) throw new Error('Mask channel a needs splat.maskMap; vertex colours have only r, g and b.');
+ }
+}
+
+function validateMaskMap(splat) {
+ if (!splat.maskMap) return;
+ imageSize(splat.maskMap.image);
+ if ((splat.maskMap.colorSpace ?? 'srgb') !== 'linear') throw new Error('splat.maskMap requires a linear texture descriptor.');
+ if (!Array.isArray(splat.maskBounds) || splat.maskBounds.length !== 4 || !splat.maskBounds.every(Number.isFinite)) throw new TypeError('splat.maskBounds must be [minimumX, minimumZ, maximumX, maximumZ].');
+ if (splat.maskBounds[2] <= splat.maskBounds[0] || splat.maskBounds[3] <= splat.maskBounds[1]) throw new RangeError('splat.maskBounds must have a positive extent.');
+}
+
+/** Throws a descriptive error unless the material's layers and splat rules can be drawn. */
+export function validateSplatMaterial(material) {
+ if (!material.layers && !material.splat) return;
+ const layers = material.layers;
+ if (!Array.isArray(layers) || layers.length < 1 || layers.length > SPLAT_MAXIMUM_LAYERS) throw new RangeError(`material.layers must hold 1 to ${SPLAT_MAXIMUM_LAYERS} layers.`);
+ layers.forEach(validateLayer);
+ const splat = material.splat ?? {};
+ 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']) {
+ 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.');
+ for (const field of ['triplanarStart', 'triplanarEnd']) {
+ if (splat[field] !== undefined) requireRange([splat[field], splat[field]], `splat.${field}`, 0, 90);
+ }
+ if ((splat.triplanarStart ?? DEFAULT_SPLAT.triplanarStart) > (splat.triplanarEnd ?? DEFAULT_SPLAT.triplanarEnd)) throw new RangeError('splat.triplanarStart must not exceed splat.triplanarEnd.');
+ if (splat.textureSize !== undefined && (!Number.isInteger(splat.textureSize) || splat.textureSize < 4)) throw new RangeError('splat.textureSize must be an integer of at least 4.');
+ if (material.map || material.normalMap || material.metallicRoughnessMap || material.occlusionMap) throw new Error('Splat materials replace base, normal, roughness and occlusion maps; remove them.');
+}
+
+/** Identity values that decide whether two materials can share one draw call. */
+export function splatBatchState(material) {
+ return [material.layers ?? null, material.splat ?? null];
+}
+
+/** Bytes of the three texture arrays (color, normal, roughness+height) with mipmaps, plus the weight texture. */
+export function splatTextureBytes(size, layerCount, maskSize = 0) {
+ const arrays = 3 * layerCount * estimateTextureBytes(size, size);
+ return arrays + (maskSize ? estimateTextureBytes(maskSize, maskSize) : 0);
+}
+
+/** Common layer resolution: the largest source, capped by the GPU limit and by `splat.textureSize`. */
+export function resolveSplatSize(material, maximumTextureSize) {
+ let size = 1;
+ for (const layer of material.layers) {
+ for (const channel of SPLAT_LAYER_CHANNELS) {
+ if (layer[channel]) size = Math.max(size, imageSize(layer[channel].image));
+ }
+ }
+ return Math.min(size, maximumTextureSize, material.splat?.textureSize ?? Infinity);
+}
+
+function writeRule(rule, index, parameters, layer) {
+ const slope = rule?.slope;
+ const height = rule?.height;
+ const maskIndex = rule?.mask === undefined ? -1 : MASK_CHANNELS[rule.mask];
+ parameters.slope.set([slope?.[0] ?? 0, slope?.[1] ?? 90, rule?.slopeSoftness ?? DEFAULT_RULE_SOFTNESS.slope, slope ? 1 : 0], index * 4);
+ parameters.height.set([height?.[0] ?? -1e6, height?.[1] ?? 1e6, rule?.heightSoftness ?? DEFAULT_RULE_SOFTNESS.height, height ? 1 : 0], index * 4);
+ parameters.mask[index] = maskIndex;
+ parameters.maskInvert[index] = rule?.invertMask ? 1 : 0;
+ const hasRules = Boolean(slope || height || maskIndex >= 0);
+ parameters.layer.set([layer.scale ?? DEFAULT_SCALE_METRES, layer.normalStrength ?? 1, layer.triplanar ? 1 : 0, hasRules ? 1 : 0], index * 4);
+ parameters.tint.set([...(layer.tint ?? [1, 1, 1]), 0], index * 4);
+}
+
+/** Flat uniform data for the shader. Layers without rules take whatever the other layers leave. */
+export function packSplatParameters(material) {
+ const splat = { ...DEFAULT_SPLAT, ...material.splat };
+ const layerCount = material.layers.length;
+ const parameters = {
+ layer: new Float32Array(16),
+ tint: new Float32Array(16),
+ slope: new Float32Array(16),
+ height: new Float32Array(16),
+ mask: new Float32Array(4).fill(-1),
+ maskInvert: new Float32Array(4),
+ 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]),
+ };
+ material.layers.forEach((layer, index) => writeRule(material.splat?.rules?.[index], index, parameters, layer));
+ return parameters;
+}
+
+/** Nearest-neighbour resample for decoded images that already carry RGBA bytes (Node, tests). */
+function resampleBytes(image, size) {
+ const output = new Uint8Array(size * size * 4);
+ for (let row = 0; row < size; row++) {
+ const sourceRow = Math.min(image.height - 1, Math.floor(row * image.height / size));
+ for (let column = 0; column < size; column++) {
+ const sourceColumn = Math.min(image.width - 1, Math.floor(column * image.width / size));
+ const source = (sourceRow * image.width + sourceColumn) * 4;
+ output.set(image.data.subarray(source, source + 4), (row * size + column) * 4);
+ }
+ }
+ return output;
+}
+
+function createScratchCanvas(size) {
+ if (typeof OffscreenCanvas !== 'undefined') return new OffscreenCanvas(size, size);
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ return canvas;
+}
+
+/** RGBA bytes of `image` resized to size by size. Browser images go through a 2D canvas. */
+export function readImagePixels(image, size) {
+ if (image.data && image.width && image.height) return resampleBytes(image, size);
+ const canvas = createScratchCanvas(size);
+ const context = canvas.getContext('2d', { willReadFrequently: true });
+ context.imageSmoothingQuality = 'high';
+ context.drawImage(image, 0, 0, size, size);
+ return new Uint8Array(context.getImageData(0, 0, size, size).data.buffer);
+}
+
+const NEUTRAL_TEXEL = Object.freeze({ color: [128, 128, 128, 255], normal: [128, 128, 255, 255], roughnessHeight: [255, 128, 0, 255] });
+
+function fillLayer(target, layerIndex, size, texel) {
+ const layerBytes = size * size * 4;
+ const start = layerIndex * layerBytes;
+ for (let offset = 0; offset < layerBytes; offset += 4) target.set(texel, start + offset);
+}
+
+/** Texel data for the three texture arrays: color, normal and roughness (red) with height (green). */
+export function buildSplatPixels(layers, size, readPixels = readImagePixels) {
+ const layerBytes = size * size * 4;
+ const color = new Uint8Array(layerBytes * layers.length);
+ const normal = new Uint8Array(layerBytes * layers.length);
+ const packed = new Uint8Array(layerBytes * layers.length);
+ layers.forEach((layer, layerIndex) => {
+ const start = layerIndex * layerBytes;
+ if (layer.color) color.set(readPixels(layer.color.image, size), start); else fillLayer(color, layerIndex, size, NEUTRAL_TEXEL.color);
+ if (layer.normal) normal.set(readPixels(layer.normal.image, size), start); else fillLayer(normal, layerIndex, size, NEUTRAL_TEXEL.normal);
+ fillLayer(packed, layerIndex, size, NEUTRAL_TEXEL.roughnessHeight);
+ const roughness = layer.roughness ? readPixels(layer.roughness.image, size) : null;
+ const height = layer.height ? readPixels(layer.height.image, size) : null;
+ for (let offset = 0; offset < layerBytes; offset += 4) {
+ if (roughness) packed[start + offset] = roughness[offset];
+ if (height) packed[start + offset + 1] = height[offset];
+ }
+ });
+ return { color, normal, packed };
+}
diff --git a/src/terrain.js b/src/terrain.js
new file mode 100644
index 00000000..4282277e
--- /dev/null
+++ b/src/terrain.js
@@ -0,0 +1,338 @@
+// Chunked heightfield terrain with distance-based level of detail and exact height queries.
+// The finest grid is sampled once. Every mesh vertex reads that grid, and heightAt() interpolates it over the same
+// triangles as the finest mesh, so vegetation and vehicles sit on the rendered surface.
+
+const DEFAULT_NOISE = Object.freeze({
+ amplitude: 14,
+ mountainAmplitude: 46,
+ featureSize: 160,
+ octaves: 6,
+ gain: 0.5,
+ lacunarity: 2,
+ warp: 36,
+ warpFeatureSize: 90,
+ baseHeight: 0,
+});
+const OCTAVE_ROTATION = Object.freeze({ cosine: 0.8, sine: 0.6 });
+const DEFAULT_MATERIAL = Object.freeze({ color: [1, 1, 1], metallic: 0, roughness: 1, emission: 0 });
+
+function clamp(value, minimum, maximum) {
+ return Math.min(maximum, Math.max(minimum, value));
+}
+
+function smoothstep(low, high, value) {
+ const fraction = clamp((value - low) / (high - low), 0, 1);
+ return fraction * fraction * (3 - 2 * fraction);
+}
+
+function hashLattice(cellX, cellZ, seed) {
+ let hash = Math.imul(cellX, 374761393) ^ Math.imul(cellZ, 668265263) ^ Math.imul(seed | 0, 1597334677);
+ hash = Math.imul(hash ^ (hash >>> 13), 1274126177);
+ hash ^= hash >>> 16;
+ return (hash >>> 0) / 4294967296;
+}
+
+/** Value noise in [-1, 1] with its analytic gradient, written into `output` as [value, dx, dz]. */
+function sampleNoise(pointX, pointZ, seed, output) {
+ const cellX = Math.floor(pointX);
+ const cellZ = Math.floor(pointZ);
+ const fractionX = pointX - cellX;
+ const fractionZ = pointZ - cellZ;
+ const blendX = fractionX * fractionX * fractionX * (fractionX * (fractionX * 6 - 15) + 10);
+ const blendZ = fractionZ * fractionZ * fractionZ * (fractionZ * (fractionZ * 6 - 15) + 10);
+ const slopeX = 30 * fractionX * fractionX * (fractionX - 1) * (fractionX - 1);
+ const slopeZ = 30 * fractionZ * fractionZ * (fractionZ - 1) * (fractionZ - 1);
+ const lowerLeft = hashLattice(cellX, cellZ, seed);
+ const lowerRight = hashLattice(cellX + 1, cellZ, seed);
+ const upperLeft = hashLattice(cellX, cellZ + 1, seed);
+ const upperRight = hashLattice(cellX + 1, cellZ + 1, seed);
+ const crossTerm = lowerLeft - lowerRight - upperLeft + upperRight;
+ const value = lowerLeft + (lowerRight - lowerLeft) * blendX + (upperLeft - lowerLeft) * blendZ + crossTerm * blendX * blendZ;
+ output[0] = value * 2 - 1;
+ output[1] = 2 * slopeX * ((lowerRight - lowerLeft) + crossTerm * blendZ);
+ output[2] = 2 * slopeZ * ((upperLeft - lowerLeft) + crossTerm * blendX);
+}
+
+// Slopes damp the finer octaves, which leaves smooth flanks and rough crests like eroded ground.
+function erosionNoise(worldX, worldZ, noise, seed, scratch) {
+ let pointX = worldX / noise.featureSize;
+ let pointZ = worldZ / noise.featureSize;
+ let sum = 0;
+ let amplitude = 1;
+ let amplitudeTotal = 0;
+ let gradientX = 0;
+ let gradientZ = 0;
+ for (let octave = 0; octave < noise.octaves; octave++) {
+ sampleNoise(pointX, pointZ, seed + octave * 17, scratch);
+ gradientX += scratch[1];
+ gradientZ += scratch[2];
+ sum += amplitude * scratch[0] / (1 + gradientX * gradientX + gradientZ * gradientZ);
+ amplitudeTotal += amplitude;
+ amplitude *= noise.gain;
+ const rotatedX = (OCTAVE_ROTATION.cosine * pointX - OCTAVE_ROTATION.sine * pointZ) * noise.lacunarity;
+ pointZ = (OCTAVE_ROTATION.sine * pointX + OCTAVE_ROTATION.cosine * pointZ) * noise.lacunarity;
+ pointX = rotatedX;
+ }
+ return sum / amplitudeTotal;
+}
+
+// Each ridge only feeds the next octave where it is strong, which carves sharp valleys between peaks.
+function ridgedNoise(worldX, worldZ, noise, seed, scratch) {
+ let pointX = worldX / noise.featureSize;
+ let pointZ = worldZ / noise.featureSize;
+ let sum = 0;
+ let amplitude = 1;
+ let amplitudeTotal = 0;
+ let weight = 1;
+ for (let octave = 0; octave < noise.octaves; octave++) {
+ sampleNoise(pointX, pointZ, seed + 101 + octave * 13, scratch);
+ const ridge = (1 - Math.abs(scratch[0])) ** 2 * weight;
+ weight = clamp(ridge * 2, 0, 1);
+ sum += ridge * amplitude;
+ amplitudeTotal += amplitude;
+ amplitude *= noise.gain;
+ const rotatedX = (OCTAVE_ROTATION.cosine * pointX - OCTAVE_ROTATION.sine * pointZ) * noise.lacunarity;
+ pointZ = (OCTAVE_ROTATION.sine * pointX + OCTAVE_ROTATION.cosine * pointZ) * noise.lacunarity;
+ pointX = rotatedX;
+ }
+ return sum / amplitudeTotal;
+}
+
+/** Height function (x, z) -> metres from noise options: domain warped hills blended into ridged mountains. */
+export function createNoiseHeight(options = {}, seed = 1) {
+ const noise = { ...DEFAULT_NOISE, ...options };
+ const scratch = new Float64Array(3);
+ const warpScratch = new Float64Array(3);
+ const maskNoise = { ...noise, featureSize: noise.featureSize * 2.6, octaves: 2 };
+ const mountainMask = options.mountainMask ?? ((worldX, worldZ) => smoothstep(0.05, 0.4, erosionNoise(worldX, worldZ, maskNoise, seed + 7, scratch)));
+ return (worldX, worldZ) => {
+ sampleNoise(worldX / noise.warpFeatureSize, worldZ / noise.warpFeatureSize, seed + 31, warpScratch);
+ const warpedX = worldX + warpScratch[0] * noise.warp;
+ const warpedZ = worldZ + warpScratch[0] * noise.warp * 0.7 + warpScratch[1] * noise.warp * 0.2;
+ const hills = erosionNoise(warpedX, warpedZ, noise, seed, scratch) * noise.amplitude;
+ const mask = mountainMask(worldX, worldZ);
+ if (mask <= 0) return noise.baseHeight + hills;
+ const mountains = ridgedNoise(warpedX, warpedZ, { ...noise, featureSize: noise.featureSize * 1.3 }, seed, scratch) * noise.mountainAmplitude;
+ return noise.baseHeight + hills * (1 - mask) + (hills * 0.4 + mountains) * mask;
+ };
+}
+
+/** Converts the red channel of an ImageData-like object to a square height array in metres. */
+export function heightmapFromImageData(imageData, amplitude = 1) {
+ if (imageData.width !== imageData.height) throw new RangeError('Heightmap images must be square.');
+ const heights = new Float32Array(imageData.width * imageData.height);
+ for (let index = 0; index < heights.length; index++) heights[index] = imageData.data[index * 4] / 255 * amplitude;
+ return heights;
+}
+
+function heightFromArray(heights, size) {
+ const side = Math.round(Math.sqrt(heights.length));
+ if (side * side !== heights.length || side < 2) throw new RangeError('A height array must be square with at least 2 by 2 samples.');
+ return (worldX, worldZ) => {
+ const gridX = clamp((worldX / size + 0.5) * (side - 1), 0, side - 1);
+ const gridZ = clamp((worldZ / size + 0.5) * (side - 1), 0, side - 1);
+ const cellX = Math.min(Math.floor(gridX), side - 2);
+ const cellZ = Math.min(Math.floor(gridZ), side - 2);
+ const fractionX = gridX - cellX;
+ const fractionZ = gridZ - cellZ;
+ const lower = heights[cellZ * side + cellX] * (1 - fractionX) + heights[cellZ * side + cellX + 1] * fractionX;
+ const upper = heights[(cellZ + 1) * side + cellX] * (1 - fractionX) + heights[(cellZ + 1) * side + cellX + 1] * fractionX;
+ return lower * (1 - fractionZ) + upper * fractionZ;
+ };
+}
+
+function resolveHeightFunction(height, size, seed) {
+ if (typeof height === 'function') return height;
+ if (height instanceof Float32Array) return heightFromArray(height, size);
+ return createNoiseHeight(height ?? {}, seed);
+}
+
+function validateOptions({ size, resolution, chunks, levels }) {
+ if (!(size > 0) || !Number.isFinite(size)) throw new RangeError('size must be a positive number of metres.');
+ if (!Number.isInteger(chunks) || chunks < 1) throw new RangeError('chunks must be a positive integer.');
+ if (!Number.isInteger(levels) || levels < 1) throw new RangeError('levels must be a positive integer.');
+ if (!Number.isInteger(resolution) || resolution < 1 || resolution % (2 ** (levels - 1)) !== 0) {
+ throw new RangeError(`resolution must be a positive integer divisible by 2^(levels - 1) = ${2 ** (levels - 1)}.`);
+ }
+}
+
+const SIDES = Object.freeze(['west', 'east', 'north', 'south']);
+
+/**
+ * Returns { parts, heightAt, normalAt, bounds, update, triangleCount }.
+ * Ground spans x and z from -size / 2 to size / 2. Call update(eye) each frame (or when the camera moves) and, when it
+ * returns a non-empty list, pass the scene parts to renderer.replaceParts.
+ */
+export function createTerrain({ size = 512, resolution = 32, chunks = 8, levels = 4, height, seed = 1, material = DEFAULT_MATERIAL, lodDistance, eye } = {}) {
+ validateOptions({ size, resolution, chunks, levels });
+ const heightFunction = resolveHeightFunction(height, size, seed);
+ const chunkSize = size / chunks;
+ const gridCells = chunks * resolution;
+ const gridSide = gridCells + 1;
+ const spacing = size / gridCells;
+ const origin = -size / 2;
+ const heights = new Float32Array(gridSide * gridSide);
+ let lowest = Infinity;
+ let highest = -Infinity;
+ for (let row = 0; row < gridSide; row++) {
+ for (let column = 0; column < gridSide; column++) {
+ const value = heightFunction(origin + column * spacing, origin + row * spacing);
+ if (!Number.isFinite(value)) throw new RangeError('Height function returned a non-finite value.');
+ heights[row * gridSide + column] = value;
+ lowest = Math.min(lowest, heights[row * gridSide + column]);
+ highest = Math.max(highest, heights[row * gridSide + column]);
+ }
+ }
+ const bounds = { min: [origin, lowest, origin], max: [-origin, highest, -origin] };
+ const nearDistance = lodDistance ?? chunkSize * 1.6;
+
+ const gridHeight = (column, row) => heights[clamp(row, 0, gridCells) * gridSide + clamp(column, 0, gridCells)];
+
+ function gridNormal(column, row, step, target, offset) {
+ const slopeX = (gridHeight(column + step, row) - gridHeight(column - step, row)) / (2 * step * spacing);
+ const slopeZ = (gridHeight(column, row + step) - gridHeight(column, row - step)) / (2 * step * spacing);
+ const inverseLength = 1 / Math.hypot(slopeX, 1, slopeZ);
+ target[offset] = -slopeX * inverseLength;
+ target[offset + 1] = inverseLength;
+ target[offset + 2] = -slopeZ * inverseLength;
+ }
+
+ function locate(worldX, worldZ) {
+ const gridX = clamp((worldX - origin) / spacing, 0, gridCells);
+ const gridZ = clamp((worldZ - origin) / spacing, 0, gridCells);
+ const column = Math.min(Math.floor(gridX), gridCells - 1);
+ const row = Math.min(Math.floor(gridZ), gridCells - 1);
+ return { column, row, fractionX: gridX - column, fractionZ: gridZ - row };
+ }
+
+ // The finest mesh splits every cell along the (0,0)-(1,1) diagonal; heightAt walks the same triangles.
+ function heightAt(worldX, worldZ) {
+ const { column, row, fractionX, fractionZ } = locate(worldX, worldZ);
+ const corner00 = gridHeight(column, row);
+ const corner10 = gridHeight(column + 1, row);
+ const corner01 = gridHeight(column, row + 1);
+ const corner11 = gridHeight(column + 1, row + 1);
+ if (fractionX >= fractionZ) return corner00 + fractionX * (corner10 - corner00) + fractionZ * (corner11 - corner10);
+ return corner00 + fractionX * (corner11 - corner01) + fractionZ * (corner01 - corner00);
+ }
+
+ function normalAt(worldX, worldZ) {
+ const { column, row, fractionX, fractionZ } = locate(worldX, worldZ);
+ const corners = new Float32Array(12);
+ gridNormal(column, row, 1, corners, 0);
+ gridNormal(column + 1, row, 1, corners, 3);
+ gridNormal(column, row + 1, 1, corners, 6);
+ gridNormal(column + 1, row + 1, 1, corners, 9);
+ const normal = [0, 0, 0];
+ for (let axis = 0; axis < 3; axis++) {
+ const lower = corners[axis] * (1 - fractionX) + corners[3 + axis] * fractionX;
+ const upper = corners[6 + axis] * (1 - fractionX) + corners[9 + axis] * fractionX;
+ normal[axis] = lower * (1 - fractionZ) + upper * fractionZ;
+ }
+ const length = Math.hypot(...normal);
+ return normal.map(component => component / length);
+ }
+
+ /** Mesh of one chunk. An edge shared with a coarser neighbour is snapped to that neighbour's edge, so no crack opens. */
+ function buildChunkGeometry(chunkColumn, chunkRow, level, edgeLevels) {
+ const step = 2 ** level;
+ const cells = resolution / step;
+ const side = cells + 1;
+ const positions = new Float32Array(side * side * 3);
+ const normals = new Float32Array(side * side * 3);
+ const uvs = new Float32Array(side * side * 2);
+ const firstColumn = chunkColumn * resolution;
+ const firstRow = chunkRow * resolution;
+ for (let row = 0; row < side; row++) {
+ for (let column = 0; column < side; column++) {
+ const vertex = row * side + column;
+ const gridColumn = firstColumn + column * step;
+ const gridRow = firstRow + row * step;
+ const worldX = origin + gridColumn * spacing;
+ const worldZ = origin + gridRow * spacing;
+ positions.set([worldX, snappedHeight(column, row, side, step, gridColumn, gridRow, edgeLevels, level), worldZ], vertex * 3);
+ gridNormal(gridColumn, gridRow, step, normals, vertex * 3);
+ uvs.set([worldX, worldZ], vertex * 2);
+ }
+ }
+ const indices = new Uint32Array(cells * cells * 6);
+ let cursor = 0;
+ for (let row = 0; row < cells; row++) {
+ for (let column = 0; column < cells; column++) {
+ const corner00 = row * side + column;
+ const corner10 = corner00 + 1;
+ const corner01 = corner00 + side;
+ const corner11 = corner01 + 1;
+ indices.set([corner00, corner11, corner10, corner00, corner01, corner11], cursor);
+ cursor += 6;
+ }
+ }
+ return { positions, normals, uvs, indices };
+ }
+
+ function snappedHeight(column, row, side, step, gridColumn, gridRow, edgeLevels, level) {
+ const last = side - 1;
+ const alongX = row === 0 ? 'north' : row === last ? 'south' : null;
+ const alongZ = column === 0 ? 'west' : column === last ? 'east' : null;
+ if (alongX && column % (2 ** (edgeLevels[alongX] - level)) !== 0) {
+ return interpolateEdge(column, 2 ** (edgeLevels[alongX] - level), (index) => gridHeight(gridColumn + (index - column) * step, gridRow));
+ }
+ if (alongZ && row % (2 ** (edgeLevels[alongZ] - level)) !== 0) {
+ return interpolateEdge(row, 2 ** (edgeLevels[alongZ] - level), (index) => gridHeight(gridColumn, gridRow + (index - row) * step));
+ }
+ return gridHeight(gridColumn, gridRow);
+ }
+
+ function interpolateEdge(index, coarseStep, heightAtIndex) {
+ const lowerIndex = Math.floor(index / coarseStep) * coarseStep;
+ const fraction = (index - lowerIndex) / coarseStep;
+ return heightAtIndex(lowerIndex) * (1 - fraction) + heightAtIndex(lowerIndex + coarseStep) * fraction;
+ }
+
+ const chunkStates = [];
+ const parts = [];
+ for (let chunkRow = 0; chunkRow < chunks; chunkRow++) {
+ for (let chunkColumn = 0; chunkColumn < chunks; chunkColumn++) {
+ const state = { chunkColumn, chunkRow, level: -1, edgeLevels: null, centerX: origin + (chunkColumn + 0.5) * chunkSize, centerZ: origin + (chunkRow + 0.5) * chunkSize };
+ state.part = { name: `Terrain chunk ${chunkColumn},${chunkRow}`, geometry: null, matrix: identityMatrix(), material };
+ chunkStates.push(state);
+ parts.push(state.part);
+ }
+ }
+
+ const chunkAt = (column, row) => (column < 0 || row < 0 || column >= chunks || row >= chunks ? null : chunkStates[row * chunks + column]);
+
+ function levelFor(state, eyePosition) {
+ const groundHeight = heightAt(clamp(eyePosition[0], origin, -origin), clamp(eyePosition[2], origin, -origin));
+ const distance = Math.hypot(eyePosition[0] - state.centerX, eyePosition[1] - groundHeight, eyePosition[2] - state.centerZ) - chunkSize * 0.5;
+ if (distance <= nearDistance) return 0;
+ return Math.min(levels - 1, Math.floor(Math.log2(distance / nearDistance)) + 1);
+ }
+
+ let triangleTotal = 0;
+ function update(eyePosition) {
+ if (!Array.isArray(eyePosition) && !(eyePosition instanceof Float32Array)) throw new TypeError('update needs an eye position [x, y, z].');
+ for (const state of chunkStates) state.targetLevel = levelFor(state, eyePosition);
+ const changed = [];
+ for (const state of chunkStates) {
+ const neighbours = [chunkAt(state.chunkColumn - 1, state.chunkRow), chunkAt(state.chunkColumn + 1, state.chunkRow), chunkAt(state.chunkColumn, state.chunkRow - 1), chunkAt(state.chunkColumn, state.chunkRow + 1)];
+ const edgeLevels = Object.fromEntries(SIDES.map((side, index) => [side, Math.max(state.targetLevel, neighbours[index]?.targetLevel ?? state.targetLevel)]));
+ const unchanged = state.level === state.targetLevel && SIDES.every(side => state.edgeLevels?.[side] === edgeLevels[side]);
+ if (unchanged) continue;
+ if (state.part.geometry) triangleTotal -= state.part.geometry.indices.length / 3;
+ state.part.geometry = buildChunkGeometry(state.chunkColumn, state.chunkRow, state.targetLevel, edgeLevels);
+ triangleTotal += state.part.geometry.indices.length / 3;
+ state.level = state.targetLevel;
+ state.edgeLevels = edgeLevels;
+ changed.push(state.part);
+ }
+ return changed;
+ }
+
+ update(eye ?? [0, highest + size * 0.5, 0]);
+ return { parts, heightAt, normalAt, bounds, update, get triangleCount() { return triangleTotal; }, chunkSize, resolution, levels, chunkLevels: () => chunkStates.map(state => state.level) };
+}
+
+function identityMatrix() {
+ return new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+}
diff --git a/src/texture-set.js b/src/texture-set.js
new file mode 100644
index 00000000..be18a9f6
--- /dev/null
+++ b/src/texture-set.js
@@ -0,0 +1,54 @@
+// Loads one scanned material (color, normal, roughness, height) as texture descriptors.
+// The descriptors have the same shape as `material.map`, so they work for splat layers and plain maps alike.
+
+export const TEXTURE_SET_CHANNELS = Object.freeze(['color', 'normal', 'roughness', 'height']);
+
+const CHANNEL_COLOR_SPACES = Object.freeze({ color: 'srgb', normal: 'linear', roughness: 'linear', height: 'linear' });
+
+async function fetchBlob(url) {
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`Texture request failed with status ${response.status}: ${url}`);
+ return response.blob();
+}
+
+function decodeBlob(blob) {
+ // Raw decoding: colour management would change the bytes the shader expects.
+ return createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none' });
+}
+
+function joinUrl(baseUrl, fileName) {
+ return `${baseUrl.replace(/\/+$/, '')}/${fileName}`;
+}
+
+function validateChannels(channels) {
+ if (!Array.isArray(channels) || channels.length === 0) throw new TypeError('channels must be a non-empty array.');
+ for (const channel of channels) {
+ if (!TEXTURE_SET_CHANNELS.includes(channel)) throw new RangeError(`Unknown texture channel: ${channel}. Use ${TEXTURE_SET_CHANNELS.join(', ')}.`);
+ }
+}
+
+/**
+ * Fetch and decode `<baseUrl>/<channel>.<extension>` for each channel.
+ * Without `channels`, every channel that exists is loaded and a missing file is skipped (some scans have no height map).
+ * With an explicit `channels` list, a missing file throws.
+ * `fetchBlob` and `decodeBlob` can be replaced, which is how Node tests run without a browser.
+ */
+export async function loadTextureSet(baseUrl, { channels, extension = 'webp', fetchBlob: fetchOne = fetchBlob, decodeBlob: decodeOne = decodeBlob, colorSpaces = {} } = {}) {
+ if (typeof baseUrl !== 'string' || baseUrl.length === 0) throw new TypeError('baseUrl must be a non-empty string.');
+ const required = channels !== undefined;
+ const requested = channels ?? TEXTURE_SET_CHANNELS;
+ validateChannels(requested);
+ const loaded = await Promise.all(requested.map(async (channel) => {
+ try {
+ const blob = await fetchOne(joinUrl(baseUrl, `${channel}.${extension}`));
+ const image = await decodeOne(blob);
+ return [channel, { image, colorSpace: colorSpaces[channel] ?? CHANNEL_COLOR_SPACES[channel] }];
+ } catch (error) {
+ if (required) throw error;
+ return null;
+ }
+ }));
+ const set = Object.fromEntries(loaded.filter(Boolean));
+ if (Object.keys(set).length === 0) throw new Error(`No texture channels found under ${baseUrl}.`);
+ return set;
+}
diff --git a/tests/splat.test.js b/tests/splat.test.js
new file mode 100644
index 00000000..c7bfd622
--- /dev/null
+++ b/tests/splat.test.js
@@ -0,0 +1,101 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { groupParts } from '../src/renderer.js';
+import { buildSplatPixels, packSplatParameters, resolveSplatSize, splatTextureBytes, validateSplatMaterial } from '../src/splat.js';
+import { estimateTextureBytes } from '../src/budget.js';
+
+function image(size, fill) {
+ const data = new Uint8ClampedArray(size * size * 4);
+ for (let index = 0; index < data.length; index += 4) data.set(fill, index);
+ return { width: size, height: size, data };
+}
+
+function layer(size = 8, extra = {}) {
+ return {
+ color: { image: image(size, [10, 20, 30, 255]), colorSpace: 'srgb' },
+ normal: { image: image(size, [128, 128, 255, 255]), colorSpace: 'linear' },
+ roughness: { image: image(size, [200, 200, 200, 255]), colorSpace: 'linear' },
+ height: { image: image(size, [90, 90, 90, 255]), colorSpace: 'linear' },
+ scale: 3,
+ ...extra,
+ };
+}
+
+function groundPart(material, geometry) {
+ return { name: 'ground', geometry, matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material };
+}
+
+const triangle = () => ({ positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 0, 1]), normals: new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0]), indices: new Uint32Array([0, 1, 2]) });
+
+test('accepts one to four layers and rejects everything else', () => {
+ validateSplatMaterial({ layers: [layer()] });
+ validateSplatMaterial({ layers: [layer(), layer(), layer(), layer()], splat: { rules: [{}, { slope: [30, 90] }, { height: [0, 20], mask: 'g' }] } });
+ assert.throws(() => validateSplatMaterial({ layers: [] }), /1 to 4/);
+ assert.throws(() => validateSplatMaterial({ layers: Array.from({ length: 5 }, () => layer()) }), /1 to 4/);
+ assert.throws(() => validateSplatMaterial({ layers: [{ scale: 2 }] }), /at least one/);
+ assert.throws(() => validateSplatMaterial({ layers: [layer(8, { scale: 0 })] }), /positive/);
+ assert.throws(() => validateSplatMaterial({ layers: [layer(8, { normal: { image: image(8, [0, 0, 0, 255]), colorSpace: 'srgb' } })] }), /linear/);
+ assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { rules: [{ slope: [50, 20] }] } }), /minimum/);
+ assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { rules: [{ slope: [0, 120] }] } }), /within/);
+ assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { rules: [{ mask: 'a' }] } }), /maskMap/);
+ assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { rules: [{}, {}] } }), /one entry per layer/);
+ assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { triplanarStart: 70, triplanarEnd: 50 } }), /triplanarStart/);
+ assert.throws(() => validateSplatMaterial({ layers: [layer()], map: { image: image(2, [0, 0, 0, 255]) } }), /replace/);
+});
+
+test('a weight texture needs bounds and a linear descriptor', () => {
+ const maskMap = { image: image(4, [255, 0, 0, 255]), colorSpace: 'linear' };
+ validateSplatMaterial({ layers: [layer()], splat: { maskMap, maskBounds: [-10, -10, 10, 10], rules: [{ mask: 'a' }] } });
+ assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { maskMap } }), /maskBounds/);
+ assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { maskMap: { ...maskMap, colorSpace: 'srgb' }, maskBounds: [0, 0, 1, 1] } }), /linear/);
+});
+
+test('packs per-layer rules for the shader', () => {
+ const parameters = packSplatParameters({ layers: [layer(), layer(8, { triplanar: true, tint: [0.5, 1, 1] })], splat: { rules: [undefined, { slope: [35, 90], slopeSoftness: 6, mask: 'b', invertMask: true }], heightBlend: 0.3 } });
+ assert.deepEqual([...parameters.layer.slice(0, 8)], [3, 1, 0, 0, 3, 1, 1, 1]);
+ assert.deepEqual([...parameters.slope.slice(4, 8)], [35, 90, 6, 1]);
+ assert.equal(parameters.mask[1], 2);
+ assert.equal(parameters.maskInvert[1], 1);
+ assert.equal(parameters.mask[0], -1);
+ assert.ok(Math.abs(parameters.blend[0] - 0.3) < 1e-6);
+ assert.equal(parameters.options[2], 2);
+ assert.deepEqual([...parameters.tint.slice(4, 7)], [0.5, 1, 1]);
+});
+
+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);
+ assert.equal(resolveSplatSize(material, 8), 8);
+ assert.equal(resolveSplatSize({ ...material, splat: { textureSize: 4 } }, 4096), 4);
+ assert.equal(splatTextureBytes(16, 2), 3 * 2 * estimateTextureBytes(16, 16));
+ assert.equal(splatTextureBytes(16, 2, 4), 3 * 2 * estimateTextureBytes(16, 16) + estimateTextureBytes(4, 4));
+ const pixels = buildSplatPixels(material.layers, 16);
+ assert.equal(pixels.color.length, 16 * 16 * 4 * 2);
+ assert.deepEqual([...pixels.color.slice(0, 4)], [10, 20, 30, 255]);
+ assert.deepEqual([...pixels.packed.slice(0, 4)], [200, 90, 0, 255]);
+ assert.deepEqual([...pixels.normal.slice(0, 4)], [128, 128, 255, 255]);
+});
+
+test('missing channels fall back to neutral texels', () => {
+ const pixels = buildSplatPixels([{ color: layer().color }], 4);
+ assert.deepEqual([...pixels.normal.slice(0, 4)], [128, 128, 255, 255]);
+ assert.deepEqual([...pixels.packed.slice(0, 4)], [255, 128, 0, 255]);
+});
+
+test('parts batch together only with the same layers and splat rules', () => {
+ const layers = [layer()];
+ const splat = { rules: [{}] };
+ const geometry = triangle();
+ const base = { color: [1, 1, 1], metallic: 0, roughness: 1 };
+ const first = groundPart({ ...base, layers, splat }, geometry);
+ const second = groundPart({ ...base, layers, splat }, geometry);
+ assert.equal(groupParts([first, second]).length, 1);
+ assert.equal(groupParts([first, groundPart({ ...base, layers: [layer()], splat }, geometry)]).length, 2);
+ assert.equal(groupParts([first, groundPart({ ...base, layers, splat: { rules: [{}] } }, geometry)]).length, 2);
+ assert.equal(groupParts([first, groundPart({ ...base }, geometry)]).length, 2);
+});
+
+test('procedural material tags reject layers', () => {
+ const part = groundPart({ color: [1, 1, 1], metallic: 0, roughness: 1, tag: 'terrain', layers: [layer()] }, triangle());
+ assert.throws(() => groupParts([part]), /standard PBR/);
+});
diff --git a/tests/terrain.test.js b/tests/terrain.test.js
new file mode 100644
index 00000000..10de9b88
--- /dev/null
+++ b/tests/terrain.test.js
@@ -0,0 +1,133 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createTerrain, heightmapFromImageData } from '../src/terrain.js';
+
+const SMALL = { size: 128, chunks: 4, resolution: 16, levels: 3, height: { amplitude: 10, mountainAmplitude: 30, featureSize: 60 }, seed: 5 };
+
+function vertexList(geometry) {
+ const vertices = [];
+ for (let index = 0; index < geometry.positions.length; index += 3) vertices.push(geometry.positions.slice(index, index + 3));
+ return vertices;
+}
+
+function edgeHeights(geometry, axis, value) {
+ const otherAxis = axis === 0 ? 2 : 0;
+ const edge = new Map();
+ for (const vertex of vertexList(geometry)) {
+ if (Math.abs(vertex[axis] - value) < 1e-4) edge.set(vertex[otherAxis].toFixed(3), vertex[1]);
+ }
+ return edge;
+}
+
+function heightOnEdge(geometry, axis, value, other) {
+ const edge = [...edgeHeights(geometry, axis, value).entries()].map(([position, height]) => [Number(position), height]).sort((first, second) => first[0] - second[0]);
+ for (let index = 0; index < edge.length - 1; index++) {
+ const [lowerPosition, lowerHeight] = edge[index];
+ const [upperPosition, upperHeight] = edge[index + 1];
+ if (other >= lowerPosition - 1e-3 && other <= upperPosition + 1e-3) {
+ return lowerHeight + (upperHeight - lowerHeight) * (other - lowerPosition) / (upperPosition - lowerPosition);
+ }
+ }
+ throw new Error('Position is not on the edge.');
+}
+
+test('the same seed gives the same terrain and another seed differs', () => {
+ const first = createTerrain(SMALL);
+ const second = createTerrain(SMALL);
+ const other = createTerrain({ ...SMALL, seed: 6 });
+ let differs = false;
+ for (const [x, z] of [[0, 0], [13.7, -22.1], [-40, 31], [60, 60]]) {
+ assert.equal(first.heightAt(x, z), second.heightAt(x, z));
+ if (first.heightAt(x, z) !== other.heightAt(x, z)) differs = true;
+ }
+ assert.ok(differs);
+ assert.deepEqual(first.parts[3].geometry.positions, second.parts[3].geometry.positions);
+});
+
+test('heightAt returns the vertex height at mesh vertices of the finest level', () => {
+ const terrain = createTerrain(SMALL);
+ terrain.update([0, 1, 0]);
+ const chunk = terrain.parts.find(part => part.name === 'Terrain chunk 2,2');
+ for (const [x, y, z] of vertexList(chunk.geometry)) assert.ok(Math.abs(terrain.heightAt(x, z) - y) < 1e-3, `${x},${z}`);
+});
+
+test('heightAt matches the interpolated triangles of the finest mesh', () => {
+ const terrain = createTerrain({ ...SMALL, resolution: 8, levels: 1 });
+ const { positions, indices } = terrain.parts[5].geometry;
+ const weights = [[1 / 3, 1 / 3], [0.6, 0.15], [0.1, 0.7]];
+ for (let triangle = 0; triangle < indices.length; triangle += 3) {
+ const corners = [0, 1, 2].map(offset => positions.subarray(indices[triangle + offset] * 3, indices[triangle + offset] * 3 + 3));
+ const [weightFirst, weightSecond] = weights[triangle / 3 % 3];
+ const weightThird = 1 - weightFirst - weightSecond;
+ const x = corners[0][0] * weightFirst + corners[1][0] * weightSecond + corners[2][0] * weightThird;
+ const z = corners[0][2] * weightFirst + corners[1][2] * weightSecond + corners[2][2] * weightThird;
+ const expected = corners[0][1] * weightFirst + corners[1][1] * weightSecond + corners[2][1] * weightThird;
+ assert.ok(Math.abs(terrain.heightAt(x, z) - expected) < 1e-3);
+ }
+});
+
+test('triangles face up and normals are unit length and smooth', () => {
+ const terrain = createTerrain(SMALL);
+ const { positions, normals, indices } = terrain.parts[0].geometry;
+ for (let triangle = 0; triangle < indices.length; triangle += 3) {
+ const [a, b, c] = [0, 1, 2].map(offset => indices[triangle + offset] * 3);
+ const edgeOne = [positions[b] - positions[a], positions[b + 2] - positions[a + 2]];
+ const edgeTwo = [positions[c] - positions[a], positions[c + 2] - positions[a + 2]];
+ assert.ok(edgeOne[1] * edgeTwo[0] - edgeOne[0] * edgeTwo[1] > 0);
+ }
+ for (let vertex = 0; vertex < normals.length; vertex += 3) {
+ assert.ok(Math.abs(Math.hypot(normals[vertex], normals[vertex + 1], normals[vertex + 2]) - 1) < 1e-4);
+ assert.ok(normals[vertex + 1] > 0);
+ }
+ assert.ok(Math.abs(Math.hypot(...terrain.normalAt(10, 10)) - 1) < 1e-6);
+});
+
+test('chunk edges stay watertight between different levels of detail', () => {
+ const terrain = createTerrain({ ...SMALL, lodDistance: 20 });
+ terrain.update([-60, 5, -60]);
+ assert.ok(new Set(terrain.chunkLevels()).size > 1, 'the eye should produce several levels');
+ const side = SMALL.chunks;
+ let checked = 0;
+ for (let row = 0; row < side; row++) {
+ for (let column = 0; column < side - 1; column++) {
+ const west = terrain.parts[row * side + column].geometry;
+ const east = terrain.parts[row * side + column + 1].geometry;
+ const edgeX = -SMALL.size / 2 + (column + 1) * terrain.chunkSize;
+ for (const [position, height] of edgeHeights(west, 0, edgeX)) {
+ assert.ok(Math.abs(heightOnEdge(east, 0, edgeX, Number(position)) - height) < 1e-3);
+ checked++;
+ }
+ for (const [position, height] of edgeHeights(east, 0, edgeX)) {
+ assert.ok(Math.abs(heightOnEdge(west, 0, edgeX, Number(position)) - height) < 1e-3);
+ }
+ }
+ }
+ assert.ok(checked > 0);
+});
+
+test('update reports only chunks that changed and keeps triangle budgets per level', () => {
+ const terrain = createTerrain({ ...SMALL, lodDistance: 20 });
+ terrain.update([0, 1, 0]);
+ assert.equal(terrain.update([0, 1, 0]).length, 0);
+ const sum = terrain.parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);
+ assert.equal(sum, terrain.triangleCount);
+ assert.ok(terrain.triangleCount < SMALL.chunks ** 2 * SMALL.resolution ** 2 * 2);
+ assert.ok(terrain.update([0, 600, 0]).length > 0);
+ assert.equal(terrain.triangleCount, SMALL.chunks ** 2 * (SMALL.resolution / 4) ** 2 * 2);
+ for (const part of terrain.parts) assert.ok(part.geometry.indices.length / 3 <= 2 * SMALL.resolution ** 2);
+});
+
+test('heightmap arrays and functions drive the surface, and bad options throw', () => {
+ const heights = new Float32Array(9).fill(2);
+ heights[4] = 8;
+ const terrain = createTerrain({ size: 64, chunks: 2, resolution: 8, levels: 1, height: heights });
+ assert.ok(Math.abs(terrain.heightAt(0, 0) - 8) < 1e-4);
+ assert.ok(Math.abs(terrain.heightAt(-32, -32) - 2) < 1e-4);
+ const flat = createTerrain({ size: 64, chunks: 2, resolution: 8, levels: 1, height: () => 3 });
+ assert.equal(flat.heightAt(5, 5), 3);
+ assert.deepEqual(flat.bounds.min, [-32, 3, -32]);
+ assert.throws(() => createTerrain({ resolution: 30, levels: 4 }), /divisible/);
+ assert.throws(() => createTerrain({ height: new Float32Array(5) }), /square/);
+ const image = { width: 2, height: 2, data: new Uint8ClampedArray([255, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 0, 0, 255]) };
+ assert.deepEqual([...heightmapFromImageData(image, 10)], [10, 0, 0, 10]);
+});
diff --git a/tests/texture-set.test.js b/tests/texture-set.test.js
new file mode 100644
index 00000000..82f003c4
--- /dev/null
+++ b/tests/texture-set.test.js
@@ -0,0 +1,47 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { loadTextureSet } from '../src/texture-set.js';
+
+function fakeFetch(available) {
+ const requested = [];
+ const fetchBlob = async (url) => {
+ requested.push(url);
+ const channel = url.split('/').pop().split('.')[0];
+ if (!available.includes(channel)) throw new Error(`Texture request failed with status 404: ${url}`);
+ return { channel };
+ };
+ return { requested, fetchBlob };
+}
+
+const decodeBlob = async blob => ({ width: 4, height: 4, channel: blob.channel });
+
+test('loads every channel with the right color spaces', async () => {
+ const { requested, fetchBlob } = fakeFetch(['color', 'normal', 'roughness', 'height']);
+ const set = await loadTextureSet('/textures/leafy_grass/', { fetchBlob, decodeBlob });
+ assert.deepEqual(Object.keys(set).sort(), ['color', 'height', 'normal', 'roughness']);
+ assert.equal(set.color.colorSpace, 'srgb');
+ for (const channel of ['normal', 'roughness', 'height']) assert.equal(set[channel].colorSpace, 'linear');
+ assert.equal(set.normal.image.channel, 'normal');
+ assert.ok(requested.includes('/textures/leafy_grass/color.webp'));
+});
+
+test('skips channels that do not exist unless they were requested by name', async () => {
+ const { fetchBlob } = fakeFetch(['color', 'normal', 'roughness']);
+ const set = await loadTextureSet('/textures/pine_bark', { fetchBlob, decodeBlob });
+ assert.equal(set.height, undefined);
+ await assert.rejects(loadTextureSet('/textures/pine_bark', { channels: ['color', 'height'], fetchBlob, decodeBlob }), /404/);
+});
+
+test('rejects unknown channels, empty lists and sets with nothing', async () => {
+ const { fetchBlob } = fakeFetch([]);
+ await assert.rejects(loadTextureSet('/x', { channels: ['metalness'], fetchBlob, decodeBlob }), /Unknown texture channel/);
+ await assert.rejects(loadTextureSet('/x', { channels: [], fetchBlob, decodeBlob }), /non-empty/);
+ await assert.rejects(loadTextureSet('/x', { fetchBlob, decodeBlob }), /No texture channels/);
+ await assert.rejects(loadTextureSet('', { fetchBlob, decodeBlob }), /baseUrl/);
+});
+
+test('a color space override applies to its channel', async () => {
+ const { fetchBlob } = fakeFetch(['color']);
+ const set = await loadTextureSet('/x', { channels: ['color'], colorSpaces: { color: 'linear' }, fetchBlob, decodeBlob });
+ assert.equal(set.color.colorSpace, 'linear');
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 5a99ced1..6cfb69b3 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -29,6 +29,8 @@ export default defineConfig({
retarget: 'src/retarget.js',
vehicle: 'src/vehicle.js',
vegetation: 'src/vegetation.js',
+ terrain: 'src/terrain.js',
+ 'texture-set': 'src/texture-set.js',
'agent-scene': 'src/agent-scene.js',
'agent-asset': 'src/agent-asset.js',
hdri: 'src/hdri.js',