| 1 | //! 3D scene graph & `wgpu` rasterizer for Fusion's `Renderer3D`, `Camera3D`, |
| 2 | //! `ImagePlane3D`, `Shape3D` (Sphere, Cylinder, Plane, Cube), `Merge3D`, `Transform3D`, |
| 3 | //! `LightAmbient`, `LightDirectional`, and `MtlCookTorrance` nodes. |
| 4 | //! |
| 5 | //! Matches Fusion's right-handed +Y-up / -Z-forward coordinate system, |
| 6 | //! `Transform3DOp` Euler rotation orders (`XYZ`, `XZY`, etc.), `ScaleLock`, |
| 7 | //! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection. |
| 8 | |
| 9 | mod alembic; |
| 10 | mod collect; |
| 11 | mod custom_vertex; |
| 12 | mod deform; |
| 13 | mod extrude; |
| 14 | mod fbx; |
| 15 | mod fbx_export; |
| 16 | mod fx; |
| 17 | mod materials; |
| 18 | mod math; |
| 19 | mod mesh; |
| 20 | mod projection; |
| 21 | mod relief; |
| 22 | mod scene_ops; |
| 23 | mod shader; |
| 24 | mod textures; |
| 25 | |
| 26 | pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d, mat4_inverse}; |
| 27 | pub use fbx_export::{bake_export_scene, export_meshes, ExportMesh}; |
| 28 | pub use math::{ |
| 29 | mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y, |
| 30 | mat4_rot_z, mat4_scale, mat4_translate, |
| 31 | }; |
| 32 | pub use shader::Vertex3D; |
| 33 | |
| 34 | use std::collections::HashMap; |
| 35 | use std::sync::{Arc, Mutex, MutexGuard}; |
| 36 | |
| 37 | fn lock_or_recover<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { |
| 38 | m.lock().unwrap_or_else(|e| e.into_inner()) |
| 39 | } |
| 40 | |
| 41 | use crate::cache::{AuxChannelTex, AuxChannels, CachedTexture, EMPTY_Z_SENTINEL}; |
| 42 | use fx::{SurfaceFx, SURFACE_FX_WGSL}; |
| 43 | use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges}; |
| 44 | use model::NodeId; |
| 45 | use shader::{ |
| 46 | DepthToEyeZUniform, MeshUniform, ShadowUniform, DEPTH_TO_EYE_Z_SHADER, MAX_DIR_LIGHTS, |
| 47 | MAX_LIGHTS, MAX_SHADOW_LIGHTS, SHADER_3D, SHADOW_MAP_SIZE, SHADOW_SHADER, UV_XFORM_WGSL, |
| 48 | }; |
| 49 | |
| 50 | pub type Mat4 = [f32; 16]; // Column-major 4x4 |
| 51 | |
| 52 | /// Mesh pipeline slot of `[cull_back, cull_front]` as bits; culling both faces maps past the end. |
| 53 | fn cull_index([cull_back, cull_front]: [bool; 2]) -> usize { |
| 54 | usize::from(cull_back) + 2 * usize::from(cull_front) |
| 55 | } |
| 56 | |
| 57 | pub struct Scene3DRenderer { |
| 58 | bgl: wgpu::BindGroupLayout, |
| 59 | /// `[triangles, lines][cull_index]`. Both faces draw in one pass in triangle order, as |
| 60 | /// Fusion's z-buffer hides whatever a translucent face drawn earlier covers. |
| 61 | pipelines: [[wgpu::RenderPipeline; 3]; 2], |
| 62 | /// Normal-channel pass, laid out like `pipelines`, writing `Rgba16Float`. |
| 63 | normal_pipelines: [[wgpu::RenderPipeline; 3]; 2], |
| 64 | /// Compute pass converting `Depth32Float` into eye-space `Z` (`R32Float`). |
| 65 | depth_z_bgl: wgpu::BindGroupLayout, |
| 66 | depth_z_pipeline: wgpu::ComputePipeline, |
| 67 | sampler: wgpu::Sampler, |
| 68 | meshes: Mutex<Lru<MeshKey, Option<GpuMesh>>>, |
| 69 | /// Memoized CPU `Text3D` extruded meshes keyed by deterministic geometry content hash. |
| 70 | text3d_mesh_cache: Mutex<Lru<u64, Arc<Vec<Vertex3D>>>>, |
| 71 | shadow_pipeline: wgpu::RenderPipeline, |
| 72 | /// `Caster` uniform (dynamic offset), material texture and sampler: group 0 of the shadow pass. |
| 73 | shadow_caster_bgl: wgpu::BindGroupLayout, |
| 74 | /// `Face` uniform (dynamic offset): group 1 of the shadow pass. |
| 75 | shadow_face_bgl: wgpu::BindGroupLayout, |
| 76 | /// 1x1 map bound when no light casts shadows. |
| 77 | shadow_dummy: wgpu::TextureView, |
| 78 | /// Immutable default `ShadowUniform` bound when no light casts shadows. |
| 79 | shadow_dummy_ubuf: wgpu::Buffer, |
| 80 | /// Cube maps and depth buffer reused across renders; grown, never shrunk. |
| 81 | shadow_targets: Mutex<Option<ShadowTargets>>, |
| 82 | /// Main-pass `Depth32Float` targets pooled by `[width, height]`. |
| 83 | depth_targets: Mutex<Lru<[u32; 2], DepthTarget>>, |
| 84 | /// Content-addressed LRU cache of immutable GPU uniform buffers (per-render `MeshUniform`, |
| 85 | /// `ShadowUniform`, and dynamic shadow caster/face uniforms). Never mutated after upload, |
| 86 | /// so multiple `Renderer3D` evaluations in the same unsubmitted `CommandEncoder` cannot alias. |
| 87 | uniform_cache: Mutex<Lru<(u64, usize), wgpu::Buffer>>, |
| 88 | } |
| 89 | |
| 90 | const UNIFORM_CACHE_CAP: usize = 64; |
| 91 | pub(crate) const MAX_CACHED_UNIFORM_BYTES: u64 = 16 * 1024 * 1024; |
| 92 | |
| 93 | fn cached_uniform_buffer( |
| 94 | cache: &Mutex<Lru<(u64, usize), wgpu::Buffer>>, |
| 95 | device: &wgpu::Device, |
| 96 | label: &'static str, |
| 97 | bytes: &[u8], |
| 98 | ) -> wgpu::Buffer { |
| 99 | use std::hash::{DefaultHasher, Hash, Hasher}; |
| 100 | let mut h = DefaultHasher::new(); |
| 101 | label.hash(&mut h); |
| 102 | bytes.len().hash(&mut h); |
| 103 | h.write(bytes); |
| 104 | let key = (h.finish(), bytes.len()); |
| 105 | lock_or_recover(cache).get_or_insert_with(key, || { |
| 106 | let size = (bytes.len() as u64).max(16); |
| 107 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 108 | label: Some(label), |
| 109 | size, |
| 110 | usage: wgpu::BufferUsages::UNIFORM, |
| 111 | mapped_at_creation: true, |
| 112 | }); |
| 113 | buf.slice(..bytes.len() as u64) |
| 114 | .get_mapped_range_mut() |
| 115 | .expect("mapped uniform buffer") |
| 116 | .copy_from_slice(bytes); |
| 117 | buf.unmap(); |
| 118 | buf |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | #[derive(Clone)] |
| 123 | struct DepthTarget { |
| 124 | tex: wgpu::Texture, |
| 125 | view: wgpu::TextureView, |
| 126 | } |
| 127 | |
| 128 | #[derive(Clone)] |
| 129 | struct ShadowTargets { |
| 130 | /// Array layers of the shadow cube-map texture (six per shadow light). |
| 131 | layers: u32, |
| 132 | /// `D2Array` view over all shadow-map layers. |
| 133 | array_view: wgpu::TextureView, |
| 134 | /// Per-layer `D2` views used as shadow-pass color attachments. |
| 135 | layer_views: Vec<wgpu::TextureView>, |
| 136 | depth: wgpu::TextureView, |
| 137 | } |
| 138 | |
| 139 | /// Bytes of the shadow pass's `Caster` and `Face` uniforms. |
| 140 | const CASTER_BYTES: usize = 64; |
| 141 | const FACE_BYTES: usize = 80; |
| 142 | |
| 143 | /// Most meshes kept resident on the GPU across frames. |
| 144 | pub(crate) const MAX_CACHED_MESH_BUFFERS: usize = 128; |
| 145 | /// Maximum GPU VRAM kept resident in `Scene3DRenderer::meshes`. |
| 146 | pub(crate) const MAX_CACHED_MESH_BYTES: u64 = 128 * 1024 * 1024; |
| 147 | /// Most main-pass depth targets pooled across distinct `Renderer3D` sizes. |
| 148 | const DEPTH_CACHE_CAP: usize = 8; |
| 149 | |
| 150 | /// Content-based key (64-bit hash + byte len + element count + aspect + wireframe) so |
| 151 | /// GPU mesh cache lookups are ABA-safe even after source CPU meshes are dropped. |
| 152 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 153 | struct MeshKey { |
| 154 | content_hash: u64, |
| 155 | byte_len: usize, |
| 156 | elem_count: usize, |
| 157 | aspect_bits: u32, |
| 158 | wireframe: bool, |
| 159 | } |
| 160 | |
| 161 | #[derive(Clone)] |
| 162 | struct GpuMesh { |
| 163 | vbuf: wgpu::Buffer, |
| 164 | ibuf: wgpu::Buffer, |
| 165 | idx_count: u32, |
| 166 | vbuf_bytes: u64, |
| 167 | ibuf_bytes: u64, |
| 168 | } |
| 169 | |
| 170 | /// Bounded map evicting the least recently used entry by count and optional byte budget. |
| 171 | struct Lru<K, V> { |
| 172 | cap: usize, |
| 173 | max_bytes: u64, |
| 174 | total_bytes: u64, |
| 175 | size_fn: fn(&V) -> u64, |
| 176 | tick: u64, |
| 177 | entries: HashMap<K, (u64, V)>, |
| 178 | } |
| 179 | |
| 180 | impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> { |
| 181 | fn new(cap: usize) -> Self { |
| 182 | Self::with_byte_cap(cap, u64::MAX, |_| 0) |
| 183 | } |
| 184 | |
| 185 | fn with_byte_cap(cap: usize, max_bytes: u64, size_fn: fn(&V) -> u64) -> Self { |
| 186 | Self { cap, max_bytes, total_bytes: 0, size_fn, tick: 0, entries: HashMap::new() } |
| 187 | } |
| 188 | |
| 189 | fn get(&mut self, key: K) -> Option<V> { |
| 190 | self.tick += 1; |
| 191 | if let Some((used, v)) = self.entries.get_mut(&key) { |
| 192 | *used = self.tick; |
| 193 | Some(v.clone()) |
| 194 | } else { |
| 195 | None |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> V { |
| 200 | self.tick += 1; |
| 201 | if let Some((used, v)) = self.entries.get_mut(&key) { |
| 202 | *used = self.tick; |
| 203 | return v.clone(); |
| 204 | } |
| 205 | let v = make(); |
| 206 | let new_bytes = (self.size_fn)(&v); |
| 207 | if self.cap == 0 || new_bytes > self.max_bytes { |
| 208 | return v; |
| 209 | } |
| 210 | while !self.entries.is_empty() |
| 211 | && (self.entries.len() >= self.cap |
| 212 | || self.total_bytes.saturating_add(new_bytes) > self.max_bytes) |
| 213 | { |
| 214 | let Some(oldest) = self.entries.iter().min_by_key(|(_, (used, _))| *used).map(|(k, _)| *k) else { |
| 215 | break; |
| 216 | }; |
| 217 | if let Some((_, evicted)) = self.entries.remove(&oldest) { |
| 218 | self.total_bytes = self.total_bytes.saturating_sub((self.size_fn)(&evicted)); |
| 219 | } |
| 220 | } |
| 221 | self.total_bytes = self.total_bytes.saturating_add(new_bytes); |
| 222 | self.entries.insert(key, (self.tick, v.clone())); |
| 223 | v |
| 224 | } |
| 225 | |
| 226 | fn clear(&mut self) { |
| 227 | self.entries.clear(); |
| 228 | self.total_bytes = 0; |
| 229 | self.tick = 0; |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | #[derive(Clone)] |
| 234 | pub struct CameraInstance { |
| 235 | /// Node name, matched against a renderer's `CameraSelector`. |
| 236 | pub name: String, |
| 237 | pub orthographic: bool, |
| 238 | pub world: Mat4, |
| 239 | pub vfov_rad: f32, |
| 240 | pub near: f32, |
| 241 | pub far: f32, |
| 242 | /// `SphericalCamera3D` lat-long layout; the camera is orthographic over pre-warped geometry. |
| 243 | pub spherical: Option<projection::Spherical>, |
| 244 | } |
| 245 | |
| 246 | #[derive(Clone, Debug)] |
| 247 | pub enum ShapeKind { |
| 248 | ImagePlane, |
| 249 | Sphere { radius: f32, sub_base: u32, sub_height: u32 }, |
| 250 | Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32, sub_height: u32, top_cap: bool, bottom_cap: bool }, |
| 251 | Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, |
| 252 | /// Uniform cube with `sub` cells per edge; `faces` is a bitmask over `CUBE_FACES` order. |
| 253 | Cube { width: f32, sub: u32, faces: u8 }, |
| 254 | TextPlate { width: f32, height: f32, depth: f32, slices: u32 }, |
| 255 | CustomMesh(Arc<Vec<Vertex3D>>), |
| 256 | /// Carries the material's UV transform and bump parameters through `DrawMesh`. |
| 257 | WithMaterialFx { inner: Box<ShapeKind>, fx: MaterialFx }, |
| 258 | } |
| 259 | |
| 260 | /// Face order shared by `Cube3D` material inputs and `build_cube`. |
| 261 | pub const CUBE_FACES: [&str; 6] = ["Front", "Back", "Right", "Left", "Top", "Bottom"]; |
| 262 | |
| 263 | /// Affine map from mesh UV (V down) to texture UV: `uv' = m * uv + t`, `m` column-major. |
| 264 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 265 | pub struct UvAffine { |
| 266 | pub m: [f32; 4], |
| 267 | pub t: [f32; 2], |
| 268 | } |
| 269 | |
| 270 | impl UvAffine { |
| 271 | pub const IDENTITY: Self = Self { m: [1.0, 0.0, 0.0, 1.0], t: [0.0, 0.0] }; |
| 272 | |
| 273 | pub fn apply(&self, uv: [f32; 2]) -> [f32; 2] { |
| 274 | [ |
| 275 | self.m[0] * uv[0] + self.m[2] * uv[1] + self.t[0], |
| 276 | self.m[1] * uv[0] + self.m[3] * uv[1] + self.t[1], |
| 277 | ] |
| 278 | } |
| 279 | |
| 280 | /// The map applying `self` first, then `outer`. |
| 281 | pub fn then(&self, outer: &Self) -> Self { |
| 282 | let o = outer.apply(self.t); |
| 283 | Self { |
| 284 | m: [ |
| 285 | outer.m[0] * self.m[0] + outer.m[2] * self.m[1], |
| 286 | outer.m[1] * self.m[0] + outer.m[3] * self.m[1], |
| 287 | outer.m[0] * self.m[2] + outer.m[2] * self.m[3], |
| 288 | outer.m[1] * self.m[2] + outer.m[3] * self.m[3], |
| 289 | ], |
| 290 | t: o, |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | pub fn hash_into(&self, h: &mut impl std::hash::Hasher) { |
| 295 | use std::hash::Hash; |
| 296 | for v in self.m { |
| 297 | v.to_bits().hash(h); |
| 298 | } |
| 299 | for v in self.t { |
| 300 | v.to_bits().hash(h); |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | /// Specular lobe of a material; `MeshInstance::specular_exponent` is the exponent for |
| 306 | /// `Blinn`/`Phong`, the roughness for `CookTorrance`, and `SpreadU` for `Ward`. |
| 307 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 308 | pub enum SpecModel { |
| 309 | #[default] |
| 310 | Blinn, |
| 311 | Phong, |
| 312 | CookTorrance, |
| 313 | /// `EnablePBRMaterial`: diffuse-only lights at 1/pi, no specular lobe. |
| 314 | Pbr, |
| 315 | /// Anisotropic Ward BRDF (`MtlWard`). |
| 316 | Ward, |
| 317 | /// `MtlPBRUber` metal/roughness BRDF; parameters live in `SurfaceFx::pbr`. |
| 318 | PbrUber, |
| 319 | } |
| 320 | |
| 321 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 322 | pub struct MaterialFx { |
| 323 | pub uv: UvAffine, |
| 324 | /// 0 = clamp, 1 = wrap, 2 = mirror |
| 325 | pub uv_wrap: u32, |
| 326 | pub bump_scale: f32, |
| 327 | /// 0 = height map, 1 = normal map |
| 328 | pub bump_mode: u32, |
| 329 | /// The bound texture only perturbs normals; it does not color the surface. |
| 330 | pub bump_only: bool, |
| 331 | pub bump_uv: UvAffine, |
| 332 | /// 0 = clamp, 1 = wrap, 2 = mirror |
| 333 | pub bump_wrap: u32, |
| 334 | pub bump_clamp_z: f32, |
| 335 | /// 0=Luminance, 1=Average, 2=Max, 3=Min, 4=Red, 5=Green, 6=Blue, 7=Alpha |
| 336 | pub bump_channel: u32, |
| 337 | pub spec_model: SpecModel, |
| 338 | /// Draw the mesh edges as lines instead of filled triangles. |
| 339 | pub wireframe: bool, |
| 340 | pub cull_back: bool, |
| 341 | pub cull_front: bool, |
| 342 | /// Unlit surface that Fusion draws once per light, so it brightens with the light count. |
| 343 | pub per_light_unlit: bool, |
| 344 | /// `Diffuse.Color.Alpha`: modulates output alpha independently of `Diffuse.Opacity`. |
| 345 | pub diffuse_color_alpha: f32, |
| 346 | /// `MtlCookTorrance` `Specular.RefractiveIndex` (used when `do_fresnel` is true). |
| 347 | pub refractive_index: f32, |
| 348 | /// `MtlCookTorrance` `Specular.DoFresnel` toggle. |
| 349 | pub do_fresnel: bool, |
| 350 | /// `MtlWard` `Specular.SpreadV` anisotropic roughness along V. |
| 351 | pub ward_spread_v: f32, |
| 352 | /// Environment shading mode: `0 = none`, `1 = standalone SphereMap`, `2 = MtlReflect`. |
| 353 | pub env_mode: u32, |
| 354 | /// `0 = equirectangular`, `1 = angular`, `2 = vertical cross`, `3 = horizontal cross`, |
| 355 | /// `4 = single cube face`, `5 = image at the mesh UV`. |
| 356 | pub env_map_mode: u32, |
| 357 | /// Texture slot carrying the environment image: `0 = solid/none`, `1 = mat_tex`, `2 = bump_tex`. |
| 358 | pub env_tex_slot: u32, |
| 359 | /// Column-major 3x3 inverse rotation matrix for `SphereMap` direction lookup. |
| 360 | pub env_rot: [f32; 9], |
| 361 | /// `MtlReflect.Reflection.StrengthVariability`: `0 = Constant`, `1 = By Angle`. |
| 362 | pub refl_strength_var: u32, |
| 363 | pub refl_constant_strength: f32, |
| 364 | pub refl_glancing_strength: f32, |
| 365 | pub refl_face_on_strength: f32, |
| 366 | pub refl_falloff: f32, |
| 367 | pub refl_tint: [f32; 3], |
| 368 | pub refl_has_bg: bool, |
| 369 | pub refract_ior: f32, |
| 370 | pub refract_tint: [f32; 3], |
| 371 | /// `MtlChanBool` per-channel boolean evaluation. |
| 372 | pub cb_enabled: bool, |
| 373 | pub cb_ops_a: [u8; 4], |
| 374 | pub cb_ops: [u8; 4], |
| 375 | pub cb_ops_b: [u8; 4], |
| 376 | /// `0 = Model`, `1 = World`, `2 = Eye`. |
| 377 | pub cb_coord_space: u8, |
| 378 | pub sfx: SurfaceFx, |
| 379 | } |
| 380 | |
| 381 | impl Default for MaterialFx { |
| 382 | fn default() -> Self { |
| 383 | Self { |
| 384 | uv: UvAffine::IDENTITY, |
| 385 | uv_wrap: 0, |
| 386 | bump_scale: 0.0, |
| 387 | bump_mode: 0, |
| 388 | bump_only: false, |
| 389 | bump_uv: UvAffine::IDENTITY, |
| 390 | bump_wrap: 0, |
| 391 | bump_clamp_z: 0.0, |
| 392 | bump_channel: 0, |
| 393 | spec_model: SpecModel::Blinn, |
| 394 | wireframe: false, |
| 395 | cull_back: false, |
| 396 | cull_front: false, |
| 397 | per_light_unlit: false, |
| 398 | diffuse_color_alpha: 1.0, |
| 399 | refractive_index: 2.0, |
| 400 | do_fresnel: true, |
| 401 | ward_spread_v: 0.16, |
| 402 | env_mode: 0, |
| 403 | env_map_mode: 0, |
| 404 | env_tex_slot: 0, |
| 405 | env_rot: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], |
| 406 | refl_strength_var: 1, |
| 407 | refl_constant_strength: 1.0, |
| 408 | refl_glancing_strength: 0.8, |
| 409 | refl_face_on_strength: 0.0, |
| 410 | refl_falloff: 2.0, |
| 411 | refl_tint: [1.0, 1.0, 1.0], |
| 412 | refl_has_bg: true, |
| 413 | refract_ior: 1.333, |
| 414 | refract_tint: [1.0, 1.0, 1.0], |
| 415 | cb_enabled: false, |
| 416 | cb_ops_a: [4, 5, 6, 7], |
| 417 | cb_ops: [0, 0, 0, 0], |
| 418 | cb_ops_b: [0, 1, 2, 3], |
| 419 | cb_coord_space: 2, |
| 420 | sfx: SurfaceFx::default(), |
| 421 | } |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | impl MaterialFx { |
| 426 | pub fn hash_into(&self, h: &mut impl std::hash::Hasher) { |
| 427 | use std::hash::Hash; |
| 428 | self.uv.hash_into(h); |
| 429 | self.uv_wrap.hash(h); |
| 430 | self.bump_scale.to_bits().hash(h); |
| 431 | self.bump_mode.hash(h); |
| 432 | self.bump_only.hash(h); |
| 433 | self.bump_uv.hash_into(h); |
| 434 | self.bump_wrap.hash(h); |
| 435 | self.bump_clamp_z.to_bits().hash(h); |
| 436 | self.bump_channel.hash(h); |
| 437 | (self.spec_model as u8).hash(h); |
| 438 | self.wireframe.hash(h); |
| 439 | self.cull_back.hash(h); |
| 440 | self.cull_front.hash(h); |
| 441 | self.per_light_unlit.hash(h); |
| 442 | self.diffuse_color_alpha.to_bits().hash(h); |
| 443 | self.refractive_index.to_bits().hash(h); |
| 444 | self.do_fresnel.hash(h); |
| 445 | self.ward_spread_v.to_bits().hash(h); |
| 446 | self.env_mode.hash(h); |
| 447 | self.env_map_mode.hash(h); |
| 448 | self.env_tex_slot.hash(h); |
| 449 | for v in self.env_rot { |
| 450 | v.to_bits().hash(h); |
| 451 | } |
| 452 | self.refl_strength_var.hash(h); |
| 453 | self.refl_constant_strength.to_bits().hash(h); |
| 454 | self.refl_glancing_strength.to_bits().hash(h); |
| 455 | self.refl_face_on_strength.to_bits().hash(h); |
| 456 | self.refl_falloff.to_bits().hash(h); |
| 457 | for v in self.refl_tint { |
| 458 | v.to_bits().hash(h); |
| 459 | } |
| 460 | self.refl_has_bg.hash(h); |
| 461 | self.refract_ior.to_bits().hash(h); |
| 462 | for v in self.refract_tint { |
| 463 | v.to_bits().hash(h); |
| 464 | } |
| 465 | self.cb_enabled.hash(h); |
| 466 | self.cb_ops_a.hash(h); |
| 467 | self.cb_ops.hash(h); |
| 468 | self.cb_ops_b.hash(h); |
| 469 | self.cb_coord_space.hash(h); |
| 470 | bytemuck::bytes_of(&self.sfx).hash(h); |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | impl ShapeKind { |
| 475 | /// Returns the underlying geometry shape without any `WithMaterialFx` wrapper. |
| 476 | pub fn base_shape(&self) -> &ShapeKind { |
| 477 | self.split_fx().0 |
| 478 | } |
| 479 | |
| 480 | pub fn split_fx(&self) -> (&ShapeKind, MaterialFx) { |
| 481 | match self { |
| 482 | ShapeKind::WithMaterialFx { inner, fx } => (inner.base_shape(), *fx), |
| 483 | other => (other, MaterialFx::default()), |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | pub fn hash_into(&self, h: &mut impl std::hash::Hasher) { |
| 488 | use std::hash::Hash; |
| 489 | match self { |
| 490 | ShapeKind::ImagePlane => 0u8.hash(h), |
| 491 | ShapeKind::Sphere { radius, sub_base, sub_height } => { |
| 492 | 1u8.hash(h); |
| 493 | radius.to_bits().hash(h); |
| 494 | sub_base.hash(h); |
| 495 | sub_height.hash(h); |
| 496 | } |
| 497 | ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base, sub_height, top_cap, bottom_cap } => { |
| 498 | 2u8.hash(h); |
| 499 | sub_height.hash(h); |
| 500 | (*top_cap, *bottom_cap).hash(h); |
| 501 | radius.to_bits().hash(h); |
| 502 | height.to_bits().hash(h); |
| 503 | start_sweep_deg.to_bits().hash(h); |
| 504 | end_sweep_deg.to_bits().hash(h); |
| 505 | sub_base.hash(h); |
| 506 | } |
| 507 | ShapeKind::Plane { width, height, sub_w, sub_h } => { |
| 508 | 3u8.hash(h); |
| 509 | width.to_bits().hash(h); |
| 510 | height.to_bits().hash(h); |
| 511 | sub_w.hash(h); |
| 512 | sub_h.hash(h); |
| 513 | } |
| 514 | ShapeKind::Cube { width, sub, faces } => { |
| 515 | 4u8.hash(h); |
| 516 | width.to_bits().hash(h); |
| 517 | sub.hash(h); |
| 518 | faces.hash(h); |
| 519 | } |
| 520 | ShapeKind::TextPlate { width, height, depth, slices } => { |
| 521 | 5u8.hash(h); |
| 522 | width.to_bits().hash(h); |
| 523 | height.to_bits().hash(h); |
| 524 | depth.to_bits().hash(h); |
| 525 | slices.hash(h); |
| 526 | } |
| 527 | ShapeKind::CustomMesh(verts) => { |
| 528 | 6u8.hash(h); |
| 529 | verts.len().hash(h); |
| 530 | let step = (verts.len() / 64).max(1); |
| 531 | for v in verts.iter().step_by(step) { |
| 532 | bytemuck::bytes_of(v).hash(h); |
| 533 | } |
| 534 | } |
| 535 | ShapeKind::WithMaterialFx { inner, fx } => { |
| 536 | 7u8.hash(h); |
| 537 | inner.hash_into(h); |
| 538 | fx.hash_into(h); |
| 539 | } |
| 540 | } |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | #[derive(Clone, Debug)] |
| 545 | pub struct Displace3DSpec { |
| 546 | pub input_node: NodeId, |
| 547 | pub scale: f32, |
| 548 | pub bias: f32, |
| 549 | pub channel: i32, // 0=Luma (default), 1=R, 2=G, 3=B, 4=A |
| 550 | } |
| 551 | |
| 552 | #[derive(Clone, Debug)] |
| 553 | pub struct DisplaceHeightmap { |
| 554 | pub size: [u32; 2], |
| 555 | pub rgba: Vec<u8>, |
| 556 | pub scale: f32, |
| 557 | pub bias: f32, |
| 558 | pub channel: i32, |
| 559 | } |
| 560 | |
| 561 | #[derive(Clone, Debug)] |
| 562 | pub struct Text3DSpec { |
| 563 | pub node_id: NodeId, |
| 564 | } |
| 565 | |
| 566 | #[derive(Clone)] |
| 567 | pub struct MeshInstance { |
| 568 | pub world: Mat4, |
| 569 | pub shape: ShapeKind, |
| 570 | pub material_node: Option<NodeId>, |
| 571 | pub bump_node: Option<NodeId>, |
| 572 | pub text3d: Option<Text3DSpec>, |
| 573 | pub diffuse_col: [f32; 4], |
| 574 | pub specular_col: [f32; 3], |
| 575 | pub specular_intensity: f32, |
| 576 | pub specular_exponent: f32, |
| 577 | pub affected_by_lights: bool, |
| 578 | pub casts_shadow: bool, |
| 579 | pub receives_shadows: bool, |
| 580 | pub flip_normals: bool, |
| 581 | pub displace: Option<Displace3DSpec>, |
| 582 | } |
| 583 | |
| 584 | #[derive(Clone, Copy, Debug)] |
| 585 | pub struct PointLight { |
| 586 | pub pos: [f32; 3], |
| 587 | pub color: [f32; 3], |
| 588 | /// 0 = none, 1 = linear (1/d), 2 = quadratic (1/d²) |
| 589 | pub decay_type: f32, |
| 590 | /// Unused by the shader; `Renderer3D` still folds it into its cache key. |
| 591 | pub decay_rate: f32, |
| 592 | /// Shadow density in `0..=1` when the light casts shadows. |
| 593 | pub shadow_density: Option<f32>, |
| 594 | } |
| 595 | |
| 596 | #[derive(Clone, Copy, Debug)] |
| 597 | pub struct SpotLight { |
| 598 | pub pos: [f32; 3], |
| 599 | pub dir: [f32; 3], |
| 600 | pub color: [f32; 3], |
| 601 | pub cos_inner: f32, |
| 602 | pub cos_outer: f32, |
| 603 | pub decay_type: f32, |
| 604 | } |
| 605 | |
| 606 | #[derive(Clone, Copy, Debug)] |
| 607 | pub struct DirLight { |
| 608 | pub to_light: [f32; 3], |
| 609 | pub color: [f32; 3], |
| 610 | } |
| 611 | |
| 612 | #[derive(Clone, Debug, Default)] |
| 613 | pub struct SceneLights { |
| 614 | pub ambient: [f32; 3], |
| 615 | /// Only the first `MAX_DIR_LIGHTS` reach the shader. |
| 616 | pub dirs: Vec<DirLight>, |
| 617 | pub points: Vec<PointLight>, |
| 618 | pub spots: Vec<SpotLight>, |
| 619 | /// Enabled light nodes of every kind, including black ones. |
| 620 | pub count: u32, |
| 621 | } |
| 622 | |
| 623 | pub struct DrawMesh { |
| 624 | pub world: Mat4, |
| 625 | pub shape: ShapeKind, |
| 626 | /// Optional deterministic content key for `ShapeKind::CustomMesh` so GPU mesh LRU avoids pointer hashing. |
| 627 | pub custom_mesh_key: Option<u64>, |
| 628 | pub tex: Option<CachedTexture>, |
| 629 | pub bump_tex: Option<CachedTexture>, |
| 630 | pub diffuse_col: [f32; 4], |
| 631 | pub specular_col: [f32; 3], |
| 632 | pub specular_intensity: f32, |
| 633 | pub specular_exponent: f32, |
| 634 | pub affected_by_lights: bool, |
| 635 | pub casts_shadow: bool, |
| 636 | pub receives_shadows: bool, |
| 637 | pub flip_normals: bool, |
| 638 | pub displace: Option<DisplaceHeightmap>, |
| 639 | } |
| 640 | |
| 641 | fn mesh_key(base_shape: &ShapeKind, custom_mesh_key: Option<u64>, aspect: f32, wireframe: bool) -> MeshKey { |
| 642 | use std::hash::{DefaultHasher, Hash, Hasher}; |
| 643 | let mut h = DefaultHasher::new(); |
| 644 | let (byte_len, elem_count) = match base_shape { |
| 645 | ShapeKind::CustomMesh(verts) => { |
| 646 | let elems = verts.len(); |
| 647 | let bytes = std::mem::size_of_val(verts.as_slice()); |
| 648 | 6u8.hash(&mut h); |
| 649 | elems.hash(&mut h); |
| 650 | bytes.hash(&mut h); |
| 651 | if let Some(ck) = custom_mesh_key { |
| 652 | ck.hash(&mut h); |
| 653 | } else { |
| 654 | h.write(bytemuck::cast_slice(verts.as_slice())); |
| 655 | } |
| 656 | (bytes, elems) |
| 657 | } |
| 658 | _ => { |
| 659 | base_shape.hash_into(&mut h); |
| 660 | (0, 0) |
| 661 | } |
| 662 | }; |
| 663 | let aspect_bits = if matches!(base_shape, ShapeKind::ImagePlane) { aspect.to_bits() } else { 0 }; |
| 664 | MeshKey { |
| 665 | content_hash: h.finish(), |
| 666 | byte_len, |
| 667 | elem_count, |
| 668 | aspect_bits, |
| 669 | wireframe, |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | /// Returns the local-space centroid of partial `Cube` face subsets so separate face |
| 674 | /// material groups sort front-to-back / back-to-front by their true face depth. |
| 675 | fn shape_local_center(shape: &ShapeKind) -> [f32; 3] { |
| 676 | let ShapeKind::Cube { width, faces, .. } = shape.base_shape() else { |
| 677 | return [0.0; 3]; |
| 678 | }; |
| 679 | let mask = *faces & 0b11_1111; |
| 680 | if mask == 0 || mask == 0b11_1111 { |
| 681 | return [0.0; 3]; |
| 682 | } |
| 683 | let hw = width * 0.5; |
| 684 | let face_centers: [[f32; 3]; 6] = [ |
| 685 | [0.0, 0.0, hw], |
| 686 | [0.0, 0.0, -hw], |
| 687 | [hw, 0.0, 0.0], |
| 688 | [-hw, 0.0, 0.0], |
| 689 | [0.0, hw, 0.0], |
| 690 | [0.0, -hw, 0.0], |
| 691 | ]; |
| 692 | let mut sum = [0.0_f32; 3]; |
| 693 | let mut count = 0u32; |
| 694 | for (i, c) in face_centers.iter().enumerate() { |
| 695 | if mask & (1 << i) != 0 { |
| 696 | sum[0] += c[0]; |
| 697 | sum[1] += c[1]; |
| 698 | sum[2] += c[2]; |
| 699 | count += 1; |
| 700 | } |
| 701 | } |
| 702 | let inv = 1.0 / (count.max(1) as f32); |
| 703 | [sum[0] * inv, sum[1] * inv, sum[2] * inv] |
| 704 | } |
| 705 | |
| 706 | /// View-projections of the six 90 degree faces (`+X -X +Y -Y +Z -Z`) around `eye`. |
| 707 | fn cube_face_view_projections(eye: [f32; 3], far: f32) -> [Mat4; 6] { |
| 708 | let proj = mat4_perspective_wgpu(std::f32::consts::FRAC_PI_2, 1.0, 0.01, far); |
| 709 | [ |
| 710 | ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), |
| 711 | ([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), |
| 712 | ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0]), |
| 713 | ([0.0, -1.0, 0.0], [0.0, 0.0, 1.0]), |
| 714 | ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]), |
| 715 | ([0.0, 0.0, -1.0], [0.0, 1.0, 0.0]), |
| 716 | ] |
| 717 | .map(|(f, up)| { |
| 718 | let right = [f[1] * up[2] - f[2] * up[1], f[2] * up[0] - f[0] * up[2], f[0] * up[1] - f[1] * up[0]]; |
| 719 | let up = [right[1] * f[2] - right[2] * f[1], right[2] * f[0] - right[0] * f[2], right[0] * f[1] - right[1] * f[0]]; |
| 720 | let dot = |a: [f32; 3]| a[0] * eye[0] + a[1] * eye[1] + a[2] * eye[2]; |
| 721 | let view = [ |
| 722 | right[0], up[0], -f[0], 0.0, |
| 723 | right[1], up[1], -f[1], 0.0, |
| 724 | right[2], up[2], -f[2], 0.0, |
| 725 | -dot(right), -dot(up), dot(f), 1.0, |
| 726 | ]; |
| 727 | mat4_mul(proj, view) |
| 728 | }) |
| 729 | } |
| 730 | |
| 731 | impl Scene3DRenderer { |
| 732 | pub fn new(device: &wgpu::Device) -> Self { |
| 733 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 734 | label: Some("scene3d-shader"), |
| 735 | source: wgpu::ShaderSource::Wgsl( |
| 736 | format!("{UV_XFORM_WGSL}{SHADER_3D}{SURFACE_FX_WGSL}{}", fx::simplex_wgsl()) |
| 737 | .replace("MAX_SHADOW_LIGHTS", &MAX_SHADOW_LIGHTS.to_string()) |
| 738 | .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string()) |
| 739 | .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()) |
| 740 | .replace("SHADOW_MAP_SIZE", &SHADOW_MAP_SIZE.to_string()) |
| 741 | .into(), |
| 742 | ), |
| 743 | }); |
| 744 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 745 | label: Some("scene3d-bgl"), |
| 746 | entries: &[ |
| 747 | wgpu::BindGroupLayoutEntry { |
| 748 | binding: 0, |
| 749 | visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, |
| 750 | ty: wgpu::BindingType::Buffer { |
| 751 | ty: wgpu::BufferBindingType::Uniform, |
| 752 | has_dynamic_offset: true, |
| 753 | min_binding_size: std::num::NonZeroU64::new(std::mem::size_of::<MeshUniform>() as u64), |
| 754 | }, |
| 755 | count: None, |
| 756 | }, |
| 757 | wgpu::BindGroupLayoutEntry { |
| 758 | binding: 1, |
| 759 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 760 | ty: wgpu::BindingType::Texture { |
| 761 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, |
| 762 | view_dimension: wgpu::TextureViewDimension::D2, |
| 763 | multisampled: false, |
| 764 | }, |
| 765 | count: None, |
| 766 | }, |
| 767 | wgpu::BindGroupLayoutEntry { |
| 768 | binding: 2, |
| 769 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 770 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), |
| 771 | count: None, |
| 772 | }, |
| 773 | wgpu::BindGroupLayoutEntry { |
| 774 | binding: 3, |
| 775 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 776 | ty: wgpu::BindingType::Buffer { |
| 777 | ty: wgpu::BufferBindingType::Uniform, |
| 778 | has_dynamic_offset: false, |
| 779 | min_binding_size: None, |
| 780 | }, |
| 781 | count: None, |
| 782 | }, |
| 783 | wgpu::BindGroupLayoutEntry { |
| 784 | binding: 4, |
| 785 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 786 | ty: wgpu::BindingType::Texture { |
| 787 | sample_type: wgpu::TextureSampleType::Float { filterable: false }, |
| 788 | view_dimension: wgpu::TextureViewDimension::D2Array, |
| 789 | multisampled: false, |
| 790 | }, |
| 791 | count: None, |
| 792 | }, |
| 793 | wgpu::BindGroupLayoutEntry { |
| 794 | binding: 5, |
| 795 | visibility: wgpu::ShaderStages::FRAGMENT, |
| 796 | ty: wgpu::BindingType::Texture { |
| 797 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, |
| 798 | view_dimension: wgpu::TextureViewDimension::D2, |
| 799 | multisampled: false, |
| 800 | }, |
| 801 | count: None, |
| 802 | }, |
| 803 | ], |
| 804 | }); |
| 805 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 806 | label: Some("scene3d-pl"), |
| 807 | bind_group_layouts: &[Some(&bgl)], |
| 808 | immediate_size: 0, |
| 809 | }); |
| 810 | let vbuf_layout = wgpu::VertexBufferLayout { |
| 811 | array_stride: std::mem::size_of::<Vertex3D>() as u64, |
| 812 | step_mode: wgpu::VertexStepMode::Vertex, |
| 813 | attributes: &[ |
| 814 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 }, |
| 815 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 12, shader_location: 1 }, |
| 816 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 }, |
| 817 | ], |
| 818 | }; |
| 819 | let make_pipeline = |topology: wgpu::PrimitiveTopology, |
| 820 | cull_slot: usize, |
| 821 | fs_entry: &'static str, |
| 822 | target_format: wgpu::TextureFormat, |
| 823 | blend: Option<wgpu::BlendState>| { |
| 824 | device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { |
| 825 | label: Some("scene3d-mesh"), |
| 826 | layout: Some(&pl), |
| 827 | vertex: wgpu::VertexState { |
| 828 | module: &shader, |
| 829 | entry_point: Some("vs_mesh"), |
| 830 | compilation_options: Default::default(), |
| 831 | buffers: &[Some(vbuf_layout.clone())], |
| 832 | }, |
| 833 | fragment: Some(wgpu::FragmentState { |
| 834 | module: &shader, |
| 835 | entry_point: Some(fs_entry), |
| 836 | compilation_options: wgpu::PipelineCompilationOptions { |
| 837 | constants: &[("DRAW_BACK", f64::from(u8::from(cull_slot & 1 == 0))), ("DRAW_FRONT", f64::from(u8::from(cull_slot & 2 == 0)))], |
| 838 | ..Default::default() |
| 839 | }, |
| 840 | targets: &[Some(wgpu::ColorTargetState { |
| 841 | format: target_format, |
| 842 | blend, |
| 843 | write_mask: wgpu::ColorWrites::ALL, |
| 844 | })], |
| 845 | }), |
| 846 | primitive: wgpu::PrimitiveState { |
| 847 | topology, |
| 848 | cull_mode: None, |
| 849 | ..Default::default() |
| 850 | }, |
| 851 | depth_stencil: Some(wgpu::DepthStencilState { |
| 852 | format: wgpu::TextureFormat::Depth32Float, |
| 853 | depth_write_enabled: Some(true), |
| 854 | depth_compare: Some(wgpu::CompareFunction::Less), |
| 855 | stencil: wgpu::StencilState::default(), |
| 856 | bias: wgpu::DepthBiasState::default(), |
| 857 | }), |
| 858 | multisample: wgpu::MultisampleState::default(), |
| 859 | multiview_mask: None, |
| 860 | cache: None, |
| 861 | }) |
| 862 | }; |
| 863 | let pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList] |
| 864 | .map(|topology| { |
| 865 | std::array::from_fn(|i| { |
| 866 | make_pipeline(topology, i, "fs_mesh", wgpu::TextureFormat::Rgba8Unorm, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING)) |
| 867 | }) |
| 868 | }); |
| 869 | let normal_pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList] |
| 870 | .map(|topology| std::array::from_fn(|i| make_pipeline(topology, i, "fs_normal", wgpu::TextureFormat::Rgba16Float, None))); |
| 871 | let depth_z_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 872 | label: Some("scene3d-depth-z-shader"), |
| 873 | source: wgpu::ShaderSource::Wgsl(DEPTH_TO_EYE_Z_SHADER.into()), |
| 874 | }); |
| 875 | let depth_z_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 876 | label: Some("scene3d-depth-z-bgl"), |
| 877 | entries: &[ |
| 878 | wgpu::BindGroupLayoutEntry { |
| 879 | binding: 0, |
| 880 | visibility: wgpu::ShaderStages::COMPUTE, |
| 881 | ty: wgpu::BindingType::Texture { |
| 882 | sample_type: wgpu::TextureSampleType::Depth, |
| 883 | view_dimension: wgpu::TextureViewDimension::D2, |
| 884 | multisampled: false, |
| 885 | }, |
| 886 | count: None, |
| 887 | }, |
| 888 | wgpu::BindGroupLayoutEntry { |
| 889 | binding: 1, |
| 890 | visibility: wgpu::ShaderStages::COMPUTE, |
| 891 | ty: wgpu::BindingType::StorageTexture { |
| 892 | access: wgpu::StorageTextureAccess::WriteOnly, |
| 893 | format: wgpu::TextureFormat::R32Float, |
| 894 | view_dimension: wgpu::TextureViewDimension::D2, |
| 895 | }, |
| 896 | count: None, |
| 897 | }, |
| 898 | wgpu::BindGroupLayoutEntry { |
| 899 | binding: 2, |
| 900 | visibility: wgpu::ShaderStages::COMPUTE, |
| 901 | ty: wgpu::BindingType::Buffer { |
| 902 | ty: wgpu::BufferBindingType::Uniform, |
| 903 | has_dynamic_offset: false, |
| 904 | min_binding_size: std::num::NonZeroU64::new( |
| 905 | std::mem::size_of::<DepthToEyeZUniform>() as u64, |
| 906 | ), |
| 907 | }, |
| 908 | count: None, |
| 909 | }, |
| 910 | ], |
| 911 | }); |
| 912 | let depth_z_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 913 | label: Some("scene3d-depth-z-pl"), |
| 914 | bind_group_layouts: &[Some(&depth_z_bgl)], |
| 915 | immediate_size: 0, |
| 916 | }); |
| 917 | let depth_z_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 918 | label: Some("scene3d-depth-to-eye-z"), |
| 919 | layout: Some(&depth_z_pl), |
| 920 | module: &depth_z_shader, |
| 921 | entry_point: Some("depth_to_eye_z"), |
| 922 | compilation_options: Default::default(), |
| 923 | cache: None, |
| 924 | }); |
| 925 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { |
| 926 | label: Some("scene3d-linear"), |
| 927 | address_mode_u: wgpu::AddressMode::ClampToEdge, |
| 928 | address_mode_v: wgpu::AddressMode::ClampToEdge, |
| 929 | mag_filter: wgpu::FilterMode::Linear, |
| 930 | min_filter: wgpu::FilterMode::Linear, |
| 931 | mipmap_filter: wgpu::MipmapFilterMode::Linear, |
| 932 | ..Default::default() |
| 933 | }); |
| 934 | let shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 935 | label: Some("scene3d-shadow-shader"), |
| 936 | source: wgpu::ShaderSource::Wgsl(SHADOW_SHADER.into()), |
| 937 | }); |
| 938 | let dynamic_uniform = |binding| wgpu::BindGroupLayoutEntry { |
| 939 | binding, |
| 940 | visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, |
| 941 | ty: wgpu::BindingType::Buffer { |
| 942 | ty: wgpu::BufferBindingType::Uniform, |
| 943 | has_dynamic_offset: true, |
| 944 | min_binding_size: None, |
| 945 | }, |
| 946 | count: None, |
| 947 | }; |
| 948 | let shadow_caster_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 949 | label: Some("scene3d-shadow-caster-bgl"), |
| 950 | entries: &[dynamic_uniform(0)], |
| 951 | }); |
| 952 | let shadow_face_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 953 | label: Some("scene3d-shadow-face-bgl"), |
| 954 | entries: &[dynamic_uniform(0)], |
| 955 | }); |
| 956 | let shadow_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 957 | label: Some("scene3d-shadow-pl"), |
| 958 | bind_group_layouts: &[Some(&shadow_caster_bgl), Some(&shadow_face_bgl)], |
| 959 | immediate_size: 0, |
| 960 | }); |
| 961 | let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { |
| 962 | label: Some("scene3d-shadow"), |
| 963 | layout: Some(&shadow_pl), |
| 964 | vertex: wgpu::VertexState { |
| 965 | module: &shadow_shader, |
| 966 | entry_point: Some("vs_shadow"), |
| 967 | compilation_options: Default::default(), |
| 968 | buffers: &[Some(vbuf_layout)], |
| 969 | }, |
| 970 | fragment: Some(wgpu::FragmentState { |
| 971 | module: &shadow_shader, |
| 972 | entry_point: Some("fs_shadow"), |
| 973 | compilation_options: Default::default(), |
| 974 | targets: &[Some(wgpu::ColorTargetState { |
| 975 | format: wgpu::TextureFormat::R32Float, |
| 976 | blend: None, |
| 977 | write_mask: wgpu::ColorWrites::ALL, |
| 978 | })], |
| 979 | }), |
| 980 | primitive: wgpu::PrimitiveState::default(), |
| 981 | depth_stencil: Some(wgpu::DepthStencilState { |
| 982 | format: wgpu::TextureFormat::Depth32Float, |
| 983 | depth_write_enabled: Some(true), |
| 984 | depth_compare: Some(wgpu::CompareFunction::Less), |
| 985 | stencil: wgpu::StencilState::default(), |
| 986 | bias: wgpu::DepthBiasState::default(), |
| 987 | }), |
| 988 | multisample: wgpu::MultisampleState::default(), |
| 989 | multiview_mask: None, |
| 990 | cache: None, |
| 991 | }); |
| 992 | let shadow_dummy = device |
| 993 | .create_texture(&wgpu::TextureDescriptor { |
| 994 | label: Some("scene3d-shadow-dummy"), |
| 995 | size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, |
| 996 | mip_level_count: 1, |
| 997 | sample_count: 1, |
| 998 | dimension: wgpu::TextureDimension::D2, |
| 999 | format: wgpu::TextureFormat::R32Float, |
| 1000 | usage: wgpu::TextureUsages::TEXTURE_BINDING, |
| 1001 | view_formats: &[], |
| 1002 | }) |
| 1003 | .create_view(&wgpu::TextureViewDescriptor { |
| 1004 | dimension: Some(wgpu::TextureViewDimension::D2Array), |
| 1005 | ..Default::default() |
| 1006 | }); |
| 1007 | let shadow_dummy_uni = ShadowUniform { |
| 1008 | face_vp: [mat4_identity(); 6 * MAX_SHADOW_LIGHTS], |
| 1009 | point: [[-1.0, 0.0, 0.0, 0.0]; MAX_LIGHTS], |
| 1010 | }; |
| 1011 | let shadow_dummy_ubuf = device.create_buffer(&wgpu::BufferDescriptor { |
| 1012 | label: Some("scene3d-shadow-dummy-u"), |
| 1013 | size: std::mem::size_of::<ShadowUniform>() as u64, |
| 1014 | usage: wgpu::BufferUsages::UNIFORM, |
| 1015 | mapped_at_creation: true, |
| 1016 | }); |
| 1017 | shadow_dummy_ubuf |
| 1018 | .slice(..) |
| 1019 | .get_mapped_range_mut() |
| 1020 | .expect("mapped shadow dummy uniform buffer") |
| 1021 | .copy_from_slice(bytemuck::bytes_of(&shadow_dummy_uni)); |
| 1022 | shadow_dummy_ubuf.unmap(); |
| 1023 | Self { |
| 1024 | bgl, |
| 1025 | pipelines, |
| 1026 | normal_pipelines, |
| 1027 | depth_z_bgl, |
| 1028 | depth_z_pipeline, |
| 1029 | sampler, |
| 1030 | meshes: Mutex::new(Lru::with_byte_cap( |
| 1031 | MAX_CACHED_MESH_BUFFERS, |
| 1032 | MAX_CACHED_MESH_BYTES, |
| 1033 | |gm| gm.as_ref().map_or(0, |m| m.vbuf_bytes + m.ibuf_bytes), |
| 1034 | )), |
| 1035 | text3d_mesh_cache: Mutex::new(Lru::new(MAX_CACHED_MESH_BUFFERS)), |
| 1036 | shadow_pipeline, |
| 1037 | shadow_caster_bgl, |
| 1038 | shadow_face_bgl, |
| 1039 | shadow_dummy, |
| 1040 | shadow_dummy_ubuf, |
| 1041 | shadow_targets: Mutex::new(None), |
| 1042 | depth_targets: Mutex::new(Lru::new(DEPTH_CACHE_CAP)), |
| 1043 | uniform_cache: Mutex::new(Lru::with_byte_cap( |
| 1044 | UNIFORM_CACHE_CAP, |
| 1045 | MAX_CACHED_UNIFORM_BYTES, |
| 1046 | |b| b.size(), |
| 1047 | )), |
| 1048 | } |
| 1049 | } |
| 1050 | |
| 1051 | /// Returns a memoized `Text3D` vertex buffer for `key`, building it on miss. |
| 1052 | pub fn get_or_build_text3d_mesh( |
| 1053 | &self, |
| 1054 | key: u64, |
| 1055 | build: impl FnOnce() -> Vec<Vertex3D>, |
| 1056 | ) -> Arc<Vec<Vertex3D>> { |
| 1057 | if let Some(hit) = lock_or_recover(&self.text3d_mesh_cache).get(key) { |
| 1058 | return hit; |
| 1059 | } |
| 1060 | let built = Arc::new(build()); |
| 1061 | lock_or_recover(&self.text3d_mesh_cache) |
| 1062 | .get_or_insert_with(key, || Arc::clone(&built)) |
| 1063 | } |
| 1064 | |
| 1065 | /// Drops cached shadow cube-map targets, main-pass depth targets, memoized `Text3D` CPU meshes, |
| 1066 | /// cached GPU mesh vertex/index buffers, and pooled uniform buffers. |
| 1067 | pub fn clear_shadow_targets(&self) { |
| 1068 | *lock_or_recover(&self.shadow_targets) = None; |
| 1069 | lock_or_recover(&self.depth_targets).clear(); |
| 1070 | lock_or_recover(&self.text3d_mesh_cache).clear(); |
| 1071 | lock_or_recover(&self.meshes).clear(); |
| 1072 | lock_or_recover(&self.uniform_cache).clear(); |
| 1073 | } |
| 1074 | |
| 1075 | /// Drops all pooled 3D render targets (`shadow_targets` and `depth_targets`) and `Text3D` CPU meshes. |
| 1076 | pub fn clear_targets(&self) { |
| 1077 | self.clear_shadow_targets(); |
| 1078 | } |
| 1079 | |
| 1080 | /// Total GPU VRAM in bytes currently occupied by `shadow_targets` (R32Float layers + Depth32Float). |
| 1081 | pub fn shadow_vram_bytes(&self) -> u64 { |
| 1082 | lock_or_recover(&self.shadow_targets).as_ref().map_or(0, |t| { |
| 1083 | let layer_bytes = u64::from(SHADOW_MAP_SIZE) * u64::from(SHADOW_MAP_SIZE) * 4; |
| 1084 | layer_bytes * (u64::from(t.layers) + 1) |
| 1085 | }) |
| 1086 | } |
| 1087 | |
| 1088 | /// Total GPU VRAM in bytes currently occupied by pooled main-pass `Depth32Float` targets. |
| 1089 | pub fn depth_vram_bytes(&self) -> u64 { |
| 1090 | lock_or_recover(&self.depth_targets) |
| 1091 | .entries |
| 1092 | .values() |
| 1093 | .map(|(_, dt)| u64::from(dt.tex.width()) * u64::from(dt.tex.height()) * 4) |
| 1094 | .sum() |
| 1095 | } |
| 1096 | |
| 1097 | /// Total GPU VRAM in bytes currently occupied by cached vertex and index buffers. |
| 1098 | pub fn mesh_vram_bytes(&self) -> u64 { |
| 1099 | lock_or_recover(&self.meshes) |
| 1100 | .entries |
| 1101 | .values() |
| 1102 | .filter_map(|(_, gm)| gm.as_ref()) |
| 1103 | .map(|gm| gm.vbuf_bytes + gm.ibuf_bytes) |
| 1104 | .sum() |
| 1105 | } |
| 1106 | |
| 1107 | /// Total GPU VRAM in bytes currently occupied by cached uniform buffers. |
| 1108 | pub fn uniform_vram_bytes(&self) -> u64 { |
| 1109 | lock_or_recover(&self.uniform_cache).total_bytes |
| 1110 | } |
| 1111 | |
| 1112 | #[cfg(test)] |
| 1113 | pub(crate) fn gpu_mesh_count(&self) -> usize { |
| 1114 | lock_or_recover(&self.meshes).entries.len() |
| 1115 | } |
| 1116 | |
| 1117 | /// Attaches empty sky auxiliary channels (`EMPTY_Z_SENTINEL` for Z, `(0,0,0,0)` for Normal) |
| 1118 | /// when a `Renderer3D` exits early (e.g. disconnected `SceneInput` or invalid clip planes). |
| 1119 | pub fn attach_empty_aux( |
| 1120 | device: &wgpu::Device, |
| 1121 | queue: &wgpu::Queue, |
| 1122 | dst: &mut CachedTexture, |
| 1123 | want_z: bool, |
| 1124 | want_normal: bool, |
| 1125 | ) { |
| 1126 | if !want_z && !want_normal { |
| 1127 | return; |
| 1128 | } |
| 1129 | let size = [dst.size[0].max(1), dst.size[1].max(1)]; |
| 1130 | let mut aux = dst.aux_cloned(); |
| 1131 | if want_z { |
| 1132 | let z_tex = AuxChannelTex::new(device, size, wgpu::TextureFormat::R32Float, "scene3d-aux-z"); |
| 1133 | let data = vec![EMPTY_Z_SENTINEL; (z_tex.size[0] as usize) * (z_tex.size[1] as usize)]; |
| 1134 | queue.write_texture( |
| 1135 | z_tex.texture.as_image_copy(), |
| 1136 | bytemuck::cast_slice(&data), |
| 1137 | wgpu::TexelCopyBufferLayout { |
| 1138 | offset: 0, |
| 1139 | bytes_per_row: Some(z_tex.size[0] * 4), |
| 1140 | rows_per_image: Some(z_tex.size[1]), |
| 1141 | }, |
| 1142 | wgpu::Extent3d { |
| 1143 | width: z_tex.size[0], |
| 1144 | height: z_tex.size[1], |
| 1145 | depth_or_array_layers: 1, |
| 1146 | }, |
| 1147 | ); |
| 1148 | aux.z = Some(z_tex); |
| 1149 | } |
| 1150 | if want_normal { |
| 1151 | let normal_tex = AuxChannelTex::new(device, size, wgpu::TextureFormat::Rgba16Float, "scene3d-aux-normal"); |
| 1152 | let data = vec![0u16; (normal_tex.size[0] as usize) * (normal_tex.size[1] as usize) * 4]; |
| 1153 | queue.write_texture( |
| 1154 | normal_tex.texture.as_image_copy(), |
| 1155 | bytemuck::cast_slice(&data), |
| 1156 | wgpu::TexelCopyBufferLayout { |
| 1157 | offset: 0, |
| 1158 | bytes_per_row: Some(normal_tex.size[0] * 8), |
| 1159 | rows_per_image: Some(normal_tex.size[1]), |
| 1160 | }, |
| 1161 | wgpu::Extent3d { |
| 1162 | width: normal_tex.size[0], |
| 1163 | height: normal_tex.size[1], |
| 1164 | depth_or_array_layers: 1, |
| 1165 | }, |
| 1166 | ); |
| 1167 | aux.normal = Some(normal_tex); |
| 1168 | } |
| 1169 | dst.set_aux(Some(Arc::new(aux))); |
| 1170 | } |
| 1171 | |
| 1172 | #[allow(clippy::too_many_arguments)] |
| 1173 | pub fn render_meshes( |
| 1174 | &self, |
| 1175 | device: &wgpu::Device, |
| 1176 | queue: &wgpu::Queue, |
| 1177 | enc: &mut wgpu::CommandEncoder, |
| 1178 | dst: &CachedTexture, |
| 1179 | dummy: &CachedTexture, |
| 1180 | view_proj: Mat4, |
| 1181 | view: Mat4, |
| 1182 | cam_pos: [f32; 3], |
| 1183 | cam_far: f32, |
| 1184 | lights: SceneLights, |
| 1185 | lighting_enabled: bool, |
| 1186 | shadows_enabled: bool, |
| 1187 | meshes: &[DrawMesh], |
| 1188 | ) { |
| 1189 | let _ = self.render_meshes_inner( |
| 1190 | device, |
| 1191 | queue, |
| 1192 | enc, |
| 1193 | dst, |
| 1194 | dummy, |
| 1195 | view_proj, |
| 1196 | view, |
| 1197 | mat4_identity(), |
| 1198 | cam_pos, |
| 1199 | cam_far, |
| 1200 | lights, |
| 1201 | lighting_enabled, |
| 1202 | shadows_enabled, |
| 1203 | false, |
| 1204 | false, |
| 1205 | meshes, |
| 1206 | ); |
| 1207 | } |
| 1208 | |
| 1209 | #[allow(clippy::too_many_arguments)] |
| 1210 | pub fn render_meshes_with_aux( |
| 1211 | &self, |
| 1212 | device: &wgpu::Device, |
| 1213 | queue: &wgpu::Queue, |
| 1214 | enc: &mut wgpu::CommandEncoder, |
| 1215 | dst: &mut CachedTexture, |
| 1216 | dummy: &CachedTexture, |
| 1217 | view_proj: Mat4, |
| 1218 | view: Mat4, |
| 1219 | proj: Mat4, |
| 1220 | cam_pos: [f32; 3], |
| 1221 | cam_far: f32, |
| 1222 | lights: SceneLights, |
| 1223 | lighting_enabled: bool, |
| 1224 | shadows_enabled: bool, |
| 1225 | want_z: bool, |
| 1226 | want_normal: bool, |
| 1227 | meshes: &[DrawMesh], |
| 1228 | ) { |
| 1229 | if let Some(aux) = self.render_meshes_inner( |
| 1230 | device, |
| 1231 | queue, |
| 1232 | enc, |
| 1233 | dst, |
| 1234 | dummy, |
| 1235 | view_proj, |
| 1236 | view, |
| 1237 | proj, |
| 1238 | cam_pos, |
| 1239 | cam_far, |
| 1240 | lights, |
| 1241 | lighting_enabled, |
| 1242 | shadows_enabled, |
| 1243 | want_z, |
| 1244 | want_normal, |
| 1245 | meshes, |
| 1246 | ) { |
| 1247 | let mut merged = dst.aux_cloned(); |
| 1248 | if aux.z.is_some() { |
| 1249 | merged.z = aux.z; |
| 1250 | } |
| 1251 | if aux.normal.is_some() { |
| 1252 | merged.normal = aux.normal; |
| 1253 | } |
| 1254 | dst.set_aux(Some(Arc::new(merged))); |
| 1255 | } |
| 1256 | } |
| 1257 | |
| 1258 | #[allow(clippy::too_many_arguments)] |
| 1259 | fn render_meshes_inner( |
| 1260 | &self, |
| 1261 | device: &wgpu::Device, |
| 1262 | queue: &wgpu::Queue, |
| 1263 | enc: &mut wgpu::CommandEncoder, |
| 1264 | dst: &CachedTexture, |
| 1265 | dummy: &CachedTexture, |
| 1266 | view_proj: Mat4, |
| 1267 | view: Mat4, |
| 1268 | proj: Mat4, |
| 1269 | cam_pos: [f32; 3], |
| 1270 | cam_far: f32, |
| 1271 | lights: SceneLights, |
| 1272 | lighting_enabled: bool, |
| 1273 | shadows_enabled: bool, |
| 1274 | want_z: bool, |
| 1275 | want_normal: bool, |
| 1276 | meshes: &[DrawMesh], |
| 1277 | ) -> Option<AuxChannels> { |
| 1278 | let depth_size = [dst.size[0].max(1), dst.size[1].max(1)]; |
| 1279 | let depth_target = lock_or_recover(&self.depth_targets).get_or_insert_with(depth_size, || { |
| 1280 | let tex = device.create_texture(&wgpu::TextureDescriptor { |
| 1281 | label: Some("scene3d-depth"), |
| 1282 | size: wgpu::Extent3d { |
| 1283 | width: depth_size[0], |
| 1284 | height: depth_size[1], |
| 1285 | depth_or_array_layers: 1, |
| 1286 | }, |
| 1287 | mip_level_count: 1, |
| 1288 | sample_count: 1, |
| 1289 | dimension: wgpu::TextureDimension::D2, |
| 1290 | format: wgpu::TextureFormat::Depth32Float, |
| 1291 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, |
| 1292 | view_formats: &[], |
| 1293 | }); |
| 1294 | let view = tex.create_view(&wgpu::TextureViewDescriptor::default()); |
| 1295 | DepthTarget { tex, view } |
| 1296 | }); |
| 1297 | let depth_view = &depth_target.view; |
| 1298 | |
| 1299 | // Point-light indices that get a cube shadow map, in slot order. |
| 1300 | let shadow_lights: Vec<usize> = if shadows_enabled { |
| 1301 | (0..lights.points.len().min(MAX_LIGHTS)) |
| 1302 | .filter(|&i| lights.points[i].shadow_density.is_some()) |
| 1303 | .take(MAX_SHADOW_LIGHTS) |
| 1304 | .collect() |
| 1305 | } else { |
| 1306 | Vec::new() |
| 1307 | }; |
| 1308 | let mut shadow_face_vps = [mat4_identity(); 6 * MAX_SHADOW_LIGHTS]; |
| 1309 | let shadow_ubuf_owned = (!shadow_lights.is_empty()).then(|| { |
| 1310 | let mut shadow_uni = ShadowUniform { |
| 1311 | face_vp: [mat4_identity(); 6 * MAX_SHADOW_LIGHTS], |
| 1312 | point: [[-1.0, 0.0, 0.0, 0.0]; MAX_LIGHTS], |
| 1313 | }; |
| 1314 | // Receivers visible to the camera are at most `cam_far` from it, so that bounds the light's reach. |
| 1315 | let distance_to_cam = |p: [f32; 3]| (0..3).map(|i| (p[i] - cam_pos[i]).powi(2)).sum::<f32>().sqrt(); |
| 1316 | for (slot, &li) in shadow_lights.iter().enumerate() { |
| 1317 | let pl = &lights.points[li]; |
| 1318 | let far = cam_far + distance_to_cam(pl.pos); |
| 1319 | let vps = cube_face_view_projections(pl.pos, far); |
| 1320 | shadow_uni.face_vp[slot * 6..slot * 6 + 6].copy_from_slice(&vps); |
| 1321 | shadow_face_vps[slot * 6..slot * 6 + 6].copy_from_slice(&vps); |
| 1322 | shadow_uni.point[li] = [slot as f32, pl.shadow_density.unwrap_or(0.0), 0.0, 0.0]; |
| 1323 | } |
| 1324 | cached_uniform_buffer( |
| 1325 | &self.uniform_cache, |
| 1326 | device, |
| 1327 | "scene3d-shadow-u", |
| 1328 | bytemuck::bytes_of(&shadow_uni), |
| 1329 | ) |
| 1330 | }); |
| 1331 | let shadow_ubuf = shadow_ubuf_owned.as_ref().unwrap_or(&self.shadow_dummy_ubuf); |
| 1332 | let shadow_targets = (!shadow_lights.is_empty()).then(|| { |
| 1333 | let layers = 6 * shadow_lights.len() as u32; |
| 1334 | let mut cache = lock_or_recover(&self.shadow_targets); |
| 1335 | match cache.as_ref() { |
| 1336 | Some(t) if t.layers >= layers => t.clone(), |
| 1337 | _ => { |
| 1338 | let target = |label, format, usage, depth_or_array_layers| { |
| 1339 | device.create_texture(&wgpu::TextureDescriptor { |
| 1340 | label: Some(label), |
| 1341 | size: wgpu::Extent3d { width: SHADOW_MAP_SIZE, height: SHADOW_MAP_SIZE, depth_or_array_layers }, |
| 1342 | mip_level_count: 1, |
| 1343 | sample_count: 1, |
| 1344 | dimension: wgpu::TextureDimension::D2, |
| 1345 | format, |
| 1346 | usage, |
| 1347 | view_formats: &[], |
| 1348 | }) |
| 1349 | }; |
| 1350 | let maps = target( |
| 1351 | "scene3d-shadow-maps", |
| 1352 | wgpu::TextureFormat::R32Float, |
| 1353 | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, |
| 1354 | layers, |
| 1355 | ); |
| 1356 | let array_view = maps.create_view(&wgpu::TextureViewDescriptor { |
| 1357 | dimension: Some(wgpu::TextureViewDimension::D2Array), |
| 1358 | ..Default::default() |
| 1359 | }); |
| 1360 | let layer_views = (0..layers) |
| 1361 | .map(|layer| { |
| 1362 | maps.create_view(&wgpu::TextureViewDescriptor { |
| 1363 | dimension: Some(wgpu::TextureViewDimension::D2), |
| 1364 | base_array_layer: layer, |
| 1365 | array_layer_count: Some(1), |
| 1366 | ..Default::default() |
| 1367 | }) |
| 1368 | }) |
| 1369 | .collect(); |
| 1370 | let fresh = ShadowTargets { |
| 1371 | layers, |
| 1372 | array_view, |
| 1373 | layer_views, |
| 1374 | depth: target( |
| 1375 | "scene3d-shadow-depth", |
| 1376 | wgpu::TextureFormat::Depth32Float, |
| 1377 | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 1378 | 1, |
| 1379 | ) |
| 1380 | .create_view(&wgpu::TextureViewDescriptor::default()), |
| 1381 | }; |
| 1382 | *cache = Some(fresh.clone()); |
| 1383 | fresh |
| 1384 | } |
| 1385 | } |
| 1386 | }); |
| 1387 | let shadow_view = shadow_targets.as_ref().map(|t| &t.array_view); |
| 1388 | // One buffer holds every caster and face uniform of this render at dynamic offsets: casters |
| 1389 | // first (at most one per mesh), then six faces per light. |
| 1390 | let align = device.limits().min_uniform_buffer_offset_alignment; |
| 1391 | let uniform_stride = (CASTER_BYTES.max(FACE_BYTES) as u32).next_multiple_of(align) as usize; |
| 1392 | let face_base = meshes.len() * uniform_stride; |
| 1393 | let mut shadow_uniform_bytes = vec![0u8; if shadow_lights.is_empty() { 0 } else { face_base + shadow_lights.len() * 6 * uniform_stride }]; |
| 1394 | let mut n_casters = 0; |
| 1395 | |
| 1396 | // One dynamic-offset uniform buffer holds every mesh's `MeshUniform` for this render call. |
| 1397 | let mesh_uni_size = std::mem::size_of::<MeshUniform>(); |
| 1398 | let mesh_uni_stride = (mesh_uni_size as u32).next_multiple_of(align) as usize; |
| 1399 | let mut mesh_uniform_bytes = vec![0u8; meshes.len() * mesh_uni_stride]; |
| 1400 | |
| 1401 | // Sort back-to-front by view-space centroid so semi-transparent planes and partial |
| 1402 | // Cube3D face groups blend cleanly while preserving scene-graph order on equal depths. |
| 1403 | let mut order: Vec<(usize, f32)> = meshes |
| 1404 | .iter() |
| 1405 | .enumerate() |
| 1406 | .map(|(i, m)| { |
| 1407 | let c = shape_local_center(&m.shape); |
| 1408 | let wx = m.world[0] * c[0] + m.world[4] * c[1] + m.world[8] * c[2] + m.world[12]; |
| 1409 | let wy = m.world[1] * c[0] + m.world[5] * c[1] + m.world[9] * c[2] + m.world[13]; |
| 1410 | let wz = m.world[2] * c[0] + m.world[6] * c[1] + m.world[10] * c[2] + m.world[14]; |
| 1411 | let vz = view[2] * wx + view[6] * wy + view[10] * wz + view[14]; |
| 1412 | (i, vz) |
| 1413 | }) |
| 1414 | .collect(); |
| 1415 | order.sort_by(|a, b| a.1.total_cmp(&b.1)); |
| 1416 | |
| 1417 | struct PreparedDraw<'a> { |
| 1418 | wireframe: bool, |
| 1419 | cull: [bool; 2], |
| 1420 | tex_view: &'a wgpu::TextureView, |
| 1421 | bump_view: &'a wgpu::TextureView, |
| 1422 | uni_offset: u32, |
| 1423 | caster_offset: Option<u32>, |
| 1424 | vbuf: wgpu::Buffer, |
| 1425 | ibuf: wgpu::Buffer, |
| 1426 | idx_count: u32, |
| 1427 | } |
| 1428 | struct GpuDraw { |
| 1429 | wireframe: bool, |
| 1430 | /// `[cull_back, cull_front]`. |
| 1431 | cull: [bool; 2], |
| 1432 | bg: wgpu::BindGroup, |
| 1433 | uni_offset: u32, |
| 1434 | /// Dynamic offset into `shadow_dyn_buf`; `None` for meshes that cast no shadow. |
| 1435 | caster_offset: Option<u32>, |
| 1436 | vbuf: wgpu::Buffer, |
| 1437 | ibuf: wgpu::Buffer, |
| 1438 | idx_count: u32, |
| 1439 | } |
| 1440 | let mut prepared = Vec::with_capacity(order.len()); |
| 1441 | for (idx, _) in order { |
| 1442 | let m = &meshes[idx]; |
| 1443 | let aspect = m |
| 1444 | .tex |
| 1445 | .as_ref() |
| 1446 | .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4)) |
| 1447 | .unwrap_or(16.0 / 9.0); |
| 1448 | let (base_shape, fx) = m.shape.split_fx(); |
| 1449 | let upload = || { |
| 1450 | let (mut verts, mut indices) = build_shape_mesh(base_shape, aspect); |
| 1451 | if indices.is_empty() { |
| 1452 | return None; |
| 1453 | } |
| 1454 | if let Some(disp) = &m.displace { |
| 1455 | apply_heightmap_displace(&mut verts, &indices, disp); |
| 1456 | } |
| 1457 | if fx.wireframe { |
| 1458 | indices = triangle_edges(&indices); |
| 1459 | } |
| 1460 | let vbytes = bytemuck::cast_slice(&verts); |
| 1461 | let ibytes = bytemuck::cast_slice(&indices); |
| 1462 | let vbuf_bytes = vbytes.len() as u64; |
| 1463 | let ibuf_bytes = ibytes.len() as u64; |
| 1464 | let vbuf = device.create_buffer(&wgpu::BufferDescriptor { |
| 1465 | label: Some("scene3d-vb"), |
| 1466 | size: vbuf_bytes, |
| 1467 | usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, |
| 1468 | mapped_at_creation: false, |
| 1469 | }); |
| 1470 | queue.write_buffer(&vbuf, 0, vbytes); |
| 1471 | let ibuf = device.create_buffer(&wgpu::BufferDescriptor { |
| 1472 | label: Some("scene3d-ib"), |
| 1473 | size: ibuf_bytes, |
| 1474 | usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, |
| 1475 | mapped_at_creation: false, |
| 1476 | }); |
| 1477 | queue.write_buffer(&ibuf, 0, ibytes); |
| 1478 | Some(GpuMesh { vbuf, ibuf, idx_count: indices.len() as u32, vbuf_bytes, ibuf_bytes }) |
| 1479 | }; |
| 1480 | // Heightmap contents are not part of the key, so displaced meshes are never cached. |
| 1481 | let gpu_mesh = if m.displace.is_some() { |
| 1482 | upload() |
| 1483 | } else { |
| 1484 | let key = mesh_key(base_shape, m.custom_mesh_key, aspect, fx.wireframe); |
| 1485 | lock_or_recover(&self.meshes).get_or_insert_with(key, upload) |
| 1486 | }; |
| 1487 | let Some(GpuMesh { vbuf, ibuf, idx_count, .. }) = gpu_mesh else { |
| 1488 | continue; |
| 1489 | }; |
| 1490 | |
| 1491 | let mvp = mat4_mul(view_proj, m.world); |
| 1492 | let tex_dod = |tex: Option<&CachedTexture>| -> [f32; 4] { |
| 1493 | tex.filter(|t| t.has_dod()) |
| 1494 | .map_or([0.0; 4], |t| [t.origin[0] as f32, t.origin[1] as f32, t.canvas_size[0] as f32, t.canvas_size[1] as f32]) |
| 1495 | }; |
| 1496 | let dod = tex_dod(m.tex.as_ref()); |
| 1497 | let bump_src = m.bump_tex.as_ref().or_else(|| if fx.bump_only { m.tex.as_ref() } else { None }); |
| 1498 | let bump_dod = tex_dod(bump_src); |
| 1499 | let mut point_pos = [[0.0_f32; 4]; MAX_LIGHTS]; |
| 1500 | let mut point_col = [[0.0_f32; 4]; MAX_LIGHTS]; |
| 1501 | let n_pt = lights.points.len().min(MAX_LIGHTS); |
| 1502 | for (pi, pl) in lights.points.iter().take(MAX_LIGHTS).enumerate() { |
| 1503 | point_pos[pi] = [pl.pos[0], pl.pos[1], pl.pos[2], pl.decay_type]; |
| 1504 | point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], 0.0]; |
| 1505 | } |
| 1506 | let mut spot_pos = [[0.0_f32; 4]; MAX_LIGHTS]; |
| 1507 | let mut spot_dir = [[0.0_f32; 4]; MAX_LIGHTS]; |
| 1508 | let mut spot_col = [[0.0_f32; 4]; MAX_LIGHTS]; |
| 1509 | let n_sp = lights.spots.len().min(MAX_LIGHTS); |
| 1510 | for (si, sl) in lights.spots.iter().take(MAX_LIGHTS).enumerate() { |
| 1511 | spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner]; |
| 1512 | spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer]; |
| 1513 | spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type]; |
| 1514 | } |
| 1515 | let mut dir_to_light = [[0.0_f32; 4]; MAX_DIR_LIGHTS]; |
| 1516 | let mut dir_color = [[0.0_f32; 4]; MAX_DIR_LIGHTS]; |
| 1517 | let n_dir = lights.dirs.len().min(MAX_DIR_LIGHTS); |
| 1518 | for (di, dl) in lights.dirs.iter().take(MAX_DIR_LIGHTS).enumerate() { |
| 1519 | dir_to_light[di] = [dl.to_light[0], dl.to_light[1], dl.to_light[2], 0.0]; |
| 1520 | dir_color[di] = [dl.color[0], dl.color[1], dl.color[2], 0.0]; |
| 1521 | } |
| 1522 | let use_diffuse_tex = m.tex.is_some() && fx.env_tex_slot != 1; |
| 1523 | let has_bump_tex = bump_src.is_some() && fx.env_tex_slot != 2 && fx.sfx.layer[3] != 2.0; |
| 1524 | let mut sfx = fx.sfx; |
| 1525 | if !lighting_enabled { |
| 1526 | sfx.layer[2] = 0.0; |
| 1527 | } |
| 1528 | let uni = MeshUniform { |
| 1529 | mvp, |
| 1530 | model: m.world, |
| 1531 | view, |
| 1532 | dod, |
| 1533 | flags: [ |
| 1534 | if use_diffuse_tex { 1.0 } else { 0.0 }, |
| 1535 | if lighting_enabled && m.affected_by_lights { 1.0 } else { 0.0 }, |
| 1536 | m.specular_intensity, |
| 1537 | if m.flip_normals { 1.0 } else { 0.0 }, |
| 1538 | ], |
| 1539 | diffuse_col: m.diffuse_col, |
| 1540 | specular_col: [ |
| 1541 | m.specular_col[0], |
| 1542 | m.specular_col[1], |
| 1543 | m.specular_col[2], |
| 1544 | m.specular_exponent, |
| 1545 | ], |
| 1546 | ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0], |
| 1547 | dir_to_light, |
| 1548 | dir_color, |
| 1549 | cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0], |
| 1550 | light_counts: [n_pt as f32, n_sp as f32, n_dir as f32, if m.receives_shadows { 1.0 } else { 0.0 }], |
| 1551 | uv_xform: fx.uv.m, |
| 1552 | uv_off_wrap: [fx.uv.t[0], fx.uv.t[1], fx.uv_wrap as f32, if lighting_enabled && fx.per_light_unlit { lights.count.max(1) as f32 } else { 1.0 }], |
| 1553 | mat_fx: [fx.bump_scale, fx.bump_mode as f32, if fx.bump_only { 1.0 } else { 0.0 }, fx.spec_model as u32 as f32], |
| 1554 | bump_uv_xform: fx.bump_uv.m, |
| 1555 | bump_off_wrap: [fx.bump_uv.t[0], fx.bump_uv.t[1], fx.bump_wrap as f32, if has_bump_tex { 1.0 } else { 0.0 }], |
| 1556 | bump_dod, |
| 1557 | bump_params: [fx.bump_clamp_z, fx.bump_channel as f32, 0.0, 0.0], |
| 1558 | mtl_params: [ |
| 1559 | fx.diffuse_color_alpha, |
| 1560 | fx.refractive_index, |
| 1561 | if fx.do_fresnel { 1.0 } else { 0.0 }, |
| 1562 | fx.ward_spread_v, |
| 1563 | ], |
| 1564 | env_rot_0: [fx.env_rot[0], fx.env_rot[1], fx.env_rot[2], fx.env_mode as f32], |
| 1565 | env_rot_1: [fx.env_rot[3], fx.env_rot[4], fx.env_rot[5], fx.env_map_mode as f32], |
| 1566 | env_rot_2: [fx.env_rot[6], fx.env_rot[7], fx.env_rot[8], fx.env_tex_slot as f32], |
| 1567 | refl_strength: [fx.refl_strength_var as f32, fx.refl_constant_strength, 0.0, 0.0], |
| 1568 | refl_params: [ |
| 1569 | fx.refl_glancing_strength, |
| 1570 | fx.refl_face_on_strength, |
| 1571 | fx.refl_falloff, |
| 1572 | fx.refract_ior, |
| 1573 | ], |
| 1574 | refl_tint: [ |
| 1575 | fx.refl_tint[0], |
| 1576 | fx.refl_tint[1], |
| 1577 | fx.refl_tint[2], |
| 1578 | if fx.refl_has_bg { 1.0 } else { 0.0 }, |
| 1579 | ], |
| 1580 | refract_tint: [fx.refract_tint[0], fx.refract_tint[1], fx.refract_tint[2], 0.0], |
| 1581 | cb_ops_a: fx.cb_ops_a.map(f32::from), |
| 1582 | cb_ops: fx.cb_ops.map(f32::from), |
| 1583 | cb_ops_b: fx.cb_ops_b.map(f32::from), |
| 1584 | cb_flags: [if fx.cb_enabled { 1.0 } else { 0.0 }, f32::from(fx.cb_coord_space), 0.0, 0.0], |
| 1585 | point_pos, |
| 1586 | point_col, |
| 1587 | spot_pos, |
| 1588 | spot_dir, |
| 1589 | spot_col, |
| 1590 | sfx, |
| 1591 | }; |
| 1592 | let uni_offset = prepared.len() * mesh_uni_stride; |
| 1593 | mesh_uniform_bytes[uni_offset..uni_offset + mesh_uni_size].copy_from_slice(bytemuck::bytes_of(&uni)); |
| 1594 | let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view); |
| 1595 | let bump_view = bump_src.map_or(&dummy.view, |t| &t.view); |
| 1596 | // Fusion's RendererOpenGL casts solid geometry shadows regardless of texture/material alpha. |
| 1597 | let caster_offset = (!shadow_lights.is_empty() && m.casts_shadow && !fx.wireframe).then(|| { |
| 1598 | let offset = n_casters * uniform_stride; |
| 1599 | shadow_uniform_bytes[offset..offset + CASTER_BYTES].copy_from_slice(bytemuck::cast_slice(&m.world)); |
| 1600 | n_casters += 1; |
| 1601 | offset as u32 |
| 1602 | }); |
| 1603 | prepared.push(PreparedDraw { |
| 1604 | wireframe: fx.wireframe, |
| 1605 | cull: [fx.cull_back, fx.cull_front], |
| 1606 | tex_view, |
| 1607 | bump_view, |
| 1608 | uni_offset: uni_offset as u32, |
| 1609 | caster_offset, |
| 1610 | vbuf, |
| 1611 | ibuf, |
| 1612 | idx_count, |
| 1613 | }); |
| 1614 | } |
| 1615 | let mesh_dyn_buf = (!prepared.is_empty()).then(|| { |
| 1616 | cached_uniform_buffer( |
| 1617 | &self.uniform_cache, |
| 1618 | device, |
| 1619 | "scene3d-mesh-dyn", |
| 1620 | &mesh_uniform_bytes[..prepared.len() * mesh_uni_stride], |
| 1621 | ) |
| 1622 | }); |
| 1623 | let draw_items: Vec<GpuDraw> = prepared |
| 1624 | .into_iter() |
| 1625 | .map(|p| { |
| 1626 | let mesh_buf = mesh_dyn_buf.as_ref().expect("mesh_dyn_buf allocated when prepared non-empty"); |
| 1627 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 1628 | label: Some("scene3d-bg"), |
| 1629 | layout: &self.bgl, |
| 1630 | entries: &[ |
| 1631 | wgpu::BindGroupEntry { |
| 1632 | binding: 0, |
| 1633 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 1634 | buffer: mesh_buf, |
| 1635 | offset: 0, |
| 1636 | size: std::num::NonZeroU64::new(mesh_uni_size as u64), |
| 1637 | }), |
| 1638 | }, |
| 1639 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(p.tex_view) }, |
| 1640 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, |
| 1641 | wgpu::BindGroupEntry { binding: 3, resource: shadow_ubuf.as_entire_binding() }, |
| 1642 | wgpu::BindGroupEntry { |
| 1643 | binding: 4, |
| 1644 | resource: wgpu::BindingResource::TextureView(shadow_view.unwrap_or(&self.shadow_dummy)), |
| 1645 | }, |
| 1646 | wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(p.bump_view) }, |
| 1647 | ], |
| 1648 | }); |
| 1649 | GpuDraw { |
| 1650 | wireframe: p.wireframe, |
| 1651 | cull: p.cull, |
| 1652 | bg, |
| 1653 | uni_offset: p.uni_offset, |
| 1654 | caster_offset: p.caster_offset, |
| 1655 | vbuf: p.vbuf, |
| 1656 | ibuf: p.ibuf, |
| 1657 | idx_count: p.idx_count, |
| 1658 | } |
| 1659 | }) |
| 1660 | .collect(); |
| 1661 | |
| 1662 | if let Some(targets) = &shadow_targets { |
| 1663 | for (slot, &li) in shadow_lights.iter().enumerate() { |
| 1664 | let pos = lights.points[li].pos; |
| 1665 | for face in 0..6 { |
| 1666 | let layer = slot * 6 + face; |
| 1667 | let mut uniform = [0.0_f32; FACE_BYTES / 4]; |
| 1668 | uniform[..16].copy_from_slice(&shadow_face_vps[layer]); |
| 1669 | uniform[16..19].copy_from_slice(&pos); |
| 1670 | let face_offset = face_base + layer * uniform_stride; |
| 1671 | shadow_uniform_bytes[face_offset..face_offset + FACE_BYTES].copy_from_slice(bytemuck::cast_slice(&uniform)); |
| 1672 | } |
| 1673 | } |
| 1674 | let shadow_dyn_buf = cached_uniform_buffer( |
| 1675 | &self.uniform_cache, |
| 1676 | device, |
| 1677 | "scene3d-shadow-dyn", |
| 1678 | &shadow_uniform_bytes, |
| 1679 | ); |
| 1680 | let caster_bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 1681 | label: Some("scene3d-shadow-caster"), |
| 1682 | layout: &self.shadow_caster_bgl, |
| 1683 | entries: &[wgpu::BindGroupEntry { |
| 1684 | binding: 0, |
| 1685 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 1686 | buffer: &shadow_dyn_buf, |
| 1687 | offset: 0, |
| 1688 | size: std::num::NonZeroU64::new(CASTER_BYTES as u64), |
| 1689 | }), |
| 1690 | }], |
| 1691 | }); |
| 1692 | let face_bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 1693 | label: Some("scene3d-shadow-face"), |
| 1694 | layout: &self.shadow_face_bgl, |
| 1695 | entries: &[wgpu::BindGroupEntry { |
| 1696 | binding: 0, |
| 1697 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 1698 | buffer: &shadow_dyn_buf, |
| 1699 | offset: 0, |
| 1700 | size: std::num::NonZeroU64::new(FACE_BYTES as u64), |
| 1701 | }), |
| 1702 | }], |
| 1703 | }); |
| 1704 | for slot in 0..shadow_lights.len() { |
| 1705 | for face in 0..6 { |
| 1706 | let layer = slot * 6 + face; |
| 1707 | let face_offset = face_base + layer * uniform_stride; |
| 1708 | let layer_view = &targets.layer_views[layer]; |
| 1709 | let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 1710 | label: Some("scene3d-shadow-pass"), |
| 1711 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { |
| 1712 | view: layer_view, |
| 1713 | depth_slice: None, |
| 1714 | resolve_target: None, |
| 1715 | ops: wgpu::Operations { |
| 1716 | load: wgpu::LoadOp::Clear(wgpu::Color { r: 1e30, g: 0.0, b: 0.0, a: 0.0 }), |
| 1717 | store: wgpu::StoreOp::Store, |
| 1718 | }, |
| 1719 | })], |
| 1720 | depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { |
| 1721 | view: &targets.depth, |
| 1722 | depth_ops: Some(wgpu::Operations { |
| 1723 | load: wgpu::LoadOp::Clear(1.0), |
| 1724 | store: wgpu::StoreOp::Discard, |
| 1725 | }), |
| 1726 | stencil_ops: None, |
| 1727 | }), |
| 1728 | timestamp_writes: None, |
| 1729 | occlusion_query_set: None, |
| 1730 | multiview_mask: None, |
| 1731 | }); |
| 1732 | pass.set_pipeline(&self.shadow_pipeline); |
| 1733 | pass.set_bind_group(1, &face_bg, &[face_offset as u32]); |
| 1734 | for d in &draw_items { |
| 1735 | let Some(caster_offset) = d.caster_offset else { continue }; |
| 1736 | pass.set_bind_group(0, &caster_bg, &[caster_offset]); |
| 1737 | pass.set_vertex_buffer(0, d.vbuf.slice(..)); |
| 1738 | pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); |
| 1739 | pass.draw_indexed(0..d.idx_count, 0, 0..1); |
| 1740 | } |
| 1741 | } |
| 1742 | } |
| 1743 | } |
| 1744 | |
| 1745 | let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 1746 | label: Some("scene3d-pass"), |
| 1747 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { |
| 1748 | view: &dst.view, |
| 1749 | depth_slice: None, |
| 1750 | resolve_target: None, |
| 1751 | ops: wgpu::Operations { |
| 1752 | load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), |
| 1753 | store: wgpu::StoreOp::Store, |
| 1754 | }, |
| 1755 | })], |
| 1756 | depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { |
| 1757 | view: depth_view, |
| 1758 | depth_ops: Some(wgpu::Operations { |
| 1759 | load: wgpu::LoadOp::Clear(1.0), |
| 1760 | store: if want_z { wgpu::StoreOp::Store } else { wgpu::StoreOp::Discard }, |
| 1761 | }), |
| 1762 | stencil_ops: None, |
| 1763 | }), |
| 1764 | timestamp_writes: None, |
| 1765 | occlusion_query_set: None, |
| 1766 | multiview_mask: None, |
| 1767 | }); |
| 1768 | for d in &draw_items { |
| 1769 | pass.set_bind_group(0, &d.bg, &[d.uni_offset]); |
| 1770 | pass.set_vertex_buffer(0, d.vbuf.slice(..)); |
| 1771 | pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); |
| 1772 | if let Some(pipeline) = self.pipelines[d.wireframe as usize].get(cull_index(d.cull)) { |
| 1773 | pass.set_pipeline(pipeline); |
| 1774 | pass.draw_indexed(0..d.idx_count, 0, 0..1); |
| 1775 | } |
| 1776 | } |
| 1777 | drop(pass); |
| 1778 | |
| 1779 | if !want_z && !want_normal { |
| 1780 | return None; |
| 1781 | } |
| 1782 | |
| 1783 | let mut aux = AuxChannels::default(); |
| 1784 | if want_z { |
| 1785 | let z_tex = AuxChannelTex::new(device, depth_size, wgpu::TextureFormat::R32Float, "scene3d-aux-z"); |
| 1786 | let depth_z_uni = DepthToEyeZUniform { |
| 1787 | proj_zw: [proj[10], proj[11], proj[14], proj[15]], |
| 1788 | params: [EMPTY_Z_SENTINEL, 0.0, 0.0, 0.0], |
| 1789 | }; |
| 1790 | let depth_z_ubuf = cached_uniform_buffer( |
| 1791 | &self.uniform_cache, |
| 1792 | device, |
| 1793 | "scene3d-depth-z-u", |
| 1794 | bytemuck::bytes_of(&depth_z_uni), |
| 1795 | ); |
| 1796 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 1797 | label: Some("scene3d-depth-z-bg"), |
| 1798 | layout: &self.depth_z_bgl, |
| 1799 | entries: &[ |
| 1800 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(depth_view) }, |
| 1801 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&z_tex.view) }, |
| 1802 | wgpu::BindGroupEntry { binding: 2, resource: depth_z_ubuf.as_entire_binding() }, |
| 1803 | ], |
| 1804 | }); |
| 1805 | let mut cpass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 1806 | label: Some("scene3d-depth-to-eye-z"), |
| 1807 | timestamp_writes: None, |
| 1808 | }); |
| 1809 | cpass.set_pipeline(&self.depth_z_pipeline); |
| 1810 | cpass.set_bind_group(0, &bg, &[]); |
| 1811 | cpass.dispatch_workgroups(z_tex.size[0].div_ceil(8), z_tex.size[1].div_ceil(8), 1); |
| 1812 | aux.z = Some(z_tex); |
| 1813 | } |
| 1814 | |
| 1815 | if want_normal { |
| 1816 | let normal_raw = device.create_texture(&wgpu::TextureDescriptor { |
| 1817 | label: Some("scene3d-aux-normal"), |
| 1818 | size: wgpu::Extent3d { |
| 1819 | width: depth_size[0], |
| 1820 | height: depth_size[1], |
| 1821 | depth_or_array_layers: 1, |
| 1822 | }, |
| 1823 | mip_level_count: 1, |
| 1824 | sample_count: 1, |
| 1825 | dimension: wgpu::TextureDimension::D2, |
| 1826 | format: wgpu::TextureFormat::Rgba16Float, |
| 1827 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT |
| 1828 | | wgpu::TextureUsages::TEXTURE_BINDING |
| 1829 | | wgpu::TextureUsages::COPY_SRC |
| 1830 | | wgpu::TextureUsages::COPY_DST, |
| 1831 | view_formats: &[], |
| 1832 | }); |
| 1833 | let normal_tex = AuxChannelTex::from_texture(normal_raw, depth_size); |
| 1834 | let mut npass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 1835 | label: Some("scene3d-normal-pass"), |
| 1836 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { |
| 1837 | view: &normal_tex.view, |
| 1838 | depth_slice: None, |
| 1839 | resolve_target: None, |
| 1840 | ops: wgpu::Operations { |
| 1841 | load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), |
| 1842 | store: wgpu::StoreOp::Store, |
| 1843 | }, |
| 1844 | })], |
| 1845 | depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { |
| 1846 | view: depth_view, |
| 1847 | depth_ops: Some(wgpu::Operations { |
| 1848 | load: wgpu::LoadOp::Clear(1.0), |
| 1849 | store: wgpu::StoreOp::Discard, |
| 1850 | }), |
| 1851 | stencil_ops: None, |
| 1852 | }), |
| 1853 | timestamp_writes: None, |
| 1854 | occlusion_query_set: None, |
| 1855 | multiview_mask: None, |
| 1856 | }); |
| 1857 | for d in &draw_items { |
| 1858 | npass.set_bind_group(0, &d.bg, &[d.uni_offset]); |
| 1859 | npass.set_vertex_buffer(0, d.vbuf.slice(..)); |
| 1860 | npass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); |
| 1861 | if let Some(pipeline) = self.normal_pipelines[d.wireframe as usize].get(cull_index(d.cull)) { |
| 1862 | npass.set_pipeline(pipeline); |
| 1863 | npass.draw_indexed(0..d.idx_count, 0, 0..1); |
| 1864 | } |
| 1865 | } |
| 1866 | drop(npass); |
| 1867 | aux.normal = Some(normal_tex); |
| 1868 | } |
| 1869 | |
| 1870 | Some(aux) |
| 1871 | } |
| 1872 | } |
| 1873 | |
| 1874 | #[cfg(test)] |
| 1875 | mod tests { |
| 1876 | use super::*; |
| 1877 | use crate::Engine; |
| 1878 | use model::Comp; |
| 1879 | |
| 1880 | /// Renders `Renderer3D` node `R` of a 64x64 scene viewed by a camera at z=4.2 (35mm lens, 1" gate). |
| 1881 | fn render(lighting: bool, scene: &str) -> Option<Vec<u8>> { |
| 1882 | let src = format!( |
| 1883 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 1884 | Bg = Background {{ Inputs = {{ Width = Input {{ Value = 8, }}, Height = Input {{ Value = 8, }}, TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.25, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }}, |
| 1885 | Tex = Texture2DOperator {{ Inputs = {{ Input = Input {{ SourceOp = "Bg", Source = "Output", }}, }}, }}, |
| 1886 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, |
| 1887 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.2, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, |
| 1888 | {scene} |
| 1889 | R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, ["RendererSoftware.LightingEnabled"] = Input {{ Value = {}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, |
| 1890 | }} }}"#, |
| 1891 | lighting as u8 |
| 1892 | ); |
| 1893 | let comp = Comp::from_fusion_str(&src).expect("parse render comp"); |
| 1894 | let mut eng = Engine::new_headless().ok()?; |
| 1895 | let id = comp.find_node("R").expect("R"); |
| 1896 | let (tex, _) = eng.evaluate(&comp, id, 0.0); |
| 1897 | eng.readback_rgba(&tex).ok() |
| 1898 | } |
| 1899 | |
| 1900 | fn center(px: &[u8]) -> [u8; 4] { |
| 1901 | let i = (32 * 64 + 32) * 4; |
| 1902 | [px[i], px[i + 1], px[i + 2], px[i + 3]] |
| 1903 | } |
| 1904 | |
| 1905 | const PLANE: &str = r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2, }, MaterialInput = Input { SourceOp = "Flat", Source = "MaterialOutput", }, }, },"#; |
| 1906 | |
| 1907 | #[test] |
| 1908 | fn point_light_decay_is_inverse_distance_and_inverse_square() { |
| 1909 | for (decay, expected) in [(0, 255.0), (1, 127.5), (2, 63.75)] { |
| 1910 | let scene = format!( |
| 1911 | r#"{PLANE} L = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 2, }}, DecayType = Input {{ Value = {decay}, }}, }}, }}, |
| 1912 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 1913 | ); |
| 1914 | let Some(px) = render(true, &scene) else { return }; |
| 1915 | let c = center(&px); |
| 1916 | assert!((c[0] as f32 - expected).abs() <= 3.0, "decay {decay}: {c:?}"); |
| 1917 | } |
| 1918 | } |
| 1919 | |
| 1920 | #[test] |
| 1921 | fn bare_texture_renders_unlit_but_blinn_diffuse_is_lit() { |
| 1922 | let scene = |mat: &str| { |
| 1923 | format!( |
| 1924 | r#"Shaded = MtlBlinn {{ Inputs = {{ ["Diffuse.Color.Material"] = Input {{ SourceOp = "Tex", Source = "MaterialOutput", }}, }}, }}, |
| 1925 | P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 2, }}, MaterialInput = Input {{ SourceOp = "{mat}", Source = "MaterialOutput", }}, }}, }}, |
| 1926 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 1927 | ) |
| 1928 | }; |
| 1929 | let (Some(flat), Some(shaded)) = (render(true, &scene("Tex")), render(true, &scene("Shaded"))) else { return }; |
| 1930 | assert_eq!(center(&flat), [255, 128, 64, 255]); |
| 1931 | assert_eq!(center(&shaded)[..3], [0, 0, 0], "lighting on with no lights is black"); |
| 1932 | } |
| 1933 | |
| 1934 | #[test] |
| 1935 | fn wireframe_draws_edges_only() { |
| 1936 | let scene = |wire: u8| { |
| 1937 | format!( |
| 1938 | r#"P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 2, }}, ["SurfacePlaneInputs.SubdivisionWidth"] = Input {{ Value = 2, }}, ["SurfacePlaneInputs.Wireframe"] = Input {{ Value = {wire}, }}, }}, }}, |
| 1939 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 1940 | ) |
| 1941 | }; |
| 1942 | let (Some(solid), Some(wire)) = (render(false, &scene(0)), render(false, &scene(1))) else { return }; |
| 1943 | let coverage = |px: &[u8]| px.chunks_exact(4).filter(|c| c[3] > 0).count(); |
| 1944 | assert_eq!(center(&solid)[3], 255); |
| 1945 | assert!(coverage(&wire) > 0 && coverage(&wire) < coverage(&solid) / 4, "{} vs {}", coverage(&wire), coverage(&solid)); |
| 1946 | } |
| 1947 | |
| 1948 | #[test] |
| 1949 | fn translucent_cube_front_hides_its_inside() { |
| 1950 | // Fusion draws the front face first, so the depth test drops the back face behind it. |
| 1951 | let scene = r#"B = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceCubeInputs" }, }, ["MtlStdInputs.Diffuse.Opacity"] = Input { Value = 0.5, }, }, }, |
| 1952 | M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "B", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#; |
| 1953 | let Some(px) = render(false, scene) else { return }; |
| 1954 | let alpha = center(&px)[3] as i32; |
| 1955 | assert!((alpha - 128).abs() <= 3, "alpha {alpha}"); |
| 1956 | } |
| 1957 | |
| 1958 | #[test] |
| 1959 | fn normals_stay_perpendicular_under_non_uniform_scale() { |
| 1960 | // Plane rotated 45 degrees about Y under a [4, 1, 1] scale: the true normal is |
| 1961 | // (1/4, 0, 1) normalized, so a +Z light gives cos = 0.970; `model * n` would give 0.243. |
| 1962 | let scene = r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2, }, ["Transform3DOp.Rotate.Y"] = Input { Value = 45, }, MaterialInput = Input { SourceOp = "Flat", Source = "MaterialOutput", }, }, }, |
| 1963 | S = Transform3D { Inputs = { ["Transform3DOp.ScaleLock"] = Input { Value = 0, }, ["Transform3DOp.Scale.X"] = Input { Value = 4, }, SceneInput1 = Input { SourceOp = "P", Source = "Output", }, }, }, |
| 1964 | L = LightDirectional { }, |
| 1965 | M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, SceneInput2 = Input { SourceOp = "L", Source = "Output", }, SceneInput3 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#; |
| 1966 | let Some(px) = render(true, scene) else { return }; |
| 1967 | let expected = 255.0 / (1.0 + 1.0 / 16.0_f32).sqrt(); |
| 1968 | let c = center(&px); |
| 1969 | assert!((c[0] as f32 - expected).abs() <= 3.0, "{c:?} vs {expected}"); |
| 1970 | } |
| 1971 | |
| 1972 | #[test] |
| 1973 | fn up_to_four_directional_lights_accumulate() { |
| 1974 | // Five 0.1 lights facing the plane: the first four reach the shader, so 0.4 * 255. |
| 1975 | let lights: String = (1..=5) |
| 1976 | .map(|i| format!(r#"L{i} = LightDirectional {{ Inputs = {{ Intensity = Input {{ Value = 0.1, }}, }}, }},"#)) |
| 1977 | .collect(); |
| 1978 | let ports: String = (1..=5).map(|i| format!(r#"SceneInput{} = Input {{ SourceOp = "L{i}", Source = "Output", }},"#, i + 1)).collect(); |
| 1979 | let scene = format!( |
| 1980 | r#"{PLANE} {lights} |
| 1981 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, {ports} SceneInput7 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 1982 | ); |
| 1983 | let Some(px) = render(true, &scene) else { return }; |
| 1984 | let c = center(&px); |
| 1985 | assert!((c[0] as f32 - 102.0).abs() <= 3.0, "{c:?}"); |
| 1986 | } |
| 1987 | |
| 1988 | #[test] |
| 1989 | fn gpu_meshes_are_reused_across_frames_and_split_by_wireframe() { |
| 1990 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 1991 | let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; |
| 1992 | let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; |
| 1993 | let renderer = Scene3DRenderer::new(&device); |
| 1994 | let target = || { |
| 1995 | CachedTexture::from_texture( |
| 1996 | device.create_texture(&wgpu::TextureDescriptor { |
| 1997 | label: None, |
| 1998 | size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 }, |
| 1999 | mip_level_count: 1, |
| 2000 | sample_count: 1, |
| 2001 | dimension: wgpu::TextureDimension::D2, |
| 2002 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 2003 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 2004 | view_formats: &[], |
| 2005 | }), |
| 2006 | [8, 8], |
| 2007 | 0, |
| 2008 | ) |
| 2009 | }; |
| 2010 | let (dst, dummy) = (target(), target()); |
| 2011 | let sphere = |x: f32, wireframe: bool| DrawMesh { |
| 2012 | world: mat4_translate(x, 0.0, 0.0), |
| 2013 | shape: ShapeKind::WithMaterialFx { |
| 2014 | inner: Box::new(ShapeKind::Sphere { radius: 1.0, sub_base: 8, sub_height: 8 }), |
| 2015 | fx: MaterialFx { wireframe, ..Default::default() }, |
| 2016 | }, |
| 2017 | custom_mesh_key: None, |
| 2018 | tex: None, |
| 2019 | bump_tex: None, |
| 2020 | diffuse_col: [1.0; 4], |
| 2021 | specular_col: [1.0; 3], |
| 2022 | specular_intensity: 0.0, |
| 2023 | specular_exponent: 50.0, |
| 2024 | affected_by_lights: false, |
| 2025 | casts_shadow: true, |
| 2026 | receives_shadows: true, |
| 2027 | flip_normals: false, |
| 2028 | displace: None, |
| 2029 | }; |
| 2030 | let frame = |meshes: &[DrawMesh]| { |
| 2031 | let mut enc = device.create_command_encoder(&Default::default()); |
| 2032 | let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]); |
| 2033 | renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, 1000.0, SceneLights::default(), false, false, meshes); |
| 2034 | queue.submit(Some(enc.finish())); |
| 2035 | lock_or_recover(&renderer.meshes).entries.len() |
| 2036 | }; |
| 2037 | assert_eq!(frame(&[sphere(0.0, false)]), 1); |
| 2038 | assert_eq!(frame(&[sphere(0.5, false)]), 1, "a moved copy reuses the upload"); |
| 2039 | assert_eq!(frame(&[sphere(0.5, true)]), 2, "wireframe uses edge indices"); |
| 2040 | } |
| 2041 | |
| 2042 | #[test] |
| 2043 | fn lru_evicts_the_least_recently_used_entry_and_reuses_hits() { |
| 2044 | let mut lru = Lru::new(2); |
| 2045 | let builds = std::cell::Cell::new(0); |
| 2046 | let get = |lru: &mut Lru<u8, u8>, k: u8| lru.get_or_insert_with(k, || { builds.set(builds.get() + 1); k }); |
| 2047 | get(&mut lru, 1); |
| 2048 | get(&mut lru, 2); |
| 2049 | get(&mut lru, 1); |
| 2050 | get(&mut lru, 3); |
| 2051 | assert_eq!(builds.get(), 3, "second request for key 1 is a hit"); |
| 2052 | get(&mut lru, 1); |
| 2053 | assert_eq!(builds.get(), 3, "key 1 was refreshed, so key 2 was evicted"); |
| 2054 | get(&mut lru, 2); |
| 2055 | assert_eq!(builds.get(), 4); |
| 2056 | assert_eq!(lru.entries.len(), 2); |
| 2057 | } |
| 2058 | |
| 2059 | #[test] |
| 2060 | fn uv_affine_then_applies_self_first() { |
| 2061 | let shift = UvAffine { m: [1.0, 0.0, 0.0, 1.0], t: [0.5, 0.0] }; |
| 2062 | let double = UvAffine { m: [2.0, 0.0, 0.0, 2.0], t: [0.0, 0.0] }; |
| 2063 | assert_eq!(shift.then(&double).apply([0.0, 0.0]), [1.0, 0.0]); |
| 2064 | assert_eq!(double.then(&shift).apply([0.0, 0.0]), [0.5, 0.0]); |
| 2065 | } |
| 2066 | |
| 2067 | #[test] |
| 2068 | fn opengl_renderer_lighting_and_point_light_shadows() { |
| 2069 | let render_gl = |lighting: u8, shadows: u8| -> Option<Vec<u8>> { |
| 2070 | let src = format!( |
| 2071 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2072 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, |
| 2073 | Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, |
| 2074 | Blocker = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 0.8, }}, ["Transform3DOp.Translate.X"] = Input {{ Value = 0.4, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 0, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, |
| 2075 | Pt = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.6, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, Intensity = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }}, |
| 2076 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.5, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, |
| 2077 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Recv", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Blocker", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Pt", Source = "Output", }}, SceneInput4 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }}, |
| 2078 | R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, RendererType = Input {{ Value = FuID {{ "RendererOpenGL" }}, }}, ["RendererOpenGL.LightingEnabled"] = Input {{ Value = {lighting}, }}, ["RendererOpenGL.ShadowsEnabled"] = Input {{ Value = {shadows}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, |
| 2079 | }} }}"# |
| 2080 | ); |
| 2081 | let comp = Comp::from_fusion_str(&src).expect("parse shadow comp"); |
| 2082 | let mut eng = Engine::new_headless().ok()?; |
| 2083 | let id = comp.find_node("R").expect("R"); |
| 2084 | let (tex, _) = eng.evaluate(&comp, id, 0.0); |
| 2085 | eng.readback_rgba(&tex).ok() |
| 2086 | }; |
| 2087 | let (Some(unlit), Some(no_shad), Some(with_shad)) = (render_gl(0, 0), render_gl(1, 0), render_gl(1, 1)) else { |
| 2088 | return; |
| 2089 | }; |
| 2090 | // With LightingEnabled=0 under RendererOpenGL, receiver is pure flat white. |
| 2091 | let px = |buf: &[u8], x: usize, y: usize| buf[(y * 64 + x) * 4]; |
| 2092 | assert_eq!(px(&unlit, 8, 32), 255); |
| 2093 | // Blocker at (0,0,0) casts a shadow onto Recv (Z=-2) to the left of center when viewed from X=1.8. |
| 2094 | let dark_pixels = |buf: &[u8]| (0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count(); |
| 2095 | assert!(dark_pixels(&with_shad) > dark_pixels(&no_shad) + 15, "shadows should darken receiver: with={} vs without={}", dark_pixels(&with_shad), dark_pixels(&no_shad)); |
| 2096 | } |
| 2097 | |
| 2098 | #[test] |
| 2099 | fn transparent_textured_casters_cast_geometry_shadow() { |
| 2100 | let dark_receiver_pixels = |card_alpha: u8, shadows: u8| -> Option<usize> { |
| 2101 | let src = format!( |
| 2102 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2103 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, |
| 2104 | Bg = Background {{ Inputs = {{ Width = Input {{ Value = 8, }}, Height = Input {{ Value = 8, }}, TopLeftRed = Input {{ Value = 1, }}, TopLeftAlpha = Input {{ Value = {card_alpha}, }}, }}, }}, |
| 2105 | Tex = Texture2DOperator {{ Inputs = {{ Input = Input {{ SourceOp = "Bg", Source = "Output", }}, }}, }}, |
| 2106 | Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, |
| 2107 | Card = ImagePlane3D {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 0.4, }}, MaterialInput = Input {{ SourceOp = "Tex", Source = "MaterialOutput", }}, }}, }}, |
| 2108 | Pt = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.6, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }}, |
| 2109 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.5, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, |
| 2110 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Recv", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Card", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Pt", Source = "Output", }}, SceneInput4 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }}, |
| 2111 | R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, RendererType = Input {{ Value = FuID {{ "RendererOpenGL" }}, }}, ["RendererOpenGL.LightingEnabled"] = Input {{ Value = 1, }}, ["RendererOpenGL.ShadowsEnabled"] = Input {{ Value = {shadows}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, |
| 2112 | }} }}"# |
| 2113 | ); |
| 2114 | let comp = Comp::from_fusion_str(&src).expect("parse shadow comp"); |
| 2115 | let mut eng = Engine::new_headless().ok()?; |
| 2116 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0); |
| 2117 | let buf = eng.readback_rgba(&tex).ok()?; |
| 2118 | Some((0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count()) |
| 2119 | }; |
| 2120 | let (Some(opaque), Some(clear), Some(off)) = (dark_receiver_pixels(255, 1), dark_receiver_pixels(0, 1), dark_receiver_pixels(0, 0)) else { |
| 2121 | return; |
| 2122 | }; |
| 2123 | assert!(opaque > off + 15, "opaque card must shadow: {opaque} vs {off}"); |
| 2124 | assert!(clear > off + 15, "RendererOpenGL casts geometry shadows regardless of texture alpha: {clear} vs {off}"); |
| 2125 | } |
| 2126 | |
| 2127 | #[test] |
| 2128 | fn multi_light_point_shadows_both_cast() { |
| 2129 | let render_multi = |shadows: u8| -> Option<Vec<u8>> { |
| 2130 | let src = format!( |
| 2131 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2132 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, |
| 2133 | Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, |
| 2134 | Card = ImagePlane3D {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 0.0, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, }}, }}, |
| 2135 | PtL = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = -1.4, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, Intensity = Input {{ Value = 0.45, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }}, |
| 2136 | PtR = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.4, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, Intensity = Input {{ Value = 0.45, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }}, |
| 2137 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.5, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, |
| 2138 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Recv", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Card", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "PtL", Source = "Output", }}, SceneInput4 = Input {{ SourceOp = "PtR", Source = "Output", }}, SceneInput5 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }}, |
| 2139 | R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, RendererType = Input {{ Value = FuID {{ "RendererOpenGL" }}, }}, ["RendererOpenGL.LightingEnabled"] = Input {{ Value = 1, }}, ["RendererOpenGL.ShadowsEnabled"] = Input {{ Value = {shadows}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, |
| 2140 | }} }}"# |
| 2141 | ); |
| 2142 | let comp = Comp::from_fusion_str(&src).expect("parse multi-light shadow comp"); |
| 2143 | let mut eng = Engine::new_headless().ok()?; |
| 2144 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0); |
| 2145 | eng.readback_rgba(&tex).ok() |
| 2146 | }; |
| 2147 | let (Some(no_s), Some(with_s)) = (render_multi(0), render_multi(1)) else { |
| 2148 | return; |
| 2149 | }; |
| 2150 | // PtL casts shadow to the right (x=46, y=32), PtR casts shadow to the left (x=18, y=32). |
| 2151 | let px = |buf: &[u8], x: usize| u16::from(buf[(32 * 64 + x) * 4]); |
| 2152 | assert!(px(&with_s, 18) + 40 < px(&no_s, 18), "right light shadow missing on left: {} vs {}", px(&with_s, 18), px(&no_s, 18)); |
| 2153 | assert!(px(&with_s, 46) + 40 < px(&no_s, 46), "left light shadow missing on right: {} vs {}", px(&with_s, 46), px(&no_s, 46)); |
| 2154 | } |
| 2155 | |
| 2156 | #[test] |
| 2157 | fn shadow_caster_and_receiver_flags_are_honored() { |
| 2158 | let dark_receiver_pixels = |blocker_extra: &str, receiver_extra: &str, flat_extra: &str| -> Option<usize> { |
| 2159 | let src = format!( |
| 2160 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2161 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, {flat_extra} }}, }}, |
| 2162 | Recv = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 8, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = -2, }}, {receiver_extra} }}, }}, |
| 2163 | Blocker = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 0.8, }}, ["Transform3DOp.Translate.X"] = Input {{ Value = 0.4, }}, MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, {blocker_extra} }}, }}, |
| 2164 | Pt = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = 1.6, }}, ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, ["ShadowLightInputs3D.ShadowsEnabled"] = Input {{ Value = 1, }}, ["ShadowLightInputs3D.ShadowDensity"] = Input {{ Value = 1.0, }}, }}, }}, |
| 2165 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.5, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, |
| 2166 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Recv", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Blocker", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Pt", Source = "Output", }}, SceneInput4 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }}, |
| 2167 | R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, RendererType = Input {{ Value = FuID {{ "RendererOpenGL" }}, }}, ["RendererOpenGL.LightingEnabled"] = Input {{ Value = 1, }}, ["RendererOpenGL.ShadowsEnabled"] = Input {{ Value = 1, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, |
| 2168 | }} }}"# |
| 2169 | ); |
| 2170 | let comp = Comp::from_fusion_str(&src).expect("parse shadow comp"); |
| 2171 | let mut eng = Engine::new_headless().ok()?; |
| 2172 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0); |
| 2173 | let buf = eng.readback_rgba(&tex).ok()?; |
| 2174 | Some((0..64 * 64).filter(|&i| buf[i * 4 + 3] > 200 && buf[i * 4] < 40).count()) |
| 2175 | }; |
| 2176 | let no_caster = r#"["SurfacePlaneInputs.Lighting.IsShadowCaster"] = Input { Value = 0, },"#; |
| 2177 | let no_receive = r#"["MtlStdInputs.ReceivesShadows"] = Input { Value = 0, },"#; |
| 2178 | let flat_receiver = r#"MaterialInput = Input { SourceOp = "Flat", Source = "MaterialOutput", },"#; |
| 2179 | let (Some(shadowed), Some(uncast), Some(unreceived), Some(unreceived_by_material)) = ( |
| 2180 | dark_receiver_pixels("", "", ""), |
| 2181 | dark_receiver_pixels(no_caster, "", ""), |
| 2182 | dark_receiver_pixels("", no_receive, ""), |
| 2183 | dark_receiver_pixels("", flat_receiver, "ReceivesShadows = Input { Value = 0, },"), |
| 2184 | ) else { |
| 2185 | return; |
| 2186 | }; |
| 2187 | assert!(shadowed > uncast + 15, "baseline must shadow: {shadowed} vs {uncast}"); |
| 2188 | assert!(shadowed > unreceived + 15, "receiver opt-out must remove the shadow: {shadowed} vs {unreceived}"); |
| 2189 | assert_eq!(uncast, unreceived, "either flag alone removes the shadow entirely"); |
| 2190 | assert_eq!(uncast, unreceived_by_material, "a material shader owns the receiver flag"); |
| 2191 | } |
| 2192 | |
| 2193 | #[test] |
| 2194 | fn shadow_vram_bytes_tracks_pool_and_clear_resets_both_caches() { |
| 2195 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 2196 | let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; |
| 2197 | let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; |
| 2198 | let renderer = Scene3DRenderer::new(&device); |
| 2199 | assert_eq!(renderer.shadow_vram_bytes(), 0); |
| 2200 | |
| 2201 | let _ = renderer.get_or_build_text3d_mesh(42, || vec![Vertex3D { pos: [0.0; 3], normal: [0.0, 0.0, 1.0], uv: [0.0; 2] }]); |
| 2202 | assert_eq!(lock_or_recover(&renderer.text3d_mesh_cache).entries.len(), 1); |
| 2203 | |
| 2204 | let tex = device.create_texture(&wgpu::TextureDescriptor { |
| 2205 | label: None, |
| 2206 | size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 }, |
| 2207 | mip_level_count: 1, |
| 2208 | sample_count: 1, |
| 2209 | dimension: wgpu::TextureDimension::D2, |
| 2210 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 2211 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 2212 | view_formats: &[], |
| 2213 | }); |
| 2214 | let dst = CachedTexture::from_texture(tex, [8, 8], 0); |
| 2215 | let dummy = dst.clone(); |
| 2216 | let mut lights = SceneLights::default(); |
| 2217 | lights.points.push(PointLight { |
| 2218 | pos: [0.0, 0.0, 2.0], |
| 2219 | color: [1.0, 1.0, 1.0], |
| 2220 | decay_type: 0.0, |
| 2221 | decay_rate: 0.0, |
| 2222 | shadow_density: Some(1.0), |
| 2223 | }); |
| 2224 | let mut enc = device.create_command_encoder(&Default::default()); |
| 2225 | renderer.render_meshes( |
| 2226 | &device, |
| 2227 | &queue, |
| 2228 | &mut enc, |
| 2229 | &dst, |
| 2230 | &dummy, |
| 2231 | mat4_identity(), |
| 2232 | mat4_identity(), |
| 2233 | [0.0, 0.0, 5.0], |
| 2234 | 100.0, |
| 2235 | lights, |
| 2236 | true, |
| 2237 | true, |
| 2238 | &[], |
| 2239 | ); |
| 2240 | queue.submit(Some(enc.finish())); |
| 2241 | |
| 2242 | // 1 shadow light = 6 R32Float layers + 1 Depth32Float texture = 7 * 1024 * 1024 * 4 bytes. |
| 2243 | let expected = u64::from(SHADOW_MAP_SIZE) * u64::from(SHADOW_MAP_SIZE) * 4 * 7; |
| 2244 | assert_eq!(renderer.shadow_vram_bytes(), expected); |
| 2245 | |
| 2246 | renderer.clear_shadow_targets(); |
| 2247 | assert_eq!(renderer.shadow_vram_bytes(), 0); |
| 2248 | assert_eq!(renderer.depth_vram_bytes(), 0); |
| 2249 | assert_eq!(lock_or_recover(&renderer.text3d_mesh_cache).entries.len(), 0); |
| 2250 | } |
| 2251 | |
| 2252 | #[test] |
| 2253 | fn depth_targets_are_reused_by_size_and_cleared_on_clear_targets() { |
| 2254 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 2255 | let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; |
| 2256 | let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; |
| 2257 | let renderer = Scene3DRenderer::new(&device); |
| 2258 | let make_tex = |w, h| { |
| 2259 | CachedTexture::from_texture( |
| 2260 | device.create_texture(&wgpu::TextureDescriptor { |
| 2261 | label: None, |
| 2262 | size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 2263 | mip_level_count: 1, |
| 2264 | sample_count: 1, |
| 2265 | dimension: wgpu::TextureDimension::D2, |
| 2266 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 2267 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 2268 | view_formats: &[], |
| 2269 | }), |
| 2270 | [w, h], |
| 2271 | 0, |
| 2272 | ) |
| 2273 | }; |
| 2274 | let dst_a = make_tex(16, 16); |
| 2275 | let dst_b = make_tex(32, 16); |
| 2276 | let dummy = make_tex(8, 8); |
| 2277 | let render_empty = |dst: &CachedTexture| { |
| 2278 | let mut enc = device.create_command_encoder(&Default::default()); |
| 2279 | renderer.render_meshes( |
| 2280 | &device, |
| 2281 | &queue, |
| 2282 | &mut enc, |
| 2283 | dst, |
| 2284 | &dummy, |
| 2285 | mat4_identity(), |
| 2286 | mat4_identity(), |
| 2287 | [0.0, 0.0, 5.0], |
| 2288 | 100.0, |
| 2289 | SceneLights::default(), |
| 2290 | false, |
| 2291 | false, |
| 2292 | &[], |
| 2293 | ); |
| 2294 | queue.submit(Some(enc.finish())); |
| 2295 | }; |
| 2296 | |
| 2297 | render_empty(&dst_a); |
| 2298 | assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 1); |
| 2299 | assert_eq!(renderer.depth_vram_bytes(), 16 * 16 * 4); |
| 2300 | |
| 2301 | render_empty(&dst_a); |
| 2302 | assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 1); |
| 2303 | assert_eq!(renderer.depth_vram_bytes(), 16 * 16 * 4); |
| 2304 | |
| 2305 | render_empty(&dst_b); |
| 2306 | assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 2); |
| 2307 | assert_eq!(renderer.depth_vram_bytes(), (16 * 16 + 32 * 16) * 4); |
| 2308 | |
| 2309 | renderer.clear_targets(); |
| 2310 | assert_eq!(lock_or_recover(&renderer.depth_targets).entries.len(), 0); |
| 2311 | assert_eq!(renderer.depth_vram_bytes(), 0); |
| 2312 | } |
| 2313 | |
| 2314 | #[test] |
| 2315 | fn gpu_mesh_buffer_cache_hits_bounds_lru_and_clears_on_bust() { |
| 2316 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 2317 | let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; |
| 2318 | let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; |
| 2319 | let renderer = Scene3DRenderer::new(&device); |
| 2320 | let make_tex = |w, h| { |
| 2321 | CachedTexture::from_texture( |
| 2322 | device.create_texture(&wgpu::TextureDescriptor { |
| 2323 | label: None, |
| 2324 | size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 2325 | mip_level_count: 1, |
| 2326 | sample_count: 1, |
| 2327 | dimension: wgpu::TextureDimension::D2, |
| 2328 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 2329 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 2330 | view_formats: &[], |
| 2331 | }), |
| 2332 | [w, h], |
| 2333 | 0, |
| 2334 | ) |
| 2335 | }; |
| 2336 | let (dst, dummy) = (make_tex(16, 16), make_tex(8, 8)); |
| 2337 | let make_custom = |z_offset: f32| -> DrawMesh { |
| 2338 | let tri = vec![ |
| 2339 | Vertex3D { pos: [-0.5, -0.5, z_offset], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }, |
| 2340 | Vertex3D { pos: [0.5, -0.5, z_offset], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }, |
| 2341 | Vertex3D { pos: [0.0, 0.5, z_offset], normal: [0.0, 0.0, 1.0], uv: [0.5, 0.0] }, |
| 2342 | ]; |
| 2343 | DrawMesh { |
| 2344 | world: mat4_identity(), |
| 2345 | shape: ShapeKind::CustomMesh(Arc::new(tri)), |
| 2346 | custom_mesh_key: None, |
| 2347 | tex: None, |
| 2348 | bump_tex: None, |
| 2349 | diffuse_col: [1.0; 4], |
| 2350 | specular_col: [1.0; 3], |
| 2351 | specular_intensity: 0.0, |
| 2352 | specular_exponent: 50.0, |
| 2353 | affected_by_lights: false, |
| 2354 | casts_shadow: false, |
| 2355 | receives_shadows: false, |
| 2356 | flip_normals: false, |
| 2357 | displace: None, |
| 2358 | } |
| 2359 | }; |
| 2360 | let render_one = |m: DrawMesh| { |
| 2361 | let mut enc = device.create_command_encoder(&Default::default()); |
| 2362 | renderer.render_meshes( |
| 2363 | &device, |
| 2364 | &queue, |
| 2365 | &mut enc, |
| 2366 | &dst, |
| 2367 | &dummy, |
| 2368 | mat4_identity(), |
| 2369 | mat4_identity(), |
| 2370 | [0.0, 0.0, 5.0], |
| 2371 | 100.0, |
| 2372 | SceneLights::default(), |
| 2373 | false, |
| 2374 | false, |
| 2375 | &[m], |
| 2376 | ); |
| 2377 | queue.submit(Some(enc.finish())); |
| 2378 | }; |
| 2379 | |
| 2380 | // 1. Repeated identical frames hit both GPU mesh cache and uniform cache, even across Arc drop/reallocation. |
| 2381 | render_one(make_custom(0.0)); |
| 2382 | let vram_1 = renderer.mesh_vram_bytes(); |
| 2383 | assert_eq!(renderer.gpu_mesh_count(), 1); |
| 2384 | assert!(vram_1 > 0); |
| 2385 | assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1); |
| 2386 | |
| 2387 | render_one(make_custom(0.0)); |
| 2388 | assert_eq!(renderer.gpu_mesh_count(), 1, "rebuilt identical Arc must hit content-keyed mesh cache"); |
| 2389 | assert_eq!(renderer.mesh_vram_bytes(), vram_1); |
| 2390 | assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1, "identical uniform bytes reuse cached buffer"); |
| 2391 | |
| 2392 | // 2. Eviction stays strictly bounded by MAX_CACHED_MESH_BUFFERS (128). |
| 2393 | for i in 1..=(MAX_CACHED_MESH_BUFFERS + 20) { |
| 2394 | render_one(make_custom(i as f32 * 0.01)); |
| 2395 | } |
| 2396 | assert_eq!(renderer.gpu_mesh_count(), MAX_CACHED_MESH_BUFFERS); |
| 2397 | assert!(lock_or_recover(&renderer.uniform_cache).entries.len() <= UNIFORM_CACHE_CAP); |
| 2398 | |
| 2399 | // 3. clear_shadow_targets() (called by bust_gpu_cache) releases all cached GPU mesh and uniform buffers. |
| 2400 | renderer.clear_shadow_targets(); |
| 2401 | assert_eq!(renderer.gpu_mesh_count(), 0); |
| 2402 | assert_eq!(renderer.mesh_vram_bytes(), 0); |
| 2403 | assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 0); |
| 2404 | } |
| 2405 | |
| 2406 | #[test] |
| 2407 | fn cube3d_semi_transparent_front_face_reveals_opaque_interior_faces() { |
| 2408 | let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { |
| 2409 | 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, }, }, }, |
| 2410 | Tex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, }, }, |
| 2411 | Cube = Cube3D { Inputs = { FrontMaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, }, |
| 2412 | Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 3.0, }, }, }, |
| 2413 | Amb = LightAmbient { Inputs = { Intensity = Input { Value = 0.25, }, }, }, |
| 2414 | M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cube", Source = "Output", }, SceneInput2 = Input { SourceOp = "Amb", Source = "Output", }, SceneInput3 = Input { SourceOp = "Cam", Source = "Output", }, }, }, |
| 2415 | R = Renderer3D { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, ["RendererSoftware.LightingEnabled"] = Input { Value = 1, }, SceneInput = Input { SourceOp = "M", Source = "Output", }, }, }, |
| 2416 | } }"#; |
| 2417 | let comp = Comp::from_fusion_str(src).expect("parse Cube3D comp"); |
| 2418 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2419 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0); |
| 2420 | let px = eng.readback_rgba(&tex).expect("readback Cube3D"); |
| 2421 | let c = center(&px); |
| 2422 | assert_eq!(c[3], 255, "transparent front face must reveal opaque back face inside cube: {c:?}"); |
| 2423 | assert!((c[0] as i32 - 64).abs() <= 2, "back face should show 0.25 ambient gray: {c:?}"); |
| 2424 | } |
| 2425 | |
| 2426 | #[test] |
| 2427 | fn diffuse_color_alpha_modulates_alpha_without_scaling_rgb() { |
| 2428 | let render_mat = |extra: &str| -> Option<[u8; 4]> { |
| 2429 | let scene = format!( |
| 2430 | 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} }}, }}, |
| 2431 | P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 4, }}, MaterialInput = Input {{ SourceOp = "Mtl", Source = "MaterialOutput", }}, }}, }}, |
| 2432 | L = LightDirectional {{ }}, |
| 2433 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 2434 | ); |
| 2435 | render(true, &scene).map(|px| center(&px)) |
| 2436 | }; |
| 2437 | let Some(ca) = render_mat(r#"["Diffuse.Color.Alpha"] = Input { Value = 0.5, },"#) else { return }; |
| 2438 | let Some(op) = render_mat(r#"["Diffuse.Opacity"] = Input { Value = 0.5, },"#) else { return }; |
| 2439 | 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:?}"); |
| 2440 | assert!((ca[3] as i32 - 128).abs() <= 2, "Diffuse.Color.Alpha must set output alpha: {ca:?}"); |
| 2441 | 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:?}"); |
| 2442 | assert!((op[3] as i32 - 128).abs() <= 2, "Diffuse.Opacity sets output alpha: {op:?}"); |
| 2443 | } |
| 2444 | |
| 2445 | #[test] |
| 2446 | fn cook_torrance_refractive_index_drives_fresnel_specular() { |
| 2447 | let render_ct = |ri: f32, do_fresnel: u8| -> Option<u8> { |
| 2448 | let scene = format!( |
| 2449 | 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}, }}, }}, }}, |
| 2450 | P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 4, }}, MaterialInput = Input {{ SourceOp = "Mtl", Source = "MaterialOutput", }}, }}, }}, |
| 2451 | L = LightDirectional {{ }}, |
| 2452 | M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# |
| 2453 | ); |
| 2454 | render(true, &scene).map(|px| center(&px)[0]) |
| 2455 | }; |
| 2456 | let (Some(n1), Some(n2), Some(n3), Some(no_f)) = ( |
| 2457 | render_ct(1.0, 1), |
| 2458 | render_ct(2.0, 1), |
| 2459 | render_ct(2.9, 1), |
| 2460 | render_ct(2.0, 0), |
| 2461 | ) else { |
| 2462 | return; |
| 2463 | }; |
| 2464 | assert_eq!(n1, 0, "RI=1.0 has zero Fresnel reflectance"); |
| 2465 | assert!(n2 > n1 && n3 > n2, "higher RI must strengthen specular: n1={n1} n2={n2} n3={n3}"); |
| 2466 | assert!(no_f > n3, "DoFresnel=0 disables Fresnel attenuation: no_f={no_f} vs n3={n3}"); |
| 2467 | } |
| 2468 | |
| 2469 | #[test] |
| 2470 | fn unlit_premultiplied_emissive_texture_preserves_rgb() { |
| 2471 | 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, }, }, }, |
| 2472 | EmissiveTex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "EmissiveBg", Source = "Output", }, }, }, |
| 2473 | Card = ImagePlane3D { Inputs = { ["Transform3DOp.Scale.X"] = Input { Value = 4, }, MaterialInput = Input { SourceOp = "EmissiveTex", Source = "MaterialOutput", }, }, }, |
| 2474 | M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Card", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#; |
| 2475 | let Some(px) = render(true, scene) else { return }; |
| 2476 | let c = center(&px); |
| 2477 | 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:?}"); |
| 2478 | assert!((c[3] as i32 - 128).abs() <= 2, "alpha must remain 0.5: {c:?}"); |
| 2479 | } |
| 2480 | |
| 2481 | #[test] |
| 2482 | fn lru_byte_cap_evicts_least_recently_used_entries() { |
| 2483 | let mut lru: Lru<u8, (u8, u64)> = Lru::with_byte_cap(16, 100, |v| v.1); |
| 2484 | lru.get_or_insert_with(1, || (1, 40)); |
| 2485 | lru.get_or_insert_with(2, || (2, 40)); |
| 2486 | assert_eq!(lru.total_bytes, 80); |
| 2487 | // Touch key 1 so key 2 becomes LRU before inserting key 3 (80 + 40 > 100). |
| 2488 | assert_eq!(lru.get(1), Some((1, 40))); |
| 2489 | lru.get_or_insert_with(3, || (3, 40)); |
| 2490 | assert_eq!(lru.total_bytes, 80); |
| 2491 | assert_eq!(lru.get(2), None, "LRU key 2 must be evicted to satisfy byte cap"); |
| 2492 | assert_eq!(lru.get(1), Some((1, 40))); |
| 2493 | assert_eq!(lru.get(3), Some((3, 40))); |
| 2494 | // Entries larger than max_bytes are returned without busting the cache or exceeding max_bytes. |
| 2495 | let oversized = lru.get_or_insert_with(4, || (4, 150)); |
| 2496 | assert_eq!(oversized, (4, 150)); |
| 2497 | assert_eq!(lru.total_bytes, 80); |
| 2498 | assert_eq!(lru.entries.len(), 2); |
| 2499 | } |
| 2500 | |
| 2501 | #[test] |
| 2502 | fn mesh_and_uniform_byte_caps_evict_lru_and_track_uniform_vram_bytes() { |
| 2503 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 2504 | let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; |
| 2505 | let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; |
| 2506 | let renderer = Scene3DRenderer::new(&device); |
| 2507 | let make_tex = |w, h| { |
| 2508 | CachedTexture::from_texture( |
| 2509 | device.create_texture(&wgpu::TextureDescriptor { |
| 2510 | label: None, |
| 2511 | size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 2512 | mip_level_count: 1, |
| 2513 | sample_count: 1, |
| 2514 | dimension: wgpu::TextureDimension::D2, |
| 2515 | format: wgpu::TextureFormat::Rgba8Unorm, |
| 2516 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, |
| 2517 | view_formats: &[], |
| 2518 | }), |
| 2519 | [w, h], |
| 2520 | 0, |
| 2521 | ) |
| 2522 | }; |
| 2523 | let (dst, dummy) = (make_tex(16, 16), make_tex(8, 8)); |
| 2524 | let make_mesh = |n_tris: usize, z: f32| -> DrawMesh { |
| 2525 | let mut verts = Vec::with_capacity(n_tris * 3); |
| 2526 | for i in 0..n_tris { |
| 2527 | let off = i as f32 * 0.001 + z; |
| 2528 | verts.push(Vertex3D { pos: [-0.5, -0.5, off], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }); |
| 2529 | verts.push(Vertex3D { pos: [0.5, -0.5, off], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }); |
| 2530 | verts.push(Vertex3D { pos: [0.0, 0.5, off], normal: [0.0, 0.0, 1.0], uv: [0.5, 0.0] }); |
| 2531 | } |
| 2532 | DrawMesh { |
| 2533 | world: mat4_identity(), |
| 2534 | shape: ShapeKind::CustomMesh(Arc::new(verts)), |
| 2535 | custom_mesh_key: None, |
| 2536 | tex: None, |
| 2537 | bump_tex: None, |
| 2538 | diffuse_col: [1.0; 4], |
| 2539 | specular_col: [1.0; 3], |
| 2540 | specular_intensity: 0.0, |
| 2541 | specular_exponent: 50.0, |
| 2542 | affected_by_lights: false, |
| 2543 | casts_shadow: false, |
| 2544 | receives_shadows: false, |
| 2545 | flip_normals: false, |
| 2546 | displace: None, |
| 2547 | } |
| 2548 | }; |
| 2549 | let render_one = |m: DrawMesh| { |
| 2550 | let mut enc = device.create_command_encoder(&Default::default()); |
| 2551 | renderer.render_meshes( |
| 2552 | &device, |
| 2553 | &queue, |
| 2554 | &mut enc, |
| 2555 | &dst, |
| 2556 | &dummy, |
| 2557 | mat4_identity(), |
| 2558 | mat4_identity(), |
| 2559 | [0.0, 0.0, 5.0], |
| 2560 | 100.0, |
| 2561 | SceneLights::default(), |
| 2562 | false, |
| 2563 | false, |
| 2564 | &[m], |
| 2565 | ); |
| 2566 | queue.submit(Some(enc.finish())); |
| 2567 | }; |
| 2568 | |
| 2569 | // Render one mesh and verify default caps and uniform_vram_bytes tracking. |
| 2570 | render_one(make_mesh(20, 0.0)); |
| 2571 | let single_mesh_bytes = renderer.mesh_vram_bytes(); |
| 2572 | let single_uni_bytes = renderer.uniform_vram_bytes(); |
| 2573 | assert!(single_mesh_bytes > 0 && single_mesh_bytes <= MAX_CACHED_MESH_BYTES); |
| 2574 | assert!(single_uni_bytes > 0 && single_uni_bytes <= MAX_CACHED_UNIFORM_BYTES); |
| 2575 | |
| 2576 | // Enforce tight byte caps (< 2 entries) and confirm LRU eviction caps both pools. |
| 2577 | lock_or_recover(&renderer.meshes).max_bytes = single_mesh_bytes + single_mesh_bytes / 2; |
| 2578 | lock_or_recover(&renderer.uniform_cache).max_bytes = single_uni_bytes + single_uni_bytes / 2; |
| 2579 | |
| 2580 | render_one(make_mesh(20, 1.0)); |
| 2581 | assert_eq!(renderer.gpu_mesh_count(), 1, "mesh byte cap must evict LRU mesh"); |
| 2582 | assert_eq!(renderer.mesh_vram_bytes(), single_mesh_bytes); |
| 2583 | assert_eq!(lock_or_recover(&renderer.uniform_cache).entries.len(), 1, "uniform byte cap must evict LRU uniform"); |
| 2584 | assert_eq!(renderer.uniform_vram_bytes(), single_uni_bytes); |
| 2585 | |
| 2586 | renderer.clear_shadow_targets(); |
| 2587 | assert_eq!(renderer.uniform_vram_bytes(), 0); |
| 2588 | assert_eq!(renderer.mesh_vram_bytes(), 0); |
| 2589 | } |
| 2590 | |
| 2591 | fn readback_aux_tex(eng: &Engine, aux: &AuxChannelTex, bpp: u32) -> Vec<u8> { |
| 2592 | let [w, h] = aux.size; |
| 2593 | let unpadded_bpr = w * bpp; |
| 2594 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; |
| 2595 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; |
| 2596 | let buf = eng.device().create_buffer(&wgpu::BufferDescriptor { |
| 2597 | label: Some("readback-aux"), |
| 2598 | size: u64::from(padded_bpr) * u64::from(h), |
| 2599 | usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, |
| 2600 | mapped_at_creation: false, |
| 2601 | }); |
| 2602 | let mut enc = eng.device().create_command_encoder(&Default::default()); |
| 2603 | enc.copy_texture_to_buffer( |
| 2604 | aux.texture.as_image_copy(), |
| 2605 | wgpu::TexelCopyBufferInfo { |
| 2606 | buffer: &buf, |
| 2607 | layout: wgpu::TexelCopyBufferLayout { |
| 2608 | offset: 0, |
| 2609 | bytes_per_row: Some(padded_bpr), |
| 2610 | rows_per_image: Some(h), |
| 2611 | }, |
| 2612 | }, |
| 2613 | wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, |
| 2614 | ); |
| 2615 | eng.queue().submit(Some(enc.finish())); |
| 2616 | let slice = buf.slice(..); |
| 2617 | let (tx, rx) = std::sync::mpsc::channel(); |
| 2618 | slice.map_async(wgpu::MapMode::Read, move |res| { |
| 2619 | let _ = tx.send(res); |
| 2620 | }); |
| 2621 | eng.device() |
| 2622 | .poll(wgpu::PollType::Wait { |
| 2623 | submission_index: None, |
| 2624 | timeout: Some(std::time::Duration::from_secs(10)), |
| 2625 | }) |
| 2626 | .unwrap(); |
| 2627 | rx.recv().unwrap().unwrap(); |
| 2628 | let data = slice.get_mapped_range().unwrap(); |
| 2629 | let mut out = Vec::with_capacity((unpadded_bpr * h) as usize); |
| 2630 | for y in 0..h as usize { |
| 2631 | let start = y * padded_bpr as usize; |
| 2632 | out.extend_from_slice(&data[start..start + unpadded_bpr as usize]); |
| 2633 | } |
| 2634 | drop(data); |
| 2635 | buf.unmap(); |
| 2636 | out |
| 2637 | } |
| 2638 | |
| 2639 | #[test] |
| 2640 | fn renderer3d_z_and_normal_aux_channels_match_fusion_convention() { |
| 2641 | let make_comp = |proj_type: &str, ch_z: u8, ch_n: u8| -> Comp { |
| 2642 | let src = format!( |
| 2643 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2644 | Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, |
| 2645 | P = Shape3D {{ Inputs = {{ |
| 2646 | ["SurfacePlaneInputs.Width"] = Input {{ Value = 0.5, }}, |
| 2647 | ["SurfacePlaneInputs.Height"] = Input {{ Value = 0.5, }}, |
| 2648 | ["Transform3DOp.Translate.Z"] = Input {{ Value = -1.0, }}, |
| 2649 | MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, |
| 2650 | }}, }}, |
| 2651 | Cam = Camera3D {{ Inputs = {{ |
| 2652 | ProjectionType = Input {{ Value = FuID {{ "{proj_type}" }}, }}, |
| 2653 | ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, |
| 2654 | ApertureW = Input {{ Value = 1.0, }}, |
| 2655 | ApertureH = Input {{ Value = 1.0, }}, |
| 2656 | }}, }}, |
| 2657 | M = Merge3D {{ Inputs = {{ |
| 2658 | SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, |
| 2659 | SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, |
| 2660 | }}, }}, |
| 2661 | R = Renderer3D {{ Inputs = {{ |
| 2662 | Width = Input {{ Value = 64, }}, |
| 2663 | Height = Input {{ Value = 64, }}, |
| 2664 | ["RendererSoftware.Channels.Z"] = Input {{ Value = {ch_z}, }}, |
| 2665 | ["RendererSoftware.Channels.Normal"] = Input {{ Value = {ch_n}, }}, |
| 2666 | SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, |
| 2667 | }}, }}, |
| 2668 | }} }}"# |
| 2669 | ); |
| 2670 | Comp::from_fusion_str(&src).expect("parse Z/Normal comp") |
| 2671 | }; |
| 2672 | |
| 2673 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2674 | |
| 2675 | // 1. Both channels disabled -> zero aux allocation (`aux == None`). |
| 2676 | let comp_off = make_comp("Perspective", 0, 0); |
| 2677 | let (tex_off, _) = eng.evaluate(&comp_off, comp_off.find_node("R").unwrap(), 0.0); |
| 2678 | assert!(tex_off.aux.is_none(), "aux must stay None when Z and Normal are disabled"); |
| 2679 | |
| 2680 | // 2. Perspective & Orthographic cameras both yield Z = -3.0 at center and EMPTY_Z_SENTINEL at corner. |
| 2681 | for proj_type in ["Perspective", "Orthographic"] { |
| 2682 | let comp = make_comp(proj_type, 1, 1); |
| 2683 | let r_id = comp.find_node("R").unwrap(); |
| 2684 | let (tex, _) = eng.evaluate(&comp, r_id, 0.0); |
| 2685 | let aux = tex.aux.as_ref().expect("aux channels must be attached"); |
| 2686 | let z_tex = aux.z.as_ref().expect("aux.z must be present"); |
| 2687 | let n_tex = aux.normal.as_ref().expect("aux.normal must be present"); |
| 2688 | assert_eq!(z_tex.format, wgpu::TextureFormat::R32Float); |
| 2689 | assert_eq!(n_tex.format, wgpu::TextureFormat::Rgba16Float); |
| 2690 | |
| 2691 | let z_bytes = readback_aux_tex(&eng, z_tex, 4); |
| 2692 | let z_vals: &[f32] = bytemuck::cast_slice(&z_bytes); |
| 2693 | let center_z = z_vals[32 * 64 + 32]; |
| 2694 | let corner_z = z_vals[0]; |
| 2695 | assert!( |
| 2696 | (center_z - (-3.0)).abs() <= 1e-3, |
| 2697 | "{proj_type} center Z should be -3.0, got {center_z}" |
| 2698 | ); |
| 2699 | assert_eq!( |
| 2700 | corner_z, EMPTY_Z_SENTINEL, |
| 2701 | "{proj_type} empty corner Z should be EMPTY_Z_SENTINEL, got {corner_z}" |
| 2702 | ); |
| 2703 | |
| 2704 | let n_bytes = readback_aux_tex(&eng, n_tex, 8); |
| 2705 | let read_n = |x: usize, y: usize| -> [f32; 4] { |
| 2706 | let off = (y * 64 + x) * 8; |
| 2707 | [ |
| 2708 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off], n_bytes[off + 1]])).to_f32(), |
| 2709 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 2], n_bytes[off + 3]])).to_f32(), |
| 2710 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 4], n_bytes[off + 5]])).to_f32(), |
| 2711 | ::exr::prelude::f16::from_bits(u16::from_le_bytes([n_bytes[off + 6], n_bytes[off + 7]])).to_f32(), |
| 2712 | ] |
| 2713 | }; |
| 2714 | let cn = read_n(32, 32); |
| 2715 | let kn = read_n(0, 0); |
| 2716 | assert!( |
| 2717 | cn[0].abs() <= 1e-3 && cn[1].abs() <= 1e-3 && (cn[2] - 1.0).abs() <= 1e-3 && cn[3].abs() <= 1e-3, |
| 2718 | "{proj_type} center normal should be (0,0,1,0), got {cn:?}" |
| 2719 | ); |
| 2720 | assert_eq!(kn, [0.0, 0.0, 0.0, 0.0], "{proj_type} corner normal should be zero"); |
| 2721 | } |
| 2722 | |
| 2723 | // 3. Toggling Channels.Z on an existing comp updates cache key cleanly. |
| 2724 | let (tex_cached_off, _) = eng.evaluate(&make_comp("Perspective", 0, 0), comp_off.find_node("R").unwrap(), 0.0); |
| 2725 | assert!(tex_cached_off.aux.is_none()); |
| 2726 | } |
| 2727 | |
| 2728 | #[test] |
| 2729 | fn mtl_ward_anisotropic_spread_u_vs_v_stretches_specular_highlight() { |
| 2730 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2731 | let mut render = |su: f32, sv: f32| -> Vec<u8> { |
| 2732 | let src = format!( |
| 2733 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2734 | Ward = MtlWard {{ Inputs = {{ |
| 2735 | ["Diffuse.Color.Red"] = Input {{ Value = 0.0, }}, |
| 2736 | ["Diffuse.Color.Green"] = Input {{ Value = 0.0, }}, |
| 2737 | ["Diffuse.Color.Blue"] = Input {{ Value = 0.0, }}, |
| 2738 | ["Specular.Intensity"] = Input {{ Value = 1.0, }}, |
| 2739 | ["Specular.SpreadU"] = Input {{ Value = {su}, }}, |
| 2740 | ["Specular.SpreadV"] = Input {{ Value = {sv}, }}, |
| 2741 | }}, }}, |
| 2742 | S = Shape3D {{ Inputs = {{ |
| 2743 | Shape = Input {{ Value = FuID {{ "SurfaceSphereInputs" }}, }}, |
| 2744 | ["SurfaceSphereInputs.Radius"] = Input {{ Value = 1.0, }}, |
| 2745 | MaterialInput = Input {{ SourceOp = "Ward", Source = "MaterialOutput", }}, |
| 2746 | }}, }}, |
| 2747 | L = LightDirectional {{ Inputs = {{ Intensity = Input {{ Value = 2.0, }}, }}, }}, |
| 2748 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 5.5, }}, }}, }}, |
| 2749 | M = Merge3D {{ Inputs = {{ |
| 2750 | SceneInput1 = Input {{ SourceOp = "S", Source = "Output", }}, |
| 2751 | SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, |
| 2752 | SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, |
| 2753 | }}, }}, |
| 2754 | R = Renderer3D {{ Inputs = {{ |
| 2755 | Width = Input {{ Value = 64, }}, |
| 2756 | Height = Input {{ Value = 64, }}, |
| 2757 | ["RendererSoftware.LightingEnabled"] = Input {{ Value = 1, }}, |
| 2758 | SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, |
| 2759 | }}, }}, |
| 2760 | }} }}"# |
| 2761 | ); |
| 2762 | let comp = Comp::from_fusion_str(&src).unwrap(); |
| 2763 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); |
| 2764 | eng.readback_rgba(&tex).unwrap() |
| 2765 | }; |
| 2766 | let horiz = render(0.45, 0.05); |
| 2767 | let vert = render(0.05, 0.45); |
| 2768 | let px_r = |buf: &[u8], x: usize, y: usize| buf[(y * 64 + x) * 4] as f32; |
| 2769 | // Sample off-center along horizontal vs vertical axes from sphere center (32, 32). |
| 2770 | let h_horiz = px_r(&horiz, 40, 32) + px_r(&horiz, 24, 32); |
| 2771 | let h_vert = px_r(&horiz, 32, 40) + px_r(&horiz, 32, 24); |
| 2772 | let v_horiz = px_r(&vert, 40, 32) + px_r(&vert, 24, 32); |
| 2773 | let v_vert = px_r(&vert, 32, 40) + px_r(&vert, 32, 24); |
| 2774 | assert!(h_horiz > h_vert + 5.0, "wide SpreadU should stretch highlight horizontally: h={h_horiz} v={h_vert}"); |
| 2775 | assert!(v_vert > v_horiz + 5.0, "wide SpreadV should stretch highlight vertically: h={v_horiz} v={v_vert}"); |
| 2776 | } |
| 2777 | |
| 2778 | #[test] |
| 2779 | fn spheremap_and_mtl_reflect_fresnel_and_constant_strength() { |
| 2780 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2781 | let mut render_reflect = |strength_var: u8, face_on: f32, glancing: f32, rot_y: f32| -> Vec<u8> { |
| 2782 | let src = format!( |
| 2783 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ |
| 2784 | Env = Background {{ Inputs = {{ |
| 2785 | Width = Input {{ Value = 64, }}, |
| 2786 | Height = Input {{ Value = 32, }}, |
| 2787 | Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, |
| 2788 | TopLeftRed = Input {{ Value = 1.0, }}, TopLeftGreen = Input {{ Value = 0.0, }}, TopLeftBlue = Input {{ Value = 0.0, }}, |
| 2789 | TopRightRed = Input {{ Value = 0.0, }}, TopRightGreen = Input {{ Value = 0.0, }}, TopRightBlue = Input {{ Value = 1.0, }}, |
| 2790 | }}, }}, |
| 2791 | SMap = SphereMap {{ Inputs = {{ |
| 2792 | Image = Input {{ SourceOp = "Env", Source = "Output", }}, |
| 2793 | ["Rotate.Y"] = Input {{ Value = {rot_y}, }}, |
| 2794 | }}, }}, |
| 2795 | Dark = MtlBlinn {{ Inputs = {{ |
| 2796 | ["Diffuse.Color.Red"] = Input {{ Value = 0.0, }}, |
| 2797 | ["Diffuse.Color.Green"] = Input {{ Value = 0.0, }}, |
| 2798 | ["Diffuse.Color.Blue"] = Input {{ Value = 0.0, }}, |
| 2799 | ["Specular.Intensity"] = Input {{ Value = 0.0, }}, |
| 2800 | }}, }}, |
| 2801 | Refl = MtlReflect {{ Inputs = {{ |
| 2802 | BackgroundMaterial = Input {{ SourceOp = "Dark", Source = "MaterialOutput", }}, |
| 2803 | ["Reflection.Color.Material"] = Input {{ SourceOp = "SMap", Source = "MaterialOutput", }}, |
| 2804 | ["Reflection.StrengthVariability"] = Input {{ Value = {strength_var}, }}, |
| 2805 | ["Reflection.ConstantStrength"] = Input {{ Value = 1.0, }}, |
| 2806 | ["Reflection.FaceOnStrength"] = Input {{ Value = {face_on}, }}, |
| 2807 | ["Reflection.GlancingStrength"] = Input {{ Value = {glancing}, }}, |
| 2808 | ["Reflection.Falloff"] = Input {{ Value = 2.0, }}, |
| 2809 | }}, }}, |
| 2810 | S = Shape3D {{ Inputs = {{ |
| 2811 | Shape = Input {{ Value = FuID {{ "SurfaceSphereInputs" }}, }}, |
| 2812 | ["SurfaceSphereInputs.Radius"] = Input {{ Value = 1.0, }}, |
| 2813 | MaterialInput = Input {{ SourceOp = "Refl", Source = "MaterialOutput", }}, |
| 2814 | }}, }}, |
| 2815 | Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 6.0, }}, }}, }}, |
| 2816 | M = Merge3D {{ Inputs = {{ |
| 2817 | SceneInput1 = Input {{ SourceOp = "S", Source = "Output", }}, |
| 2818 | SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, |
| 2819 | }}, }}, |
| 2820 | R = Renderer3D {{ Inputs = {{ |
| 2821 | Width = Input {{ Value = 64, }}, |
| 2822 | Height = Input {{ Value = 64, }}, |
| 2823 | SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, |
| 2824 | }}, }}, |
| 2825 | }} }}"# |
| 2826 | ); |
| 2827 | let comp = Comp::from_fusion_str(&src).unwrap(); |
| 2828 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); |
| 2829 | eng.readback_rgba(&tex).unwrap() |
| 2830 | }; |
| 2831 | let luma = |buf: &[u8], x: usize, y: usize| { |
| 2832 | let o = (y * 64 + x) * 4; |
| 2833 | buf[o] as f32 + buf[o + 1] as f32 + buf[o + 2] as f32 |
| 2834 | }; |
| 2835 | // Fresnel By-Angle: face-on center is dark (0), grazing rim is bright! |
| 2836 | let fresnel = render_reflect(1, 0.0, 1.0, 0.0); |
| 2837 | let center_l = luma(&fresnel, 32, 32); |
| 2838 | let rim_l = (46..=56).map(|x| luma(&fresnel, x, 32)).fold(0.0_f32, f32::max); |
| 2839 | assert!(center_l < 15.0 && rim_l > 80.0, "Fresnel center={center_l} rim={rim_l}"); |
| 2840 | |
| 2841 | // Constant full reflection reflects at center too, and rotating SphereMap by 180° shifts colors. |
| 2842 | let c0 = render_reflect(0, 0.0, 1.0, 0.0); |
| 2843 | let c180 = render_reflect(0, 0.0, 1.0, 180.0); |
| 2844 | assert!(luma(&c0, 32, 32) > 80.0, "constant reflection should brighten center"); |
| 2845 | let diff: f32 = (0..64 * 64 * 4).map(|i| (c0[i] as f32 - c180[i] as f32).abs()).sum::<f32>() / (64.0 * 64.0 * 4.0); |
| 2846 | assert!(diff > 5.0, "rotating SphereMap by 180 deg must change reflected image, diff={diff}"); |
| 2847 | } |
| 2848 | |
| 2849 | #[test] |
| 2850 | fn mtl_chan_bool_inverts_swaps_and_combines_channels() { |
| 2851 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2852 | let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { |
| 2853 | Bg = MtlBlinn { Inputs = { |
| 2854 | ["Diffuse.Color.Red"] = Input { Value = 0.0, }, |
| 2855 | ["Diffuse.Color.Green"] = Input { Value = 1.0, }, |
| 2856 | ["Diffuse.Color.Blue"] = Input { Value = 0.0, }, |
| 2857 | ReceivesLighting = Input { Value = 0, }, |
| 2858 | }, }, |
| 2859 | Fg = MtlBlinn { Inputs = { |
| 2860 | ["Diffuse.Color.Red"] = Input { Value = 0.0, }, |
| 2861 | ["Diffuse.Color.Green"] = Input { Value = 0.0, }, |
| 2862 | ["Diffuse.Color.Blue"] = Input { Value = 0.5, }, |
| 2863 | ReceivesLighting = Input { Value = 0, }, |
| 2864 | }, }, |
| 2865 | CB = MtlChanBool { Inputs = { |
| 2866 | BackgroundMaterial = Input { SourceOp = "Bg", Source = "MaterialOutput", }, |
| 2867 | ForegroundMaterial = Input { SourceOp = "Fg", Source = "MaterialOutput", }, |
| 2868 | -- R = BG.G (5 -> 1.0), G = 1 - BG.G (op 2 -> 0.0), B = BG.B + FG.B (op 4 -> 0.5), A = White (9 -> 1.0) |
| 2869 | OperandAR = Input { Value = 5, }, OperationR = Input { Value = 0, }, |
| 2870 | OperandAG = Input { Value = 5, }, OperationG = Input { Value = 2, }, |
| 2871 | OperandAB = Input { Value = 6, }, OperationB = Input { Value = 4, }, OperandBB = Input { Value = 2, }, |
| 2872 | OperandAA = Input { Value = 9, }, OperationA = Input { Value = 0, }, |
| 2873 | }, }, |
| 2874 | P = Shape3D { Inputs = { |
| 2875 | ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, |
| 2876 | MaterialInput = Input { SourceOp = "CB", Source = "MaterialOutput", }, |
| 2877 | }, }, |
| 2878 | Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 2.0, }, }, }, |
| 2879 | M = Merge3D { Inputs = { |
| 2880 | SceneInput1 = Input { SourceOp = "P", Source = "Output", }, |
| 2881 | SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, |
| 2882 | }, }, |
| 2883 | R = Renderer3D { Inputs = { |
| 2884 | Width = Input { Value = 32, }, |
| 2885 | Height = Input { Value = 32, }, |
| 2886 | SceneInput = Input { SourceOp = "M", Source = "Output", }, |
| 2887 | }, }, |
| 2888 | } }"#; |
| 2889 | let comp = Comp::from_fusion_str(src).unwrap(); |
| 2890 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); |
| 2891 | let px = eng.readback_rgba(&tex).unwrap(); |
| 2892 | let o = (16 * 32 + 16) * 4; |
| 2893 | let rgba = [px[o], px[o + 1], px[o + 2], px[o + 3]]; |
| 2894 | assert!(rgba[0] >= 250 && rgba[1] <= 5 && (rgba[2] as i32 - 128).abs() <= 4 && rgba[3] >= 250, "unexpected MtlChanBool pixel {rgba:?}"); |
| 2895 | } |
| 2896 | |
| 2897 | #[test] |
| 2898 | fn bender3d_and_replicate3d_render_end_to_end() { |
| 2899 | let Ok(mut eng) = Engine::new_headless() else { return }; |
| 2900 | let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { |
| 2901 | Dest = Shape3D { Inputs = { |
| 2902 | ["SurfacePlaneInputs.Width"] = Input { Value = 1.6, }, |
| 2903 | ["SurfacePlaneInputs.SubdivisionWidth"] = Input { Value = 1, }, |
| 2904 | }, }, |
| 2905 | Dot = Shape3D { Inputs = { |
| 2906 | ["SurfacePlaneInputs.Width"] = Input { Value = 0.3, }, |
| 2907 | ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 1.0, }, |
| 2908 | ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.2, }, |
| 2909 | ["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.0, }, |
| 2910 | ["MtlStdInputs.ReceivesLighting"] = Input { Value = 0, }, |
| 2911 | }, }, |
| 2912 | BentDot = Bender3D { Inputs = { |
| 2913 | SceneInput = Input { SourceOp = "Dot", Source = "Output", }, |
| 2914 | Bender = Input { Value = FuID { "Twist" }, }, |
| 2915 | Amount = Input { Value = 0.25, }, |
| 2916 | }, }, |
| 2917 | Rep = Replicate3D { Inputs = { |
| 2918 | Destination = Input { SourceOp = "Dest", Source = "Output", }, |
| 2919 | Input1 = Input { SourceOp = "BentDot", Source = "Output", }, |
| 2920 | }, }, |
| 2921 | Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 4.5, }, }, }, |
| 2922 | M = Merge3D { Inputs = { |
| 2923 | SceneInput1 = Input { SourceOp = "Rep", Source = "Output", }, |
| 2924 | SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, |
| 2925 | }, }, |
| 2926 | R = Renderer3D { Inputs = { |
| 2927 | Width = Input { Value = 64, }, |
| 2928 | Height = Input { Value = 64, }, |
| 2929 | SceneInput = Input { SourceOp = "M", Source = "Output", }, |
| 2930 | }, }, |
| 2931 | } }"#; |
| 2932 | let comp = Comp::from_fusion_str(src).unwrap(); |
| 2933 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); |
| 2934 | let px = eng.readback_rgba(&tex).unwrap(); |
| 2935 | // 4 corners of the destination plane should produce non-empty orange pixels, while center (32, 32) is empty! |
| 2936 | let center_a = px[(32 * 64 + 32) * 4 + 3]; |
| 2937 | let lit_pixels = px.chunks_exact(4).filter(|p| p[0] > 200 && p[3] > 200).count(); |
| 2938 | assert_eq!(center_a, 0, "center between 4 replicated corners should be transparent"); |
| 2939 | assert!(lit_pixels >= 40, "expected 4 replicated corner quads to render, got {lit_pixels} pixels"); |
| 2940 | } |
| 2941 | } |