From 6b08e39c45b70bb37ac6c03d0ed2c5a44f430957 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 16:19:46 -0800 Subject: [PATCH] fix(engine): wire Diffuse.Color.Alpha and Specular.RefractiveIndex in Scene3D and add mesh/uniform byte caps --- crates/engine/src/scene3d/collect.rs | 55 ++++++- crates/engine/src/scene3d/mod.rs | 236 ++++++++++++++++++++++++++- crates/engine/src/scene3d/shader.rs | 35 +++- 3 files changed, 307 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/scene3d/collect.rs b/crates/engine/src/scene3d/collect.rs index a599210a4dc43aa9f56bacce7f2bc301d25559e6..a5c737cef244411e90e341928d8b931e5129dabd 100644 --- a/crates/engine/src/scene3d/collect.rs +++ b/crates/engine/src/scene3d/collect.rs @@ -735,6 +735,7 @@ fn cube_subdivisions(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> fn apply_mtl_std(mat: &mut ResolvedMaterial, comp: &Comp, node: &Node, prefix: &str, time: f64, expr: &ExprEngine) { let f = |k: &str, d: f64| comp.eval_number(node, &format!("{prefix}MtlStdInputs.{k}"), time, d, expr) as f32; mat.diffuse_col = [f("Diffuse.Color.Red", 1.0), f("Diffuse.Color.Green", 1.0), f("Diffuse.Color.Blue", 1.0), f("Diffuse.Opacity", 1.0)]; + mat.fx.diffuse_color_alpha = f("Diffuse.Color.Alpha", 1.0).clamp(0.0, 1.0); mat.specular_col = [f("Specular.Color.Red", 1.0), f("Specular.Color.Green", 1.0), f("Specular.Color.Blue", 1.0)]; mat.specular_intensity = f("Specular.Intensity", 1.0).clamp(0.0, 4.0); mat.specular_exponent = f("Specular.Exponent", 50.0).max(1.0); @@ -903,31 +904,49 @@ fn resolve_material_inner( comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32, comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32, ]; + let col_alpha = comp.eval_number(n, "Diffuse.Color.Alpha", time, 1.0, expr).clamp(0.0, 1.0) as f32; let spec_col = [ comp.eval_number(n, "Specular.Color.Red", time, 1.0, expr) as f32, comp.eval_number(n, "Specular.Color.Green", time, 1.0, expr) as f32, comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32, ]; let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32; - let (spec_exp, spec_model) = match n.kind.as_str() { + let (spec_exp, spec_model, refractive_index, do_fresnel) = match n.kind.as_str() { "MtlCookTorrance" => ( comp.eval_number(n, "Specular.Roughness", time, 0.6, expr).clamp(0.05, 1.0) as f32, SpecModel::CookTorrance, + comp.eval_number(n, "Specular.RefractiveIndex", time, 2.0, expr).max(1.0) as f32, + comp.eval_number(n, "Specular.DoFresnel", time, 1.0, expr) > 0.5, ), - "MtlPhong" => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Phong), - _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn), + "MtlPhong" => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Phong, 2.0, true), + _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn, 2.0, true), }; let spec_model = if comp.eval_number(n, "EnablePBRMaterial", time, 0.0, expr) > 0.5 { SpecModel::Pbr } else { spec_model }; let lit = comp.eval_number(n, "ReceivesLighting", time, 1.0, expr) > 0.5; let mut tex_node = diff_mat.tex_node; let mut bump_node = diff_mat.bump_node; - let mut fx = MaterialFx { spec_model, per_light_unlit: !lit, ..diff_mat.fx }; + let mut fx = MaterialFx { + spec_model, + per_light_unlit: !lit, + diffuse_color_alpha: col_alpha, + refractive_index, + do_fresnel, + ..diff_mat.fx + }; if let Some(bm) = bump_mat { bump_node = bm.bump_node.or(bm.tex_node); if tex_node.is_none() { tex_node = bump_node; - fx = MaterialFx { bump_only: true, spec_model, per_light_unlit: !lit, ..bm.fx }; + fx = MaterialFx { + bump_only: true, + spec_model, + per_light_unlit: !lit, + diffuse_color_alpha: col_alpha, + refractive_index, + do_fresnel, + ..bm.fx + }; } fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 }; fx.bump_mode = bm.fx.bump_mode; @@ -1764,4 +1783,30 @@ mod tests { // Target at -Z rotates Merge3D +Z toward -Z (world[10] == -1). assert!((meshes[0].world[10] + 1.0).abs() < 1e-4, "world[10]={}", meshes[0].world[10]); } + + #[test] + fn diffuse_color_alpha_and_cook_torrance_fresnel_inputs_are_collected() { + let src = comp_src( + r#"Blinn = MtlBlinn { Inputs = { ["Diffuse.Color.Alpha"] = Input { Value = 0.35, }, ["Diffuse.Opacity"] = Input { Value = 0.8, }, }, }, + Cook = MtlCookTorrance { Inputs = { ["Diffuse.Color.Alpha"] = Input { Value = 0.5, }, ["Specular.RefractiveIndex"] = Input { Value = 2.75, }, ["Specular.DoFresnel"] = Input { Value = 0, }, }, }, + Std = Shape3D { Inputs = { ["MtlStdInputs.Diffuse.Color.Alpha"] = Input { Value = 0.25, }, ["MtlStdInputs.Diffuse.Opacity"] = Input { Value = 0.6, }, }, }, + Sb = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, }, + Sc = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Cook", Source = "MaterialOutput", }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Sb", Source = "Output", }, SceneInput2 = Input { SourceOp = "Sc", Source = "Output", }, SceneInput3 = Input { SourceOp = "Std", Source = "Output", }, }, },"#, + ); + let (_, meshes, _) = collect(&src, "M"); + assert_eq!(meshes.len(), 3); + let b_fx = meshes[0].shape.split_fx().1; + assert!((b_fx.diffuse_color_alpha - 0.35).abs() < 1e-5); + assert!((meshes[0].diffuse_col[3] - 0.8).abs() < 1e-5); + + let c_fx = meshes[1].shape.split_fx().1; + assert!((c_fx.diffuse_color_alpha - 0.5).abs() < 1e-5); + assert!((c_fx.refractive_index - 2.75).abs() < 1e-5); + assert!(!c_fx.do_fresnel); + + let s_fx = meshes[2].shape.split_fx().1; + assert!((s_fx.diffuse_color_alpha - 0.25).abs() < 1e-5); + assert!((meshes[2].diffuse_col[3] - 0.6).abs() < 1e-5); + } } diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs index 8441efb9541afd79562212ec79689943b1059a6e..e4b4746d56469b0d227750e27ca62bac2ed00889 100644 --- a/crates/engine/src/scene3d/mod.rs +++ b/crates/engine/src/scene3d/mod.rs @@ -58,6 +58,7 @@ pub struct Scene3DRenderer { } const UNIFORM_CACHE_CAP: usize = 64; +pub(crate) const MAX_CACHED_UNIFORM_BYTES: u64 = 16 * 1024 * 1024; fn cached_uniform_buffer( cache: &Mutex>, @@ -111,6 +112,8 @@ const FACE_BYTES: usize = 80; /// Most meshes kept resident on the GPU across frames. pub(crate) const MAX_CACHED_MESH_BUFFERS: usize = 128; +/// Maximum GPU VRAM kept resident in `Scene3DRenderer::meshes`. +pub(crate) const MAX_CACHED_MESH_BYTES: u64 = 128 * 1024 * 1024; /// Most main-pass depth targets pooled across distinct `Renderer3D` sizes. const DEPTH_CACHE_CAP: usize = 8; @@ -134,16 +137,23 @@ struct GpuMesh { ibuf_bytes: u64, } -/// Bounded map evicting the least recently used entry. +/// Bounded map evicting the least recently used entry by count and optional byte budget. struct Lru { cap: usize, + max_bytes: u64, + total_bytes: u64, + size_fn: fn(&V) -> u64, tick: u64, entries: HashMap, } impl Lru { fn new(cap: usize) -> Self { - Self { cap, tick: 0, entries: HashMap::new() } + Self::with_byte_cap(cap, u64::MAX, |_| 0) + } + + fn with_byte_cap(cap: usize, max_bytes: u64, size_fn: fn(&V) -> u64) -> Self { + Self { cap, max_bytes, total_bytes: 0, size_fn, tick: 0, entries: HashMap::new() } } fn get(&mut self, key: K) -> Option { @@ -162,18 +172,30 @@ impl Lru { *used = self.tick; return v.clone(); } - if self.entries.len() >= self.cap { - if let Some(oldest) = self.entries.iter().min_by_key(|(_, (used, _))| *used).map(|(k, _)| *k) { - self.entries.remove(&oldest); - } - } let v = make(); + let new_bytes = (self.size_fn)(&v); + if self.cap == 0 || new_bytes > self.max_bytes { + return v; + } + while !self.entries.is_empty() + && (self.entries.len() >= self.cap + || self.total_bytes.saturating_add(new_bytes) > self.max_bytes) + { + let Some(oldest) = self.entries.iter().min_by_key(|(_, (used, _))| *used).map(|(k, _)| *k) else { + break; + }; + if let Some((_, evicted)) = self.entries.remove(&oldest) { + self.total_bytes = self.total_bytes.saturating_sub((self.size_fn)(&evicted)); + } + } + self.total_bytes = self.total_bytes.saturating_add(new_bytes); self.entries.insert(key, (self.tick, v.clone())); v } fn clear(&mut self) { self.entries.clear(); + self.total_bytes = 0; self.tick = 0; } } @@ -283,6 +305,12 @@ pub struct MaterialFx { pub cull_front: bool, /// Unlit surface that Fusion draws once per light, so it brightens with the light count. pub per_light_unlit: bool, + /// `Diffuse.Color.Alpha`: modulates output alpha independently of `Diffuse.Opacity`. + pub diffuse_color_alpha: f32, + /// `MtlCookTorrance` `Specular.RefractiveIndex` (used when `do_fresnel` is true). + pub refractive_index: f32, + /// `MtlCookTorrance` `Specular.DoFresnel` toggle. + pub do_fresnel: bool, } impl Default for MaterialFx { @@ -302,6 +330,9 @@ impl Default for MaterialFx { cull_back: false, cull_front: false, per_light_unlit: false, + diffuse_color_alpha: 1.0, + refractive_index: 2.0, + do_fresnel: true, } } } @@ -323,6 +354,9 @@ impl MaterialFx { self.cull_back.hash(h); self.cull_front.hash(h); self.per_light_unlit.hash(h); + self.diffuse_color_alpha.to_bits().hash(h); + self.refractive_index.to_bits().hash(h); + self.do_fresnel.hash(h); } } @@ -812,7 +846,11 @@ impl Scene3DRenderer { bgl, pipelines, sampler, - meshes: Mutex::new(Lru::new(MAX_CACHED_MESH_BUFFERS)), + meshes: Mutex::new(Lru::with_byte_cap( + MAX_CACHED_MESH_BUFFERS, + MAX_CACHED_MESH_BYTES, + |gm| gm.as_ref().map_or(0, |m| m.vbuf_bytes + m.ibuf_bytes), + )), text3d_mesh_cache: Mutex::new(Lru::new(MAX_CACHED_MESH_BUFFERS)), shadow_pipeline, shadow_caster_bgl, @@ -821,7 +859,11 @@ impl Scene3DRenderer { shadow_dummy_ubuf, shadow_targets: Mutex::new(None), depth_targets: Mutex::new(Lru::new(DEPTH_CACHE_CAP)), - uniform_cache: Mutex::new(Lru::new(UNIFORM_CACHE_CAP)), + uniform_cache: Mutex::new(Lru::with_byte_cap( + UNIFORM_CACHE_CAP, + MAX_CACHED_UNIFORM_BYTES, + |b| b.size(), + )), } } @@ -887,6 +929,11 @@ impl Scene3DRenderer { .sum() } + /// Total GPU VRAM in bytes currently occupied by cached uniform buffers. + pub fn uniform_vram_bytes(&self) -> u64 { + self.uniform_cache.lock().unwrap().total_bytes + } + #[cfg(test)] pub(crate) fn gpu_mesh_count(&self) -> usize { self.meshes.lock().unwrap().entries.len() @@ -1182,6 +1229,12 @@ impl Scene3DRenderer { bump_off_wrap: [fx.bump_uv.t[0], fx.bump_uv.t[1], fx.bump_wrap as f32, if bump_src.is_some() { 1.0 } else { 0.0 }], bump_dod, bump_params: [fx.bump_clamp_z, fx.bump_channel as f32, 0.0, 0.0], + mtl_params: [ + fx.diffuse_color_alpha, + fx.refractive_index, + if fx.do_fresnel { 1.0 } else { 0.0 }, + 0.0, + ], point_pos, point_col, spot_pos, @@ -1929,4 +1982,169 @@ mod tests { assert_eq!(c[3], 255, "transparent front face must reveal opaque back face inside cube: {c:?}"); assert!((c[0] as i32 - 64).abs() <= 2, "back face should show 0.25 ambient gray: {c:?}"); } + + #[test] + fn diffuse_color_alpha_modulates_alpha_without_scaling_rgb() { + let render_mat = |extra: &str| -> Option<[u8; 4]> { + let scene = format!( + r#"Mtl = MtlBlinn {{ Inputs = {{ ["Diffuse.Color.Red"] = Input {{ Value = 0.8, }}, ["Diffuse.Color.Green"] = Input {{ Value = 0.4, }}, ["Diffuse.Color.Blue"] = Input {{ Value = 0.2, }}, ["Specular.Intensity"] = Input {{ Value = 0, }}, {extra} }}, }}, + P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 4, }}, MaterialInput = Input {{ SourceOp = "Mtl", Source = "MaterialOutput", }}, }}, }}, + L = LightDirectional {{ }}, + M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# + ); + render(true, &scene).map(|px| center(&px)) + }; + let Some(ca) = render_mat(r#"["Diffuse.Color.Alpha"] = Input { Value = 0.5, },"#) else { return }; + let Some(op) = render_mat(r#"["Diffuse.Opacity"] = Input { Value = 0.5, },"#) else { return }; + assert!((ca[0] as i32 - 204).abs() <= 2 && (ca[1] as i32 - 102).abs() <= 2 && (ca[2] as i32 - 51).abs() <= 2, "Diffuse.Color.Alpha must not attenuate RGB: {ca:?}"); + assert!((ca[3] as i32 - 128).abs() <= 2, "Diffuse.Color.Alpha must set output alpha: {ca:?}"); + assert!((op[0] as i32 - 102).abs() <= 2 && (op[1] as i32 - 51).abs() <= 2 && (op[2] as i32 - 25).abs() <= 2, "Diffuse.Opacity scales premultiplied RGB: {op:?}"); + assert!((op[3] as i32 - 128).abs() <= 2, "Diffuse.Opacity sets output alpha: {op:?}"); + } + + #[test] + fn cook_torrance_refractive_index_drives_fresnel_specular() { + let render_ct = |ri: f32, do_fresnel: u8| -> Option { + let scene = format!( + r#"Mtl = MtlCookTorrance {{ Inputs = {{ ["Diffuse.Color.Red"] = Input {{ Value = 0, }}, ["Diffuse.Color.Green"] = Input {{ Value = 0, }}, ["Diffuse.Color.Blue"] = Input {{ Value = 0, }}, ["Specular.Roughness"] = Input {{ Value = 0.6, }}, ["Specular.RefractiveIndex"] = Input {{ Value = {ri}, }}, ["Specular.DoFresnel"] = Input {{ Value = {do_fresnel}, }}, }}, }}, + P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 4, }}, MaterialInput = Input {{ SourceOp = "Mtl", Source = "MaterialOutput", }}, }}, }}, + L = LightDirectional {{ }}, + M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# + ); + render(true, &scene).map(|px| center(&px)[0]) + }; + let (Some(n1), Some(n2), Some(n3), Some(no_f)) = ( + render_ct(1.0, 1), + render_ct(2.0, 1), + render_ct(2.9, 1), + render_ct(2.0, 0), + ) else { + return; + }; + assert_eq!(n1, 0, "RI=1.0 has zero Fresnel reflectance"); + assert!(n2 > n1 && n3 > n2, "higher RI must strengthen specular: n1={n1} n2={n2} n3={n3}"); + assert!(no_f > n3, "DoFresnel=0 disables Fresnel attenuation: no_f={no_f} vs n3={n3}"); + } + + #[test] + fn unlit_premultiplied_emissive_texture_preserves_rgb() { + let scene = r#"EmissiveBg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, TopLeftRed = Input { Value = 0.8, }, TopLeftGreen = Input { Value = 0.4, }, TopLeftBlue = Input { Value = 0.2, }, TopLeftAlpha = Input { Value = 0.5, }, }, }, + EmissiveTex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "EmissiveBg", Source = "Output", }, }, }, + Card = ImagePlane3D { Inputs = { ["Transform3DOp.Scale.X"] = Input { Value = 4, }, MaterialInput = Input { SourceOp = "EmissiveTex", Source = "MaterialOutput", }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Card", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#; + let Some(px) = render(true, scene) else { return }; + let c = center(&px); + assert!((c[0] as i32 - 204).abs() <= 2 && (c[1] as i32 - 102).abs() <= 2 && (c[2] as i32 - 51).abs() <= 2, "premultiplied emissive RGB must not be attenuated by alpha: {c:?}"); + assert!((c[3] as i32 - 128).abs() <= 2, "alpha must remain 0.5: {c:?}"); + } + + #[test] + fn lru_byte_cap_evicts_least_recently_used_entries() { + let mut lru: Lru = Lru::with_byte_cap(16, 100, |v| v.1); + lru.get_or_insert_with(1, || (1, 40)); + lru.get_or_insert_with(2, || (2, 40)); + assert_eq!(lru.total_bytes, 80); + // Touch key 1 so key 2 becomes LRU before inserting key 3 (80 + 40 > 100). + assert_eq!(lru.get(1), Some((1, 40))); + lru.get_or_insert_with(3, || (3, 40)); + assert_eq!(lru.total_bytes, 80); + assert_eq!(lru.get(2), None, "LRU key 2 must be evicted to satisfy byte cap"); + assert_eq!(lru.get(1), Some((1, 40))); + assert_eq!(lru.get(3), Some((3, 40))); + // Entries larger than max_bytes are returned without busting the cache or exceeding max_bytes. + let oversized = lru.get_or_insert_with(4, || (4, 150)); + assert_eq!(oversized, (4, 150)); + assert_eq!(lru.total_bytes, 80); + assert_eq!(lru.entries.len(), 2); + } + + #[test] + fn mesh_and_uniform_byte_caps_evict_lru_and_track_uniform_vram_bytes() { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; + let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; + let renderer = Scene3DRenderer::new(&device); + let make_tex = |w, h| { + CachedTexture::from_texture( + device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }), + [w, h], + 0, + ) + }; + let (dst, dummy) = (make_tex(16, 16), make_tex(8, 8)); + let make_mesh = |n_tris: usize, z: f32| -> DrawMesh { + let mut verts = Vec::with_capacity(n_tris * 3); + for i in 0..n_tris { + let off = i as f32 * 0.001 + z; + verts.push(Vertex3D { pos: [-0.5, -0.5, off], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }); + verts.push(Vertex3D { pos: [0.5, -0.5, off], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }); + verts.push(Vertex3D { pos: [0.0, 0.5, off], normal: [0.0, 0.0, 1.0], uv: [0.5, 0.0] }); + } + DrawMesh { + world: mat4_identity(), + shape: ShapeKind::CustomMesh(Arc::new(verts)), + custom_mesh_key: None, + tex: None, + bump_tex: None, + diffuse_col: [1.0; 4], + specular_col: [1.0; 3], + specular_intensity: 0.0, + specular_exponent: 50.0, + affected_by_lights: false, + casts_shadow: false, + receives_shadows: false, + flip_normals: false, + displace: None, + } + }; + let render_one = |m: DrawMesh| { + let mut enc = device.create_command_encoder(&Default::default()); + renderer.render_meshes( + &device, + &queue, + &mut enc, + &dst, + &dummy, + mat4_identity(), + mat4_identity(), + [0.0, 0.0, 5.0], + 100.0, + SceneLights::default(), + false, + false, + &[m], + ); + queue.submit(Some(enc.finish())); + }; + + // Render one mesh and verify default caps and uniform_vram_bytes tracking. + render_one(make_mesh(20, 0.0)); + let single_mesh_bytes = renderer.mesh_vram_bytes(); + let single_uni_bytes = renderer.uniform_vram_bytes(); + assert!(single_mesh_bytes > 0 && single_mesh_bytes <= MAX_CACHED_MESH_BYTES); + assert!(single_uni_bytes > 0 && single_uni_bytes <= MAX_CACHED_UNIFORM_BYTES); + + // Enforce tight byte caps (< 2 entries) and confirm LRU eviction caps both pools. + renderer.meshes.lock().unwrap().max_bytes = single_mesh_bytes + single_mesh_bytes / 2; + renderer.uniform_cache.lock().unwrap().max_bytes = single_uni_bytes + single_uni_bytes / 2; + + render_one(make_mesh(20, 1.0)); + assert_eq!(renderer.gpu_mesh_count(), 1, "mesh byte cap must evict LRU mesh"); + assert_eq!(renderer.mesh_vram_bytes(), single_mesh_bytes); + assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 1, "uniform byte cap must evict LRU uniform"); + assert_eq!(renderer.uniform_vram_bytes(), single_uni_bytes); + + renderer.clear_shadow_targets(); + assert_eq!(renderer.uniform_vram_bytes(), 0); + assert_eq!(renderer.mesh_vram_bytes(), 0); + } } diff --git a/crates/engine/src/scene3d/shader.rs b/crates/engine/src/scene3d/shader.rs index f84bc4ff6ba248f0e799c803c7aab7208409e3ec..9eb4bc1672eb402bc0bd29437c86efaac307b627 100644 --- a/crates/engine/src/scene3d/shader.rs +++ b/crates/engine/src/scene3d/shader.rs @@ -56,6 +56,8 @@ pub(super) struct MeshUniform { pub(super) bump_dod: [f32; 4], /// `[bump_clamp_z, bump_channel, bump_filter_size, 0]` pub(super) bump_params: [f32; 4], + /// `[diffuse_color_alpha, refractive_index, do_fresnel, 0]` + pub(super) mtl_params: [f32; 4], /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)` pub(super) point_pos: [[f32; 4]; MAX_LIGHTS], /// Point light colors * intensity `(r, g, b, 0)` @@ -148,6 +150,7 @@ struct MeshUniform { bump_off_wrap: vec4, bump_dod: vec4, bump_params: vec4, + mtl_params: vec4, point_pos: array, MAX_LIGHTS>, point_col: array, MAX_LIGHTS>, spot_pos: array, MAX_LIGHTS>, @@ -288,10 +291,28 @@ fn eval_light_contrib( if (model == 1) { lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess); } else if (model == 2) { - // Beckmann distribution; shininess carries roughness. + // Cook-Torrance: Beckmann D, Torrance-Sparrow G, exact unpolarized Fresnel F. + // `eval_light_contrib` omits the outer N·L factor on `lobe`, so `(F*D*G)/(4*N·L*N·V) * N·L` + // simplifies to `(F*D*G)/(4*N·V)`. let nh = max(dot(n, h), 1e-3); + let nv = max(dot(n, v), 1e-3); + let vh = max(dot(v, h), 1e-3); let m2 = max(shininess * shininess, 1e-3); - lobe = 0.03 * exp(-(1.0 - nh * nh) / (nh * nh * m2)) / (3.14159265 * m2 * nh * nh * nh * nh); + let nh2 = nh * nh; + let d_term = exp(-(1.0 - nh2) / (nh2 * m2)) / (3.14159265 * m2 * nh2 * nh2); + let g_term = min(1.0, min(2.0 * nh * nv / vh, 2.0 * nh * ndotl / vh)); + var fresnel = 1.0; + if (u.mtl_params.z > 0.5) { + let eta = max(u.mtl_params.y, 1.0); + let c = vh; + let g = sqrt(max(eta * eta + c * c - 1.0, 0.0)); + let gmc = g - c; + let gpc = max(g + c, 1e-5); + let r_s = gmc / gpc; + let r_p = (c * gpc - 1.0) / max(c * gmc + 1.0, 1e-5); + fresnel = 0.5 * r_s * r_s * (1.0 + r_p * r_p); + } + lobe = (fresnel * d_term * g_term) / (4.0 * nv); } else { lobe = pow(max(dot(n, h), 0.0), shininess); } @@ -416,7 +437,11 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { } col = select(tex_col, vec4(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; } - if (col.a <= 0.002) { + // `rgb_alpha` is `tex_col.a * Diffuse.Opacity`; `Diffuse.Color.Alpha` (`u.mtl_params.x`) + // modulates output alpha without attenuating diffuse/specular RGB. + let rgb_alpha = col.a; + let out_alpha = rgb_alpha * u.mtl_params.x; + if (out_alpha <= 0.002) { discard; } @@ -486,9 +511,9 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { } } - col = vec4(clamp(lit, vec3(0.0), vec3(1.0)) * col.a, col.a); + col = vec4(clamp(lit * rgb_alpha, vec3(0.0), vec3(1.0)), out_alpha); } else { - col = vec4(min(albedo * u.uv_off_wrap.w, vec3(1.0)) * col.a, col.a); + col = vec4(clamp(albedo * u.uv_off_wrap.w * rgb_alpha, vec3(0.0), vec3(1.0)), out_alpha); } return col; } -- 2.54.1