Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
R3F (sdk/r3f) draws more of raea as three.js does: a <ThreeShaderMaterial glsl> is three's own ShaderMaterial, its uniforms and samplers set each frame (three/shader.ts), and a <BufferMesh> carries its own attributes for it; <Look mode="paint"> and cartoon paint in the surfaces (three/paint.ts, colours written through the inverse of three's ACES) and the frame pass only draws the cells; Grass is clumps of tapered blades by the engine's detail steps, made once per field; an HDR or EXR panorama lights the scene only once it has loaded (one still loading compiled every lit material's shader wrong, so nothing drew) and wakes every page that asked for it; a light inside a moved Entity moves with it; a Grade's top-level value is each section's unless the section sets its own; emissive_nits sets emissiveIntensity; meshopt-compressed glTFs decode; the composition's size is in whole pixels. kinds.ts gets rows for Skybox and Lightmap (engine: their .ktx2 files are ones three's KTX2Loader does not read)
shinyobjectzeb56911dd61e
diff --git a/sdk/r3f/src/output/Raea.tsx b/sdk/r3f/src/output/Raea.tsxindex 3c6a410c..91445e81 100644--- a/sdk/r3f/src/output/Raea.tsx+++ b/sdk/r3f/src/output/Raea.tsx@@ -59,7 +59,8 @@ export function Raea<P extends object>({ component: C, props, width, height, fps};}, [page, host, invalidate]);- const w = width ?? size.width, h = height ?? size.height;+ // the composition's size in whole pixels (a canvas laid out by CSS can be a fraction wide; the clock takes integers)+ const w = Math.max(1, Math.round(width ?? size.width)), h = Math.max(1, Math.round(height ?? size.height));useFrame((_state, dt) => {if (!root.current) return;diff --git a/sdk/r3f/src/three/effects.ts b/sdk/r3f/src/three/effects.tsindex af72f7d2..96523452 100644--- a/sdk/r3f/src/three/effects.ts+++ b/sdk/r3f/src/three/effects.ts@@ -220,7 +220,9 @@ void main() {/** a grade field across shadows, midtones and highlights */function levels(p: Record<string, unknown>, k: string, d: number): THREE.Vector3 {- const at = (s: string) => num((p[s] as Record<string, unknown> | undefined)?.[k], d);+ // Grade's top-level value (its `saturation`, Bevy's global one) is each section's unless the section sets its own+ const all = num(p[k], d);+ const at = (s: string) => num((p[s] as Record<string, unknown> | undefined)?.[k], all);return new THREE.Vector3(at("shadows"), at("midtones"), at("highlights"));}@@ -369,7 +371,8 @@ export class Effects {const mode = String(p.mode ?? "site");u.size.value.set(w, h);u.cell.value = num(p.pixelSize, 6);- u.mode.value = { pixel: 0, site: 1, ink: 2, paint: 3, cartoon: 3 }[mode] ?? 1;+ // paint and cartoon are in the surfaces (paint.ts): the pass only draws the frame in cells, as pixel does+ u.mode.value = { pixel: 0, site: 1, ink: 2, paint: 0, cartoon: 0 }[mode] ?? 1;u.keep.value = num(p.color, 1);u.lift.value = num(p.lift, 0);u.gain.value = num(p.gain, 1);@@ -380,7 +383,7 @@ export class Effects {u.ink.value.set(String(p.ink ?? "#1a1410"));u.paper.value.set(String(p.paper ?? "#efe6d2"));u.light.value = p.theme === "light" ? 1 : 0;- if (mode === "paint" || mode === "cartoon") u.cell.value = 1;+ if (mode === "paint" || mode === "cartoon") u.cell.value = num(p.pixelSize, 1);break;}case "Fisheye":diff --git a/sdk/r3f/src/three/extras.ts b/sdk/r3f/src/three/extras.tsindex 7f19b71b..e856a1ab 100644--- a/sdk/r3f/src/three/extras.ts+++ b/sdk/r3f/src/three/extras.ts@@ -70,46 +70,115 @@ export function fire(had: THREE.Group | undefined, p: Props, seconds: number): Treturn g;}-// ---- Grass: blades scattered over the sampled ground, one instanced mesh -----export function grass(spec: Props): THREE.InstancedMesh | undefined {- const s = spec.spec as { area: number[]; grid: [number, number]; height: number[]; density: number[]; tints?: [string, string][]; bladeHeight?: number; width?: [number, number]; seed?: number } | undefined;+// ---- Grass: clumps of tapered blades over the sampled ground, one instanced mesh per patch ----+// As raea-sys-grass grows it (sdk/render/src/3d/grass.tsx): clumps placed by the density grid, each a tuft of `blades`+// leaning blades, root to tip in its patch's tints with a warm highlight on each tip, their normals the ground's (up,+// tilted with the slope), so the field shades as the hill does. Detail by distance from the eye (the engine's steps:+// every clump within 5 m, half of them in 8 blades to 14 m, a fifth in 5 blades beyond), each step a clump mesh per+// tint drawn as instances.+type GrassSpec = {+ area: number[]; grid: [number, number]; height: number[]; density: number[]; patch?: number[]; size?: number[];+ tints?: [string, string][]; highlight?: string; highlightMix?: number; blades?: number; bladeHeight?: number; width?: [number, number];+ spread?: number; lean?: [number, number]; scale?: [number, number]; seed?: number; lod?: { to: number; keep: number; blades: number }[];+};+const LOD = [{ to: 5, keep: 1, blades: 14 }, { to: 14, keep: 0.5, blades: 8 }, { to: Infinity, keep: 0.2, blades: 5 }];++function clumpGeometry(s: GrassSpec, tint: number, n: number, seed: number) {+ const r = rng(seed);+ const [rootHex, tipHex] = s.tints?.[tint] ?? s.tints?.[0] ?? ["#2c4a1a", "#5f8a2c"];+ const root = new THREE.Color(rootHex), tip = new THREE.Color(tipHex), hi = new THREE.Color(s.highlight ?? "#f2e7a0");+ const top = tip.clone().lerp(hi, s.highlightMix ?? 0.22);+ const H = s.bladeHeight ?? 0.3, [w0, w1] = s.width ?? [0.034, 0.05], spread = s.spread ?? 0.06, [l0, l1] = s.lean ?? [0.2, 0.7];+ const pos: number[] = [], nor: number[] = [], col: number[] = [], idx: number[] = [];+ const seg = 3;+ for (let k = 0; k < n; k++) {+ const a = r() * Math.PI * 2, d = Math.sqrt(r()) * spread, x = Math.cos(a) * d, z = Math.sin(a) * d;+ const ang = r() * Math.PI * 2, ca = Math.cos(ang), sa = Math.sin(ang);+ const h = H * (0.55 + r() * 0.75), w = w0 + r() * (w1 - w0), lean = l0 + r() * (l1 - l0);+ const o = pos.length / 3;+ for (let i = 0; i <= seg; i++) {+ const t = i / seg, bend = lean * t * t * h, hw = (w * (1 - t)) / 2 + 0.0008;+ const cx = x + ca * bend, cz = z + sa * bend, cy = h * t;+ const c = i === seg ? top : root.clone().lerp(tip, t);+ for (const side of [-1, 1]) {+ pos.push(cx - sa * hw * side, cy, cz + ca * hw * side);+ nor.push(0, 1, 0);+ col.push(c.r, c.g, c.b);+ }+ if (i < seg) { const q = o + i * 2; idx.push(q, q + 1, q + 2, q + 1, q + 3, q + 2); }+ }+ }+ const g = new THREE.BufferGeometry();+ g.setAttribute("position", new THREE.Float32BufferAttribute(pos, 3));+ g.setAttribute("normal", new THREE.Float32BufferAttribute(nor, 3));+ g.setAttribute("color", new THREE.Float32BufferAttribute(col, 3));+ g.setIndex(idx);+ return g;+}++export function grass(spec: Props, eye?: THREE.Vector3): THREE.Group | undefined {+ const s = spec.spec as GrassSpec | undefined;if (!s) return undefined;const [x0, z0, x1, z1] = s.area, [nx, nz] = s.grid;- const at = (gx: number, gz: number) => {- const i = Math.min(nx - 2, Math.max(0, Math.floor(gx))), k = Math.min(nz - 2, Math.max(0, Math.floor(gz)));- const fx = gx - i, fz = gz - k;- const v = (a: number[], ii: number, kk: number) => a[kk * nx + ii];- const lerp = (a: number[]) => (v(a, i, k) * (1 - fx) + v(a, i + 1, k) * fx) * (1 - fz) + (v(a, i, k + 1) * (1 - fx) + v(a, i + 1, k + 1) * fx) * fz;- return { h: lerp(s.height), d: lerp(s.density) };+ const cell = (u: number, w: number) => [Math.min(nx - 2, Math.max(0, Math.floor(u))), Math.min(nz - 2, Math.max(0, Math.floor(w)))];+ const lerp = (a: number[], u: number, w: number) => {+ const [i, k] = cell(u, w), fx = u - i, fz = w - k, v = (ii: number, kk: number) => a[kk * nx + ii];+ return (v(i, k) * (1 - fx) + v(i + 1, k) * fx) * (1 - fz) + (v(i, k + 1) * (1 - fx) + v(i + 1, k + 1) * fx) * fz;};+ const nearest = (a: number[], u: number, w: number) => a[Math.round(Math.min(nz - 1, Math.max(0, w))) * nx + Math.round(Math.min(nx - 1, Math.max(0, u)))];+ const gx = (x: number) => ((x - x0) / (x1 - x0)) * (nx - 1), gz = (z: number) => ((z - z0) / (z1 - z0)) * (nz - 1);+ const hAt = (x: number, z: number) => lerp(s.height, gx(x), gz(z));const r = rng(s.seed ?? 7);- const area = (x1 - x0) * (z1 - z0);- const blades: [number, number, number, number][] = [];- const tries = Math.min(60000, Math.round(area * Math.max(...s.density)));- for (let i = 0; i < tries; i++) {- const u = r(), w = r();- const x = x0 + u * (x1 - x0), z = z0 + w * (z1 - z0);- const g = at(u * (nx - 1), w * (nz - 1));- if (r() * Math.max(...s.density) <= g.d) blades.push([x, g.h, z, r()]);- }- if (!blades.length) return undefined;- const h = s.bladeHeight ?? 0.35, [w0] = s.width ?? [0.03, 0.01];- const geo = new THREE.BufferGeometry();- geo.setAttribute("position", new THREE.Float32BufferAttribute([-w0, 0, 0, w0, 0, 0, 0, h, 0], 3));- geo.computeVertexNormals();- const [base, tip] = s.tints?.[0] ?? ["#3f6b2a", "#9cc25a"];- const mat = new THREE.MeshStandardMaterial({ color: new THREE.Color(base).lerp(new THREE.Color(tip), 0.5), side: THREE.DoubleSide, roughness: 0.9 });- const m = new THREE.InstancedMesh(geo, mat, blades.length);+ const steps = s.lod ?? LOD;+ const tints = Math.max(1, s.tints?.length ?? 1);+ const blades = s.blades ?? 14;+ const [sc0, sc1] = s.scale ?? [0.85, 1.35];+ const at = eye ?? new THREE.Vector3((x0 + x1) / 2, 0, z1);+ // clumps per step and tint, as matrices+ const mats: THREE.Matrix4[][][] = steps.map(() => Array.from({ length: tints }, () => []));+ const cellArea = ((x1 - x0) / (nx - 1)) * ((z1 - z0) / (nz - 1));const o = new THREE.Object3D();- blades.forEach(([x, y, z, k], i) => {- o.position.set(x, y, z);- o.rotation.set((k - 0.5) * 0.4, k * Math.PI * 2, 0);- o.scale.setScalar(0.7 + k * 0.6);- o.updateMatrix();- m.setMatrixAt(i, o.matrix);- });- m.receiveShadow = true;- return m;+ let total = 0;+ for (let k = 0; k < nz - 1; k++)+ for (let i = 0; i < nx - 1; i++) {+ const d = (s.density[k * nx + i] + s.density[k * nx + i + 1] + s.density[(k + 1) * nx + i] + s.density[(k + 1) * nx + i + 1]) / 4;+ let n = d * cellArea;+ for (; n > 0; n--) {+ if (n < 1 && r() > n) break;+ const u = i + r(), w = k + r();+ const x = x0 + (u / (nx - 1)) * (x1 - x0), z = z0 + (w / (nz - 1)) * (z1 - z0);+ const dist = Math.hypot(x - at.x, z - at.z);+ const step = steps.findIndex((st) => dist < st.to);+ const st = step < 0 ? steps.length - 1 : step;+ if (r() > steps[st].keep) continue;+ const y = hAt(x, z), e = 0.1;+ const dx = (hAt(x + e, z) - hAt(x - e, z)) / (2 * e), dz = (hAt(x, z + e) - hAt(x, z - e)) / (2 * e);+ const size = (s.size ? lerp(s.size, u, w) : 1) * (sc0 + r() * (sc1 - sc0));+ // a thinned step's clumps are wider, so the field stays as full+ const widen = 1 / Math.sqrt(steps[st].keep);+ o.position.set(x, y, z);+ o.rotation.set(Math.atan(dz), r() * Math.PI * 2, -Math.atan(dx), "YXZ");+ o.scale.set(size * widen, size, size * widen);+ o.updateMatrix();+ const tint = s.patch ? Math.min(tints - 1, nearest(s.patch, u, w)) : 0;+ mats[st][tint].push(o.matrix.clone());+ total++;+ }+ }+ if (!total) return undefined;+ const group = new THREE.Group();+ const material = new THREE.MeshStandardMaterial({ vertexColors: true, side: THREE.DoubleSide, roughness: 0.9 });+ steps.forEach((st, si) =>+ mats[si].forEach((list, ti) => {+ if (!list.length) return;+ const m = new THREE.InstancedMesh(clumpGeometry(s, ti, Math.min(blades, st.blades), 100 + ti + si * 17), material, list.length);+ list.forEach((mx, j) => m.setMatrixAt(j, mx));+ m.receiveShadow = true;+ m.frustumCulled = false;+ group.add(m);+ }),+ );+ return group;}// ---- Splat: the splats' centres in their colours (a .ply of 3DGS, or antimatter's .splat) ----diff --git a/sdk/r3f/src/three/geometry.ts b/sdk/r3f/src/three/geometry.tsindex a5126259..e8a98871 100644--- a/sdk/r3f/src/three/geometry.ts+++ b/sdk/r3f/src/three/geometry.ts@@ -22,6 +22,8 @@ interface BufferSpec {normals?: number[];uvs?: number[];colors?: number[] | string[];+ /** its own attributes for a <ThreeShaderMaterial> (each one's size, 1-4, and values a vertex) */+ attributes?: Record<string, { size: number; values: number[] }>;}/** a <BufferMesh>'s arrays as a geometry */@@ -37,6 +39,7 @@ export function bufferGeometry(b: BufferSpec): THREE.BufferGeometry {const rgba = typeof c[0] === "string" ? (c as string[]).flatMap((h) => { const k = new THREE.Color(h); return [k.r, k.g, k.b, 1]; }) : (c as number[]);g.setAttribute("color", new THREE.Float32BufferAttribute(rgba, 4));}+ for (const [k, a] of Object.entries(b.attributes ?? {})) g.setAttribute(k, new THREE.Float32BufferAttribute(a.values, a.size));return g;}diff --git a/sdk/r3f/src/three/kinds.ts b/sdk/r3f/src/three/kinds.tsindex cfdb75e3..cd666699 100644--- a/sdk/r3f/src/three/kinds.ts+++ b/sdk/r3f/src/three/kinds.ts@@ -28,7 +28,7 @@ export const KINDS: Record<string, { status: Status; three: string; note?: strinMeshStandardMaterial: { status: "drawn", three: "MeshStandardMaterial (maps, alpha modes, sides, uv transform, samplers)" },MeshPhysicalMaterial: { status: "drawn", three: "MeshPhysicalMaterial (clearcoat, transmission, ior, thickness, attenuation, anisotropy, specular)" },MeshBasicMaterial: { status: "drawn", three: "MeshBasicMaterial" },- ThreeShaderMaterial: { status: "engine", three: "a three.js shader run by raea's engine (raea-sys-three-shader)", note: "it came from three.js (a ShaderMaterial's GLSL or a node material's WGSL); exported back to three.js, the original material is the one to keep" },+ ThreeShaderMaterial: { status: "drawn", three: "three's own ShaderMaterial from its GLSL, uniforms and samplers set each frame (a node material's WGSL is raea's engine's, drawn in its colour)", note: "it came from three.js (a ShaderMaterial's GLSL or a node material's WGSL); exported back to three.js, the original material is the one to keep" },MeshToonMaterial: { status: "near", three: "MeshToonMaterial with a gradient of its steps or bands", note: "raea's rim, highlight and ink outline are its own shader's: three's toon shades the bands only" },PerspectiveCamera: { status: "drawn", three: "PerspectiveCamera, or OrthographicCamera when `ortho`" },AmbientLight: { status: "drawn", three: "AmbientLight (units.ts)" },@@ -70,6 +70,8 @@ export const KINDS: Record<string, { status: Status; three: string; note?: strinCompute: { status: "engine", three: "a WGSL compute pass runs in Bevy" },BevyComponent: { status: "engine", three: "a Bevy component (a gizmo's is drawn as lines)" },BevyResource: { status: "engine", three: "a Bevy resource" },+ Skybox: { status: "engine", three: "not drawn: Bevy's cubemap sky, a .ktx2 (rgb9e5, zstd) three's KTX2Loader doesn't read", note: "an <Environment background> is the sky three draws" },+ Lightmap: { status: "engine", three: "not drawn: a light bake on a Model's meshes, a .ktx2 sampled by their second UVs", note: "three's lightMap on uv1 could draw a PNG bake; raea's are .ktx2" },Entities: { status: "drawn", three: "a mesh per Mesh entity of World.scene() (its shape, a standard surface of its colour, roughness and metalness, world space), as the engine reads it" },};diff --git a/sdk/r3f/src/three/materials.ts b/sdk/r3f/src/three/materials.tsindex 73ed061e..e809d4f3 100644--- a/sdk/r3f/src/three/materials.ts+++ b/sdk/r3f/src/three/materials.ts@@ -80,6 +80,9 @@ export function paint(m: THREE.Material, p: Props, over = false) {if (have instanceof THREE.Color && typeof v === "string") have.set(v);else if ((typeof v === "number" || typeof v === "boolean") && (typeof have === "number" || typeof have === "boolean")) target[k] = v;}+ // a Bevy StandardMaterial's emissive strength (bevy3d materials.tsx: `emissive_nits`, as the engine draws it,+ // core/scene emissive_power): in three's units already, since a StandardMaterial's emissive skips the camera exposure+ if (typeof p.emissive_nits === "number" && typeof target.emissiveIntensity === "number") target.emissiveIntensity = p.emissive_nits;for (const [from, to, colour] of MAPS) {if (!(to in target) || (over && !(from in p))) continue;const src = p[from];diff --git a/sdk/r3f/src/three/paint.ts b/sdk/r3f/src/three/paint.tsnew file mode 100644index 00000000..7e43a4b8--- /dev/null+++ b/sdk/r3f/src/three/paint.ts@@ -0,0 +1,111 @@+// <Look mode="paint"> (and cartoon) on three.js: raea paints in its material shader, so here each lit surface's+// material becomes a painted one. A surface facing the sun and in its light is its own colour; turned from the sun, its+// colour times `mid` (form shadow); in a cast shadow, its colour times `shadow`. The colours are final (not tone+// mapped), as raea's painted surfaces are. Unlit materials (pictures, the sky) are left as they are. The frame pass+// (effects.ts) then only draws the frame in cells of `pixelSize`.+import * as THREE from "three";++type Props = Record<string, unknown>;+const painted = new WeakMap<THREE.Material, { key: string; mat: THREE.Material }>();++/** the frame's tone mapping, which the composer runs after the surfaces (Scene3d.apply sets it): painted colours are+ * written through its inverse so they come out as themselves. 1: three's ACES at `exposure` (exact), 0: none to undo+ * (no tone mapping, or one with no inverse here, such as Tony's table) */+export const paintTone = { mode: { value: 0 }, exposure: { value: 1 } };++const UNTONE = `+uniform float paintToneMode; uniform float paintExposure;+vec3 paintUntone(vec3 c) {+ if (paintToneMode < 0.5) return c;+ // three's ACESFilmicToneMapping, backwards: its output matrix, the RRT+ODT fit per channel, its input matrix, the+ // exposure (three's 1/0.6 in it)+ const mat3 inM = mat3(vec3(0.59719, 0.07600, 0.02840), vec3(0.35458, 0.90834, 0.13383), vec3(0.04823, 0.01566, 0.83777));+ const mat3 outM = mat3(vec3(1.60475, -0.10208, -0.00327), vec3(-0.53108, 1.10813, -0.07276), vec3(-0.07367, -0.00605, 1.07602));+ vec3 y = clamp(inverse(outM) * clamp(c, 0.0, 0.999), 0.0, 0.999);+ vec3 a = 0.0245786 - y * 0.4329510, q = 1.0 - y * 0.983729, b = 0.000090537 + y * 0.238081;+ vec3 v = (-a + sqrt(a * a + 4.0 * q * b)) / (2.0 * q);+ return max(inverse(inM) * v, 0.0) * 0.6 / max(paintExposure, 1e-5);+}+`;++function paintedOf(src: THREE.Material, mid: THREE.Color, shadow: THREE.Color): THREE.Material {+ const key = mid.getHexString() + shadow.getHexString();+ const had = painted.get(src);+ if (had && had.key === key) return had.mat;+ const s = src as THREE.MeshStandardMaterial;+ const m = new THREE.MeshLambertMaterial({+ color: s.color?.clone() ?? new THREE.Color(1, 1, 1),+ map: s.map ?? null,+ vertexColors: s.vertexColors,+ side: s.side,+ transparent: s.transparent,+ opacity: s.opacity,+ alphaTest: s.alphaTest,+ alphaMap: s.alphaMap ?? null,+ });+ m.toneMapped = false;+ m.onBeforeCompile = (sh) => {+ sh.uniforms.paintMid = { value: mid };+ sh.uniforms.paintShadow = { value: shadow };+ sh.uniforms.paintToneMode = paintTone.mode;+ sh.uniforms.paintExposure = paintTone.exposure;+ sh.fragmentShader = sh.fragmentShader+ .replace("void main() {", "uniform vec3 paintMid; uniform vec3 paintShadow;\n" + UNTONE + "\nvoid main() {")+ .replace(+ "#include <opaque_fragment>",+ `#if NUM_DIR_LIGHTS > 0+ float paintFacing = dot(normalize(vNormal), directionalLights[0].direction);+ float paintLit = dot(reflectedLight.directDiffuse, vec3(0.3333)) / max(dot(diffuseColor.rgb * directionalLights[0].color, vec3(0.3333)) * RECIPROCAL_PI, 1e-5);+ vec3 paintTone = paintFacing <= 0.0 ? paintMid : (paintLit < 0.5 * paintFacing ? paintShadow : vec3(1.0));+ outgoingLight = paintUntone(diffuseColor.rgb * paintTone);+ #else+ outgoingLight = paintUntone(diffuseColor.rgb);+ #endif+ #include <opaque_fragment>`,+ );+ };+ m.customProgramCacheKey = () => "raea-paint";+ painted.set(src, { key, mat: m });+ return m;+}++/** an unlit surface (a picture card) under paint: its colour as itself, through the frame's tone mapping */+function shownOf(src: THREE.MeshBasicMaterial): THREE.Material {+ const had = painted.get(src);+ if (had) return had.mat;+ const m = src.clone();+ m.onBeforeCompile = (sh) => {+ sh.uniforms.paintToneMode = paintTone.mode;+ sh.uniforms.paintExposure = paintTone.exposure;+ sh.fragmentShader = sh.fragmentShader+ .replace("void main() {", UNTONE + "\nvoid main() {")+ .replace("#include <opaque_fragment>", "outgoingLight = paintUntone(outgoingLight);\n#include <opaque_fragment>");+ };+ m.customProgramCacheKey = () => "raea-paint-shown";+ painted.set(src, { key: "", mat: m });+ return m;+}++/** paint (or unpaint) every lit surface in `root` for a Look's props (undefined: no paint look on the page) */+export function paintLook(root: THREE.Object3D, look: Props | undefined) {+ const on = look && (look.mode === "paint" || look.mode === "cartoon");+ const mid = new THREE.Color(String(look?.mid ?? (look?.mode === "cartoon" ? look?.shadow ?? "#f2c7b8" : "#b4b6bc")));+ const shadow = new THREE.Color(String(look?.shadow ?? "#b4b6bc"));+ root.traverse((o) => {+ const mesh = o as THREE.Mesh;+ if (!mesh.isMesh) return;+ const own = (mesh.userData.unpainted as THREE.Material | undefined) ?? (mesh.material as THREE.Material);+ if (Array.isArray(own)) return;+ if (on && own instanceof THREE.MeshBasicMaterial && own.map) {+ mesh.userData.unpainted = own;+ mesh.material = shownOf(own);+ return;+ }+ if (!on || !(own instanceof THREE.MeshStandardMaterial || own instanceof THREE.MeshLambertMaterial || own instanceof THREE.MeshPhongMaterial)) {+ if (mesh.userData.unpainted) (mesh.material = own), delete mesh.userData.unpainted;+ return;+ }+ mesh.userData.unpainted = own;+ mesh.material = paintedOf(own, mid, shadow);+ });+}diff --git a/sdk/r3f/src/three/scene.ts b/sdk/r3f/src/three/scene.tsindex 74528c2f..24dcaef7 100644--- a/sdk/r3f/src/three/scene.ts+++ b/sdk/r3f/src/three/scene.ts@@ -6,11 +6,13 @@ import * as THREE from "three";import { EXRLoader } from "three/examples/jsm/loaders/EXRLoader.js";import { HDRLoader } from "three/examples/jsm/loaders/HDRLoader.js";import type { Sky } from "three/examples/jsm/objects/Sky.js";+import { paintLook, paintTone } from "./paint";import { fire, flat, grass, placeFlat, plateTexture, richText, screenCard, sky, splatPoints } from "./extras";import { GEOMETRY, geometryOfShape, shapesReady } from "./geometry";import { KINDS, PRIMITIVES } from "./kinds";import { TONE, fitCamera, makeLight, setCamera, setLight, vec } from "./lights";import { MATERIAL, paint, texture, vertexColoured } from "./materials";+import { shaderMaterial } from "./shader";import { ModelPart, decal, gizmoLines, imagePlane, instanced, place } from "./things";import { EXPOSURE } from "../units";@@ -29,6 +31,8 @@ interface Kept {waiting?: boolean;/** <Entities>: a mesh per entity id, and the shape it was made from */entities?: Map<number, { mesh: THREE.Mesh; shape: string }>;+ /** <Grass>: the field it was made from */+ made?: string;}/** what raea's settings make of the renderer: apply() sets them */@@ -47,18 +51,34 @@ const GIZMO = "bevy_gizmos::retained::Gizmo";const envLoaders = { hdr: new HDRLoader(), exr: new EXRLoader() };const envs = new Map<string, THREE.Texture>();+/** panoramas that have loaded: three builds the environment's shaders from its size, so one still loading isn't lit by+ * (an HDR's texture before its data arrives compiles every lit material's shader wrong, and they draw nothing) */+const ready = new WeakSet<THREE.Texture>();++/** what each panorama still loading should do once it has: every page that asked for it, not only the first */+const waiting = new Map<THREE.Texture, Set<() => void>>();function panorama(src: string, done: () => void): THREE.Texture {let t = envs.get(src);- if (t) return t;+ if (t) {+ if (!ready.has(t)) waiting.get(t)?.add(done);+ return t;+ }+ const loaded = () => {+ ready.add(t!);+ for (const f of waiting.get(t!) ?? []) f();+ waiting.delete(t!);+ };const ext = src.split("?")[0].split(".").pop()!.toLowerCase();try {- t = ext === "hdr" || ext === "exr" ? envLoaders[ext].load(src, done) : texture(src, true);+ t = ext === "hdr" || ext === "exr" ? envLoaders[ext].load(src, loaded) : texture(src, true);+ if (!(ext === "hdr" || ext === "exr")) ready.add(t);} catch (e) {console.warn(`raea/r3f: Environment ${src} couldn't be loaded: ${String(e)}`);t = new THREE.Texture();}t.mapping = THREE.EquirectangularReflectionMapping;envs.set(src, t);+ if (!ready.has(t)) waiting.set(t, new Set([done]));return t;}@@ -112,6 +132,8 @@ export class Scene3d {this.kept.delete(el);}}+ // a paint look is in the surfaces (paint.ts); the frame pass only draws its cells+ paintLook(this.scene, this.effects.find((e) => e.kind === "Look")?.props);this.fit(this.width, this.height);}@@ -274,14 +296,23 @@ export class Scene3d {return k;case "Environment": {const src = p.src as string;- const t = panorama(src, () => this.onLoad());+ // attached once it has loaded (a cube-UV map made from an empty texture fails to compile), by this page's+ // next sync or, if the rows don't change, here+ const t = panorama(src, () => {+ const env = this.scene.userData.raeaEnvironment as { src: string; intensity: number; background: boolean } | undefined;+ if (env?.src === src) {+ if (env.intensity > 0) this.scene.environment = t;+ if (env.background) this.scene.background = t;+ }+ this.onLoad();+ });// for the source export (../export): the panorama as raea gave itthis.scene.userData.raeaEnvironment = { src, intensity: (p.intensity as number) ?? 1, rotation: (p.rotation as number) ?? 0, background: !!p.background, backgroundIntensity: (p.backgroundIntensity as number) ?? (p.intensity as number) ?? 1 };const intensity = ((p.intensity as number) ?? 1) * 1000 * EXPOSURE;- this.scene.environment = intensity > 0 ? t : null;+ this.scene.environment = intensity > 0 && ready.has(t) ? t : null;this.scene.environmentIntensity = intensity;this.scene.environmentRotation.set(0, (p.rotation as number) ?? 0, 0);- if (p.background) {+ if (p.background && ready.has(t)) {this.scene.background = t;this.scene.backgroundIntensity = ((p.backgroundIntensity as number) ?? (p.intensity as number) ?? 1) * 1000 * EXPOSURE;this.scene.backgroundRotation.set(0, (p.rotation as number) ?? 0, 0);@@ -298,8 +329,12 @@ export class Scene3d {this.hang(k, el, fire(k.obj as THREE.Group | undefined, p, this.seconds));return k;case "Grass": {+ // made once per field (its grids are thousands of numbers), near the eye in full and thinned beyond+ const json = JSON.stringify(p.spec ?? null);+ if (k.obj && k.made === json) return k;k.obj?.removeFromParent();- const g = grass(p);+ k.made = json;+ const g = grass(p, this.camera.position);if (g) this.hang(k, el, g);return k;}@@ -348,6 +383,12 @@ export class Scene3d {}return k;}+ if (kind === "ThreeShaderMaterial") {+ const mesh = owner?.obj instanceof THREE.Mesh ? owner.obj : undefined;+ k.material = shaderMaterial(k.material, p);+ if (mesh) mesh.material = k.material;+ return k;+ }if (kind in MATERIAL) {// a material inside a Model re-covers it (read there)if (owner?.kind === "Model") return k;@@ -376,11 +417,13 @@ export class Scene3d {if (kind.endsWith("Light")) {const l = (k.obj as THREE.Light | undefined) ?? makeLight(kind);if (!l) return k;- if (!k.obj) {- k.obj = l;- this.scene.add(l);- }+ // a light is an entity like any other: inside a moved Entity it moves with it (its position and its target are+ // in the parent's frame, as Bevy's Transform is)+ if (!k.obj) k.obj = l;+ if (!l.parent) this.parentOf(el).add(l);setLight(l, kind, p, this.scene, this.settings.shadowMap);+ const target = (l as THREE.SpotLight).target as THREE.Object3D | undefined;+ if (target && l.parent && target.parent !== l.parent) l.parent.add(target);return k;}const status = KINDS[kind]?.status;@@ -418,6 +461,8 @@ export class Scene3d {renderer.toneMapping = this.settings.toneMapping;// three's ACES scales its input by 1/0.6 (tonemapping_pars_fragment); Bevy's ACESFitted doesn'trenderer.toneMappingExposure = this.settings.exposure * (this.settings.toneMapping === THREE.ACESFilmicToneMapping ? 0.6 : 1);+ paintTone.mode.value = !this.settings.tony && this.settings.toneMapping === THREE.ACESFilmicToneMapping ? 1 : 0;+ paintTone.exposure.value = renderer.toneMappingExposure;renderer.shadowMap.enabled = this.settings.shadows;renderer.shadowMap.type = THREE.PCFSoftShadowMap;}diff --git a/sdk/r3f/src/three/shader.ts b/sdk/r3f/src/three/shader.tsnew file mode 100644index 00000000..a1ccd051--- /dev/null+++ b/sdk/r3f/src/three/shader.ts@@ -0,0 +1,72 @@+// <ThreeShaderMaterial glsl={{vertex, fragment}}> on three.js: it came from three.js, so here it is three's own+// ShaderMaterial (RawShaderMaterial when `raw`), its uniforms set each frame from the props and its samplers loaded as+// pictures. A node material's WGSL (`wgsl`) is raea's engine's only; three draws that mesh in its `color`.+import * as THREE from "three";+import { texture } from "./materials";++type Props = Record<string, unknown>;++const BLEND: Record<string, THREE.Blending> = {+ normal: THREE.NormalBlending,+ additive: THREE.AdditiveBlending,+ add: THREE.AdditiveBlending,+ multiply: THREE.MultiplyBlending,+ none: THREE.NoBlending,+};+const SIDE: Record<string, THREE.Side> = { front: THREE.FrontSide, back: THREE.BackSide, double: THREE.DoubleSide };++function value(v: unknown): unknown {+ if (!Array.isArray(v)) return typeof v === "boolean" ? (v ? 1 : 0) : v;+ if (v.length === 2) return new THREE.Vector2(v[0], v[1]);+ if (v.length === 3) return new THREE.Vector3(v[0], v[1], v[2]);+ if (v.length === 4) return new THREE.Vector4(v[0], v[1], v[2], v[3]);+ if (v.length === 9) return new THREE.Matrix3().fromArray(v);+ if (v.length === 16) return new THREE.Matrix4().fromArray(v);+ return v;+}++/** the material for these props: the one it had while its source is the same (its uniforms updated), else a new one */+export function shaderMaterial(had: THREE.Material | undefined, p: Props): THREE.Material {+ const glsl = p.glsl as { vertex: string; fragment: string; raw?: boolean; vertexColors?: boolean } | undefined;+ if (!glsl) {+ const m = had instanceof THREE.MeshBasicMaterial ? had : new THREE.MeshBasicMaterial();+ m.color.set((p.color as string | undefined) ?? "#ff00ff");+ return m;+ }+ const key = `${glsl.raw ? 1 : 0}|${glsl.vertex}|${glsl.fragment}`;+ let m = had as THREE.ShaderMaterial | undefined;+ if (!m || m.userData.raeaShader !== key) {+ had?.dispose();+ m = new (glsl.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({ vertexShader: glsl.vertex, fragmentShader: glsl.fragment, uniforms: {} });+ m.userData.raeaShader = key;+ }+ m.vertexColors = !!glsl.vertexColors;+ for (const [k, v] of Object.entries((p.uniforms as Props | undefined) ?? {})) {+ const u = m.uniforms[k];+ const val = value(v);+ if (u && u.value instanceof THREE.Vector2 && Array.isArray(v)) (u.value as THREE.Vector2).fromArray(v as number[]);+ else if (u && (u.value instanceof THREE.Vector3 || u.value instanceof THREE.Vector4) && Array.isArray(v)) u.value.fromArray(v as number[]);+ else if (u) u.value = val;+ else m.uniforms[k] = { value: val };+ }+ for (const [k, v] of Object.entries((p.textures as Record<string, string | { src: string; colorSpace?: string }> | undefined) ?? {})) {+ const src = typeof v === "string" ? v : v.src;+ const colour = typeof v === "string" || v.colorSpace !== "linear";+ const t = texture(src, colour);+ if (m.uniforms[k]) m.uniforms[k].value = t;+ else m.uniforms[k] = { value: t };+ }+ const time = p.time as [number, number, number] | undefined;+ if (time) {+ for (const [k, i] of [["time", 0], ["uTime", 0], ["iTime", 0]] as const) if (k in m.uniforms) m.uniforms[k].value = time[i];+ }+ m.transparent = !!p.transparent;+ m.blending = BLEND[(p.blending as string | undefined) ?? "normal"] ?? THREE.NormalBlending;+ m.side = SIDE[(p.side as string | undefined) ?? "front"] ?? THREE.FrontSide;+ m.depthWrite = p.depthWrite !== undefined ? !!p.depthWrite : !p.transparent;+ m.depthTest = p.depthTest !== false;+ m.alphaTest = typeof p.alphaTest === "number" ? p.alphaTest : 0;+ // "display" (a ShaderMaterial's): its colour is what the canvas shows, past the tone curve+ m.toneMapped = p.output === "linear";+ return m;+}diff --git a/sdk/r3f/src/three/things.ts b/sdk/r3f/src/three/things.tsindex 726b8cae..53130f4a 100644--- a/sdk/r3f/src/three/things.ts+++ b/sdk/r3f/src/three/things.ts@@ -2,6 +2,7 @@// materials), pictures on cards, instanced copies, gizmo lines and decals.import * as THREE from "three";import { GLTFLoader, type GLTF } from "three/examples/jsm/loaders/GLTFLoader.js";+import { MeshoptDecoder } from "three/examples/jsm/libs/meshopt_decoder.module.js";import { paint, texture } from "./materials";import { vec } from "./lights";@@ -21,7 +22,8 @@ export function place(o: THREE.Object3D, p: Props) {}// ---- glTF -----const gltfLoader = new GLTFLoader();+// meshopt-compressed models (gltf-transform's meshopt: a web build's models a fraction of the size) decode in place+const gltfLoader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder);const gltfs = new Map<string, Promise<GLTF>>();export const loadGltf = (src: string) => {let g = gltfs.get(src);