| ... | ... | @@ -58,6 +58,7 @@ pub struct Scene3DRenderer { |
| 58 | 58 | } |
| 59 | 59 | |
| 60 | 60 | const UNIFORM_CACHE_CAP: usize = 64; |
| 61 | pub(crate) const MAX_CACHED_UNIFORM_BYTES: u64 = 16 * 1024 * 1024; |
| 61 | 62 | |
| 62 | 63 | fn cached_uniform_buffer( |
| 63 | 64 | cache: &Mutex<Lru<(u64, usize), wgpu::Buffer>>, |
| ... | ... | @@ -111,6 +112,8 @@ const FACE_BYTES: usize = 80; |
| 111 | 112 | |
| 112 | 113 | /// Most meshes kept resident on the GPU across frames. |
| 113 | 114 | pub(crate) const MAX_CACHED_MESH_BUFFERS: usize = 128; |
| 115 | /// Maximum GPU VRAM kept resident in `Scene3DRenderer::meshes`. |
| 116 | pub(crate) const MAX_CACHED_MESH_BYTES: u64 = 128 * 1024 * 1024; |
| 114 | 117 | /// Most main-pass depth targets pooled across distinct `Renderer3D` sizes. |
| 115 | 118 | const DEPTH_CACHE_CAP: usize = 8; |
| 116 | 119 | |
| ... | ... | @@ -134,16 +137,23 @@ struct GpuMesh { |
| 134 | 137 | ibuf_bytes: u64, |
| 135 | 138 | } |
| 136 | 139 | |
| 137 | | /// Bounded map evicting the least recently used entry. |
| 140 | /// Bounded map evicting the least recently used entry by count and optional byte budget. |
| 138 | 141 | struct Lru<K, V> { |
| 139 | 142 | cap: usize, |
| 143 | max_bytes: u64, |
| 144 | total_bytes: u64, |
| 145 | size_fn: fn(&V) -> u64, |
| 140 | 146 | tick: u64, |
| 141 | 147 | entries: HashMap<K, (u64, V)>, |
| 142 | 148 | } |
| 143 | 149 | |
| 144 | 150 | impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> { |
| 145 | 151 | 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() } |
| 147 | 157 | } |
| 148 | 158 | |
| 149 | 159 | fn get(&mut self, key: K) -> Option<V> { |
| ... | ... | @@ -162,18 +172,30 @@ impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> { |
| 162 | 172 | *used = self.tick; |
| 163 | 173 | return v.clone(); |
| 164 | 174 | } |
| 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)); |
| 168 | 189 | } |
| 169 | 190 | } |
| 170 | | let v = make(); |
| 191 | self.total_bytes = self.total_bytes.saturating_add(new_bytes); |
| 171 | 192 | self.entries.insert(key, (self.tick, v.clone())); |
| 172 | 193 | v |
| 173 | 194 | } |
| 174 | 195 | |
| 175 | 196 | fn clear(&mut self) { |
| 176 | 197 | self.entries.clear(); |
| 198 | self.total_bytes = 0; |
| 177 | 199 | self.tick = 0; |
| 178 | 200 | } |
| 179 | 201 | } |
| ... | ... | @@ -283,6 +305,12 @@ pub struct MaterialFx { |
| 283 | 305 | pub cull_front: bool, |
| 284 | 306 | /// Unlit surface that Fusion draws once per light, so it brightens with the light count. |
| 285 | 307 | 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, |
| 286 | 314 | } |
| 287 | 315 | |
| 288 | 316 | impl Default for MaterialFx { |
| ... | ... | @@ -302,6 +330,9 @@ impl Default for MaterialFx { |
| 302 | 330 | cull_back: false, |
| 303 | 331 | cull_front: false, |
| 304 | 332 | per_light_unlit: false, |
| 333 | diffuse_color_alpha: 1.0, |
| 334 | refractive_index: 2.0, |
| 335 | do_fresnel: true, |
| 305 | 336 | } |
| 306 | 337 | } |
| 307 | 338 | } |
| ... | ... | @@ -323,6 +354,9 @@ impl MaterialFx { |
| 323 | 354 | self.cull_back.hash(h); |
| 324 | 355 | self.cull_front.hash(h); |
| 325 | 356 | 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); |
| 326 | 360 | } |
| 327 | 361 | } |
| 328 | 362 | |
| ... | ... | @@ -812,7 +846,11 @@ impl Scene3DRenderer { |
| 812 | 846 | bgl, |
| 813 | 847 | pipelines, |
| 814 | 848 | 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 | )), |
| 816 | 854 | text3d_mesh_cache: Mutex::new(Lru::new(MAX_CACHED_MESH_BUFFERS)), |
| 817 | 855 | shadow_pipeline, |
| 818 | 856 | shadow_caster_bgl, |
| ... | ... | @@ -821,7 +859,11 @@ impl Scene3DRenderer { |
| 821 | 859 | shadow_dummy_ubuf, |
| 822 | 860 | shadow_targets: Mutex::new(None), |
| 823 | 861 | 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 | )), |
| 825 | 867 | } |
| 826 | 868 | } |
| 827 | 869 | |
| ... | ... | @@ -887,6 +929,11 @@ impl Scene3DRenderer { |
| 887 | 929 | .sum() |
| 888 | 930 | } |
| 889 | 931 | |
| 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 | |
| 890 | 937 | #[cfg(test)] |
| 891 | 938 | pub(crate) fn gpu_mesh_count(&self) -> usize { |
| 892 | 939 | self.meshes.lock().unwrap().entries.len() |
| ... | ... | @@ -1182,6 +1229,12 @@ impl Scene3DRenderer { |
| 1182 | 1229 | 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 }], |
| 1183 | 1230 | bump_dod, |
| 1184 | 1231 | 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 | ], |
| 1185 | 1238 | point_pos, |
| 1186 | 1239 | point_col, |
| 1187 | 1240 | spot_pos, |
| ... | ... | @@ -1929,4 +1982,169 @@ mod tests { |
| 1929 | 1982 | assert_eq!(c[3], 255, "transparent front face must reveal opaque back face inside cube: {c:?}"); |
| 1930 | 1983 | assert!((c[0] as i32 - 64).abs() <= 2, "back face should show 0.25 ambient gray: {c:?}"); |
| 1931 | 1984 | } |
| 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 | } |
| 1932 | 2150 | } |