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
R3F24: a MeshStandardMaterial or MeshPhysicalMaterial with an onBeforeCompile of its own is three's own program with the patch applied (src/input/patched.ts): ShaderLib's source handed to the patch with the material's defines and uniforms, patched once a program as three does, the material's values refreshed into it each frame, the defines three puts in front for its maps, sides and vertex colours; the fragment cut at three's lights and writing its surface for raea's engine to light (the lit GLSL stage). A patch past the lights is named once and left out. kinds.ts notes; material.ts routes it, scene.ts leaves its uvs as three gives them. test/patched.test.ts
shinyobjectz2a8ea0b81b61
diff --git a/sdk/r3f/src/input/kinds.ts b/sdk/r3f/src/input/kinds.tsindex 6d85fc59..7a9e550d 100644--- a/sdk/r3f/src/input/kinds.ts+++ b/sdk/r3f/src/input/kinds.ts@@ -43,8 +43,8 @@ export const CLASSES: Record<string, { status: InputStatus; raea: string; note?:Audio: { status: "none", raea: "sound: raea/tone" },PositionalAudio: { status: "none", raea: "sound: <Sound3D>" },// materials- MeshStandardMaterial: { status: "drawn", raea: "MeshStandardMaterial (maps, alpha test and blending, sides, uv placement, samplers)" },- MeshPhysicalMaterial: { status: "drawn", raea: "MeshPhysicalMaterial (clearcoat, transmission, ior, thickness, attenuation, anisotropy, specular)", note: "sheen and iridescence are three's" },+ MeshStandardMaterial: { status: "drawn", raea: "MeshStandardMaterial (maps, alpha test and blending, sides, uv placement, samplers)", note: "patched by onBeforeCompile: three's own program with the patch, its surface lit by raea (patched.ts); a patch past three's lighting is left out" },+ MeshPhysicalMaterial: { status: "drawn", raea: "MeshPhysicalMaterial (clearcoat, transmission, ior, thickness, attenuation, anisotropy, specular)", note: "sheen and iridescence are three's; patched by onBeforeCompile: three's own program with the patch, lit by raea (sheen, clearcoat and transmission then left out)" },MeshBasicMaterial: { status: "drawn", raea: "MeshBasicMaterial" },MeshLambertMaterial: { status: "drawn", raea: "MeshStandardMaterial, roughness 1, metalness 0" },MeshPhongMaterial: { status: "near", raea: "MeshPhysicalMaterial: its shininess as a roughness, its specular colour as F0 (reflectance and specular tint)", note: "GGX's highlight, not Blinn-Phong's; an F0 above 0.16 (Bevy's highest reflectance) is held there, so a bright specular colour glints less" },@@ -58,8 +58,8 @@ export const CLASSES: Record<string, { status: InputStatus; raea: string; note?:PointsMaterial: { status: "drawn", raea: "MeshBasicMaterial on the points' quads" },LineBasicMaterial: { status: "drawn", raea: "the Gizmo's colours" },LineDashedMaterial: { status: "drawn", raea: "the Gizmo's colours, the line cut into its dashes by its line distances" },- ShaderMaterial: { status: "drawn", raea: "ThreeShaderMaterial: its GLSL translated by naga and run with three's built-ins", note: "at most 4 textures, 254 vec4s of uniforms and 4 attributes of its own; a render target's texture is white; onBeforeCompile isn't read" },- RawShaderMaterial: { status: "drawn", raea: "ThreeShaderMaterial: its GLSL translated by naga and run with three's built-ins", note: "at most 4 textures, 254 vec4s of uniforms and 4 attributes of its own; a render target's texture is white; onBeforeCompile isn't read" },+ ShaderMaterial: { status: "drawn", raea: "ThreeShaderMaterial: its GLSL translated by naga and run with three's built-ins", note: "at most 4 textures, 254 vec4s of uniforms and 4 attributes of its own; a render target's texture is the image raea draws it into on its GPU, a depth texture white; onBeforeCompile isn't read" },+ RawShaderMaterial: { status: "drawn", raea: "ThreeShaderMaterial: its GLSL translated by naga and run with three's built-ins", note: "at most 4 textures, 254 vec4s of uniforms and 4 attributes of its own; a render target's texture is the image raea draws it into on its GPU, a depth texture white; onBeforeCompile isn't read" },Material: { status: "none", raea: "the base class" },// three/webgpu's node materials (TSL): one with no node of its own is the classic material it extends, drawn natively;// one with a graph (colorNode, positionNode, ...) on a mesh is compiled to WGSL by three's own WGSLNodeBuilder and rundiff --git a/sdk/r3f/src/input/material.ts b/sdk/r3f/src/input/material.tsindex bae5ff94..d6da9944 100644--- a/sdk/r3f/src/input/material.ts+++ b/sdk/r3f/src/input/material.ts@@ -1,13 +1,14 @@// A three.js material as raea's: the component that draws it the same way and its props. Standard and physical are// Bevy's StandardMaterial on both sides; basic is unlit; Lambert is the standard surface with no gloss; Phong's// shininess becomes a roughness (Blinn-Phong's exponent as a GGX roughness); toon is raea's toon surface with a band per-// step of its gradient map; normal, matcap, depth and distance materials are drawn as the unlit colour each puts on-// screen most (their per-pixel looks need three's shaders). A ShaderMaterial's GLSL doesn't run in Bevy: it is drawn-// with its `color` (or diffuse) uniform, unlit, and named once, with raea's <SurfaceShader> (WESL) as its port.+// step of its gradient map; normal and matcap run three's own programs; depth and distance materials are drawn as the+// unlit grey of three's passes. A ShaderMaterial's GLSL runs in raea's engine (shader.ts), and a standard or physical+// material patched by onBeforeCompile runs its patched program, lit by Bevy (patched.ts).import * as THREE from "three";import { placementOf, srcOf } from "./texture";import { classicOf, nodeMaterialOf, type NodeAt } from "./tsl";import { builtinPart, farPlane, isShader, shaderPart } from "./shader";+import { drawsPatched, patchedPart } from "./patched";export type Props = Record<string, unknown>;export interface Part {@@ -122,6 +123,8 @@ function warnOnce(type: string, why: string) {export function materialOf(m: THREE.Material, vertexColors: boolean, at?: NodeAt): Part {const p: Props = {};const t = m.type;+ // a lit material patched by onBeforeCompile: three's own program with the patch applied (R3F24)+ if (drawsPatched(m)) return patchedPart(m as THREE.MeshStandardMaterial);switch (t) {case "MeshPhysicalMaterial":physical(m as THREE.MeshPhysicalMaterial, p);diff --git a/sdk/r3f/src/input/patched.ts b/sdk/r3f/src/input/patched.tsnew file mode 100644index 00000000..cf926809--- /dev/null+++ b/sdk/r3f/src/input/patched.ts@@ -0,0 +1,140 @@+// A lit material patched by onBeforeCompile (docs/r3f.feature R3F24: drei's MeshWobbleMaterial, MeshDistortMaterial and+// MeshReflectorMaterial, an app's own vertex displacement) as raea's <ThreeShaderMaterial> of three's own program with+// the patch applied, as three compiles it: ShaderLib's standard or physical source handed to the material's+// onBeforeCompile with the material's defines and uniforms, once a program as three does (again when its version or+// customProgramCacheKey changes), its uniforms refreshed from the material each frame as three's renderer refreshes+// them, the defines three's WebGLProgram sets for its maps, sides and vertex colours in front.+//+// Its lighting is Bevy's, as a lit TSL material's is (R3F21): the fragment stage is cut where three's lights begin+// (<lights_physical_fragment>) and writes the surface it has made by then for raea's engine to light+// (raea-sys-three-shader's lit stage, glsl.rs): base (diffuseColor), normal (view space, w the roughness), emissive+// (w the metalness) and the point in world space. A patch that changes what comes after (the light, the output) is+// named once and left out.+import * as THREE from "three";+import type { Part } from "./material";+import { expandIncludes, shaderPart } from "./shader";++type Lit = THREE.MeshStandardMaterial;+type Program = THREE.WebGLProgramParametersWithUniforms & { shaderName: string; shaderType: string };++/** whether a material has an onBeforeCompile of its own (three's own is empty) */+export const isPatched = (m: THREE.Material): boolean => m.onBeforeCompile !== THREE.Material.prototype.onBeforeCompile;++/** whether raea draws a material as its patched program (a lit standard or physical one with a patch) */+export const drawsPatched = (m: THREE.Material): boolean => (m.type === "MeshStandardMaterial" || m.type === "MeshPhysicalMaterial") && isPatched(m);++const LIGHTS_AT = "#include <lights_physical_fragment>";+/** what follows the cut in three's own program: a patched program whose tail differs changed the light or output */+const TAIL = THREE.ShaderLib.physical.fragmentShader.slice(THREE.ShaderLib.physical.fragmentShader.indexOf(LIGHTS_AT));+/** the chunks only three's lighting reads, left out with it */+const DEAD = /^[ \t]*#include +<(lights_pars_begin|lights_physical_pars_fragment|envmap_common_pars_fragment|envmap_physical_pars_fragment|cube_uv_reflection_fragment|transmission_pars_fragment|shadowmap_pars_fragment|iridescence_fragment|aomap_pars_fragment|lightmap_pars_fragment)>/gm;+const OUTS = ["raeaBase", "raeaNormal", "raeaEmissive", "raeaWorld"];+const WRITE = [+ "\traeaBase = diffuseColor;",+ "\traeaNormal = vec4( normal, roughnessFactor );",+ "\traeaEmissive = vec4( totalEmissiveRadiance, metalnessFactor );",+ "\t// the point in world space: three's view matrix turned back (a camera's has no scale)",+ "\traeaWorld = vec4( transpose( mat3( viewMatrix ) ) * ( - vViewPosition - viewMatrix[ 3 ].xyz ), 1.0 );",+ "}",+ "",+].join("\n");++/** the maps three's program reads, each by its USE_ and _UV defines, its uniform and its Transform */+const MAPS = ["map", "alphaMap", "emissiveMap", "roughnessMap", "metalnessMap", "normalMap", "bumpMap", "displacementMap"] as const;+/** maps three only lights with, which Bevy's lighting doesn't take from a surface */+const UNREAD = ["aoMap", "lightMap"] as const;++const warned = new Set<string>();+function warnOnce(k: string, why: string) {+ if (warned.has(k)) return;+ warned.add(k);+ console.warn(`raea/r3f: ${k} ${why}`);+}++/** a patched fragment stage cut at three's lights, writing its surface instead */+export function surfaceStage(fragment: string, what: string): string {+ const at = fragment.indexOf(LIGHTS_AT);+ if (at < 0) throw new Error(`raea/r3f: ${what}'s patch took out three's <lights_physical_fragment>, where raea lights its surface`);+ if (fragment.slice(at).trim() !== TAIL.trim()) warnOnce(`${what}'s patch past three's lighting`, "is left out: raea's engine lights its surface");+ const head = fragment.slice(0, at).replace(DEAD, "");+ const main = head.search(/\bvoid\s+main\s*\(/);+ return `${head.slice(0, main)}${OUTS.map((o, i) => `layout(location = ${i}) out highp vec4 ${o};`).join("\n")}\n${head.slice(main)}${WRITE}`;+}++/** the defines three's WebGLProgram puts in front for this material (its maps, sides, vertex colours, alpha test) */+function definesOf(m: Lit): Record<string, string> {+ const d: Record<string, string> = {};+ for (const k of MAPS) {+ if (!(m as unknown as Record<string, THREE.Texture | null>)[k]) continue;+ const K = k.toUpperCase();+ d[`USE_${K}`] = "";+ d[`${K}_UV`] = "uv";+ }+ if (m.normalMap) d.USE_NORMALMAP_TANGENTSPACE = "";+ if (m.flatShading) d.FLAT_SHADED = "";+ if (m.side === THREE.DoubleSide) d.DOUBLE_SIDED = "";+ if (m.side === THREE.BackSide) d.FLIP_SIDED = "";+ if (m.vertexColors) d.USE_COLOR = "";+ if (m.alphaTest > 0) d.USE_ALPHATEST = "";+ for (const k of UNREAD) if ((m as unknown as Record<string, unknown>)[k]) warnOnce(`a patched ${m.type}'s ${k}`, "is left out (Bevy lights the surface)");+ return d;+}++/** the material's values in its program's uniforms, as three's renderer sets them each frame (refreshUniformsCommon,+ * refreshUniformsStandard) */+function refresh(u: Record<string, THREE.IUniform>, m: Lit) {+ (u.diffuse.value as THREE.Color).copy(m.color);+ u.opacity.value = m.opacity;+ (u.emissive.value as THREE.Color).copy(m.emissive).multiplyScalar(m.emissiveIntensity);+ u.roughness.value = m.roughness;+ u.metalness.value = m.metalness;+ if (m.alphaTest > 0) u.alphaTest.value = m.alphaTest;+ const back = m.side === THREE.BackSide ? -1 : 1;+ (u.normalScale.value as THREE.Vector2).copy(m.normalScale).multiplyScalar(back);+ u.bumpScale.value = m.bumpScale * back;+ u.displacementScale.value = m.displacementScale;+ u.displacementBias.value = m.displacementBias;+ for (const k of MAPS) {+ const t = (m as unknown as Record<string, THREE.Texture | null>)[k];+ if (!t) continue;+ u[k].value = t;+ if (t.matrixAutoUpdate) t.updateMatrix();+ (u[`${k}Transform`].value as THREE.Matrix3).copy(t.matrix);+ }+}++/** each patched material's program, patched when three would compile it */+const programs = new WeakMap<THREE.Material, { key: string; p: Program }>();++function programOf(m: Lit, defines: Record<string, string>): Program {+ const key = `${m.version}|${m.customProgramCacheKey()}|${JSON.stringify(defines)}`;+ const had = programs.get(m);+ if (had?.key === key) return had.p;+ const lib = m.type === "MeshPhysicalMaterial" ? THREE.ShaderLib.physical : THREE.ShaderLib.standard;+ // three hands the patch the material's own defines (a patch may add to them, as drei's reflector adds USE_UV)+ const p = { shaderName: m.type, shaderType: m.type, uniforms: THREE.UniformsUtils.clone(lib.uniforms), vertexShader: lib.vertexShader, fragmentShader: lib.fragmentShader, defines: { ...(m.defines ?? {}) } } as unknown as Program;+ m.onBeforeCompile(p, undefined as unknown as THREE.WebGLRenderer);+ programs.set(m, { key, p });+ return p;+}++/** A lit material with an onBeforeCompile of its own as the <ThreeShaderMaterial> of its patched program */+export function patchedPart(m: Lit): Part {+ const defines = definesOf(m);+ const p = programOf(m, defines);+ refresh(p.uniforms, m);+ const fragment = surfaceStage(p.fragmentShader, m.type);+ // only the uniforms the program declares (three's lights' and environment's go with its lighting)+ const text = expandIncludes(`${p.vertexShader}\n${fragment}`);+ const uniforms = Object.fromEntries(Object.entries(p.uniforms).filter(([k]) => new RegExp(`\\b${k}\\b`).test(text)));+ // three's light counts, each 0 as its prefix sets them with no lights of its own (its shadow and light-map guards)+ const counts = Object.fromEntries([...new Set(text.match(/\bNUM_\w+/g))].filter((n) => !n.includes("CLIPPING")).map((n) => [n, "0"]));+ const sm = new THREE.ShaderMaterial({ uniforms, vertexShader: p.vertexShader, fragmentShader: fragment, defines: { ...counts, ...defines, ...p.defines } });+ Object.assign(sm, { transparent: m.transparent, opacity: m.opacity, side: m.side, depthWrite: m.depthWrite, depthTest: m.depthTest, blending: m.blending, alphaTest: m.alphaTest, vertexColors: m.vertexColors, toneMapped: m.toneMapped });+ const part = shaderPart(sm);+ (part.props.glsl as { lit?: boolean }).lit = true;+ // a lit surface's colour is scene light, tone-mapped by Bevy as raea's standard material's is+ part.props.output = "linear";+ if (m.fog === false) part.props.fog = false;+ return part;+}diff --git a/sdk/r3f/src/input/scene.ts b/sdk/r3f/src/input/scene.tsindex 435d080e..36d4d15f 100644--- a/sdk/r3f/src/input/scene.ts+++ b/sdk/r3f/src/input/scene.ts@@ -14,6 +14,7 @@ import { clipArrays, clipOf, type Clip } from "./clip";import { cameraOf, fogOf, lightsOf, skyOf, toneOf } from "./lights";import { materialOf, type Part, type Props } from "./material";import { isShader, ownAttributes, shaderPart } from "./shader";+import { drawsPatched } from "./patched";import { composerEffects, postParts } from "./post";import { classicOf } from "./tsl";import { dispatchesOf } from "./tsl-compute";@@ -62,8 +63,9 @@ function flipped(m: THREE.Material | THREE.Material[]): boolean {// a node material's graph reads its uvs as three gives them, and flips where it samples a flipped picture (tsl.ts)const one = Array.isArray(m) ? m[0] : m;if ((one as { isNodeMaterial?: boolean } | undefined)?.isNodeMaterial && !classicOf(one)) return false;- // a ShaderMaterial reads its uvs as three gives them; the engine flips where it samples a flipped picture- if (one && isShader(one)) return false;+ // a ShaderMaterial (or a patched program) reads its uvs as three gives them; the engine flips where it samples a+ // flipped picture+ if (one && (isShader(one) || drawsPatched(one))) return false;const map = ((Array.isArray(m) ? m[0] : m) as THREE.MeshBasicMaterial | undefined)?.map;return map ? flipsY(map) : true;}diff --git a/sdk/r3f/test/patched.test.ts b/sdk/r3f/test/patched.test.tsnew file mode 100644index 00000000..301c1a3e--- /dev/null+++ b/sdk/r3f/test/patched.test.ts@@ -0,0 +1,88 @@+// A lit material patched by onBeforeCompile as three's own program with the patch applied (src/input/patched.ts,+// docs/r3f.feature R3F24): patched once as three patches it, its uniforms the material's each frame, its fragment cut+// where three's lights begin and writing the surface raea's engine lights.+import { describe, expect, spyOn, test } from "bun:test";+import * as THREE from "three";+import { materialOf } from "../src/input/material";++/** drei's MeshWobbleMaterial's patch: the vertex turned about y by a uniform the material keeps */+class Wobble extends THREE.MeshStandardMaterial {+ time = { value: 0 };+ compiled = 0;+ override onBeforeCompile(shader: THREE.WebGLProgramParametersWithUniforms) {+ this.compiled++;+ shader.uniforms.time = this.time;+ shader.vertexShader = `uniform float time;\n${shader.vertexShader}`.replace("#include <begin_vertex>", "float theta = sin( time + position.y ) / 2.0;\nvec3 transformed = vec3( position ) * mat3( cos( theta ), 0, sin( theta ), 0, 1, 0, -sin( theta ), 0, cos( theta ) );");+ }+}++const props = (m: THREE.Material) => materialOf(m, false).props as Record<string, any>;++describe("a material patched by onBeforeCompile", () => {+ test("is its patched program, its surface lit by raea's engine", () => {+ const m = new Wobble({ color: "#ff8000", roughness: 0.3, metalness: 0.2 });+ const part = materialOf(m, false);+ expect(part.type).toBe("ThreeShaderMaterial");+ const p = part.props as Record<string, any>;+ expect(p.glsl.lit).toBe(true);+ expect(p.output).toBe("linear");+ expect(p.glsl.vertex).toContain("float theta = sin( time + position.y ) / 2.0;");+ expect(p.glsl.vertex).toContain("#define STANDARD");+ // cut at three's lights: the surface written, none of three's lighting left+ expect(p.glsl.fragment).toContain("layout(location = 3) out highp vec4 raeaWorld;");+ expect(p.glsl.fragment).toContain("raeaNormal = vec4( normal, roughnessFactor );");+ expect(p.glsl.fragment).not.toContain("RE_Direct");+ expect(p.glsl.fragment).not.toContain("directionalLights");+ expect(p.uniforms.roughness).toBeCloseTo(0.3);+ expect(p.uniforms.metalness).toBeCloseTo(0.2);+ expect(p.uniforms.diffuse).toEqual(new THREE.Color("#ff8000").toArray());+ // only what the program declares: none of three's lights or environment+ expect(p.uniforms.ambientLightColor).toBeUndefined();+ expect(Object.keys(p.textures)).toEqual([]);+ });++ test("is patched once, as three compiles it; its uniforms are read each frame", () => {+ const m = new Wobble();+ expect(props(m).uniforms.time).toBe(0);+ m.time.value = 2.5;+ m.roughness = 0.75;+ const p = props(m);+ expect(p.uniforms.time).toBe(2.5);+ expect(p.uniforms.roughness).toBe(0.75);+ expect(m.compiled).toBe(1);+ m.needsUpdate = true;+ props(m);+ expect(m.compiled).toBe(2);+ });++ test("takes its maps as three's program does, read with v as given", () => {+ const pic = new THREE.DataTexture(new Uint8Array([255, 0, 0, 255]), 1, 1);+ pic.needsUpdate = true;+ pic.offset.set(0.5, 0);+ const m = new Wobble({ map: pic, side: THREE.DoubleSide });+ const p = props(m);+ expect(p.glsl.fragment).toContain("#define USE_MAP");+ expect(p.glsl.fragment).toContain("#define MAP_UV uv");+ expect(p.glsl.fragment).toContain("#define DOUBLE_SIDED");+ expect(Object.keys(p.textures)).toEqual(["map"]);+ expect(p.uniforms.mapTransform.slice(6, 8)).toEqual([0.5, 0]);+ });++ test("a patch past three's lights is named once and left out", () => {+ const warn = spyOn(console, "warn").mockImplementation(() => {});+ const m = new THREE.MeshPhysicalMaterial();+ m.onBeforeCompile = (s) => {+ s.fragmentShader = s.fragmentShader.replace("#include <dithering_fragment>", "gl_FragColor.rgb = vec3( 1.0 );");+ };+ const p = props(m);+ props(m);+ expect(p.glsl.vertex).toContain("#define PHYSICAL");+ expect(p.glsl.fragment).not.toContain("gl_FragColor.rgb = vec3( 1.0 );");+ expect(warn.mock.calls.filter((c) => String(c[0]).includes("past three's lighting")).length).toBe(1);+ warn.mockRestore();+ });++ test("an unpatched standard material stays raea's own", () => {+ expect(materialOf(new THREE.MeshStandardMaterial(), false).type).toBe("MeshStandardMaterial");+ });+});