Official Codebase of 3DCodeVerse
Python
lib: one world-space base and one copy of each shared helper
gaoypeng1503efc30c30
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.jsindex 41c0e007..f98ed9b0 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js@@ -26,109 +26,33 @@*/import * as THREE from 'three';-import { patchStandard, composeRoughness } from './shader.js';--// Named as terrain_shade, waterside, surface_wear and aging name them,-// so a material wearing several libraries declares ONE pair; the vertex-// locals are ac* because those four own astraWp, wsP, wrP and agP.-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',-].join('\n');+import {+ patchStandard, composeRoughness, glslAxes, glslCurv, glslTriNoise,+ seedVec3, toColor, towardRoughness, unit, upVector, worldBase,+} from './shader.js';// Both patches read these, so they are declared once, in the base.// astraAcc*, not a neighbour's spelling: patchStandard THROWS when two// chained patches give one function name two different bodies.const ACC_HEAD = [- 'vec3 astraAccAxes(vec3 n) {',- ' vec3 w = abs(n * n * n);',- ' return w / max(w.x + w.y + w.z, 1e-4);',- '}',+ glslAxes('astraAccAxes'),// Three world-plane projections blended by the normal: a deposit// must break up the same way on a wall, a roof and a boulder.- 'float astraAccNoise(vec3 p, vec3 w) {',- ' return astraNoise2(p.yz + 23.1) * w.x',- ' + astraNoise2(p.zx + 57.7) * w.y',- ' + astraNoise2(p.xy + 91.3) * w.z;',- '}',- // Curvature in 1/m: how far the normal turns per metre of surface- // under one pixel. NEGATIVE is the concave lee that holds what a- // convex edge sheds. Zero across a hard, unwelded edge.- 'float astraAccCurv(vec3 n, vec3 p) {',- ' vec3 dx = dFdx(p), dy = dFdy(p);',- ' float d = dot(dx, dx) + dot(dy, dy);',- ' return (dot(dFdx(n), dx) + dot(dFdy(n), dy)) / max(d, 1e-12);',- '}',+ glslTriNoise('astraAccNoise', 23.1, 57.7, 91.3),+ // NEGATIVE curvature is the concave lee that holds what a convex+ // edge sheds.+ glslCurv('astraAccCurv'),].join('\n');-// One base for both. `transformed` is still object-space after-// <begin_vertex>, so the instance transform is folded in by hand or-// every scattered copy takes its weather from the world origin.-const BASE = {- name: 'acc:base',- vertexHead: WORLD_VARYINGS,- vertexBody: [- ' vec4 acP = vec4(transformed, 1.0);',- ' vec3 acN = normal;',- '#ifdef USE_INSTANCING',- ' acP = instanceMatrix * acP;',- ' acN = mat3(instanceMatrix) * acN;',- '#endif',- ' vAstraWorld = (modelMatrix * acP).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(acN, 0.0)).xyz);',- ].join('\n'),- fragmentHead: [WORLD_VARYINGS, ACC_HEAD].join('\n'),-};--/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}+// One base for both, on the world varyings every library shares; the+// vertex locals are ac* because terrain_shade, waterside, surface_wear+// and aging own astraWp, wsP, wrP and agP.+const BASE = worldBase('acc:base', 'acP', 'acN', ACC_HEAD);-/** Clamp to 0..1 without importing MathUtils for one call. */-function unit(value) {- return Math.max(0, Math.min(1, value));-}--/** fract(), which JS's % gets wrong for a negative seed. */-function frac(x) {- return x - Math.floor(x);-}--/** astraHash11 from GLSL_UTIL, so CPU and shader agree on a seed. */-function hash11(x) {- let p = frac(x * 0.1031);- p *= p + 33.33;- return frac(p * (p + p));-}--/**- * Turn a seed into a noise-space offset, so two materials differ.- *- * The offset is a UNIFORM: a seed baked into the GLSL would be fixed- * for every material sharing the cache key. The constants differ from- * surface_wear's and aging's, or one seed would drift this library's- * snow along that library's blotches.- */-function seedOffset(seed, salt) {- return new THREE.Vector3(- hash11(seed + salt + 1.61), hash11(seed + salt + 8.09),- hash11(seed + salt + 13.77)).multiplyScalar(56);-}--/**- * Read `up`-style options as a unit vector, never as NaN.- *- * A degenerate vector would divide by zero in the shader and paint the- * object black, so a zero-length one falls back to world up.- */-function upVector(value) {- const v = new THREE.Vector3(0, 1, 0);- if (value) v.fromArray(value.toArray ? value.toArray() : value);- if (!(v.lengthSq() > 1e-9)) v.set(0, 1, 0);- return v.normalize();-}+// The constants differ from surface_wear's and aging's, or one seed+// would drift this library's snow along that library's blotches.+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.@@ -144,20 +68,6 @@ function windVector(value, fallback) {return v;}-/**- * Move the material's gloss toward the cover's, never past it.- *- * Roughness is per MATERIAL here, so a cover can only say how much of- * the surface is no longer the material: `blend` 0 leaves it alone, 1- * hands the whole material to the cover's own roughness.- */-function towardRoughness(material, target, blend) {- const store = material.userData.astraRoughness;- const base = store ? store.base : material.roughness;- if (!(base > 0)) return 1;- return 1 + (target / base - 1) * unit(blend);-}-/*** Lay snow on everything at once, by how each surface is turned.*@@ -236,7 +146,6 @@ export function patchSnow(material, opts = {}) {uSnowWarm: { value: new THREE.Vector4(warm.x, warm.y, warm.z, warmR) },uSnowSeed: { value: seedOffset(seed, 0.7) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uSnowDepth;','uniform vec3 uSnowColor;',@@ -413,7 +322,6 @@ export function patchSand(material, opts = {}) {uSandUp: { value: upVector(opts.up) },uSandSeed: { value: seedOffset(seed, 3.9) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uSandAmt;','uniform vec3 uSandColor;',diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/aging.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/aging.jsindex d10555b3..fc904fac 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/aging.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/aging.js@@ -33,25 +33,16 @@* leaching out of, and nothing in this file may hardcode a light.*/-import * as THREE from 'three';-import { patchStandard, composeRoughness } from './shader.js';--// Named as terrain_shade, waterside and surface_wear name them, so a-// material wearing several libraries declares ONE pair; the vertex-// locals are ag* because those three own astraWp, wsP and wrP.-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',-].join('\n');+import {+ patchStandard, composeRoughness, glslAxes, glslCurv, matteFactor,+ seedVec3, toColor, unit, upVector, worldBase,+} from './shader.js';// All three patches read these, so they are declared once, in the base.// Names are age-prefixed rather than shared with surface_wear's: a// neighbour's helper is only there when that neighbour was applied.const AGE_HEAD = [- 'vec3 astraAgeAxes(vec3 n) {',- ' vec3 w = abs(n * n * n);',- ' return w / max(w.x + w.y + w.z, 1e-4);',- '}',+ glslAxes('astraAgeAxes'),// The vertical-streak field: three world-plane projections blended by// the normal, world Y compressed by `lift` in the two upright ones so// a feature is taller than wide on ANY face. lift 1.0 = blotches.@@ -60,90 +51,28 @@ const AGE_HEAD = [' + astraNoise2(p.xz + 41.9) * w.y',' + astraNoise2(vec2(p.x, p.y * lift) + 73.1) * w.z;','}',- // Curvature in 1/m: how far the normal turns per metre of surface- // under one pixel. Positive is convex (swept clean), negative the- // concave lee that holds. Zero across a hard, unwelded edge.- 'float astraAgeCurv(vec3 n, vec3 p) {',- ' vec3 dx = dFdx(p), dy = dFdy(p);',- ' float d = dot(dx, dx) + dot(dy, dy);',- ' return (dot(dFdx(n), dx) + dot(dFdy(n), dy)) / max(d, 1e-12);',- '}',+ // Positive curvature is convex (swept clean), negative the concave+ // lee that holds.+ glslCurv('astraAgeCurv'),].join('\n');-// One base for all three. `transformed` is still object-space after-// <begin_vertex>, so the instance transform is folded in by hand or-// every scattered copy weathers from the world origin.-const BASE = {- name: 'aging:base',- vertexHead: WORLD_VARYINGS,- vertexBody: [- ' vec4 agP = vec4(transformed, 1.0);',- ' vec3 agN = normal;',- '#ifdef USE_INSTANCING',- ' agP = instanceMatrix * agP;',- ' agN = mat3(instanceMatrix) * agN;',- '#endif',- ' vAstraWorld = (modelMatrix * agP).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(agN, 0.0)).xyz);',- ].join('\n'),- fragmentHead: [WORLD_VARYINGS, AGE_HEAD].join('\n'),-};--/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}+// One base for all three, on the world varyings every library shares;+// the vertex locals are ag* because terrain_shade, waterside and+// surface_wear own astraWp, wsP and wrP.+const BASE = worldBase('aging:base', 'agP', 'agN', AGE_HEAD);-/** Clamp to 0..1 without importing MathUtils for one call. */-function unit(value) {- return Math.max(0, Math.min(1, value));-}--/** fract(), which JS's % gets wrong for a negative seed. */-function frac(x) {- return x - Math.floor(x);-}--/** astraHash11 from GLSL_UTIL, so CPU and shader agree on a seed. */-function hash11(x) {- let p = frac(x * 0.1031);- p *= p + 33.33;- return frac(p * (p + p));-}+// The constants differ from surface_wear's, or one seed would land this+// library's stains on that one's blotches.+const seedOffset = (seed, salt) =>+ seedVec3(seed + salt, 0.29, 5.13, 9.47, 48);-/**- * Turn a seed into a noise-space offset, so two materials differ.- *- * The offset is a UNIFORM: a seed baked into the GLSL would be fixed- * for every material that shares the cache key. The constants differ- * from surface_wear's, or one seed would land this library's stains on- * that one's blotches.- */-function seedOffset(seed, salt) {- return new THREE.Vector3(- hash11(seed + salt + 0.29), hash11(seed + salt + 5.13),- hash11(seed + salt + 9.47)).multiplyScalar(48);-}--/**- * A roughening factor one patch cannot push past fully rough.- *- * Every effect here is matte, so each raises roughness; roughness only- * means anything up to 1, and the material may start near it.- *- * The `add` each patch passes used to be token — a fully rusted steel- * tank moved from 0.45 to 0.50 and went on mirroring the sky, which- * washed the oxide off the frame at every distance. A crust of oxide,- * dust or dried grime is one of the matte-est things there is, so these- * now buy real roughness: the cap keeps a surface that already starts- * rough from moving at all.- */-function matteFactor(material, add) {- const store = material.userData.astraRoughness;- const base = store ? store.base : material.roughness;- return base > 0 ? Math.min(1 + add, 1 / base) : 1;-}+// Every effect here is matte, so each raises roughness through+// `matteFactor`. The `add` each patch passes used to be token — a fully+// rusted steel tank moved from 0.45 to 0.50 and went on mirroring the+// sky, which washed the oxide off the frame at every distance. A crust+// of oxide, dust or dried grime is one of the matte-est things there+// is, so these now buy real roughness: the cap keeps a surface that+// already starts rough from moving at all./*** The vertical streaks that run down from every ledge, sill and joint.@@ -215,7 +144,6 @@ export function patchDripStains(material, opts = {}) {uDripGate: { value: gated ? 1 : 0 },uDripSeed: { value: seedOffset(seed, 0) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uDripAmt;','uniform vec3 uDripColor;',@@ -353,7 +281,6 @@ export function patchRust(material, opts = {}) {uRustScale: { value: Math.max(1e-3, scale) },uRustSeed: { value: seedOffset(seed, 2.3) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uRustAmt;','uniform vec3 uRustColor;',@@ -456,9 +383,7 @@ export function patchRust(material, opts = {}) {export function patchDust(material, opts = {}) {const strength = opts.strength === undefined ? 0.3 : opts.strength;const seed = opts.seed === undefined ? 1 : opts.seed;- const up = new THREE.Vector3(0, 1, 0);- if (opts.up) up.fromArray(opts.up.toArray ? opts.up.toArray() : opts.up);- if (!(up.lengthSq() > 1e-9)) up.set(0, 1, 0);+ const up = upVector(opts.up);composeRoughness(material, 'aging:dust',matteFactor(material, 0.55 * unit(strength)));patchStandard(material, BASE);@@ -467,10 +392,9 @@ export function patchDust(material, opts = {}) {uniforms: {uDustAmt: { value: unit(strength) },uDustColor: { value: toColor(opts.color, 0xb8b2a6) },- uDustUp: { value: up.normalize() },+ uDustUp: { value: up },uDustSeed: { value: seedOffset(seed, 4.7) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uDustAmt;','uniform vec3 uDustColor;',diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.jsindex b50f5a0f..21554d46 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/building.js@@ -124,6 +124,28 @@ function revealMat() {return MAT.plaster({ color: 0x24262c, roughness: 1, hueBreak: 0.05 });}+/**+ * One merged mesh per `[geometries, material, name]` part, then one per+ * lit-room class in `litBins`, added to `root` in that order. Empty+ * parts are skipped.+ */+function addMerged(root, parts, litBins) {+ litBins.forEach((geos, i) => parts.push(+ [geos, litMat(LIT_CLASSES[i]), i ? 'LitRooms' + (i + 1) : 'LitRooms']));+ for (const [geos, mat, nm] of parts) {+ if (!geos.length) continue;+ const merged = geos.length === 1 ? geos[0] : mergeGeometries(geos, false);+ if (!merged) continue;+ const m = new THREE.Mesh(merged, mat);+ m.name = nm;+ // The shell and the lit cards live inside the openings; casting+ // from them only stipples the reveal they are meant to fill.+ m.castShadow = nm !== 'Reveals' && !nm.startsWith('LitRooms');+ m.receiveShadow = true;+ root.add(m);+ }+}+/*** Build a block with modelled openings, a plinth and a cornice.*@@ -270,25 +292,11 @@ export function block(opts = {}) {const root = new THREE.Group();root.name = opts.name || 'Block';- const parts = [[wall, wallMat, 'Walls'],- [trim, trimMat, 'Trim'],- [glassBins[0], glassMats[0], 'Glazing'],- [glassBins[1], glassMats[1], 'Glazing2'],- [dark, darkMat, 'Reveals']];- litBins.forEach((geos, i) => parts.push(- [geos, litMat(LIT_CLASSES[i]), i ? 'LitRooms' + (i + 1) : 'LitRooms']));- for (const [geos, mat, nm] of parts) {- if (!geos.length) continue;- const merged = geos.length === 1 ? geos[0] : mergeGeometries(geos, false);- if (!merged) continue;- const m = new THREE.Mesh(merged, mat);- m.name = nm;- // The shell and the lit cards live inside the openings; casting- // from them only stipples the reveal they are meant to fill.- m.castShadow = nm !== 'Reveals' && !nm.startsWith('LitRooms');- m.receiveShadow = true;- root.add(m);- }+ addMerged(root, [[wall, wallMat, 'Walls'],+ [trim, trimMat, 'Trim'],+ [glassBins[0], glassMats[0], 'Glazing'],+ [glassBins[1], glassMats[1], 'Glazing2'],+ [dark, darkMat, 'Reveals']], litBins);root.userData.forward = '-Z';root.userData.floors = floors + (baseH > 0 ? 1 : 0);return root;@@ -698,25 +706,13 @@ export function cottage(opts = {}) {// to be merged into the Roof mesh and came out terracotta: red// rectangles pasted on a white wall, which is what the flat-facade// complaint actually looked like on a cottage.- const parts = [[walls, wallMat, 'Walls'],- [roof, roofMat, 'Roof'],- [stack, MAT.brick({ color: 0x8f5843, variant: rand() }),- 'Chimney'],- [trim, trimMat, 'Trim'],- [door, doorMat, 'Door'],- [glass, glassMat, 'Glazing']];- litBins.forEach((geos, i) => parts.push(- [geos, litMat(LIT_CLASSES[i]), i ? 'LitRooms' + (i + 1) : 'LitRooms']));- for (const [geos, mat, nm] of parts) {- if (!geos.length) continue;- const merged = geos.length === 1 ? geos[0] : mergeGeometries(geos, false);- if (!merged) continue;- const m = new THREE.Mesh(merged, mat);- m.name = nm;- m.castShadow = !nm.startsWith('LitRooms');- m.receiveShadow = true;- root.add(m);- }+ addMerged(root, [[walls, wallMat, 'Walls'],+ [roof, roofMat, 'Roof'],+ [stack, MAT.brick({ color: 0x8f5843, variant: rand() }),+ 'Chimney'],+ [trim, trimMat, 'Trim'],+ [door, doorMat, 'Door'],+ [glass, glassMat, 'Glazing']], litBins);root.userData.forward = '-Z';root.userData.ridgeY = h + pitch;return root;@@ -765,7 +761,6 @@ export function tower(opts = {}) {root.add(mast);}root.userData.forward = '-Z';- void rand;return root;}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/canopy.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/canopy.jsindex df4694df..9bc5519d 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/canopy.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/canopy.js@@ -29,18 +29,13 @@import * as THREE from 'three';import { fbm3, mulberry32 } from './noise.js';-import { patchStandard, shadowLike, tickShaders } from './shader.js';+import {+ glslLocalDir, patchStandard, shadowLike, tickShaders, unit,+} from './shader.js';import { patchLeafSSS } from './foliage_shade.js';import { windOf } from './grass.js';-const LOCAL_DIR = [- 'vec3 leafLocalDir(vec3 w) {',- ' mat3 m = mat3(modelMatrix);',- ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',- ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',- ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',- '}',-].join('\n');+const LOCAL_DIR = glslLocalDir('leafLocalDir');/*** Build the leaf mass for one or more crowns.@@ -95,7 +90,7 @@ export function makeCanopy(opts = {}) {? Math.max(0.05, Math.min(0.4, thin * 0.12)): opts.size;const seed = opts.seed === undefined ? 7 : opts.seed;- const shell = clamp01(opts.shell === undefined ? 0.72 : opts.shell);+ const shell = unit(opts.shell === undefined ? 0.72 : opts.shell);const droop = opts.droop === undefined ? 0.35 : opts.droop;const hue = opts.hue === undefined ? 0.3 : opts.hue;// Albedos, not screen colours: a scene sun runs at 5-6, so a hex that@@ -121,11 +116,6 @@ function clampSigned(v) {return Math.max(-1, Math.min(1, v));}-/** Clamp to 0..1 without importing MathUtils for three calls. */-function clamp01(v) {- return Math.max(0, Math.min(1, v));-}-/*** A leaf in shadow is darker, cooler AND more saturated — never merely* darker. The old form desaturated it (`s * 0.9`), which is what a@@ -153,7 +143,7 @@ function shadeOf(c) {*/function sunUp(dir) {if (!dir || dir.y === undefined) return 1;- return clamp01((dir.y + 0.09) / 0.09);+ return unit((dir.y + 0.09) / 0.09);}/** Read `crowns`, or the single-crown spelling, into one list. */@@ -269,7 +259,7 @@ function leafField(crowns, opts, shell, size, seed) {vary[k * 4 + 2] = rand() * Math.PI * 2; // twist / phase// Depth into the crown, plus a lift for the leaves the sky sees:// a canopy is lit from ABOVE, not evenly over its shell.- vary[k * 4 + 3] = clamp01(t * (0.72 + 0.28 * (dy * 0.5 + 0.5)));+ vary[k * 4 + 3] = unit(t * (0.72 + 0.28 * (dy * 0.5 + 0.5)));box.expandByPoint(new THREE.Vector3(px, py, pz));}}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/caustics.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/caustics.jsindex fbedecdc..996dfbc9 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/caustics.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/caustics.js@@ -11,27 +11,13 @@*/import * as THREE from 'three';-import { patchStandard } from './shader.js';+import { patchStandard, toColor, WORLD_VARYINGS, worldBody } from './shader.js';-// Named as terrain_shade and waterside name them, so a submerged bank-// wearing a splat, a waterline and this declares ONE pair.-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',-].join('\n');--// `transformed` is still object-space after <begin_vertex>, so an-// instanced boulder takes the origin's depth unless this is folded in.-const CAU_VERTEX = [- ' vec4 cauWp = vec4(transformed, 1.0);',- ' vec3 cauWn = normal;',- '#ifdef USE_INSTANCING',- ' cauWp = instanceMatrix * cauWp;',- ' cauWn = mat3(instanceMatrix) * cauWn;',- '#endif',- ' vAstraWorld = (modelMatrix * cauWp).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(cauWn, 0.0)).xyz);',-].join('\n');+// The world varyings terrain_shade and waterside share, so a submerged+// bank wearing a splat, a waterline and this declares ONE pair; the+// instance transform folded in, or an instanced boulder takes the+// origin's depth.+const CAU_VERTEX = worldBody('cauWp', 'cauWn');const CAU_HEAD = ['uniform float uCauLevel;',@@ -149,12 +135,6 @@ const CAU_BODY = [' * (cauNet * cauK * uCauAmt);',].join('\n');-/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}-/*** Metres a sunbeam slides sideways per metre of depth, REFRACTED.*diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.jsindex 850bccc0..c3aa01aa 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js@@ -37,6 +37,7 @@import * as THREE from 'three';+import { lehmer } from './noise.js';import {instancedQuad, keepOutOfDepthPasses, makeShaderMaterial,tickShaders } from './shader.js';@@ -52,12 +53,6 @@ const ORDER_SHIMMER = 20;const _SIZE = new THREE.Vector2();-/** 16807 LCG: same seed, same sky, on every machine. */-function prng(seed) {- let s = (seed >>> 0) || 1;- return () => ((s = (s * 16807) % 2147483647) / 2147483647);-}-/*** Copy the frame drawn so far into a texture the shimmer can sample.*@@ -170,7 +165,7 @@ export function makeHeatShimmer(opts = {}) {// 30 m one, where a fixed count would give the big card boulders.const cells = opts.cells === undefined? Math.max(2.5, height / 0.95) : opts.cells;- const rnd = prng(opts.seed === undefined ? 5 : opts.seed);+ const rnd = lehmer(opts.seed === undefined ? 5 : opts.seed);// The billboard sweeps a sphere about the card's centre, which is// half a card up: a stated radius, never instancedQuad's 10 km@@ -350,7 +345,7 @@ export function makeStars(opts = {}) {const ambient = Math.min(Math.max(opts.ambient === undefined ? 0.2 : opts.ambient, 0), 1);const bright = ambient >= 0.35;- const rnd = prng(seed);+ const rnd = lehmer(seed);// Galactic pole: the band is a great circle, so one vector fixes// where it crosses the sky.const pole = new THREE.Vector3(0.34, 0.83, -0.44).normalize();@@ -626,7 +621,7 @@ export function makeAurora(opts = {}) {const bright = ambient >= 0.35;const color = opts.color? new THREE.Color(opts.color) : new THREE.Color(0x54ffa8);- const rnd = prng(seed);+ const rnd = lehmer(seed);const n = 3 + Math.round(activity * 4);const base = radius * 0.30;const swing = radius * (0.02 + 0.10 * activity);diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.jsindex 6185591d..b56c4a21 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js@@ -44,7 +44,9 @@ import * as THREE from 'three';import { windOf } from './grass.js';import { mulberry32 } from './noise.js';-import { patchStandard, shadowLike, tickShaders } from './shader.js';+import {+ glslLocalDir, patchStandard, shadowLike, tickShaders, unit,+} from './shader.js';const _TAU = Math.PI * 2;const _G = 9.81;@@ -61,11 +63,6 @@ const _WAVE_MODES = [[2, -1], [2, 2], [3, 1], [1, 3], [3, 2], [2, 3],];-/** Clamp to 0..1 without importing MathUtils for a handful of calls. */-function clamp01(v) {- return Math.max(0, Math.min(1, v));-}-/*** Rotations about Y that send local +X (or +Z) to a world XZ heading.*@@ -176,7 +173,7 @@ function flagSheet(width, height, rad, color, wind, rand) {const pos = geom.attributes.position;const env = new Float32Array(pos.count * 4);for (let i = 0; i < pos.count; i++) {- const u = clamp01((pos.getX(i) - rad) / Math.max(width, 1e-6));+ const u = unit((pos.getX(i) - rad) / Math.max(width, 1e-6));// u^1.6, not u: a linear envelope reads as a sheet hinged at the// mast, and the growth toward the fly is the whole cue.env[i * 4] = u;@@ -433,7 +430,7 @@ function bannerCloth(width, drop, folds, color, wind, rand) {for (let i = 0; i < pos.count; i++) {const x = pos.getX(i) / Math.max(width, 1e-6) + 0.5;const f = prof(x);- data[i * 4] = clamp01(-pos.getY(i) / Math.max(drop, 1e-6));+ data[i * 4] = unit(-pos.getY(i) / Math.max(drop, 1e-6));data[i * 4 + 1] = f.v;data[i * 4 + 2] = f.d / Math.max(width, 1e-6);data[i * 4 + 3] = f.s;@@ -543,12 +540,12 @@ function foldProfile(folds, rand) {}const mid = cum[N] / 2;return (x) => {- const t = clamp01(x) * N;+ const t = unit(x) * N;const i = Math.min(N - 1, Math.floor(t));const f = t - i;return {- v: raw(clamp01(x)) / peak,- d: slope(clamp01(x)),+ v: raw(unit(x)) / peak,+ d: slope(unit(x)),s: cum[i] + (cum[i + 1] - cum[i]) * f - mid,};};@@ -771,7 +768,7 @@ function gustTexture(seed, size = 128) {}const data = new Uint8Array(size * size * 4);for (let i = 0; i < raw.length; i++) {- const v = Math.round(255 * clamp01(0.5 + 0.5 * raw[i] / peak));+ const v = Math.round(255 * unit(0.5 + 0.5 * raw[i] / peak));data[i * 4] = data[i * 4 + 1] = data[i * 4 + 2] = v;data[i * 4 + 3] = 255;}@@ -919,14 +916,7 @@ const STALK_HEAD = ['attribute vec3 iVar;','varying vec4 vWheat;','varying float vWheatTone;',- // A world direction as the LOCAL offset that moves this surface- // one metre along it, valid while the basis stays orthogonal.- 'vec3 clothLocalDir(vec3 w) {',- ' mat3 m = mat3(modelMatrix);',- ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',- ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',- ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',- '}',+ glslLocalDir('clothLocalDir'),].join('\n');const STALK_VERTEX = [diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.jsindex 4df09f36..6bdf135d 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/damp.js@@ -29,40 +29,22 @@*/import * as THREE from 'three';-import { patchStandard, composeRoughness } from './shader.js';--// Named as terrain_shade, waterside, surface_wear, aging and-// accumulation name them, so a material wearing several libraries-// declares ONE pair; the vertex locals are dm* because those five own-// astraWp, wsP, wrP, agP and acP.-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',-].join('\n');+import {+ patchStandard, composeRoughness, baseRoughness, frac, glslAxes, glslCurv,+ glslTriNoise, seedVec3, toColor, towardRoughness, unit, upVector,+ worldBase,+} from './shader.js';// All three patches read these, so they are declared once, in the base.// astraDamp*, not a neighbour's spelling: patchStandard THROWS when two// chained patches give one function name two different bodies.const DAMP_HEAD = [- 'vec3 astraDampAxes(vec3 n) {',- ' vec3 w = abs(n * n * n);',- ' return w / max(w.x + w.y + w.z, 1e-4);',- '}',+ glslAxes('astraDampAxes'),// Three world-plane projections blended by the normal: growth has to// break up the same way on a boulder, a wall and a bridge soffit.- 'float astraDampNoise(vec3 p, vec3 w) {',- ' return astraNoise2(p.yz + 29.3) * w.x',- ' + astraNoise2(p.zx + 63.1) * w.y',- ' + astraNoise2(p.xy + 97.7) * w.z;',- '}',- // Curvature in 1/m: how far the normal turns per metre of surface- // under one pixel. NEGATIVE is the concave crevice that holds water.- // Zero across a hard, unwelded edge.- 'float astraDampCurv(vec3 n, vec3 p) {',- ' vec3 dx = dFdx(p), dy = dFdy(p);',- ' float d = dot(dx, dx) + dot(dy, dy);',- ' return (dot(dFdx(n), dx) + dot(dFdy(n), dy)) / max(d, 1e-12);',- '}',+ glslTriNoise('astraDampNoise', 29.3, 63.1, 97.7),+ // NEGATIVE curvature is the concave crevice that holds water.+ glslCurv('astraDampCurv'),'vec2 astraDampSite(vec2 c) {',' return c + vec2(astraHash21(c), astraHash21(c + 37.7));','}',@@ -97,74 +79,16 @@ const DAMP_HEAD = ['}',].join('\n');-// One base for all three. `transformed` is still object-space after-// <begin_vertex>, so the instance transform is folded in by hand or-// every scattered copy takes its weather from the world origin.-const BASE = {- name: 'damp:base',- vertexHead: WORLD_VARYINGS,- vertexBody: [- ' vec4 dmP = vec4(transformed, 1.0);',- ' vec3 dmN = normal;',- '#ifdef USE_INSTANCING',- ' dmP = instanceMatrix * dmP;',- ' dmN = mat3(instanceMatrix) * dmN;',- '#endif',- ' vAstraWorld = (modelMatrix * dmP).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(dmN, 0.0)).xyz);',- ].join('\n'),- fragmentHead: [WORLD_VARYINGS, DAMP_HEAD].join('\n'),-};--/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}--/** Clamp to 0..1 without importing MathUtils for one call. */-function unit(value) {- return Math.max(0, Math.min(1, value));-}--/** fract(), which JS's % gets wrong for a negative seed. */-function frac(x) {- return x - Math.floor(x);-}--/** astraHash11 from GLSL_UTIL, so CPU and shader agree on a seed. */-function hash11(x) {- let p = frac(x * 0.1031);- p *= p + 33.33;- return frac(p * (p + p));-}--/**- * Turn a seed into a noise-space offset, so two materials differ.- *- * The offset is a UNIFORM: a seed baked into the GLSL would be fixed- * for every material sharing the cache key. The constants differ from- * surface_wear's, aging's and accumulation's, or one seed would grow- * this library's moss along that library's blotches.- */-function seedOffset(seed, salt) {- return new THREE.Vector3(- hash11(seed + salt + 2.71), hash11(seed + salt + 6.83),- hash11(seed + salt + 11.29)).multiplyScalar(40);-}+// One base for all three, on the world varyings every library shares;+// the vertex locals are dm* because terrain_shade, waterside,+// surface_wear, aging and accumulation own astraWp, wsP, wrP, agP and acP.+const BASE = worldBase('damp:base', 'dmP', 'dmN', DAMP_HEAD);-/**- * Read an `up`-style option as a unit vector, never as NaN.- *- * A degenerate vector would divide by zero in the shader and paint the- * object black, so a zero-length one falls back to world up.- */-function upVector(value) {- const v = new THREE.Vector3(0, 1, 0);- if (value) v.fromArray(value.toArray ? value.toArray() : value);- if (!(v.lengthSq() > 1e-9)) v.set(0, 1, 0);- return v.normalize();-}+// The constants differ from surface_wear's, aging's and accumulation's,+// or one seed would grow this library's moss along that library's+// blotches.+const seedOffset = (seed, salt) =>+ seedVec3(seed + salt, 2.71, 6.83, 11.29, 40);/*** Read `north` as the HORIZONTAL direction that stays shaded.@@ -187,25 +111,6 @@ function northVector(value, up) {return v.normalize();}-/**- * Move the material's gloss toward the cover's, never past it.- *- * Roughness is per MATERIAL here, so a cover can only say how much of- * the surface is no longer the material: `blend` 0 leaves it alone, 1- * hands the whole material to the cover's own roughness.- */-function towardRoughness(material, target, blend) {- const base = baseRoughness(material);- if (!(base > 0)) return 1;- return 1 + (target / base - 1) * unit(blend);-}--/** The roughness the material was AUTHORED with, before any cover. */-function baseRoughness(material) {- const store = material.userData.astraRoughness;- return store ? store.base : material.roughness;-}-/*** A wet target that is glossier than the surface it lands on — never a* mirror, and never rougher than what it landed on.@@ -359,7 +264,6 @@ export function patchMoss(material, opts = {}) {uMossNorth: { value: northVector(opts.north, up) },uMossSeed: { value: seedOffset(seed, 0.4) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uMossAmt;','uniform vec3 uMossColor;',@@ -523,7 +427,6 @@ export function patchMoisture(material, opts = {}) {uMoistAmt: { value: strength },uMoistSeed: { value: seedOffset(seed, 2.9) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uMoistY;','uniform float uMoistReach;',@@ -655,7 +558,6 @@ export function patchCrackedMud(material, opts = {}) {uMudWet: { value: wet },uMudSeed: { value: seedOffset(seed, 5.1) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uMudScale;','uniform float uMudDepth;',diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/finish.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/finish.jsindex 15251699..ca1f93fa 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/finish.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/finish.js@@ -16,71 +16,16 @@* front lighting, so neither can be albedo.*/-import * as THREE from 'three';-import { patchStandard, composeRoughness } from './shader.js';+import {+ patchStandard, composeRoughness, seedVec3, toColor, unit, worldBase,+} from './shader.js';-// Named as terrain_shade, waterside, surface_wear and aging name them,-// so a material wearing several libraries declares ONE pair; the vertex-// locals are fn* because those four own astraWp, wsP, wrP and agP.-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',-].join('\n');--// `transformed` is still object-space after <begin_vertex>, so the-// instance transform is folded in by hand or every scattered copy is-// shaded as though it stood at the world origin.-const BASE = {- name: 'finish:base',- vertexHead: WORLD_VARYINGS,- vertexBody: [- ' vec4 fnP = vec4(transformed, 1.0);',- ' vec3 fnN = normal;',- '#ifdef USE_INSTANCING',- ' fnP = instanceMatrix * fnP;',- ' fnN = mat3(instanceMatrix) * fnN;',- '#endif',- ' vAstraWorld = (modelMatrix * fnP).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(fnN, 0.0)).xyz);',- ].join('\n'),- fragmentHead: WORLD_VARYINGS,-};--/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}--/** Clamp to 0..1 without importing MathUtils for one call. */-function unit(value) {- return Math.max(0, Math.min(1, value));-}--/** fract(), which JS's % gets wrong for a negative seed. */-function frac(x) {- return x - Math.floor(x);-}--/** astraHash11 from GLSL_UTIL, so CPU and shader agree on a seed. */-function hash11(x) {- let p = frac(x * 0.1031);- p *= p + 33.33;- return frac(p * (p + p));-}+// On the world varyings every library shares; the vertex locals are fn*+// because terrain_shade, waterside, surface_wear and aging own astraWp,+// wsP, wrP and agP.+const BASE = worldBase('finish:base', 'fnP', 'fnN');-/**- * Turn a seed into a noise-space offset, so two materials differ.- *- * The offset is a UNIFORM: a seed baked into the GLSL would be fixed for- * every other material that shares this patch's cache key, because the- * first one to compile a key decides the source for all of them.- */-function seedOffset(seed) {- return new THREE.Vector3(- hash11(seed + 0.29), hash11(seed + 5.11), hash11(seed + 9.67))- .multiplyScalar(48);-}+const seedOffset = (seed) => seedVec3(seed, 0.29, 5.11, 9.67, 48);const TRANS_HEAD = ['uniform float uTrsThick;',@@ -252,8 +197,7 @@ export function patchTranslucency(material, opts = {}) {uTrsPow: { value: Math.max(0.1, power) },uTrsSeed: { value: seedOffset(seed) },},- vertexHead: WORLD_VARYINGS,- fragmentHead: [WORLD_VARYINGS, TRANS_HEAD].join('\n'),+ fragmentHead: TRANS_HEAD,fragmentBody: TRANS_BODY,});}@@ -448,8 +392,7 @@ export function patchIridescence(material, opts = {}) {uIriIor: { value: Math.max(1.01, ior) },uIriSeed: { value: seedOffset(seed + 0.5) },},- vertexHead: WORLD_VARYINGS,- fragmentHead: [WORLD_VARYINGS, IRID_HEAD].join('\n'),+ fragmentHead: IRID_HEAD,fragmentBody: IRID_BODY,});}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flock.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flock.jsindex 10cc6360..55a070be 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flock.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flock.js@@ -32,18 +32,13 @@import * as THREE from 'three';import { mulberry32 } from './noise.js';-import { instancedQuad, makeShaderMaterial, tickShaders, keepOutOfDepthPasses } from './shader.js';+import {+ instancedQuad, makeShaderMaterial, readVec3, tickShaders, keepOutOfDepthPasses,+} from './shader.js';const _TAU = Math.PI * 2;const _MAX_PTS = 8; // the size of the shader's uPath array-/** Read a Vector3, an array or an {x,y,z} into a Vector3. */-function _toVec(p, fx = 0, fy = 0, fz = 0) {- if (!p) return new THREE.Vector3(fx, fy, fz);- if (Array.isArray(p)) return new THREE.Vector3(p[0], p[1], p[2]);- return new THREE.Vector3(p.x, p.y, p.z);-}-/** Default route: a shallow ellipse over the scene, gently undulating. */function _defaultPath(extent, height) {const pts = [];@@ -96,7 +91,7 @@ export function makeFlock(opts = {}) {// A rook's back is nearer 4%, and that is what reads as a bird.const color = new THREE.Color(opts.color === undefined ? (kind ? 0x9fb4c2 : 0x36393f) : opts.color);- const sun = _toVec(opts.sunDir, 0.45, 0.78, 0.35).normalize();+ const sun = readVec3(opts.sunDir, 0.45, 0.78, 0.35).normalize();// Defaults are a daylight rig's own two colours; a caller with a// rig should hand over its sun and its sky and stop guessing.const sunCol = new THREE.Color(@@ -105,7 +100,7 @@ export function makeFlock(opts = {}) {opts.skyColor === undefined ? 0x93b4dd : opts.skyColor);const pts = (opts.path && opts.path.length >= 3- ? opts.path.map((p) => _toVec(p))+ ? opts.path.map((p) => readVec3(p)): _defaultPath(extent, height)).slice(0, _MAX_PTS);// Uniform Catmull-Rom, closed: the same curve the shader evaluates,// so `speed` is honest metres per second rather than a loop rate.diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.jsindex 72a45ecc..d9955d29 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/flowers.js@@ -31,8 +31,8 @@ import { patchTranslucency } from './finish.js';import { patchLeafSSS } from './foliage_shade.js';import { mulberry32 } from './noise.js';import {- instancedQuad, keepOutOfDepthPasses, patchStandard, shadowLike,- tickShaders,+ glslLocalDir, glslWob, instancedQuad, keepOutOfDepthPasses, patchStandard,+ shadowLike, tickShaders, wobX, wobZ,} from './shader.js';const _TAU = Math.PI * 2;@@ -414,14 +414,7 @@ const PLANT_VERTEX_HEAD = ['attribute vec4 iVar;','varying vec4 vFlow;','varying vec3 vFlowVar;',- // A world direction as the LOCAL offset that moves this surface one- // metre along it, valid while the basis columns stay orthogonal.- 'vec3 flowLocalDir(vec3 w) {',- ' mat3 m = mat3(modelMatrix);',- ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',- ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',- ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',- '}',+ glslLocalDir('flowLocalDir'),// The gust field grass.js rides: streaks running downwind, so a// scene's meadow and its flowers are pushed by the same air.'float flowSway(vec3 root, float ph, float lag) {',@@ -655,25 +648,8 @@ const _FALL_KINDS = {},};-// Two octaves with a fixed envelope, so the slide is bounded by 1 and-// the stated volume is exactly the volume the field occupies. The GLSL-// below is these two functions, spelled the same.-function _wobX(f, p, t) {- return Math.sin(f * t + p) * 0.75 + Math.sin(f * 1.9 * t + p * 2.1) * 0.25;-}--function _wobZ(f, p, t) {- return Math.cos(f * t + p) * 0.75 + Math.cos(f * 2.3 * t + p * 1.6) * 0.25;-}--const _FALL_WOB_GLSL = [- 'float flowFallWobX(float f, float p, float t) {',- ' return sin(f * t + p) * 0.75 + sin(f * 1.9 * t + p * 2.1) * 0.25;',- '}',- 'float flowFallWobZ(float f, float p, float t) {',- ' return cos(f * t + p) * 0.75 + cos(f * 2.3 * t + p * 1.6) * 0.25;',- '}',-].join('\n');+// The slide: `wobX`/`wobZ` on the CPU mirror, the same pair in GLSL.+const _FALL_WOB_GLSL = glslWob('flowFallWob');/** Wrap v into [-lim, lim), the CPU mirror of GLSL mod(). */function _wrap(v, lim) {@@ -797,10 +773,10 @@ export function makeFalling(opts = {}) {const y = (pos[k * 3 + 1] - fall * fal[k * 4] * t) % drop;return new THREE.Vector3(_wrap(pos[k * 3] + drift.x * t, lim)- + wob * _wobX(swing[k * 4], swing[k * 4 + 1], t),+ + wob * wobX(swing[k * 4], swing[k * 4 + 1], t),(y < 0 ? y + drop : y) + span,_wrap(pos[k * 3 + 2] + drift.y * t, lim)- + wob * _wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t));+ + wob * wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t));};return g;}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.jsindex 36b2a6e7..79da9db0 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 { patchStandard } from './shader.js';+import { glslLocalDir, patchStandard } 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@@ -24,18 +24,7 @@ const SHARED_VERTEX_HEAD = [' return (modelMatrix * vec4(p, 1.0)).xyz;','#endif','}',- // A world direction as the LOCAL offset that moves this surface one- // metre along it. compose(pos, quat, scale) leaves the basis columns- // orthogonal, so that inverse is one projection per column.- 'vec3 astraFolLocalDir(vec3 w) {',- ' mat3 m = mat3(modelMatrix);',- '#ifdef USE_INSTANCING',- ' m = m * mat3(instanceMatrix);',- '#endif',- ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',- ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',- ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',- '}',+ glslLocalDir('astraFolLocalDir', true),].join('\n');// Goes on once however many patches a material carries: patchStandarddiff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.jsindex 54bf87af..ee9db7d1 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/godrays.js@@ -30,6 +30,7 @@import * as THREE from 'three';+import { lehmer } from './noise.js';import {instancedQuad, makeShaderMaterial, sweepProfile, tickShaders, keepOutOfDepthPasses } from './shader.js';@@ -135,7 +136,7 @@ export function makeGodRays(opts = {}) {const runLen = run.length();if (runLen > 1e-6) run.divideScalar(runLen); else run.set(0, 0, 1);- const rnd = prng(seed);+ const rnd = lehmer(seed);const shafts = [];const drop = height / -dir.y;// A shaft's LENGTH is the drop divided by the slant, so a low sun@@ -244,12 +245,6 @@ function slantDir(v) {return d;}-/** 16807 LCG: same seed, same field, on every machine. */-function prng(seed) {- let s = (seed >>> 0) || 1;- return () => ((s = (s * 16807) % 2147483647) / 2147483647);-}-/*** How far the field reaches from the group's own origin.*@@ -510,7 +505,7 @@ function poolMesh(shafts, dir, run, side, color, air, spark) {function moteMesh(shafts, dir, side, perp, width, color, air, spark, seed) {const n = Math.max(30, shafts.length * 44);const geom = instancedQuad(n, 1, 1, fieldRadius(shafts, dir) + width);- const rnd = prng((seed >>> 0) * 7 + 13);+ const rnd = lehmer((seed >>> 0) * 7 + 13);const org = new Float32Array(n * 3), off = new Float32Array(n * 3);const data = new Float32Array(n * 4);for (let i = 0; i < n; i++) {@@ -635,13 +630,7 @@ function moteMaterial(dir, side, perp, color, air, spark, width) {// a ball of cotton.' float a = (pow(1.0 - d, 3.4) + 0.14 * pow(1.0 - d, 1.3))',' * life * vTwinkle * exp(-vLife * 1.2) * 1.05 * uAmp;',- '#ifdef USE_FOG',- ' #ifdef FOG_EXP2',- ' a *= exp(-fogDensity * fogDensity * vFogDepth * vFogDepth);',- ' #else',- ' a *= 1.0 - smoothstep(fogNear, fogFar, vFogDepth);',- ' #endif',- '#endif',+ _FOG_FADE,' if (a < 0.003) discard;',' gl_FragColor = vec4(mix(uColor, uAir, vMist),',' clamp(a, 0.0, 1.0));',diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.jsindex 2a42b7e1..4acc5a46 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js@@ -27,23 +27,15 @@import * as THREE from 'three';import { fbm2, mulberry32 } from './noise.js';-import { patchStandard, shadowLike, tickShaders } from './shader.js';+import {+ glslLocalDir, patchStandard, shadowLike, tickShaders, unit,+} from './shader.js';// Blade shape: enough rows to curve, one column because the width is// swept in the shader. 4 rows is where a bent blade stops faceting.const BLADE_ROWS = 4;-// A world direction as the LOCAL offset that moves this surface one-// metre along it — the same projection foliage_shade.js uses, valid-// because compose() leaves the basis columns orthogonal.-const LOCAL_DIR = [- 'vec3 grassLocalDir(vec3 w) {',- ' mat3 m = mat3(modelMatrix);',- ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',- ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',- ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',- '}',-].join('\n');+const LOCAL_DIR = glslLocalDir('grassLocalDir');/*** Cover a patch of ground in grass.@@ -80,7 +72,7 @@ export function makeGrass(opts = {}) {const density = opts.density === undefined ? 180 : opts.density;const height = opts.height === undefined ? 0.42 : opts.height;const seed = opts.seed === undefined ? 11 : opts.seed;- const patchy = clamp01(opts.patchy === undefined ? 0.5 : opts.patchy);+ const patchy = unit(opts.patchy === undefined ? 0.5 : opts.patchy);const maxBlades = opts.maxBlades === undefined ? 60000 : opts.maxBlades;// Albedos, not screen colours: a scene sun runs at 5-6, so a hex// that already looks like sunlit grass tone-maps to pale felt.@@ -109,11 +101,6 @@ export function makeGrass(opts = {}) {return g;}-/** Clamp to 0..1 without importing MathUtils for two calls. */-function clamp01(v) {- return Math.max(0, Math.min(1, v));-}-/*** Read the `wind` option in either of its two spellings.*@@ -165,7 +152,7 @@ function clumpField(seed, extent) {return (x, z) => {// Contrast, or every patch lands mid-field and the whole extent is// one wash: a tussock is either there or it is not.- const v = clamp01(0.5 + (raw(x, z) - mean) / (2.6 * sd));+ const v = unit(0.5 + (raw(x, z) - mean) / (2.6 * sd));return 0.45 * v + 0.55 * v * v * (3 - 2 * v);};}@@ -211,7 +198,7 @@ function plantField(extent, density, maxBlades, height, patchy, seed,// Measured, +-6 deg read as a single albedo at any distance// (local hue spread 8 deg against 25-45 in a photograph).vary.push((rand() - 0.5) * 1.3, rand(),- clamp01(0.75 * (1 - c) + (rand() - 0.5) * 0.18),+ unit(0.75 * (1 - c) + (rand() - 0.5) * 0.18),(rand() - 0.5) * 0.85);maxH = Math.max(maxH, h);n++;diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.jsindex 0c9ca266..c08ef1a2 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js@@ -23,7 +23,7 @@ import * as THREE from 'three';import {keepOutOfDepthPasses, makeShaderMaterial, patchStandard, sweepProfile,- tickShaders } from './shader.js';+ tickShaders, toColor } from './shader.js';const _UP = new THREE.Vector3(0, 1, 0);@@ -77,12 +77,6 @@ function seedKey(seed) {return ((s * 16807) % 9973) * 0.011;}-/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}-/** A point in any accepted spelling as its own Vector3. */function toVec(p) {if (p && p.isVector3) return p.clone();diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.jsindex 0d7832f8..e860e3d6 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.js@@ -1,7 +1,8 @@/*** Seeded noise substrate: fBm fields, procedural DataTextures, and* terrain displacement. ImprovedNoise is UNSEEDED and the platform's- * global RNG is banned, so `mulberry32` is the one sanctioned PRNG and+ * global RNG is banned, so `mulberry32` is the sanctioned PRNG (`lehmer`+ * only keeps the older effects tuned on it where they were) and* fbm2/fbm3 seed the lattice via per-octave domain offsets. Other lib* modules build on this — keep the exported signatures stable.* (The ban is stated without naming the call: the scene_threejs lint@@ -30,6 +31,20 @@ export function mulberry32(seed) {};}+/**+ * The 16807 (Park-Miller) stream the older effects were tuned on —+ * celestial, godrays, veils, watermist, submerged and+ * `instanceVariation`. Kept because moving them to `mulberry32` would+ * move every star, shaft and drop they place; new code takes that.+ *+ * @param {number} seed Any integer; 0 is taken as 1.+ * @returns {() => number} A function returning uniform values in (0, 1).+ */+export function lehmer(seed) {+ let s = (seed >>> 0) || 1;+ return () => ((s = (s * 16807) % 2147483647) / 2147483647);+}+// Seed-derived per-octave domain offsets; they also de-align octave// zeros so grid artifacts can't stack. Cached: fbm runs per vertex.const _offsetCache = new Map();diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/place.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/place.jsindex 8769ded2..2495b519 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/place.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/place.js@@ -381,23 +381,6 @@ export function alignAlong(obj, dir, forward) {return obj;}-/**- * Face an object the same way as the thing it sits on or in — a- * person must look the way the chair looks, not AT the chair (the- * classic 180-degree seating error).- *- * @param {THREE.Object3D} obj The figure being seated.- * @param {THREE.Object3D} seatObj The chair/bench/stool.- * @param {string} [forward] The figure's forward from assets_api.json.- * @param {string} [seatForward] The seat's forward from assets_api.json.- * @returns {THREE.Object3D} obj- */-export function matchFacing(obj, seatObj, forward, seatForward) {- const f = fwdVec(seatForward).applyEuler(- new THREE.Euler(0, seatObj.rotation.y, 0));- return alignAlong(obj, f, forward);-}-/*** Sample a route as a closed or open path and walk objects along it.*diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/roadway.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/roadway.jsindex 1ffd6556..8b425394 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/roadway.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/roadway.js@@ -37,32 +37,24 @@*/import * as THREE from 'three';-import { patchStandard, composeRoughness } from './shader.js';+import {+ patchStandard, composeRoughness, glslAxes, glslTriNoise, matteFactor,+ seedVec3, toColor, unit, WORLD_VARYINGS,+} from './shader.js';-// Named as terrain_shade, surface_wear, aging, accumulation and strata-// name them, so a material wearing several libraries carries ONE world-// position; vAstraRoad is this library's own and no neighbour's.-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',- 'varying vec4 vAstraRoad;',-].join('\n');+// The world varyings terrain_shade, surface_wear, aging, accumulation and+// strata share, so a material wearing several libraries carries ONE+// world position; vAstraRoad is this library's own and no neighbour's.+const ROAD_VARYINGS = [WORLD_VARYINGS, 'varying vec4 vAstraRoad;'].join('\n');// All three patches read these, so they are declared once, in the// frame. astraRoad*, not a neighbour's spelling: patchStandard THROWS// when two chained patches give one function name two different bodies.const ROAD_HEAD = [- 'vec3 astraRoadAxes(vec3 n) {',- ' vec3 w = abs(n * n * n);',- ' return w / max(w.x + w.y + w.z, 1e-4);',- '}',+ glslAxes('astraRoadAxes'),// Three world-plane projections blended by the normal: the top of a// kerb and its face have to carry the same grit.- 'float astraRoadNoise(vec3 p, vec3 w) {',- ' return astraNoise2(p.yz + 31.7) * w.x',- ' + astraNoise2(p.zx + 67.3) * w.y',- ' + astraNoise2(p.xy + 13.9) * w.z;',- '}',+ glslTriNoise('astraRoadNoise', 31.7, 67.3, 13.9),// A fine field is TEXTURE up close and STATIC once a pixel spans a// cycle of it, so every grain here is faded out by the world size of// its own pixel. `cycle` is metres per repeat.@@ -109,54 +101,11 @@ const FRAME_HEAD = ['uniform float uRoadHalf;',].join('\n');-/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}--/** Clamp to 0..1 without importing MathUtils for one call. */-function unit(value) {- return Math.max(0, Math.min(1, value));-}--/** fract(), which JS's % gets wrong for a negative seed. */-function frac(x) {- return x - Math.floor(x);-}--/** astraHash11 from GLSL_UTIL, so CPU and shader agree on a seed. */-function hash11(x) {- let p = frac(x * 0.1031);- p *= p + 33.33;- return frac(p * (p + p));-}--/**- * Turn a seed into a noise-space offset, so two materials differ.- *- * The offset is a UNIFORM: a seed baked into the GLSL would be fixed- * for every material sharing the cache key. The constants differ from- * surface_wear's, aging's and accumulation's, or one seed would lay- * this library's grit along that library's blotches.- */-function seedOffset(seed, salt) {- return new THREE.Vector3(- hash11(seed + salt + 2.11), hash11(seed + salt + 6.37),- hash11(seed + salt + 11.83)).multiplyScalar(40);-}--/**- * A roughening factor one patch cannot push past fully rough.- *- * Grit and weeds are matte, roughness only means anything up to 1, and- * the material may start near it.- */-function matteFactor(material, add) {- const store = material.userData.astraRoughness;- const base = store ? store.base : material.roughness;- return base > 0 ? Math.min(1 + add, 1 / base) : 1;-}+// The constants differ from surface_wear's, aging's and accumulation's,+// or one seed would lay this library's grit along that library's+// blotches.+const seedOffset = (seed, salt) =>+ seedVec3(seed + salt, 2.11, 6.37, 11.83, 40);/** Read a direction option, never as a zero vector the GPU divides by. */function dirVector(value, fallback) {@@ -204,8 +153,8 @@ function withFrame(material, opts) {uRoadCenter: { value: center.clone() },uRoadHalf: { value: half },},- vertexHead: [WORLD_VARYINGS, FRAME_HEAD].join('\n'),- fragmentHead: [WORLD_VARYINGS, FRAME_HEAD, ROAD_HEAD].join('\n'),+ vertexHead: [ROAD_VARYINGS, FRAME_HEAD].join('\n'),+ fragmentHead: [ROAD_VARYINGS, FRAME_HEAD, ROAD_HEAD].join('\n'),vertexBody: FRAME_BODY,});}@@ -290,7 +239,6 @@ export function patchRoadSurface(material, opts = {}) {uRoadLane: { value: lane },uRoadSeed: { value: seedOffset(seed, 0.9) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uRoadAgg;','uniform float uRoadWear;',@@ -479,7 +427,6 @@ export function patchSeamBand(material, opts = {}) {uSeamWeed: { value: new THREE.Color(0x53602f) },uSeamSeed: { value: seedOffset(seed, 5.3) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uSeamWidth;','uniform vec3 uSeamColor;',@@ -607,7 +554,6 @@ export function patchTracks(material, opts = {}) {uTrkOffset: { value: opts.offset === undefined ? 0 : opts.offset },uTrkSeed: { value: seedOffset(seed, 8.7) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uTrkCount;','uniform float uTrkDepth;',diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.jsindex d2d65041..5c90e9ec 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js@@ -37,6 +37,7 @@*/import * as THREE from 'three';+import { lehmer } from './noise.js';/*** Shared GLSL helpers. Include with `${GLSL_UTIL}` in a head string.@@ -138,6 +139,157 @@ export const GLSL_UTIL = ['}',].join('\n');+// ---------------------------------------------------------------------+// Library-internal helpers the effect modules share. None of them is in+// the catalog: they exist so one body is written once, not fifteen times.++/** Take a THREE.Color, a hex or nothing, never sharing the instance. */+export function toColor(value, fallback) {+ return new THREE.Color(+ value === undefined || value === null ? fallback : value);+}++/** Clamp to 0..1. */+export function unit(value) {+ return Math.max(0, Math.min(1, value));+}++/** fract(), which JS's % gets wrong for a negative seed. */+export function frac(x) {+ return x - Math.floor(x);+}++/** astraHash11 from GLSL_UTIL, so CPU and shader agree on a seed. */+export function hash11(x) {+ let p = frac(x * 0.1031);+ p *= p + 33.33;+ return frac(p * (p + p));+}++/**+ * Turn a seed into a noise-space offset, so two materials differ.+ *+ * The offset is a UNIFORM: a seed baked into the GLSL would be fixed for+ * every material sharing the cache key, because the first one to compile+ * a key decides the source for all of them. `s` is the seed (plus the+ * patch's own salt); `a`, `b`, `c` and the scale `k` are per LIBRARY, or+ * one seed would lay one library's field along another's blotches.+ */+export function seedVec3(s, a, b, c, k) {+ return new THREE.Vector3(hash11(s + a), hash11(s + b), hash11(s + c))+ .multiplyScalar(k);+}++/** 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);+ if (Array.isArray(p)) return new THREE.Vector3(p[0], p[1], p[2]);+ return new THREE.Vector3(p.x, p.y, p.z);+}++/**+ * Read an `up`-style option as a unit vector, never as NaN.+ *+ * A degenerate vector would divide by zero in the shader and paint the+ * object black, so a zero-length one falls back to world up.+ */+export function upVector(value) {+ const v = new THREE.Vector3(0, 1, 0);+ if (value) v.fromArray(value.toArray ? value.toArray() : value);+ if (!(v.lengthSq() > 1e-9)) v.set(0, 1, 0);+ return v.normalize();+}++// GLSL several libraries each carry under their OWN name. A chained+// material wears several libraries at once and patchStandard throws when+// two patches give one function name two different bodies, so every+// library keeps its prefix (astraAcc..., astraWear...) and these write+// the body once. Each returns its lines joined by '\n'.++/** `vec3 name(vec3 n)`: triplanar weights, the cubed normal normalised. */+export function glslAxes(name) {+ return [+ `vec3 ${name}(vec3 n) {`,+ ' vec3 w = abs(n * n * n);',+ ' return w / max(w.x + w.y + w.z, 1e-4);',+ '}',+ ].join('\n');+}++/**+ * `float name(vec3 p, vec3 w)`: astraNoise2 on the three world planes,+ * blended by the weights `w`; `a`, `b`, `c` offset the planes apart.+ */+export function glslTriNoise(name, a, b, c) {+ return [+ `float ${name}(vec3 p, vec3 w) {`,+ ` return astraNoise2(p.yz + ${a}) * w.x`,+ ` + astraNoise2(p.zx + ${b}) * w.y`,+ ` + astraNoise2(p.xy + ${c}) * w.z;`,+ '}',+ ].join('\n');+}++/**+ * `float name(vec3 n, vec3 p)`: curvature in 1/m — how far the normal+ * turns per metre of surface under one pixel. Positive is convex,+ * negative the concave lee; ZERO across a hard, unwelded edge.+ * Fragment stage only (screen derivatives).+ */+export function glslCurv(name) {+ return [+ `float ${name}(vec3 n, vec3 p) {`,+ ' vec3 dx = dFdx(p), dy = dFdy(p);',+ ' float d = dot(dx, dx) + dot(dy, dy);',+ ' return (dot(dFdx(n), dx) + dot(dFdy(n), dy)) / max(d, 1e-12);',+ '}',+ ].join('\n');+}++/**+ * `vec3 name(vec3 w)`: a world direction as the LOCAL offset that moves+ * this surface one metre along it — one projection per basis column,+ * valid because compose() leaves the columns orthogonal. `instanced`+ * folds in instanceMatrix, which three applies after the vertex hook.+ */+export function glslLocalDir(name, instanced = false) {+ return [+ `vec3 ${name}(vec3 w) {`,+ ' mat3 m = mat3(modelMatrix);',+ ...(instanced ? ['#ifdef USE_INSTANCING',+ ' m = m * mat3(instanceMatrix);', '#endif'] : []),+ ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',+ ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',+ ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',+ '}',+ ].join('\n');+}++/**+ * Two octaves of sway with a fixed envelope, so the slide is bounded by+ * 1 and a field's stated volume is exactly the volume it occupies.+ * `wobX`/`wobZ` on the CPU; `glslWob(prefix)` is the same pair in GLSL,+ * spelled the same, named `<prefix>X` / `<prefix>Z`.+ */+export function wobX(f, p, t) {+ return Math.sin(f * t + p) * 0.75 + Math.sin(f * 1.9 * t + p * 2.1) * 0.25;+}++export function wobZ(f, p, t) {+ return Math.cos(f * t + p) * 0.75 + Math.cos(f * 2.3 * t + p * 1.6) * 0.25;+}++export function glslWob(prefix) {+ return [+ `float ${prefix}X(float f, float p, float t) {`,+ ' return sin(f * t + p) * 0.75 + sin(f * 1.9 * t + p * 2.1) * 0.25;',+ '}',+ `float ${prefix}Z(float f, float p, float t) {`,+ ' return cos(f * t + p) * 0.75 + cos(f * 2.3 * t + p * 1.6) * 0.25;',+ '}',+ ].join('\n');+}+const FOG_PARS_V = '#include <fog_pars_vertex>';const FOG_V = '#include <fog_vertex>';const FOG_PARS_F = '#include <fog_pars_fragment>';@@ -603,6 +755,71 @@ export function patchStandard(material, opts = {}) {return material;}+/**+ * The world position and normal the surface patches shade from.+ *+ * Named once for every library that reads them, so a material wearing+ * several declares ONE pair (patchStandard drops a repeated varying);+ * each library writes them from its OWN vertex locals, because two+ * bodies declaring one local is a compile error.+ */+export const WORLD_VARYINGS = [+ 'varying vec3 vAstraWorld;',+ 'varying vec3 vAstraWorldN;',+].join('\n');++/**+ * The vertex body that writes WORLD_VARYINGS from locals `p` and `n`.+ *+ * `transformed` is still object-space after <begin_vertex>, so the+ * instance transform is folded in by hand, or every scattered copy is+ * shaded as though it stood at the world origin.+ */+export function worldBody(p, n) {+ return [+ ` vec4 ${p} = vec4(transformed, 1.0);`,+ ` vec3 ${n} = normal;`,+ '#ifdef USE_INSTANCING',+ ` ${p} = instanceMatrix * ${p};`,+ ` ${n} = mat3(instanceMatrix) * ${n};`,+ '#endif',+ ` vAstraWorld = (modelMatrix * ${p}).xyz;`,+ ` vAstraWorldN = normalize((modelMatrix * vec4(${n}, 0.0)).xyz);`,+ ].join('\n');+}++/**+ * A library's base patch: the world varyings and their vertex body, and+ * `head` — the helpers all of that library's patches read — in the+ * fragment stage. Apply it before each of them: patchStandard replaces a+ * patch of the SAME name in place, so the base costs one body however+ * many of the library's patches a material wears.+ */+export function worldBase(name, p, n, head) {+ return {+ name,+ vertexHead: WORLD_VARYINGS,+ vertexBody: worldBody(p, n),+ fragmentHead: head ? [WORLD_VARYINGS, head].join('\n')+ : WORLD_VARYINGS,+ };+}++/** Apply a library's `base`, then the patch itself. */+export function withBase(material, base, part) {+ // A raw ShaderMaterial (the addon Water, anything from+ // makeShaderMaterial) has neither hook, so the patch is a silent+ // no-op — the one failure mode nothing else here would report.+ if (material && material.isShaderMaterial) {+ console.warn(+ part.name + ': ' + (material.name || 'material') + ' is a raw ' ++ 'ShaderMaterial with no <color_fragment> hook, so this patch ' ++ 'does nothing. Patch a standard-material surface instead.');+ }+ patchStandard(material, base);+ return patchStandard(material, part);+}+/*** Compose a roughness multiplier from several patches, in one place.@@ -647,6 +864,36 @@ export function composeRoughness(material, key, factor, floor = 0.04) {return material.roughness;}+/** The roughness the material was AUTHORED with, before any cover. */+export function baseRoughness(material) {+ const store = material.userData.astraRoughness;+ return store ? store.base : material.roughness;+}++/**+ * A roughening factor one patch cannot push past fully rough.+ *+ * Roughness only means anything up to 1, and the material may start+ * near it.+ */+export function matteFactor(material, add) {+ const base = baseRoughness(material);+ return base > 0 ? Math.min(1 + add, 1 / base) : 1;+}++/**+ * Move the material's gloss toward a cover's, never past it.+ *+ * Roughness is per MATERIAL here, so a cover can only say how much of+ * the surface is no longer the material: `blend` 0 leaves it alone, 1+ * hands the whole material to the cover's own roughness.+ */+export function towardRoughness(material, target, blend) {+ const base = baseRoughness(material);+ if (!(base > 0)) return 1;+ return 1 + (target / base - 1) * unit(blend);+}+/*** Drive every astra shader under `root` from one call in `tick()`.@@ -729,8 +976,7 @@ export function instanceVariation(mesh, opts = {}) {const { seed = 1, hue = 0.34, scale = 0.12, apply = true } = opts;const count = mesh.count || 0;if (!count) return mesh;- let s = seed >>> 0 || 1;- const rand = () => ((s = (s * 16807) % 2147483647) / 2147483647);+ const rand = lehmer(seed);const data = new Float32Array(count * 3);for (let i = 0; i < count; i++) {data[i * 3] = (rand() * 2 - 1) * hue;diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.jsindex afd9709d..6c704aa0 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js@@ -55,7 +55,6 @@ export function lowSunAmount(sunY) {return 1 - THREE.MathUtils.smoothstep(sunY, 0.02, 0.35);}-const _up = new THREE.Vector3(0, 1, 0);const _tmp = new THREE.Vector3();/**diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.jsindex 69adeca5..526a8d3b 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.js@@ -25,7 +25,8 @@ import { mulberry32 } from './noise.js';// cannot drift apart on the same `wind` option.import { windOf } from './grass.js';import {- instancedQuad, makeShaderMaterial, patchStandard, shadowLike, tickShaders,+ glslLocalDir, instancedQuad, makeShaderMaterial, patchStandard, readVec3,+ shadowLike, tickShaders, unit,} from './shader.js';const _TAU = Math.PI * 2;@@ -61,18 +62,6 @@ const _KINDS = {},};-/** Read a Vector3, an array or an {x,y,z} into a Vector3. */-function _toVec(p, fx = 0, fy = 0, fz = 0) {- if (!p) return new THREE.Vector3(fx, fy, fz);- if (Array.isArray(p)) return new THREE.Vector3(p[0], p[1], p[2]);- return new THREE.Vector3(p.x, p.y, p.z);-}--/** Clamp to 0..1 without importing MathUtils for four calls. */-function clamp01(v) {- return Math.max(0, Math.min(1, v));-}-// A swarm is drawn UNLIT, so the scene's own lights have to reach it as a// number. Re-read every `_RELIGHT` ticks: a traverse is cheap, but not 60// times a second in a scene of thousands of objects.@@ -161,7 +150,7 @@ export function makeInsects(opts = {}) {const seed = opts.seed === undefined ? 11 : opts.seed;const color = new THREE.Color(opts.color === undefined ? kind.color : opts.color);- const center = _toVec(opts.center, 0, height * 0.5, 0);+ const center = readVec3(opts.center, 0, height * 0.5, 0);const half = new THREE.Vector3(extent, height * 0.5, extent);const amp = new THREE.Vector3(kind.wander * extent, kind.rise * height * 0.5, kind.wander * extent);@@ -514,8 +503,8 @@ function reedField(extent, density, height, waterY, ground, wind, seed,const bed = ground ? ground(x, z) : 0;const depth = waterY - bed;const h = height * (0.6 + 0.7 * rand());- const dry = clamp01(1 + depth / 0.3);- const deep = 1 - 0.6 * clamp01((depth - h * 0.7) / h);+ const dry = unit(1 + depth / 0.3);+ const deep = 1 - 0.6 * unit((depth - h * 0.7) / h);if (rand() > dry * deep) continue;// Radians of tip bend at a full gust: a taller stem is a longer// lever, and each one carries its own stiffness.@@ -523,7 +512,7 @@ function reedField(extent, density, height, waterY, ground, wind, seed,const head = rand() < 0.45 && depth < h * 0.85? 0.010 + 0.006 * rand() : 0;pos.push(x, bed, z);- shape.push(h, 0.004 + 0.003 * rand(), clamp01(depth / h), head);+ shape.push(h, 0.004 + 0.003 * rand(), unit(depth / h), head);bend.push(wind.amp * stiff, wind.amp * stiff * _SUB_DAMP,rand() * _TAU, 0.04 + 0.14 * rand());// phase, hue, tone, dryness — dead stems a MINORITY, since a@@ -648,14 +637,7 @@ const STEM_HEAD = ['varying vec4 vReed;','varying vec4 vReedVar;','varying vec2 vReedW;',- // A world direction as the LOCAL offset that moves this surface- // one metre along it, valid while the basis stays orthogonal.- 'vec3 reedLocalDir(vec3 w) {',- ' mat3 m = mat3(modelMatrix);',- ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',- ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',- ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',- '}',+ glslLocalDir('reedLocalDir'),].join('\n');const STEM_VERTEX = [diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/strata.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/strata.jsindex 93f243d6..c02e5e95 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/strata.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/strata.js@@ -20,14 +20,10 @@*/import * as THREE from 'three';-import { patchStandard, composeRoughness } from './shader.js';--// Named as terrain_shade, aging, surface_wear and waterside name them,-// so a material wearing several libraries carries ONE world position.-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',-].join('\n');+import {+ patchStandard, composeRoughness, glslCurv, hash11, seedVec3, toColor,+ unit, worldBase,+} from './shader.js';// Helpers both patches share, all astraStrata-prefixed: GLSL has one// global namespace, and a chained patch redefining a neighbour's@@ -67,14 +63,8 @@ const STRATA_HEAD = [' }',' return clamp((s / w - 0.5) * 2.2 + 0.5, 0.0, 1.0);','}',- // Total curvature in 1/m: how far the normal turns per metre of- // surface under one pixel. Positive convex, negative the concave that- // holds water, and ZERO across a hard unwelded edge.- 'float astraStrataCurv(vec3 n, vec3 p) {',- ' vec3 dx = dFdx(p), dy = dFdy(p);',- ' float d = dot(dx, dx) + dot(dy, dy);',- ' return (dot(dFdx(n), dx) + dot(dFdy(n), dy)) / max(d, 1e-12);',- '}',+ // Total curvature: negative is the concave that holds water.+ glslCurv('astraStrataCurv'),// The same, restricted to ONE surface direction. A lip is convex// along the flow and a rib is convex across it, and they do opposite// things to a run, so the two halves have to be separable.@@ -91,24 +81,10 @@ const STRATA_HEAD = ['}',].join('\n');-// `transformed` is still object-space after <begin_vertex>, so the-// instance transform is folded in by hand or every scattered boulder-// takes its bedding from the mesh origin.-const BASE = {- name: 'strata:base',- vertexHead: WORLD_VARYINGS,- vertexBody: [- ' vec4 stbP = vec4(transformed, 1.0);',- ' vec3 stbN = normal;',- '#ifdef USE_INSTANCING',- ' stbP = instanceMatrix * stbP;',- ' stbN = mat3(instanceMatrix) * stbN;',- '#endif',- ' vAstraWorld = (modelMatrix * stbP).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(stbN, 0.0)).xyz);',- ].join('\n'),- fragmentHead: [WORLD_VARYINGS, STRATA_HEAD].join('\n'),-};+// On the world varyings terrain_shade, aging, surface_wear and waterside+// share, so a material wearing several libraries carries ONE world+// position.+const BASE = worldBase('strata:base', 'stbP', 'stbN', STRATA_HEAD);// A pale sandstone, an iron-rich tan, a grey-green marl and a dark// red-brown mudstone: enough spread that a thin dark bed between two@@ -134,42 +110,10 @@ const BASE = {// reaches G/R = 1 in the render is one grain-multiply away from green.const BEDS = [0xcc9f78, 0x8e6541, 0x74583f, 0x5b3a23];-/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}--/** Clamp to 0..1 without importing MathUtils for one call. */-function unit(value) {- return Math.max(0, Math.min(1, value));-}--/** fract(), which JS's % gets wrong for a negative seed. */-function frac(x) {- return x - Math.floor(x);-}--/** astraHash11 from GLSL_UTIL, so CPU and shader agree on a seed. */-function hash11(x) {- let p = frac(x * 0.1031);- p *= p + 33.33;- return frac(p * (p + p));-}--/**- * Turn a seed into a noise-space offset, so two rocks differ.- *- * The offset is a UNIFORM: a seed baked into the GLSL would be fixed- * for every material sharing the cache key. The constants differ from- * aging's and surface_wear's, or one seed would lay these runs down the- * middle of that library's stains.- */-function seedOffset(seed, salt) {- return new THREE.Vector3(- hash11(seed + salt + 1.63), hash11(seed + salt + 6.41),- hash11(seed + salt + 11.09)).multiplyScalar(52);-}+// The constants differ from aging's and surface_wear's, or one seed+// would lay these runs down the middle of that library's stains.+const seedOffset = (seed, salt) =>+ seedVec3(seed + salt, 1.63, 6.41, 11.09, 52);/*** Resample any palette to the four tones the shader ramps through.@@ -271,7 +215,6 @@ export function patchRockStrata(material, opts = {}) {uStrataC2: { value: beds[2] },uStrataC3: { value: beds[3] },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform vec3 uStrataUp;','uniform float uStrataSpacing;',@@ -464,7 +407,6 @@ export function patchErosionStreaks(material, opts = {}) {uErosScale: { value: Math.max(1e-3, scale) },uErosSeed: { value: seedOffset(seed, 3.7) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uErosAmt;','uniform vec3 uErosColor;',diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.jsindex 20750aa9..2d0cd68b 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.js@@ -20,9 +20,10 @@*/import * as THREE from 'three';+import { lehmer } from './noise.js';import {- patchStandard, composeRoughness, makeShaderMaterial, instancedQuad,- keepOutOfDepthPasses,+ composeRoughness, makeShaderMaterial, instancedQuad, keepOutOfDepthPasses,+ toColor, unit, withBase, worldBase,} from './shader.js';// Water absorbs red an order of magnitude faster than blue, and that@@ -34,48 +35,10 @@ const EXT_RATIO = new THREE.Vector3(1.0, 0.26, 0.10);// water plane, and stays inside the 2 cm an asset's base is allowed.const LIFT = 0.012;-// Named as caustics and waterside name them, so a submerged bank-// wearing a waterline, a net and this declares ONE pair.-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',-].join('\n');--// One base for both patches. `transformed` is still object-space after-// <begin_vertex>, so the instance transform is folded in by hand or-// every scattered cobble takes its depth from the world origin.-const BASE = {- name: 'submerged:base',- vertexHead: WORLD_VARYINGS,- vertexBody: [- ' vec4 subWp = vec4(transformed, 1.0);',- ' vec3 subWn = normal;',- '#ifdef USE_INSTANCING',- ' subWp = instanceMatrix * subWp;',- ' subWn = mat3(instanceMatrix) * subWn;',- '#endif',- ' vAstraWorld = (modelMatrix * subWp).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(subWn, 0.0)).xyz);',- ].join('\n'),- fragmentHead: WORLD_VARYINGS,-};--/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}--/** Clamp to 0..1 without importing MathUtils for one call. */-function unit(value) {- return Math.max(0, Math.min(1, value));-}--/** Deterministic 0..1 stream: a shipped factory owns its own RNG. */-function rng(seed) {- let s = (seed >>> 0) || 1;- return () => ((s = (s * 16807) % 2147483647) / 2147483647);-}+// One base for both patches, on the world varyings caustics and+// waterside share, so a submerged bank wearing a waterline, a net and+// this declares ONE pair.+const BASE = worldBase('submerged:base', 'subWp', 'subWn');/*** A seed becomes a far-apart lattice offset, not a one-cell shift.@@ -102,26 +65,6 @@ function extinctionVec(value) {return EXT_RATIO.clone().multiplyScalar(k);}-/**- * Apply the shared world-space base, then the patch itself.- *- * `patchStandard` replaces a patch of the SAME name in place, so the- * base costs one vertex body however many of these a material wears.- */-function withBase(material, part) {- // A raw ShaderMaterial (the addon Water, anything from- // makeShaderMaterial) has neither hook, so the patch is a silent- // no-op — the one failure mode nothing else here would report.- if (material && material.isShaderMaterial) {- console.warn(- part.name + ': ' + (material.name || 'material') + ' is a raw ' +- 'ShaderMaterial with no <color_fragment> hook, so this patch ' +- 'does nothing. Patch a standard-material surface instead.');- }- patchStandard(material, BASE);- return patchStandard(material, part);-}-const UNDER_HEAD = ['uniform float uSubLevel;','uniform vec3 uSubExt;',@@ -271,7 +214,7 @@ export function patchUnderwater(material, opts = {}) {+ 'MeshBasicMaterial and a raw ShaderMaterial do not have. '+ 'Patch a lit material instead.');}- return withBase(material, {+ return withBase(material, BASE, {name: 'submerged:underwater',uniforms: {uSubLevel: { value: level },@@ -417,7 +360,7 @@ export function makeRainRings(opts = {}) {const count = Math.max(1, opts.count === undefined ? 320 : opts.count);const width = opts.width === undefined ? 0.055 : opts.width;const opacity = opts.opacity === undefined ? 0.42 : opts.opacity;- const rand = rng(opts.seed === undefined ? 7 : opts.seed);+ const rand = lehmer(opts.seed === undefined ? 7 : opts.seed);const off = new Float32Array(count * 3);const ext = new Float32Array(count * 3);@@ -656,7 +599,7 @@ export function patchThinIce(material, opts = {}) {// one thing here that cannot be a uniform.composeRoughness(material, 'submerged:thinIce',0.18 + 0.62 * unit(frost));- return withBase(material, {+ return withBase(material, BASE, {name: 'submerged:thinIce',uniforms: {uIceThick: { value: Math.max(thick, 1e-3) },diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/surface_wear.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/surface_wear.jsindex 3524b0ea..99f6fbac 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/surface_wear.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/surface_wear.js@@ -44,84 +44,25 @@* by 0.35 * strength for wear that covers a fraction of it. 0.12.*/-import * as THREE from 'three';-import { patchStandard, composeRoughness } from './shader.js';--// Named as terrain_shade and waterside name them, so a material wearing-// a splat, a waterline and wear declares ONE pair (patchStandard-// dedupes varyings); the locals are prefixed wr because those two-// vertex bodies already own astraWp and wsP.-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',-].join('\n');+import {+ patchStandard, composeRoughness, glslAxes, glslTriNoise, hash11, seedVec3,+ toColor, unit, worldBase,+} from './shader.js';// Both patches read the same two fields, so they are built once. A// planar UV would smear either of them into vertical streaks on a wall,// and these patches land on walls.const WEAR_HEAD = [- 'vec3 astraWearAxes(vec3 n) {',- ' vec3 w = abs(n * n * n);',- ' return w / max(w.x + w.y + w.z, 1e-4);',- '}',- 'float astraWearNoise(vec3 p, vec3 w) {',- ' return astraNoise2(p.yz + 13.7) * w.x',- ' + astraNoise2(p.zx + 41.3) * w.y',- ' + astraNoise2(p.xy + 71.9) * w.z;',- '}',+ glslAxes('astraWearAxes'),+ glslTriNoise('astraWearNoise', 13.7, 41.3, 71.9),].join('\n');-const BASE = {- name: 'wear:base',- vertexHead: WORLD_VARYINGS,- vertexBody: [- ' vec4 wrP = vec4(transformed, 1.0);',- ' vec3 wrN = normal;',- '#ifdef USE_INSTANCING',- ' wrP = instanceMatrix * wrP;',- ' wrN = mat3(instanceMatrix) * wrN;',- '#endif',- ' vAstraWorld = (modelMatrix * wrP).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(wrN, 0.0)).xyz);',- ].join('\n'),- fragmentHead: [WORLD_VARYINGS, WEAR_HEAD].join('\n'),-};--/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}--/** Clamp to 0..1 without importing MathUtils for one call. */-function unit(value) {- return Math.max(0, Math.min(1, value));-}--/** fract(), which JS's % gets wrong for a negative seed. */-function frac(x) {- return x - Math.floor(x);-}--/** astraHash11 from GLSL_UTIL, so CPU and shader agree on a seed. */-function hash11(x) {- let p = frac(x * 0.1031);- p *= p + 33.33;- return frac(p * (p + p));-}+// On the world varyings terrain_shade and waterside share, so a material+// wearing a splat, a waterline and wear declares ONE pair; the locals+// are prefixed wr because those two vertex bodies own astraWp and wsP.+const BASE = worldBase('wear:base', 'wrP', 'wrN', WEAR_HEAD);-/**- * Turn a seed into a noise-space offset, so two materials differ.- *- * An offset is a UNIFORM: the seed must not reach the GLSL, or the- * first material to compile the shared cache key would fix its own- * seed for every other material wearing the same patch.- */-function seedOffset(seed) {- return new THREE.Vector3(- hash11(seed + 0.17), hash11(seed + 3.71), hash11(seed + 7.13))- .multiplyScalar(64);-}+const seedOffset = (seed) => seedVec3(seed, 0.17, 3.71, 7.13, 64);/*** Break up the flat, even surface that reads as moulded plastic.@@ -179,7 +120,6 @@ export function patchMicroBreakup(material, opts = {}) {uMicroHue: { value: hue },uMicroSeed: { value: seedOffset(seed) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uMicroScale;','uniform float uMicroAmt;',@@ -291,7 +231,6 @@ export function patchEdgeWear(material, opts = {}) {uEdgeWidth: { value: Math.max(1e-3, width) },uEdgeSeed: { value: seedOffset(seed + 0.5) },},- vertexHead: WORLD_VARYINGS,fragmentHead: ['uniform float uEdgeAmt;','uniform vec3 uEdgeColor;',diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain_shade.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain_shade.jsindex 1a15c82a..a6b57ced 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain_shade.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/terrain_shade.js@@ -8,27 +8,11 @@* fog and depth chunks stay exactly as they were.*/-import * as THREE from 'three';-import { patchStandard } from './shader.js';+import { patchStandard, toColor, worldBase } from './shader.js';-// The whole interface between the stages. `transformed` is still-// object-space at <begin_vertex>, so the instance transform has to be-// folded in here or every scattered rock projects from the origin.-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',-].join('\n');--const WORLD_BODY = [- ' vec4 astraWp = vec4(transformed, 1.0);',- ' vec3 astraWn = normal;',- '#ifdef USE_INSTANCING',- ' astraWp = instanceMatrix * astraWp;',- ' astraWn = mat3(instanceMatrix) * astraWn;',- '#endif',- ' vAstraWorld = (modelMatrix * astraWp).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(astraWn, 0.0)).xyz);',-].join('\n');+// The whole interface between the stages: the world varyings every+// library shares, written once by this base.+const WORLD = worldBase('terrain:world', 'astraWp', 'astraWn');// astraFbm2 sums 0.5, 0.25, ... so its top end moves with the octave// count; rescaled to 0..1, one mix factor means the same at any count.@@ -206,12 +190,6 @@ const SPLAT_BODY_OVER_TRI = [SPLAT_CORE, SPLAT_TAIL_OVER_TRI].join('\n');// +/-5 m snow band survives float32 (at 1e9 it would collapse to NaN).const SNOW_OFF = 1e6;-/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}-/** Clamp to the 1..6 astraFbm2 actually loops over. */function toOctaves(value) {return Math.max(1, Math.min(6, Math.round(value)));@@ -226,13 +204,7 @@ function toOctaves(value) {* landed on the same bank material.*/function withWorld(material) {- return patchStandard(material, {- name: 'terrain:world',- vertexHead: WORLD_VARYINGS,- fragmentHead: WORLD_VARYINGS,- vertexBody: WORLD_BODY,- util: true,- });+ return patchStandard(material, WORLD);}@@ -278,7 +250,6 @@ export function patchTriplanar(material, opts = {}) {uTriSharp: { value: Math.max(1, sharpness) },uTriOct: { value: toOctaves(oct) },},- vertexHead: WORLD_VARYINGS,fragmentHead: [FBM_UNIT, GRAIN, TRI_HEAD].join('\n'),fragmentBody: TRI_BODY,});@@ -357,7 +328,6 @@ export function patchSlopeSplat(material, opts = {}) {? Math.max(1e-2, band) : Math.max(1, band),},},- vertexHead: WORLD_VARYINGS,fragmentHead: [FBM_UNIT, GRAIN, SPLAT_HEAD].join('\n'),fragmentBody: overTri ? SPLAT_BODY_OVER_TRI : SPLAT_BODY,});diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.jsindex c406d2a9..2729cb26 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js@@ -22,23 +22,12 @@ import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';import { patchNeonSpill } from './neon.js';import { fbm2, mulberry32, noiseDataTexture } from './noise.js';import {- composeRoughness, keepOutOfDepthPasses, makeShaderMaterial, patchStandard,- tickShaders,+ baseRoughness, composeRoughness, keepOutOfDepthPasses, makeShaderMaterial,+ patchStandard, tickShaders, toColor, unit,} from './shader.js';const _UP = new THREE.Vector3(0, 1, 0);-/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}--/** Clamp to 0..1 without importing MathUtils for one call. */-function unit(value) {- return Math.max(0, Math.min(1, value));-}-/** A point in any accepted spelling as its own Vector3. */function toVec(p) {if (p && p.isVector3) return p.clone();@@ -274,8 +263,7 @@ export function patchCurtainWall(material, opts = {}) {const reflect = opts.reflect === undefined ? 0.22 : unit(opts.reflect);// Glass is the smoothest thing on a street; roughness is a MATERIAL// property here (no patch can reach the per-pixel one).- const base = material.userData.astraRoughness- ? material.userData.astraRoughness.base : material.roughness;+ const base = baseRoughness(material);composeRoughness(material, 'urban:curtain',base > 0 ? Math.max(0.05, 0.10 / base) : 1);return patchStandard(material, {diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.jsindex 89d27128..66aba1fc 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js@@ -49,19 +49,15 @@import * as THREE from 'three';-import { instancedQuad, keepOutOfDepthPasses, makeShaderMaterial, tickShaders }- from './shader.js';+import { lehmer } from './noise.js';+import {+ glslWob, instancedQuad, keepOutOfDepthPasses, makeShaderMaterial,+ 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;-/** 16807 LCG: same seed, same field, on every machine. */-function prng(seed) {- let s = (seed >>> 0) || 1;- return () => ((s = (s * 16807) % 2147483647) / 2147483647);-}-/** 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);@@ -74,26 +70,8 @@ function toWind(v, dx, dz) {return new THREE.Vector2(dx, dz);}-// Two octaves with a fixed envelope, so the swing is bounded by 1 and-// the field's stated volume is exactly the volume it occupies.-function _wobX(f, p, t) {- return Math.sin(f * t + p) * 0.75- + Math.sin(f * 1.9 * t + p * 2.1) * 0.25;-}--function _wobZ(f, p, t) {- return Math.cos(f * t + p) * 0.75- + Math.cos(f * 2.3 * t + p * 1.6) * 0.25;-}--const _WOB_GLSL = [- 'float astraVeilWobX(float f, float p, float t) {',- ' return sin(f * t + p) * 0.75 + sin(f * 1.9 * t + p * 2.1) * 0.25;',- '}',- 'float astraVeilWobZ(float f, float p, float t) {',- ' return cos(f * t + p) * 0.75 + cos(f * 2.3 * t + p * 1.6) * 0.25;',- '}',-].join('\n');+// The swing: `wobX`/`wobZ` on the CPU mirror, the same pair in GLSL.+const _WOB_GLSL = glslWob('astraVeilWob');/** Wrap v into [-half, half), the CPU mirror of GLSL mod(). */function _wrap(v, extent, half) {@@ -272,7 +250,7 @@ export function makeRainVeil(opts = {}) {const color = new THREE.Color(opts.color === undefined ? 0xb9c6d4 : opts.color);const autoTint = opts.color === undefined ? color : null;- const rnd = prng(opts.seed === undefined ? 7 : opts.seed);+ const rnd = lehmer(opts.seed === undefined ? 7 : opts.seed);const axis = new THREE.Vector3(wind.x, -_RAIN_FALL, wind.y).normalize();// Length ALONG the slanted axis that spans `height` vertically, so@@ -507,7 +485,7 @@ export function makeSnowfall(opts = {}) {const drift = toWind(opts.drift, 0.35, 0);const color = new THREE.Color(opts.color === undefined ? 0xf2f7ff : opts.color);- const rnd = prng(opts.seed === undefined ? 9 : opts.seed);+ const rnd = lehmer(opts.seed === undefined ? 9 : opts.seed);const autoTint = opts.color === undefined ? color : null;// A bigger flake carries more mass per unit drag, so it falls@@ -564,11 +542,11 @@ export function makeSnowfall(opts = {}) {const y = pos[k * 3 + 1] - fall * flake[k * 4 + 1] * t;return new THREE.Vector3(_wrap(pos[k * 3] + drift.x * t- + wob * _wobX(swing[k * 4], swing[k * 4 + 1], t),+ + wob * wobX(swing[k * 4], swing[k * 4 + 1], t),extent, half),y - Math.floor(y / height) * height,_wrap(pos[k * 3 + 2] + drift.y * t- + wob * _wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t),+ + wob * wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t),extent, half));};return g;@@ -702,7 +680,7 @@ export function makeMotes(opts = {}) {opts.size === undefined ? 0.024 : opts.size);const color = new THREE.Color(opts.color === undefined ? 0xfff2d8 : opts.color);- const rnd = prng(opts.seed === undefined ? 13 : opts.seed);+ const rnd = lehmer(opts.seed === undefined ? 13 : opts.seed);const half = extent * 0.5;// Dust does not fall so much as fail to stay up.@@ -757,9 +735,9 @@ export function makeMotes(opts = {}) {const k = Math.min(count - 1, Math.max(0, i | 0));const y = pos[k * 3 + 1] - settle * t;return new THREE.Vector3(- pos[k * 3] + wob * _wobX(swing[k * 4], swing[k * 4 + 1], t),+ pos[k * 3] + wob * wobX(swing[k * 4], swing[k * 4 + 1], t),y - Math.floor(y / height) * height,- pos[k * 3 + 2] + wob * _wobZ(swing[k * 4 + 2],+ pos[k * 3 + 2] + wob * wobZ(swing[k * 4 + 2],swing[k * 4 + 3], t));};return g;diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.jsindex a571546b..53d74c00 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/watermist.js@@ -42,18 +42,13 @@import * as THREE from 'three';+import { lehmer } from './noise.js';import { instancedQuad, makeShaderMaterial, tickShaders, keepOutOfDepthPasses } from './shader.js';// Free fall. It is written twice on purpose — in the vertex shader and// in the CPU mirror `userData.sample` — so both read this one number.const _G = 9.81;-/** 16807 LCG: same seed, same field, on every machine. */-function prng(seed) {- let s = (seed >>> 0) || 1;- return () => ((s = (s * 16807) % 2147483647) / 2147483647);-}-/** A THREE.Vector3 from a vector, an [x,y,z] array or nothing. */function toVec3(v) {if (Array.isArray(v)) {@@ -150,7 +145,7 @@ export function makeWaterMist(opts = {}) {opts.sunColor === undefined ? 0xfff2e0 : opts.sunColor);const flow = toFlow(opts.drift);const heightAt = opts.heightAt || null;- const rnd = prng(opts.seed === undefined ? 5 : opts.seed);+ const rnd = lehmer(opts.seed === undefined ? 5 : opts.seed);// Cards no wider than the bank is deep. A ray that crosses the// bank must meet SEVERAL of them or the one it meets paints its@@ -447,7 +442,7 @@ export function makeSpray(opts = {}) {const sun = toSun(opts.sunDir);const sunColor = new THREE.Color(opts.sunColor === undefined ? 0xfff2e0 : opts.sunColor);- const rnd = prng(opts.seed === undefined ? 3 : opts.seed);+ const rnd = lehmer(opts.seed === undefined ? 3 : opts.seed);// A droplet lives one whole arc, so the field is exactly the launch// rate times the longest flight — no particle count to guess.diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterside.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterside.jsindex a9990c45..be94c040 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterside.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterside.js@@ -16,64 +16,13 @@*/import * as THREE from 'three';-import { patchStandard, composeRoughness } from './shader.js';+import {+ composeRoughness, toColor, unit, withBase, worldBase,+} from './shader.js';-// Named as terrain_shade names them, so a bank wearing a splat and a-// waterline declares ONE pair (patchStandard dedupes varyings).-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',-].join('\n');--// One base for all three. `transformed` is still object-space after-// <begin_vertex>, so the instance transform is folded in by hand or-// every scattered rock takes its waterline from the world origin.-const BASE = {- name: 'waterside:base',- vertexHead: WORLD_VARYINGS,- vertexBody: [- ' vec4 wsP = vec4(transformed, 1.0);',- ' vec3 wsN = normal;',- '#ifdef USE_INSTANCING',- ' wsP = instanceMatrix * wsP;',- ' wsN = mat3(instanceMatrix) * wsN;',- '#endif',- ' vAstraWorld = (modelMatrix * wsP).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(wsN, 0.0)).xyz);',- ].join('\n'),- fragmentHead: WORLD_VARYINGS,-};--/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}--/** Clamp to 0..1 without importing MathUtils for one call. */-function unit(value) {- return Math.max(0, Math.min(1, value));-}--/**- * Apply the shared world-space base, then the patch itself.- *- * `patchStandard` replaces a patch of the SAME name in place, so the- * base costs one vertex body however many of these a material wears.- */-function withBase(material, part) {- // A raw ShaderMaterial (the addon Water, anything from- // makeShaderMaterial) has neither hook, so the patch is a silent- // no-op — the one failure mode nothing else here would report.- if (material && material.isShaderMaterial) {- console.warn(- part.name + ': ' + (material.name || 'material') + ' is a raw ' +- 'ShaderMaterial with no <color_fragment> hook, so this patch ' +- 'does nothing. Patch a standard-material surface instead.');- }- patchStandard(material, BASE);- return patchStandard(material, part);-}+// One base for all three, on the world varyings terrain_shade shares, so+// a bank wearing a splat and a waterline declares ONE pair.+const BASE = worldBase('waterside:base', 'wsP', 'wsN');/*** Darken and gloss the ground below a waterline, fading out above it.@@ -122,7 +71,7 @@ export function patchShoreWet(material, opts = {}) {const sat = opts.saturate === undefined ? 0.35 : opts.saturate;const sheen = opts.sheen === undefined ? 0.22 : opts.sheen;composeRoughness(material, 'waterside:wet', Math.max(gloss, 0));- return withBase(material, {+ return withBase(material, BASE, {name: 'waterside:shoreWet',uniforms: {uWetY: { value: level },@@ -218,7 +167,7 @@ export function patchShoreFoam(material, opts = {}) {const speed = opts.speed === undefined ? 0.6 : opts.speed;const strength = opts.strength === undefined ? 0.85 : opts.strength;const reach = opts.reach === undefined ? 3 : opts.reach;- return withBase(material, {+ return withBase(material, BASE, {name: 'waterside:shoreFoam',uniforms: {uFoamY: { value: level },@@ -371,7 +320,7 @@ export function patchShallowWater(material, opts = {}) {const fade = opts.edgeFade === undefined? (material && material.transparent ? 0.55 : 1): unit(opts.edgeFade);- return withBase(material, {+ return withBase(material, BASE, {name: 'waterside:shallow',uniforms: {uShoalBed: { value: fitBedPlane(opts.bedAt, bounds, bedLevel) },diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/windows.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/windows.jsindex db7076a0..01eb1cc4 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/windows.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/windows.js@@ -12,7 +12,7 @@*/import * as THREE from 'three';-import { patchStandard } from './shader.js';+import { patchStandard, toColor } from './shader.js';const WIN_VARYINGS = ['varying vec2 vWinUv;',@@ -229,12 +229,6 @@ const WIN_BODY = [' * ((1.0 - winOn) * winPane);',].join('\n');-/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}-/*** A seed becomes a far-apart WHOLE-NUMBER lattice offset.*diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.jsindex 099b6679..ea7720da 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/woodland.js@@ -24,8 +24,9 @@ import * as THREE from 'three';import { mulberry32 } from './noise.js';import { windOf } from './grass.js';import {- composeRoughness, instancedQuad, keepOutOfDepthPasses, makeShaderMaterial,- patchStandard, tickShaders,+ composeRoughness, glslLocalDir, instancedQuad, keepOutOfDepthPasses,+ makeShaderMaterial, patchStandard, readVec3, seedVec3, tickShaders,+ toColor, unit,} from './shader.js';const _TAU = Math.PI * 2;@@ -53,48 +54,7 @@ const BARK_KINDS = {crack: [0.07, 0.35], plate: [0, 0], node: 0.34, rough: 0.72 },};-/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}--/** Read a Vector3, an array or an {x,y,z} into a Vector3. */-function toVec(p, fx, fy, fz) {- if (!p) return new THREE.Vector3(fx, fy, fz);- if (Array.isArray(p)) return new THREE.Vector3(p[0], p[1], p[2]);- return new THREE.Vector3(p.x, p.y, p.z);-}--/** Clamp to 0..1 without importing MathUtils for four calls. */-function unit(v) {- return Math.max(0, Math.min(1, v));-}--/** fract(), which JS's % gets wrong for a negative seed. */-function frac(x) {- return x - Math.floor(x);-}--/** astraHash11 from GLSL_UTIL, so CPU and shader agree on a seed. */-function hash11(x) {- let p = frac(x * 0.1031);- p *= p + 33.33;- return frac(p * (p + p));-}--/**- * A seed as a noise-space offset, because the seed is a UNIFORM.- *- * The first material to compile the shared cache key fixes the GLSL for- * every other material wearing this patch, so a seed baked into the- * source would be every trunk's seed.- */-function seedOffset(seed) {- return new THREE.Vector3(- hash11(seed + 0.29), hash11(seed + 4.13), hash11(seed + 9.67))- .multiplyScalar(48);-}+const seedOffset = (seed) => seedVec3(seed, 0.29, 4.13, 9.67, 48);const BARK_VARYINGS = ['varying vec3 vAstraBarkP;',@@ -109,15 +69,7 @@ const BARK_VARYINGS = [const BARK_VERTEX_HEAD = [BARK_VARYINGS,'uniform vec3 uBarkSun;',- 'vec3 astraBarkLocalDir(vec3 w) {',- ' mat3 m = mat3(modelMatrix);',- '#ifdef USE_INSTANCING',- ' m = m * mat3(instanceMatrix);',- '#endif',- ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',- ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',- ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',- '}',+ glslLocalDir('astraBarkLocalDir', true),].join('\n');const BARK_FRAGMENT_HEAD = [@@ -314,7 +266,7 @@ export function patchBark(material, opts = {}) {const depth = unit(opts.depth === undefined ? 0.55 : opts.depth);const mossy = unit(opts.mossy === undefined ? 0.12 : opts.mossy);const seed = opts.seed === undefined ? 1 : opts.seed;- const axis = toVec(opts.axis, 0, 1, 0);+ const axis = readVec3(opts.axis, 0, 1, 0);if (axis.lengthSq() < 1e-9) axis.set(0, 1, 0);// A node count in FIELD units: the along-axis coordinate is already// divided by scale * aniso, so a spacing in metres has to come back@@ -337,7 +289,7 @@ export function patchBark(material, opts = {}) {uBarkAxis: { value: axis.normalize() },uBarkTint: { value: toColor(opts.tint, kind.tint) },uBarkMossColor: { value: toColor(opts.mossColor, 0x46551f) },- uBarkSun: { value: toVec(opts.sun, 0.45, 0.78, 0.35).normalize() },+ uBarkSun: { value: readVec3(opts.sun, 0.45, 0.78, 0.35).normalize() },uBarkSeed: { value: seedOffset(seed) },},vertexHead: BARK_VERTEX_HEAD,@@ -550,7 +502,7 @@ export function makeImposters(opts = {}) {color: toColor(opts.color, kind.color),second: toColor(opts.trunkColor, kind.second),sun: opts.sunDir === undefined && light- ? light.sunDir : toVec(opts.sunDir, 0.45, 0.78, 0.35).normalize(),+ ? light.sunDir : readVec3(opts.sunDir, 0.45, 0.78, 0.35).normalize(),// Irradiance, not a screen colour.sunColor: opts.sunColor === undefined? (light ? light.sunColor : DAY_SUN.clone())