authoravatarclover caruso<git@paperclover.net>2026-12-01 16:19:46-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 16:27:14-08:00
log6b08e39c45b70bb37ac6c03d0ed2c5a44f430957
tree9f08f34deb4c92c698f7b40e699e8f6cdf5104fe
parent1d0c6e86ad69ac238e43a212f8ee67bc4ba92d18
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(engine): wire Diffuse.Color.Alpha and Specular.RefractiveIndex in Scene3D and add mesh/uniform byte caps


3 files changed, 306 insertions(+), 18 deletions(-)

crates/engine/src/scene3d/collect.rs+50-5
......@@ -735,6 +735,7 @@ fn cube_subdivisions(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) ->
735735fn apply_mtl_std(mat: &mut ResolvedMaterial, comp: &Comp, node: &Node, prefix: &str, time: f64, expr: &ExprEngine) {
736736 let f = |k: &str, d: f64| comp.eval_number(node, &format!("{prefix}MtlStdInputs.{k}"), time, d, expr) as f32;
737737 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)];
738 mat.fx.diffuse_color_alpha = f("Diffuse.Color.Alpha", 1.0).clamp(0.0, 1.0);
738739 mat.specular_col = [f("Specular.Color.Red", 1.0), f("Specular.Color.Green", 1.0), f("Specular.Color.Blue", 1.0)];
739740 mat.specular_intensity = f("Specular.Intensity", 1.0).clamp(0.0, 4.0);
740741 mat.specular_exponent = f("Specular.Exponent", 50.0).max(1.0);
......@@ -903,31 +904,49 @@ fn resolve_material_inner(
903904 comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32,
904905 comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32,
905906 ];
907 let col_alpha = comp.eval_number(n, "Diffuse.Color.Alpha", time, 1.0, expr).clamp(0.0, 1.0) as f32;
906908 let spec_col = [
907909 comp.eval_number(n, "Specular.Color.Red", time, 1.0, expr) as f32,
908910 comp.eval_number(n, "Specular.Color.Green", time, 1.0, expr) as f32,
909911 comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32,
910912 ];
911913 let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32;
912 let (spec_exp, spec_model) = match n.kind.as_str() {
914 let (spec_exp, spec_model, refractive_index, do_fresnel) = match n.kind.as_str() {
913915 "MtlCookTorrance" => (
914916 comp.eval_number(n, "Specular.Roughness", time, 0.6, expr).clamp(0.05, 1.0) as f32,
915917 SpecModel::CookTorrance,
918 comp.eval_number(n, "Specular.RefractiveIndex", time, 2.0, expr).max(1.0) as f32,
919 comp.eval_number(n, "Specular.DoFresnel", time, 1.0, expr) > 0.5,
916920 ),
917 "MtlPhong" => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Phong),
918 _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn),
921 "MtlPhong" => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Phong, 2.0, true),
922 _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn, 2.0, true),
919923 };
920924
921925 let spec_model = if comp.eval_number(n, "EnablePBRMaterial", time, 0.0, expr) > 0.5 { SpecModel::Pbr } else { spec_model };
922926 let lit = comp.eval_number(n, "ReceivesLighting", time, 1.0, expr) > 0.5;
923927 let mut tex_node = diff_mat.tex_node;
924928 let mut bump_node = diff_mat.bump_node;
925 let mut fx = MaterialFx { spec_model, per_light_unlit: !lit, ..diff_mat.fx };
929 let mut fx = MaterialFx {
930 spec_model,
931 per_light_unlit: !lit,
932 diffuse_color_alpha: col_alpha,
933 refractive_index,
934 do_fresnel,
935 ..diff_mat.fx
936 };
926937 if let Some(bm) = bump_mat {
927938 bump_node = bm.bump_node.or(bm.tex_node);
928939 if tex_node.is_none() {
929940 tex_node = bump_node;
930 fx = MaterialFx { bump_only: true, spec_model, per_light_unlit: !lit, ..bm.fx };
941 fx = MaterialFx {
942 bump_only: true,
943 spec_model,
944 per_light_unlit: !lit,
945 diffuse_color_alpha: col_alpha,
946 refractive_index,
947 do_fresnel,
948 ..bm.fx
949 };
931950 }
932951 fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 };
933952 fx.bump_mode = bm.fx.bump_mode;
......@@ -1764,4 +1783,30 @@ mod tests {
17641783 // Target at -Z rotates Merge3D +Z toward -Z (world[10] == -1).
17651784 assert!((meshes[0].world[10] + 1.0).abs() < 1e-4, "world[10]={}", meshes[0].world[10]);
17661785 }
1786
1787 #[test]
1788 fn diffuse_color_alpha_and_cook_torrance_fresnel_inputs_are_collected() {
1789 let src = comp_src(
1790 r#"Blinn = MtlBlinn { Inputs = { ["Diffuse.Color.Alpha"] = Input { Value = 0.35, }, ["Diffuse.Opacity"] = Input { Value = 0.8, }, }, },
1791 Cook = MtlCookTorrance { Inputs = { ["Diffuse.Color.Alpha"] = Input { Value = 0.5, }, ["Specular.RefractiveIndex"] = Input { Value = 2.75, }, ["Specular.DoFresnel"] = Input { Value = 0, }, }, },
1792 Std = Shape3D { Inputs = { ["MtlStdInputs.Diffuse.Color.Alpha"] = Input { Value = 0.25, }, ["MtlStdInputs.Diffuse.Opacity"] = Input { Value = 0.6, }, }, },
1793 Sb = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, },
1794 Sc = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Cook", Source = "MaterialOutput", }, }, },
1795 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Sb", Source = "Output", }, SceneInput2 = Input { SourceOp = "Sc", Source = "Output", }, SceneInput3 = Input { SourceOp = "Std", Source = "Output", }, }, },"#,
1796 );
1797 let (_, meshes, _) = collect(&src, "M");
1798 assert_eq!(meshes.len(), 3);
1799 let b_fx = meshes[0].shape.split_fx().1;
1800 assert!((b_fx.diffuse_color_alpha - 0.35).abs() < 1e-5);
1801 assert!((meshes[0].diffuse_col[3] - 0.8).abs() < 1e-5);
1802
1803 let c_fx = meshes[1].shape.split_fx().1;
1804 assert!((c_fx.diffuse_color_alpha - 0.5).abs() < 1e-5);
1805 assert!((c_fx.refractive_index - 2.75).abs() < 1e-5);
1806 assert!(!c_fx.do_fresnel);
1807
1808 let s_fx = meshes[2].shape.split_fx().1;
1809 assert!((s_fx.diffuse_color_alpha - 0.25).abs() < 1e-5);
1810 assert!((meshes[2].diffuse_col[3] - 0.6).abs() < 1e-5);
1811 }
17671812}
crates/engine/src/scene3d/mod.rs+226-8
......@@ -58,6 +58,7 @@ pub struct Scene3DRenderer {
5858}
5959
6060const UNIFORM_CACHE_CAP: usize = 64;
61pub(crate) const MAX_CACHED_UNIFORM_BYTES: u64 = 16 * 1024 * 1024;
6162
6263fn cached_uniform_buffer(
6364 cache: &Mutex<Lru<(u64, usize), wgpu::Buffer>>,
......@@ -111,6 +112,8 @@ const FACE_BYTES: usize = 80;
111112
112113/// Most meshes kept resident on the GPU across frames.
113114pub(crate) const MAX_CACHED_MESH_BUFFERS: usize = 128;
115/// Maximum GPU VRAM kept resident in `Scene3DRenderer::meshes`.
116pub(crate) const MAX_CACHED_MESH_BYTES: u64 = 128 * 1024 * 1024;
114117/// Most main-pass depth targets pooled across distinct `Renderer3D` sizes.
115118const DEPTH_CACHE_CAP: usize = 8;
116119
......@@ -134,16 +137,23 @@ struct GpuMesh {
134137 ibuf_bytes: u64,
135138}
136139
137/// Bounded map evicting the least recently used entry.
140/// Bounded map evicting the least recently used entry by count and optional byte budget.
138141struct Lru<K, V> {
139142 cap: usize,
143 max_bytes: u64,
144 total_bytes: u64,
145 size_fn: fn(&V) -> u64,
140146 tick: u64,
141147 entries: HashMap<K, (u64, V)>,
142148}
143149
144150impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> {
145151 fn new(cap: usize) -> Self {
146 Self { cap, tick: 0, entries: HashMap::new() }
152 Self::with_byte_cap(cap, u64::MAX, |_| 0)
153 }
154
155 fn with_byte_cap(cap: usize, max_bytes: u64, size_fn: fn(&V) -> u64) -> Self {
156 Self { cap, max_bytes, total_bytes: 0, size_fn, tick: 0, entries: HashMap::new() }
147157 }
148158
149159 fn get(&mut self, key: K) -> Option<V> {
......@@ -162,18 +172,30 @@ impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> {
162172 *used = self.tick;
163173 return v.clone();
164174 }
165 if self.entries.len() >= self.cap {
166 if let Some(oldest) = self.entries.iter().min_by_key(|(_, (used, _))| *used).map(|(k, _)| *k) {
167 self.entries.remove(&oldest);
175 let v = make();
176 let new_bytes = (self.size_fn)(&v);
177 if self.cap == 0 || new_bytes > self.max_bytes {
178 return v;
179 }
180 while !self.entries.is_empty()
181 && (self.entries.len() >= self.cap
182 || self.total_bytes.saturating_add(new_bytes) > self.max_bytes)
183 {
184 let Some(oldest) = self.entries.iter().min_by_key(|(_, (used, _))| *used).map(|(k, _)| *k) else {
185 break;
186 };
187 if let Some((_, evicted)) = self.entries.remove(&oldest) {
188 self.total_bytes = self.total_bytes.saturating_sub((self.size_fn)(&evicted));
168189 }
169190 }
170 let v = make();
191 self.total_bytes = self.total_bytes.saturating_add(new_bytes);
171192 self.entries.insert(key, (self.tick, v.clone()));
172193 v
173194 }
174195
175196 fn clear(&mut self) {
176197 self.entries.clear();
198 self.total_bytes = 0;
177199 self.tick = 0;
178200 }
179201}
......@@ -283,6 +305,12 @@ pub struct MaterialFx {
283305 pub cull_front: bool,
284306 /// Unlit surface that Fusion draws once per light, so it brightens with the light count.
285307 pub per_light_unlit: bool,
308 /// `Diffuse.Color.Alpha`: modulates output alpha independently of `Diffuse.Opacity`.
309 pub diffuse_color_alpha: f32,
310 /// `MtlCookTorrance` `Specular.RefractiveIndex` (used when `do_fresnel` is true).
311 pub refractive_index: f32,
312 /// `MtlCookTorrance` `Specular.DoFresnel` toggle.
313 pub do_fresnel: bool,
286314}
287315
288316impl Default for MaterialFx {
......@@ -302,6 +330,9 @@ impl Default for MaterialFx {
302330 cull_back: false,
303331 cull_front: false,
304332 per_light_unlit: false,
333 diffuse_color_alpha: 1.0,
334 refractive_index: 2.0,
335 do_fresnel: true,
305336 }
306337 }
307338}
......@@ -323,6 +354,9 @@ impl MaterialFx {
323354 self.cull_back.hash(h);
324355 self.cull_front.hash(h);
325356 self.per_light_unlit.hash(h);
357 self.diffuse_color_alpha.to_bits().hash(h);
358 self.refractive_index.to_bits().hash(h);
359 self.do_fresnel.hash(h);
326360 }
327361}
328362
......@@ -812,7 +846,11 @@ impl Scene3DRenderer {
812846 bgl,
813847 pipelines,
814848 sampler,
815 meshes: Mutex::new(Lru::new(MAX_CACHED_MESH_BUFFERS)),
849 meshes: Mutex::new(Lru::with_byte_cap(
850 MAX_CACHED_MESH_BUFFERS,
851 MAX_CACHED_MESH_BYTES,
852 |gm| gm.as_ref().map_or(0, |m| m.vbuf_bytes + m.ibuf_bytes),
853 )),
816854 text3d_mesh_cache: Mutex::new(Lru::new(MAX_CACHED_MESH_BUFFERS)),
817855 shadow_pipeline,
818856 shadow_caster_bgl,
......@@ -821,7 +859,11 @@ impl Scene3DRenderer {
821859 shadow_dummy_ubuf,
822860 shadow_targets: Mutex::new(None),
823861 depth_targets: Mutex::new(Lru::new(DEPTH_CACHE_CAP)),
824 uniform_cache: Mutex::new(Lru::new(UNIFORM_CACHE_CAP)),
862 uniform_cache: Mutex::new(Lru::with_byte_cap(
863 UNIFORM_CACHE_CAP,
864 MAX_CACHED_UNIFORM_BYTES,
865 |b| b.size(),
866 )),
825867 }
826868 }
827869
......@@ -887,6 +929,11 @@ impl Scene3DRenderer {
887929 .sum()
888930 }
889931
932 /// Total GPU VRAM in bytes currently occupied by cached uniform buffers.
933 pub fn uniform_vram_bytes(&self) -> u64 {
934 self.uniform_cache.lock().unwrap().total_bytes
935 }
936
890937 #[cfg(test)]
891938 pub(crate) fn gpu_mesh_count(&self) -> usize {
892939 self.meshes.lock().unwrap().entries.len()
......@@ -1182,6 +1229,12 @@ impl Scene3DRenderer {
11821229 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 }],
11831230 bump_dod,
11841231 bump_params: [fx.bump_clamp_z, fx.bump_channel as f32, 0.0, 0.0],
1232 mtl_params: [
1233 fx.diffuse_color_alpha,
1234 fx.refractive_index,
1235 if fx.do_fresnel { 1.0 } else { 0.0 },
1236 0.0,
1237 ],
11851238 point_pos,
11861239 point_col,
11871240 spot_pos,
......@@ -1929,4 +1982,169 @@ mod tests {
19291982 assert_eq!(c[3], 255, "transparent front face must reveal opaque back face inside cube: {c:?}");
19301983 assert!((c[0] as i32 - 64).abs() <= 2, "back face should show 0.25 ambient gray: {c:?}");
19311984 }
1985
1986 #[test]
1987 fn diffuse_color_alpha_modulates_alpha_without_scaling_rgb() {
1988 let render_mat = |extra: &str| -> Option<[u8; 4]> {
1989 let scene = format!(
1990 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} }}, }},
1991 P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 4, }}, MaterialInput = Input {{ SourceOp = "Mtl", Source = "MaterialOutput", }}, }}, }},
1992 L = LightDirectional {{ }},
1993 M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"#
1994 );
1995 render(true, &scene).map(|px| center(&px))
1996 };
1997 let Some(ca) = render_mat(r#"["Diffuse.Color.Alpha"] = Input { Value = 0.5, },"#) else { return };
1998 let Some(op) = render_mat(r#"["Diffuse.Opacity"] = Input { Value = 0.5, },"#) else { return };
1999 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:?}");
2000 assert!((ca[3] as i32 - 128).abs() <= 2, "Diffuse.Color.Alpha must set output alpha: {ca:?}");
2001 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:?}");
2002 assert!((op[3] as i32 - 128).abs() <= 2, "Diffuse.Opacity sets output alpha: {op:?}");
2003 }
2004
2005 #[test]
2006 fn cook_torrance_refractive_index_drives_fresnel_specular() {
2007 let render_ct = |ri: f32, do_fresnel: u8| -> Option<u8> {
2008 let scene = format!(
2009 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}, }}, }}, }},
2010 P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 4, }}, MaterialInput = Input {{ SourceOp = "Mtl", Source = "MaterialOutput", }}, }}, }},
2011 L = LightDirectional {{ }},
2012 M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"#
2013 );
2014 render(true, &scene).map(|px| center(&px)[0])
2015 };
2016 let (Some(n1), Some(n2), Some(n3), Some(no_f)) = (
2017 render_ct(1.0, 1),
2018 render_ct(2.0, 1),
2019 render_ct(2.9, 1),
2020 render_ct(2.0, 0),
2021 ) else {
2022 return;
2023 };
2024 assert_eq!(n1, 0, "RI=1.0 has zero Fresnel reflectance");
2025 assert!(n2 > n1 && n3 > n2, "higher RI must strengthen specular: n1={n1} n2={n2} n3={n3}");
2026 assert!(no_f > n3, "DoFresnel=0 disables Fresnel attenuation: no_f={no_f} vs n3={n3}");
2027 }
2028
2029 #[test]
2030 fn unlit_premultiplied_emissive_texture_preserves_rgb() {
2031 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, }, }, },
2032 EmissiveTex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "EmissiveBg", Source = "Output", }, }, },
2033 Card = ImagePlane3D { Inputs = { ["Transform3DOp.Scale.X"] = Input { Value = 4, }, MaterialInput = Input { SourceOp = "EmissiveTex", Source = "MaterialOutput", }, }, },
2034 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Card", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#;
2035 let Some(px) = render(true, scene) else { return };
2036 let c = center(&px);
2037 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:?}");
2038 assert!((c[3] as i32 - 128).abs() <= 2, "alpha must remain 0.5: {c:?}");
2039 }
2040
2041 #[test]
2042 fn lru_byte_cap_evicts_least_recently_used_entries() {
2043 let mut lru: Lru<u8, (u8, u64)> = Lru::with_byte_cap(16, 100, |v| v.1);
2044 lru.get_or_insert_with(1, || (1, 40));
2045 lru.get_or_insert_with(2, || (2, 40));
2046 assert_eq!(lru.total_bytes, 80);
2047 // Touch key 1 so key 2 becomes LRU before inserting key 3 (80 + 40 > 100).
2048 assert_eq!(lru.get(1), Some((1, 40)));
2049 lru.get_or_insert_with(3, || (3, 40));
2050 assert_eq!(lru.total_bytes, 80);
2051 assert_eq!(lru.get(2), None, "LRU key 2 must be evicted to satisfy byte cap");
2052 assert_eq!(lru.get(1), Some((1, 40)));
2053 assert_eq!(lru.get(3), Some((3, 40)));
2054 // Entries larger than max_bytes are returned without busting the cache or exceeding max_bytes.
2055 let oversized = lru.get_or_insert_with(4, || (4, 150));
2056 assert_eq!(oversized, (4, 150));
2057 assert_eq!(lru.total_bytes, 80);
2058 assert_eq!(lru.entries.len(), 2);
2059 }
2060
2061 #[test]
2062 fn mesh_and_uniform_byte_caps_evict_lru_and_track_uniform_vram_bytes() {
2063 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
2064 let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return };
2065 let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return };
2066 let renderer = Scene3DRenderer::new(&device);
2067 let make_tex = |w, h| {
2068 CachedTexture::from_texture(
2069 device.create_texture(&wgpu::TextureDescriptor {
2070 label: None,
2071 size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
2072 mip_level_count: 1,
2073 sample_count: 1,
2074 dimension: wgpu::TextureDimension::D2,
2075 format: wgpu::TextureFormat::Rgba8Unorm,
2076 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
2077 view_formats: &[],
2078 }),
2079 [w, h],
2080 0,
2081 )
2082 };
2083 let (dst, dummy) = (make_tex(16, 16), make_tex(8, 8));
2084 let make_mesh = |n_tris: usize, z: f32| -> DrawMesh {
2085 let mut verts = Vec::with_capacity(n_tris * 3);
2086 for i in 0..n_tris {
2087 let off = i as f32 * 0.001 + z;
2088 verts.push(Vertex3D { pos: [-0.5, -0.5, off], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] });
2089 verts.push(Vertex3D { pos: [0.5, -0.5, off], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] });
2090 verts.push(Vertex3D { pos: [0.0, 0.5, off], normal: [0.0, 0.0, 1.0], uv: [0.5, 0.0] });
2091 }
2092 DrawMesh {
2093 world: mat4_identity(),
2094 shape: ShapeKind::CustomMesh(Arc::new(verts)),
2095 custom_mesh_key: None,
2096 tex: None,
2097 bump_tex: None,
2098 diffuse_col: [1.0; 4],
2099 specular_col: [1.0; 3],
2100 specular_intensity: 0.0,
2101 specular_exponent: 50.0,
2102 affected_by_lights: false,
2103 casts_shadow: false,
2104 receives_shadows: false,
2105 flip_normals: false,
2106 displace: None,
2107 }
2108 };
2109 let render_one = |m: DrawMesh| {
2110 let mut enc = device.create_command_encoder(&Default::default());
2111 renderer.render_meshes(
2112 &device,
2113 &queue,
2114 &mut enc,
2115 &dst,
2116 &dummy,
2117 mat4_identity(),
2118 mat4_identity(),
2119 [0.0, 0.0, 5.0],
2120 100.0,
2121 SceneLights::default(),
2122 false,
2123 false,
2124 &[m],
2125 );
2126 queue.submit(Some(enc.finish()));
2127 };
2128
2129 // Render one mesh and verify default caps and uniform_vram_bytes tracking.
2130 render_one(make_mesh(20, 0.0));
2131 let single_mesh_bytes = renderer.mesh_vram_bytes();
2132 let single_uni_bytes = renderer.uniform_vram_bytes();
2133 assert!(single_mesh_bytes > 0 && single_mesh_bytes <= MAX_CACHED_MESH_BYTES);
2134 assert!(single_uni_bytes > 0 && single_uni_bytes <= MAX_CACHED_UNIFORM_BYTES);
2135
2136 // Enforce tight byte caps (< 2 entries) and confirm LRU eviction caps both pools.
2137 renderer.meshes.lock().unwrap().max_bytes = single_mesh_bytes + single_mesh_bytes / 2;
2138 renderer.uniform_cache.lock().unwrap().max_bytes = single_uni_bytes + single_uni_bytes / 2;
2139
2140 render_one(make_mesh(20, 1.0));
2141 assert_eq!(renderer.gpu_mesh_count(), 1, "mesh byte cap must evict LRU mesh");
2142 assert_eq!(renderer.mesh_vram_bytes(), single_mesh_bytes);
2143 assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 1, "uniform byte cap must evict LRU uniform");
2144 assert_eq!(renderer.uniform_vram_bytes(), single_uni_bytes);
2145
2146 renderer.clear_shadow_targets();
2147 assert_eq!(renderer.uniform_vram_bytes(), 0);
2148 assert_eq!(renderer.mesh_vram_bytes(), 0);
2149 }
19322150}
crates/engine/src/scene3d/shader.rs+30-5
......@@ -56,6 +56,8 @@ pub(super) struct MeshUniform {
5656 pub(super) bump_dod: [f32; 4],
5757 /// `[bump_clamp_z, bump_channel, bump_filter_size, 0]`
5858 pub(super) bump_params: [f32; 4],
59 /// `[diffuse_color_alpha, refractive_index, do_fresnel, 0]`
60 pub(super) mtl_params: [f32; 4],
5961 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`
6062 pub(super) point_pos: [[f32; 4]; MAX_LIGHTS],
6163 /// Point light colors * intensity `(r, g, b, 0)`
......@@ -148,6 +150,7 @@ struct MeshUniform {
148150 bump_off_wrap: vec4<f32>,
149151 bump_dod: vec4<f32>,
150152 bump_params: vec4<f32>,
153 mtl_params: vec4<f32>,
151154 point_pos: array<vec4<f32>, MAX_LIGHTS>,
152155 point_col: array<vec4<f32>, MAX_LIGHTS>,
153156 spot_pos: array<vec4<f32>, MAX_LIGHTS>,
......@@ -288,10 +291,28 @@ fn eval_light_contrib(
288291 if (model == 1) {
289292 lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess);
290293 } else if (model == 2) {
291 // Beckmann distribution; shininess carries roughness.
294 // Cook-Torrance: Beckmann D, Torrance-Sparrow G, exact unpolarized Fresnel F.
295 // `eval_light_contrib` omits the outer N·L factor on `lobe`, so `(F*D*G)/(4*N·L*N·V) * N·L`
296 // simplifies to `(F*D*G)/(4*N·V)`.
292297 let nh = max(dot(n, h), 1e-3);
298 let nv = max(dot(n, v), 1e-3);
299 let vh = max(dot(v, h), 1e-3);
293300 let m2 = max(shininess * shininess, 1e-3);
294 lobe = 0.03 * exp(-(1.0 - nh * nh) / (nh * nh * m2)) / (3.14159265 * m2 * nh * nh * nh * nh);
301 let nh2 = nh * nh;
302 let d_term = exp(-(1.0 - nh2) / (nh2 * m2)) / (3.14159265 * m2 * nh2 * nh2);
303 let g_term = min(1.0, min(2.0 * nh * nv / vh, 2.0 * nh * ndotl / vh));
304 var fresnel = 1.0;
305 if (u.mtl_params.z > 0.5) {
306 let eta = max(u.mtl_params.y, 1.0);
307 let c = vh;
308 let g = sqrt(max(eta * eta + c * c - 1.0, 0.0));
309 let gmc = g - c;
310 let gpc = max(g + c, 1e-5);
311 let r_s = gmc / gpc;
312 let r_p = (c * gpc - 1.0) / max(c * gmc + 1.0, 1e-5);
313 fresnel = 0.5 * r_s * r_s * (1.0 + r_p * r_p);
314 }
315 lobe = (fresnel * d_term * g_term) / (4.0 * nv);
295316 } else {
296317 lobe = pow(max(dot(n, h), 0.0), shininess);
297318 }
......@@ -416,7 +437,11 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
416437 }
417438 col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col;
418439 }
419 if (col.a <= 0.002) {
440 // `rgb_alpha` is `tex_col.a * Diffuse.Opacity`; `Diffuse.Color.Alpha` (`u.mtl_params.x`)
441 // modulates output alpha without attenuating diffuse/specular RGB.
442 let rgb_alpha = col.a;
443 let out_alpha = rgb_alpha * u.mtl_params.x;
444 if (out_alpha <= 0.002) {
420445 discard;
421446 }
422447
......@@ -486,9 +511,9 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
486511 }
487512 }
488513
489 col = vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)) * col.a, col.a);
514 col = vec4<f32>(clamp(lit * rgb_alpha, vec3<f32>(0.0), vec3<f32>(1.0)), out_alpha);
490515 } else {
491 col = vec4<f32>(min(albedo * u.uv_off_wrap.w, vec3<f32>(1.0)) * col.a, col.a);
516 col = vec4<f32>(clamp(albedo * u.uv_off_wrap.w * rgb_alpha, vec3<f32>(0.0), vec3<f32>(1.0)), out_alpha);
492517 }
493518 return col;
494519}