Skip to content

Official Codebase of 3DCodeVerse

Python

scene lib: one readWind reads the scene's wind for every effect, so the catalog's wind object no longer throws

gaoypengfc50e700fdcd
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js
index 0620df6a..e5922806 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js
@@ -27,7 +27,7 @@
import * as THREE from 'three';
import {
patchStandard, glslAxes, glslCurv, glslTriNoise,
- seedVec3, toColor, unit, upVector, worldBase,
+ readWind, seedVec3, toColor, unit, upVector, worldBase,
} from './shader.js';
// Both patches read these, so they are declared once, in the base.
@@ -54,17 +54,15 @@ const seedOffset = (seed, salt) =>
seedVec3(seed + salt, 1.61, 8.09, 13.77, 56);
/**
- * Read `wind` as a direction it blows TOWARD, length 0..1 = strength.
+ * Read `wind` as the horizontal direction it blows TOWARD, length 0..1 = strength.
*
* Length rather than a second option: zero wind must mean an even fall
* with no drift axis at all, and normalizing a zero vector is NaN.
*/
function windVector(value, fallback) {
- const v = new THREE.Vector3();
- if (value) v.fromArray(value.toArray ? value.toArray() : value);
- else if (fallback) v.fromArray(fallback);
- if (v.lengthSq() > 1) v.normalize();
- return v;
+ if (value == null && !fallback) return new THREE.Vector3();
+ const w = readWind(value, fallback, 'wind');
+ return new THREE.Vector3(w.x, 0, w.z).clampLength(0, 1);
}
/**
@@ -107,8 +105,8 @@ function windVector(value, fallback) {
* neutral white below 0.78 linear — snow is the brightest albedo in a scene
* and still has to sit UNDER the tone curve's shoulder, or its own
* shading clips to one flat card); `up` THREE.Vector3 or [x, y, z], the scene's up
- * (default +Y); `wind` THREE.Vector3 or [x, y, z] it blows TOWARD,
- * its LENGTH 0..1 the strength (default none, an even fall);
+ * (default +Y); `wind` the scene's wind (shader.js `readWind`) it blows
+ * TOWARD, its horizontal LENGTH 0..1 the strength (default none, an even fall);
* `melt` 0..1 how high the thaw has climbed, or
* `{ amount, at, radius }` to melt around a warm point as well
* (default 0); `seed` moves the drifts (default 1).
@@ -294,8 +292,8 @@ export function patchSnow(material, opts = {}) {
* `color` THREE.Color or hex (default a warm ochre at 0.42 linear, the
* luminance family a lit ground sits in — a paler one renders as cream
* under a physical sun and stops reading as sand at all); `wind`
- * THREE.Vector3 or [x, y, z] it blows TOWARD, its LENGTH 0..1 the
- * strength (default [1, 0, 0]); `up` THREE.Vector3 or [x, y, z], the
+ * the scene's wind (shader.js `readWind`) it blows TOWARD, its
+ * horizontal LENGTH 0..1 the strength (default [1, 0, 0]); `up` THREE.Vector3 or [x, y, z], the
* scene's up (default +Y); `seed` moves the drifts (default 1).
* @returns {THREE.Material} The same material, with its uniforms live
* on `material.userData.uniforms`, so `uSandWind` can swing with a
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js
index f719f7f7..a2ccd903 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/clouds.js
@@ -4,7 +4,7 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32, fbm2 } from './noise.js';
-import { makeShaderMaterial, keepOutOfDepthPasses, sunVector } from './shader.js';
+import { makeShaderMaterial, keepOutOfDepthPasses, readWind, sunVector } from './shader.js';
// Cumulus/cirrus mood presets, graded for THIS renderer: ACES filmic at
// exposure 1.0, sRGB out, and nothing after that rescues a dim top or
@@ -153,7 +153,7 @@ export function makeClouds(opts = {}) {
const altitude = opts.altitude ?? p.altitude ?? 260;
const spread = opts.spread ?? p.spread ?? 120;
const alpha = opts.alpha ?? p.alpha ?? 0.92;
- const wind = opts.wind ?? 3.0;
+ const wind = readWind(opts.wind, 3.0, 'makeClouds wind').strength;
const stretch = opts.stretch ?? p.stretch ?? 1.0;
if (!Number.isSafeInteger(seed) || !Number.isInteger(count) || count < 0 || count > 1000 ||
![area, altitude, spread, alpha, wind, stretch].every(Number.isFinite) ||
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js
index f10c7505..c586b58e 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloudvolume.js
@@ -15,7 +15,7 @@
* reconstruction or external textures are required.
*/
import * as THREE from 'three';
-import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe } from './shader.js';
+import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, readWind } from './shader.js';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { bakeFbm3, dataTexture3D, mulberry32, sampleGrid3 } from './noise.js';
@@ -179,7 +179,7 @@ float cloudSunDepth(vec3 position, float jitter) {
*/
export function makeCloudVolume(opts = {}) {
const size = vector(opts.size, [600, 180, 360], 3, 'size');
- const wind = vector(opts.wind, [2.5, .4], 2, 'wind');
+ const w = readWind(opts.wind, [2.5, .4], 'makeCloudVolume wind'), wind = [w.x, w.z];
const direction = vector(opts.sunDirection, [-.5, .7, -.3], 3, 'sunDirection');
const seed = opts.seed ?? 19;
const coverage = opts.coverage ?? .55;
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js
index acf0f08b..e0887acd 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/fire.js
@@ -20,7 +20,7 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
-import { makeShaderMaterial, keepOutOfDepthPasses, patchStandard } from './shader.js';
+import { makeShaderMaterial, keepOutOfDepthPasses, patchStandard, readWind } from './shader.js';
const finite = (v, fallback, lo, hi) => Number.isFinite(v)
? THREE.MathUtils.clamp(v, lo, hi) : fallback;
@@ -172,7 +172,7 @@ function installDispose(group) {
/**
* @param {object} [opts]
* radius=.35, height=1.1: flame envelope in metres; style='campfire'|'candle'.
- * wind=[x,z]: lateral lean / height, bounded to ±.6. intensity=1: emission.
+ * wind=[x,z] (or any shader.js readWind spelling): lateral lean / height, bounded to ±.6. intensity=1: emission.
* quality='medium'; seed=7; embers=26 (0 for candle), max 256.
* light=true, lightIntensity=14 (candela), lightDistance=height*8.
* Flame geometry only: add your own logs/burner. userData.bounds is local and
@@ -184,7 +184,10 @@ export function makeFire(opts = {}) {
const height = finite(opts.height, candle ? 0.055 : 1.1, 0.004, 50);
const intensity = finite(opts.intensity, 1, 0, 8);
const seed = finite(opts.seed, 7, -2147483648, 2147483647) | 0;
- const wind = [finite(opts.wind?.[0], 0, -0.6, 0.6), finite(opts.wind?.[1], 0, -0.6, 0.6)];
+ const w = readWind(opts.wind, [0, 0], 'makeFire wind');
+ // bounded to ±.6 per axis by scaling both, so a strong wind still leans the way it blows
+ const lean = 0.6 / Math.max(0.6, Math.abs(w.x), Math.abs(w.z));
+ const wind = [w.x * lean, w.z * lean];
const steps = Object.hasOwn(QUALITY, opts.quality) ? QUALITY[opts.quality] : QUALITY.medium;
const extentX = radius * 1.65 + Math.abs(wind[0]) * height * 1.2;
const extentZ = radius * 1.65 + Math.abs(wind[1]) * height * 1.2;
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js
index 542d2a1c..c7c8d9c1 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js
@@ -29,7 +29,7 @@
*/
import * as THREE from 'three';
import { bakeFbm3, dataTexture3D, mulberry32, sampleGrid3 } from './noise.js';
-import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, withRendererState } from './shader.js';
+import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, readWind, withRendererState } from './shader.js';
import { snapshotResources, attachDisposal } from './lifecycle.js';
const TIERS = {
@@ -314,7 +314,7 @@ export function makeFireField(opts = {}) {
const seed=number(opts.seed,7,-2147483648,2147483647,'seed');
if(!Number.isInteger(seed))throw new RangeError('makeFireField: seed must be an integer');
const quality=opts.quality??'balanced';if(!Object.hasOwn(TIERS,quality))throw new RangeError('makeFireField: invalid quality');
- const tier=TIERS[quality],wind=vector(opts.wind,[.12,0],2,'wind');
+ const tier=TIERS[quality],w=readWind(opts.wind,[.12,0],'makeFireField wind'),wind=[w.x,w.z];
if(wind.some(v=>Math.abs(v)>8))throw new RangeError('makeFireField: wind exceeds8m/s');
const intensity=number(opts.intensity,1,0,8,'intensity'),turbulence=number(opts.turbulence,1,0,2,'turbulence');
const radius=sources.reduce((s,e)=>s+e.radius,0)/sources.length;
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/foliage_shade.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/foliage_shade.js
index dcfa05a8..6cab58b0 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/foliage_shade.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/foliage_shade.js
@@ -10,7 +10,7 @@
*/
import * as THREE from 'three';
-import { glslLocalDir, patchStandard } from './shader.js';
+import { glslLocalDir, patchStandard, readWind } from './shader.js';
// three applies instanceMatrix in <project_vertex>, AFTER the body
// patched in here, so anything that needs world space at this point has
@@ -200,7 +200,7 @@ export function patchLeafSSS(material, opts = {}) {
* @returns {THREE.Material} The same material.
*/
export function patchWind(material, opts = {}) {
- const dir = (opts.dir || new THREE.Vector2(1, 0.35)).clone().normalize();
+ const dir = readWind(opts.dir, [1, 0.35], 'patchWind dir').dir;
const strength = opts.strength === undefined ? 0.25 : opts.strength;
const speed = opts.speed === undefined ? 0.9 : opts.speed;
const height = opts.height === undefined ? 4 : opts.height;
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js
index 5096153d..31e33cbd 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js
@@ -29,7 +29,7 @@ import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { fbm2, mulberry32 } from './noise.js';
import {
- glslLocalDir, patchStandard, shadowLike, tickShaders, unit,
+ glslLocalDir, patchStandard, readWind, shadowLike, tickShaders, unit,
} from './shader.js';
// Blade shape: enough rows to curve, one column because the width is
@@ -103,27 +103,15 @@ export function makeGrass(opts = {}) {
}
/**
- * Read the `wind` option in either of its two spellings: a number
- * (strength) or {dir (alias `direction`): [x,z] or {x,y}, strength, speed}.
- *
- * Exported because one scene's wind has to move its meadow,
- * its reeds and its trees as ONE wind: a library that
- * re-implements this reader is a library that will drift
- * away from it.
+ * The grass family's reading of the scene's one `wind` (shader.js
+ * `readWind`: a number, [x,z], a vector or {dir|direction, strength,
+ * speed}): its direction, `amp` radians of tip bend at a full gust from a
+ * 1 = breeze strength, and speed. Meadow, reeds, trees, canopy, flowers,
+ * cloth and small life all read it here, so one wind moves them alike.
*/
export function windOf(w) {
- const o = (w && typeof w === 'object') ? w : { strength: w };
- const d = o.dir ?? o.direction;
- const dir = new THREE.Vector2(
- d ? (d.x === undefined ? d[0] : d.x) : 1,
- d ? (d.y === undefined ? d[1] : d.y) : 0.45);
- if (dir.lengthSq() < 1e-9) dir.set(1, 0);
- return {
- dir: dir.normalize(),
- // Radians of tip bend at a full gust, from a 1 = breeze strength.
- amp: 0.5 * (o.strength === undefined ? 1 : o.strength),
- speed: o.speed === undefined ? 1 : o.speed,
- };
+ const r = readWind(w, { dir: [1, 0.45], strength: 1 }, 'wind');
+ return { dir: r.dir, amp: 0.5 * r.strength, speed: r.speed };
}
/**
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js
index 2d2c36ae..3e6318fc 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/meadow.js
@@ -9,8 +9,8 @@
* makeMeadow({size:[10,10], density:700, height:.38, seed:12, heightAt,
* mask, wind:{dir:[1,.3],strength:1,speed:1}, dry:.12,
* shadows:true, ground:true, diversity:.85, seedHeads:.003}) -> Group; userData.update(t), dispose().
- * wind is grass.js's `windOf`: a number (strength) or {dir|direction, strength, speed},
- * so one wind moves the meadow, grass and trees alike (strength 1 = breeze).
+ * wind is grass.js's `windOf` over shader.js `readWind`: a number (strength), [x,z] or
+ * {dir|direction, strength, speed}, so one wind moves the meadow, grass and trees alike (strength 1 = breeze).
* density = blades/m² before the mask; maxBlades bounds memory and triangles.
* mask(x,z) -> 0..1 and heightAt(x,z) are LOCAL coordinates. A mask of 0
* leaves soil, a mask of 1 grows all blades. diversity (0..1) blends between
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js
index fc3021c7..46ee8e95 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ocean.js
@@ -16,7 +16,7 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32 } from './noise.js';
-import { GLSL_UTIL, makeLightProbe, planarCapture } from './shader.js';
+import { GLSL_UTIL, makeLightProbe, planarCapture, readWind } from './shader.js';
import { Reflector } from 'three/addons/objects/Reflector.js';
const TAU = Math.PI * 2;
@@ -289,15 +289,10 @@ export function makeOceanSurface(opts = {}) {
finite(opts.reflectionSize, 512, 'reflectionSize', 64, 2048)
);
const seed = finite(opts.seed, 42, 'seed', 0, 4294967295);
- const wind = opts.windDirection ?? [1, 0.2];
- if (
- !Array.isArray(wind) ||
- wind.length !== 2 ||
- !wind.every(Number.isFinite) ||
- Math.hypot(...wind) < 1e-8
- )
+ const wind = readWind(opts.windDirection, [1, 0.2], 'makeOceanSurface windDirection');
+ if (Math.hypot(wind.x, wind.z) < 1e-8)
throw new RangeError('makeOceanSurface: windDirection must be a nonzero [x,z]');
- const windAngle = Math.atan2(wind[1], wind[0]);
+ const windAngle = Math.atan2(wind.z, wind.x);
const rng = mulberry32(seed),
waves = [],
phases = [];
@@ -400,7 +395,7 @@ export function makeOceanSurface(opts = {}) {
seaSunColor: { value: new THREE.Color(0xffffff) },
seaAmbient: { value: new THREE.Color(0.28, 0.36, 0.43) },
seaKey: { value: new THREE.Color(0.8, 0.8, 0.8) },
- seaWind: { value: new THREE.Vector2(...wind).normalize() },
+ seaWind: { value: wind.dir.clone() },
seaRotation: { value: new THREE.Matrix3() },
},
]);
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js
index 5bec6ff2..b04ab33d 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js
@@ -13,7 +13,7 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { mulberry32, fbm2, noiseDataTexture } from './noise.js';
-import { makeShaderMaterial, keepOutOfDepthPasses } from './shader.js';
+import { makeShaderMaterial, keepOutOfDepthPasses, readWind } from './shader.js';
const _UP = new THREE.Vector3(0, 1, 0);
@@ -127,7 +127,7 @@ export function makeRain(opts = {}) {
const speed = opts.speed === undefined ? 14 : opts.speed;
const length = opts.length === undefined ? 0.6 : opts.length;
const width = opts.width === undefined ? 0.014 : opts.width;
- const wind = opts.wind || [1.4, 0];
+ const w = readWind(opts.wind, [1.4, 0], 'makeRain wind'), wind = [w.x, w.z];
const opacity = opts.opacity === undefined ? 0.42 : opts.opacity;
const follow = opts.follow === false ? 0 : 1;
const center = opts.center || [0, height * 0.5, 0];
@@ -143,9 +143,9 @@ export function makeRain(opts = {}) {
}
if (!Number.isInteger(count) || count < 0 || count > 1000000 ||
- ![radius, height, speed, length, width, opacity, ...wind, ...center].every(Number.isFinite) ||
+ ![radius, height, speed, length, width, opacity, ...center].every(Number.isFinite) ||
radius <= 0 || height <= 0 || speed <= 0 || length <= 0 || width <= 0 || opacity < 0 || opacity > 1 ||
- wind.length !== 2 || center.length !== 3) {
+ center.length !== 3) {
throw new RangeError('makeRain: use finite positive dimensions/speed, count 0..1000000, wind [x,z], center [x,y,z] and opacity 0..1');
}
const rand = mulberry32(seed);
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js
index 11b651e0..2cf7d5b0 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sand.js
@@ -5,7 +5,7 @@
import * as THREE from 'three';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { fbm2, mulberry32 } from './noise.js';
-import { patchStandard } from './shader.js';
+import { patchStandard, readWind } from './shader.js';
import { triangleValue } from './terrain.js';
const TAU = Math.PI * 2;
@@ -74,13 +74,7 @@ export function makeSandTerrain(opts = {}) {
const [width, depth] = size;
const nx = clamp(Math.round(opts.segments ?? 256), 8, 512);
const nz = clamp(Math.round(nx * depth / width), 8, 512);
- const direction = opts.windDirection ?? [1, 0.18];
- if (!Array.isArray(direction) || direction.length !== 2 || !direction.every(Number.isFinite)) {
- throw new RangeError('sand windDirection must be two finite numbers [x,z]');
- }
- const wind = new THREE.Vector2(...direction);
- if (wind.lengthSq() < 1e-8) wind.set(1, 0);
- wind.normalize();
+ const wind = readWind(opts.windDirection, [1, 0.18], 'makeSandTerrain windDirection').dir;
const height = Math.max(0, opts.duneHeight ?? 3.8);
const spacing = Math.max(1, opts.duneSpacing ?? 19);
const phase = rand() * spacing;
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js
index 195ef480..92ffff27 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js
@@ -239,6 +239,55 @@ export function sunVector(azDeg, elDeg) {
Math.cos(el) * Math.sin(az));
}
+/**
+ * Read "the scene's wind" in every spelling the library documents, so ONE
+ * wind can be handed to every effect: a number (strength, along the
+ * fallback's direction); `[x, z]`; `[x, y, z]` or a THREE.Vector3 / `{x, y, z}`
+ * (y is ignored); a THREE.Vector2 / `{x, y}` (y is world z); or `{ dir |
+ * direction, strength, speed }` with `dir` in any of those forms.
+ * `null`/missing reads `fallback`, which takes the same spellings; anything
+ * else throws a RangeError naming `label`.
+ *
+ * Returns `{ x, z, dir, strength, speed }`: (x, z) is the horizontal
+ * vector — an array or vector IS it, an object is dir * strength; `dir`
+ * its unit Vector2 over world XZ ((1, 0) when it has no direction);
+ * `speed` defaults to 1. Each effect keeps its own units for strength.
+ */
+export function readWind(value, fallback, label = 'wind') {
+ const bad = () => new RangeError(`${label}: a wind is a number, [x, z], [x, y, z], `
+ + 'a THREE vector or { dir, strength, speed } of finite numbers');
+ // [x, z] of an array or a vector, or null when it is neither
+ const xz = (v) => {
+ const r = Array.isArray(v) ? (v.length === 2 ? [v[0], v[1]] : v.length === 3 ? [v[0], v[2]] : null)
+ : v && typeof v === 'object' && v.x !== undefined ? [v.x, v.z ?? v.y] : null;
+ if (r && !r.every(Number.isFinite)) throw bad();
+ return r;
+ };
+ const unitXZ = ([x, z]) => {
+ const l = Math.hypot(x, z);
+ return l > 1e-9 ? new THREE.Vector2(x / l, z / l) : new THREE.Vector2(1, 0);
+ };
+ const w = value ?? fallback;
+ const vec = xz(w);
+ if (vec) return { x: vec[0], z: vec[1], dir: unitXZ(vec), strength: Math.hypot(...vec), speed: 1 };
+ if (typeof w !== 'number' && !(w && typeof w === 'object')) throw bad();
+ const o = typeof w === 'number' ? { strength: w } : w;
+ const d = o.dir ?? o.direction;
+ let dir;
+ if (d !== undefined && d !== null) {
+ const v = xz(d);
+ if (!v) throw bad();
+ dir = unitXZ(v);
+ } else {
+ dir = w !== fallback && fallback !== undefined && fallback !== null
+ ? readWind(fallback, null, label).dir : new THREE.Vector2(1, 0);
+ }
+ const strength = o.strength ?? 1;
+ const speed = o.speed ?? 1;
+ if (!Number.isFinite(strength) || !Number.isFinite(speed)) throw bad();
+ return { x: dir.x * strength, z: dir.y * strength, dir, strength, speed };
+}
+
/** Read a Vector3, an array or an {x,y,z} into a new Vector3. */
export function readVec3(p, fx = 0, fy = 0, fz = 0) {
if (!p) return new THREE.Vector3(fx, fy, fz);
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js
index 1b5c0409..feca376a 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smoke.js
@@ -13,7 +13,7 @@
* Overlapping transparent objects use ordinary Three.js object sorting.
*/
import * as THREE from 'three';
-import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe } from './shader.js';
+import { makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, readWind } from './shader.js';
import { attachDisposal, snapshotResources } from './lifecycle.js';
import { bakeFbm3, dataTexture3D, mulberry32, sampleGrid3 } from './noise.js';
@@ -124,7 +124,7 @@ function makePlume(opts, steam) {
const radius = opts.radius ?? height * (steam ? .09 : .047);
const spread = opts.spread ?? (steam ? .16 : .20);
const rise = opts.riseSpeed ?? height * (steam ? .38 : .2333333);
- const wind = opts.wind?.toArray ? opts.wind.toArray() : opts.wind ?? [height * .02, 0];
+ const w = readWind(opts.wind, [height * .02, 0], 'makeSmoke/makeSteam wind'), wind = [w.x, w.z];
const extinction = opts.density ?? (steam ? 2.1 : 5) / height;
const turbulence = opts.turbulence ?? (steam ? .9 : 1);
const dissipation = opts.dissipation ?? (steam ? 1.2 : .7);
@@ -133,7 +133,7 @@ function makePlume(opts, steam) {
if (![height,radius,spread,rise,extinction,turbulence,dissipation,anisotropy].every(Number.isFinite) ||
height < .001 || height > 10000 || radius <= 0 || radius > height * 4 || spread < 0 || spread > 2 ||
rise <= 0 || extinction < 0 || turbulence < 0 || turbulence > 2 || dissipation < 0 ||
- Math.abs(anisotropy) > .9 || !Array.isArray(wind) || wind.length !== 2 || !wind.every(Number.isFinite) ||
+ Math.abs(anisotropy) > .9 ||
!Number.isSafeInteger(seed) || !Object.hasOwn(TIERS,quality) || Math.hypot(...wind) / rise > 10) {
throw new RangeError('makeSmoke/makeSteam: invalid dimensions, flow, density, scattering, seed or quality');
}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js
index a807438e..8ef120ff 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js
@@ -52,24 +52,12 @@ import { attachDisposal, snapshotResources } from './lifecycle.js';
import { lehmer } from './noise.js';
import {
glslWob, instancedQuad, keepOutOfDepthPasses, makeShaderMaterial,
- tickShaders, wobX, wobZ } from './shader.js';
+ readWind, tickShaders, wobX, wobZ } from './shader.js';
// Terminal fall of medium rain. Written once because the slant, the
// sheet length and the streak rate must all read the same number.
const _RAIN_FALL = 9.0;
-/** Horizontal velocity in xz from a number, an array or a vector. */
-function toWind(v, dx, dz) {
- if (typeof v === 'number') return new THREE.Vector2(v, 0);
- if (Array.isArray(v)) {
- return new THREE.Vector2(v[0] || 0,
- (v.length > 2 ? v[2] : v[1]) || 0);
- }
- if (v && v.isVector3) return new THREE.Vector2(v.x, v.z);
- if (v && v.isVector2) return new THREE.Vector2(v.x, v.y);
- return new THREE.Vector2(dx, dz);
-}
-
// The swing: `wobX`/`wobZ` on the CPU mirror, the same pair in GLSL.
const _WOB_GLSL = glslWob('astraVeilWob');
@@ -258,7 +246,8 @@ export function makeRainVeil(opts = {}) {
opts.extent === undefined ? 120 : opts.extent);
const height = Math.max(3,
opts.height === undefined ? 60 : opts.height);
- const wind = toWind(opts.direction, 3.5, 0);
+ const w = readWind(opts.direction, [3.5, 0], 'makeRainVeil direction');
+ const wind = new THREE.Vector2(w.x, w.z);
const density = Math.min(0.97, Math.max(0.02,
opts.density === undefined ? 0.6 : opts.density));
const color = new THREE.Color(
@@ -497,7 +486,8 @@ export function makeSnowfall(opts = {}) {
const rate = Math.max(1, opts.rate === undefined ? 260 : opts.rate);
const size = Math.max(0.002,
opts.size === undefined ? 0.035 : opts.size);
- const drift = toWind(opts.drift, 0.35, 0);
+ const d = readWind(opts.drift, [0.35, 0], 'makeSnowfall drift');
+ const drift = new THREE.Vector2(d.x, d.z);
const color = new THREE.Color(
opts.color === undefined ? 0xf2f7ff : opts.color);
const rnd = lehmer(opts.seed === undefined ? 9 : opts.seed);
diff --git a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
index 83e6b805..35254577 100644
--- a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
+++ b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
@@ -25,7 +25,7 @@ says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says
| thick broken ice with actual open fissures | `makeFracturedIce({ size: [8,6], thickness: 0.28, crackDensity: 0.65, frost: 0.35, seed })` — `lib/ice.js`; closed floes, bevels, internal air and local optical thickness. Nominal top is y=0. `userData.sampleHeight(x,z)` returns local top height or null in a gap. Supply an opaque lakebed/water backing: transparent volumes are not recursively refracted. |
| dunes, wind ripples, sand grains | `makeSandTerrain({ size: [60, 60], duneHeight: 3, duneSpacing: 18, windDirection: [1, 0.3], seed })` — `lib/sand.js`; Group with `userData.sampleHeight(x, z)` and `userData.update(t, dt)`. Sample height for every prop. |
| a close-view fractured rock or a talus field | `makeRock({ type: 'sandstone', size: [2, 1.5, 2], seed, moisture: 0.2 })` · `makeRockField` — `lib/rock.js`; types sandstone / granite / basalt; closed geometry, stratification and weathering. Rock rests at local y≈0; place using terrain height. |
-| close-view grass with folded blades and flowing wind | `makeMeadow({ size: [8, 8], height: 0.3, density: 900, heightAt, mask, seed, wind: { dir: [1, 0.3], strength: 1.2, speed: 1 } })` — `lib/meadow.js`; its wind is read by grass.js's `windOf`, so one wind object moves meadow, grass and trees alike; mask(x,z) is 0..1 coverage; Group with `userData.update(t, dt)`. Set `ground: false` over an existing terrain. Fit the sun shadow frustum tightly; blades need millimetre-scale shadow texels. |
+| close-view grass with folded blades and flowing wind | `makeMeadow({ size: [8, 8], height: 0.3, density: 900, heightAt, mask, seed, wind: { dir: [1, 0.3], strength: 1.2, speed: 1 } })` — `lib/meadow.js`; every effect's wind option (wind; the veils' direction and drift; the ocean's and sand's windDirection) is read by ONE reader, `readWind` in `lib/shader.js` — a number, `[x, z]`, a vector or this object — so one wind object moves meadow, grass, trees, fire, smoke and rain alike; mask(x,z) is 0..1 coverage; Group with `userData.update(t, dt)`. Set `ground: false` over an existing terrain. Fit the sun shadow frustum tightly; blades need millimetre-scale shadow texels. |
| a grassy surface | `makeGrass({ extent, density, height, heightAt, patchy })` — `lib/grass.js` |
| a complete near/middle-distance tree or shrub | `makeTree({ species: 'oak', height: 6, crownRadius: 2.5, leafDensity: 1, seed, wind: { dir: [1,0.3], strength: 0.5, speed: 1 } })` · `makeShrub` — `lib/tree.js`; oak/birch/willow, connected branches, individual leaves and matching moving shadows. Root at y=0, actual envelope in `userData.bounds`. A default tree is heavy geometry. `leafSegments: 4` reduces per-leaf geometry while preserving crown density; species defaults are 10–16 for close views. Also lower `opts.maxLeaves`/`opts.leafDensity`, or use distant imposters when leaves are unresolved. |
| A CROWN OF LEAVES — every broadleaf tree, hedge and bush | `makeCanopy({ crowns: [{position, radius, height}] — or [{position, size:[x,y,z]}] for a mass that is not a ball, which is how a HEDGE is built — color, hue, wind })` — `lib/canopy.js`. NEVER a displaced sphere: see the rule at the end. |
diff --git a/harness/tests/scene_runtime/lib/test_shader.py b/harness/tests/scene_runtime/lib/test_shader.py
index 9f8c61ef..3e1ca1ed 100644
--- a/harness/tests/scene_runtime/lib/test_shader.py
+++ b/harness/tests/scene_runtime/lib/test_shader.py
@@ -394,3 +394,70 @@ console.log(JSON.stringify({ tail }));
assert out["tail"] == ("#include <roughnessmap_fragment>\n"
"#include <metalnessmap_fragment>\n"
"#include <opaque_fragment>\n}")
+
+
+# The catalog's one wind object, the [x,z] pair the fire/smoke rows use, a number and a
+# Vector3: each handed to every wind reader. Before readWind, the object threw in
+# firefield/smoke/clouds/cloudvolume (RangeError) and rain (TypeError), fire read no wind,
+# snow read NaN, and windOf ignored the pair and blew the default way.
+_WIND = """
+import * as THREE from 'three';
+import { readWind } from './lib/shader.js';
+import { windOf } from './lib/grass.js';
+import { makeFire } from './lib/fire.js';
+import { makeFireField } from './lib/firefield.js';
+import { makeSmoke } from './lib/smoke.js';
+import { makeRain } from './lib/rain.js';
+import { makeCloudVolume } from './lib/cloudvolume.js';
+import { makeClouds } from './lib/clouds.js';
+import { patchSnow } from './lib/accumulation.js';
+import { makeRainVeil } from './lib/veils.js';
+const uni = (g, name) => { let u; g.traverse((o) => { const v = o.material?.uniforms?.[name]; if (v && !u) u = v.value; }); return u; };
+const xz = (v) => v.isVector3 ? [v.x, v.z] : typeof v === 'number' ? [v, 0] : [v.x, v.y];
+const winds = { object: { dir: [1, 0.3], strength: 1.2, speed: 1 }, pair: [1, 0.3], number: 1.2,
+ vec3: new THREE.Vector3(1, 5, 0.3) };
+const out = {};
+for (const [k, w] of Object.entries(winds)) {
+ const r = readWind(w, [0, 0]);
+ out[k] = {
+ read: [r.dir.x, r.dir.y],
+ windOf: xz(windOf(w).dir),
+ fire: xz(uni(makeFire({ wind: w }), 'uWind')),
+ firefield: 'ok' && makeFireField({ emitters: [{ position: [0, 0, 0], radius: 0.3, height: 1 }], wind: w, quality: 'low' }) && 'ok',
+ smoke: xz(makeSmoke({ wind: w }).material.uniforms.uWind.value),
+ rain: (({ x, z }) => [x, z])(makeRain({ wind: w, count: 10 }).material.uniforms.uVel.value),
+ cloudVolume: xz(makeCloudVolume({ wind: w, quality: 'low' }).material.uniforms.uWind.value),
+ clouds: uni(makeClouds({ wind: w, count: 2 }), 'uWind'),
+ snow: xz(patchSnow(new THREE.MeshStandardMaterial(), { wind: w }).userData.uniforms.uSnowWind.value),
+ veil: xz(uni(makeRainVeil({ direction: w }), 'uWind')),
+ };
+}
+console.log(JSON.stringify(out));
+"""
+
+_WIND_LIBS = ("grass.js", "fire.js", "firefield.js", "smoke.js", "rain.js", "cloudvolume.js",
+ "clouds.js", "accumulation.js", "veils.js")
+
+
[email protected](scope="module")
+def wind() -> dict:
+ return measure(_WIND, _WIND_LIBS)
+
+
[email protected]("spelling", ["object", "pair", "number", "vec3"])
+def test_one_wind_is_read_the_same_way_by_every_effect(wind, spelling):
+ import math
+ w = wind[spelling]
+ ref = w["read"]
+ # the number has no direction of its own: it blows along the fallback's
+ expect = [1, 0] if spelling == "number" else [1 / math.hypot(1, 0.3), 0.3 / math.hypot(1, 0.3)]
+ assert ref == pytest.approx(expect)
+ for reader in ("fire", "smoke", "rain", "cloudVolume", "snow", "veil"):
+ v = w[reader]
+ n = math.hypot(*v)
+ assert n > 0 and all(math.isfinite(c) for c in v), (reader, v)
+ if spelling != "number": # a number blows along each effect's own default direction
+ assert (v[0] / n, v[1] / n) == pytest.approx(tuple(ref), abs=1e-6), (reader, v)
+ if spelling != "number": # windOf's own fallback direction is (1, 0.45)
+ assert w["windOf"] == pytest.approx(ref)
+ assert w["firefield"] == "ok" and math.isfinite(w["clouds"]) and w["clouds"] > 0