| ... | @@ -51,6 +51,41 @@ pub struct Scene3DRenderer { | ... | @@ -51,6 +51,41 @@ pub struct Scene3DRenderer { |
| 51 | shadow_targets: Mutex<Option<ShadowTargets>>, | 51 | shadow_targets: Mutex<Option<ShadowTargets>>, |
| 52 | /// Main-pass `Depth32Float` targets pooled by `[width, height]`. | 52 | /// Main-pass `Depth32Float` targets pooled by `[width, height]`. |
| 53 | depth_targets: Mutex<Lru<[u32; 2], DepthTarget>>, | 53 | depth_targets: Mutex<Lru<[u32; 2], DepthTarget>>, |
| | 54 | /// Content-addressed LRU cache of immutable GPU uniform buffers (per-render `MeshUniform`, |
| | 55 | /// `ShadowUniform`, and dynamic shadow caster/face uniforms). Never mutated after upload, |
| | 56 | /// so multiple `Renderer3D` evaluations in the same unsubmitted `CommandEncoder` cannot alias. |
| | 57 | uniform_cache: Mutex<Lru<(u64, usize), wgpu::Buffer>>, |
| | 58 | } |
| | 59 | |
| | 60 | const UNIFORM_CACHE_CAP: usize = 64; |
| | 61 | |
| | 62 | fn cached_uniform_buffer( |
| | 63 | cache: &Mutex<Lru<(u64, usize), wgpu::Buffer>>, |
| | 64 | device: &wgpu::Device, |
| | 65 | label: &'static str, |
| | 66 | bytes: &[u8], |
| | 67 | ) -> wgpu::Buffer { |
| | 68 | use std::hash::{DefaultHasher, Hash, Hasher}; |
| | 69 | let mut h = DefaultHasher::new(); |
| | 70 | label.hash(&mut h); |
| | 71 | bytes.len().hash(&mut h); |
| | 72 | h.write(bytes); |
| | 73 | let key = (h.finish(), bytes.len()); |
| | 74 | cache.lock().unwrap().get_or_insert_with(key, || { |
| | 75 | let size = (bytes.len() as u64).max(16); |
| | 76 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| | 77 | label: Some(label), |
| | 78 | size, |
| | 79 | usage: wgpu::BufferUsages::UNIFORM, |
| | 80 | mapped_at_creation: true, |
| | 81 | }); |
| | 82 | buf.slice(..bytes.len() as u64) |
| | 83 | .get_mapped_range_mut() |
| | 84 | .expect("mapped uniform buffer") |
| | 85 | .copy_from_slice(bytes); |
| | 86 | buf.unmap(); |
| | 87 | buf |
| | 88 | }) |
| 54 | } | 89 | } |
| 55 | | 90 | |
| 56 | #[derive(Clone)] | 91 | #[derive(Clone)] |
| ... | @@ -75,19 +110,28 @@ const CASTER_BYTES: usize = 64; | ... | @@ -75,19 +110,28 @@ const CASTER_BYTES: usize = 64; |
| 75 | const FACE_BYTES: usize = 80; | 110 | const FACE_BYTES: usize = 80; |
| 76 | | 111 | |
| 77 | /// Most meshes kept resident on the GPU across frames. | 112 | /// Most meshes kept resident on the GPU across frames. |
| 78 | const MESH_CACHE_CAP: usize = 64; | 113 | pub(crate) const MAX_CACHED_MESH_BUFFERS: usize = 128; |
| 79 | /// Most main-pass depth targets pooled across distinct `Renderer3D` sizes. | 114 | /// Most main-pass depth targets pooled across distinct `Renderer3D` sizes. |
| 80 | const DEPTH_CACHE_CAP: usize = 8; | 115 | const DEPTH_CACHE_CAP: usize = 8; |
| 81 | | 116 | |
| 82 | /// `(base shape hash, image-plane aspect bits, wireframe)`; everything `build_shape_mesh` and the | 117 | /// Content-based key (64-bit hash + byte len + element count + aspect + wireframe) so |
| 83 | /// edge conversion read, so animated transforms and materials reuse one upload. | 118 | /// GPU mesh cache lookups are ABA-safe even after source CPU meshes are dropped. |
| 84 | type MeshKey = (u64, u32, bool); | 119 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| | 120 | struct MeshKey { |
| | 121 | content_hash: u64, |
| | 122 | byte_len: usize, |
| | 123 | elem_count: usize, |
| | 124 | aspect_bits: u32, |
| | 125 | wireframe: bool, |
| | 126 | } |
| 85 | | 127 | |
| 86 | #[derive(Clone)] | 128 | #[derive(Clone)] |
| 87 | struct GpuMesh { | 129 | struct GpuMesh { |
| 88 | vbuf: wgpu::Buffer, | 130 | vbuf: wgpu::Buffer, |
| 89 | ibuf: wgpu::Buffer, | 131 | ibuf: wgpu::Buffer, |
| 90 | idx_count: u32, | 132 | idx_count: u32, |
| | 133 | vbuf_bytes: u64, |
| | 134 | ibuf_bytes: u64, |
| 91 | } | 135 | } |
| 92 | | 136 | |
| 93 | /// Bounded map evicting the least recently used entry. | 137 | /// Bounded map evicting the least recently used entry. |
| ... | @@ -451,16 +495,66 @@ pub struct DrawMesh { | ... | @@ -451,16 +495,66 @@ pub struct DrawMesh { |
| 451 | fn mesh_key(base_shape: &ShapeKind, custom_mesh_key: Option<u64>, aspect: f32, wireframe: bool) -> MeshKey { | 495 | fn mesh_key(base_shape: &ShapeKind, custom_mesh_key: Option<u64>, aspect: f32, wireframe: bool) -> MeshKey { |
| 452 | use std::hash::{DefaultHasher, Hash, Hasher}; | 496 | use std::hash::{DefaultHasher, Hash, Hasher}; |
| 453 | let mut h = DefaultHasher::new(); | 497 | let mut h = DefaultHasher::new(); |
| 454 | if matches!(base_shape, ShapeKind::CustomMesh(_)) { | 498 | let (byte_len, elem_count) = match base_shape { |
| 455 | if let Some(ck) = custom_mesh_key { | 499 | ShapeKind::CustomMesh(verts) => { |
| | 500 | let elems = verts.len(); |
| | 501 | let bytes = std::mem::size_of_val(verts.as_slice()); |
| 456 | 6u8.hash(&mut h); | 502 | 6u8.hash(&mut h); |
| 457 | ck.hash(&mut h); | 503 | elems.hash(&mut h); |
| 458 | return (h.finish(), 0, wireframe); | 504 | bytes.hash(&mut h); |
| | 505 | if let Some(ck) = custom_mesh_key { |
| | 506 | ck.hash(&mut h); |
| | 507 | } else { |
| | 508 | h.write(bytemuck::cast_slice(verts.as_slice())); |
| | 509 | } |
| | 510 | (bytes, elems) |
| 459 | } | 511 | } |
| 460 | } | 512 | _ => { |
| 461 | base_shape.hash_into(&mut h); | 513 | base_shape.hash_into(&mut h); |
| | 514 | (0, 0) |
| | 515 | } |
| | 516 | }; |
| 462 | let aspect_bits = if matches!(base_shape, ShapeKind::ImagePlane) { aspect.to_bits() } else { 0 }; | 517 | let aspect_bits = if matches!(base_shape, ShapeKind::ImagePlane) { aspect.to_bits() } else { 0 }; |
| 463 | (h.finish(), aspect_bits, wireframe) | 518 | MeshKey { |
| | 519 | content_hash: h.finish(), |
| | 520 | byte_len, |
| | 521 | elem_count, |
| | 522 | aspect_bits, |
| | 523 | wireframe, |
| | 524 | } |
| | 525 | } |
| | 526 | |
| | 527 | /// Returns the local-space centroid of partial `Cube` face subsets so separate face |
| | 528 | /// material groups sort front-to-back / back-to-front by their true face depth. |
| | 529 | fn shape_local_center(shape: &ShapeKind) -> [f32; 3] { |
| | 530 | let ShapeKind::Cube { width, faces, .. } = shape.base_shape() else { |
| | 531 | return [0.0; 3]; |
| | 532 | }; |
| | 533 | let mask = *faces & 0b11_1111; |
| | 534 | if mask == 0 || mask == 0b11_1111 { |
| | 535 | return [0.0; 3]; |
| | 536 | } |
| | 537 | let hw = width * 0.5; |
| | 538 | let face_centers: [[f32; 3]; 6] = [ |
| | 539 | [0.0, 0.0, hw], |
| | 540 | [0.0, 0.0, -hw], |
| | 541 | [hw, 0.0, 0.0], |
| | 542 | [-hw, 0.0, 0.0], |
| | 543 | [0.0, hw, 0.0], |
| | 544 | [0.0, -hw, 0.0], |
| | 545 | ]; |
| | 546 | let mut sum = [0.0_f32; 3]; |
| | 547 | let mut count = 0u32; |
| | 548 | for (i, c) in face_centers.iter().enumerate() { |
| | 549 | if mask & (1 << i) != 0 { |
| | 550 | sum[0] += c[0]; |
| | 551 | sum[1] += c[1]; |
| | 552 | sum[2] += c[2]; |
| | 553 | count += 1; |
| | 554 | } |
| | 555 | } |
| | 556 | let inv = 1.0 / (count.max(1) as f32); |
| | 557 | [sum[0] * inv, sum[1] * inv, sum[2] * inv] |
| 464 | } | 558 | } |
| 465 | | 559 | |
| 466 | /// View-projections of the six 90 degree faces (`+X -X +Y -Y +Z -Z`) around `eye`. | 560 | /// View-projections of the six 90 degree faces (`+X -X +Y -Y +Z -Z`) around `eye`. |
| ... | @@ -718,8 +812,8 @@ impl Scene3DRenderer { | ... | @@ -718,8 +812,8 @@ impl Scene3DRenderer { |
| 718 | bgl, | 812 | bgl, |
| 719 | pipelines, | 813 | pipelines, |
| 720 | sampler, | 814 | sampler, |
| 721 | meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)), | 815 | meshes: Mutex::new(Lru::new(MAX_CACHED_MESH_BUFFERS)), |
| 722 | text3d_mesh_cache: Mutex::new(Lru::new(MESH_CACHE_CAP)), | 816 | text3d_mesh_cache: Mutex::new(Lru::new(MAX_CACHED_MESH_BUFFERS)), |
| 723 | shadow_pipeline, | 817 | shadow_pipeline, |
| 724 | shadow_caster_bgl, | 818 | shadow_caster_bgl, |
| 725 | shadow_face_bgl, | 819 | shadow_face_bgl, |
| ... | @@ -727,6 +821,7 @@ impl Scene3DRenderer { | ... | @@ -727,6 +821,7 @@ impl Scene3DRenderer { |
| 727 | shadow_dummy_ubuf, | 821 | shadow_dummy_ubuf, |
| 728 | shadow_targets: Mutex::new(None), | 822 | shadow_targets: Mutex::new(None), |
| 729 | depth_targets: Mutex::new(Lru::new(DEPTH_CACHE_CAP)), | 823 | depth_targets: Mutex::new(Lru::new(DEPTH_CACHE_CAP)), |
| | 824 | uniform_cache: Mutex::new(Lru::new(UNIFORM_CACHE_CAP)), |
| 730 | } | 825 | } |
| 731 | } | 826 | } |
| 732 | | 827 | |
| ... | @@ -746,11 +841,14 @@ impl Scene3DRenderer { | ... | @@ -746,11 +841,14 @@ impl Scene3DRenderer { |
| 746 | .get_or_insert_with(key, || Arc::clone(&built)) | 841 | .get_or_insert_with(key, || Arc::clone(&built)) |
| 747 | } | 842 | } |
| 748 | | 843 | |
| 749 | /// Drops the cached shadow cube-map pool, main-pass depth target pool, and memoized `Text3D` CPU meshes. | 844 | /// Drops cached shadow cube-map targets, main-pass depth targets, memoized `Text3D` CPU meshes, |
| | 845 | /// cached GPU mesh vertex/index buffers, and pooled uniform buffers. |
| 750 | pub fn clear_shadow_targets(&self) { | 846 | pub fn clear_shadow_targets(&self) { |
| 751 | *self.shadow_targets.lock().unwrap() = None; | 847 | *self.shadow_targets.lock().unwrap() = None; |
| 752 | self.depth_targets.lock().unwrap().clear(); | 848 | self.depth_targets.lock().unwrap().clear(); |
| 753 | self.text3d_mesh_cache.lock().unwrap().clear(); | 849 | self.text3d_mesh_cache.lock().unwrap().clear(); |
| | 850 | self.meshes.lock().unwrap().clear(); |
| | 851 | self.uniform_cache.lock().unwrap().clear(); |
| 754 | } | 852 | } |
| 755 | | 853 | |
| 756 | /// Drops all pooled 3D render targets (`shadow_targets` and `depth_targets`) and `Text3D` CPU meshes. | 854 | /// Drops all pooled 3D render targets (`shadow_targets` and `depth_targets`) and `Text3D` CPU meshes. |
| ... | @@ -777,6 +875,18 @@ impl Scene3DRenderer { | ... | @@ -777,6 +875,18 @@ impl Scene3DRenderer { |
| 777 | .sum() | 875 | .sum() |
| 778 | } | 876 | } |
| 779 | | 877 | |
| | 878 | /// Total GPU VRAM in bytes currently occupied by cached vertex and index buffers. |
| | 879 | pub fn mesh_vram_bytes(&self) -> u64 { |
| | 880 | self.meshes |
| | 881 | .lock() |
| | 882 | .unwrap() |
| | 883 | .entries |
| | 884 | .values() |
| | 885 | .filter_map(|(_, gm)| gm.as_ref()) |
| | 886 | .map(|gm| gm.vbuf_bytes + gm.ibuf_bytes) |
| | 887 | .sum() |
| | 888 | } |
| | 889 | |
| 780 | #[cfg(test)] | 890 | #[cfg(test)] |
| 781 | pub(crate) fn gpu_mesh_count(&self) -> usize { | 891 | pub(crate) fn gpu_mesh_count(&self) -> usize { |
| 782 | self.meshes.lock().unwrap().entries.len() | 892 | self.meshes.lock().unwrap().entries.len() |
| ... | @@ -845,14 +955,12 @@ impl Scene3DRenderer { | ... | @@ -845,14 +955,12 @@ impl Scene3DRenderer { |
| 845 | shadow_face_vps[slot * 6..slot * 6 + 6].copy_from_slice(&vps); | 955 | shadow_face_vps[slot * 6..slot * 6 + 6].copy_from_slice(&vps); |
| 846 | shadow_uni.point[li] = [slot as f32, pl.shadow_density.unwrap_or(0.0), 0.0, 0.0]; | 956 | shadow_uni.point[li] = [slot as f32, pl.shadow_density.unwrap_or(0.0), 0.0, 0.0]; |
| 847 | } | 957 | } |
| 848 | let buf = device.create_buffer(&wgpu::BufferDescriptor { | 958 | cached_uniform_buffer( |
| 849 | label: Some("scene3d-shadow-u"), | 959 | &self.uniform_cache, |
| 850 | size: std::mem::size_of::<ShadowUniform>() as u64, | 960 | device, |
| 851 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | 961 | "scene3d-shadow-u", |
| 852 | mapped_at_creation: false, | 962 | bytemuck::bytes_of(&shadow_uni), |
| 853 | }); | 963 | ) |
| 854 | queue.write_buffer(&buf, 0, bytemuck::bytes_of(&shadow_uni)); | | |
| 855 | buf | | |
| 856 | }); | 964 | }); |
| 857 | let shadow_ubuf = shadow_ubuf_owned.as_ref().unwrap_or(&self.shadow_dummy_ubuf); | 965 | let shadow_ubuf = shadow_ubuf_owned.as_ref().unwrap_or(&self.shadow_dummy_ubuf); |
| 858 | let shadow_targets = (!shadow_lights.is_empty()).then(|| { | 966 | let shadow_targets = (!shadow_lights.is_empty()).then(|| { |
| ... | @@ -917,57 +1025,40 @@ impl Scene3DRenderer { | ... | @@ -917,57 +1025,40 @@ impl Scene3DRenderer { |
| 917 | let uniform_stride = (CASTER_BYTES.max(FACE_BYTES) as u32).next_multiple_of(align) as usize; | 1025 | let uniform_stride = (CASTER_BYTES.max(FACE_BYTES) as u32).next_multiple_of(align) as usize; |
| 918 | let face_base = meshes.len() * uniform_stride; | 1026 | let face_base = meshes.len() * uniform_stride; |
| 919 | let mut shadow_uniform_bytes = vec![0u8; if shadow_lights.is_empty() { 0 } else { face_base + shadow_lights.len() * 6 * uniform_stride }]; | 1027 | let mut shadow_uniform_bytes = vec![0u8; if shadow_lights.is_empty() { 0 } else { face_base + shadow_lights.len() * 6 * uniform_stride }]; |
| 920 | let shadow_dyn_buf = (!shadow_lights.is_empty()).then(|| { | | |
| 921 | device.create_buffer(&wgpu::BufferDescriptor { | | |
| 922 | label: Some("scene3d-shadow-dyn"), | | |
| 923 | size: shadow_uniform_bytes.len() as u64, | | |
| 924 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | | |
| 925 | mapped_at_creation: false, | | |
| 926 | }) | | |
| 927 | }); | | |
| 928 | let caster_bg = shadow_dyn_buf.as_ref().map(|buf| { | | |
| 929 | device.create_bind_group(&wgpu::BindGroupDescriptor { | | |
| 930 | label: Some("scene3d-shadow-caster"), | | |
| 931 | layout: &self.shadow_caster_bgl, | | |
| 932 | entries: &[wgpu::BindGroupEntry { | | |
| 933 | binding: 0, | | |
| 934 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { | | |
| 935 | buffer: buf, | | |
| 936 | offset: 0, | | |
| 937 | size: std::num::NonZeroU64::new(CASTER_BYTES as u64), | | |
| 938 | }), | | |
| 939 | }], | | |
| 940 | }) | | |
| 941 | }); | | |
| 942 | let mut n_casters = 0; | 1028 | let mut n_casters = 0; |
| 943 | | 1029 | |
| 944 | // One dynamic-offset uniform buffer holds every mesh's `MeshUniform` for this render call. | 1030 | // One dynamic-offset uniform buffer holds every mesh's `MeshUniform` for this render call. |
| 945 | let mesh_uni_size = std::mem::size_of::<MeshUniform>(); | 1031 | let mesh_uni_size = std::mem::size_of::<MeshUniform>(); |
| 946 | let mesh_uni_stride = (mesh_uni_size as u32).next_multiple_of(align) as usize; | 1032 | let mesh_uni_stride = (mesh_uni_size as u32).next_multiple_of(align) as usize; |
| 947 | let mut mesh_uniform_bytes = vec![0u8; meshes.len() * mesh_uni_stride]; | 1033 | let mut mesh_uniform_bytes = vec![0u8; meshes.len() * mesh_uni_stride]; |
| 948 | let mesh_dyn_buf = (!meshes.is_empty()).then(|| { | | |
| 949 | device.create_buffer(&wgpu::BufferDescriptor { | | |
| 950 | label: Some("scene3d-mesh-dyn"), | | |
| 951 | size: mesh_uniform_bytes.len() as u64, | | |
| 952 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | | |
| 953 | mapped_at_creation: false, | | |
| 954 | }) | | |
| 955 | }); | | |
| 956 | | 1034 | |
| 957 | // Sort back-to-front in camera view space so semi-transparent planes blend cleanly. | 1035 | // Sort back-to-front by view-space centroid so semi-transparent planes and partial |
| | 1036 | // Cube3D face groups blend cleanly while preserving scene-graph order on equal depths. |
| 958 | let mut order: Vec<(usize, f32)> = meshes | 1037 | let mut order: Vec<(usize, f32)> = meshes |
| 959 | .iter() | 1038 | .iter() |
| 960 | .enumerate() | 1039 | .enumerate() |
| 961 | .map(|(i, m)| { | 1040 | .map(|(i, m)| { |
| 962 | let wx = m.world[12]; | 1041 | let c = shape_local_center(&m.shape); |
| 963 | let wy = m.world[13]; | 1042 | let wx = m.world[0] * c[0] + m.world[4] * c[1] + m.world[8] * c[2] + m.world[12]; |
| 964 | let wz = m.world[14]; | 1043 | let wy = m.world[1] * c[0] + m.world[5] * c[1] + m.world[9] * c[2] + m.world[13]; |
| | 1044 | let wz = m.world[2] * c[0] + m.world[6] * c[1] + m.world[10] * c[2] + m.world[14]; |
| 965 | let vz = view[2] * wx + view[6] * wy + view[10] * wz + view[14]; | 1045 | let vz = view[2] * wx + view[6] * wy + view[10] * wz + view[14]; |
| 966 | (i, vz) | 1046 | (i, vz) |
| 967 | }) | 1047 | }) |
| 968 | .collect(); | 1048 | .collect(); |
| 969 | order.sort_by(|a, b| a.1.total_cmp(&b.1)); | 1049 | order.sort_by(|a, b| a.1.total_cmp(&b.1)); |
| 970 | | 1050 | |
| | 1051 | struct PreparedDraw<'a> { |
| | 1052 | wireframe: bool, |
| | 1053 | cull: [bool; 2], |
| | 1054 | tex_view: &'a wgpu::TextureView, |
| | 1055 | bump_view: &'a wgpu::TextureView, |
| | 1056 | uni_offset: u32, |
| | 1057 | caster_offset: Option<u32>, |
| | 1058 | vbuf: wgpu::Buffer, |
| | 1059 | ibuf: wgpu::Buffer, |
| | 1060 | idx_count: u32, |
| | 1061 | } |
| 971 | struct GpuDraw { | 1062 | struct GpuDraw { |
| 972 | wireframe: bool, | 1063 | wireframe: bool, |
| 973 | /// Skip the `[back-facing, front-facing]` pass. | 1064 | /// Skip the `[back-facing, front-facing]` pass. |
| ... | @@ -980,7 +1071,7 @@ impl Scene3DRenderer { | ... | @@ -980,7 +1071,7 @@ impl Scene3DRenderer { |
| 980 | ibuf: wgpu::Buffer, | 1071 | ibuf: wgpu::Buffer, |
| 981 | idx_count: u32, | 1072 | idx_count: u32, |
| 982 | } | 1073 | } |
| 983 | let mut draw_items = Vec::with_capacity(order.len()); | 1074 | let mut prepared = Vec::with_capacity(order.len()); |
| 984 | for (idx, _) in order { | 1075 | for (idx, _) in order { |
| 985 | let m = &meshes[idx]; | 1076 | let m = &meshes[idx]; |
| 986 | let aspect = m | 1077 | let aspect = m |
| ... | @@ -1002,21 +1093,23 @@ impl Scene3DRenderer { | ... | @@ -1002,21 +1093,23 @@ impl Scene3DRenderer { |
| 1002 | } | 1093 | } |
| 1003 | let vbytes = bytemuck::cast_slice(&verts); | 1094 | let vbytes = bytemuck::cast_slice(&verts); |
| 1004 | let ibytes = bytemuck::cast_slice(&indices); | 1095 | let ibytes = bytemuck::cast_slice(&indices); |
| | 1096 | let vbuf_bytes = vbytes.len() as u64; |
| | 1097 | let ibuf_bytes = ibytes.len() as u64; |
| 1005 | let vbuf = device.create_buffer(&wgpu::BufferDescriptor { | 1098 | let vbuf = device.create_buffer(&wgpu::BufferDescriptor { |
| 1006 | label: Some("scene3d-vb"), | 1099 | label: Some("scene3d-vb"), |
| 1007 | size: vbytes.len() as u64, | 1100 | size: vbuf_bytes, |
| 1008 | usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, | 1101 | usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, |
| 1009 | mapped_at_creation: false, | 1102 | mapped_at_creation: false, |
| 1010 | }); | 1103 | }); |
| 1011 | queue.write_buffer(&vbuf, 0, vbytes); | 1104 | queue.write_buffer(&vbuf, 0, vbytes); |
| 1012 | let ibuf = device.create_buffer(&wgpu::BufferDescriptor { | 1105 | let ibuf = device.create_buffer(&wgpu::BufferDescriptor { |
| 1013 | label: Some("scene3d-ib"), | 1106 | label: Some("scene3d-ib"), |
| 1014 | size: ibytes.len() as u64, | 1107 | size: ibuf_bytes, |
| 1015 | usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, | 1108 | usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, |
| 1016 | mapped_at_creation: false, | 1109 | mapped_at_creation: false, |
| 1017 | }); | 1110 | }); |
| 1018 | queue.write_buffer(&ibuf, 0, ibytes); | 1111 | queue.write_buffer(&ibuf, 0, ibytes); |
| 1019 | Some(GpuMesh { vbuf, ibuf, idx_count: indices.len() as u32 }) | 1112 | Some(GpuMesh { vbuf, ibuf, idx_count: indices.len() as u32, vbuf_bytes, ibuf_bytes }) |
| 1020 | }; | 1113 | }; |
| 1021 | // Heightmap contents are not part of the key, so displaced meshes are never cached. | 1114 | // Heightmap contents are not part of the key, so displaced meshes are never cached. |
| 1022 | let gpu_mesh = if m.displace.is_some() { | 1115 | let gpu_mesh = if m.displace.is_some() { |
| ... | @@ -1095,44 +1188,22 @@ impl Scene3DRenderer { | ... | @@ -1095,44 +1188,22 @@ impl Scene3DRenderer { |
| 1095 | spot_dir, | 1188 | spot_dir, |
| 1096 | spot_col, | 1189 | spot_col, |
| 1097 | }; | 1190 | }; |
| 1098 | let mesh_buf = mesh_dyn_buf.as_ref().expect("mesh_dyn_buf allocated when meshes non-empty"); | 1191 | let uni_offset = prepared.len() * mesh_uni_stride; |
| 1099 | let uni_offset = draw_items.len() * mesh_uni_stride; | | |
| 1100 | mesh_uniform_bytes[uni_offset..uni_offset + mesh_uni_size].copy_from_slice(bytemuck::bytes_of(&uni)); | 1192 | mesh_uniform_bytes[uni_offset..uni_offset + mesh_uni_size].copy_from_slice(bytemuck::bytes_of(&uni)); |
| 1101 | let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view); | 1193 | let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view); |
| 1102 | let bump_view = bump_src.map_or(&dummy.view, |t| &t.view); | 1194 | let bump_view = bump_src.map_or(&dummy.view, |t| &t.view); |
| 1103 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { | | |
| 1104 | label: Some("scene3d-bg"), | | |
| 1105 | layout: &self.bgl, | | |
| 1106 | entries: &[ | | |
| 1107 | wgpu::BindGroupEntry { | | |
| 1108 | binding: 0, | | |
| 1109 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { | | |
| 1110 | buffer: mesh_buf, | | |
| 1111 | offset: 0, | | |
| 1112 | size: std::num::NonZeroU64::new(mesh_uni_size as u64), | | |
| 1113 | }), | | |
| 1114 | }, | | |
| 1115 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) }, | | |
| 1116 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, | | |
| 1117 | wgpu::BindGroupEntry { binding: 3, resource: shadow_ubuf.as_entire_binding() }, | | |
| 1118 | wgpu::BindGroupEntry { | | |
| 1119 | binding: 4, | | |
| 1120 | resource: wgpu::BindingResource::TextureView(shadow_view.unwrap_or(&self.shadow_dummy)), | | |
| 1121 | }, | | |
| 1122 | wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(bump_view) }, | | |
| 1123 | ], | | |
| 1124 | }); | | |
| 1125 | // Fusion's RendererOpenGL casts solid geometry shadows regardless of texture/material alpha. | 1195 | // Fusion's RendererOpenGL casts solid geometry shadows regardless of texture/material alpha. |
| 1126 | let caster_offset = shadow_dyn_buf.as_ref().filter(|_| m.casts_shadow && !fx.wireframe).map(|_| { | 1196 | let caster_offset = (!shadow_lights.is_empty() && m.casts_shadow && !fx.wireframe).then(|| { |
| 1127 | let offset = n_casters * uniform_stride; | 1197 | let offset = n_casters * uniform_stride; |
| 1128 | shadow_uniform_bytes[offset..offset + CASTER_BYTES].copy_from_slice(bytemuck::cast_slice(&m.world)); | 1198 | shadow_uniform_bytes[offset..offset + CASTER_BYTES].copy_from_slice(bytemuck::cast_slice(&m.world)); |
| 1129 | n_casters += 1; | 1199 | n_casters += 1; |
| 1130 | offset as u32 | 1200 | offset as u32 |
| 1131 | }); | 1201 | }); |
| 1132 | draw_items.push(GpuDraw { | 1202 | prepared.push(PreparedDraw { |
| 1133 | wireframe: fx.wireframe, | 1203 | wireframe: fx.wireframe, |
| 1134 | cull: [fx.cull_back, fx.cull_front], | 1204 | cull: [fx.cull_back, fx.cull_front], |
| 1135 | bg, | 1205 | tex_view, |
| | 1206 | bump_view, |
| 1136 | uni_offset: uni_offset as u32, | 1207 | uni_offset: uni_offset as u32, |
| 1137 | caster_offset, | 1208 | caster_offset, |
| 1138 | vbuf, | 1209 | vbuf, |
| ... | @@ -1140,34 +1211,99 @@ impl Scene3DRenderer { | ... | @@ -1140,34 +1211,99 @@ impl Scene3DRenderer { |
| 1140 | idx_count, | 1211 | idx_count, |
| 1141 | }); | 1212 | }); |
| 1142 | } | 1213 | } |
| 1143 | if let Some(mesh_buf) = &mesh_dyn_buf { | 1214 | let mesh_dyn_buf = (!prepared.is_empty()).then(|| { |
| 1144 | if !draw_items.is_empty() { | 1215 | cached_uniform_buffer( |
| 1145 | queue.write_buffer(mesh_buf, 0, &mesh_uniform_bytes[..draw_items.len() * mesh_uni_stride]); | 1216 | &self.uniform_cache, |
| 1146 | } | 1217 | device, |
| 1147 | } | 1218 | "scene3d-mesh-dyn", |
| | 1219 | &mesh_uniform_bytes[..prepared.len() * mesh_uni_stride], |
| | 1220 | ) |
| | 1221 | }); |
| | 1222 | let draw_items: Vec<GpuDraw> = prepared |
| | 1223 | .into_iter() |
| | 1224 | .map(|p| { |
| | 1225 | let mesh_buf = mesh_dyn_buf.as_ref().expect("mesh_dyn_buf allocated when prepared non-empty"); |
| | 1226 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| | 1227 | label: Some("scene3d-bg"), |
| | 1228 | layout: &self.bgl, |
| | 1229 | entries: &[ |
| | 1230 | wgpu::BindGroupEntry { |
| | 1231 | binding: 0, |
| | 1232 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| | 1233 | buffer: mesh_buf, |
| | 1234 | offset: 0, |
| | 1235 | size: std::num::NonZeroU64::new(mesh_uni_size as u64), |
| | 1236 | }), |
| | 1237 | }, |
| | 1238 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(p.tex_view) }, |
| | 1239 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, |
| | 1240 | wgpu::BindGroupEntry { binding: 3, resource: shadow_ubuf.as_entire_binding() }, |
| | 1241 | wgpu::BindGroupEntry { |
| | 1242 | binding: 4, |
| | 1243 | resource: wgpu::BindingResource::TextureView(shadow_view.unwrap_or(&self.shadow_dummy)), |
| | 1244 | }, |
| | 1245 | wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(p.bump_view) }, |
| | 1246 | ], |
| | 1247 | }); |
| | 1248 | GpuDraw { |
| | 1249 | wireframe: p.wireframe, |
| | 1250 | cull: p.cull, |
| | 1251 | bg, |
| | 1252 | uni_offset: p.uni_offset, |
| | 1253 | caster_offset: p.caster_offset, |
| | 1254 | vbuf: p.vbuf, |
| | 1255 | ibuf: p.ibuf, |
| | 1256 | idx_count: p.idx_count, |
| | 1257 | } |
| | 1258 | }) |
| | 1259 | .collect(); |
| 1148 | | 1260 | |
| 1149 | if let (Some(targets), Some(buf), Some(caster_bg)) = (&shadow_targets, &shadow_dyn_buf, &caster_bg) { | 1261 | if let Some(targets) = &shadow_targets { |
| | 1262 | for (slot, &li) in shadow_lights.iter().enumerate() { |
| | 1263 | let pos = lights.points[li].pos; |
| | 1264 | for face in 0..6 { |
| | 1265 | let layer = slot * 6 + face; |
| | 1266 | let mut uniform = [0.0_f32; FACE_BYTES / 4]; |
| | 1267 | uniform[..16].copy_from_slice(&shadow_face_vps[layer]); |
| | 1268 | uniform[16..19].copy_from_slice(&pos); |
| | 1269 | let face_offset = face_base + layer * uniform_stride; |
| | 1270 | shadow_uniform_bytes[face_offset..face_offset + FACE_BYTES].copy_from_slice(bytemuck::cast_slice(&uniform)); |
| | 1271 | } |
| | 1272 | } |
| | 1273 | let shadow_dyn_buf = cached_uniform_buffer( |
| | 1274 | &self.uniform_cache, |
| | 1275 | device, |
| | 1276 | "scene3d-shadow-dyn", |
| | 1277 | &shadow_uniform_bytes, |
| | 1278 | ); |
| | 1279 | let caster_bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| | 1280 | label: Some("scene3d-shadow-caster"), |
| | 1281 | layout: &self.shadow_caster_bgl, |
| | 1282 | entries: &[wgpu::BindGroupEntry { |
| | 1283 | binding: 0, |
| | 1284 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| | 1285 | buffer: &shadow_dyn_buf, |
| | 1286 | offset: 0, |
| | 1287 | size: std::num::NonZeroU64::new(CASTER_BYTES as u64), |
| | 1288 | }), |
| | 1289 | }], |
| | 1290 | }); |
| 1150 | let face_bg = device.create_bind_group(&wgpu::BindGroupDescriptor { | 1291 | let face_bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 1151 | label: Some("scene3d-shadow-face"), | 1292 | label: Some("scene3d-shadow-face"), |
| 1152 | layout: &self.shadow_face_bgl, | 1293 | layout: &self.shadow_face_bgl, |
| 1153 | entries: &[wgpu::BindGroupEntry { | 1294 | entries: &[wgpu::BindGroupEntry { |
| 1154 | binding: 0, | 1295 | binding: 0, |
| 1155 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { | 1296 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 1156 | buffer: buf, | 1297 | buffer: &shadow_dyn_buf, |
| 1157 | offset: 0, | 1298 | offset: 0, |
| 1158 | size: std::num::NonZeroU64::new(FACE_BYTES as u64), | 1299 | size: std::num::NonZeroU64::new(FACE_BYTES as u64), |
| 1159 | }), | 1300 | }), |
| 1160 | }], | 1301 | }], |
| 1161 | }); | 1302 | }); |
| 1162 | for (slot, &li) in shadow_lights.iter().enumerate() { | 1303 | for slot in 0..shadow_lights.len() { |
| 1163 | let pos = lights.points[li].pos; | | |
| 1164 | for face in 0..6 { | 1304 | for face in 0..6 { |
| 1165 | let layer = slot * 6 + face; | 1305 | let layer = slot * 6 + face; |
| 1166 | let mut uniform = [0.0_f32; FACE_BYTES / 4]; | | |
| 1167 | uniform[..16].copy_from_slice(&shadow_face_vps[layer]); | | |
| 1168 | uniform[16..19].copy_from_slice(&pos); | | |
| 1169 | let face_offset = face_base + layer * uniform_stride; | 1306 | let face_offset = face_base + layer * uniform_stride; |
| 1170 | shadow_uniform_bytes[face_offset..face_offset + FACE_BYTES].copy_from_slice(bytemuck::cast_slice(&uniform)); | | |
| 1171 | let layer_view = &targets.layer_views[layer]; | 1307 | let layer_view = &targets.layer_views[layer]; |
| 1172 | let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { | 1308 | let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 1173 | label: Some("scene3d-shadow-pass"), | 1309 | label: Some("scene3d-shadow-pass"), |
| ... | @@ -1196,14 +1332,13 @@ impl Scene3DRenderer { | ... | @@ -1196,14 +1332,13 @@ impl Scene3DRenderer { |
| 1196 | pass.set_bind_group(1, &face_bg, &[face_offset as u32]); | 1332 | pass.set_bind_group(1, &face_bg, &[face_offset as u32]); |
| 1197 | for d in &draw_items { | 1333 | for d in &draw_items { |
| 1198 | let Some(caster_offset) = d.caster_offset else { continue }; | 1334 | let Some(caster_offset) = d.caster_offset else { continue }; |
| 1199 | pass.set_bind_group(0, caster_bg, &[caster_offset]); | 1335 | pass.set_bind_group(0, &caster_bg, &[caster_offset]); |
| 1200 | pass.set_vertex_buffer(0, d.vbuf.slice(..)); | 1336 | pass.set_vertex_buffer(0, d.vbuf.slice(..)); |
| 1201 | pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); | 1337 | pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); |
| 1202 | pass.draw_indexed(0..d.idx_count, 0, 0..1); | 1338 | pass.draw_indexed(0..d.idx_count, 0, 0..1); |
| 1203 | } | 1339 | } |
| 1204 | } | 1340 | } |
| 1205 | } | 1341 | } |
| 1206 | queue.write_buffer(buf, 0, &shadow_uniform_bytes); | | |
| 1207 | } | 1342 | } |
| 1208 | | 1343 | |
| 1209 | let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { | 1344 | let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { |
| ... | @@ -1682,4 +1817,116 @@ mod tests { | ... | @@ -1682,4 +1817,116 @@ mod tests { |
| 1682 | assert_eq!(renderer.depth_targets.lock().unwrap().entries.len(), 0); | 1817 | assert_eq!(renderer.depth_targets.lock().unwrap().entries.len(), 0); |
| 1683 | assert_eq!(renderer.depth_vram_bytes(), 0); | 1818 | assert_eq!(renderer.depth_vram_bytes(), 0); |
| 1684 | } | 1819 | } |
| | 1820 | |
| | 1821 | #[test] |
| | 1822 | fn gpu_mesh_buffer_cache_hits_bounds_lru_and_clears_on_bust() { |
| | 1823 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| | 1824 | let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; |
| | 1825 | let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; |
| | 1826 | let renderer = Scene3DRenderer::new(&device); |
| | 1827 | let make_tex = |w, h| { |
| | 1828 | CachedTexture::from_texture( |
| | 1829 | device.create_texture(&wgpu::TextureDescriptor { |
| | 1830 | label: None, |
| | 1831 | size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| | 1832 | mip_level_count: 1, |
| | 1833 | sample_count: 1, |
| | 1834 | dimension: wgpu::TextureDimension::D2, |
| | 1835 | format: wgpu::TextureFormat::Rgba8Unorm, |
| | 1836 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| | 1837 | view_formats: &[], |
| | 1838 | }), |
| | 1839 | [w, h], |
| | 1840 | 0, |
| | 1841 | ) |
| | 1842 | }; |
| | 1843 | let (dst, dummy) = (make_tex(16, 16), make_tex(8, 8)); |
| | 1844 | let make_custom = |z_offset: f32| -> DrawMesh { |
| | 1845 | let tri = vec![ |
| | 1846 | Vertex3D { pos: [-0.5, -0.5, z_offset], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }, |
| | 1847 | Vertex3D { pos: [0.5, -0.5, z_offset], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }, |
| | 1848 | Vertex3D { pos: [0.0, 0.5, z_offset], normal: [0.0, 0.0, 1.0], uv: [0.5, 0.0] }, |
| | 1849 | ]; |
| | 1850 | DrawMesh { |
| | 1851 | world: mat4_identity(), |
| | 1852 | shape: ShapeKind::CustomMesh(Arc::new(tri)), |
| | 1853 | custom_mesh_key: None, |
| | 1854 | tex: None, |
| | 1855 | bump_tex: None, |
| | 1856 | diffuse_col: [1.0; 4], |
| | 1857 | specular_col: [1.0; 3], |
| | 1858 | specular_intensity: 0.0, |
| | 1859 | specular_exponent: 50.0, |
| | 1860 | affected_by_lights: false, |
| | 1861 | casts_shadow: false, |
| | 1862 | receives_shadows: false, |
| | 1863 | flip_normals: false, |
| | 1864 | displace: None, |
| | 1865 | } |
| | 1866 | }; |
| | 1867 | let render_one = |m: DrawMesh| { |
| | 1868 | let mut enc = device.create_command_encoder(&Default::default()); |
| | 1869 | renderer.render_meshes( |
| | 1870 | &device, |
| | 1871 | &queue, |
| | 1872 | &mut enc, |
| | 1873 | &dst, |
| | 1874 | &dummy, |
| | 1875 | mat4_identity(), |
| | 1876 | mat4_identity(), |
| | 1877 | [0.0, 0.0, 5.0], |
| | 1878 | 100.0, |
| | 1879 | SceneLights::default(), |
| | 1880 | false, |
| | 1881 | false, |
| | 1882 | &[m], |
| | 1883 | ); |
| | 1884 | queue.submit(Some(enc.finish())); |
| | 1885 | }; |
| | 1886 | |
| | 1887 | // 1. Repeated identical frames hit both GPU mesh cache and uniform cache, even across Arc drop/reallocation. |
| | 1888 | render_one(make_custom(0.0)); |
| | 1889 | let vram_1 = renderer.mesh_vram_bytes(); |
| | 1890 | assert_eq!(renderer.gpu_mesh_count(), 1); |
| | 1891 | assert!(vram_1 > 0); |
| | 1892 | assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 1); |
| | 1893 | |
| | 1894 | render_one(make_custom(0.0)); |
| | 1895 | assert_eq!(renderer.gpu_mesh_count(), 1, "rebuilt identical Arc must hit content-keyed mesh cache"); |
| | 1896 | assert_eq!(renderer.mesh_vram_bytes(), vram_1); |
| | 1897 | assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 1, "identical uniform bytes reuse cached buffer"); |
| | 1898 | |
| | 1899 | // 2. Eviction stays strictly bounded by MAX_CACHED_MESH_BUFFERS (128). |
| | 1900 | for i in 1..=(MAX_CACHED_MESH_BUFFERS + 20) { |
| | 1901 | render_one(make_custom(i as f32 * 0.01)); |
| | 1902 | } |
| | 1903 | assert_eq!(renderer.gpu_mesh_count(), MAX_CACHED_MESH_BUFFERS); |
| | 1904 | assert!(renderer.uniform_cache.lock().unwrap().entries.len() <= UNIFORM_CACHE_CAP); |
| | 1905 | |
| | 1906 | // 3. clear_shadow_targets() (called by bust_gpu_cache) releases all cached GPU mesh and uniform buffers. |
| | 1907 | renderer.clear_shadow_targets(); |
| | 1908 | assert_eq!(renderer.gpu_mesh_count(), 0); |
| | 1909 | assert_eq!(renderer.mesh_vram_bytes(), 0); |
| | 1910 | assert_eq!(renderer.uniform_cache.lock().unwrap().entries.len(), 0); |
| | 1911 | } |
| | 1912 | |
| | 1913 | #[test] |
| | 1914 | fn cube3d_semi_transparent_front_face_reveals_opaque_interior_faces() { |
| | 1915 | let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { |
| | 1916 | Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, TopLeftRed = Input { Value = 0, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 0, }, }, }, |
| | 1917 | Tex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, }, }, |
| | 1918 | Cube = Cube3D { Inputs = { FrontMaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, }, |
| | 1919 | Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 3.0, }, }, }, |
| | 1920 | Amb = LightAmbient { Inputs = { Intensity = Input { Value = 0.25, }, }, }, |
| | 1921 | M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cube", Source = "Output", }, SceneInput2 = Input { SourceOp = "Amb", Source = "Output", }, SceneInput3 = Input { SourceOp = "Cam", Source = "Output", }, }, }, |
| | 1922 | R = Renderer3D { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, ["RendererSoftware.LightingEnabled"] = Input { Value = 1, }, SceneInput = Input { SourceOp = "M", Source = "Output", }, }, }, |
| | 1923 | } }"#; |
| | 1924 | let comp = Comp::from_fusion_str(src).expect("parse Cube3D comp"); |
| | 1925 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| | 1926 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0); |
| | 1927 | let px = eng.readback_rgba(&tex).expect("readback Cube3D"); |
| | 1928 | let c = center(&px); |
| | 1929 | assert_eq!(c[3], 255, "transparent front face must reveal opaque back face inside cube: {c:?}"); |
| | 1930 | assert!((c[0] as i32 - 64).abs() <= 2, "back face should show 0.25 ambient gray: {c:?}"); |
| | 1931 | } |
| 1685 | } | 1932 | } |