diff --git a/native/shared/src/lib.rs b/native/shared/src/lib.rs index 48f22b1f..01e8b61c 100644 --- a/native/shared/src/lib.rs +++ b/native/shared/src/lib.rs @@ -43,6 +43,7 @@ pub mod profiler; #[cfg(all(feature = "models3d", feature = "jolt"))] pub mod ragdoll; pub mod scene; +mod scene_gi_soup; pub mod sdf_cache; pub mod shadows; pub mod staging; diff --git a/native/shared/src/renderer/formats.rs b/native/shared/src/renderer/formats.rs index d9db6f63..ab7c4854 100644 --- a/native/shared/src/renderer/formats.rs +++ b/native/shared/src/renderer/formats.rs @@ -1076,3 +1076,39 @@ pub(super) fn create_bloom_chain( let full_view = textures[0].create_view(&wgpu::TextureViewDescriptor::default()); (textures, views, full_view) } + +/// Diagnostic (`BLOOM_GPU_TIME=1`): start timing this frame's GPU work. +/// +/// On tile-based GPUs per-pass timestamps overlap and frame time is quantised +/// to the display, so the time from submit to completion is the only number +/// that isolates GPU cost. Measuring it serialises CPU and GPU: never leave it +/// on when judging frame rate. +pub(super) fn gpu_frame_clock() -> Option { + static ENABLED: std::sync::OnceLock = std::sync::OnceLock::new(); + ENABLED + .get_or_init(|| std::env::var("BLOOM_GPU_TIME").is_ok_and(|value| value == "1")) + .then(std::time::Instant::now) +} + +/// Block until the GPU has finished the submitted frame, accumulate its time +/// and print the mean every 120 frames. +pub(super) fn finish_gpu_frame_clock(start: Option, device: &wgpu::Device) { + let Some(start) = start else { + return; + }; + #[cfg(not(target_arch = "wasm32"))] + let _ = device.poll(wgpu::PollType::Wait { + submission_index: None, + timeout: None, + }); + #[cfg(target_arch = "wasm32")] + let _ = device; + static TOTAL: std::sync::Mutex<(f64, u32)> = std::sync::Mutex::new((0.0, 0)); + let mut total = TOTAL.lock().unwrap(); + total.0 += start.elapsed().as_secs_f64() * 1000.0; + total.1 += 1; + if total.1 == 120 { + eprintln!("bloom gpu: {:.2} ms/frame (mean of 120)", total.0 / 120.0); + *total = (0.0, 0); + } +} diff --git a/native/shared/src/renderer/gi_bake.rs b/native/shared/src/renderer/gi_bake.rs index 58a56aad..d63a6836 100644 --- a/native/shared/src/renderer/gi_bake.rs +++ b/native/shared/src/renderer/gi_bake.rs @@ -188,6 +188,8 @@ impl Renderer { transparent_gi, prep.next_node, gather_budget, + // An eighth of a voxel: far below what the field resolves. + SCENE_SDF_CLIPMAP_EXTENT / SCENE_SDF_CLIPMAP_RES as f32 * 0.125, &mut prep.vertices, &mut prep.indices, ); diff --git a/native/shared/src/renderer/mod.rs b/native/shared/src/renderer/mod.rs index 203c4565..ef0acf9e 100644 --- a/native/shared/src/renderer/mod.rs +++ b/native/shared/src/renderer/mod.rs @@ -13318,8 +13318,10 @@ impl Renderer { self.finish_frame_readback(readback); } else { profiler.begin("queue_submit"); + let gpu_clock = formats::gpu_frame_clock(); self.submit_frame_commands(encoder.finish()); profiler.end("queue_submit"); + formats::finish_gpu_frame_clock(gpu_clock, &self.device); } #[cfg(target_arch = "wasm32")] { diff --git a/native/shared/src/renderer/shaders/ao.rs b/native/shared/src/renderer/shaders/ao.rs index e504682f..3415de5f 100644 --- a/native/shared/src/renderer/shaders/ao.rs +++ b/native/shared/src/renderer/shaders/ao.rs @@ -272,8 +272,10 @@ fn cs_main(@builtin(global_invocation_id) gid: vec3) { let P = view_pos_from_linear(uv, center_z); let uv_r = uv + vec2(inv_sz.x, 0.0); let uv_u = uv + vec2(0.0, -inv_sz.y); - let P_r = view_pos_from_linear(uv_r, hiz_sample(uv_r, 0)); - let P_u = view_pos_from_linear(uv_u, hiz_sample(uv_u, 0)); + let z_r = hiz_sample(uv_r, 0); + let z_u = hiz_sample(uv_u, 0); + let P_r = view_pos_from_linear(uv_r, z_r); + let P_u = view_pos_from_linear(uv_u, z_u); let N = normalize(cross(P_r - P, P_u - P)); let coord = vec2(px); @@ -357,9 +359,22 @@ fn cs_main(@builtin(global_invocation_id) gid: vec3) { // quad neighbours, checkerboard gone by construction. Flat walls, // ground and grass-over-ground keep the cheap 2-direction path (their // directions agree), so the 4× fan-out cost stays foliage-local. + // + // Both absorbers only fail at a depth silhouette, so that is part of the + // trigger. Direction disagreement alone is also what any crease or + // cluttered interior produces (a third of the pixels in a ship's hold), + // where the blur and the EMA do their job and the 4x scan bought nothing. let anisotropic = (vis_max - vis_min) > 0.3; + var silhouette = false; + if (anisotropic) { + let z_l = hiz_sample(uv - vec2(inv_sz.x, 0.0), 0); + let z_d = hiz_sample(uv + vec2(0.0, inv_sz.y), 0); + let z_near = min(min(z_r, z_u), min(z_l, z_d)); + let z_far = max(max(z_r, z_u), max(z_l, z_d)); + silhouette = z_far > center_z * 1.08 || z_near < center_z * 0.92; + } let near_field = (-P.z) < 1.5; - if (anisotropic || near_field) { + if ((anisotropic && silhouette) || near_field) { for (var d = 0u; d < N_DIRS_TOTAL; d = d + 1u) { if ((d % N_PHASES) == phase) { continue; } let angle = (f32(d) / f32(N_DIRS_TOTAL)) * PI + jitter_angle; diff --git a/native/shared/src/renderer/shaders/mod.rs b/native/shared/src/renderer/shaders/mod.rs index 17299d9c..24c8ac1c 100644 --- a/native/shared/src/renderer/shaders/mod.rs +++ b/native/shared/src/renderer/shaders/mod.rs @@ -186,8 +186,10 @@ mod ray_query_variant_tests { assert!(!source.contains("u.params.y * ndotd")); } for source in traces { - assert!(source.contains("@compute @workgroup_size(8, 1, 1)")); - assert!(source.contains("lid.x >= PROBE_TRACE_RAYS")); + // Eight probes by eight rays per workgroup: one-probe groups of + // eight threads cost a mobile GPU more in scheduling than in tracing. + assert!(source.contains("@compute @workgroup_size(8, 8, 1)")); + assert!(source.contains("ray.x >= PROBE_TRACE_RAYS")); assert!(!source.contains("lid.y >= PROBE_OCT_SIZE / 2u")); } assert!(PROBE_HELPERS_WGSL.contains("fn probe_lattice_jitter(phase_in: u32)")); diff --git a/native/shared/src/renderer/shaders/ssgi.rs b/native/shared/src/renderer/shaders/ssgi.rs index 8a0298ea..681f331a 100644 --- a/native/shared/src/renderer/shaders/ssgi.rs +++ b/native/shared/src/renderer/shaders/ssgi.rs @@ -404,20 +404,23 @@ fn hiz_sample(uv: vec2, mip: i32) -> f32 { } } -@compute @workgroup_size(8, 1, 1) +@compute @workgroup_size(8, 8, 1) fn cs_main( @builtin(workgroup_id) wg: vec3, @builtin(local_invocation_id) lid: vec3, ) { let grid_w = u.size.z; let grid_h = u.size.w; - if (wg.x >= grid_w || wg.y >= grid_h) { return; } - if (lid.x >= PROBE_TRACE_RAYS) { return; } + // One workgroup traces eight neighbouring probes (x) by eight rays (y). + let probe = vec2(wg.x * 8u + lid.x, wg.y); + let ray = vec2(lid.y, 0u); + if (probe.x >= grid_w || probe.y >= grid_h) { return; } + if (ray.x >= PROBE_TRACE_RAYS) { return; } - let probe_idx = wg.y * grid_w + wg.x; + let probe_idx = probe.y * grid_w + probe.x; let header = probes[probe_idx]; - let dst_coord = vec3(i32(wg.x), i32(wg.y), i32(lid.y * PROBE_OCT_SIZE + lid.x)); + let dst_coord = vec3(i32(probe.x), i32(probe.y), i32(ray.x)); // Invalid probe (sky tile) → contribute zero. if (header.world_pos.w < 0.5) { @@ -428,7 +431,7 @@ fn cs_main( // Cosine-hemisphere sampling keeps every ray above the receiver and folds // the Lambertian cosine/pdf term into the distribution itself. let dir_ws = probe_trace_direction( - lid.xy, + ray, header.world_pos.xyz, n_ws, u.params.x, @@ -997,21 +1000,24 @@ fn hw_gi_trace_sample( return HwGiSample(radiance, hit_distance, source_id); } -@compute @workgroup_size(8, 1, 1) +@compute @workgroup_size(8, 8, 1) fn cs_main( @builtin(workgroup_id) wg: vec3, @builtin(local_invocation_id) lid: vec3, ) { let grid_w = u.size.z; let grid_h = u.size.w; - if (wg.x >= grid_w || wg.y >= grid_h) { return; } - if (lid.x >= PROBE_TRACE_RAYS) { return; } + // One workgroup traces eight neighbouring probes (x) by eight rays (y). + let probe = vec2(wg.x * 8u + lid.x, wg.y); + let ray = vec2(lid.y, 0u); + if (probe.x >= grid_w || probe.y >= grid_h) { return; } + if (ray.x >= PROBE_TRACE_RAYS) { return; } - let probe_idx = wg.y * grid_w + wg.x; + let probe_idx = probe.y * grid_w + probe.x; let header = probes[probe_idx]; - let lane = lid.y * PROBE_OCT_SIZE + lid.x; - let dst_coord = vec3(i32(wg.x), i32(wg.y), i32(lane)); + let lane = ray.x; + let dst_coord = vec3(i32(probe.x), i32(probe.y), i32(lane)); if (header.world_pos.w < 0.5) { textureStore(radiance_out, dst_coord, vec4(0.0)); @@ -1028,7 +1034,7 @@ fn cs_main( var source_id = 0.0; if (lane < PROBE_TRACE_RAYS) { let dir_ws = probe_trace_direction( - lid.xy, + ray, header.world_pos.xyz, n_ws, u.params.x, @@ -1259,19 +1265,22 @@ fn wsrc_sample(pos_ws: vec3, dir_ws: vec3) -> vec3 { + c01 * (ix * fy) + c11 * (fx * fy); } -@compute @workgroup_size(8, 1, 1) +// One workgroup traces eight neighbouring probes (x) by eight rays (y). +@compute @workgroup_size(8, 8, 1) fn cs_main( @builtin(workgroup_id) wg: vec3, @builtin(local_invocation_id) lid: vec3, ) { let grid_w = u.size.z; let grid_h = u.size.w; - if (wg.x >= grid_w || wg.y >= grid_h) { return; } - if (lid.x >= PROBE_TRACE_RAYS) { return; } + let probe = vec2(wg.x * 8u + lid.x, wg.y); + let ray = vec2(lid.y, 0u); + if (probe.x >= grid_w || probe.y >= grid_h) { return; } + if (ray.x >= PROBE_TRACE_RAYS) { return; } - let probe_idx = wg.y * grid_w + wg.x; + let probe_idx = probe.y * grid_w + probe.x; let header = probes[probe_idx]; - let dst_coord = vec3(i32(wg.x), i32(wg.y), i32(lid.y * PROBE_OCT_SIZE + lid.x)); + let dst_coord = vec3(i32(probe.x), i32(probe.y), i32(ray.x)); if (header.world_pos.w < 0.5) { textureStore(radiance_out, dst_coord, vec4(0.0)); @@ -1280,7 +1289,7 @@ fn cs_main( // Temporally stratified 8-ray diffuse estimate. See the HW path. let n_ws = header.normal.xyz; let dir_ws = probe_trace_direction( - lid.xy, + ray, header.world_pos.xyz, n_ws, u.params.x, @@ -1298,7 +1307,7 @@ fn cs_main( var transparent_idx: i32 = -1; var transparent_t: f32 = max_t + 1.0; if (BLOOM_TRANSPARENT_GI) { - let instance_count = arrayLength(&instance_data); + let instance_count = min(arrayLength(&instance_data), u32(u.shadow_params.w)); for (var i: u32 = 0u; i < instance_count; i = i + 1u) { let candidate = instance_data[i]; if (candidate.mat_params.z <= 0.0) { continue; } @@ -1358,13 +1367,16 @@ fn cs_main( // back to analytic sun/sky × gray when no instance matches // (clipmap sentinel voxels, hits inside unaccounted-for // geometry, etc.). - let count = arrayLength(&instance_data); + // Walk the live records only (the buffer is a zero-padded power of + // two), and read just the fields the test needs: this loop runs for + // every ray that hits, and copying the whole 176-byte record per + // instance cost more than the march itself on mobile GPUs. + let count = min(arrayLength(&instance_data), u32(u.shadow_params.w)); var picked: i32 = -1; var picked_vol: f32 = 1e30; for (var i: u32 = 0u; i < count; i = i + 1u) { - let ad = instance_data[i]; - if (ad.card_slot.w < 0.5) { continue; } - if (BLOOM_TRANSPARENT_GI && ad.mat_params.z > 0.0) { continue; } + if (instance_data[i].card_slot.w < 0.5) { continue; } + if (BLOOM_TRANSPARENT_GI && instance_data[i].mat_params.z > 0.0) { continue; } // EN-023 — compare the WORLD hit against the WORLD AABB. // The old object-space comparison only matched assets whose // vertices were already in world space; every transformed @@ -1373,8 +1385,8 @@ fn cs_main( // spanning instance (the shooter's ±140 m terrain proxy) // otherwise swallows every hit — walls and trees included — // and its mostly-empty side cards darken the bounce. - let bmin = ad.world_aabb_min.xyz - vec3(0.05); - let bmax = ad.world_aabb_max.xyz + vec3(0.05); + let bmin = instance_data[i].world_aabb_min.xyz - vec3(0.05); + let bmax = instance_data[i].world_aabb_max.xyz + vec3(0.05); if (hit_pos.x >= bmin.x && hit_pos.x <= bmax.x && hit_pos.y >= bmin.y && hit_pos.y <= bmax.y && hit_pos.z >= bmin.z && hit_pos.z <= bmax.z) { diff --git a/native/shared/src/renderer/ssgi_pass.rs b/native/shared/src/renderer/ssgi_pass.rs index 71d74ec4..b089a642 100644 --- a/native/shared/src/renderer/ssgi_pass.rs +++ b/native/shared/src/renderer/ssgi_pass.rs @@ -291,7 +291,8 @@ impl Renderer { // Bistro's red awnings onto the façade above them) appear // as a sudden delayed light change ~20 s into a session. self.card_light_coherent_ramp, - 0.0, + // Live instance records, for the SDF trace's card lookup. + self.tlas_instance_data_count as f32, ], }; self.queue.write_buffer( @@ -525,7 +526,7 @@ impl Renderer { self.probe_trace_hw_bg_cache[prev_idx].as_ref().unwrap(), &[], ); - pass.dispatch_workgroups(gw, gh, 1); + pass.dispatch_workgroups(gw.div_ceil(8), gh, 1); } else if use_sdf { // Ticket 014 V3 — SW SDF sphere-trace path. // V3 (ticket 016) uses a per-prev_idx slot for the @@ -631,7 +632,9 @@ impl Renderer { self.probe_trace_sdf_bg_cache[prev_idx].as_ref().unwrap(), &[], ); - pass.dispatch_workgroups(gw, gh, 1); + if !self.dbg_skip("gi_trace") { + pass.dispatch_workgroups(gw.div_ceil(8), gh, 1); + } } else { let ts = profiler.compute_pass_timestamp_writes("probe_trace_pass"); let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { @@ -644,7 +647,7 @@ impl Renderer { self.probe_trace_bg_cache[prev_idx].as_ref().unwrap(), &[], ); - pass.dispatch_workgroups(gw, gh, 1); + pass.dispatch_workgroups(gw.div_ceil(8), gh, 1); } // ---- temporal (EMA) ---- @@ -793,7 +796,9 @@ impl Renderer { self.probe_temporal_bg_cache[write_idx].as_ref().unwrap(), &[], ); - pass.dispatch_workgroups(gw, gh, 1); + if !self.dbg_skip("gi_temporal") { + pass.dispatch_workgroups(gw, gh, 1); + } } { let ts = profiler.compute_pass_timestamp_writes("probe_spatial_pass"); @@ -807,7 +812,9 @@ impl Renderer { self.probe_temporal_bg_cache[write_idx].as_ref().unwrap(), &[], ); - pass.dispatch_workgroups(gw.div_ceil(8), gh.div_ceil(8), 1); + if !self.dbg_skip("gi_spatial") { + pass.dispatch_workgroups(gw.div_ceil(8), gh.div_ceil(8), 1); + } } self.probe_history_valid = true; @@ -922,7 +929,9 @@ impl Renderer { self.probe_resolve_bg_cache[write_idx].as_ref().unwrap(), &[], ); - pass.dispatch_workgroups(half_w.div_ceil(8), half_h.div_ceil(8), 1); + if !self.dbg_skip("gi_resolve") { + pass.dispatch_workgroups(half_w.div_ceil(8), half_h.div_ceil(8), 1); + } } else { // Suppressed frames do not produce probe history. This also // catches progressive PT changing ownership without a mode change. diff --git a/native/shared/src/scene.rs b/native/shared/src/scene.rs index c3e09efb..06fadce0 100644 --- a/native/shared/src/scene.rs +++ b/native/shared/src/scene.rs @@ -840,6 +840,7 @@ impl SceneGraph { exclude_physical_transmission, 0, usize::MAX, + 0.0, &mut vbuf, &mut ibuf, ); @@ -851,17 +852,16 @@ impl SceneGraph { /// vertices have been appended in this call. Returns the node to resume /// from, the triangles appended, and whether every node has been visited. /// A scene SDF rebake uses it to spread the gather over several frames. + /// `min_feature` thins sub-voxel triangles (see `scene_gi_soup`); 0 keeps all. pub(crate) fn append_world_triangles_for_gi( &self, exclude_physical_transmission: bool, first_node: usize, max_vertices: usize, + min_feature: f32, vbuf: &mut Vec, ibuf: &mut Vec, ) -> (usize, u32, bool) { - // 12 floats per vertex to match `Vertex3D` stride the bake - // shader indexes with. position + zero-padding. - const STRIDE: usize = 12; let mut next_node = first_node; let mut appended = 0usize; let mut tri_count: u32 = 0; @@ -877,24 +877,15 @@ impl SceneGraph { { continue; } - let base = (vbuf.len() / STRIDE) as u32; - let world_transform = node.world_transform(); - let t = &world_transform; - vbuf.reserve(node.vertices().len() * STRIDE); - for v in node.vertices() { - let px = v.position[0]; - let py = v.position[1]; - let pz = v.position[2]; - let wx = t[0][0] * px + t[1][0] * py + t[2][0] * pz + t[3][0]; - let wy = t[0][1] * px + t[1][1] * py + t[2][1] * pz + t[3][1]; - let wz = t[0][2] * px + t[1][2] * py + t[2][2] * pz + t[3][2]; - // Zero-pad the remaining 9 floats — only position is - // read by `SDF_BAKE_WGSL`. - vbuf.extend_from_slice(&[wx, wy, wz, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); - } - ibuf.extend(node.indices().iter().map(|&idx| base + idx)); - tri_count += (node.indices().len() / 3) as u32; appended += node.vertices().len(); + tri_count += crate::scene_gi_soup::append_node_triangles( + node.vertices(), + node.indices(), + &node.world_transform(), + min_feature, + vbuf, + ibuf, + ); } (next_node, tri_count, true) } diff --git a/native/shared/src/scene_gi_soup.rs b/native/shared/src/scene_gi_soup.rs new file mode 100644 index 00000000..6fc489c3 --- /dev/null +++ b/native/shared/src/scene_gi_soup.rs @@ -0,0 +1,218 @@ +//! World-space triangle soup for the scene distance field. +//! +//! `min_feature` (world units, 0 = keep everything) thins triangles that are +//! far smaller than the field's voxels. A field sampled every 62 cm gains +//! nothing from a character's 8 mm triangles, yet the bake tested each voxel +//! against every one of them. Of the triangles with area below +//! `min_feature`², only the first to fall in each `min_feature`-sized world +//! cell is kept, so a dense surface stays covered by samples about +//! `min_feature` apart and the distance to it moves by at most that. Larger +//! triangles are untouched. + +use crate::renderer::Vertex3D; + +/// 12 floats per vertex, the `Vertex3D` stride the bake shader indexes with: +/// position, then zero padding. +const STRIDE: usize = 12; + +fn push_position(vbuf: &mut Vec, t: &[[f32; 4]; 4], p: [f32; 3]) { + vbuf.extend_from_slice(&[ + t[0][0] * p[0] + t[1][0] * p[1] + t[2][0] * p[2] + t[3][0], + t[0][1] * p[0] + t[1][1] * p[1] + t[2][1] * p[2] + t[3][1], + t[0][2] * p[0] + t[1][2] * p[1] + t[2][2] * p[2] + t[3][2], + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ]); +} + +/// Append one mesh in world space; returns the triangles appended. +pub(crate) fn append_node_triangles( + vertices: &[Vertex3D], + indices: &[u32], + world_transform: &[[f32; 4]; 4], + min_feature: f32, + vbuf: &mut Vec, + ibuf: &mut Vec, +) -> u32 { + let base = (vbuf.len() / STRIDE) as u32; + let thinned = if min_feature > 0.0 { + thin_small_triangles(vertices, indices, world_transform, min_feature) + } else { + None + }; + if let Some(kept) = thinned { + // Only the surviving triangles' corners are emitted. + vbuf.reserve(kept.len() * STRIDE); + for (slot, &index) in kept.iter().enumerate() { + push_position(vbuf, world_transform, vertices[index as usize].position); + ibuf.push(base + slot as u32); + } + return (kept.len() / 3) as u32; + } + vbuf.reserve(vertices.len() * STRIDE); + for vertex in vertices { + push_position(vbuf, world_transform, vertex.position); + } + ibuf.extend(indices.iter().map(|&index| base + index)); + (indices.len() / 3) as u32 +} + +/// The corner indices of the triangles that survive thinning, or `None` when +/// nothing was dropped and the mesh should be emitted as it is. +fn thin_small_triangles( + vertices: &[Vertex3D], + indices: &[u32], + world_transform: &[[f32; 4]; 4], + min_feature: f32, +) -> Option> { + // Areas are measured in object space and scaled by the transform's mean + // area scale; shear and non-uniform scale only move the threshold a little. + let t = world_transform; + let axis = |c: usize| (t[c][0] * t[c][0] + t[c][1] * t[c][1] + t[c][2] * t[c][2]).sqrt(); + let (sx, sy, sz) = (axis(0), axis(1), axis(2)); + let area_scale = (sx * sy + sy * sz + sz * sx) / 3.0; + let small_area = min_feature * min_feature / area_scale; + let inv_cell = 1.0 / min_feature; + if !small_area.is_finite() || !inv_cell.is_finite() { + return None; + } + let mut occupied: std::collections::HashSet<[i32; 3]> = Default::default(); + let mut kept: Vec = Vec::new(); + let mut dropped_any = false; + for (triangle, corners) in indices.chunks_exact(3).enumerate() { + let position = |corner: u32| vertices.get(corner as usize).map(|v| v.position); + let (Some(a), Some(b), Some(c)) = ( + position(corners[0]), + position(corners[1]), + position(corners[2]), + ) else { + return None; + }; + let ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; + let cross = [ + ab[1] * ac[2] - ab[2] * ac[1], + ab[2] * ac[0] - ab[0] * ac[2], + ab[0] * ac[1] - ab[1] * ac[0], + ]; + let area = 0.5 * (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt(); + // A small triangle survives only as the first one in its world cell. + let keep = area >= small_area || { + let m = [ + (a[0] + b[0] + c[0]) / 3.0, + (a[1] + b[1] + c[1]) / 3.0, + (a[2] + b[2] + c[2]) / 3.0, + ]; + let cell = |row: usize| { + let world = t[0][row] * m[0] + t[1][row] * m[1] + t[2][row] * m[2] + t[3][row]; + (world * inv_cell).floor() as i32 + }; + occupied.insert([cell(0), cell(1), cell(2)]) + }; + if keep { + if dropped_any { + kept.extend_from_slice(corners); + } + } else if !dropped_any { + // First drop: everything before it was kept. + dropped_any = true; + kept.reserve(indices.len() / 4); + kept.extend_from_slice(&indices[..triangle * 3]); + } + } + dropped_any.then_some(kept) +} + +#[cfg(test)] +mod tests { + use super::*; + + const IDENTITY: [[f32; 4]; 4] = [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ]; + + /// A flat `cells`×`cells` grid of side `size`, two triangles per cell. + fn grid(cells: u32, size: f32) -> (Vec, Vec) { + let mut vertices = Vec::new(); + for y in 0..=cells { + for x in 0..=cells { + vertices.push(Vertex3D { + position: [ + x as f32 * size / cells as f32, + 0.0, + y as f32 * size / cells as f32, + ], + ..Default::default() + }); + } + } + let mut indices = Vec::new(); + let row = cells + 1; + for y in 0..cells { + for x in 0..cells { + let a = y * row + x; + indices.extend_from_slice(&[a, a + 1, a + row, a + 1, a + row + 1, a + row]); + } + } + (vertices, indices) + } + + #[test] + fn large_triangles_are_emitted_unchanged() { + let (vertices, indices) = grid(4, 4.0); // 0.5 m² triangles + let (mut vbuf, mut ibuf) = (Vec::new(), Vec::new()); + let count = + append_node_triangles(&vertices, &indices, &IDENTITY, 0.08, &mut vbuf, &mut ibuf); + assert_eq!(count, 32); + assert_eq!(ibuf, indices); + assert_eq!(vbuf.len(), vertices.len() * STRIDE); + } + + #[test] + fn dense_mesh_is_thinned_to_one_sample_per_cell_and_stays_covered() { + // 1 m² in 20 000 triangles of 0.5 cm² each; samples 10 cm apart. + let (vertices, indices) = grid(100, 1.0); + let (mut vbuf, mut ibuf) = (Vec::new(), Vec::new()); + let count = + append_node_triangles(&vertices, &indices, &IDENTITY, 0.1, &mut vbuf, &mut ibuf); + assert!((100..=121).contains(&count), "kept {count}"); + assert_eq!(ibuf.len() as u32, count * 3); + assert_eq!(vbuf.len(), ibuf.len() * STRIDE); + // Every point of the sheet is still within one sample spacing of a + // surviving triangle. + let mut worst = 0.0f32; + for gy in 0..=10 { + for gx in 0..=10 { + let (px, pz) = (gx as f32 * 0.1, gy as f32 * 0.1); + let nearest = vbuf + .chunks_exact(STRIDE) + .map(|v| ((v[0] - px).powi(2) + (v[2] - pz).powi(2)).sqrt()) + .fold(f32::MAX, f32::min); + worst = worst.max(nearest); + } + } + assert!(worst <= 0.15, "largest hole {worst} m"); + } + + #[test] + fn scale_is_taken_from_the_transform() { + let (vertices, indices) = grid(100, 1.0); + let mut big = IDENTITY; + big[0][0] = 100.0; + big[1][1] = 100.0; + big[2][2] = 100.0; // triangles are now 0.5 m² each + let (mut vbuf, mut ibuf) = (Vec::new(), Vec::new()); + let count = append_node_triangles(&vertices, &indices, &big, 0.1, &mut vbuf, &mut ibuf); + assert_eq!(count, 20_000); + } +}