The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Material functions on a glTF file's own materials, by name (GLTFModel.functions), and wetLayer: the rain on any material's shading
Evan (Yifeng) Wang1eea744e5b7e
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.tsindex 3ad24e4..79ff913 100644--- a/packages/scene/src/core.ts+++ b/packages/scene/src/core.ts@@ -1771,11 +1771,18 @@ export class GLTFModel extends Object3D {uri: string;/** Only these glTF nodes (by name, with their transforms in the file); all when null. */nodes: string[] | null;+ /**+ * Material functions on the file's own materials, by material name prefix (the first that matches): the function+ * gets the glTF material's shading (`base`, its maps sampled) and changes it, e.g. `WetLayer` on a city's ground.+ * Set at build: changing them rebuilds the scene.+ */+ functions: Record<string, ShaderBinding> | null;declare private _animation: AnimationPose | null;- constructor(uri: string, opts: { nodes?: string[]; animation?: AnimationPose } = {}) {+ constructor(uri: string, opts: { nodes?: string[]; animation?: AnimationPose; functions?: Record<string, ShaderBinding> } = {}) {super();this.uri = uri;this.nodes = opts.nodes ?? null;+ this.functions = opts.functions ?? null;this.animation = opts.animation ?? null;}get animation(): AnimationPose | null {diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.tsindex 5c5d676..4105c34 100644--- a/packages/scene/src/engine.ts+++ b/packages/scene/src/engine.ts@@ -156,7 +156,7 @@ type ObjectKindDesc =| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "group" }/** `materials`: one per geometry group (three.js's material array; `material` is the first). */| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "mesh"; geometry: number; material: number; materials?: number[]; dynamicGeometry?: boolean }- | { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "model"; uri: string; nodes?: string[]; animation?: AnimationDesc }+ | { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "model"; uri: string; nodes?: string[]; animation?: AnimationDesc; functions?: { prefix: string; shader: NonNullable<MaterialDesc["shader"]> }[] }| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "light"; light: LightDesc }| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "camera"; camera: CameraDesc }| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "particles"; count: number; emitter: { id: string; params: number[] }; material: number; emitterArea?: number }@@ -918,7 +918,7 @@ export class SceneBinding {if (o instanceof VolumeMesh) return `volume:${o.shape}:${JSON.stringify(this.volumeBinding(o.volume))}:${o.majorant}:${o.anisotropy}:${o.homogeneous}:${o.grid ? this.gridId(o.grid) : ""}`;if (o instanceof GpuParticles) return `gpuParticles:${o.capacity}:${JSON.stringify(this.particleProgram(o.program))}:${this.materialId(o.material)}:${o.castShadow}:${o.emitterArea}:${o.rate}:${JSON.stringify(o.collide)}`;if (o instanceof Particles) return `particles:${o.count}:${JSON.stringify(this.particleEmitter(o.emitter))}:${this.materialId(o.material)}:${o.castShadow}:${o.emitterArea}`;- if (o instanceof GLTFModel) return `model:${o.uri}:${o.nodes?.join(",") ?? ""}:${o.castShadow}`;+ if (o instanceof GLTFModel) return `model:${o.uri}:${o.nodes?.join(",") ?? ""}:${o.castShadow}:${o.functions ? JSON.stringify(this.modelFunctions(o)) : ""}`;if (o instanceof Light) {const d = lightDesc(o);return `light:${d.type}:${d.castShadow}:${d.type === "rect" ? d.visible !== false : ""}`;@@ -944,7 +944,7 @@ export class SceneBinding {if (o instanceof Particles) return { ...base, kind: "particles", count: o.count, emitter: this.particleEmitter(o.emitter), material: this.materialId(o.material), ...(o.emitterArea > 0 ? { emitterArea: o.emitterArea } : {}) };if (o instanceof GLTFModel) {const animation = animationDesc(o);- return { ...base, kind: "model", uri: o.uri, ...(o.nodes ? { nodes: [...o.nodes] } : {}), ...(animation ? { animation } : {}) };+ return { ...base, kind: "model", uri: o.uri, ...(o.nodes ? { nodes: [...o.nodes] } : {}), ...(animation ? { animation } : {}), ...(o.functions ? { functions: this.modelFunctions(o) } : {}) };}if (o instanceof Light) return { ...base, kind: "light", light: lightDesc(o) };if (o instanceof PerspectiveCamera) return { ...base, kind: "camera", camera: this.cameraDesc(o) };@@ -1285,6 +1285,11 @@ export class SceneBinding {return { id: f.name, params };}+ /** A model's material functions by material name prefix (`GLTFModel.functions`). */+ private modelFunctions(o: GLTFModel): { prefix: string; shader: NonNullable<MaterialDesc["shader"]> }[] {+ return Object.entries(o.functions ?? {}).map(([prefix, b]) => ({ prefix, shader: this.shaderBinding(b)! }));+ }+private shaderBinding(b: ShaderBinding): MaterialDesc["shader"] {const l = this.layoutOf(b.fn);const params = new Array<number>(32).fill(0);diff --git a/packages/scene/src/materials.ts b/packages/scene/src/materials.tsindex 610c9af..65718b0 100644--- a/packages/scene/src/materials.ts+++ b/packages/scene/src/materials.ts@@ -1006,3 +1006,65 @@ export class SurfaceMaterial extends LibraryMaterial<SurfaceParameters> {);}}++// ------------------------------------------------------------------------------------------------ wet layer++const WET_LAYER = new MaterialFunction("std_wet_layer", {+ params: { Wet: 1, PuddleAmount: 1, PuddleScale: 6 },+ helpers: SURFACE_HELPERS,+ code: `+ let p = i.wp;+ let ng = i.ng;+ var col = base.base;+ var rough = base.roughness;+ var metal = base.metallic;+ var spec = base.specular;+ var n = base.normal;+ // SurfaceMaterial's wetness (Lagarde), on the material's own shading.+ let wet = clamp($Wet * i.wetness, 0.0, 1.0);+ if (wet > 0.0) {+ var pud = 0.0;+ if ($PuddleAmount > 0.0 && ng.y > 0.6 && i.near) {+ let hgt = std_fbm(p.xz / $PuddleScale) + 0.35 * (dot(col, vec3<f32>(0.2126, 0.7152, 0.0722)) - 0.1);+ let level = 0.32 + 0.22 * $PuddleAmount * i.wetness;+ pud = 1.0 - smoothstep(level - 0.03, level + 0.03, hgt);+ }+ let damp = max(wet, pud);+ col *= mix(1.0, 0.5, damp * (1.0 - metal));+ rough = mix(rough, min(rough, 0.14), wet);+ n = normalize(mix(n, ng, 0.5 * wet));+ rough = mix(rough, 0.02, pud);+ col = mix(col, col * 0.6, pud);+ metal = mix(metal, 0.0, pud);+ spec = mix(spec, 0.5, pud);+ n = normalize(mix(n, ng, pud));+ if (i.rain > 0.0 && ng.y > 0.6 && i.depth == 0u) {+ let g = std_ripples(p.xz, i.time) * i.rain * (0.015 + 0.1 * pud);+ n = normalize(n - vec3<f32>(g.x, 0.0, g.y));+ }+ }+ o.base = col;+ o.roughness = rough;+ o.metallic = metal;+ o.specular = spec;+ o.normal = n;`,+});++export interface WetLayerParameters {+ /** Scales `scene.wetness` (1). */+ wet?: number;+ /** How much floods at full wetness (1; 0 = no puddles). */+ puddles?: number;+ /** Metres across a puddle field's noise (6). */+ puddleScale?: number;+}++/**+ * The rain on any material: `SurfaceMaterial`'s wetness as a layer on another material's own shading (its maps+ * sampled). With `scene.wetness` the surface darkens and glosses; on up-facing ground puddles fill (mirror-flat), and+ * `scene.rain` rings ripple in them. For a glTF file's materials: `new GLTFModel(uri, { functions: { ground:+ * wetLayer() } })`.+ */+export function wetLayer(p: WetLayerParameters = {}): ShaderBinding {+ return WET_LAYER.with({ Wet: p.wet ?? 1, PuddleAmount: p.puddles ?? 1, PuddleScale: p.puddleScale ?? 6 });+}diff --git a/renderer/src/desc.rs b/renderer/src/desc.rsindex cd3ccfa..7db9f06 100644--- a/renderer/src/desc.rs+++ b/renderer/src/desc.rs@@ -13,8 +13,15 @@ pub struct Shader {pub helpers: String,}+/// A model's material function on its file's materials whose name starts with `prefix` (`GLTFModel.functions`).+#[derive(Deserialize, Debug, Clone, PartialEq)]+pub struct ModelFunction {+ pub prefix: String,+ pub shader: ShaderRef,+}+/// A material's binding to a material function: 32 parameter floats (8 vec4) and up to 8 textures.-#[derive(Deserialize, Debug, Clone)]+#[derive(Deserialize, Debug, Clone, PartialEq)]pub struct ShaderRef {/// Material function name.pub id: String,diff --git a/renderer/src/live.rs b/renderer/src/live.rsindex 6f4e6c7..0ad253a 100644--- a/renderer/src/live.rs+++ b/renderer/src/live.rs@@ -2354,7 +2354,7 @@ impl LiveCore {let mut pose: Option<&crate::desc::Animation> = None;for (id, _) in &pg.members {let Some(o) = world.objects.get(id) else { return Ok(false) };- let crate::world::Kind::Model { uri, nodes, animation: Some(a) } = &o.kind else { return Ok(false) };+ let crate::world::Kind::Model { uri, nodes, animation: Some(a), .. } = &o.kind else { return Ok(false) };if !world.shown(*id) || *uri != pg.uri || *nodes != pg.nodes || pose.is_some_and(|p| p != a) {return Ok(false);}@@ -2864,12 +2864,15 @@ impl LiveCore {(record, gpu, blas, entry)}Kind::Mesh { materials, .. } if materials.len() > 1 => return Err("a mesh with several materials".into()),- Kind::Model { uri, nodes, animation } => {+ Kind::Model { uri, nodes, animation, functions } => {// A static model already in the scene: another instance of its mesh (one not in it brings materials// and textures, which load with a rebuild).if animation.is_some() {return Err("an animated model".into());}+ if !functions.is_empty() {+ return Err("a model with material functions (its materials load with a rebuild)".into());+ }if features & gpu::F_INST == 0 || m.determinant() <= 0.0 || std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "0") {return Err("a model the build would flatten (mirrored, instancing off, or the scene's first instance)".into());}diff --git a/renderer/src/scene.rs b/renderer/src/scene.rsindex 35e984a..f1ecfac 100644--- a/renderer/src/scene.rs+++ b/renderer/src/scene.rs@@ -811,20 +811,27 @@ pub fn build_material(id: u32, m: &desc::Material, textures: &HashMap<u32, worldmt: [-1; 8],};if let Some(sh) = &m.shader {- let f = *shaders.get(sh.id.as_str()).ok_or_else(|| anyhow!("material {id}: unknown material function {}", sh.id))?;- gm.tex1[3] = f + 1;- for (k, v) in sh.params.iter().take(32).enumerate() {- gm.mp[k / 4][k % 4] = *v;- }- for (k, t) in sh.textures.iter().take(8).enumerate() {- if let Some(tid) = t {- gm.mt[k] = tex(*tid, false)?;- }- }+ apply_shader(&mut gm, sh, shaders, tex).with_context(|| format!("material {id}"))?;}Ok(gm)}+/// A material function's binding on a GPU material: the function, its 32 parameters and its textures (`tex(texture,+/// sRGB requested)`).+pub fn apply_shader(gm: &mut GpuMaterial, sh: &desc::ShaderRef, shaders: &HashMap<String, i32>, tex: &mut dyn FnMut(u32, bool) -> Result<i32>) -> Result<()> {+ let f = *shaders.get(sh.id.as_str()).ok_or_else(|| anyhow!("unknown material function {}", sh.id))?;+ gm.tex1[3] = f + 1;+ for (k, v) in sh.params.iter().take(32).enumerate() {+ gm.mp[k / 4][k % 4] = *v;+ }+ for (k, t) in sh.textures.iter().take(8).enumerate() {+ if let Some(tid) = t {+ gm.mt[k] = tex(*tid, false)?;+ }+ }+ Ok(())+}+/// Analytic light of a light object with world matrix `m` (rect lights with a visible card are emitter geometry/// instead, see `card_material`). Emission scales with the node's power.pub fn gpu_light(l: &Light, m: Mat4, power: f32) -> Option<GpuLight> {@@ -1030,7 +1037,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seif instancing && std::env::var("THREERT_POSE_SHARE").map_or(true, |v| v != "0") {let mut count: HashMap<PoseKey, usize> = HashMap::new();for id in &order {- let Kind::Model { uri, nodes, animation: Some(a) } = &w.objects[id].kind else { continue };+ let Kind::Model { uri, nodes, animation: Some(a), .. } = &w.objects[id].kind else { continue };if !w.shown(*id) || worlds[id].determinant() <= 0.0 {continue;}@@ -1223,10 +1230,13 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&seretained.dynamic.insert(*id, DynamicModel { first, mats: attrs[first as usize..].iter().map(|a| a.uv[3].to_bits()).collect(), ..Default::default() });}}- Kind::Model { uri, nodes, animation } if shown => {+ Kind::Model { uri, nodes, animation, functions } if shown => {let glb = model_gltf(uri, assets)?;let (doc, _, images) = &glb.gltf;- let key = uri.clone();+ // (A model with material functions has its own copies of the file's materials.)+ let key = if functions.is_empty() { uri.clone() } else { format!("{uri}\u{0}{functions:?}") };+ // (Its meshes too: placements share a mesh only with the same functions.)+ let mesh_key = (key.clone(), nodes.clone());// (material index, instancing class: 0 opaque, 1 cutout, 2 flattened per placement: glass (shadow rays// pass), emissive (emitter sampling), material function)let mut resolve = |gm: Option<gltf::Material>| -> Result<(u32, u32)> {@@ -1234,7 +1244,20 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&selet i = match asset_materials.get(&(key.clone(), idx)) {Some(i) => *i,None => {- let gpu = gltf_material(gm, images, &key, &mut texcache, &model_images)?;+ let name = gm.as_ref().and_then(|g| g.name()).unwrap_or_default().to_string();+ let mut gpu = gltf_material(gm, images, uri, &mut texcache, &model_images)?;+ // The first function whose prefix the material's name starts with, on the glTF shading.+ if let Some(f) = functions.iter().find(|f| name.starts_with(f.prefix.as_str())) {+ let mut tex = |tid: u32, srgb_default: bool| -> Result<i32> {+ let t = w.textures.get(&tid).ok_or_else(|| anyhow!("unknown texture {tid}"))?;+ let (tkey, img) = match decoded.get(&tid) {+ Some(d) => d.clone(),+ None => texture_image(t, assets)?,+ };+ texcache.add((tkey, t.srgb && srgb_default), t.wrap, || Ok(img))+ };+ apply_shader(&mut gpu, &f.shader, &retained.shaders, &mut tex).with_context(|| format!("{uri}: material {name}"))?;+ }let i = materials.len() as u32;materials.push(gpu);asset_materials.insert((key.clone(), idx), i);@@ -1405,7 +1428,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se}}if instancing && !posed && m.determinant() > 0.0 {- let key = (uri.clone(), nodes.clone());+ let key = mesh_key.clone();let mesh = match mesh_of.get(&key) {Some(k) => *k,None => {@@ -1927,7 +1950,7 @@ pub fn dynamic_tris(w: &World, id: u32, d: &DynamicModel, assets: &Path) -> Resu}Some(tris.iter().zip(attrs).map(|(t, a)| (t.map(Vec3::from), a)).collect())}- Kind::Model { uri, nodes, animation } => {+ Kind::Model { uri, nodes, animation, .. } => {let tris = model_gltf(uri, assets)?.triangles(m, nodes.as_deref(), animation.as_ref())?;if tris.len() != d.mats.len() {return Ok(None);diff --git a/renderer/src/script.rs b/renderer/src/script.rsindex ed266d3..7597d2b 100644--- a/renderer/src/script.rs+++ b/renderer/src/script.rs@@ -263,7 +263,7 @@ fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<Rlet materials: Vec<u32> = j["materials"].as_array().map_or(vec![], |a| a.iter().filter_map(|v| v.as_u64().map(|x| x as u32)).collect());Kind::Mesh { geometry: num("geometry").unwrap_or(0), material: num("material").unwrap_or(0), own_blas: j["dynamicGeometry"].as_bool().unwrap_or(false) || (body && materials.len() <= 1), materials }}- "model" => Kind::Model { uri: j["uri"].as_str().unwrap_or_default().to_string(), nodes: serde_json::from_value(j["nodes"].clone()).ok(), animation: serde_json::from_value(j["animation"].clone()).ok() },+ "model" => Kind::Model { uri: j["uri"].as_str().unwrap_or_default().to_string(), nodes: serde_json::from_value(j["nodes"].clone()).ok(), animation: serde_json::from_value(j["animation"].clone()).ok(), functions: serde_json::from_value(j["functions"].clone()).unwrap_or_default() },"light" => Kind::Light(serde_json::from_value(j["light"].clone()).map_err(|e| Exception::throw_type(&ctx, &format!("engine.object light: {e}")))?),"camera" => Kind::Camera(serde_json::from_value(j["camera"].clone()).map_err(|e| Exception::throw_type(&ctx, &format!("engine.object camera: {e}")))?),"volume" => Kind::Volume {diff --git a/renderer/src/world.rs b/renderer/src/world.rsindex 7f9980a..8dfb2b8 100644--- a/renderer/src/world.rs+++ b/renderer/src/world.rs@@ -125,7 +125,8 @@ pub enum Kind {/// `materials`: one per geometry group (three.js's material array; empty: `material` for every triangle).Mesh { geometry: u32, material: u32, own_blas: bool, materials: Vec<u32> },/// glTF asset (path relative to the asset root), optionally only some of its nodes (by name).- Model { uri: String, nodes: Option<Vec<String>>, animation: Option<desc::Animation> },+ /// `functions`: material functions on its materials, by name prefix (`GLTFModel.functions`).+ Model { uri: String, nodes: Option<Vec<String>>, animation: Option<desc::Animation>, functions: Vec<desc::ModelFunction> },Light(desc::Light),Camera(desc::Camera),/// `count` particles: each a quad that the particle function `emitter` (with `params`, 8 vec4) places every frame@@ -1371,7 +1372,7 @@ mod tests {w.set_object(1, "a".into(), None, Kind::Mesh { geometry: 1, material: 1, own_blas: false, materials: vec![] }, true, false).unwrap();w.set_object(2, "cam".into(), None, Kind::Group, false, false).unwrap();for bad in ["../x.glb", "/etc/passwd", "a/../../b", "https://x/y.glb", ""] {- assert!(w.set_object(9, "m".into(), None, Kind::Model { uri: bad.into(), nodes: None, animation: None }, true, false).is_err(), "{bad}");+ assert!(w.set_object(9, "m".into(), None, Kind::Model { uri: bad.into(), nodes: None, animation: None, functions: vec![] }, true, false).is_err(), "{bad}");}w.settings.camera = Some(2);assert!(w.take_changes().structural);diff --git a/tests/render/surface-wet-layer-gltf.ts b/tests/render/surface-wet-layer-gltf.tsnew file mode 100644index 0000000..941857c--- /dev/null+++ b/tests/render/surface-wet-layer-gltf.ts@@ -0,0 +1,29 @@+// A material function on a glTF file's own material (`GLTFModel.functions`, by material name): `wetLayer` on the+// grey quad of tests/render/data/quad.glb (albedo 0.5, roughness 1), puddles off, at full `scene.wetness`. As+// `surface/wet`: the diffuse halves and the roughness drops to 0.14 (Lagarde), under a uniform 1-nit sky wet over+// dry = (0.25 + s_wet) / (0.5 + s_dry), the sky's specular reflection s = 0.012 rough, 0.031 at roughness 0.14+// (`surface/wet`'s 0.531 at albedo 0.8). The other copy of the file, without the function, stays dry.+import { GLTFModel, wetLayer } from "@threert/scene";+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";++export const test: TestMeta = {+ id: "surface/wet-layer-gltf", features: ["material-library", "wetness", "gltf"], reference: "analytic", temporal: false,+ metric: { kind: "ratio", a: [0.65, 0.4, 0.85, 0.6], b: [0.15, 0.4, 0.35, 0.6], expected: 0.549, tolerance: 0.015 },+ requires: ["tests/render/data/quad.glb"],+ note: "wetLayer on a glTF material, by name: wet over dry 0.549; the copy without it stays dry",+};++const URI = "tests/render/data/quad.glb";++export default function () {+ const scene = sceneWithSky(1);+ scene.wetness = 1;+ const quad = (x: number, wet: boolean) => {+ const m = new GLTFModel(URI, wet ? { functions: { gr: wetLayer({ puddles: 0 }) } } : {});+ m.rotation.x = -Math.PI / 2;+ m.scale.setScalar(1.8);+ m.position.set(x, 0, 0);+ return m;+ };+ return result(scene, camera(scene, [0, 4, 0.001], [0, 0, 0]), [quad(-1, false), quad(1, true)]);+}