3D engine that AI agents drive
Vegetation: scanned bark textures, swaying single-sided leaf cards
Nguyen Xuan Anaf8c9cdba190
diff --git a/docs/guide.md b/docs/guide.mdindex 7393d696..dd6673f8 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -209,7 +209,7 @@ The [vehicle contract](/vehicle.md) lists conventions, options and limits.2. Pick detail per camera with `selectLevels(forest.instances, eye)`.3. Pass `view.parts` to `Renderer67` and rebuild when `view.changed` is true.-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.+Cards (`leaves: 'cards'`, the default) are single-sided, alpha-masked, double-sided `foliage` textures that sway with the wind; `'mesh'` leaves cost about twice the triangles. Pass `barkTextures` for scanned bark. The [Vegetation contract](/vegetation.md) lists species, triangle budgets and limits.## Retained surface attachments@@ -234,7 +234,7 @@ An attachment positions one rigid frame. It does not conform the accessory footpThe optional GLB addon creates these descriptors. HDR requires `EXT_color_buffer_float`. Inspect `renderer.capabilities.hdr` and `hdrFallbackReason`. The renderer falls back when floating-point targets are unavailable.-Tags select specialized behavior: `armor` allows studio finish overrides. `floor` is a studio floor. `water` adds animated normals and ripples. `foliage` and `grass` add wind.+Tags select specialized behavior: `armor` allows studio finish overrides. `floor` is a studio floor. `water` adds animated normals and ripples. `foliage` and `grass` add wind and accept a base-colour `map` with alpha mask and `doubleSided` for leaf cards.`material.alphaMode` is `'opaque'` (default), `'mask'` (cutout at `alphaCutoff`, default 0.5, shadows follow it) or `'blend'` (drawn last, back to front, no depth write). `material.opacity` (default 1) multiplies the base map alpha. `material.doubleSided` (default false) disables back-face culling and lights both faces. These are batch state and cannot change after upload. See `docs/material-maps.md`.diff --git a/docs/vegetation.md b/docs/vegetation.mdindex 35f58ffc..2c21c8a4 100644--- a/docs/vegetation.md+++ b/docs/vegetation.md@@ -44,21 +44,33 @@ Measured triangle counts for seed 4 (level 0 / 1 / 2):| Species | `cards` | `mesh` || --- | --- | --- |-| broadleaf | 7.4k / 2.4k / 0.7k | 16.0k / 5.3k / 3.0k |-| birch | 10.7k / 3.3k / 0.8k | 21.9k / 7.0k / 2.8k |-| conifer | 26.1k / 7.2k / 2.3k | 63.9k / 19.8k / 3.4k |-| palm | 6.4k / 1.9k / 1.1k | 11.8k / 3.7k / 2.9k |-| bush | 4.7k / 1.7k / 0.5k | 10.9k / 3.7k / 1.9k |+| broadleaf | 5.8k / 1.8k / 0.5k | 16.0k / 5.3k / 3.0k |+| birch | 7.9k / 2.3k / 0.6k | 21.9k / 7.0k / 2.8k |+| conifer | 18.5k / 4.7k / 2.2k | 63.9k / 19.8k / 3.4k |+| palm | 3.8k / 1.0k / 0.9k | 11.8k / 3.7k / 2.9k |+| bush | 3.1k / 1.1k / 0.4k | 10.9k / 3.7k / 1.9k |++Cards are single-sided now that the renderer honors `doubleSided`; the old duplicated back faces cost 22 to 41 percent of level 0 (broadleaf 7.4k to 5.8k, birch 10.7k to 7.9k, conifer 26.1k to 18.5k, palm 6.4k to 3.8k, bush 4.7k to 3.1k).++## Scanned bark++`createTree({ species, barkTextures, barkTileSize })` and `scatterVegetation({ barkTextures })` take scanned bark as texture descriptors (see [Material maps](/material-maps.md)):+one set `{ color, normal, roughness }` for every species, or an object keyed by species (`{ broadleaf: set, conifer: set, palm: set }`; species without an entry keep procedural bark).+Every descriptor needs repeat wrapping. `roughness` goes to `metallicRoughnessMap`, which reads roughness from G and metallic from B, so repack a grey roughness scan as `(1, roughness, 0)` first or the bark turns metallic. `public/textures` holds `bark_willow_02`, `pine_bark` and `palm_tree_bark` (CC0, see its CREDITS.md); the demo maps broadleaf to willow, conifer to pine and palm to palm bark, and leaves birch procedural white.++Scanned bark gets world-scale UVs: `v` runs along the branch and `u` around it at `barkTileSize` meters per tile (default 0.8), computed per ring so a trunk and a twig have the same texel density and square texels.+Rings wide enough for 1.5 tiles or more wrap a whole number of tiles, so they have no seam. Thinner rings keep the exact scale and put their seam on the underside, away from the usual view. Without `barkTextures` the procedural bark keeps its whole-number repeats and 0.6 m tile.## Leaves: cards or mesh-`leaves: 'cards'` (default) uses a procedural RGBA leaf texture (`material.map`) on crossed, slightly curved cards with `alphaMode: 'mask'`, `alphaCutoff: 0.5` and `doubleSided: true`.+`leaves: 'cards'` (default) uses a procedural RGBA leaf texture (`material.map`) on crossed, slightly curved cards with the `foliage` tag (`grass` for grass cards), `alphaMode: 'mask'`, `alphaCutoff: 0.5` and `doubleSided: true`.Cards rely on the renderer's alpha masking with alpha-to-coverage under MSAA; with `samples: 1` their edges fall back to a hard cutout.-Cards also carry both faces in the geometry, so they stay visible with back-face culling. Once `doubleSided` is honored, that duplicate costs triangles you can drop.+Cards hold one face each and `doubleSided` draws the back. For the `foliage` and `grass` tags the fragment shader does not flip the normal on a back face, so the canopy-leaning shading normal lights both sides alike and the existing back-lighting term adds translucency.`leaves: 'mesh'` builds real leaf silhouettes (ovate, fir spray, palm leaflet) as folded, drooping meshes with the `foliage` tag. It needs no alpha support and costs about twice the triangles.-Wind: the vertex shader sways only the `foliage` and `grass` tags, by local height. Mesh leaves and grass blades therefore sway, and bark (a standard material) stays still.-Textured materials must use a standard tag, so `cards` do not sway yet. A small shader hook that reads the tag for textured materials would add it.+Wind: the vertex shader sways only the `foliage` and `grass` tags, and those tags accept a base-colour `map` with alpha mask and `doubleSided` (other maps stay unsupported). Cards, mesh leaves and grass blades sway; bark (a standard material) stays still.+The displacement is a pure function of `frame.time`, `frame.wind` (default 0.3), the vertex's local position and its uv: a slow sway that grows with height and with distance from the tree's axis (branch tips swing more than the crown centre, both capped at 2.5 m and 3 m so leaves stay near their twigs) plus a faster flutter that grows toward each leaf's tip (`uv.y` 0).+The shadow vertex shader applies the same function, and the renderer redraws the shadow map whenever `frame.time` or `frame.wind` changes while a `foliage` or `grass` batch casts shadows, so shadows follow the leaves. This costs one extra shadow pass per frame for scenes with swaying foliage.## Grass and flowers@@ -94,6 +106,6 @@ Meshes and textures are built in plain JavaScript, so tests run in Node.## Limits-- Cards need the renderer's alpha mask to look right, and do not sway under the current shader.+- Cards need the renderer's alpha mask to look right. The leaf textures are 128 px procedural sprigs; a card seen from under 1 m shows flat, pale shading on needle cards (seen on conifer needles in the close-up render).- Level changes pop; there is no cross-fade. Level 2 crowns are blobs or crossed cards, not baked imposters.- Species are fixed presets; there is no seasonal color, wind-bent skeleton or collision with other trees.diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex ff8eff7b..d1bac895 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -47,7 +47,7 @@ The material tags select renderer behavior.| `water` | Flat ponds and streams only: replaces normals with a near-horizontal ripple field. || `liquid` | Shaped water (jets, sheets, splashes): refracts the opaque scene, absorbs by thickness, Fresnel reflection. `color` is what one metre lets through. || `foam` | Soft alpha-blended whitewater droplets drawn after liquids. Set `castShadow: false`. |-| `foliage`, `grass` | Wind movement and backlighting. |+| `foliage`, `grass` | Wind movement (also in the shadow pass) and backlighting. Accept a base-colour `map` with `alphaMode: 'mask'` and `doubleSided` for leaf cards. || `terrain` | Subtle natural surface variation. || `fire`, `smoke` | Film ignition expansion and procedural shading. || `unlit` | Flat linear color for vector scenes. |diff --git a/src/renderer.js b/src/renderer.jsindex af585d00..077c1f82 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -23,6 +23,9 @@ const MAP_FLAGS = ['hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'hasconst DEFAULT_NORMAL_SCALE = [1, 1];const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain', 'floor', 'fire', 'smoke', 'liquid', 'foam']);+// Tags whose vertices sway in the wind; the shadow pass must be redrawn when time moves.+const SWAYING_TAGS = new Set(['foliage', 'grass']);+function renderPass(material) {return TRANSLUCENT_TAGS.has(material.tag) ? material.tag : 'opaque';}@@ -305,6 +308,7 @@ export class Renderer67 {this.textures = new Map();this.textureBytes = 4;this.shadowsDirty = true;+ this.windState = { time: 0, strength: 0.3 };const groups = groupParts(this.groundPart ? [...parts, this.groundPart] : parts, batching);const textureLimit = this.context.getParameter(this.context.MAX_TEXTURE_SIZE);this.hasSkins = groups.some(group => group[0].skin);@@ -384,6 +388,7 @@ export class Renderer67 {this.depthAlphaUniforms = Object.fromEntries(DEPTH_ALPHA_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));this.depthUniform = this.context.getUniformLocation(this.depthProgram, 'lightProjection');this.depthAssemblyUniform = this.context.getUniformLocation(this.depthProgram, 'assemblyAmount');+ this.depthWindUniforms = { time: this.context.getUniformLocation(this.depthProgram, 'time'), wind: this.context.getUniformLocation(this.depthProgram, 'wind') };this.partCount = parts.length;this.triangles = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);this.whiteTexture = this.createTexture(null);@@ -804,6 +809,8 @@ export class Renderer67 {context.useProgram(this.depthProgram);context.uniformMatrix4fv(this.depthUniform, false, this.lightProjection);context.uniform1f(this.depthAssemblyUniform, this.assemblyAmount ?? 0);+ context.uniform1f(this.depthWindUniforms.time, this.windState.time);+ context.uniform1f(this.depthWindUniforms.wind, this.windState.strength);// The base map sampler must not alias the shadow texture on unit 0 while that texture is the render target.context.uniform1i(this.depthAlphaUniforms.baseMap, 1);context.enable(context.POLYGON_OFFSET_FILL);@@ -815,6 +822,15 @@ export class Renderer67 {this.shadowsDirty = false;}+ /** Stores the wind time and strength the shadow pass must use; true when swaying batches need a new shadow map. */+ updateWindState(frame) {+ const next = { time: frame.time ?? 0, strength: frame.wind ?? 0.3 };+ const previous = this.windState;+ this.windState = next;+ if (previous.time === next.time && previous.strength === next.strength) return false;+ return this.batches.some(batch => batch.castShadow && SWAYING_TAGS.has(batch.parts[0].material.tag));+ }+resize() {const plan = planRenderSize({ width: Math.max(1, this.canvas.clientWidth), height: Math.max(1, this.canvas.clientHeight), pixelRatio: this.pixelRatio, samples: this.samples, memoryBudgetMiB: this.memoryBudgetMiB, geometryBytes: this.geometryBytes, textureBytes: this.textureBytes, hdr: this.hdr, bloom: !this.benchmark, depth: this.depth, maximumSize: Math.min(this.context.getParameter(this.context.MAX_RENDERBUFFER_SIZE), this.context.getParameter(this.context.MAX_TEXTURE_SIZE)) });const { width, height } = plan;@@ -1289,7 +1305,9 @@ export class Renderer67 {const start = performance.now();const context = this.context;const assemblyAmount = Math.max(0, Math.min(1, frame.assemblyAmount ?? 0));- if (this.assemblyAmount !== assemblyAmount || this.shadowsDirty) {+ // Swaying foliage moves every frame, so its shadow map is redrawn whenever time or wind changes.+ const windChanged = this.updateWindState(frame);+ if (this.assemblyAmount !== assemblyAmount || this.shadowsDirty || windChanged) {this.assemblyAmount = assemblyAmount;this.createShadowMap();}diff --git a/src/shaders.js b/src/shaders.jsindex 01af1c4e..a0b0d3b1 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -55,6 +55,23 @@ mat4 skinTransform() {}`;+// Wind for the foliage (4) and grass (7) tags, shared by the colour and shadow vertex shaders so both+// move identically. It depends only on local position, the card's uv, world position and time.+// The slow sway grows with height and with distance from the model's vertical axis (branch tips swing+// more than the crown centre) but is capped, because bark never moves and leaves must stay near their twigs.+// uv.y is 1 at a leaf's base and 0 at its tip, which drives the faster flutter.+const windShader = `+vec3 windOffset(vec3 localPosition, vec3 worldPoint, vec2 leafUv, float surfaceTag, float seconds, float strength) {+ if (surfaceTag != 4.0 && surfaceTag != 7.0) return vec3(0.0);+ float heightReach = min(max(localPosition.y + 0.5, 0.0), 2.5);+ float branchReach = 1.0 + 0.3 * min(length(localPosition.xz), 3.0);+ float sway = sin(seconds * 1.2 + worldPoint.z * 0.31 + worldPoint.x * 0.17) * strength * 0.10 * heightReach * branchReach;+ float tip = clamp(1.0 - leafUv.y, 0.0, 1.0);+ float flutter = sin(seconds * 3.1 + worldPoint.x * 1.7 + worldPoint.z * 1.3 + localPosition.y * 2.0) * strength * 0.08 * tip;+ return vec3(sway + flutter, 0.0, flutter * 0.6);+}+`;+export const vertexShader = `#version 300 esprecision highp float;layout(location=0) in vec3 position;@@ -85,13 +102,12 @@ out vec3 vertexTint;flat out vec3 emissionColor;${skinningShader}${morphingShader}+${windShader}void main() {mat4 deformation = skinTransform();vec4 world = instanceMatrix * deformation * vec4(morphedPosition(position), 1.0);world.xyz += assemblyOffset * assemblyAmount + assemblyDetailOffset * smoothstep(0.3, 1.0, assemblyAmount);- if (instanceSurface.w == 4.0 || instanceSurface.w == 7.0) {- world.x += sin(time * 1.2 + world.z * 0.31 + world.x * 0.17) * wind * 0.10 * max(position.y + 0.5, 0.0);- }+ world.xyz += windOffset(position, world.xyz, uv, instanceSurface.w, time, wind);if (instanceSurface.w == 3.0) {world.y += sin(world.x * 1.4 + time * 0.8) * 0.025 + sin(world.z * 1.8 - time) * 0.02;}@@ -115,17 +131,23 @@ export const depthVertexShader = `#version 300 esprecision highp float;layout(location=0) in vec3 position;layout(location=2) in mat4 instanceMatrix;+layout(location=10) in vec4 instanceSurface;layout(location=11) in vec3 assemblyOffset;layout(location=12) in vec3 assemblyDetailOffset;layout(location=13) in vec2 uv;uniform mat4 lightProjection;uniform float assemblyAmount;+uniform float time;+uniform float wind;out vec2 textureUV;${skinningShader}${morphingShader}+${windShader}void main() {vec4 world = instanceMatrix * skinTransform() * vec4(morphedPosition(position), 1.0);world.xyz += assemblyOffset * assemblyAmount + assemblyDetailOffset * smoothstep(0.3, 1.0, assemblyAmount);+ // Same displacement as the colour pass, so shadows follow the swaying leaves.+ world.xyz += windOffset(position, world.xyz, uv, instanceSurface.w, time, wind);textureUV = uv;gl_Position = lightProjection * world;}`;@@ -471,7 +493,10 @@ float surfaceAlpha(float textureAlpha) {void main() {vec3 normal = normalize(worldNormal);- if (doubleSided > 0.5 && !gl_FrontFacing) normal = -normal;+ // Foliage and grass cards are single-sided geometry whose shading normal already leans toward the+ // canopy, so the back face keeps it instead of flipping to point into the crown.+ bool canopyShaded = surface.w == 4.0 || surface.w == 7.0;+ if (doubleSided > 0.5 && !gl_FrontFacing && !canopyShaded) normal = -normal;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)));diff --git a/src/vegetation-geometry.js b/src/vegetation-geometry.jsindex 7c9f57a0..0b7d467d 100644--- a/src/vegetation-geometry.js+++ b/src/vegetation-geometry.js@@ -139,21 +139,48 @@ export function createMeshBuilder({ withColors = false } = {}) {};}-/** Sweeps a tapered round tube along a polyline with parallel-transported rings. */-export function addTube(builder, points, radii, sides, tileSize, color = [1, 1, 1]) {- const repeatAround = Math.max(1, Math.round(FULL_TURN * radii[0] / tileSize));+// Below this many texture repeats around a ring the bark texture is not wrapped to a whole number:+// rounding would stretch a thin twig by more than a third, so it keeps true world scale instead.+const MINIMUM_WHOLE_REPEATS = 1.5;+const MINIMUM_UNDERSIDE_REACH = 0.25;++function wholeOrExactRepeats(exactRepeats) {+ return exactRepeats >= MINIMUM_WHOLE_REPEATS ? Math.round(exactRepeats) : exactRepeats;+}++/** Angle around the ring whose radial direction points most nearly straight down, or `fallback` on near-vertical rings. */+function undersideAngle(frame, fallback) {+ const downOnFirst = -frame.first[1];+ const downOnSecond = -frame.second[1];+ if (Math.hypot(downOnFirst, downOnSecond) < MINIMUM_UNDERSIDE_REACH) return fallback;+ return Math.atan2(downOnSecond, downOnFirst);+}++/**+ * Sweeps a tapered round tube along a polyline with parallel-transported rings.+ * By default `u` repeats a whole number of times around the base ring. With `worldScaleUv` every ring+ * gets `u` and `v` from its own circumference so texels keep one world size from trunk to twig, rings+ * wide enough to wrap whole tiles do so (no seam), and thinner rings put their seam on the underside.+ */+export function addTube(builder, points, radii, sides, tileSize, color = [1, 1, 1], { worldScaleUv = false } = {}) {+ const baseRepeats = Math.max(1, Math.round(FULL_TURN * radii[0] / tileSize));const firstVertex = builder.vertexCount;const lastIndex = points.length - 1;let frame = null;- let distance = 0;+ let along = 0;+ let seamAngle = 0;points.forEach((point, index) => {const tangent = normalized(subtractVectors(points[Math.min(index + 1, lastIndex)], points[Math.max(index - 1, 0)]));frame = frame ? transportFrame(frame, tangent) : createFrame(tangent);- if (index > 0) distance += vectorLength(subtractVectors(point, points[index - 1]));+ const exactRepeats = FULL_TURN * radii[index] / tileSize;+ const repeatsAround = worldScaleUv ? wholeOrExactRepeats(exactRepeats) : baseRepeats;+ const alongScale = worldScaleUv && exactRepeats > 1e-6 ? repeatsAround / exactRepeats : 1;+ if (index > 0) along += vectorLength(subtractVectors(point, points[index - 1])) / tileSize * alongScale;+ if (worldScaleUv) seamAngle = undersideAngle(frame, seamAngle);for (let side = 0; side <= sides; side++) {- const angle = side / sides * FULL_TURN;+ const angle = seamAngle + side / sides * FULL_TURN;const radial = addVectors(scaleVector(frame.first, Math.cos(angle)), scaleVector(frame.second, Math.sin(angle)));- builder.addVertex(addScaled(point, radial, radii[index]), radial, side / sides * repeatAround, distance / tileSize, color);+ builder.addVertex(addScaled(point, radial, radii[index]), radial, side / sides * repeatsAround, along, color);}});const ringSize = sides + 1;diff --git a/src/vegetation.js b/src/vegetation.jsindex f9c5bb38..8726f490 100644--- a/src/vegetation.js+++ b/src/vegetation.js@@ -19,6 +19,7 @@ import { barkTextureDescriptor, leafTextureDescriptor } from './vegetation-textuexport { SPECIES };const BARK_TILE_SIZE = 0.6;+const SCANNED_BARK_TILE_SIZE = 0.8;const LEAF_MODES = ['cards', 'mesh'];const GRASS_LEVEL_DISTANCES = [24];const LEAF_COLOR_BASE = [0.85, 0.95, 0.8];@@ -148,7 +149,7 @@ function describeCrown(leafSites) {return { center, radius };}-function buildBark(skeleton, preset, setting) {+function buildBark(skeleton, preset, setting, bark) {const lastLevel = preset.levels.length - 1;const maximumLevel = setting.maximumBranchLevel < 0 ? lastLevel + setting.maximumBranchLevel : setting.maximumBranchLevel;const builder = createMeshBuilder();@@ -162,11 +163,30 @@ function buildBark(skeleton, preset, setting) {points = [addScaled(points[0], direction, -0.3), ...points];radii = [radii[0] * preset.rootFlare, ...radii];}- addTube(builder, points, radii, sides, BARK_TILE_SIZE);+ addTube(builder, points, radii, sides, bark.tileSize, [1, 1, 1], { worldScaleUv: bark.scanned });}return builder.build();}+function isTextureDescriptor(value) {+ return Boolean(value) && typeof value === 'object' && Boolean(value.image);+}++/**+ * Picks the scanned bark set for a species. `barkTextures` is either one set+ * (`{ color, normal, roughness }`) or an object keyed by species name; returns null for procedural bark.+ */+export function resolveBarkTextures(barkTextures, species) {+ if (!barkTextures) return null;+ const set = isTextureDescriptor(barkTextures.color) ? barkTextures : barkTextures[species];+ if (!set) return null;+ if (!isTextureDescriptor(set.color)) throw new TypeError(`Bark textures for ${species} need a color texture descriptor.`);+ for (const channel of ['normal', 'roughness']) {+ if (set[channel] !== undefined && !isTextureDescriptor(set[channel])) throw new TypeError(`Bark ${channel} must be a texture descriptor.`);+ }+ return set;+}+function crownShading(skeleton, position) {const { center, radius } = skeleton.crown;const offset = subtractVectors(position, center);@@ -211,6 +231,7 @@ function addCards(builder, skeleton, spec, site, scale, random) {length: spec.cardSize[1] * site.scale * scale,width: spec.cardSize[0] * site.scale * scale,rows: [[0, 1], [0.5, 1], [1, 1]],+ backFaces: false,droop: 0.12,canopyNormal,canopyBlend: 0.55,@@ -270,6 +291,7 @@ function addCrownClumps(builder, skeleton, spec, mode, random) {length: radius * 2,width: radius * 2,rows: [[0, 1], [1, 1]],+ backFaces: false,canopyNormal: shading.canopyNormal,canopyBlend: 0.7,colorBase: LEAF_COLOR_BASE,@@ -296,14 +318,24 @@ function buildFoliage(skeleton, preset, mode, levelIndex, random) {return builder.build();}-function createMaterials(preset, mode) {- const bark = { color: preset.bark.tint, roughness: 0.95, metallic: 0, emission: 0, map: barkTextureDescriptor(preset.bark.texture) };+function createBarkMaterial(preset, scannedTextures) {+ if (!scannedTextures) {+ return { color: preset.bark.tint, roughness: 0.95, metallic: 0, emission: 0, map: barkTextureDescriptor(preset.bark.texture) };+ }+ const material = { color: [1, 1, 1], roughness: 1, metallic: 0, emission: 0, map: scannedTextures.color };+ if (scannedTextures.normal) material.normalMap = scannedTextures.normal;+ if (scannedTextures.roughness) material.metallicRoughnessMap = scannedTextures.roughness;+ return material;+}++function createMaterials(preset, mode, scannedBark) {+ const bark = createBarkMaterial(preset, scannedBark);if (mode === 'mesh') {const foliage = { tag: 'foliage', color: preset.leaf.foliageColor, roughness: 0.8, metallic: 0, emission: 0 };return { bark, foliage, crown: foliage };}const cardMaterial = (texture) => ({- color: preset.leaf.tint, roughness: 0.85, metallic: 0, emission: 0,+ tag: 'foliage', color: preset.leaf.tint, roughness: 0.85, metallic: 0, emission: 0,map: leafTextureDescriptor(texture, preset.leaf.color), alphaMode: 'mask', alphaCutoff: 0.5, doubleSided: true,});return { bark, foliage: cardMaterial(preset.leaf.texture), crown: cardMaterial('clump') };@@ -328,7 +360,7 @@ function describeLevel(parts) {/*** Grows one tree. `speciesOrOptions` is a preset name ('broadleaf', 'birch', 'conifer', 'palm',- * 'bush') or `{ species, height, leaves }`. Returns three levels of detail; each level lists the+ * 'bush') or `{ species, height, leaves, barkTextures, barkTileSize }`. Returns three levels of detail; each level lists the* parts (`bark`, `foliage`) with their geometry and material, in local meters with the trunk at the origin.*/export function createTree(speciesOrOptions = 'broadleaf', seed = 1) {@@ -341,12 +373,14 @@ export function createTree(speciesOrOptions = 'broadleaf', seed = 1) {const random = createRandom(seed * 7919 + 17);const height = options.height ?? randomInRange(random, preset.height);const skeleton = growSkeleton(preset, height, random);- const materials = createMaterials(preset, leaves);+ const scannedBark = resolveBarkTextures(options.barkTextures, options.species);+ const bark = { scanned: Boolean(scannedBark), tileSize: options.barkTileSize ?? (scannedBark ? SCANNED_BARK_TILE_SIZE : BARK_TILE_SIZE) };+ const materials = createMaterials(preset, leaves, scannedBark);const levels = LEVEL_SETTINGS.map((setting, levelIndex) => {const levelRandom = createRandom(seed * 104729 + levelIndex);const foliageMaterial = setting.leafKeep === 0 ? materials.crown : materials.foliage;return describeLevel([- { role: 'bark', geometry: buildBark(skeleton, preset, setting), material: materials.bark, tintable: false },+ { role: 'bark', geometry: buildBark(skeleton, preset, setting, bark), material: materials.bark, tintable: false },{ role: 'foliage', geometry: buildFoliage(skeleton, preset, leaves, levelIndex, levelRandom), material: foliageMaterial, tintable: true },]);});@@ -359,7 +393,7 @@ export function createTree(speciesOrOptions = 'broadleaf', seed = 1) {function grassMaterial(style, color) {if (style === 'cards') {- return { color: [1, 1, 1], roughness: 0.9, metallic: 0, emission: 0, map: leafTextureDescriptor('grass', [80, 128, 40]), alphaMode: 'mask', alphaCutoff: 0.5, doubleSided: true };+ return { tag: 'grass', color: [1, 1, 1], roughness: 0.9, metallic: 0, emission: 0, map: leafTextureDescriptor('grass', [80, 128, 40]), alphaMode: 'mask', alphaCutoff: 0.5, doubleSided: true };}return { tag: 'grass', color, roughness: 0.9, metallic: 0, emission: 0 };}@@ -398,6 +432,7 @@ function buildGrassCards(random, height, radius) {length: height * (0.9 + random() * 0.2),width: radius * 2.4,rows: [[0, 1], [0.5, 1], [1, 1]],+ backFaces: false,droop: 0.1,canopyNormal: WORLD_UP,canopyBlend: 0.6,@@ -459,10 +494,10 @@ export function createFlowerPatch({ flowers = 5, height = 0.4, color = [1, 0.85,const FLOWER_COLORS = [[0.95, 0.8, 0.25], [0.8, 0.35, 0.55], [0.9, 0.9, 0.85], [0.45, 0.4, 0.85]];-function createVariant(species, variantSeed, variantIndex, leaves) {+function createVariant(species, variantSeed, variantIndex, leaves, barkTextures) {if (species === 'grass') return createGrassClump({ seed: variantSeed, height: 0.38 + 0.12 * (variantIndex % 3) });if (species === 'flowers') return createFlowerPatch({ seed: variantSeed, color: FLOWER_COLORS[variantIndex % FLOWER_COLORS.length] });- return createTree({ species, leaves }, variantSeed);+ return createTree({ species, leaves, barkTextures }, variantSeed);}function poissonDiskPoints(area, radius, random, accept) {@@ -552,13 +587,13 @@ function instanceParts(instance, levelIndex, label) {/*** Scatters vegetation with Poisson-disk spacing. `area` is `{ minX, maxX, minZ, maxZ }`, `density` is* instances per square meter, `slopeLimit` is degrees, `exclusion(x, z)` returns true to keep a spot clear- * and `mix` weighs species ('broadleaf', 'birch', 'conifer', 'palm', 'bush', 'grass', 'flowers').+ * `barkTextures` (one set or one per species) swaps procedural bark for scanned textures, and `mix` weighs species ('broadleaf', 'birch', 'conifer', 'palm', 'bush', 'grass', 'flowers').* A few variants per species are shared by every instance, so the renderer batches them as instances.* Returns `{ instances, parts, variants, counts }`; `parts` shows every instance at full detail.*/export function scatterVegetation({area, density = 0.012, terrainHeight = () => 0, slopeLimit = 32, exclusion = () => false, seed = 1,- mix = DEFAULT_MIX, variants = 3, leaves = 'cards', scale = [0.8, 1.25], spacing,+ mix = DEFAULT_MIX, variants = 3, leaves = 'cards', scale = [0.8, 1.25], spacing, barkTextures,} = {}) {if (!area || ![area.minX, area.maxX, area.minZ, area.maxZ].every(Number.isFinite) || area.maxX <= area.minX || area.maxZ <= area.minZ) {throw new TypeError('Scatter area needs finite minX < maxX and minZ < maxZ.');@@ -573,7 +608,7 @@ export function scatterVegetation({const instances = points.map(([x, z], index) => {const species = chooseSpecies(speciesNames, mix, x, z, seed, random);if (!variantsBySpecies[species]) {- variantsBySpecies[species] = Array.from({ length: variants }, (_, variantIndex) => createVariant(species, seed * 131 + variantIndex * 977 + species.length, variantIndex, leaves));+ variantsBySpecies[species] = Array.from({ length: variants }, (_, variantIndex) => createVariant(species, seed * 131 + variantIndex * 977 + species.length, variantIndex, leaves, barkTextures));}const variant = variantsBySpecies[species][Math.floor(random() * variants)];const size = randomInRange(random, scale);diff --git a/tests/vegetation-bark-wind.test.js b/tests/vegetation-bark-wind.test.jsnew file mode 100644index 00000000..4008f77a--- /dev/null+++ b/tests/vegetation-bark-wind.test.js@@ -0,0 +1,136 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createTree, resolveBarkTextures, scatterVegetation } from '../src/vegetation.js';+import { addLeafSurface, addTube, createLeafFrame, createMeshBuilder } from '../src/vegetation-geometry.js';+import { depthVertexShader, vertexShader } from '../src/shaders.js';++const TILE_SIZE = 0.8;++function syntheticDescriptor() {+ return { image: { width: 4, height: 4, data: new Uint8ClampedArray(64) }, colorSpace: 'linear', wrapS: 10497, wrapT: 10497 };+}++function syntheticBarkSet() {+ return { color: syntheticDescriptor(), normal: syntheticDescriptor(), roughness: syntheticDescriptor() };+}++function straightTube(radius, sides, direction = [0, 1, 0]) {+ const builder = createMeshBuilder();+ const points = [0, 1, 2, 3].map(step => direction.map(component => component * step));+ addTube(builder, points, [radius, radius, radius, radius], sides, TILE_SIZE, [1, 1, 1], { worldScaleUv: true });+ return { geometry: builder.build(), sides, ringSize: sides + 1 };+}++test('bark u spans each ring by its own circumference, so texel density matches from trunk to twig', () => {+ for (const radius of [0.3, 0.1, 0.02]) {+ const { geometry, ringSize } = straightTube(radius, 8);+ const exactRepeats = 2 * Math.PI * radius / TILE_SIZE;+ const spanOfRing = geometry.uvs[ringSize * 2 - 2] - geometry.uvs[0];+ const expected = exactRepeats >= 1.5 ? Math.round(exactRepeats) : exactRepeats;+ assert.ok(Math.abs(spanOfRing - expected) < 1e-6, `radius ${radius}: span ${spanOfRing}, expected ${expected}`);+ const density = spanOfRing / exactRepeats;+ assert.ok(density > 0.74 && density < 1.34, `radius ${radius}: density ratio ${density}`);+ if (exactRepeats < 1.5) assert.ok(Math.abs(density - 1) < 1e-6);+ }+});++test('bark v advances at the same texel density as u, so texels stay square and do not stretch', () => {+ for (const radius of [0.3, 0.1, 0.02]) {+ const { geometry, ringSize } = straightTube(radius, 8);+ const circumference = 2 * Math.PI * radius;+ const uPerMeter = (geometry.uvs[ringSize * 2 - 2] - geometry.uvs[0]) / circumference;+ const vPerMeter = (geometry.uvs[(ringSize + 0) * 2 + 1] - geometry.uvs[1]) / 1;+ assert.ok(Math.abs(uPerMeter - vPerMeter) < 1e-6, `radius ${radius}: u ${uPerMeter} per meter, v ${vPerMeter} per meter`);+ }+});++test('bark v is constant around a ring and never decreases along the tube', () => {+ const { geometry, ringSize } = straightTube(0.1, 6);+ for (let ring = 0; ring < 4; ring++) {+ const firstV = geometry.uvs[ring * ringSize * 2 + 1];+ for (let side = 0; side < ringSize; side++) assert.equal(geometry.uvs[(ring * ringSize + side) * 2 + 1], firstV);+ if (ring > 0) assert.ok(firstV > geometry.uvs[(ring - 1) * ringSize * 2 + 1]);+ }+});++test('the bark seam of a thin horizontal branch sits on its underside', () => {+ const { geometry, ringSize } = straightTube(0.02, 6, [1, 0, 0]);+ for (let ring = 0; ring < 4; ring++) {+ const seamNormalY = geometry.normals[ring * ringSize * 3 + 1];+ assert.ok(seamNormalY < -0.99, `ring ${ring} seam normal y ${seamNormalY}`);+ }+});++test('procedural bark keeps its whole-number repeats and 0.6 m tile by default', () => {+ const tree = createTree('broadleaf', 4);+ assert.equal(tree.materials.bark.normalMap, undefined);+ const { uvs } = tree.levels[0].parts[0].geometry;+ for (let index = 0; index < uvs.length; index += 2) assert.ok(Number.isFinite(uvs[index]) && Number.isFinite(uvs[index + 1]));+});++test('scanned bark textures reach the bark material as map, normalMap and metallicRoughnessMap', () => {+ const set = syntheticBarkSet();+ const tree = createTree({ species: 'conifer', barkTextures: set }, 3);+ assert.equal(tree.materials.bark.map, set.color);+ assert.equal(tree.materials.bark.normalMap, set.normal);+ assert.equal(tree.materials.bark.metallicRoughnessMap, set.roughness);+ assert.equal(tree.materials.bark.tag, undefined);+});++test('barkTextures accepts one set or one set per species and rejects malformed sets', () => {+ const set = syntheticBarkSet();+ assert.equal(resolveBarkTextures(set, 'palm'), set);+ assert.equal(resolveBarkTextures({ palm: set }, 'palm'), set);+ assert.equal(resolveBarkTextures({ palm: set }, 'birch'), null);+ assert.equal(resolveBarkTextures(undefined, 'palm'), null);+ assert.throws(() => resolveBarkTextures({ palm: { normal: syntheticDescriptor() } }, 'palm'), TypeError);+ assert.throws(() => resolveBarkTextures({ color: syntheticDescriptor(), normal: 7 }, 'palm'), TypeError);+});++test('scatterVegetation passes per-species bark textures to its variants', () => {+ const set = syntheticBarkSet();+ const forest = scatterVegetation({ area: { minX: 0, maxX: 20, minZ: 0, maxZ: 20 }, density: 0.02, mix: { conifer: 1, birch: 1 }, barkTextures: { conifer: set }, variants: 1, seed: 5 });+ assert.equal(forest.variants.conifer[0].materials.bark.map, set.color);+ assert.notEqual(forest.variants.birch[0].materials.bark.map, set.color);+});++test('textured bark is deterministic for the same seed', () => {+ const set = syntheticBarkSet();+ const first = createTree({ species: 'broadleaf', barkTextures: set }, 9).levels[0].parts[0].geometry;+ const second = createTree({ species: 'broadleaf', barkTextures: set }, 9).levels[0].parts[0].geometry;+ assert.deepEqual(first.uvs, second.uvs);+ assert.deepEqual(first.positions, second.positions);+});++test('leaf cards are single-sided: one copy of each face, half the old triangles', () => {+ const frame = createLeafFrame([0, 0, 1], 0);+ const options = { origin: [0, 0, 0], frame, length: 1, width: 1, rows: [[0, 1], [0.5, 1], [1, 1]], canopyNormal: [0, 1, 0] };+ const both = createMeshBuilder({ withColors: true });+ const single = createMeshBuilder({ withColors: true });+ addLeafSurface(both, options);+ addLeafSurface(single, { ...options, backFaces: false });+ assert.equal(single.triangleCount * 2, both.triangleCount);+ assert.equal(single.vertexCount * 2, both.vertexCount);+ const foliage = createTree({ species: 'broadleaf' }, 4).levels[0].parts[1].geometry;+ assert.equal(foliage.indices.length / 3, foliage.positions.length / 3 / 1.5, 'each card has 6 vertices and 4 triangles');+});++test('cards use the swaying foliage tag with a base map, alpha mask and double-sided drawing', () => {+ const tree = createTree({ species: 'broadleaf' }, 4);+ for (const material of [tree.materials.foliage, tree.materials.crown]) {+ assert.equal(material.tag, 'foliage');+ assert.equal(material.alphaMode, 'mask');+ assert.equal(material.doubleSided, true);+ assert.ok(material.map);+ for (const unsupported of ['normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap']) assert.equal(material[unsupported], undefined);+ }+});++test('colour and shadow vertex shaders apply the same wind displacement', () => {+ for (const source of [vertexShader, depthVertexShader]) {+ assert.match(source, /vec3 windOffset\(/);+ assert.match(source, /windOffset\(position, world\.xyz, uv, instanceSurface\.w, time, wind\)/);+ assert.match(source, /uniform float time;/);+ assert.match(source, /uniform float wind;/);+ }+});